@0xmonaco/mcp-server 1.0.85 → 1.0.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/dist/bin.js +10 -10
  3. package/package.json +3 -3
package/dist/bin.js CHANGED
@@ -62,11 +62,11 @@ ${PD(h)}`;super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessag
62
62
  `);super(c,t.cause?{cause:t.cause}:void 0);Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.cause=t.cause,this.details=r,this.docs=i,this.docsOrigin=o,this.docsPath=n,this.shortMessage=e,this.showVersion=s,this.version=a}walk(e){return BD(this,e)}};Object.defineProperty($e,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${zD()}`}});(()=>{$e.setStaticOptions($e.defaultStaticOptions)})()});function Fd(e,t){if(vo(e)>t)throw new MP({givenSize:vo(e),maxSize:t})}function DD(e,t){if(typeof t==="number"&&t>0&&t>vo(e)-1)throw new Ob({offset:t,position:"start",size:vo(e)})}function FD(e,t,r){if(typeof t==="number"&&typeof r==="number"&&vo(e)!==r-t)throw new Ob({offset:r,position:"end",size:vo(e)})}function CP(e){if(e>=Bs.zero&&e<=Bs.nine)return e-Bs.zero;if(e>=Bs.A&&e<=Bs.F)return e-(Bs.A-10);if(e>=Bs.a&&e<=Bs.f)return e-(Bs.a-10);return}function UD(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new NP({size:e.length,targetSize:n,type:"Bytes"});let o=new Uint8Array(n);for(let i=0;i<n;i++){let s=r==="right";o[s?i:n-i-1]=e[s?i:e.length-i-1]}return o}function OP(e,t={}){let{dir:r="left"}=t,n=e,o=0;for(let i=0;i<n.length-1;i++)if(n[r==="left"?i:n.length-i-1].toString()==="0")o++;else break;return n=r==="left"?n.slice(o):n.slice(0,n.length-o),n}var Bs;var jD=K(()=>{Ud();Bs={zero:48,nine:57,A:65,F:70,a:97,f:102}});function jd(e,t){if(Er(e)>t)throw new LP({givenSize:Er(e),maxSize:t})}function qD(e,t){if(typeof t==="number"&&t>0&&t>Er(e)-1)throw new Mb({offset:t,position:"start",size:Er(e)})}function HD(e,t,r){if(typeof t==="number"&&typeof r==="number"&&Er(e)!==r-t)throw new Mb({offset:r,position:"end",size:Er(e)})}function $P(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let o=e.replace("0x","");if(o.length>n*2)throw new BP({size:Math.ceil(o.length/2),targetSize:n,type:"Hex"});return`0x${o[r==="right"?"padEnd":"padStart"](n*2,"0")}`}var zP=K(()=>{Fn()});function Nb(e,t,r){return JSON.stringify(e,(n,o)=>{if(typeof t==="function")return t(n,o);if(typeof o==="bigint")return o.toString()+"#__bigint";return o},r)}function ZD(e){if(e instanceof Uint8Array)return e;if(typeof e==="string")return DP(e);return vle(e)}function vle(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function DP(e,t={}){let{size:r}=t,n=e;if(r)jd(e,r),n=zi(e,r);let o=n.slice(2);if(o.length%2)o=`0${o}`;let i=o.length/2,s=new Uint8Array(i);for(let a=0,c=0;a<i;a++){let l=CP(o.charCodeAt(c++)),d=CP(o.charCodeAt(c++));if(l===void 0||d===void 0)throw new $e(`Invalid byte sequence ("${o[c-2]}${o[c-1]}" in "${o}").`);s[a]=l<<4|d}return s}function WD(e,t={}){let{size:r}=t,n=Tle.encode(e);if(typeof r==="number")return Fd(n,r),Ele(n,r);return n}function Ele(e,t){return UD(e,{dir:"right",size:t})}function vo(e){return e.length}function KD(e,t,r,n={}){let{strict:o}=n;DD(e,t);let i=e.slice(t,r);if(o)FD(i,t,r);return i}function YD(e,t={}){let{size:r}=t;if(typeof r<"u")Fd(e,r);let n=an(e,t);return UP(n,t)}function JD(e,t={}){let{size:r}=t,n=e;if(typeof r<"u")Fd(n,r),n=FP(n);if(n.length>1||n[0]>1)throw new XD(n);return Boolean(n[0])}function $i(e,t={}){let{size:r}=t;if(typeof r<"u")Fd(e,r);let n=an(e,t);return $b(n,t)}function QD(e,t={}){let{size:r}=t,n=e;if(typeof r<"u")Fd(n,r),n=Ple(n);return _le.decode(n)}function FP(e){return OP(e,{dir:"left"})}function Ple(e){return OP(e,{dir:"right"})}var _le,Tle,XD,MP,Ob,NP;var Ud=K(()=>{To();Fn();jD();zP();_le=new TextDecoder,Tle=new TextEncoder;XD=class XD extends $e{constructor(e){super(`Bytes value \`${e}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"})}};MP=class MP extends $e{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}};Ob=class Ob extends $e{constructor({offset:e,position:t,size:r}){super(`Slice ${t==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${r}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SliceOffsetOutOfBoundsError"})}};NP=class NP extends $e{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}});function kle(e,t={}){let{strict:r=!1}=t;if(!e)throw new jP(e);if(typeof e!=="string")throw new jP(e);if(r){if(!/^0x[0-9a-fA-F]*$/.test(e))throw new qP(e)}if(!e.startsWith("0x"))throw new qP(e)}function Fr(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function e9(e){if(e instanceof Uint8Array)return an(e);if(Array.isArray(e))return an(new Uint8Array(e));return e}function zb(e,t={}){let r=`0x${Number(e)}`;if(typeof t.size==="number")return jd(r,t.size),Ds(r,t.size);return r}function an(e,t={}){let r="";for(let o=0;o<e.length;o++)r+=Ile[e[o]];let n=`0x${r}`;if(typeof t.size==="number")return jd(n,t.size),zi(n,t.size);return n}function Sr(e,t={}){let{signed:r,size:n}=t,o=BigInt(e),i;if(n)if(r)i=(1n<<BigInt(n)*8n-1n)-1n;else i=2n**(BigInt(n)*8n)-1n;else if(typeof e==="number")i=BigInt(Number.MAX_SAFE_INTEGER);let s=typeof i==="bigint"&&r?-i-1n:0;if(i&&o>i||o<s){let l=typeof e==="bigint"?"n":"";throw new Lb({max:i?`${i}${l}`:void 0,min:`${s}${l}`,signed:r,size:n,value:`${e}${l}`})}let c=`0x${(r&&o<0?BigInt.asUintN(n*8,BigInt(o)):o).toString(16)}`;if(n)return Ds(c,n);return c}function qd(e,t={}){return an(Ale.encode(e),t)}function Ds(e,t){return $P(e,{dir:"left",size:t})}function zi(e,t){return $P(e,{dir:"right",size:t})}function cn(e,t,r,n={}){let{strict:o}=n;qD(e,t);let i=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;if(o)HD(i,t,r);return i}function Er(e){return Math.ceil((e.length-2)/2)}function UP(e,t={}){let{signed:r}=t;if(t.size)jd(e,t.size);let n=BigInt(e);if(!r)return n;let o=(e.length-2)/2,i=(1n<<BigInt(o)*8n)-1n,s=i>>1n;if(n<=s)return n;return n-i-1n}function $b(e,t={}){let{signed:r,size:n}=t;if(!r&&!n)return Number(e);return Number(UP(e,t))}function HP(e,t={}){let{strict:r=!1}=t;try{return kle(e,{strict:r}),!0}catch{return!1}}var Ale,Ile,Lb,jP,qP,LP,Mb,BP;var Fn=K(()=>{To();zP();Ale=new TextEncoder,Ile=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Lb=class Lb extends $e{constructor({max:e,min:t,signed:r,size:n,value:o}){super(`Number \`${o}\` is not in safe${n?` ${n*8}-bit`:""}${r?" signed":" unsigned"} integer range ${e?`(\`${t}\` to \`${e}\`)`:`(above \`${t}\`)`}`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}};jP=class jP extends $e{constructor(e){super(`Value \`${typeof e==="object"?Nb(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}};qP=class qP extends $e{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}};LP=class LP extends $e{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}};Mb=class Mb extends $e{constructor({offset:e,position:t,size:r}){super(`Slice ${t==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${r}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}};BP=class BP extends $e{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}});function t9(e){return{address:e.address,amount:Sr(e.amount),index:Sr(e.index),validatorIndex:Sr(e.validatorIndex)}}var r9=K(()=>{Fn()});function Bb(e){return{...typeof e.baseFeePerGas==="bigint"&&{baseFeePerGas:Sr(e.baseFeePerGas)},...typeof e.blobBaseFee==="bigint"&&{blobBaseFee:Sr(e.blobBaseFee)},...typeof e.feeRecipient==="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit==="bigint"&&{gasLimit:Sr(e.gasLimit)},...typeof e.number==="bigint"&&{number:Sr(e.number)},...typeof e.prevRandao==="bigint"&&{prevRandao:Sr(e.prevRandao)},...typeof e.time==="bigint"&&{time:Sr(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(t9)}}}var GP=K(()=>{Fn();r9()});var o9="0x82ad56cb";var Db="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",i9="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",s9="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",Tu="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033";function vu(e){let{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;let o=t.find((s)=>("type"in s)&&s.type==="constructor");if(!o)throw new fE({docsPath:VP});if(!("inputs"in o))throw new K0({docsPath:VP});if(!o.inputs||o.inputs.length===0)throw new K0({docsPath:VP});let i=_n(o.inputs,r);return dr([n,i])}var VP="/docs/contract/encodeDeployData";var Fb=K(()=>{Tr();ks()});function Ur(e,t){if(!_t(e,{strict:!1}))throw new Qt({address:e});if(!_t(t,{strict:!1}))throw new Qt({address:t});return e.toLowerCase()===t.toLowerCase()}var Fs=K(()=>{Ri();Qn()});function ro(e){let{blockHash:t,blockNumber:r,blockTag:n,requireCanonical:o}=e;if(o!==void 0&&!t)throw new N("`requireCanonical` can only be provided when `blockHash` is set.");if(t)return o?{blockHash:t,requireCanonical:o}:{blockHash:t};if(typeof r==="bigint")return Z(r);return n??"latest"}var Eu=K(()=>{et();Ke()});var Li,Zo,Km,Ym,Jm,Qm,Xm,eh,th,rh,Us,Wo;var js=K(()=>{md();et();Li=class Li extends N{constructor({cause:e,message:t}={}){let r=t?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${r?`with reason: ${r}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}};Object.defineProperty(Li,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(Li,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});Zo=class Zo extends N{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${Mr(t)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}};Object.defineProperty(Zo,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});Km=class Km extends N{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${Mr(t)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}};Object.defineProperty(Km,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});Ym=class Ym extends N{constructor({cause:e,nonce:t}={}){super(`Nonce provided for the transaction ${t?`(${t}) `:""}is higher than the next one expected.`,{cause:e,name:"NonceTooHighError"})}};Object.defineProperty(Ym,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});Jm=class Jm extends N{constructor({cause:e,nonce:t}={}){super([`Nonce provided for the transaction ${t?`(${t}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
63
63
  `),{cause:e,name:"NonceTooLowError"})}};Object.defineProperty(Jm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});Qm=class Qm extends N{constructor({cause:e,nonce:t}={}){super(`Nonce provided for the transaction ${t?`(${t}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}};Object.defineProperty(Qm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});Xm=class Xm extends N{constructor({cause:e}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
64
64
  `),{cause:e,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}};Object.defineProperty(Xm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});eh=class eh extends N{constructor({cause:e,gas:t}={}){super(`The amount of gas ${t?`(${t}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:e,name:"IntrinsicGasTooHighError"})}};Object.defineProperty(eh,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});th=class th extends N{constructor({cause:e,gas:t}={}){super(`The amount of gas ${t?`(${t}) `:""}provided for the transaction is too low.`,{cause:e,name:"IntrinsicGasTooLowError"})}};Object.defineProperty(th,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});rh=class rh extends N{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}};Object.defineProperty(rh,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});Us=class Us extends N{constructor({cause:e,maxPriorityFeePerGas:t,maxFeePerGas:r}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${t?` = ${Mr(t)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${r?` = ${Mr(r)} gwei`:""}).`].join(`
65
- `),{cause:e,name:"TipAboveFeeCapError"})}};Object.defineProperty(Us,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});Wo=class Wo extends N{constructor({cause:e}){super(`An error occurred while executing: ${e?.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}});function ic(e,t){let r=(e.details||"").toLowerCase(),n=e instanceof N?e.walk((o)=>o?.code===Li.code):e;if(n instanceof N)return new Li({cause:e,message:n.details});if(Li.nodeMessage.test(r))return new Li({cause:e,message:e.details});if(Zo.nodeMessage.test(r))return new Zo({cause:e,maxFeePerGas:t?.maxFeePerGas});if(Km.nodeMessage.test(r))return new Km({cause:e,maxFeePerGas:t?.maxFeePerGas});if(Ym.nodeMessage.test(r))return new Ym({cause:e,nonce:t?.nonce});if(Jm.nodeMessage.test(r))return new Jm({cause:e,nonce:t?.nonce});if(Qm.nodeMessage.test(r))return new Qm({cause:e,nonce:t?.nonce});if(Xm.nodeMessage.test(r))return new Xm({cause:e});if(eh.nodeMessage.test(r))return new eh({cause:e,gas:t?.gas});if(th.nodeMessage.test(r))return new th({cause:e,gas:t?.gas});if(rh.nodeMessage.test(r))return new rh({cause:e});if(Us.nodeMessage.test(r))return new Us({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas});return new Wo({cause:e})}var nh=K(()=>{et();js()});function Ub(e,{docsPath:t,...r}){let n=(()=>{let o=ic(e,r);if(o instanceof Wo)return e;return o})();return new bu(n,{docsPath:t,...r})}var ZP=K(()=>{$s();js();nh()});function Eo(e,{format:t}){if(!t)return{};let r={};function n(i){let s=Object.keys(i);for(let a of s){if(a in e)r[a]=e[a];if(i[a]&&typeof i[a]==="object"&&!Array.isArray(i[a]))n(i[a])}}let o=t(e||{});return n(o),r}function un(e,t){let r={};if(typeof e.authorizationList<"u")r.authorizationList=Ole(e.authorizationList);if(typeof e.accessList<"u")r.accessList=e.accessList;if(typeof e.blobVersionedHashes<"u")r.blobVersionedHashes=e.blobVersionedHashes;if(typeof e.blobs<"u")if(typeof e.blobs[0]!=="string")r.blobs=e.blobs.map((n)=>St(n));else r.blobs=e.blobs;if(typeof e.data<"u")r.data=e.data;if(e.account)r.from=e.account.address;if(typeof e.from<"u")r.from=e.from;if(typeof e.gas<"u")r.gas=Z(e.gas);if(typeof e.gasPrice<"u")r.gasPrice=Z(e.gasPrice);if(typeof e.maxFeePerBlobGas<"u")r.maxFeePerBlobGas=Z(e.maxFeePerBlobGas);if(typeof e.maxFeePerGas<"u")r.maxFeePerGas=Z(e.maxFeePerGas);if(typeof e.maxPriorityFeePerGas<"u")r.maxPriorityFeePerGas=Z(e.maxPriorityFeePerGas);if(typeof e.nonce<"u")r.nonce=Z(e.nonce);if(typeof e.to<"u")r.to=e.to;if(typeof e.type<"u")r.type=Cle[e.type];if(typeof e.value<"u")r.value=Z(e.value);return r}function Ole(e){return e.map((t)=>({address:t.address,r:t.r?Z(BigInt(t.r)):t.r,s:t.s?Z(BigInt(t.s)):t.s,chainId:Z(t.chainId),nonce:Z(t.nonce),...typeof t.yParity<"u"?{yParity:Z(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:Z(t.v)}:{}}))}var Cle;var qs=K(()=>{Ke();Cle={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"}});function Hd(){let e=()=>{return},t=()=>{return};return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function Gd({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:o}){let i=async()=>{let d=c();s();let f=d.map(({args:h})=>h);if(f.length===0)return;e(f).then((h)=>{if(o&&Array.isArray(h))h.sort(o);for(let g=0;g<d.length;g++){let{resolve:x}=d[g];x?.([h[g],h])}}).catch((h)=>{for(let g=0;g<d.length;g++){let{reject:x}=d[g];x?.(h)}})},s=()=>WP.delete(t),a=()=>c().map(({args:d})=>d),c=()=>WP.get(t)||[],l=(d)=>WP.set(t,[...c(),d]);return{flush:s,async schedule(d){let{promise:f,resolve:h,reject:g}=Hd();if(r?.([...a(),d]))i();if(c().length>0)return l({args:d,resolve:h,reject:g}),f;return l({args:d,resolve:h,reject:g}),setTimeout(i,n),f}}}var WP;var jb=K(()=>{WP=new Map});function a9(e){if(!e||e.length===0)return;return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new eb({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new eb({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function Mle(e){let{balance:t,nonce:r,state:n,stateDiff:o,code:i}=e,s={};if(i!==void 0)s.code=i;if(t!==void 0)s.balance=Z(t);if(r!==void 0)s.nonce=Z(r);if(n!==void 0)s.state=a9(n);if(o!==void 0){if(s.state)throw new yP;s.stateDiff=a9(o)}return s}function Vd(e){if(!e)return;let t={};for(let{address:r,...n}of e){if(!_t(r,{strict:!1}))throw new Qt({address:r});if(t[r])throw new gP({address:r});t[r]=Mle(n)}return t}var qb=K(()=>{Ri();tb();bP();Qn();Ke()});var S2e,_2e,T2e,v2e,E2e,P2e,A2e,I2e,k2e,R2e,C2e,O2e,M2e,N2e,$2e,z2e,L2e,B2e,D2e,F2e,U2e,j2e,q2e,H2e,G2e,V2e,Z2e,W2e,K2e,Y2e,J2e,Q2e,X2e,e6e,t6e,r6e,n6e,o6e,i6e,s6e,a6e,c6e,u6e,l6e,d6e,p6e,f6e,m6e,h6e,g6e,y6e,b6e,x6e,w6e,S6e,_6e,T6e,v6e,E6e,P6e,A6e,I6e,k6e,R6e,C6e,O6e,M6e,N6e,$6e,z6e,L6e,B6e,D6e,F6e,U6e,j6e,q6e,H6e,G6e,V6e,Z6e,W6e,K6e,Y6e,J6e,Q6e,X6e,e5e,t5e,r5e,n5e,o5e,i5e,s5e,a5e,Zd;var KP=K(()=>{S2e=2n**(8n-1n)-1n,_2e=2n**(16n-1n)-1n,T2e=2n**(24n-1n)-1n,v2e=2n**(32n-1n)-1n,E2e=2n**(40n-1n)-1n,P2e=2n**(48n-1n)-1n,A2e=2n**(56n-1n)-1n,I2e=2n**(64n-1n)-1n,k2e=2n**(72n-1n)-1n,R2e=2n**(80n-1n)-1n,C2e=2n**(88n-1n)-1n,O2e=2n**(96n-1n)-1n,M2e=2n**(104n-1n)-1n,N2e=2n**(112n-1n)-1n,$2e=2n**(120n-1n)-1n,z2e=2n**(128n-1n)-1n,L2e=2n**(136n-1n)-1n,B2e=2n**(144n-1n)-1n,D2e=2n**(152n-1n)-1n,F2e=2n**(160n-1n)-1n,U2e=2n**(168n-1n)-1n,j2e=2n**(176n-1n)-1n,q2e=2n**(184n-1n)-1n,H2e=2n**(192n-1n)-1n,G2e=2n**(200n-1n)-1n,V2e=2n**(208n-1n)-1n,Z2e=2n**(216n-1n)-1n,W2e=2n**(224n-1n)-1n,K2e=2n**(232n-1n)-1n,Y2e=2n**(240n-1n)-1n,J2e=2n**(248n-1n)-1n,Q2e=2n**(256n-1n)-1n,X2e=-(2n**(8n-1n)),e6e=-(2n**(16n-1n)),t6e=-(2n**(24n-1n)),r6e=-(2n**(32n-1n)),n6e=-(2n**(40n-1n)),o6e=-(2n**(48n-1n)),i6e=-(2n**(56n-1n)),s6e=-(2n**(64n-1n)),a6e=-(2n**(72n-1n)),c6e=-(2n**(80n-1n)),u6e=-(2n**(88n-1n)),l6e=-(2n**(96n-1n)),d6e=-(2n**(104n-1n)),p6e=-(2n**(112n-1n)),f6e=-(2n**(120n-1n)),m6e=-(2n**(128n-1n)),h6e=-(2n**(136n-1n)),g6e=-(2n**(144n-1n)),y6e=-(2n**(152n-1n)),b6e=-(2n**(160n-1n)),x6e=-(2n**(168n-1n)),w6e=-(2n**(176n-1n)),S6e=-(2n**(184n-1n)),_6e=-(2n**(192n-1n)),T6e=-(2n**(200n-1n)),v6e=-(2n**(208n-1n)),E6e=-(2n**(216n-1n)),P6e=-(2n**(224n-1n)),A6e=-(2n**(232n-1n)),I6e=-(2n**(240n-1n)),k6e=-(2n**(248n-1n)),R6e=-(2n**(256n-1n)),C6e=2n**8n-1n,O6e=2n**16n-1n,M6e=2n**24n-1n,N6e=2n**32n-1n,$6e=2n**40n-1n,z6e=2n**48n-1n,L6e=2n**56n-1n,B6e=2n**64n-1n,D6e=2n**72n-1n,F6e=2n**80n-1n,U6e=2n**88n-1n,j6e=2n**96n-1n,q6e=2n**104n-1n,H6e=2n**112n-1n,G6e=2n**120n-1n,V6e=2n**128n-1n,Z6e=2n**136n-1n,W6e=2n**144n-1n,K6e=2n**152n-1n,Y6e=2n**160n-1n,J6e=2n**168n-1n,Q6e=2n**176n-1n,X6e=2n**184n-1n,e5e=2n**192n-1n,t5e=2n**200n-1n,r5e=2n**208n-1n,n5e=2n**216n-1n,o5e=2n**224n-1n,i5e=2n**232n-1n,s5e=2n**240n-1n,a5e=2n**248n-1n,Zd=2n**256n-1n});function jr(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:n,to:o}=e,i=t?je(t):void 0;if(i&&!_t(i.address))throw new Qt({address:i.address});if(o&&!_t(o))throw new Qt({address:o});if(r&&r>Zd)throw new Zo({maxFeePerGas:r});if(n&&r&&n>r)throw new Us({maxFeePerGas:r,maxPriorityFeePerGas:n})}var Bi=K(()=>{KP();Ri();js();Qn()});var YP,JP,QP;var c9=K(()=>{et();YP=class YP extends N{constructor({callbackSelector:e,cause:t,data:r,extraData:n,sender:o,urls:i}){super(t.shortMessage||"An error occurred while fetching for an offchain result.",{cause:t,metaMessages:[...t.metaMessages||[],t.metaMessages?.length?"":[],"Offchain Gateway Call:",i&&[" Gateway URL(s):",...i.map((s)=>` ${yu(s)}`)],` Sender: ${o}`,` Data: ${r}`,` Callback selector: ${e}`,` Extra data: ${n}`].flat(),name:"OffchainLookupError"})}};JP=class JP extends N{constructor({result:e,url:t}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${yu(t)}`,`Response: ${at(e)}`],name:"OffchainLookupResponseMalformedError"})}};QP=class QP extends N{constructor({sender:e,to:t}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${t}`,`OffchainLookup sender address: ${e}`],name:"OffchainLookupSenderMismatchError"})}}});async function l9(e,{blockNumber:t,blockTag:r,data:n,requestOptions:o,to:i}){let{args:s}=Eb({data:n,abi:[Nle]}),[a,c,l,d,f]=s,{ccipRead:h}=e,g=h&&typeof h?.request==="function"?h.request:$le;try{if(!Ur(i,a))throw new QP({sender:a,to:i});let x=c.includes(zs)?await kP({data:l,ccipRequest:(S)=>g({...S,requestOptions:o})}):await g({data:l,requestOptions:o,sender:a,urls:c}),{data:w}=await Un(e,{blockNumber:t,blockTag:r,data:Or([d,_n([{type:"bytes"},{type:"bytes"}],[x,f])]),requestOptions:o,to:i});return w}catch(x){if(o?.signal?.aborted)throw rn(o.signal);if(Dn(x))throw x;throw new YP({callbackSelector:d,cause:x,data:n,extraData:f,sender:a,urls:c})}}async function $le({data:e,requestOptions:t,sender:r,urls:n}){let o=Error("An unknown error occurred.");for(let i=0;i<n.length;i++){if(t?.signal?.aborted)throw rn(t.signal);let s=n[i],a=s.includes("{data}")?"GET":"POST",c=a==="POST"?{data:e,sender:r}:void 0,l=a==="POST"?{"Content-Type":"application/json"}:{};try{let d=await fetch(s.replace("{sender}",r.toLowerCase()).replace("{data}",e),{body:JSON.stringify(c),headers:l,method:a,...t?.signal?{signal:t.signal}:{}}),f;if(d.headers.get("Content-Type")?.startsWith("application/json"))f=(await d.json()).data;else f=await d.text();if(!d.ok){o=new Go({body:c,details:f?.error?at(f.error):d.statusText,headers:d.headers,status:d.status,url:s});continue}if(!cr(f)){o=new JP({result:f,url:s});continue}return f}catch(d){if(t?.signal?.aborted)throw rn(t.signal);if(Dn(d))throw d;o=new Go({body:c,details:d.message,url:s})}}throw o}var u9="0x556f1830",Nle;var d9=K(()=>{sc();c9();wu();fP();ks();Fs();Vm();Nle={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]}});async function Un(e,t){let{account:r=e.account,authorizationList:n,batch:o=Boolean(e.batch?.multicall),blockHash:i,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,accessList:l,blobs:d,blockOverrides:f,code:h,data:g,factory:x,factoryData:w,gas:S,gasPrice:_,maxFeePerBlobGas:A,maxFeePerGas:T,maxPriorityFeePerGas:v,nonce:E,requestOptions:k,to:O,value:B,stateOverride:G,...M}=t,J=r?je(r):void 0;if(h&&(x||w))throw new N("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(h&&O)throw new N("Cannot provide both `code` & `to` as parameters.");let W=h&&g,he=x&&w&&O&&g,ge=W||he,j=(()=>{if(W)return m9({code:h,data:g});if(he)return Ule({data:g,factory:x,factoryData:w,to:O});return g})();try{jr(t);let se=ro({blockHash:i,blockNumber:s,blockTag:a,requireCanonical:c}),Se=f?Bb(f):void 0,D=Vd(G),q=e.chain?.formatters?.transactionRequest?.format,ke=(q||un)({...Eo(M,{format:q}),accessList:l,account:J,authorizationList:n,blobs:d,data:j,gas:S,gasPrice:_,maxFeePerBlobGas:A,maxFeePerGas:T,maxPriorityFeePerGas:v,nonce:E,to:ge?void 0:O,value:B},"call");if(o&&zle({request:ke})&&!Se&&i===void 0)try{let{deployless:Ce=!1}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},Oe=f9(e,{blockNumber:s,deployless:Ce});if(!Oe||!Fle(D,Oe))return await Dle(e,{...ke,blockHash:i,blockNumber:s,blockTag:a,multicallAddress:Oe,requestOptions:k,requireCanonical:c,rpcStateOverride:D})}catch(Ce){if(!(Ce instanceof _b)&&!(Ce instanceof dd))throw Ce}let ne=(()=>{let Ce=[ke,se];if(D&&Se)return[...Ce,D,Se];if(D)return[...Ce,D];if(Se)return[...Ce,{},Se];return Ce})(),Le=await e.request({method:"eth_call",params:ne},k);if(Le==="0x")return{data:void 0};return{data:Le}}catch(se){if(k?.signal?.aborted)throw rn(k.signal);if(Dn(se))throw se;let Se=jle(se);await Promise.resolve().then(() => d9());if(e.ccipRead!==!1&&Se?.slice(0,10)===u9&&O)return{data:await l9(e,{data:Se,requestOptions:k,to:O})};if(ge&&Se?.slice(0,10)==="0x101bb98d")throw new EP({factory:x});throw Ub(se,{...t,account:J,chain:e.chain})}}function zle({request:e}){let{data:t,to:r,...n}=e;if(!t)return!1;if(t.startsWith(o9))return!1;if(!r)return!1;if(Object.values(n).filter((o)=>typeof o<"u").length>0)return!1;return!0}function Ble(e){if(!e)return"default";let t=p9.get(e);if(t!==void 0)return t;let r=Lle++;return p9.set(e,r),r}async function Dle(e,t){let{batchSize:r=1024,deployless:n=!1,wait:o=0}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},{blockHash:i,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,data:l,multicallAddress:d,requestOptions:f,rpcStateOverride:h,to:g}=t,x=d!==void 0?d:f9(e,{blockNumber:s,deployless:n}),w=ro({blockHash:i,blockNumber:s,blockTag:a,requireCanonical:c}),S=typeof w==="string"?w:JSON.stringify(w),_=h?`.${JSON.stringify(h)}`:"",{schedule:A}=Gd({id:`${e.uid}.${S}.${Ble(f)}${_}`,wait:o,shouldSplitBatch(E){return E.reduce((O,{data:B})=>O+(B.length-2),0)>r*2},fn:async(E)=>{let k=E.map((M)=>({allowFailure:!0,callData:M.data,target:M.to})),O=Dt({abi:bo,args:[k],functionName:"aggregate3"}),B={...x===null?{data:m9({code:Tu,data:O})}:{to:x,data:O}},G=await e.request({method:"eth_call",params:h?[B,w,h]:[B,w]},f);return sn({abi:bo,args:[k],functionName:"aggregate3",data:G||"0x"})}}),[{returnData:T,success:v}]=await A({data:l,to:g});if(!v)throw new Ns({data:T});if(T==="0x")return{data:void 0};return{data:T}}function f9(e,t){let{blockNumber:r,deployless:n}=t;if(n)return null;if(e.chain)return So({blockNumber:r,chain:e.chain,contract:"multicall3"});throw new _b}function Fle(e,t){if(!e)return!1;return Object.keys(e).some((r)=>Ur(r,t))}function m9(e){let{code:t,data:r}=e;return vu({abi:bb(["constructor(bytes, bytes)"]),bytecode:Db,args:[t,r]})}function Ule(e){let{data:t,factory:r,factoryData:n,to:o}=e;return vu({abi:bb(["constructor(address, bytes, address, bytes)"]),bytecode:i9,args:[o,t,r,n]})}function jle(e){if(!(e instanceof N))return;let t=e.walk();return typeof t?.data==="object"?t.data?.data:t.data}var Lle=0,p9;var sc=K(()=>{Dm();GP();en();et();Um();$s();Ms();Fb();Bn();Fs();Eu();mu();ZP();qs();jb();qb();Bi();p9=new WeakMap});var oA,iA=(e,t,r)=>new oA(e,t).update(r).digest();var I9=K(()=>{tu();oA=class oA extends fm{constructor(e,t){super();this.finished=!1,this.destroyed=!1,R4(e);let r=pm(t);if(this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),ys(o)}update(e){return Zl(this),this.iHash.update(e),this}digestInto(e){Zl(this),eu(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:r,finished:n,destroyed:o,blockLen:i,outputLen:s}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};iA.create=(e,t)=>new oA(e,t)});function k9(e){if(e.lowS!==void 0)Ei("lowS",e.lowS);if(e.prehash!==void 0)Ei("prehash",e.prehash)}function Yle(e){let t=xm(e);Ss(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw Error("invalid endo: CURVE.a must be 0");if(typeof r!=="object"||typeof r.beta!=="bigint"||typeof r.splitScalar!=="function")throw Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}function sA(e,t){return Va(iu(e,t))}function Qle(e){let t=Yle(e),{Fp:r}=t,n=_s(t.n,t.nBitLength),o=t.toBytes||((T,v,E)=>{let k=v.toAffine();return Za(Uint8Array.from([4]),r.toBytes(k.x),r.toBytes(k.y))}),i=t.fromBytes||((T)=>{let v=T.subarray(1),E=r.fromBytes(v.subarray(0,r.BYTES)),k=r.fromBytes(v.subarray(r.BYTES,2*r.BYTES));return{x:E,y:k}});function s(T){let{a:v,b:E}=t,k=r.sqr(T),O=r.mul(k,T);return r.add(r.add(O,r.mul(T,v)),E)}function a(T,v){let E=r.sqr(v),k=s(T);return r.eql(E,k)}if(!a(t.Gx,t.Gy))throw Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,aA),Jle),l=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,l)))throw Error("bad curve params: a or b");function d(T){return k0(T,qr,t.n)}function f(T){let{allowedPrivateKeyLengths:v,nByteLength:E,wrapPrivateKey:k,n:O}=t;if(v&&typeof T!=="bigint"){if(Wl(T))T=Va(T);if(typeof T!=="string"||!v.includes(T.length))throw Error("invalid private key");T=T.padStart(E*2,"0")}let B;try{B=typeof T==="bigint"?T:ws(nr("private key",T,E))}catch(G){throw Error("invalid private key, expected hex or "+E+" bytes, got "+typeof T)}if(k)B=Lt(B,O);return Yn("private key",B,qr,O),B}function h(T){if(!(T instanceof w))throw Error("ProjectivePoint expected")}let g=Yl((T,v)=>{let{px:E,py:k,pz:O}=T;if(r.eql(O,r.ONE))return{x:E,y:k};let B=T.is0();if(v==null)v=B?r.ONE:r.inv(O);let G=r.mul(E,v),M=r.mul(k,v),J=r.mul(O,v);if(B)return{x:r.ZERO,y:r.ZERO};if(!r.eql(J,r.ONE))throw Error("invZ was invalid");return{x:G,y:M}}),x=Yl((T)=>{if(T.is0()){if(t.allowInfinityPoint&&!r.is0(T.py))return;throw Error("bad point: ZERO")}let{x:v,y:E}=T.toAffine();if(!r.isValid(v)||!r.isValid(E))throw Error("bad point: x or y not FE");if(!a(v,E))throw Error("bad point: equation left != right");if(!T.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class w{constructor(T,v,E){if(T==null||!r.isValid(T))throw Error("x required");if(v==null||!r.isValid(v)||r.is0(v))throw Error("y required");if(E==null||!r.isValid(E))throw Error("z required");this.px=T,this.py=v,this.pz=E,Object.freeze(this)}static fromAffine(T){let{x:v,y:E}=T||{};if(!T||!r.isValid(v)||!r.isValid(E))throw Error("invalid affine point");if(T instanceof w)throw Error("projective point not allowed");let k=(O)=>r.eql(O,r.ZERO);if(k(v)&&k(E))return w.ZERO;return new w(v,E,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(T){let v=Jl(r,T.map((E)=>E.pz));return T.map((E,k)=>E.toAffine(v[k])).map(w.fromAffine)}static fromHex(T){let v=w.fromAffine(i(nr("pointHex",T)));return v.assertValidity(),v}static fromPrivateKey(T){return w.BASE.multiply(f(T))}static msm(T,v){return O0(w,n,T,v)}_setWindowSize(T){A.setWindowSize(this,T)}assertValidity(){x(this)}hasEvenY(){let{y:T}=this.toAffine();if(r.isOdd)return!r.isOdd(T);throw Error("Field doesn't support isOdd")}equals(T){h(T);let{px:v,py:E,pz:k}=this,{px:O,py:B,pz:G}=T,M=r.eql(r.mul(v,G),r.mul(O,k)),J=r.eql(r.mul(E,G),r.mul(B,k));return M&&J}negate(){return new w(this.px,r.neg(this.py),this.pz)}double(){let{a:T,b:v}=t,E=r.mul(v,aA),{px:k,py:O,pz:B}=this,{ZERO:G,ZERO:M,ZERO:J}=r,W=r.mul(k,k),he=r.mul(O,O),ge=r.mul(B,B),j=r.mul(k,O);return j=r.add(j,j),J=r.mul(k,B),J=r.add(J,J),G=r.mul(T,J),M=r.mul(E,ge),M=r.add(G,M),G=r.sub(he,M),M=r.add(he,M),M=r.mul(G,M),G=r.mul(j,G),J=r.mul(E,J),ge=r.mul(T,ge),j=r.sub(W,ge),j=r.mul(T,j),j=r.add(j,J),J=r.add(W,W),W=r.add(J,W),W=r.add(W,ge),W=r.mul(W,j),M=r.add(M,W),ge=r.mul(O,B),ge=r.add(ge,ge),W=r.mul(ge,j),G=r.sub(G,W),J=r.mul(ge,he),J=r.add(J,J),J=r.add(J,J),new w(G,M,J)}add(T){h(T);let{px:v,py:E,pz:k}=this,{px:O,py:B,pz:G}=T,{ZERO:M,ZERO:J,ZERO:W}=r,he=t.a,ge=r.mul(t.b,aA),j=r.mul(v,O),se=r.mul(E,B),Se=r.mul(k,G),D=r.add(v,E),q=r.add(O,B);D=r.mul(D,q),q=r.add(j,se),D=r.sub(D,q),q=r.add(v,k);let Q=r.add(O,G);return q=r.mul(q,Q),Q=r.add(j,Se),q=r.sub(q,Q),Q=r.add(E,k),M=r.add(B,G),Q=r.mul(Q,M),M=r.add(se,Se),Q=r.sub(Q,M),W=r.mul(he,q),M=r.mul(ge,Se),W=r.add(M,W),M=r.sub(se,W),W=r.add(se,W),J=r.mul(M,W),se=r.add(j,j),se=r.add(se,j),Se=r.mul(he,Se),q=r.mul(ge,q),se=r.add(se,Se),Se=r.sub(j,Se),Se=r.mul(he,Se),q=r.add(q,Se),j=r.mul(se,q),J=r.add(J,j),j=r.mul(Q,q),M=r.mul(D,M),M=r.sub(M,j),j=r.mul(D,se),W=r.mul(Q,W),W=r.add(W,j),new w(M,J,W)}subtract(T){return this.add(T.negate())}is0(){return this.equals(w.ZERO)}wNAF(T){return A.wNAFCached(this,T,w.normalizeZ)}multiplyUnsafe(T){let{endo:v,n:E}=t;Yn("scalar",T,Gs,E);let k=w.ZERO;if(T===Gs)return k;if(this.is0()||T===qr)return this;if(!v||A.hasPrecomputes(this))return A.wNAFCachedUnsafe(this,T,w.normalizeZ);let{k1neg:O,k1:B,k2neg:G,k2:M}=v.splitScalar(T),J=k,W=k,he=this;while(B>Gs||M>Gs){if(B&qr)J=J.add(he);if(M&qr)W=W.add(he);he=he.double(),B>>=qr,M>>=qr}if(O)J=J.negate();if(G)W=W.negate();return W=new w(r.mul(W.px,v.beta),W.py,W.pz),J.add(W)}multiply(T){let{endo:v,n:E}=t;Yn("scalar",T,qr,E);let k,O;if(v){let{k1neg:B,k1:G,k2neg:M,k2:J}=v.splitScalar(T),{p:W,f:he}=this.wNAF(G),{p:ge,f:j}=this.wNAF(J);W=A.constTimeNegate(B,W),ge=A.constTimeNegate(M,ge),ge=new w(r.mul(ge.px,v.beta),ge.py,ge.pz),k=W.add(ge),O=he.add(j)}else{let{p:B,f:G}=this.wNAF(T);k=B,O=G}return w.normalizeZ([k,O])[0]}multiplyAndAddUnsafe(T,v,E){let k=w.BASE,O=(G,M)=>M===Gs||M===qr||!G.equals(k)?G.multiplyUnsafe(M):G.multiply(M),B=O(this,v).add(O(T,E));return B.is0()?void 0:B}toAffine(T){return g(this,T)}isTorsionFree(){let{h:T,isTorsionFree:v}=t;if(T===qr)return!0;if(v)return v(w,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:T,clearCofactor:v}=t;if(T===qr)return this;if(v)return v(w,this);return this.multiplyUnsafe(t.h)}toRawBytes(T=!0){return Ei("isCompressed",T),this.assertValidity(),o(w,this,T)}toHex(T=!0){return Ei("isCompressed",T),Va(this.toRawBytes(T))}}w.BASE=new w(t.Gx,t.Gy,r.ONE),w.ZERO=new w(r.ZERO,r.ONE,r.ZERO);let{endo:S,nBitLength:_}=t,A=C0(w,S?Math.ceil(_/2):_);return{CURVE:t,ProjectivePoint:w,normPrivateKeyToScalar:f,weierstrassEquation:s,isWithinCurveOrder:d}}function Xle(e){let t=xm(e);return Ss(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function C9(e){let t=Xle(e),{Fp:r,n,nByteLength:o,nBitLength:i}=t,s=r.BYTES+1,a=2*r.BYTES+1;function c(j){return Lt(j,n)}function l(j){return R0(j,n)}let{ProjectivePoint:d,normPrivateKeyToScalar:f,weierstrassEquation:h,isWithinCurveOrder:g}=Qle({...t,toBytes(j,se,Se){let D=se.toAffine(),q=r.toBytes(D.x),Q=Za;if(Ei("isCompressed",Se),Se)return Q(Uint8Array.from([se.hasEvenY()?2:3]),q);else return Q(Uint8Array.from([4]),q,r.toBytes(D.y))},fromBytes(j){let se=j.length,Se=j[0],D=j.subarray(1);if(se===s&&(Se===2||Se===3)){let q=ws(D);if(!k0(q,qr,r.ORDER))throw Error("Point is not on curve");let Q=h(q),ke;try{ke=r.sqrt(Q)}catch(Ce){let Oe=Ce instanceof Error?": "+Ce.message:"";throw Error("Point is not on curve"+Oe)}let ne=(ke&qr)===qr;if((Se&1)===1!==ne)ke=r.neg(ke);return{x:q,y:ke}}else if(se===a&&Se===4){let q=r.fromBytes(D.subarray(0,r.BYTES)),Q=r.fromBytes(D.subarray(r.BYTES,2*r.BYTES));return{x:q,y:Q}}else{let q=s,Q=a;throw Error("invalid Point, expected length of "+q+", or uncompressed "+Q+", got "+se)}}});function x(j){let se=n>>qr;return j>se}function w(j){return x(j)?c(-j):j}let S=(j,se,Se)=>ws(j.slice(se,Se));class _{constructor(j,se,Se){if(Yn("r",j,qr,n),Yn("s",se,qr,n),this.r=j,this.s=se,Se!=null)this.recovery=Se;Object.freeze(this)}static fromCompact(j){let se=o;return j=nr("compactSignature",j,se*2),new _(S(j,0,se),S(j,se,2*se))}static fromDER(j){let{r:se,s:Se}=Hs.toSig(nr("DER",j));return new _(se,Se)}assertValidity(){}addRecoveryBit(j){return new _(this.r,this.s,j)}recoverPublicKey(j){let{r:se,s:Se,recovery:D}=this,q=O(nr("msgHash",j));if(D==null||![0,1,2,3].includes(D))throw Error("recovery id invalid");let Q=D===2||D===3?se+t.n:se;if(Q>=r.ORDER)throw Error("recovery id 2 or 3 invalid");let ke=(D&1)===0?"02":"03",ne=d.fromHex(ke+sA(Q,r.BYTES)),Le=l(Q),Ce=c(-q*Le),Oe=c(Se*Le),ct=d.BASE.multiplyAndAddUnsafe(ne,Ce,Oe);if(!ct)throw Error("point at infinify");return ct.assertValidity(),ct}hasHighS(){return x(this.s)}normalizeS(){return this.hasHighS()?new _(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ym(this.toDERHex())}toDERHex(){return Hs.hexFromSig(this)}toCompactRawBytes(){return ym(this.toCompactHex())}toCompactHex(){let j=o;return sA(this.r,j)+sA(this.s,j)}}let A={isValidPrivateKey(j){try{return f(j),!0}catch(se){return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let j=Dv(t.n);return uB(t.randomBytes(j),t.n)},precompute(j=8,se=d.BASE){return se._setWindowSize(j),se.multiply(BigInt(3)),se}};function T(j,se=!0){return d.fromPrivateKey(j).toRawBytes(se)}function v(j){if(typeof j==="bigint")return!1;if(j instanceof d)return!0;let Se=nr("key",j).length,D=r.BYTES,q=D+1,Q=2*D+1;if(t.allowedPrivateKeyLengths||o===q)return;else return Se===q||Se===Q}function E(j,se,Se=!0){if(v(j)===!0)throw Error("first arg must be private key");if(v(se)===!1)throw Error("second arg must be public key");return d.fromHex(se).multiply(f(j)).toRawBytes(Se)}let k=t.bits2int||function(j){if(j.length>8192)throw Error("input is too large");let se=ws(j),Se=j.length*8-i;return Se>0?se>>BigInt(Se):se},O=t.bits2int_modN||function(j){return c(k(j))},B=su(i);function G(j){return Yn("num < 2^"+i,j,Gs,B),iu(j,o)}function M(j,se,Se=J){if(["recovered","canonical"].some((Ft)=>(Ft in Se)))throw Error("sign() legacy options not supported");let{hash:D,randomBytes:q}=t,{lowS:Q,prehash:ke,extraEntropy:ne}=Se;if(Q==null)Q=!0;if(j=nr("msgHash",j),k9(Se),ke)j=nr("prehashed msgHash",D(j));let Le=O(j),Ce=f(se),Oe=[G(Ce),G(Le)];if(ne!=null&&ne!==!1){let Ft=ne===!0?q(r.BYTES):ne;Oe.push(nr("extraEntropy",Ft))}let ct=Za(...Oe),gt=Le;function yt(Ft){let Kt=k(Ft);if(!g(Kt))return;let pr=l(Kt),_r=d.BASE.multiply(Kt).toAffine(),ir=c(_r.x);if(ir===Gs)return;let At=c(pr*c(gt+ir*Ce));if(At===Gs)return;let Vr=(_r.x===ir?0:2)|Number(_r.y&qr),Vi=At;if(Q&&x(At))Vi=w(At),Vr^=1;return new _(ir,Vi,Vr)}return{seed:ct,k2sig:yt}}let J={lowS:t.lowS,prehash:!1},W={lowS:t.lowS,prehash:!1};function he(j,se,Se=J){let{seed:D,k2sig:q}=M(j,se,Se),Q=t;return tB(Q.hash.outputLen,Q.nByteLength,Q.hmac)(D,q)}d.BASE._setWindowSize(8);function ge(j,se,Se,D=W){let q=j;se=nr("msgHash",se),Se=nr("publicKey",Se);let{lowS:Q,prehash:ke,format:ne}=D;if(k9(D),"strict"in D)throw Error("options.strict was renamed to lowS");if(ne!==void 0&&ne!=="compact"&&ne!=="der")throw Error("format must be compact or der");let Le=typeof q==="string"||Wl(q),Ce=!Le&&!ne&&typeof q==="object"&&q!==null&&typeof q.r==="bigint"&&typeof q.s==="bigint";if(!Le&&!Ce)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");let Oe=void 0,ct;try{if(Ce)Oe=new _(q.r,q.s);if(Le){try{if(ne!=="compact")Oe=_.fromDER(q)}catch(Vr){if(!(Vr instanceof Hs.Err))throw Vr}if(!Oe&&ne!=="der")Oe=_.fromCompact(q)}ct=d.fromHex(Se)}catch(Vr){return!1}if(!Oe)return!1;if(Q&&Oe.hasHighS())return!1;if(ke)se=t.hash(se);let{r:gt,s:yt}=Oe,Ft=O(se),Kt=l(yt),pr=c(Ft*Kt),_r=c(gt*Kt),ir=d.BASE.multiplyAndAddUnsafe(ct,pr,_r)?.toAffine();if(!ir)return!1;return c(ir.x)===gt}return{CURVE:t,getPublicKey:T,getSharedSecret:E,sign:he,verify:ge,ProjectivePoint:d,Signature:_,utils:A}}var R9,Hs,Gs,qr,jOe,aA,Jle;var O9=K(()=>{Gv();Ql();bm();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */R9=class R9 extends Error{constructor(e=""){super(e)}};Hs={Err:R9,_tlv:{encode:(e,t)=>{let{Err:r}=Hs;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=gm(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let i=n>127?gm(o.length/2|128):"";return gm(e)+i+o+t},decode(e,t){let{Err:r}=Hs,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of l)s=s<<8|d;if(n+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(e){let{Err:t}=Hs;if(e<Gs)throw new t("integer: negative integers are not allowed");let r=gm(e);if(Number.parseInt(r[0],16)&8)r="00"+r;if(r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=Hs;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return ws(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=Hs,o=nr("signature",e),{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:d}=n.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){let{_tlv:t,_int:r}=Hs,n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),i=n+o;return t.encode(48,i)}};Gs=BigInt(0),qr=BigInt(1),jOe=BigInt(2),aA=BigInt(3),Jle=BigInt(4)});function ede(e){return{hash:e,hmac:(t,...r)=>iA(e,t,Av(...r)),randomBytes:P0}}function M9(e,t){let r=(n)=>C9({...e,...ede(n)});return{...r(t),create:r}}var N9=K(()=>{I9();tu();O9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */});function nde(e){let t=L9,r=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,d=l*l*e%t,f=or(d,r,t)*d%t,h=or(f,r,t)*d%t,g=or(h,cA,t)*l%t,x=or(g,o,t)*g%t,w=or(x,i,t)*x%t,S=or(w,a,t)*w%t,_=or(S,c,t)*S%t,A=or(_,a,t)*w%t,T=or(A,r,t)*d%t,v=or(T,s,t)*x%t,E=or(v,n,t)*l%t,k=or(E,cA,t);if(!uA.eql(uA.sqr(k),e))throw Error("Cannot find square root");return k}var L9,$9,tde,rde,cA,z9=(e,t)=>(e+t/cA)/t,uA,Vs;var ih=K(()=>{Cv();N9();Ql();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */L9=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),$9=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),tde=BigInt(0),rde=BigInt(1),cA=BigInt(2);uA=_s(L9,void 0,void 0,{sqrt:nde}),Vs=M9({a:tde,b:BigInt(7),Fp:uA,n:$9,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:(e)=>{let t=$9,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-rde*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,s=BigInt("0x100000000000000000000000000000000"),a=z9(i*e,t),c=z9(-n*e,t),l=Lt(e-a*r-c*o,t),d=Lt(-a*n-c*i,t),f=l>s,h=d>s;if(f)l=t-l;if(h)d=t-d;if(l>s||d>s)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:f,k1:l,k2neg:h,k2:d}}}},W4)});var wl={};GZ(wl,{ZodISODate:()=>xC,ZodISODateTime:()=>bC,ZodISODuration:()=>SC,ZodISOTime:()=>wC,date:()=>GT,datetime:()=>oy,duration:()=>ZT,time:()=>VT});import{webcrypto as Fhe}from"node:crypto";import yW from"node:http";import bW from"node:https";import Qu from"node:zlib";import n2,{PassThrough as o2,pipeline as Xu}from"node:stream";import{Buffer as ag}from"node:buffer";function ZZ(e){if(!/^data:/i.test(e))throw TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');e=e.replace(/\r?\n/g,"");let t=e.indexOf(",");if(t===-1||t<=4)throw TypeError("malformed data: URI");let r=e.substring(5,t).split(";"),n="",o=!1,i=r[0]||"text/plain",s=i;for(let d=1;d<r.length;d++)if(r[d]==="base64")o=!0;else if(r[d]){if(s+=`;${r[d]}`,r[d].indexOf("charset=")===0)n=r[d].substring(8)}if(!r[0]&&!n.length)s+=";charset=US-ASCII",n="US-ASCII";let a=o?"base64":"ascii",c=unescape(e.substring(t+1)),l=Buffer.from(c,a);return l.type=i,l.typeFull=s,l.charset=n,l}var ER=ZZ;Yp();Xh();import sa,{PassThrough as qR}from"node:stream";import{types as HR,deprecate as cS,promisify as cW}from"node:util";import{Buffer as so}from"node:buffer";class oa extends Error{constructor(e,t){super(e);Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}class qn extends oa{constructor(e,t,r){super(e,t);if(r)this.code=this.errno=r.code,this.erroredSysCall=r.syscall}}var eg=Symbol.toStringTag,iS=(e)=>typeof e==="object"&&typeof e.append==="function"&&typeof e.delete==="function"&&typeof e.get==="function"&&typeof e.getAll==="function"&&typeof e.has==="function"&&typeof e.set==="function"&&typeof e.sort==="function"&&e[eg]==="URLSearchParams",Qp=(e)=>e&&typeof e==="object"&&typeof e.arrayBuffer==="function"&&typeof e.type==="string"&&typeof e.stream==="function"&&typeof e.constructor==="function"&&/^(Blob|File)$/.test(e[eg]),NR=(e)=>typeof e==="object"&&(e[eg]==="AbortSignal"||e[eg]==="EventTarget"),$R=(e,t)=>{let r=new URL(t).hostname,n=new URL(e).hostname;return r===n||r.endsWith(`.${n}`)},zR=(e,t)=>{let r=new URL(t).protocol,n=new URL(e).protocol;return r===n};var uW=cW(sa.pipeline),An=Symbol("Body internals");class ts{constructor(e,{size:t=0}={}){let r=null;if(e===null)e=null;else if(iS(e))e=so.from(e.toString());else if(Qp(e));else if(so.isBuffer(e));else if(HR.isAnyArrayBuffer(e))e=so.from(e);else if(ArrayBuffer.isView(e))e=so.from(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof sa);else if(e instanceof kc)e=MR(e),r=e.type.split("=")[1];else e=so.from(String(e));let n=e;if(so.isBuffer(e))n=sa.Readable.from(e);else if(Qp(e))n=sa.Readable.from(e.stream());if(this[An]={body:e,stream:n,boundary:r,disturbed:!1,error:null},this.size=t,e instanceof sa)e.on("error",(o)=>{let i=o instanceof oa?o:new qn(`Invalid response body while trying to fetch ${this.url}: ${o.message}`,"system",o);this[An].error=i})}get body(){return this[An].stream}get bodyUsed(){return this[An].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:r}=await aS(this);return e.slice(t,t+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new kc,n=new URLSearchParams(await this.text());for(let[o,i]of n)r.append(o,i);return r}await Promise.resolve().then(() => jR());return UR(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[An].body&&this[An].body.type||"",t=await this.arrayBuffer();return new es([t],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await aS(this);return new TextDecoder().decode(e)}buffer(){return aS(this)}}ts.prototype.buffer=cS(ts.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(ts.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:cS(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});async function aS(e){if(e[An].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[An].disturbed=!0,e[An].error)throw e[An].error;let{body:t}=e;if(t===null)return so.alloc(0);if(!(t instanceof sa))return so.alloc(0);let r=[],n=0;try{for await(let o of t){if(e.size>0&&n+o.length>e.size){let i=new qn(`content size at ${e.url} over limit: ${e.size}`,"max-size");throw t.destroy(i),i}n+=o.length,r.push(o)}}catch(o){throw o instanceof oa?o:new qn(`Invalid response body while trying to fetch ${e.url}: ${o.message}`,"system",o)}if(t.readableEnded===!0||t._readableState.ended===!0)try{if(r.every((o)=>typeof o==="string"))return so.from(r.join(""));return so.concat(r,n)}catch(o){throw new qn(`Could not create Buffer from response body for ${e.url}: ${o.message}`,"system",o)}else throw new qn(`Premature close of server response while trying to fetch ${e.url}`)}var Yu=(e,t)=>{let r,n,{body:o}=e[An];if(e.bodyUsed)throw Error("cannot clone body after it is used");if(o instanceof sa&&typeof o.getBoundary!=="function")r=new qR({highWaterMark:t}),n=new qR({highWaterMark:t}),o.pipe(r),o.pipe(n),e[An].stream=r,o=n;return o},lW=cS((e)=>e.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),ng=(e,t)=>{if(e===null)return null;if(typeof e==="string")return"text/plain;charset=UTF-8";if(iS(e))return"application/x-www-form-urlencoded;charset=UTF-8";if(Qp(e))return e.type||null;if(so.isBuffer(e)||HR.isAnyArrayBuffer(e)||ArrayBuffer.isView(e))return null;if(e instanceof kc)return`multipart/form-data; boundary=${t[An].boundary}`;if(e&&typeof e.getBoundary==="function")return`multipart/form-data;boundary=${lW(e)}`;if(e instanceof sa)return null;return"text/plain;charset=UTF-8"},GR=(e)=>{let{body:t}=e[An];if(t===null)return 0;if(Qp(t))return t.size;if(so.isBuffer(t))return t.length;if(t&&typeof t.getLengthSync==="function")return t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null;return null},VR=async(e,{body:t})=>{if(t===null)e.end();else await uW(t,e)};import{types as ZR}from"node:util";import ig from"node:http";var og=typeof ig.validateHeaderName==="function"?ig.validateHeaderName:(e)=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){let t=TypeError(`Header name must be a valid HTTP token [${e}]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),t}},uS=typeof ig.validateHeaderValue==="function"?ig.validateHeaderValue:(e,t)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(t)){let r=TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(r,"code",{value:"ERR_INVALID_CHAR"}),r}};class fn extends URLSearchParams{constructor(e){let t=[];if(e instanceof fn){let r=e.raw();for(let[n,o]of Object.entries(r))t.push(...o.map((i)=>[n,i]))}else if(e==null);else if(typeof e==="object"&&!ZR.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)t.push(...Object.entries(e));else{if(typeof r!=="function")throw TypeError("Header pairs must be iterable");t=[...e].map((n)=>{if(typeof n!=="object"||ZR.isBoxedPrimitive(n))throw TypeError("Each header pair must be an iterable object");return[...n]}).map((n)=>{if(n.length!==2)throw TypeError("Each header pair must be a name/value tuple");return[...n]})}}else throw TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");t=t.length>0?t.map(([r,n])=>(og(r),uS(r,String(n)),[String(r).toLowerCase(),String(n)])):void 0;super(t);return new Proxy(this,{get(r,n,o){switch(n){case"append":case"set":return(i,s)=>(og(i),uS(i,String(s)),URLSearchParams.prototype[n].call(r,String(i).toLowerCase(),String(s)));case"delete":case"has":case"getAll":return(i)=>(og(i),URLSearchParams.prototype[n].call(r,String(i).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,n,o)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let r=t.join(", ");if(/^content-encoding$/i.test(e))r=r.toLowerCase();return r}forEach(e,t=void 0){for(let r of this.keys())Reflect.apply(e,t,[this.get(r),r,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,t)=>{let r=this.getAll(t);if(t==="host")e[t]=r[0];else e[t]=r.length>1?r:r[0];return e},{})}}Object.defineProperties(fn.prototype,["get","entries","forEach","values"].reduce((e,t)=>(e[t]={enumerable:!0},e),{}));function WR(e=[]){return new fn(e.reduce((t,r,n,o)=>{if(n%2===0)t.push(o.slice(n,n+2));return t},[]).filter(([t,r])=>{try{return og(t),uS(t,String(r)),!0}catch{return!1}}))}var dW=new Set([301,302,303,307,308]),sg=(e)=>dW.has(e);var Ro=Symbol("Response internals");class Wr extends ts{constructor(e=null,t={}){super(e,t);let r=t.status!=null?t.status:200,n=new fn(t.headers);if(e!==null&&!n.has("Content-Type")){let o=ng(e,this);if(o)n.append("Content-Type",o)}this[Ro]={type:"default",url:t.url,status:r,statusText:t.statusText||"",headers:n,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[Ro].type}get url(){return this[Ro].url||""}get status(){return this[Ro].status}get ok(){return this[Ro].status>=200&&this[Ro].status<300}get redirected(){return this[Ro].counter>0}get statusText(){return this[Ro].statusText}get headers(){return this[Ro].headers}get highWaterMark(){return this[Ro].highWaterMark}clone(){return new Wr(Yu(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,t=302){if(!sg(t))throw RangeError('Failed to execute "redirect" on "response": Invalid status code');return new Wr(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new Wr(null,{status:0,statusText:""});return e[Ro].type="error",e}static json(e=void 0,t={}){let r=JSON.stringify(e);if(r===void 0)throw TypeError("data is not JSON serializable");let n=new fn(t&&t.headers);if(!n.has("content-type"))n.set("content-type","application/json");return new Wr(r,{...t,headers:n})}get[Symbol.toStringTag](){return"Response"}}Object.defineProperties(Wr.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});import{format as mW}from"node:url";import{deprecate as hW}from"node:util";var KR=(e)=>{if(e.search)return e.search;let t=e.href.length-1,r=e.hash||(e.href[t]==="#"?"#":"");return e.href[t-r.length]==="?"?"?":""};import{isIP as pW}from"node:net";function YR(e,t=!1){if(e==null)return"no-referrer";if(e=new URL(e),/^(about|blob|data):$/.test(e.protocol))return"no-referrer";if(e.username="",e.password="",e.hash="",t)e.pathname="",e.search="";return e}var JR=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),QR="strict-origin-when-cross-origin";function XR(e){if(!JR.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function fW(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let t=e.host.replace(/(^\[)|(]$)/g,""),r=pW(t);if(r===4&&/^127\./.test(t))return!0;if(r===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(t))return!0;if(e.host==="localhost"||e.host.endsWith(".localhost"))return!1;if(e.protocol==="file:")return!0;return!1}function Ju(e){if(/^about:(blank|srcdoc)$/.test(e))return!0;if(e.protocol==="data:")return!0;if(/^(blob|filesystem):$/.test(e.protocol))return!0;return fW(e)}function e2(e,{referrerURLCallback:t,referrerOriginCallback:r}={}){if(e.referrer==="no-referrer"||e.referrerPolicy==="")return null;let n=e.referrerPolicy;if(e.referrer==="about:client")return"no-referrer";let o=e.referrer,i=YR(o),s=YR(o,!0);if(i.toString().length>4096)i=s;if(t)i=t(i);if(r)s=r(s);let a=new URL(e.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return s;case"unsafe-url":return i;case"strict-origin":if(Ju(i)&&!Ju(a))return"no-referrer";return s.toString();case"strict-origin-when-cross-origin":if(i.origin===a.origin)return i;if(Ju(i)&&!Ju(a))return"no-referrer";return s;case"same-origin":if(i.origin===a.origin)return i;return"no-referrer";case"origin-when-cross-origin":if(i.origin===a.origin)return i;return s;case"no-referrer-when-downgrade":if(Ju(i)&&!Ju(a))return"no-referrer";return i;default:throw TypeError(`Invalid referrerPolicy: ${n}`)}}function t2(e){let t=(e.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of t)if(n&&JR.has(n))r=n;return r}var Nr=Symbol("Request internals"),ef=(e)=>typeof e==="object"&&typeof e[Nr]==="object",gW=hW(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)");class rs extends ts{constructor(e,t={}){let r;if(ef(e))r=new URL(e.url);else r=new URL(e),e={};if(r.username!==""||r.password!=="")throw TypeError(`${r} is an url with embedded credentials.`);let n=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(n))n=n.toUpperCase();if(!ef(t)&&"data"in t)gW();if((t.body!=null||ef(e)&&e.body!==null)&&(n==="GET"||n==="HEAD"))throw TypeError("Request with GET/HEAD method cannot have body");let o=t.body?t.body:ef(e)&&e.body!==null?Yu(e):null;super(o,{size:t.size||e.size||0});let i=new fn(t.headers||e.headers||{});if(o!==null&&!i.has("Content-Type")){let c=ng(o,this);if(c)i.set("Content-Type",c)}let s=ef(e)?e.signal:null;if("signal"in t)s=t.signal;if(s!=null&&!NR(s))throw TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let a=t.referrer==null?e.referrer:t.referrer;if(a==="")a="no-referrer";else if(a){let c=new URL(a);a=/^about:(\/\/)?client$/.test(c)?"client":c}else a=void 0;this[Nr]={method:n,redirect:t.redirect||e.redirect||"follow",headers:i,parsedURL:r,signal:s,referrer:a},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||""}get method(){return this[Nr].method}get url(){return mW(this[Nr].parsedURL)}get headers(){return this[Nr].headers}get redirect(){return this[Nr].redirect}get signal(){return this[Nr].signal}get referrer(){if(this[Nr].referrer==="no-referrer")return"";if(this[Nr].referrer==="client")return"about:client";if(this[Nr].referrer)return this[Nr].referrer.toString();return}get referrerPolicy(){return this[Nr].referrerPolicy}set referrerPolicy(e){this[Nr].referrerPolicy=XR(e)}clone(){return new rs(this)}get[Symbol.toStringTag](){return"Request"}}Object.defineProperties(rs.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});var r2=(e)=>{let{parsedURL:t}=e[Nr],r=new fn(e[Nr].headers);if(!r.has("Accept"))r.set("Accept","*/*");let n=null;if(e.body===null&&/^(post|put)$/i.test(e.method))n="0";if(e.body!==null){let a=GR(e);if(typeof a==="number"&&!Number.isNaN(a))n=String(a)}if(n)r.set("Content-Length",n);if(e.referrerPolicy==="")e.referrerPolicy=QR;if(e.referrer&&e.referrer!=="no-referrer")e[Nr].referrer=e2(e);else e[Nr].referrer="no-referrer";if(e[Nr].referrer instanceof URL)r.set("Referer",e.referrer);if(!r.has("User-Agent"))r.set("User-Agent","node-fetch");if(e.compress&&!r.has("Accept-Encoding"))r.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=e;if(typeof o==="function")o=o(t);let i=KR(t),s={path:t.pathname+i,method:e.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:e.insecureHTTPParser,agent:o};return{parsedURL:t,options:s}};class lS extends oa{constructor(e,t="aborted"){super(e,t)}}Xh();sS();var xW=new Set(["data:","http:","https:"]);async function cg(e,t){return new Promise((r,n)=>{let o=new rs(e,t),{parsedURL:i,options:s}=r2(o);if(!xW.has(i.protocol))throw TypeError(`node-fetch cannot load ${e}. URL scheme "${i.protocol.replace(/:$/,"")}" is not supported.`);if(i.protocol==="data:"){let x=ER(o.url),w=new Wr(x,{headers:{"Content-Type":x.typeFull}});r(w);return}let a=(i.protocol==="https:"?bW:yW).request,{signal:c}=o,l=null,d=()=>{let x=new lS("The operation was aborted.");if(n(x),o.body&&o.body instanceof n2.Readable)o.body.destroy(x);if(!l||!l.body)return;l.body.emit("error",x)};if(c&&c.aborted){d();return}let f=()=>{d(),g()},h=a(i.toString(),s);if(c)c.addEventListener("abort",f);let g=()=>{if(h.abort(),c)c.removeEventListener("abort",f)};if(h.on("error",(x)=>{n(new qn(`request to ${o.url} failed, reason: ${x.message}`,"system",x)),g()}),wW(h,(x)=>{if(l&&l.body)l.body.destroy(x)}),process.version<"v14")h.on("socket",(x)=>{let w;x.prependListener("end",()=>{w=x._eventsCount}),x.prependListener("close",(S)=>{if(l&&w<x._eventsCount&&!S){let _=Error("Premature close");_.code="ERR_STREAM_PREMATURE_CLOSE",l.body.emit("error",_)}})});h.on("response",(x)=>{h.setTimeout(0);let w=WR(x.rawHeaders);if(sg(x.statusCode)){let v=w.get("Location"),E=null;try{E=v===null?null:new URL(v,o.url)}catch{if(o.redirect!=="manual"){n(new qn(`uri requested responds with an invalid redirect URL: ${v}`,"invalid-redirect")),g();return}}switch(o.redirect){case"error":n(new qn(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),g();return;case"manual":break;case"follow":{if(E===null)break;if(o.counter>=o.follow){n(new qn(`maximum redirect reached at: ${o.url}`,"max-redirect")),g();return}let k={headers:new fn(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:Yu(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!$R(o.url,E)||!zR(o.url,E))for(let B of["authorization","www-authenticate","cookie","cookie2"])k.headers.delete(B);if(x.statusCode!==303&&o.body&&t.body instanceof n2.Readable){n(new qn("Cannot follow redirect with body being a readable stream","unsupported-redirect")),g();return}if(x.statusCode===303||(x.statusCode===301||x.statusCode===302)&&o.method==="POST")k.method="GET",k.body=void 0,k.headers.delete("content-length");let O=t2(w);if(O)k.referrerPolicy=O;r(cg(new rs(E,k))),g();return}default:return n(TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}if(c)x.once("end",()=>{c.removeEventListener("abort",f)});let S=Xu(x,new o2,(v)=>{if(v)n(v)});if(process.version<"v12.10")x.on("aborted",f);let _={url:o.url,status:x.statusCode,statusText:x.statusMessage,headers:w,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},A=w.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||A===null||x.statusCode===204||x.statusCode===304){l=new Wr(S,_),r(l);return}let T={flush:Qu.Z_SYNC_FLUSH,finishFlush:Qu.Z_SYNC_FLUSH};if(A==="gzip"||A==="x-gzip"){S=Xu(S,Qu.createGunzip(T),(v)=>{if(v)n(v)}),l=new Wr(S,_),r(l);return}if(A==="deflate"||A==="x-deflate"){let v=Xu(x,new o2,(E)=>{if(E)n(E)});v.once("data",(E)=>{if((E[0]&15)===8)S=Xu(S,Qu.createInflate(),(k)=>{if(k)n(k)});else S=Xu(S,Qu.createInflateRaw(),(k)=>{if(k)n(k)});l=new Wr(S,_),r(l)}),v.once("end",()=>{if(!l)l=new Wr(S,_),r(l)});return}if(A==="br"){S=Xu(S,Qu.createBrotliDecompress(),(v)=>{if(v)n(v)}),l=new Wr(S,_),r(l);return}l=new Wr(S,_),r(l)}),VR(h,o).catch(n)})}function wW(e,t){let r=ag.from(`0\r
65
+ `),{cause:e,name:"TipAboveFeeCapError"})}};Object.defineProperty(Us,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});Wo=class Wo extends N{constructor({cause:e}){super(`An error occurred while executing: ${e?.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}});function ic(e,t){let r=(e.details||"").toLowerCase(),n=e instanceof N?e.walk((o)=>o?.code===Li.code):e;if(n instanceof N)return new Li({cause:e,message:n.details});if(Li.nodeMessage.test(r))return new Li({cause:e,message:e.details});if(Zo.nodeMessage.test(r))return new Zo({cause:e,maxFeePerGas:t?.maxFeePerGas});if(Km.nodeMessage.test(r))return new Km({cause:e,maxFeePerGas:t?.maxFeePerGas});if(Ym.nodeMessage.test(r))return new Ym({cause:e,nonce:t?.nonce});if(Jm.nodeMessage.test(r))return new Jm({cause:e,nonce:t?.nonce});if(Qm.nodeMessage.test(r))return new Qm({cause:e,nonce:t?.nonce});if(Xm.nodeMessage.test(r))return new Xm({cause:e});if(eh.nodeMessage.test(r))return new eh({cause:e,gas:t?.gas});if(th.nodeMessage.test(r))return new th({cause:e,gas:t?.gas});if(rh.nodeMessage.test(r))return new rh({cause:e});if(Us.nodeMessage.test(r))return new Us({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas});return new Wo({cause:e})}var nh=K(()=>{et();js()});function Ub(e,{docsPath:t,...r}){let n=(()=>{let o=ic(e,r);if(o instanceof Wo)return e;return o})();return new bu(n,{docsPath:t,...r})}var ZP=K(()=>{$s();js();nh()});function Eo(e,{format:t}){if(!t)return{};let r={};function n(i){let s=Object.keys(i);for(let a of s){if(a in e)r[a]=e[a];if(i[a]&&typeof i[a]==="object"&&!Array.isArray(i[a]))n(i[a])}}let o=t(e||{});return n(o),r}function un(e,t){let r={};if(typeof e.authorizationList<"u")r.authorizationList=Ole(e.authorizationList);if(typeof e.accessList<"u")r.accessList=e.accessList;if(typeof e.blobVersionedHashes<"u")r.blobVersionedHashes=e.blobVersionedHashes;if(typeof e.blobs<"u")if(typeof e.blobs[0]!=="string")r.blobs=e.blobs.map((n)=>St(n));else r.blobs=e.blobs;if(typeof e.data<"u")r.data=e.data;if(e.account)r.from=e.account.address;if(typeof e.from<"u")r.from=e.from;if(typeof e.gas<"u")r.gas=Z(e.gas);if(typeof e.gasPrice<"u")r.gasPrice=Z(e.gasPrice);if(typeof e.maxFeePerBlobGas<"u")r.maxFeePerBlobGas=Z(e.maxFeePerBlobGas);if(typeof e.maxFeePerGas<"u")r.maxFeePerGas=Z(e.maxFeePerGas);if(typeof e.maxPriorityFeePerGas<"u")r.maxPriorityFeePerGas=Z(e.maxPriorityFeePerGas);if(typeof e.nonce<"u")r.nonce=Z(e.nonce);if(typeof e.to<"u")r.to=e.to;if(typeof e.type<"u")r.type=Cle[e.type];if(typeof e.value<"u")r.value=Z(e.value);return r}function Ole(e){return e.map((t)=>({address:t.address,r:t.r?Z(BigInt(t.r)):t.r,s:t.s?Z(BigInt(t.s)):t.s,chainId:Z(t.chainId),nonce:Z(t.nonce),...typeof t.yParity<"u"?{yParity:Z(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:Z(t.v)}:{}}))}var Cle;var qs=K(()=>{Ke();Cle={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"}});function Hd(){let e=()=>{return},t=()=>{return};return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function Gd({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:o}){let i=async()=>{let d=c();s();let f=d.map(({args:h})=>h);if(f.length===0)return;e(f).then((h)=>{if(o&&Array.isArray(h))h.sort(o);for(let g=0;g<d.length;g++){let{resolve:x}=d[g];x?.([h[g],h])}}).catch((h)=>{for(let g=0;g<d.length;g++){let{reject:x}=d[g];x?.(h)}})},s=()=>WP.delete(t),a=()=>c().map(({args:d})=>d),c=()=>WP.get(t)||[],l=(d)=>WP.set(t,[...c(),d]);return{flush:s,async schedule(d){let{promise:f,resolve:h,reject:g}=Hd();if(r?.([...a(),d]))i();if(c().length>0)return l({args:d,resolve:h,reject:g}),f;return l({args:d,resolve:h,reject:g}),setTimeout(i,n),f}}}var WP;var jb=K(()=>{WP=new Map});function a9(e){if(!e||e.length===0)return;return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new eb({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new eb({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function Mle(e){let{balance:t,nonce:r,state:n,stateDiff:o,code:i}=e,s={};if(i!==void 0)s.code=i;if(t!==void 0)s.balance=Z(t);if(r!==void 0)s.nonce=Z(r);if(n!==void 0)s.state=a9(n);if(o!==void 0){if(s.state)throw new yP;s.stateDiff=a9(o)}return s}function Vd(e){if(!e)return;let t={};for(let{address:r,...n}of e){if(!_t(r,{strict:!1}))throw new Qt({address:r});if(t[r])throw new gP({address:r});t[r]=Mle(n)}return t}var qb=K(()=>{Ri();tb();bP();Qn();Ke()});var S2e,_2e,T2e,v2e,E2e,P2e,A2e,I2e,k2e,R2e,C2e,O2e,M2e,N2e,$2e,z2e,L2e,B2e,D2e,F2e,U2e,j2e,q2e,H2e,G2e,V2e,Z2e,W2e,K2e,Y2e,J2e,Q2e,X2e,e6e,t6e,r6e,n6e,o6e,i6e,s6e,a6e,c6e,u6e,l6e,d6e,p6e,f6e,m6e,h6e,g6e,y6e,b6e,x6e,w6e,S6e,_6e,T6e,v6e,E6e,P6e,A6e,I6e,k6e,R6e,C6e,O6e,M6e,N6e,$6e,z6e,L6e,B6e,D6e,F6e,U6e,j6e,q6e,H6e,G6e,V6e,Z6e,W6e,K6e,Y6e,J6e,Q6e,X6e,eCe,tCe,rCe,nCe,oCe,iCe,sCe,aCe,Zd;var KP=K(()=>{S2e=2n**(8n-1n)-1n,_2e=2n**(16n-1n)-1n,T2e=2n**(24n-1n)-1n,v2e=2n**(32n-1n)-1n,E2e=2n**(40n-1n)-1n,P2e=2n**(48n-1n)-1n,A2e=2n**(56n-1n)-1n,I2e=2n**(64n-1n)-1n,k2e=2n**(72n-1n)-1n,R2e=2n**(80n-1n)-1n,C2e=2n**(88n-1n)-1n,O2e=2n**(96n-1n)-1n,M2e=2n**(104n-1n)-1n,N2e=2n**(112n-1n)-1n,$2e=2n**(120n-1n)-1n,z2e=2n**(128n-1n)-1n,L2e=2n**(136n-1n)-1n,B2e=2n**(144n-1n)-1n,D2e=2n**(152n-1n)-1n,F2e=2n**(160n-1n)-1n,U2e=2n**(168n-1n)-1n,j2e=2n**(176n-1n)-1n,q2e=2n**(184n-1n)-1n,H2e=2n**(192n-1n)-1n,G2e=2n**(200n-1n)-1n,V2e=2n**(208n-1n)-1n,Z2e=2n**(216n-1n)-1n,W2e=2n**(224n-1n)-1n,K2e=2n**(232n-1n)-1n,Y2e=2n**(240n-1n)-1n,J2e=2n**(248n-1n)-1n,Q2e=2n**(256n-1n)-1n,X2e=-(2n**(8n-1n)),e6e=-(2n**(16n-1n)),t6e=-(2n**(24n-1n)),r6e=-(2n**(32n-1n)),n6e=-(2n**(40n-1n)),o6e=-(2n**(48n-1n)),i6e=-(2n**(56n-1n)),s6e=-(2n**(64n-1n)),a6e=-(2n**(72n-1n)),c6e=-(2n**(80n-1n)),u6e=-(2n**(88n-1n)),l6e=-(2n**(96n-1n)),d6e=-(2n**(104n-1n)),p6e=-(2n**(112n-1n)),f6e=-(2n**(120n-1n)),m6e=-(2n**(128n-1n)),h6e=-(2n**(136n-1n)),g6e=-(2n**(144n-1n)),y6e=-(2n**(152n-1n)),b6e=-(2n**(160n-1n)),x6e=-(2n**(168n-1n)),w6e=-(2n**(176n-1n)),S6e=-(2n**(184n-1n)),_6e=-(2n**(192n-1n)),T6e=-(2n**(200n-1n)),v6e=-(2n**(208n-1n)),E6e=-(2n**(216n-1n)),P6e=-(2n**(224n-1n)),A6e=-(2n**(232n-1n)),I6e=-(2n**(240n-1n)),k6e=-(2n**(248n-1n)),R6e=-(2n**(256n-1n)),C6e=2n**8n-1n,O6e=2n**16n-1n,M6e=2n**24n-1n,N6e=2n**32n-1n,$6e=2n**40n-1n,z6e=2n**48n-1n,L6e=2n**56n-1n,B6e=2n**64n-1n,D6e=2n**72n-1n,F6e=2n**80n-1n,U6e=2n**88n-1n,j6e=2n**96n-1n,q6e=2n**104n-1n,H6e=2n**112n-1n,G6e=2n**120n-1n,V6e=2n**128n-1n,Z6e=2n**136n-1n,W6e=2n**144n-1n,K6e=2n**152n-1n,Y6e=2n**160n-1n,J6e=2n**168n-1n,Q6e=2n**176n-1n,X6e=2n**184n-1n,eCe=2n**192n-1n,tCe=2n**200n-1n,rCe=2n**208n-1n,nCe=2n**216n-1n,oCe=2n**224n-1n,iCe=2n**232n-1n,sCe=2n**240n-1n,aCe=2n**248n-1n,Zd=2n**256n-1n});function jr(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:n,to:o}=e,i=t?je(t):void 0;if(i&&!_t(i.address))throw new Qt({address:i.address});if(o&&!_t(o))throw new Qt({address:o});if(r&&r>Zd)throw new Zo({maxFeePerGas:r});if(n&&r&&n>r)throw new Us({maxFeePerGas:r,maxPriorityFeePerGas:n})}var Bi=K(()=>{KP();Ri();js();Qn()});var YP,JP,QP;var c9=K(()=>{et();YP=class YP extends N{constructor({callbackSelector:e,cause:t,data:r,extraData:n,sender:o,urls:i}){super(t.shortMessage||"An error occurred while fetching for an offchain result.",{cause:t,metaMessages:[...t.metaMessages||[],t.metaMessages?.length?"":[],"Offchain Gateway Call:",i&&[" Gateway URL(s):",...i.map((s)=>` ${yu(s)}`)],` Sender: ${o}`,` Data: ${r}`,` Callback selector: ${e}`,` Extra data: ${n}`].flat(),name:"OffchainLookupError"})}};JP=class JP extends N{constructor({result:e,url:t}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${yu(t)}`,`Response: ${at(e)}`],name:"OffchainLookupResponseMalformedError"})}};QP=class QP extends N{constructor({sender:e,to:t}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${t}`,`OffchainLookup sender address: ${e}`],name:"OffchainLookupSenderMismatchError"})}}});async function l9(e,{blockNumber:t,blockTag:r,data:n,requestOptions:o,to:i}){let{args:s}=Eb({data:n,abi:[Nle]}),[a,c,l,d,f]=s,{ccipRead:h}=e,g=h&&typeof h?.request==="function"?h.request:$le;try{if(!Ur(i,a))throw new QP({sender:a,to:i});let x=c.includes(zs)?await kP({data:l,ccipRequest:(S)=>g({...S,requestOptions:o})}):await g({data:l,requestOptions:o,sender:a,urls:c}),{data:w}=await Un(e,{blockNumber:t,blockTag:r,data:Or([d,_n([{type:"bytes"},{type:"bytes"}],[x,f])]),requestOptions:o,to:i});return w}catch(x){if(o?.signal?.aborted)throw rn(o.signal);if(Dn(x))throw x;throw new YP({callbackSelector:d,cause:x,data:n,extraData:f,sender:a,urls:c})}}async function $le({data:e,requestOptions:t,sender:r,urls:n}){let o=Error("An unknown error occurred.");for(let i=0;i<n.length;i++){if(t?.signal?.aborted)throw rn(t.signal);let s=n[i],a=s.includes("{data}")?"GET":"POST",c=a==="POST"?{data:e,sender:r}:void 0,l=a==="POST"?{"Content-Type":"application/json"}:{};try{let d=await fetch(s.replace("{sender}",r.toLowerCase()).replace("{data}",e),{body:JSON.stringify(c),headers:l,method:a,...t?.signal?{signal:t.signal}:{}}),f;if(d.headers.get("Content-Type")?.startsWith("application/json"))f=(await d.json()).data;else f=await d.text();if(!d.ok){o=new Go({body:c,details:f?.error?at(f.error):d.statusText,headers:d.headers,status:d.status,url:s});continue}if(!cr(f)){o=new JP({result:f,url:s});continue}return f}catch(d){if(t?.signal?.aborted)throw rn(t.signal);if(Dn(d))throw d;o=new Go({body:c,details:d.message,url:s})}}throw o}var u9="0x556f1830",Nle;var d9=K(()=>{sc();c9();wu();fP();ks();Fs();Vm();Nle={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]}});async function Un(e,t){let{account:r=e.account,authorizationList:n,batch:o=Boolean(e.batch?.multicall),blockHash:i,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,accessList:l,blobs:d,blockOverrides:f,code:h,data:g,factory:x,factoryData:w,gas:S,gasPrice:_,maxFeePerBlobGas:A,maxFeePerGas:T,maxPriorityFeePerGas:v,nonce:E,requestOptions:k,to:O,value:B,stateOverride:G,...M}=t,J=r?je(r):void 0;if(h&&(x||w))throw new N("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(h&&O)throw new N("Cannot provide both `code` & `to` as parameters.");let W=h&&g,he=x&&w&&O&&g,ge=W||he,j=(()=>{if(W)return m9({code:h,data:g});if(he)return Ule({data:g,factory:x,factoryData:w,to:O});return g})();try{jr(t);let se=ro({blockHash:i,blockNumber:s,blockTag:a,requireCanonical:c}),Se=f?Bb(f):void 0,D=Vd(G),q=e.chain?.formatters?.transactionRequest?.format,ke=(q||un)({...Eo(M,{format:q}),accessList:l,account:J,authorizationList:n,blobs:d,data:j,gas:S,gasPrice:_,maxFeePerBlobGas:A,maxFeePerGas:T,maxPriorityFeePerGas:v,nonce:E,to:ge?void 0:O,value:B},"call");if(o&&zle({request:ke})&&!Se&&i===void 0)try{let{deployless:Ce=!1}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},Oe=f9(e,{blockNumber:s,deployless:Ce});if(!Oe||!Fle(D,Oe))return await Dle(e,{...ke,blockHash:i,blockNumber:s,blockTag:a,multicallAddress:Oe,requestOptions:k,requireCanonical:c,rpcStateOverride:D})}catch(Ce){if(!(Ce instanceof _b)&&!(Ce instanceof dd))throw Ce}let ne=(()=>{let Ce=[ke,se];if(D&&Se)return[...Ce,D,Se];if(D)return[...Ce,D];if(Se)return[...Ce,{},Se];return Ce})(),Le=await e.request({method:"eth_call",params:ne},k);if(Le==="0x")return{data:void 0};return{data:Le}}catch(se){if(k?.signal?.aborted)throw rn(k.signal);if(Dn(se))throw se;let Se=jle(se);await Promise.resolve().then(() => d9());if(e.ccipRead!==!1&&Se?.slice(0,10)===u9&&O)return{data:await l9(e,{data:Se,requestOptions:k,to:O})};if(ge&&Se?.slice(0,10)==="0x101bb98d")throw new EP({factory:x});throw Ub(se,{...t,account:J,chain:e.chain})}}function zle({request:e}){let{data:t,to:r,...n}=e;if(!t)return!1;if(t.startsWith(o9))return!1;if(!r)return!1;if(Object.values(n).filter((o)=>typeof o<"u").length>0)return!1;return!0}function Ble(e){if(!e)return"default";let t=p9.get(e);if(t!==void 0)return t;let r=Lle++;return p9.set(e,r),r}async function Dle(e,t){let{batchSize:r=1024,deployless:n=!1,wait:o=0}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},{blockHash:i,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,data:l,multicallAddress:d,requestOptions:f,rpcStateOverride:h,to:g}=t,x=d!==void 0?d:f9(e,{blockNumber:s,deployless:n}),w=ro({blockHash:i,blockNumber:s,blockTag:a,requireCanonical:c}),S=typeof w==="string"?w:JSON.stringify(w),_=h?`.${JSON.stringify(h)}`:"",{schedule:A}=Gd({id:`${e.uid}.${S}.${Ble(f)}${_}`,wait:o,shouldSplitBatch(E){return E.reduce((O,{data:B})=>O+(B.length-2),0)>r*2},fn:async(E)=>{let k=E.map((M)=>({allowFailure:!0,callData:M.data,target:M.to})),O=Dt({abi:bo,args:[k],functionName:"aggregate3"}),B={...x===null?{data:m9({code:Tu,data:O})}:{to:x,data:O}},G=await e.request({method:"eth_call",params:h?[B,w,h]:[B,w]},f);return sn({abi:bo,args:[k],functionName:"aggregate3",data:G||"0x"})}}),[{returnData:T,success:v}]=await A({data:l,to:g});if(!v)throw new Ns({data:T});if(T==="0x")return{data:void 0};return{data:T}}function f9(e,t){let{blockNumber:r,deployless:n}=t;if(n)return null;if(e.chain)return So({blockNumber:r,chain:e.chain,contract:"multicall3"});throw new _b}function Fle(e,t){if(!e)return!1;return Object.keys(e).some((r)=>Ur(r,t))}function m9(e){let{code:t,data:r}=e;return vu({abi:bb(["constructor(bytes, bytes)"]),bytecode:Db,args:[t,r]})}function Ule(e){let{data:t,factory:r,factoryData:n,to:o}=e;return vu({abi:bb(["constructor(address, bytes, address, bytes)"]),bytecode:i9,args:[o,t,r,n]})}function jle(e){if(!(e instanceof N))return;let t=e.walk();return typeof t?.data==="object"?t.data?.data:t.data}var Lle=0,p9;var sc=K(()=>{Dm();GP();en();et();Um();$s();Ms();Fb();Bn();Fs();Eu();mu();ZP();qs();jb();qb();Bi();p9=new WeakMap});var oA,iA=(e,t,r)=>new oA(e,t).update(r).digest();var I9=K(()=>{tu();oA=class oA extends fm{constructor(e,t){super();this.finished=!1,this.destroyed=!1,R4(e);let r=pm(t);if(this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),ys(o)}update(e){return Zl(this),this.iHash.update(e),this}digestInto(e){Zl(this),eu(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:r,finished:n,destroyed:o,blockLen:i,outputLen:s}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};iA.create=(e,t)=>new oA(e,t)});function k9(e){if(e.lowS!==void 0)Ei("lowS",e.lowS);if(e.prehash!==void 0)Ei("prehash",e.prehash)}function Yle(e){let t=xm(e);Ss(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw Error("invalid endo: CURVE.a must be 0");if(typeof r!=="object"||typeof r.beta!=="bigint"||typeof r.splitScalar!=="function")throw Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}function sA(e,t){return Va(iu(e,t))}function Qle(e){let t=Yle(e),{Fp:r}=t,n=_s(t.n,t.nBitLength),o=t.toBytes||((T,v,E)=>{let k=v.toAffine();return Za(Uint8Array.from([4]),r.toBytes(k.x),r.toBytes(k.y))}),i=t.fromBytes||((T)=>{let v=T.subarray(1),E=r.fromBytes(v.subarray(0,r.BYTES)),k=r.fromBytes(v.subarray(r.BYTES,2*r.BYTES));return{x:E,y:k}});function s(T){let{a:v,b:E}=t,k=r.sqr(T),O=r.mul(k,T);return r.add(r.add(O,r.mul(T,v)),E)}function a(T,v){let E=r.sqr(v),k=s(T);return r.eql(E,k)}if(!a(t.Gx,t.Gy))throw Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,aA),Jle),l=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,l)))throw Error("bad curve params: a or b");function d(T){return k0(T,qr,t.n)}function f(T){let{allowedPrivateKeyLengths:v,nByteLength:E,wrapPrivateKey:k,n:O}=t;if(v&&typeof T!=="bigint"){if(Wl(T))T=Va(T);if(typeof T!=="string"||!v.includes(T.length))throw Error("invalid private key");T=T.padStart(E*2,"0")}let B;try{B=typeof T==="bigint"?T:ws(nr("private key",T,E))}catch(G){throw Error("invalid private key, expected hex or "+E+" bytes, got "+typeof T)}if(k)B=Lt(B,O);return Yn("private key",B,qr,O),B}function h(T){if(!(T instanceof w))throw Error("ProjectivePoint expected")}let g=Yl((T,v)=>{let{px:E,py:k,pz:O}=T;if(r.eql(O,r.ONE))return{x:E,y:k};let B=T.is0();if(v==null)v=B?r.ONE:r.inv(O);let G=r.mul(E,v),M=r.mul(k,v),J=r.mul(O,v);if(B)return{x:r.ZERO,y:r.ZERO};if(!r.eql(J,r.ONE))throw Error("invZ was invalid");return{x:G,y:M}}),x=Yl((T)=>{if(T.is0()){if(t.allowInfinityPoint&&!r.is0(T.py))return;throw Error("bad point: ZERO")}let{x:v,y:E}=T.toAffine();if(!r.isValid(v)||!r.isValid(E))throw Error("bad point: x or y not FE");if(!a(v,E))throw Error("bad point: equation left != right");if(!T.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class w{constructor(T,v,E){if(T==null||!r.isValid(T))throw Error("x required");if(v==null||!r.isValid(v)||r.is0(v))throw Error("y required");if(E==null||!r.isValid(E))throw Error("z required");this.px=T,this.py=v,this.pz=E,Object.freeze(this)}static fromAffine(T){let{x:v,y:E}=T||{};if(!T||!r.isValid(v)||!r.isValid(E))throw Error("invalid affine point");if(T instanceof w)throw Error("projective point not allowed");let k=(O)=>r.eql(O,r.ZERO);if(k(v)&&k(E))return w.ZERO;return new w(v,E,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(T){let v=Jl(r,T.map((E)=>E.pz));return T.map((E,k)=>E.toAffine(v[k])).map(w.fromAffine)}static fromHex(T){let v=w.fromAffine(i(nr("pointHex",T)));return v.assertValidity(),v}static fromPrivateKey(T){return w.BASE.multiply(f(T))}static msm(T,v){return O0(w,n,T,v)}_setWindowSize(T){A.setWindowSize(this,T)}assertValidity(){x(this)}hasEvenY(){let{y:T}=this.toAffine();if(r.isOdd)return!r.isOdd(T);throw Error("Field doesn't support isOdd")}equals(T){h(T);let{px:v,py:E,pz:k}=this,{px:O,py:B,pz:G}=T,M=r.eql(r.mul(v,G),r.mul(O,k)),J=r.eql(r.mul(E,G),r.mul(B,k));return M&&J}negate(){return new w(this.px,r.neg(this.py),this.pz)}double(){let{a:T,b:v}=t,E=r.mul(v,aA),{px:k,py:O,pz:B}=this,{ZERO:G,ZERO:M,ZERO:J}=r,W=r.mul(k,k),he=r.mul(O,O),ge=r.mul(B,B),j=r.mul(k,O);return j=r.add(j,j),J=r.mul(k,B),J=r.add(J,J),G=r.mul(T,J),M=r.mul(E,ge),M=r.add(G,M),G=r.sub(he,M),M=r.add(he,M),M=r.mul(G,M),G=r.mul(j,G),J=r.mul(E,J),ge=r.mul(T,ge),j=r.sub(W,ge),j=r.mul(T,j),j=r.add(j,J),J=r.add(W,W),W=r.add(J,W),W=r.add(W,ge),W=r.mul(W,j),M=r.add(M,W),ge=r.mul(O,B),ge=r.add(ge,ge),W=r.mul(ge,j),G=r.sub(G,W),J=r.mul(ge,he),J=r.add(J,J),J=r.add(J,J),new w(G,M,J)}add(T){h(T);let{px:v,py:E,pz:k}=this,{px:O,py:B,pz:G}=T,{ZERO:M,ZERO:J,ZERO:W}=r,he=t.a,ge=r.mul(t.b,aA),j=r.mul(v,O),se=r.mul(E,B),Se=r.mul(k,G),D=r.add(v,E),q=r.add(O,B);D=r.mul(D,q),q=r.add(j,se),D=r.sub(D,q),q=r.add(v,k);let Q=r.add(O,G);return q=r.mul(q,Q),Q=r.add(j,Se),q=r.sub(q,Q),Q=r.add(E,k),M=r.add(B,G),Q=r.mul(Q,M),M=r.add(se,Se),Q=r.sub(Q,M),W=r.mul(he,q),M=r.mul(ge,Se),W=r.add(M,W),M=r.sub(se,W),W=r.add(se,W),J=r.mul(M,W),se=r.add(j,j),se=r.add(se,j),Se=r.mul(he,Se),q=r.mul(ge,q),se=r.add(se,Se),Se=r.sub(j,Se),Se=r.mul(he,Se),q=r.add(q,Se),j=r.mul(se,q),J=r.add(J,j),j=r.mul(Q,q),M=r.mul(D,M),M=r.sub(M,j),j=r.mul(D,se),W=r.mul(Q,W),W=r.add(W,j),new w(M,J,W)}subtract(T){return this.add(T.negate())}is0(){return this.equals(w.ZERO)}wNAF(T){return A.wNAFCached(this,T,w.normalizeZ)}multiplyUnsafe(T){let{endo:v,n:E}=t;Yn("scalar",T,Gs,E);let k=w.ZERO;if(T===Gs)return k;if(this.is0()||T===qr)return this;if(!v||A.hasPrecomputes(this))return A.wNAFCachedUnsafe(this,T,w.normalizeZ);let{k1neg:O,k1:B,k2neg:G,k2:M}=v.splitScalar(T),J=k,W=k,he=this;while(B>Gs||M>Gs){if(B&qr)J=J.add(he);if(M&qr)W=W.add(he);he=he.double(),B>>=qr,M>>=qr}if(O)J=J.negate();if(G)W=W.negate();return W=new w(r.mul(W.px,v.beta),W.py,W.pz),J.add(W)}multiply(T){let{endo:v,n:E}=t;Yn("scalar",T,qr,E);let k,O;if(v){let{k1neg:B,k1:G,k2neg:M,k2:J}=v.splitScalar(T),{p:W,f:he}=this.wNAF(G),{p:ge,f:j}=this.wNAF(J);W=A.constTimeNegate(B,W),ge=A.constTimeNegate(M,ge),ge=new w(r.mul(ge.px,v.beta),ge.py,ge.pz),k=W.add(ge),O=he.add(j)}else{let{p:B,f:G}=this.wNAF(T);k=B,O=G}return w.normalizeZ([k,O])[0]}multiplyAndAddUnsafe(T,v,E){let k=w.BASE,O=(G,M)=>M===Gs||M===qr||!G.equals(k)?G.multiplyUnsafe(M):G.multiply(M),B=O(this,v).add(O(T,E));return B.is0()?void 0:B}toAffine(T){return g(this,T)}isTorsionFree(){let{h:T,isTorsionFree:v}=t;if(T===qr)return!0;if(v)return v(w,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:T,clearCofactor:v}=t;if(T===qr)return this;if(v)return v(w,this);return this.multiplyUnsafe(t.h)}toRawBytes(T=!0){return Ei("isCompressed",T),this.assertValidity(),o(w,this,T)}toHex(T=!0){return Ei("isCompressed",T),Va(this.toRawBytes(T))}}w.BASE=new w(t.Gx,t.Gy,r.ONE),w.ZERO=new w(r.ZERO,r.ONE,r.ZERO);let{endo:S,nBitLength:_}=t,A=C0(w,S?Math.ceil(_/2):_);return{CURVE:t,ProjectivePoint:w,normPrivateKeyToScalar:f,weierstrassEquation:s,isWithinCurveOrder:d}}function Xle(e){let t=xm(e);return Ss(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function C9(e){let t=Xle(e),{Fp:r,n,nByteLength:o,nBitLength:i}=t,s=r.BYTES+1,a=2*r.BYTES+1;function c(j){return Lt(j,n)}function l(j){return R0(j,n)}let{ProjectivePoint:d,normPrivateKeyToScalar:f,weierstrassEquation:h,isWithinCurveOrder:g}=Qle({...t,toBytes(j,se,Se){let D=se.toAffine(),q=r.toBytes(D.x),Q=Za;if(Ei("isCompressed",Se),Se)return Q(Uint8Array.from([se.hasEvenY()?2:3]),q);else return Q(Uint8Array.from([4]),q,r.toBytes(D.y))},fromBytes(j){let se=j.length,Se=j[0],D=j.subarray(1);if(se===s&&(Se===2||Se===3)){let q=ws(D);if(!k0(q,qr,r.ORDER))throw Error("Point is not on curve");let Q=h(q),ke;try{ke=r.sqrt(Q)}catch(Ce){let Oe=Ce instanceof Error?": "+Ce.message:"";throw Error("Point is not on curve"+Oe)}let ne=(ke&qr)===qr;if((Se&1)===1!==ne)ke=r.neg(ke);return{x:q,y:ke}}else if(se===a&&Se===4){let q=r.fromBytes(D.subarray(0,r.BYTES)),Q=r.fromBytes(D.subarray(r.BYTES,2*r.BYTES));return{x:q,y:Q}}else{let q=s,Q=a;throw Error("invalid Point, expected length of "+q+", or uncompressed "+Q+", got "+se)}}});function x(j){let se=n>>qr;return j>se}function w(j){return x(j)?c(-j):j}let S=(j,se,Se)=>ws(j.slice(se,Se));class _{constructor(j,se,Se){if(Yn("r",j,qr,n),Yn("s",se,qr,n),this.r=j,this.s=se,Se!=null)this.recovery=Se;Object.freeze(this)}static fromCompact(j){let se=o;return j=nr("compactSignature",j,se*2),new _(S(j,0,se),S(j,se,2*se))}static fromDER(j){let{r:se,s:Se}=Hs.toSig(nr("DER",j));return new _(se,Se)}assertValidity(){}addRecoveryBit(j){return new _(this.r,this.s,j)}recoverPublicKey(j){let{r:se,s:Se,recovery:D}=this,q=O(nr("msgHash",j));if(D==null||![0,1,2,3].includes(D))throw Error("recovery id invalid");let Q=D===2||D===3?se+t.n:se;if(Q>=r.ORDER)throw Error("recovery id 2 or 3 invalid");let ke=(D&1)===0?"02":"03",ne=d.fromHex(ke+sA(Q,r.BYTES)),Le=l(Q),Ce=c(-q*Le),Oe=c(Se*Le),ct=d.BASE.multiplyAndAddUnsafe(ne,Ce,Oe);if(!ct)throw Error("point at infinify");return ct.assertValidity(),ct}hasHighS(){return x(this.s)}normalizeS(){return this.hasHighS()?new _(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ym(this.toDERHex())}toDERHex(){return Hs.hexFromSig(this)}toCompactRawBytes(){return ym(this.toCompactHex())}toCompactHex(){let j=o;return sA(this.r,j)+sA(this.s,j)}}let A={isValidPrivateKey(j){try{return f(j),!0}catch(se){return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let j=Dv(t.n);return uB(t.randomBytes(j),t.n)},precompute(j=8,se=d.BASE){return se._setWindowSize(j),se.multiply(BigInt(3)),se}};function T(j,se=!0){return d.fromPrivateKey(j).toRawBytes(se)}function v(j){if(typeof j==="bigint")return!1;if(j instanceof d)return!0;let Se=nr("key",j).length,D=r.BYTES,q=D+1,Q=2*D+1;if(t.allowedPrivateKeyLengths||o===q)return;else return Se===q||Se===Q}function E(j,se,Se=!0){if(v(j)===!0)throw Error("first arg must be private key");if(v(se)===!1)throw Error("second arg must be public key");return d.fromHex(se).multiply(f(j)).toRawBytes(Se)}let k=t.bits2int||function(j){if(j.length>8192)throw Error("input is too large");let se=ws(j),Se=j.length*8-i;return Se>0?se>>BigInt(Se):se},O=t.bits2int_modN||function(j){return c(k(j))},B=su(i);function G(j){return Yn("num < 2^"+i,j,Gs,B),iu(j,o)}function M(j,se,Se=J){if(["recovered","canonical"].some((Ft)=>(Ft in Se)))throw Error("sign() legacy options not supported");let{hash:D,randomBytes:q}=t,{lowS:Q,prehash:ke,extraEntropy:ne}=Se;if(Q==null)Q=!0;if(j=nr("msgHash",j),k9(Se),ke)j=nr("prehashed msgHash",D(j));let Le=O(j),Ce=f(se),Oe=[G(Ce),G(Le)];if(ne!=null&&ne!==!1){let Ft=ne===!0?q(r.BYTES):ne;Oe.push(nr("extraEntropy",Ft))}let ct=Za(...Oe),gt=Le;function yt(Ft){let Kt=k(Ft);if(!g(Kt))return;let pr=l(Kt),_r=d.BASE.multiply(Kt).toAffine(),ir=c(_r.x);if(ir===Gs)return;let At=c(pr*c(gt+ir*Ce));if(At===Gs)return;let Vr=(_r.x===ir?0:2)|Number(_r.y&qr),Vi=At;if(Q&&x(At))Vi=w(At),Vr^=1;return new _(ir,Vi,Vr)}return{seed:ct,k2sig:yt}}let J={lowS:t.lowS,prehash:!1},W={lowS:t.lowS,prehash:!1};function he(j,se,Se=J){let{seed:D,k2sig:q}=M(j,se,Se),Q=t;return tB(Q.hash.outputLen,Q.nByteLength,Q.hmac)(D,q)}d.BASE._setWindowSize(8);function ge(j,se,Se,D=W){let q=j;se=nr("msgHash",se),Se=nr("publicKey",Se);let{lowS:Q,prehash:ke,format:ne}=D;if(k9(D),"strict"in D)throw Error("options.strict was renamed to lowS");if(ne!==void 0&&ne!=="compact"&&ne!=="der")throw Error("format must be compact or der");let Le=typeof q==="string"||Wl(q),Ce=!Le&&!ne&&typeof q==="object"&&q!==null&&typeof q.r==="bigint"&&typeof q.s==="bigint";if(!Le&&!Ce)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");let Oe=void 0,ct;try{if(Ce)Oe=new _(q.r,q.s);if(Le){try{if(ne!=="compact")Oe=_.fromDER(q)}catch(Vr){if(!(Vr instanceof Hs.Err))throw Vr}if(!Oe&&ne!=="der")Oe=_.fromCompact(q)}ct=d.fromHex(Se)}catch(Vr){return!1}if(!Oe)return!1;if(Q&&Oe.hasHighS())return!1;if(ke)se=t.hash(se);let{r:gt,s:yt}=Oe,Ft=O(se),Kt=l(yt),pr=c(Ft*Kt),_r=c(gt*Kt),ir=d.BASE.multiplyAndAddUnsafe(ct,pr,_r)?.toAffine();if(!ir)return!1;return c(ir.x)===gt}return{CURVE:t,getPublicKey:T,getSharedSecret:E,sign:he,verify:ge,ProjectivePoint:d,Signature:_,utils:A}}var R9,Hs,Gs,qr,jOe,aA,Jle;var O9=K(()=>{Gv();Ql();bm();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */R9=class R9 extends Error{constructor(e=""){super(e)}};Hs={Err:R9,_tlv:{encode:(e,t)=>{let{Err:r}=Hs;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=gm(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let i=n>127?gm(o.length/2|128):"";return gm(e)+i+o+t},decode(e,t){let{Err:r}=Hs,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of l)s=s<<8|d;if(n+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(e){let{Err:t}=Hs;if(e<Gs)throw new t("integer: negative integers are not allowed");let r=gm(e);if(Number.parseInt(r[0],16)&8)r="00"+r;if(r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=Hs;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return ws(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=Hs,o=nr("signature",e),{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:d}=n.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){let{_tlv:t,_int:r}=Hs,n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),i=n+o;return t.encode(48,i)}};Gs=BigInt(0),qr=BigInt(1),jOe=BigInt(2),aA=BigInt(3),Jle=BigInt(4)});function ede(e){return{hash:e,hmac:(t,...r)=>iA(e,t,Av(...r)),randomBytes:P0}}function M9(e,t){let r=(n)=>C9({...e,...ede(n)});return{...r(t),create:r}}var N9=K(()=>{I9();tu();O9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */});function nde(e){let t=L9,r=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,d=l*l*e%t,f=or(d,r,t)*d%t,h=or(f,r,t)*d%t,g=or(h,cA,t)*l%t,x=or(g,o,t)*g%t,w=or(x,i,t)*x%t,S=or(w,a,t)*w%t,_=or(S,c,t)*S%t,A=or(_,a,t)*w%t,T=or(A,r,t)*d%t,v=or(T,s,t)*x%t,E=or(v,n,t)*l%t,k=or(E,cA,t);if(!uA.eql(uA.sqr(k),e))throw Error("Cannot find square root");return k}var L9,$9,tde,rde,cA,z9=(e,t)=>(e+t/cA)/t,uA,Vs;var ih=K(()=>{Cv();N9();Ql();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */L9=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),$9=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),tde=BigInt(0),rde=BigInt(1),cA=BigInt(2);uA=_s(L9,void 0,void 0,{sqrt:nde}),Vs=M9({a:tde,b:BigInt(7),Fp:uA,n:$9,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:(e)=>{let t=$9,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-rde*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,s=BigInt("0x100000000000000000000000000000000"),a=z9(i*e,t),c=z9(-n*e,t),l=Lt(e-a*r-c*o,t),d=Lt(-a*n-c*i,t),f=l>s,h=d>s;if(f)l=t-l;if(h)d=t-d;if(l>s||d>s)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:f,k1:l,k2neg:h,k2:d}}}},W4)});var wl={};GZ(wl,{ZodISODate:()=>x5,ZodISODateTime:()=>b5,ZodISODuration:()=>S5,ZodISOTime:()=>w5,date:()=>GT,datetime:()=>oy,duration:()=>ZT,time:()=>VT});import{webcrypto as Fhe}from"node:crypto";import yW from"node:http";import bW from"node:https";import Qu from"node:zlib";import n2,{PassThrough as o2,pipeline as Xu}from"node:stream";import{Buffer as ag}from"node:buffer";function ZZ(e){if(!/^data:/i.test(e))throw TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');e=e.replace(/\r?\n/g,"");let t=e.indexOf(",");if(t===-1||t<=4)throw TypeError("malformed data: URI");let r=e.substring(5,t).split(";"),n="",o=!1,i=r[0]||"text/plain",s=i;for(let d=1;d<r.length;d++)if(r[d]==="base64")o=!0;else if(r[d]){if(s+=`;${r[d]}`,r[d].indexOf("charset=")===0)n=r[d].substring(8)}if(!r[0]&&!n.length)s+=";charset=US-ASCII",n="US-ASCII";let a=o?"base64":"ascii",c=unescape(e.substring(t+1)),l=Buffer.from(c,a);return l.type=i,l.typeFull=s,l.charset=n,l}var ER=ZZ;Yp();Xh();import sa,{PassThrough as qR}from"node:stream";import{types as HR,deprecate as cS,promisify as cW}from"node:util";import{Buffer as so}from"node:buffer";class oa extends Error{constructor(e,t){super(e);Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}class qn extends oa{constructor(e,t,r){super(e,t);if(r)this.code=this.errno=r.code,this.erroredSysCall=r.syscall}}var eg=Symbol.toStringTag,iS=(e)=>typeof e==="object"&&typeof e.append==="function"&&typeof e.delete==="function"&&typeof e.get==="function"&&typeof e.getAll==="function"&&typeof e.has==="function"&&typeof e.set==="function"&&typeof e.sort==="function"&&e[eg]==="URLSearchParams",Qp=(e)=>e&&typeof e==="object"&&typeof e.arrayBuffer==="function"&&typeof e.type==="string"&&typeof e.stream==="function"&&typeof e.constructor==="function"&&/^(Blob|File)$/.test(e[eg]),NR=(e)=>typeof e==="object"&&(e[eg]==="AbortSignal"||e[eg]==="EventTarget"),$R=(e,t)=>{let r=new URL(t).hostname,n=new URL(e).hostname;return r===n||r.endsWith(`.${n}`)},zR=(e,t)=>{let r=new URL(t).protocol,n=new URL(e).protocol;return r===n};var uW=cW(sa.pipeline),An=Symbol("Body internals");class ts{constructor(e,{size:t=0}={}){let r=null;if(e===null)e=null;else if(iS(e))e=so.from(e.toString());else if(Qp(e));else if(so.isBuffer(e));else if(HR.isAnyArrayBuffer(e))e=so.from(e);else if(ArrayBuffer.isView(e))e=so.from(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof sa);else if(e instanceof kc)e=MR(e),r=e.type.split("=")[1];else e=so.from(String(e));let n=e;if(so.isBuffer(e))n=sa.Readable.from(e);else if(Qp(e))n=sa.Readable.from(e.stream());if(this[An]={body:e,stream:n,boundary:r,disturbed:!1,error:null},this.size=t,e instanceof sa)e.on("error",(o)=>{let i=o instanceof oa?o:new qn(`Invalid response body while trying to fetch ${this.url}: ${o.message}`,"system",o);this[An].error=i})}get body(){return this[An].stream}get bodyUsed(){return this[An].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:r}=await aS(this);return e.slice(t,t+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new kc,n=new URLSearchParams(await this.text());for(let[o,i]of n)r.append(o,i);return r}await Promise.resolve().then(() => jR());return UR(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[An].body&&this[An].body.type||"",t=await this.arrayBuffer();return new es([t],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await aS(this);return new TextDecoder().decode(e)}buffer(){return aS(this)}}ts.prototype.buffer=cS(ts.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(ts.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:cS(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});async function aS(e){if(e[An].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[An].disturbed=!0,e[An].error)throw e[An].error;let{body:t}=e;if(t===null)return so.alloc(0);if(!(t instanceof sa))return so.alloc(0);let r=[],n=0;try{for await(let o of t){if(e.size>0&&n+o.length>e.size){let i=new qn(`content size at ${e.url} over limit: ${e.size}`,"max-size");throw t.destroy(i),i}n+=o.length,r.push(o)}}catch(o){throw o instanceof oa?o:new qn(`Invalid response body while trying to fetch ${e.url}: ${o.message}`,"system",o)}if(t.readableEnded===!0||t._readableState.ended===!0)try{if(r.every((o)=>typeof o==="string"))return so.from(r.join(""));return so.concat(r,n)}catch(o){throw new qn(`Could not create Buffer from response body for ${e.url}: ${o.message}`,"system",o)}else throw new qn(`Premature close of server response while trying to fetch ${e.url}`)}var Yu=(e,t)=>{let r,n,{body:o}=e[An];if(e.bodyUsed)throw Error("cannot clone body after it is used");if(o instanceof sa&&typeof o.getBoundary!=="function")r=new qR({highWaterMark:t}),n=new qR({highWaterMark:t}),o.pipe(r),o.pipe(n),e[An].stream=r,o=n;return o},lW=cS((e)=>e.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),ng=(e,t)=>{if(e===null)return null;if(typeof e==="string")return"text/plain;charset=UTF-8";if(iS(e))return"application/x-www-form-urlencoded;charset=UTF-8";if(Qp(e))return e.type||null;if(so.isBuffer(e)||HR.isAnyArrayBuffer(e)||ArrayBuffer.isView(e))return null;if(e instanceof kc)return`multipart/form-data; boundary=${t[An].boundary}`;if(e&&typeof e.getBoundary==="function")return`multipart/form-data;boundary=${lW(e)}`;if(e instanceof sa)return null;return"text/plain;charset=UTF-8"},GR=(e)=>{let{body:t}=e[An];if(t===null)return 0;if(Qp(t))return t.size;if(so.isBuffer(t))return t.length;if(t&&typeof t.getLengthSync==="function")return t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null;return null},VR=async(e,{body:t})=>{if(t===null)e.end();else await uW(t,e)};import{types as ZR}from"node:util";import ig from"node:http";var og=typeof ig.validateHeaderName==="function"?ig.validateHeaderName:(e)=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){let t=TypeError(`Header name must be a valid HTTP token [${e}]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),t}},uS=typeof ig.validateHeaderValue==="function"?ig.validateHeaderValue:(e,t)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(t)){let r=TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(r,"code",{value:"ERR_INVALID_CHAR"}),r}};class fn extends URLSearchParams{constructor(e){let t=[];if(e instanceof fn){let r=e.raw();for(let[n,o]of Object.entries(r))t.push(...o.map((i)=>[n,i]))}else if(e==null);else if(typeof e==="object"&&!ZR.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)t.push(...Object.entries(e));else{if(typeof r!=="function")throw TypeError("Header pairs must be iterable");t=[...e].map((n)=>{if(typeof n!=="object"||ZR.isBoxedPrimitive(n))throw TypeError("Each header pair must be an iterable object");return[...n]}).map((n)=>{if(n.length!==2)throw TypeError("Each header pair must be a name/value tuple");return[...n]})}}else throw TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");t=t.length>0?t.map(([r,n])=>(og(r),uS(r,String(n)),[String(r).toLowerCase(),String(n)])):void 0;super(t);return new Proxy(this,{get(r,n,o){switch(n){case"append":case"set":return(i,s)=>(og(i),uS(i,String(s)),URLSearchParams.prototype[n].call(r,String(i).toLowerCase(),String(s)));case"delete":case"has":case"getAll":return(i)=>(og(i),URLSearchParams.prototype[n].call(r,String(i).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,n,o)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let r=t.join(", ");if(/^content-encoding$/i.test(e))r=r.toLowerCase();return r}forEach(e,t=void 0){for(let r of this.keys())Reflect.apply(e,t,[this.get(r),r,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,t)=>{let r=this.getAll(t);if(t==="host")e[t]=r[0];else e[t]=r.length>1?r:r[0];return e},{})}}Object.defineProperties(fn.prototype,["get","entries","forEach","values"].reduce((e,t)=>(e[t]={enumerable:!0},e),{}));function WR(e=[]){return new fn(e.reduce((t,r,n,o)=>{if(n%2===0)t.push(o.slice(n,n+2));return t},[]).filter(([t,r])=>{try{return og(t),uS(t,String(r)),!0}catch{return!1}}))}var dW=new Set([301,302,303,307,308]),sg=(e)=>dW.has(e);var Ro=Symbol("Response internals");class Wr extends ts{constructor(e=null,t={}){super(e,t);let r=t.status!=null?t.status:200,n=new fn(t.headers);if(e!==null&&!n.has("Content-Type")){let o=ng(e,this);if(o)n.append("Content-Type",o)}this[Ro]={type:"default",url:t.url,status:r,statusText:t.statusText||"",headers:n,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[Ro].type}get url(){return this[Ro].url||""}get status(){return this[Ro].status}get ok(){return this[Ro].status>=200&&this[Ro].status<300}get redirected(){return this[Ro].counter>0}get statusText(){return this[Ro].statusText}get headers(){return this[Ro].headers}get highWaterMark(){return this[Ro].highWaterMark}clone(){return new Wr(Yu(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,t=302){if(!sg(t))throw RangeError('Failed to execute "redirect" on "response": Invalid status code');return new Wr(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new Wr(null,{status:0,statusText:""});return e[Ro].type="error",e}static json(e=void 0,t={}){let r=JSON.stringify(e);if(r===void 0)throw TypeError("data is not JSON serializable");let n=new fn(t&&t.headers);if(!n.has("content-type"))n.set("content-type","application/json");return new Wr(r,{...t,headers:n})}get[Symbol.toStringTag](){return"Response"}}Object.defineProperties(Wr.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});import{format as mW}from"node:url";import{deprecate as hW}from"node:util";var KR=(e)=>{if(e.search)return e.search;let t=e.href.length-1,r=e.hash||(e.href[t]==="#"?"#":"");return e.href[t-r.length]==="?"?"?":""};import{isIP as pW}from"node:net";function YR(e,t=!1){if(e==null)return"no-referrer";if(e=new URL(e),/^(about|blob|data):$/.test(e.protocol))return"no-referrer";if(e.username="",e.password="",e.hash="",t)e.pathname="",e.search="";return e}var JR=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),QR="strict-origin-when-cross-origin";function XR(e){if(!JR.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function fW(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let t=e.host.replace(/(^\[)|(]$)/g,""),r=pW(t);if(r===4&&/^127\./.test(t))return!0;if(r===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(t))return!0;if(e.host==="localhost"||e.host.endsWith(".localhost"))return!1;if(e.protocol==="file:")return!0;return!1}function Ju(e){if(/^about:(blank|srcdoc)$/.test(e))return!0;if(e.protocol==="data:")return!0;if(/^(blob|filesystem):$/.test(e.protocol))return!0;return fW(e)}function e2(e,{referrerURLCallback:t,referrerOriginCallback:r}={}){if(e.referrer==="no-referrer"||e.referrerPolicy==="")return null;let n=e.referrerPolicy;if(e.referrer==="about:client")return"no-referrer";let o=e.referrer,i=YR(o),s=YR(o,!0);if(i.toString().length>4096)i=s;if(t)i=t(i);if(r)s=r(s);let a=new URL(e.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return s;case"unsafe-url":return i;case"strict-origin":if(Ju(i)&&!Ju(a))return"no-referrer";return s.toString();case"strict-origin-when-cross-origin":if(i.origin===a.origin)return i;if(Ju(i)&&!Ju(a))return"no-referrer";return s;case"same-origin":if(i.origin===a.origin)return i;return"no-referrer";case"origin-when-cross-origin":if(i.origin===a.origin)return i;return s;case"no-referrer-when-downgrade":if(Ju(i)&&!Ju(a))return"no-referrer";return i;default:throw TypeError(`Invalid referrerPolicy: ${n}`)}}function t2(e){let t=(e.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of t)if(n&&JR.has(n))r=n;return r}var Nr=Symbol("Request internals"),ef=(e)=>typeof e==="object"&&typeof e[Nr]==="object",gW=hW(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)");class rs extends ts{constructor(e,t={}){let r;if(ef(e))r=new URL(e.url);else r=new URL(e),e={};if(r.username!==""||r.password!=="")throw TypeError(`${r} is an url with embedded credentials.`);let n=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(n))n=n.toUpperCase();if(!ef(t)&&"data"in t)gW();if((t.body!=null||ef(e)&&e.body!==null)&&(n==="GET"||n==="HEAD"))throw TypeError("Request with GET/HEAD method cannot have body");let o=t.body?t.body:ef(e)&&e.body!==null?Yu(e):null;super(o,{size:t.size||e.size||0});let i=new fn(t.headers||e.headers||{});if(o!==null&&!i.has("Content-Type")){let c=ng(o,this);if(c)i.set("Content-Type",c)}let s=ef(e)?e.signal:null;if("signal"in t)s=t.signal;if(s!=null&&!NR(s))throw TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let a=t.referrer==null?e.referrer:t.referrer;if(a==="")a="no-referrer";else if(a){let c=new URL(a);a=/^about:(\/\/)?client$/.test(c)?"client":c}else a=void 0;this[Nr]={method:n,redirect:t.redirect||e.redirect||"follow",headers:i,parsedURL:r,signal:s,referrer:a},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||""}get method(){return this[Nr].method}get url(){return mW(this[Nr].parsedURL)}get headers(){return this[Nr].headers}get redirect(){return this[Nr].redirect}get signal(){return this[Nr].signal}get referrer(){if(this[Nr].referrer==="no-referrer")return"";if(this[Nr].referrer==="client")return"about:client";if(this[Nr].referrer)return this[Nr].referrer.toString();return}get referrerPolicy(){return this[Nr].referrerPolicy}set referrerPolicy(e){this[Nr].referrerPolicy=XR(e)}clone(){return new rs(this)}get[Symbol.toStringTag](){return"Request"}}Object.defineProperties(rs.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});var r2=(e)=>{let{parsedURL:t}=e[Nr],r=new fn(e[Nr].headers);if(!r.has("Accept"))r.set("Accept","*/*");let n=null;if(e.body===null&&/^(post|put)$/i.test(e.method))n="0";if(e.body!==null){let a=GR(e);if(typeof a==="number"&&!Number.isNaN(a))n=String(a)}if(n)r.set("Content-Length",n);if(e.referrerPolicy==="")e.referrerPolicy=QR;if(e.referrer&&e.referrer!=="no-referrer")e[Nr].referrer=e2(e);else e[Nr].referrer="no-referrer";if(e[Nr].referrer instanceof URL)r.set("Referer",e.referrer);if(!r.has("User-Agent"))r.set("User-Agent","node-fetch");if(e.compress&&!r.has("Accept-Encoding"))r.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=e;if(typeof o==="function")o=o(t);let i=KR(t),s={path:t.pathname+i,method:e.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:e.insecureHTTPParser,agent:o};return{parsedURL:t,options:s}};class lS extends oa{constructor(e,t="aborted"){super(e,t)}}Xh();sS();var xW=new Set(["data:","http:","https:"]);async function cg(e,t){return new Promise((r,n)=>{let o=new rs(e,t),{parsedURL:i,options:s}=r2(o);if(!xW.has(i.protocol))throw TypeError(`node-fetch cannot load ${e}. URL scheme "${i.protocol.replace(/:$/,"")}" is not supported.`);if(i.protocol==="data:"){let x=ER(o.url),w=new Wr(x,{headers:{"Content-Type":x.typeFull}});r(w);return}let a=(i.protocol==="https:"?bW:yW).request,{signal:c}=o,l=null,d=()=>{let x=new lS("The operation was aborted.");if(n(x),o.body&&o.body instanceof n2.Readable)o.body.destroy(x);if(!l||!l.body)return;l.body.emit("error",x)};if(c&&c.aborted){d();return}let f=()=>{d(),g()},h=a(i.toString(),s);if(c)c.addEventListener("abort",f);let g=()=>{if(h.abort(),c)c.removeEventListener("abort",f)};if(h.on("error",(x)=>{n(new qn(`request to ${o.url} failed, reason: ${x.message}`,"system",x)),g()}),wW(h,(x)=>{if(l&&l.body)l.body.destroy(x)}),process.version<"v14")h.on("socket",(x)=>{let w;x.prependListener("end",()=>{w=x._eventsCount}),x.prependListener("close",(S)=>{if(l&&w<x._eventsCount&&!S){let _=Error("Premature close");_.code="ERR_STREAM_PREMATURE_CLOSE",l.body.emit("error",_)}})});h.on("response",(x)=>{h.setTimeout(0);let w=WR(x.rawHeaders);if(sg(x.statusCode)){let v=w.get("Location"),E=null;try{E=v===null?null:new URL(v,o.url)}catch{if(o.redirect!=="manual"){n(new qn(`uri requested responds with an invalid redirect URL: ${v}`,"invalid-redirect")),g();return}}switch(o.redirect){case"error":n(new qn(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),g();return;case"manual":break;case"follow":{if(E===null)break;if(o.counter>=o.follow){n(new qn(`maximum redirect reached at: ${o.url}`,"max-redirect")),g();return}let k={headers:new fn(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:Yu(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!$R(o.url,E)||!zR(o.url,E))for(let B of["authorization","www-authenticate","cookie","cookie2"])k.headers.delete(B);if(x.statusCode!==303&&o.body&&t.body instanceof n2.Readable){n(new qn("Cannot follow redirect with body being a readable stream","unsupported-redirect")),g();return}if(x.statusCode===303||(x.statusCode===301||x.statusCode===302)&&o.method==="POST")k.method="GET",k.body=void 0,k.headers.delete("content-length");let O=t2(w);if(O)k.referrerPolicy=O;r(cg(new rs(E,k))),g();return}default:return n(TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}if(c)x.once("end",()=>{c.removeEventListener("abort",f)});let S=Xu(x,new o2,(v)=>{if(v)n(v)});if(process.version<"v12.10")x.on("aborted",f);let _={url:o.url,status:x.statusCode,statusText:x.statusMessage,headers:w,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},A=w.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||A===null||x.statusCode===204||x.statusCode===304){l=new Wr(S,_),r(l);return}let T={flush:Qu.Z_SYNC_FLUSH,finishFlush:Qu.Z_SYNC_FLUSH};if(A==="gzip"||A==="x-gzip"){S=Xu(S,Qu.createGunzip(T),(v)=>{if(v)n(v)}),l=new Wr(S,_),r(l);return}if(A==="deflate"||A==="x-deflate"){let v=Xu(x,new o2,(E)=>{if(E)n(E)});v.once("data",(E)=>{if((E[0]&15)===8)S=Xu(S,Qu.createInflate(),(k)=>{if(k)n(k)});else S=Xu(S,Qu.createInflateRaw(),(k)=>{if(k)n(k)});l=new Wr(S,_),r(l)}),v.once("end",()=>{if(!l)l=new Wr(S,_),r(l)});return}if(A==="br"){S=Xu(S,Qu.createBrotliDecompress(),(v)=>{if(v)n(v)}),l=new Wr(S,_),r(l);return}l=new Wr(S,_),r(l)}),VR(h,o).catch(n)})}function wW(e,t){let r=ag.from(`0\r
66
66
  \r
67
- `),n=!1,o=!1,i;e.on("response",(s)=>{let{headers:a}=s;n=a["transfer-encoding"]==="chunked"&&!a["content-length"]}),e.on("socket",(s)=>{let a=()=>{if(n&&!o){let l=Error("Premature close");l.code="ERR_STREAM_PREMATURE_CLOSE",t(l)}},c=(l)=>{if(o=ag.compare(l.slice(-5),r)===0,!o&&i)o=ag.compare(i.slice(-3),r.slice(0,3))===0&&ag.compare(l.slice(-2),r.slice(3))===0;i=l};s.prependListener("close",a),s.on("data",c),e.on("close",()=>{s.removeListener("close",a),s.removeListener("data",c)})})}var LK=pn(Q2(),1),BK=pn(xg(),1),DK=pn(rl(),1),FK=pn(gS(),1),UK=pn(bS(),1),jK=pn(vS(),1),ES=pn(vg(),1),qK=pn(o6(),1);var mt;(function(e){e.assertEqual=(o)=>{};function t(o){}e.assertIs=t;function r(o){throw Error()}e.assertNever=r,e.arrayToEnum=(o)=>{let i={};for(let s of o)i[s]=s;return i},e.getValidEnumValues=(o)=>{let i=e.objectKeys(o).filter((a)=>typeof o[o[a]]!=="number"),s={};for(let a of i)s[a]=o[a];return e.objectValues(s)},e.objectValues=(o)=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys==="function"?(o)=>Object.keys(o):(o)=>{let i=[];for(let s in o)if(Object.prototype.hasOwnProperty.call(o,s))i.push(s);return i},e.find=(o,i)=>{for(let s of o)if(i(s))return s;return},e.isInteger=typeof Number.isInteger==="function"?(o)=>Number.isInteger(o):(o)=>typeof o==="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,i=" | "){return o.map((s)=>typeof s==="string"?`'${s}'`:s).join(i)}e.joinValues=n,e.jsonStringifyReplacer=(o,i)=>{if(typeof i==="bigint")return i.toString();return i}})(mt||(mt={}));var i6;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(i6||(i6={}));var _e=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ss=(e)=>{switch(typeof e){case"undefined":return _e.undefined;case"string":return _e.string;case"number":return Number.isNaN(e)?_e.nan:_e.number;case"boolean":return _e.boolean;case"function":return _e.function;case"bigint":return _e.bigint;case"symbol":return _e.symbol;case"object":if(Array.isArray(e))return _e.array;if(e===null)return _e.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return _e.promise;if(typeof Map<"u"&&e instanceof Map)return _e.map;if(typeof Set<"u"&&e instanceof Set)return _e.set;if(typeof Date<"u"&&e instanceof Date)return _e.date;return _e.object;default:return _e.unknown}};var ce=mt.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Vn extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(r)=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(o){return o.message},r={_errors:[]},n=(o)=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)r._errors.push(t(i));else{let s=r,a=0;while(a<i.path.length){let c=i.path[a];if(a!==i.path.length-1)s[c]=s[c]||{_errors:[]};else s[c]=s[c]||{_errors:[]},s[c]._errors.push(t(i));s=s[c],a++}}};return n(this),r}static assert(e){if(!(e instanceof Vn))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,mt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t=Object.create(null),r=[];for(let n of this.issues)if(n.path.length>0){let o=n.path[0];t[o]=t[o]||[],t[o].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Vn.create=(e)=>new Vn(e);var HK=(e,t)=>{let r;switch(e.code){case ce.invalid_type:if(e.received===_e.undefined)r="Required";else r=`Expected ${e.expected}, received ${e.received}`;break;case ce.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case ce.unrecognized_keys:r=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case ce.invalid_union:r="Invalid input";break;case ce.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case ce.invalid_enum_value:r=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case ce.invalid_arguments:r="Invalid function arguments";break;case ce.invalid_return_type:r="Invalid function return type";break;case ce.invalid_date:r="Invalid date";break;case ce.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")r=`${r} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)r=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)r=`Invalid input: must end with "${e.validation.endsWith}"`;else mt.assertNever(e.validation);else if(e.validation!=="regex")r=`Invalid ${e.validation}`;else r="Invalid";break;case ce.too_small:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else r="Invalid input";break;case ce.too_big:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else r="Invalid input";break;case ce.custom:r="Invalid input";break;case ce.invalid_intersection_types:r="Intersection results could not be merged";break;case ce.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ce.not_finite:r="Number must be finite";break;default:r=t.defaultError,mt.assertNever(e)}return{message:r}},da=HK;var GK=da;function cf(){return GK}var Pg=(e)=>{let{data:t,path:r,errorMaps:n,issueData:o}=e,i=[...r,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",c=n.filter((l)=>!!l).slice().reverse();for(let l of c)a=l(s,{data:t,defaultError:a}).message;return{...o,path:i,message:a}};function we(e,t){let r=cf(),n=Pg({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===da?void 0:da].filter((o)=>!!o)});e.common.issues.push(n)}class on{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let r=[];for(let n of t){if(n.status==="aborted")return qe;if(n.status==="dirty")e.dirty();r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let n of t){let o=await n.key,i=await n.value;r.push({key:o,value:i})}return on.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:o,value:i}=n;if(o.status==="aborted")return qe;if(i.status==="aborted")return qe;if(o.status==="dirty")e.dirty();if(i.status==="dirty")e.dirty();if(o.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet))r[o.value]=i.value}return{status:e.value,value:r}}}var qe=Object.freeze({status:"aborted"}),cl=(e)=>({status:"dirty",value:e}),hn=(e)=>({status:"valid",value:e}),PS=(e)=>e.status==="aborted",AS=(e)=>e.status==="dirty",Nc=(e)=>e.status==="valid",uf=(e)=>typeof Promise<"u"&&e instanceof Promise;var Re;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(Re||(Re={}));class Oo{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var s6=(e,t)=>{if(Nc(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Vn(e.common.issues);return this._error=r,this._error}}}};function nt(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:o};return{errorMap:(s,a)=>{let{message:c}=e;if(s.code==="invalid_enum_value")return{message:c??a.defaultError};if(typeof a.data>"u")return{message:c??n??a.defaultError};if(s.code!=="invalid_type")return{message:a.defaultError};return{message:c??r??a.defaultError}},description:o}}class ut{get description(){return this._def.description}_getType(e){return ss(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ss(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new on,ctx:{common:e.parent.common,data:e.data,parsedType:ss(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(uf(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)},n=this._parseSync({data:e,path:r.path,parent:r});return s6(r,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Nc(r)?{value:r.value}:{issues:t.common.issues}}catch(r){if(r?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((r)=>Nc(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(uf(n)?n:Promise.resolve(n));return s6(r,o)}refine(e,t){let r=(n)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(n);else return t};return this._refinement((n,o)=>{let i=e(n),s=()=>o.addIssue({code:ce.custom,...r(n)});if(typeof Promise<"u"&&i instanceof Promise)return i.then((a)=>{if(!a)return s(),!1;else return!0});if(!i)return s(),!1;else return!0})}refinement(e,t){return this._refinement((r,n)=>{if(!e(r))return n.addIssue(typeof t==="function"?t(r,n):t),!1;else return!0})}_refinement(e){return new ci({schema:this,typeName:pe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return ai.create(this,this._def)}nullable(){return pa.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return si.create(this)}promise(){return fl.create(this,this._def)}or(e){return mf.create([this,e],this._def)}and(e){return hf.create(this,e,this._def)}transform(e){return new ci({...nt(this._def),schema:this,typeName:pe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new xf({...nt(this._def),innerType:this,defaultValue:t,typeName:pe.ZodDefault})}brand(){return new CS({typeName:pe.ZodBranded,type:this,...nt(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new wf({...nt(this._def),innerType:this,catchValue:t,typeName:pe.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return Ng.create(this,e)}readonly(){return Sf.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var VK=/^c[^\s-]{8,}$/i,ZK=/^[0-9a-z]+$/,WK=/^[0-9A-HJKMNP-TV-Z]{26}$/i,KK=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,YK=/^[a-z0-9_-]{21}$/i,JK=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,QK=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,XK=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,eY="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",IS,tY=/^(?:(?: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])$/,rY=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,nY=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,oY=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,iY=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,sY=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,a6="((\\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])))",aY=new RegExp(`^${a6}$`);function c6(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function cY(e){return new RegExp(`^${c6(e)}$`)}function uY(e){let t=`${a6}T${c6(e)}`,r=[];if(r.push(e.local?"Z?":"Z"),e.offset)r.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function lY(e,t){if((t==="v4"||!t)&&tY.test(e))return!0;if((t==="v6"||!t)&&nY.test(e))return!0;return!1}function dY(e,t){if(!JK.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));if(typeof o!=="object"||o===null)return!1;if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&o.alg!==t)return!1;return!0}catch{return!1}}function pY(e,t){if((t==="v4"||!t)&&rY.test(e))return!0;if((t==="v6"||!t)&&oY.test(e))return!0;return!1}class cs extends ut{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==_e.string){let o=this._getOrReturnCtx(e);return we(o,{code:ce.invalid_type,expected:_e.string,received:o.parsedType}),qe}let r=new on,n=void 0;for(let o of this._def.checks)if(o.kind==="min"){if(e.data.length<o.value)n=this._getOrReturnCtx(e,n),we(n,{code:ce.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty()}else if(o.kind==="max"){if(e.data.length>o.value)n=this._getOrReturnCtx(e,n),we(n,{code:ce.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty()}else if(o.kind==="length"){let i=e.data.length>o.value,s=e.data.length<o.value;if(i||s){if(n=this._getOrReturnCtx(e,n),i)we(n,{code:ce.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message});else if(s)we(n,{code:ce.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message});r.dirty()}}else if(o.kind==="email"){if(!XK.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"email",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="emoji"){if(!IS)IS=new RegExp(eY,"u");if(!IS.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"emoji",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="uuid"){if(!KK.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"uuid",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="nanoid"){if(!YK.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"nanoid",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cuid"){if(!VK.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"cuid",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cuid2"){if(!ZK.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"cuid2",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="ulid"){if(!WK.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"ulid",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),we(n,{validation:"url",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="regex"){if(o.regex.lastIndex=0,!o.regex.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"regex",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="trim")e.data=e.data.trim();else if(o.kind==="includes"){if(!e.data.includes(o.value,o.position))n=this._getOrReturnCtx(e,n),we(n,{code:ce.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()}else if(o.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(o.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(o.kind==="startsWith"){if(!e.data.startsWith(o.value))n=this._getOrReturnCtx(e,n),we(n,{code:ce.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()}else if(o.kind==="endsWith"){if(!e.data.endsWith(o.value))n=this._getOrReturnCtx(e,n),we(n,{code:ce.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()}else if(o.kind==="datetime"){if(!uY(o).test(e.data))n=this._getOrReturnCtx(e,n),we(n,{code:ce.invalid_string,validation:"datetime",message:o.message}),r.dirty()}else if(o.kind==="date"){if(!aY.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{code:ce.invalid_string,validation:"date",message:o.message}),r.dirty()}else if(o.kind==="time"){if(!cY(o).test(e.data))n=this._getOrReturnCtx(e,n),we(n,{code:ce.invalid_string,validation:"time",message:o.message}),r.dirty()}else if(o.kind==="duration"){if(!QK.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"duration",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="ip"){if(!lY(e.data,o.version))n=this._getOrReturnCtx(e,n),we(n,{validation:"ip",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="jwt"){if(!dY(e.data,o.alg))n=this._getOrReturnCtx(e,n),we(n,{validation:"jwt",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cidr"){if(!pY(e.data,o.version))n=this._getOrReturnCtx(e,n),we(n,{validation:"cidr",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="base64"){if(!iY.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"base64",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="base64url"){if(!sY.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"base64url",code:ce.invalid_string,message:o.message}),r.dirty()}else mt.assertNever(o);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement((n)=>e.test(n),{validation:t,code:ce.invalid_string,...Re.errToObj(r)})}_addCheck(e){return new cs({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Re.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Re.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Re.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Re.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Re.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Re.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Re.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Re.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Re.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Re.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Re.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Re.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Re.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Re.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Re.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Re.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Re.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Re.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Re.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Re.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Re.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Re.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Re.errToObj(t)})}nonempty(e){return this.min(1,Re.errToObj(e))}trim(){return new cs({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new cs({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new cs({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e)=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find((e)=>e.kind==="date")}get isTime(){return!!this._def.checks.find((e)=>e.kind==="time")}get isDuration(){return!!this._def.checks.find((e)=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find((e)=>e.kind==="email")}get isURL(){return!!this._def.checks.find((e)=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find((e)=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find((e)=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((e)=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((e)=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((e)=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find((e)=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find((e)=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find((e)=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find((e)=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find((e)=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}cs.create=(e)=>new cs({checks:[],typeName:pe.ZodString,coerce:e?.coerce??!1,...nt(e)});function fY(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return i%s/10**o}class ll extends ut{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce)e.data=Number(e.data);if(this._getType(e)!==_e.number){let o=this._getOrReturnCtx(e);return we(o,{code:ce.invalid_type,expected:_e.number,received:o.parsedType}),qe}let r=void 0,n=new on;for(let o of this._def.checks)if(o.kind==="int"){if(!mt.isInteger(e.data))r=this._getOrReturnCtx(e,r),we(r,{code:ce.invalid_type,expected:"integer",received:"float",message:o.message}),n.dirty()}else if(o.kind==="min"){if(o.inclusive?e.data<o.value:e.data<=o.value)r=this._getOrReturnCtx(e,r),we(r,{code:ce.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()}else if(o.kind==="max"){if(o.inclusive?e.data>o.value:e.data>=o.value)r=this._getOrReturnCtx(e,r),we(r,{code:ce.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()}else if(o.kind==="multipleOf"){if(fY(e.data,o.value)!==0)r=this._getOrReturnCtx(e,r),we(r,{code:ce.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()}else if(o.kind==="finite"){if(!Number.isFinite(e.data))r=this._getOrReturnCtx(e,r),we(r,{code:ce.not_finite,message:o.message}),n.dirty()}else mt.assertNever(o);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Re.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Re.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Re.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Re.toString(t))}setLimit(e,t,r,n){return new ll({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Re.toString(n)}]})}_addCheck(e){return new ll({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Re.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Re.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Re.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Re.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Re.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Re.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Re.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Re.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Re.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&mt.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;else if(r.kind==="min"){if(t===null||r.value>t)t=r.value}else if(r.kind==="max"){if(e===null||r.value<e)e=r.value}return Number.isFinite(t)&&Number.isFinite(e)}}ll.create=(e)=>new ll({checks:[],typeName:pe.ZodNumber,coerce:e?.coerce||!1,...nt(e)});class dl extends ut{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==_e.bigint)return this._getInvalidInput(e);let r=void 0,n=new on;for(let o of this._def.checks)if(o.kind==="min"){if(o.inclusive?e.data<o.value:e.data<=o.value)r=this._getOrReturnCtx(e,r),we(r,{code:ce.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()}else if(o.kind==="max"){if(o.inclusive?e.data>o.value:e.data>=o.value)r=this._getOrReturnCtx(e,r),we(r,{code:ce.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()}else if(o.kind==="multipleOf"){if(e.data%o.value!==BigInt(0))r=this._getOrReturnCtx(e,r),we(r,{code:ce.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()}else mt.assertNever(o);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return we(t,{code:ce.invalid_type,expected:_e.bigint,received:t.parsedType}),qe}gte(e,t){return this.setLimit("min",e,!0,Re.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Re.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Re.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Re.toString(t))}setLimit(e,t,r,n){return new dl({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Re.toString(n)}]})}_addCheck(e){return new dl({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Re.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Re.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Re.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Re.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Re.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}dl.create=(e)=>new dl({checks:[],typeName:pe.ZodBigInt,coerce:e?.coerce??!1,...nt(e)});class Ag extends ut{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==_e.boolean){let r=this._getOrReturnCtx(e);return we(r,{code:ce.invalid_type,expected:_e.boolean,received:r.parsedType}),qe}return hn(e.data)}}Ag.create=(e)=>new Ag({typeName:pe.ZodBoolean,coerce:e?.coerce||!1,...nt(e)});class df extends ut{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==_e.date){let o=this._getOrReturnCtx(e);return we(o,{code:ce.invalid_type,expected:_e.date,received:o.parsedType}),qe}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return we(o,{code:ce.invalid_date}),qe}let r=new on,n=void 0;for(let o of this._def.checks)if(o.kind==="min"){if(e.data.getTime()<o.value)n=this._getOrReturnCtx(e,n),we(n,{code:ce.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()}else if(o.kind==="max"){if(e.data.getTime()>o.value)n=this._getOrReturnCtx(e,n),we(n,{code:ce.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()}else mt.assertNever(o);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new df({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Re.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Re.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}}df.create=(e)=>new df({checks:[],coerce:e?.coerce||!1,typeName:pe.ZodDate,...nt(e)});class Ig extends ut{_parse(e){if(this._getType(e)!==_e.symbol){let r=this._getOrReturnCtx(e);return we(r,{code:ce.invalid_type,expected:_e.symbol,received:r.parsedType}),qe}return hn(e.data)}}Ig.create=(e)=>new Ig({typeName:pe.ZodSymbol,...nt(e)});class pf extends ut{_parse(e){if(this._getType(e)!==_e.undefined){let r=this._getOrReturnCtx(e);return we(r,{code:ce.invalid_type,expected:_e.undefined,received:r.parsedType}),qe}return hn(e.data)}}pf.create=(e)=>new pf({typeName:pe.ZodUndefined,...nt(e)});class ff extends ut{_parse(e){if(this._getType(e)!==_e.null){let r=this._getOrReturnCtx(e);return we(r,{code:ce.invalid_type,expected:_e.null,received:r.parsedType}),qe}return hn(e.data)}}ff.create=(e)=>new ff({typeName:pe.ZodNull,...nt(e)});class kg extends ut{constructor(){super(...arguments);this._any=!0}_parse(e){return hn(e.data)}}kg.create=(e)=>new kg({typeName:pe.ZodAny,...nt(e)});class $c extends ut{constructor(){super(...arguments);this._unknown=!0}_parse(e){return hn(e.data)}}$c.create=(e)=>new $c({typeName:pe.ZodUnknown,...nt(e)});class us extends ut{_parse(e){let t=this._getOrReturnCtx(e);return we(t,{code:ce.invalid_type,expected:_e.never,received:t.parsedType}),qe}}us.create=(e)=>new us({typeName:pe.ZodNever,...nt(e)});class Rg extends ut{_parse(e){if(this._getType(e)!==_e.undefined){let r=this._getOrReturnCtx(e);return we(r,{code:ce.invalid_type,expected:_e.void,received:r.parsedType}),qe}return hn(e.data)}}Rg.create=(e)=>new Rg({typeName:pe.ZodVoid,...nt(e)});class si extends ut{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==_e.array)return we(t,{code:ce.invalid_type,expected:_e.array,received:t.parsedType}),qe;if(n.exactLength!==null){let i=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;if(i||s)we(t,{code:i?ce.too_big:ce.too_small,minimum:s?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty()}if(n.minLength!==null){if(t.data.length<n.minLength.value)we(t,{code:ce.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()}if(n.maxLength!==null){if(t.data.length>n.maxLength.value)we(t,{code:ce.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()}if(t.common.async)return Promise.all([...t.data].map((i,s)=>n.type._parseAsync(new Oo(t,i,t.path,s)))).then((i)=>on.mergeArray(r,i));let o=[...t.data].map((i,s)=>n.type._parseSync(new Oo(t,i,t.path,s)));return on.mergeArray(r,o)}get element(){return this._def.type}min(e,t){return new si({...this._def,minLength:{value:e,message:Re.toString(t)}})}max(e,t){return new si({...this._def,maxLength:{value:e,message:Re.toString(t)}})}length(e,t){return new si({...this._def,exactLength:{value:e,message:Re.toString(t)}})}nonempty(e){return this.min(1,e)}}si.create=(e,t)=>new si({type:e,minLength:null,maxLength:null,exactLength:null,typeName:pe.ZodArray,...nt(t)});function ul(e){if(e instanceof fr){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=ai.create(ul(n))}return new fr({...e._def,shape:()=>t})}else if(e instanceof si)return new si({...e._def,type:ul(e.element)});else if(e instanceof ai)return ai.create(ul(e.unwrap()));else if(e instanceof pa)return pa.create(ul(e.unwrap()));else if(e instanceof ls)return ls.create(e.items.map((t)=>ul(t)));else return e}class fr extends ut{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=mt.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==_e.object){let c=this._getOrReturnCtx(e);return we(c,{code:ce.invalid_type,expected:_e.object,received:c.parsedType}),qe}let{status:r,ctx:n}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof us&&this._def.unknownKeys==="strip")){for(let c in n.data)if(!i.includes(c))s.push(c)}let a=[];for(let c of i){let l=o[c],d=n.data[c];a.push({key:{status:"valid",value:c},value:l._parse(new Oo(n,d,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof us){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of s)a.push({key:{status:"valid",value:l},value:{status:"valid",value:n.data[l]}});else if(c==="strict"){if(s.length>0)we(n,{code:ce.unrecognized_keys,keys:s}),r.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of s){let d=n.data[l];a.push({key:{status:"valid",value:l},value:c._parse(new Oo(n,d,n.path,l)),alwaysSet:l in n.data})}}if(n.common.async)return Promise.resolve().then(async()=>{let c=[];for(let l of a){let d=await l.key,f=await l.value;c.push({key:d,value:f,alwaysSet:l.alwaysSet})}return c}).then((c)=>on.mergeObjectSync(r,c));else return on.mergeObjectSync(r,a)}get shape(){return this._def.shape()}strict(e){return Re.errToObj,new fr({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let n=this._def.errorMap?.(t,r).message??r.defaultError;if(t.code==="unrecognized_keys")return{message:Re.errToObj(e).message??n};return{message:n}}}:{}})}strip(){return new fr({...this._def,unknownKeys:"strip"})}passthrough(){return new fr({...this._def,unknownKeys:"passthrough"})}extend(e){return new fr({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new fr({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:pe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new fr({...this._def,catchall:e})}pick(e){let t={};for(let r of mt.objectKeys(e))if(e[r]&&this.shape[r])t[r]=this.shape[r];return new fr({...this._def,shape:()=>t})}omit(e){let t={};for(let r of mt.objectKeys(this.shape))if(!e[r])t[r]=this.shape[r];return new fr({...this._def,shape:()=>t})}deepPartial(){return ul(this)}partial(e){let t={};for(let r of mt.objectKeys(this.shape)){let n=this.shape[r];if(e&&!e[r])t[r]=n;else t[r]=n.optional()}return new fr({...this._def,shape:()=>t})}required(e){let t={};for(let r of mt.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let o=this.shape[r];while(o instanceof ai)o=o._def.innerType;t[r]=o}return new fr({...this._def,shape:()=>t})}keyof(){return u6(mt.objectKeys(this.shape))}}fr.create=(e,t)=>new fr({shape:()=>e,unknownKeys:"strip",catchall:us.create(),typeName:pe.ZodObject,...nt(t)});fr.strictCreate=(e,t)=>new fr({shape:()=>e,unknownKeys:"strict",catchall:us.create(),typeName:pe.ZodObject,...nt(t)});fr.lazycreate=(e,t)=>new fr({shape:e,unknownKeys:"strip",catchall:us.create(),typeName:pe.ZodObject,...nt(t)});class mf extends ut{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function n(o){for(let s of o)if(s.result.status==="valid")return s.result;for(let s of o)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;let i=o.map((s)=>new Vn(s.ctx.common.issues));return we(t,{code:ce.invalid_union,unionErrors:i}),qe}if(t.common.async)return Promise.all(r.map(async(o)=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);else{let o=void 0,i=[];for(let a of r){let c={...t,common:{...t.common,issues:[]},parent:null},l=a._parseSync({data:t.data,path:t.path,parent:c});if(l.status==="valid")return l;else if(l.status==="dirty"&&!o)o={result:l,ctx:c};if(c.common.issues.length)i.push(c.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let s=i.map((a)=>new Vn(a));return we(t,{code:ce.invalid_union,unionErrors:s}),qe}}get options(){return this._def.options}}mf.create=(e,t)=>new mf({options:e,typeName:pe.ZodUnion,...nt(t)});var as=(e)=>{if(e instanceof gf)return as(e.schema);else if(e instanceof ci)return as(e.innerType());else if(e instanceof yf)return[e.value];else if(e instanceof zc)return e.options;else if(e instanceof bf)return mt.objectValues(e.enum);else if(e instanceof xf)return as(e._def.innerType);else if(e instanceof pf)return[void 0];else if(e instanceof ff)return[null];else if(e instanceof ai)return[void 0,...as(e.unwrap())];else if(e instanceof pa)return[null,...as(e.unwrap())];else if(e instanceof CS)return as(e.unwrap());else if(e instanceof Sf)return as(e.unwrap());else if(e instanceof wf)return as(e._def.innerType);else return[]};class RS extends ut{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==_e.object)return we(t,{code:ce.invalid_type,expected:_e.object,received:t.parsedType}),qe;let r=this.discriminator,n=t.data[r],o=this.optionsMap.get(n);if(!o)return we(t,{code:ce.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),qe;if(t.common.async)return o._parseAsync({data:t.data,path:t.path,parent:t});else return o._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let n=new Map;for(let o of t){let i=as(o.shape[e]);if(!i.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of i){if(n.has(s))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,o)}}return new RS({typeName:pe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...nt(r)})}}function kS(e,t){let r=ss(e),n=ss(t);if(e===t)return{valid:!0,data:e};else if(r===_e.object&&n===_e.object){let o=mt.objectKeys(t),i=mt.objectKeys(e).filter((a)=>o.indexOf(a)!==-1),s={...e,...t};for(let a of i){let c=kS(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===_e.array&&n===_e.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let i=0;i<e.length;i++){let s=e[i],a=t[i],c=kS(s,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else if(r===_e.date&&n===_e.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class hf extends ut{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(o,i)=>{if(PS(o)||PS(i))return qe;let s=kS(o.value,i.value);if(!s.valid)return we(r,{code:ce.invalid_intersection_types}),qe;if(AS(o)||AS(i))t.dirty();return{status:t.value,value:s.data}};if(r.common.async)return Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>n(o,i));else return n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}hf.create=(e,t,r)=>new hf({left:e,right:t,typeName:pe.ZodIntersection,...nt(r)});class ls extends ut{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==_e.array)return we(r,{code:ce.invalid_type,expected:_e.array,received:r.parsedType}),qe;if(r.data.length<this._def.items.length)return we(r,{code:ce.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),qe;if(!this._def.rest&&r.data.length>this._def.items.length)we(r,{code:ce.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let o=[...r.data].map((i,s)=>{let a=this._def.items[s]||this._def.rest;if(!a)return null;return a._parse(new Oo(r,i,r.path,s))}).filter((i)=>!!i);if(r.common.async)return Promise.all(o).then((i)=>on.mergeArray(t,i));else return on.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new ls({...this._def,rest:e})}}ls.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new ls({items:e,typeName:pe.ZodTuple,rest:null,...nt(t)})};class Cg extends ut{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==_e.object)return we(r,{code:ce.invalid_type,expected:_e.object,received:r.parsedType}),qe;let n=[],o=this._def.keyType,i=this._def.valueType;for(let s in r.data)n.push({key:o._parse(new Oo(r,s,r.path,s)),value:i._parse(new Oo(r,r.data[s],r.path,s)),alwaysSet:s in r.data});if(r.common.async)return on.mergeObjectAsync(t,n);else return on.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){if(t instanceof ut)return new Cg({keyType:e,valueType:t,typeName:pe.ZodRecord,...nt(r)});return new Cg({keyType:cs.create(),valueType:e,typeName:pe.ZodRecord,...nt(t)})}}class Og extends ut{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==_e.map)return we(r,{code:ce.invalid_type,expected:_e.map,received:r.parsedType}),qe;let n=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([s,a],c)=>({key:n._parse(new Oo(r,s,r.path,[c,"key"])),value:o._parse(new Oo(r,a,r.path,[c,"value"]))}));if(r.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let a of i){let c=await a.key,l=await a.value;if(c.status==="aborted"||l.status==="aborted")return qe;if(c.status==="dirty"||l.status==="dirty")t.dirty();s.set(c.value,l.value)}return{status:t.value,value:s}})}else{let s=new Map;for(let a of i){let{key:c,value:l}=a;if(c.status==="aborted"||l.status==="aborted")return qe;if(c.status==="dirty"||l.status==="dirty")t.dirty();s.set(c.value,l.value)}return{status:t.value,value:s}}}}Og.create=(e,t,r)=>new Og({valueType:t,keyType:e,typeName:pe.ZodMap,...nt(r)});class pl extends ut{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==_e.set)return we(r,{code:ce.invalid_type,expected:_e.set,received:r.parsedType}),qe;let n=this._def;if(n.minSize!==null){if(r.data.size<n.minSize.value)we(r,{code:ce.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()}if(n.maxSize!==null){if(r.data.size>n.maxSize.value)we(r,{code:ce.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty()}let o=this._def.valueType;function i(a){let c=new Set;for(let l of a){if(l.status==="aborted")return qe;if(l.status==="dirty")t.dirty();c.add(l.value)}return{status:t.value,value:c}}let s=[...r.data.values()].map((a,c)=>o._parse(new Oo(r,a,r.path,c)));if(r.common.async)return Promise.all(s).then((a)=>i(a));else return i(s)}min(e,t){return new pl({...this._def,minSize:{value:e,message:Re.toString(t)}})}max(e,t){return new pl({...this._def,maxSize:{value:e,message:Re.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}pl.create=(e,t)=>new pl({valueType:e,minSize:null,maxSize:null,typeName:pe.ZodSet,...nt(t)});class lf extends ut{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==_e.function)return we(t,{code:ce.invalid_type,expected:_e.function,received:t.parsedType}),qe;function r(s,a){return Pg({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,cf(),da].filter((c)=>!!c),issueData:{code:ce.invalid_arguments,argumentsError:a}})}function n(s,a){return Pg({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,cf(),da].filter((c)=>!!c),issueData:{code:ce.invalid_return_type,returnTypeError:a}})}let o={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof fl){let s=this;return hn(async function(...a){let c=new Vn([]),l=await s._def.args.parseAsync(a,o).catch((h)=>{throw c.addIssue(r(a,h)),c}),d=await Reflect.apply(i,this,l);return await s._def.returns._def.type.parseAsync(d,o).catch((h)=>{throw c.addIssue(n(d,h)),c})})}else{let s=this;return hn(function(...a){let c=s._def.args.safeParse(a,o);if(!c.success)throw new Vn([r(a,c.error)]);let l=Reflect.apply(i,this,c.data),d=s._def.returns.safeParse(l,o);if(!d.success)throw new Vn([n(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new lf({...this._def,args:ls.create(e).rest($c.create())})}returns(e){return new lf({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new lf({args:e?e:ls.create([]).rest($c.create()),returns:t||$c.create(),typeName:pe.ZodFunction,...nt(r)})}}class gf extends ut{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}gf.create=(e,t)=>new gf({getter:e,typeName:pe.ZodLazy,...nt(t)});class yf extends ut{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return we(t,{received:t.data,code:ce.invalid_literal,expected:this._def.value}),qe}return{status:"valid",value:e.data}}get value(){return this._def.value}}yf.create=(e,t)=>new yf({value:e,typeName:pe.ZodLiteral,...nt(t)});function u6(e,t){return new zc({values:e,typeName:pe.ZodEnum,...nt(t)})}class zc extends ut{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return we(t,{expected:mt.joinValues(r),received:t.parsedType,code:ce.invalid_type}),qe}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return we(t,{received:t.data,code:ce.invalid_enum_value,options:r}),qe}return hn(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return zc.create(e,{...this._def,...t})}exclude(e,t=this._def){return zc.create(this.options.filter((r)=>!e.includes(r)),{...this._def,...t})}}zc.create=u6;class bf extends ut{_parse(e){let t=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==_e.string&&r.parsedType!==_e.number){let n=mt.objectValues(t);return we(r,{expected:mt.joinValues(n),received:r.parsedType,code:ce.invalid_type}),qe}if(!this._cache)this._cache=new Set(mt.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let n=mt.objectValues(t);return we(r,{received:r.data,code:ce.invalid_enum_value,options:n}),qe}return hn(e.data)}get enum(){return this._def.values}}bf.create=(e,t)=>new bf({values:e,typeName:pe.ZodNativeEnum,...nt(t)});class fl extends ut{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==_e.promise&&t.common.async===!1)return we(t,{code:ce.invalid_type,expected:_e.promise,received:t.parsedType}),qe;let r=t.parsedType===_e.promise?t.data:Promise.resolve(t.data);return hn(r.then((n)=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}fl.create=(e,t)=>new fl({type:e,typeName:pe.ZodPromise,...nt(t)});class ci extends ut{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===pe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:(i)=>{if(we(r,i),i.fatal)t.abort();else t.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),n.type==="preprocess"){let i=n.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async(s)=>{if(t.value==="aborted")return qe;let a=await this._def.schema._parseAsync({data:s,path:r.path,parent:r});if(a.status==="aborted")return qe;if(a.status==="dirty")return cl(a.value);if(t.value==="dirty")return cl(a.value);return a});else{if(t.value==="aborted")return qe;let s=this._def.schema._parseSync({data:i,path:r.path,parent:r});if(s.status==="aborted")return qe;if(s.status==="dirty")return cl(s.value);if(t.value==="dirty")return cl(s.value);return s}}if(n.type==="refinement"){let i=(s)=>{let a=n.refinement(s,o);if(r.common.async)return Promise.resolve(a);if(a instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(s.status==="aborted")return qe;if(s.status==="dirty")t.dirty();return i(s.value),{status:t.value,value:s.value}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((s)=>{if(s.status==="aborted")return qe;if(s.status==="dirty")t.dirty();return i(s.value).then(()=>({status:t.value,value:s.value}))})}if(n.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Nc(i))return qe;let s=n.transform(i.value,o);if(s instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((i)=>{if(!Nc(i))return qe;return Promise.resolve(n.transform(i.value,o)).then((s)=>({status:t.value,value:s}))});mt.assertNever(n)}}ci.create=(e,t,r)=>new ci({schema:e,typeName:pe.ZodEffects,effect:t,...nt(r)});ci.createWithPreprocess=(e,t,r)=>new ci({schema:t,effect:{type:"preprocess",transform:e},typeName:pe.ZodEffects,...nt(r)});class ai extends ut{_parse(e){if(this._getType(e)===_e.undefined)return hn(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ai.create=(e,t)=>new ai({innerType:e,typeName:pe.ZodOptional,...nt(t)});class pa extends ut{_parse(e){if(this._getType(e)===_e.null)return hn(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pa.create=(e,t)=>new pa({innerType:e,typeName:pe.ZodNullable,...nt(t)});class xf extends ut{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;if(t.parsedType===_e.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}xf.create=(e,t)=>new xf({innerType:e,typeName:pe.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...nt(t)});class wf extends ut{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if(uf(n))return n.then((o)=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Vn(r.common.issues)},input:r.data})}));else return{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Vn(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}wf.create=(e,t)=>new wf({innerType:e,typeName:pe.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...nt(t)});class Mg extends ut{_parse(e){if(this._getType(e)!==_e.nan){let r=this._getOrReturnCtx(e);return we(r,{code:ce.invalid_type,expected:_e.nan,received:r.parsedType}),qe}return{status:"valid",value:e.data}}}Mg.create=(e)=>new Mg({typeName:pe.ZodNaN,...nt(e)});var Kye=Symbol("zod_brand");class CS extends ut{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ng extends ut{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(o.status==="aborted")return qe;if(o.status==="dirty")return t.dirty(),cl(o.value);else return this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();else{let n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(n.status==="aborted")return qe;if(n.status==="dirty")return t.dirty(),{status:"dirty",value:n.value};else return this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new Ng({in:e,out:t,typeName:pe.ZodPipeline})}}class Sf extends ut{_parse(e){let t=this._def.innerType._parse(e),r=(n)=>{if(Nc(n))n.value=Object.freeze(n.value);return n};return uf(t)?t.then((n)=>r(n)):r(t)}unwrap(){return this._def.innerType}}Sf.create=(e,t)=>new Sf({innerType:e,typeName:pe.ZodReadonly,...nt(t)});var Yye={object:fr.lazycreate},pe;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(pe||(pe={}));var Jye=cs.create,Qye=ll.create,Xye=Mg.create,e0e=dl.create,t0e=Ag.create,r0e=df.create,n0e=Ig.create,o0e=pf.create,i0e=ff.create,s0e=kg.create,a0e=$c.create,c0e=us.create,u0e=Rg.create,l0e=si.create,{create:l6,strictCreate:d0e}=fr,p0e=mf.create,f0e=RS.create,m0e=hf.create,h0e=ls.create,g0e=Cg.create,y0e=Og.create,b0e=pl.create,x0e=lf.create,w0e=gf.create,S0e=yf.create,_0e=zc.create,T0e=bf.create,v0e=fl.create,E0e=ci.create,P0e=ai.create,A0e=pa.create,I0e=ci.createWithPreprocess,k0e=Ng.create;var d6;function U(e,t,r){function n(a,c){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=s.prototype,d=Object.keys(l);for(let f=0;f<d.length;f++){let h=d[f];if(!(h in a))a[h]=l[h].bind(a)}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let d of l._zod.deferred)d();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:(a)=>{if(r?.Parent&&a instanceof r.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var C0e=Symbol("zod_brand");class ds extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class _f extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(d6=globalThis).__zod_globalConfig??(d6.__zod_globalConfig={});var ml=globalThis.__zod_globalConfig;function Zn(e){if(e)Object.assign(ml,e);return ml}function zg(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function MS(e,t="|"){return e.map((r)=>zS(r)).join(t)}function Tf(e,t){if(typeof t==="bigint")return t.toString();return t}function vf(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function Lg(e){return e===null||e===void 0}function Bg(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function f6(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-n)<o)return 0;return r-n}var p6=Symbol("evaluating");function Et(e,t,r){let n=void 0;Object.defineProperty(e,t,{get(){if(n===p6)return;if(n===void 0)n=p6,n=r();return n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Lc(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function fa(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function NS(e){return JSON.stringify(e)}function m6(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var $S="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function hl(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var h6=vf(()=>{if(ml.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Bc(e){if(hl(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(hl(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Dg(e){if(Bc(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var g6=new Set(["string","number","symbol"]);function ma(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function co(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function Ie(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function zS(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function y6(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var b6={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function x6(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=fa(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;s[a]=r.shape[a]}return Lc(this,"shape",s),s},checks:[]});return co(e,i)}function w6(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=fa(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete s[a]}return Lc(this,"shape",s),s},checks:[]});return co(e,i)}function S6(e,t){if(!Bc(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=fa(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Lc(this,"shape",i),i}});return co(e,o)}function _6(e,t){if(!Bc(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Lc(this,"shape",n),n}});return co(e,r)}function mY(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Lc(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return co(e,r)}function T6(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let s=fa(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let l in r){if(!(l in a))throw Error(`Unrecognized key: "${l}"`);if(!r[l])continue;c[l]=e?new e({type:"optional",innerType:a[l]}):a[l]}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return Lc(this,"shape",c),c},checks:[]});return co(t,s)}function v6(e,t,r){let n=fa(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw Error(`Unrecognized key: "${s}"`);if(!r[s])continue;i[s]=new e({type:"nonoptional",innerType:o[s]})}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Lc(this,"shape",i),i}});return co(t,n)}function Dc(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function E6(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function ha(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function $g(e){return typeof e==="string"?e:e?.message}function Mo(e,t,r){let n=e.message?e.message:$g(e.inst?._zod.def?.error?.(e))??$g(t?.error?.(e))??$g(r.customError?.(e))??$g(r.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;if(a.path??(a.path=[]),a.message=n,t?.reportInput)a.input=s;return a}function Fg(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function P6(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Fc(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}var A6=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Tf,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ug=U("$ZodError",A6),Ef=U("$ZodError",A6,{Parent:Error});function I6(e,t=(r)=>r.message){let r={},n=[];for(let o of e.issues)if(o.path.length>0)r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o));else n.push(t(o));return{formErrors:n,fieldErrors:r}}function k6(e,t=(r)=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,l=0;while(l<a.length){let d=a[l];if(l!==a.length-1)c[d]=c[d]||{_errors:[]};else c[d]=c[d]||{_errors:[]},c[d]._errors.push(t(s));c=c[d],l++}}}};return n(e),r}var Pf=(e)=>(t,r,n,o)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new ds;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map((c)=>Mo(c,i,Zn())));throw $S(a,o?.callee),a}return s.value},jg=Pf(Ef),Af=(e)=>async(t,r,n,o)=>{let i=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)s=await s;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map((c)=>Mo(c,i,Zn())));throw $S(a,o?.callee),a}return s.value},qg=Af(Ef),If=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new ds;return i.issues.length?{success:!1,error:new(e??Ug)(i.issues.map((s)=>Mo(s,o,Zn())))}:{success:!0,data:i.value}},Uc=If(Ef),kf=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)i=await i;return i.issues.length?{success:!1,error:new e(i.issues.map((s)=>Mo(s,o,Zn())))}:{success:!0,data:i.value}},jc=kf(Ef),R6=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Pf(e)(t,r,o)};var C6=(e)=>(t,r,n)=>Pf(e)(t,r,n);var O6=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Af(e)(t,r,o)};var M6=(e)=>async(t,r,n)=>Af(e)(t,r,n);var N6=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return If(e)(t,r,o)};var $6=(e)=>(t,r,n)=>If(e)(t,r,n);var z6=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return kf(e)(t,r,o)};var L6=(e)=>async(t,r,n)=>kf(e)(t,r,n);var B6=/^[cC][0-9a-z]{6,}$/,D6=/^[0-9a-z]+$/,F6=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,U6=/^[0-9a-vA-V]{20}$/,j6=/^[A-Za-z0-9]{27}$/,q6=/^[a-zA-Z0-9_-]{21}$/,H6=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var G6=/^([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})$/,LS=(e)=>{if(!e)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)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var V6=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var gY="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Z6(){return new RegExp(gY,"u")}var W6=/^(?:(?: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])$/,K6=/^(([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}|:))$/;var Y6=/^((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])$/,J6=/^(([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])$/,Q6=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,BS=/^[A-Za-z0-9_-]*$/;var X6=/^https?$/,e5=/^\+[1-9]\d{6,14}$/,t5="(?:(?:\\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])))",r5=new RegExp(`^${t5}$`);function n5(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function o5(e){return new RegExp(`^${n5(e)}$`)}function i5(e){let t=n5({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${t5}T(?:${n})$`)}var s5=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},a5=/^-?\d+n?$/,c5=/^-?\d+$/,DS=/^-?\d+(?:\.\d+)?$/,u5=/^(?:true|false)$/i,l5=/^null$/i;var d5=/^[^A-Z]*$/,p5=/^[^a-z]*$/;var zr=U("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),f5={number:"number",bigint:"bigint",object:"date"},FS=U("$ZodCheckLessThan",(e,t)=>{zr.init(e,t);let r=f5[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<i)if(t.inclusive)o.maximum=t.value;else o.exclusiveMaximum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),US=U("$ZodCheckGreaterThan",(e,t)=>{zr.init(e,t);let r=f5[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>i)if(t.inclusive)o.minimum=t.value;else o.exclusiveMinimum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),m5=U("$ZodCheckMultipleOf",(e,t)=>{zr.init(e,t),e._zod.onattach.push((r)=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):f6(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),h5=U("$ZodCheckNumberFormat",(e,t)=>{zr.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=b6[t.format];e._zod.onattach.push((s)=>{let a=s._zod.bag;if(a.format=t.format,a.minimum=o,a.maximum=i,r)a.pattern=c5}),e._zod.check=(s)=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}if(a<o)s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(a>i)s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var g5=U("$ZodCheckMaxLength",(e,t)=>{var r;zr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Lg(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<o)n._zod.bag.maximum=t.maximum}),e._zod.check=(n)=>{let o=n.value;if(o.length<=t.maximum)return;let s=Fg(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),y5=U("$ZodCheckMinLength",(e,t)=>{var r;zr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Lg(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>o)n._zod.bag.minimum=t.minimum}),e._zod.check=(n)=>{let o=n.value;if(o.length>=t.minimum)return;let s=Fg(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),b5=U("$ZodCheckLengthEquals",(e,t)=>{var r;zr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Lg(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=(n)=>{let o=n.value,i=o.length;if(i===t.length)return;let s=Fg(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Cf=U("$ZodCheckStringFormat",(e,t)=>{var r,n;if(zr.init(e,t),e._zod.onattach.push((o)=>{let i=o._zod.bag;if(i.format=t.format,t.pattern)i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})}),x5=U("$ZodCheckRegex",(e,t)=>{Cf.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),w5=U("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=d5),Cf.init(e,t)}),S5=U("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=p5),Cf.init(e,t)}),_5=U("$ZodCheckIncludes",(e,t)=>{zr.init(e,t);let r=ma(t.includes),n=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push((o)=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),T5=U("$ZodCheckStartsWith",(e,t)=>{zr.init(e,t);let r=new RegExp(`^${ma(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),v5=U("$ZodCheckEndsWith",(e,t)=>{zr.init(e,t);let r=new RegExp(`.*${ma(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var E5=U("$ZodCheckOverwrite",(e,t)=>{zr.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class jS{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
67
+ `),n=!1,o=!1,i;e.on("response",(s)=>{let{headers:a}=s;n=a["transfer-encoding"]==="chunked"&&!a["content-length"]}),e.on("socket",(s)=>{let a=()=>{if(n&&!o){let l=Error("Premature close");l.code="ERR_STREAM_PREMATURE_CLOSE",t(l)}},c=(l)=>{if(o=ag.compare(l.slice(-5),r)===0,!o&&i)o=ag.compare(i.slice(-3),r.slice(0,3))===0&&ag.compare(l.slice(-2),r.slice(3))===0;i=l};s.prependListener("close",a),s.on("data",c),e.on("close",()=>{s.removeListener("close",a),s.removeListener("data",c)})})}var LK=pn(Q2(),1),BK=pn(xg(),1),DK=pn(rl(),1),FK=pn(gS(),1),UK=pn(bS(),1),jK=pn(vS(),1),ES=pn(vg(),1),qK=pn(o6(),1);var mt;(function(e){e.assertEqual=(o)=>{};function t(o){}e.assertIs=t;function r(o){throw Error()}e.assertNever=r,e.arrayToEnum=(o)=>{let i={};for(let s of o)i[s]=s;return i},e.getValidEnumValues=(o)=>{let i=e.objectKeys(o).filter((a)=>typeof o[o[a]]!=="number"),s={};for(let a of i)s[a]=o[a];return e.objectValues(s)},e.objectValues=(o)=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys==="function"?(o)=>Object.keys(o):(o)=>{let i=[];for(let s in o)if(Object.prototype.hasOwnProperty.call(o,s))i.push(s);return i},e.find=(o,i)=>{for(let s of o)if(i(s))return s;return},e.isInteger=typeof Number.isInteger==="function"?(o)=>Number.isInteger(o):(o)=>typeof o==="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,i=" | "){return o.map((s)=>typeof s==="string"?`'${s}'`:s).join(i)}e.joinValues=n,e.jsonStringifyReplacer=(o,i)=>{if(typeof i==="bigint")return i.toString();return i}})(mt||(mt={}));var i6;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(i6||(i6={}));var _e=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ss=(e)=>{switch(typeof e){case"undefined":return _e.undefined;case"string":return _e.string;case"number":return Number.isNaN(e)?_e.nan:_e.number;case"boolean":return _e.boolean;case"function":return _e.function;case"bigint":return _e.bigint;case"symbol":return _e.symbol;case"object":if(Array.isArray(e))return _e.array;if(e===null)return _e.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return _e.promise;if(typeof Map<"u"&&e instanceof Map)return _e.map;if(typeof Set<"u"&&e instanceof Set)return _e.set;if(typeof Date<"u"&&e instanceof Date)return _e.date;return _e.object;default:return _e.unknown}};var ce=mt.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Vn extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(r)=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(o){return o.message},r={_errors:[]},n=(o)=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)r._errors.push(t(i));else{let s=r,a=0;while(a<i.path.length){let c=i.path[a];if(a!==i.path.length-1)s[c]=s[c]||{_errors:[]};else s[c]=s[c]||{_errors:[]},s[c]._errors.push(t(i));s=s[c],a++}}};return n(this),r}static assert(e){if(!(e instanceof Vn))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,mt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t=Object.create(null),r=[];for(let n of this.issues)if(n.path.length>0){let o=n.path[0];t[o]=t[o]||[],t[o].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Vn.create=(e)=>new Vn(e);var HK=(e,t)=>{let r;switch(e.code){case ce.invalid_type:if(e.received===_e.undefined)r="Required";else r=`Expected ${e.expected}, received ${e.received}`;break;case ce.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case ce.unrecognized_keys:r=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case ce.invalid_union:r="Invalid input";break;case ce.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case ce.invalid_enum_value:r=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case ce.invalid_arguments:r="Invalid function arguments";break;case ce.invalid_return_type:r="Invalid function return type";break;case ce.invalid_date:r="Invalid date";break;case ce.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")r=`${r} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)r=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)r=`Invalid input: must end with "${e.validation.endsWith}"`;else mt.assertNever(e.validation);else if(e.validation!=="regex")r=`Invalid ${e.validation}`;else r="Invalid";break;case ce.too_small:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else r="Invalid input";break;case ce.too_big:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else r="Invalid input";break;case ce.custom:r="Invalid input";break;case ce.invalid_intersection_types:r="Intersection results could not be merged";break;case ce.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ce.not_finite:r="Number must be finite";break;default:r=t.defaultError,mt.assertNever(e)}return{message:r}},da=HK;var GK=da;function cf(){return GK}var Pg=(e)=>{let{data:t,path:r,errorMaps:n,issueData:o}=e,i=[...r,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",c=n.filter((l)=>!!l).slice().reverse();for(let l of c)a=l(s,{data:t,defaultError:a}).message;return{...o,path:i,message:a}};function we(e,t){let r=cf(),n=Pg({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===da?void 0:da].filter((o)=>!!o)});e.common.issues.push(n)}class on{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let r=[];for(let n of t){if(n.status==="aborted")return qe;if(n.status==="dirty")e.dirty();r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let n of t){let o=await n.key,i=await n.value;r.push({key:o,value:i})}return on.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:o,value:i}=n;if(o.status==="aborted")return qe;if(i.status==="aborted")return qe;if(o.status==="dirty")e.dirty();if(i.status==="dirty")e.dirty();if(o.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet))r[o.value]=i.value}return{status:e.value,value:r}}}var qe=Object.freeze({status:"aborted"}),cl=(e)=>({status:"dirty",value:e}),hn=(e)=>({status:"valid",value:e}),PS=(e)=>e.status==="aborted",AS=(e)=>e.status==="dirty",Nc=(e)=>e.status==="valid",uf=(e)=>typeof Promise<"u"&&e instanceof Promise;var Re;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(Re||(Re={}));class Oo{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var s6=(e,t)=>{if(Nc(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Vn(e.common.issues);return this._error=r,this._error}}}};function nt(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:o};return{errorMap:(s,a)=>{let{message:c}=e;if(s.code==="invalid_enum_value")return{message:c??a.defaultError};if(typeof a.data>"u")return{message:c??n??a.defaultError};if(s.code!=="invalid_type")return{message:a.defaultError};return{message:c??r??a.defaultError}},description:o}}class ut{get description(){return this._def.description}_getType(e){return ss(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ss(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new on,ctx:{common:e.parent.common,data:e.data,parsedType:ss(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(uf(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)},n=this._parseSync({data:e,path:r.path,parent:r});return s6(r,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Nc(r)?{value:r.value}:{issues:t.common.issues}}catch(r){if(r?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((r)=>Nc(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(uf(n)?n:Promise.resolve(n));return s6(r,o)}refine(e,t){let r=(n)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(n);else return t};return this._refinement((n,o)=>{let i=e(n),s=()=>o.addIssue({code:ce.custom,...r(n)});if(typeof Promise<"u"&&i instanceof Promise)return i.then((a)=>{if(!a)return s(),!1;else return!0});if(!i)return s(),!1;else return!0})}refinement(e,t){return this._refinement((r,n)=>{if(!e(r))return n.addIssue(typeof t==="function"?t(r,n):t),!1;else return!0})}_refinement(e){return new ci({schema:this,typeName:pe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return ai.create(this,this._def)}nullable(){return pa.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return si.create(this)}promise(){return fl.create(this,this._def)}or(e){return mf.create([this,e],this._def)}and(e){return hf.create(this,e,this._def)}transform(e){return new ci({...nt(this._def),schema:this,typeName:pe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new xf({...nt(this._def),innerType:this,defaultValue:t,typeName:pe.ZodDefault})}brand(){return new CS({typeName:pe.ZodBranded,type:this,...nt(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new wf({...nt(this._def),innerType:this,catchValue:t,typeName:pe.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return Ng.create(this,e)}readonly(){return Sf.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var VK=/^c[^\s-]{8,}$/i,ZK=/^[0-9a-z]+$/,WK=/^[0-9A-HJKMNP-TV-Z]{26}$/i,KK=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,YK=/^[a-z0-9_-]{21}$/i,JK=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,QK=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,XK=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,eY="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",IS,tY=/^(?:(?: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])$/,rY=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,nY=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,oY=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,iY=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,sY=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,a6="((\\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])))",aY=new RegExp(`^${a6}$`);function c6(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function cY(e){return new RegExp(`^${c6(e)}$`)}function uY(e){let t=`${a6}T${c6(e)}`,r=[];if(r.push(e.local?"Z?":"Z"),e.offset)r.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function lY(e,t){if((t==="v4"||!t)&&tY.test(e))return!0;if((t==="v6"||!t)&&nY.test(e))return!0;return!1}function dY(e,t){if(!JK.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));if(typeof o!=="object"||o===null)return!1;if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&o.alg!==t)return!1;return!0}catch{return!1}}function pY(e,t){if((t==="v4"||!t)&&rY.test(e))return!0;if((t==="v6"||!t)&&oY.test(e))return!0;return!1}class cs extends ut{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==_e.string){let o=this._getOrReturnCtx(e);return we(o,{code:ce.invalid_type,expected:_e.string,received:o.parsedType}),qe}let r=new on,n=void 0;for(let o of this._def.checks)if(o.kind==="min"){if(e.data.length<o.value)n=this._getOrReturnCtx(e,n),we(n,{code:ce.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty()}else if(o.kind==="max"){if(e.data.length>o.value)n=this._getOrReturnCtx(e,n),we(n,{code:ce.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty()}else if(o.kind==="length"){let i=e.data.length>o.value,s=e.data.length<o.value;if(i||s){if(n=this._getOrReturnCtx(e,n),i)we(n,{code:ce.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message});else if(s)we(n,{code:ce.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message});r.dirty()}}else if(o.kind==="email"){if(!XK.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"email",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="emoji"){if(!IS)IS=new RegExp(eY,"u");if(!IS.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"emoji",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="uuid"){if(!KK.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"uuid",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="nanoid"){if(!YK.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"nanoid",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cuid"){if(!VK.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"cuid",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cuid2"){if(!ZK.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"cuid2",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="ulid"){if(!WK.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"ulid",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),we(n,{validation:"url",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="regex"){if(o.regex.lastIndex=0,!o.regex.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"regex",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="trim")e.data=e.data.trim();else if(o.kind==="includes"){if(!e.data.includes(o.value,o.position))n=this._getOrReturnCtx(e,n),we(n,{code:ce.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()}else if(o.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(o.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(o.kind==="startsWith"){if(!e.data.startsWith(o.value))n=this._getOrReturnCtx(e,n),we(n,{code:ce.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()}else if(o.kind==="endsWith"){if(!e.data.endsWith(o.value))n=this._getOrReturnCtx(e,n),we(n,{code:ce.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()}else if(o.kind==="datetime"){if(!uY(o).test(e.data))n=this._getOrReturnCtx(e,n),we(n,{code:ce.invalid_string,validation:"datetime",message:o.message}),r.dirty()}else if(o.kind==="date"){if(!aY.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{code:ce.invalid_string,validation:"date",message:o.message}),r.dirty()}else if(o.kind==="time"){if(!cY(o).test(e.data))n=this._getOrReturnCtx(e,n),we(n,{code:ce.invalid_string,validation:"time",message:o.message}),r.dirty()}else if(o.kind==="duration"){if(!QK.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"duration",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="ip"){if(!lY(e.data,o.version))n=this._getOrReturnCtx(e,n),we(n,{validation:"ip",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="jwt"){if(!dY(e.data,o.alg))n=this._getOrReturnCtx(e,n),we(n,{validation:"jwt",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cidr"){if(!pY(e.data,o.version))n=this._getOrReturnCtx(e,n),we(n,{validation:"cidr",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="base64"){if(!iY.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"base64",code:ce.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="base64url"){if(!sY.test(e.data))n=this._getOrReturnCtx(e,n),we(n,{validation:"base64url",code:ce.invalid_string,message:o.message}),r.dirty()}else mt.assertNever(o);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement((n)=>e.test(n),{validation:t,code:ce.invalid_string,...Re.errToObj(r)})}_addCheck(e){return new cs({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Re.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Re.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Re.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Re.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Re.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Re.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Re.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Re.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Re.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Re.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Re.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Re.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Re.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Re.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Re.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Re.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Re.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Re.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Re.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Re.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Re.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Re.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Re.errToObj(t)})}nonempty(e){return this.min(1,Re.errToObj(e))}trim(){return new cs({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new cs({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new cs({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e)=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find((e)=>e.kind==="date")}get isTime(){return!!this._def.checks.find((e)=>e.kind==="time")}get isDuration(){return!!this._def.checks.find((e)=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find((e)=>e.kind==="email")}get isURL(){return!!this._def.checks.find((e)=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find((e)=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find((e)=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((e)=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((e)=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((e)=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find((e)=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find((e)=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find((e)=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find((e)=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find((e)=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}cs.create=(e)=>new cs({checks:[],typeName:pe.ZodString,coerce:e?.coerce??!1,...nt(e)});function fY(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return i%s/10**o}class ll extends ut{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce)e.data=Number(e.data);if(this._getType(e)!==_e.number){let o=this._getOrReturnCtx(e);return we(o,{code:ce.invalid_type,expected:_e.number,received:o.parsedType}),qe}let r=void 0,n=new on;for(let o of this._def.checks)if(o.kind==="int"){if(!mt.isInteger(e.data))r=this._getOrReturnCtx(e,r),we(r,{code:ce.invalid_type,expected:"integer",received:"float",message:o.message}),n.dirty()}else if(o.kind==="min"){if(o.inclusive?e.data<o.value:e.data<=o.value)r=this._getOrReturnCtx(e,r),we(r,{code:ce.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()}else if(o.kind==="max"){if(o.inclusive?e.data>o.value:e.data>=o.value)r=this._getOrReturnCtx(e,r),we(r,{code:ce.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()}else if(o.kind==="multipleOf"){if(fY(e.data,o.value)!==0)r=this._getOrReturnCtx(e,r),we(r,{code:ce.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()}else if(o.kind==="finite"){if(!Number.isFinite(e.data))r=this._getOrReturnCtx(e,r),we(r,{code:ce.not_finite,message:o.message}),n.dirty()}else mt.assertNever(o);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Re.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Re.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Re.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Re.toString(t))}setLimit(e,t,r,n){return new ll({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Re.toString(n)}]})}_addCheck(e){return new ll({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Re.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Re.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Re.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Re.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Re.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Re.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Re.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Re.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Re.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&mt.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;else if(r.kind==="min"){if(t===null||r.value>t)t=r.value}else if(r.kind==="max"){if(e===null||r.value<e)e=r.value}return Number.isFinite(t)&&Number.isFinite(e)}}ll.create=(e)=>new ll({checks:[],typeName:pe.ZodNumber,coerce:e?.coerce||!1,...nt(e)});class dl extends ut{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==_e.bigint)return this._getInvalidInput(e);let r=void 0,n=new on;for(let o of this._def.checks)if(o.kind==="min"){if(o.inclusive?e.data<o.value:e.data<=o.value)r=this._getOrReturnCtx(e,r),we(r,{code:ce.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()}else if(o.kind==="max"){if(o.inclusive?e.data>o.value:e.data>=o.value)r=this._getOrReturnCtx(e,r),we(r,{code:ce.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()}else if(o.kind==="multipleOf"){if(e.data%o.value!==BigInt(0))r=this._getOrReturnCtx(e,r),we(r,{code:ce.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()}else mt.assertNever(o);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return we(t,{code:ce.invalid_type,expected:_e.bigint,received:t.parsedType}),qe}gte(e,t){return this.setLimit("min",e,!0,Re.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Re.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Re.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Re.toString(t))}setLimit(e,t,r,n){return new dl({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Re.toString(n)}]})}_addCheck(e){return new dl({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Re.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Re.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Re.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Re.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Re.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}dl.create=(e)=>new dl({checks:[],typeName:pe.ZodBigInt,coerce:e?.coerce??!1,...nt(e)});class Ag extends ut{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==_e.boolean){let r=this._getOrReturnCtx(e);return we(r,{code:ce.invalid_type,expected:_e.boolean,received:r.parsedType}),qe}return hn(e.data)}}Ag.create=(e)=>new Ag({typeName:pe.ZodBoolean,coerce:e?.coerce||!1,...nt(e)});class df extends ut{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==_e.date){let o=this._getOrReturnCtx(e);return we(o,{code:ce.invalid_type,expected:_e.date,received:o.parsedType}),qe}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return we(o,{code:ce.invalid_date}),qe}let r=new on,n=void 0;for(let o of this._def.checks)if(o.kind==="min"){if(e.data.getTime()<o.value)n=this._getOrReturnCtx(e,n),we(n,{code:ce.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()}else if(o.kind==="max"){if(e.data.getTime()>o.value)n=this._getOrReturnCtx(e,n),we(n,{code:ce.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()}else mt.assertNever(o);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new df({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Re.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Re.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}}df.create=(e)=>new df({checks:[],coerce:e?.coerce||!1,typeName:pe.ZodDate,...nt(e)});class Ig extends ut{_parse(e){if(this._getType(e)!==_e.symbol){let r=this._getOrReturnCtx(e);return we(r,{code:ce.invalid_type,expected:_e.symbol,received:r.parsedType}),qe}return hn(e.data)}}Ig.create=(e)=>new Ig({typeName:pe.ZodSymbol,...nt(e)});class pf extends ut{_parse(e){if(this._getType(e)!==_e.undefined){let r=this._getOrReturnCtx(e);return we(r,{code:ce.invalid_type,expected:_e.undefined,received:r.parsedType}),qe}return hn(e.data)}}pf.create=(e)=>new pf({typeName:pe.ZodUndefined,...nt(e)});class ff extends ut{_parse(e){if(this._getType(e)!==_e.null){let r=this._getOrReturnCtx(e);return we(r,{code:ce.invalid_type,expected:_e.null,received:r.parsedType}),qe}return hn(e.data)}}ff.create=(e)=>new ff({typeName:pe.ZodNull,...nt(e)});class kg extends ut{constructor(){super(...arguments);this._any=!0}_parse(e){return hn(e.data)}}kg.create=(e)=>new kg({typeName:pe.ZodAny,...nt(e)});class $c extends ut{constructor(){super(...arguments);this._unknown=!0}_parse(e){return hn(e.data)}}$c.create=(e)=>new $c({typeName:pe.ZodUnknown,...nt(e)});class us extends ut{_parse(e){let t=this._getOrReturnCtx(e);return we(t,{code:ce.invalid_type,expected:_e.never,received:t.parsedType}),qe}}us.create=(e)=>new us({typeName:pe.ZodNever,...nt(e)});class Rg extends ut{_parse(e){if(this._getType(e)!==_e.undefined){let r=this._getOrReturnCtx(e);return we(r,{code:ce.invalid_type,expected:_e.void,received:r.parsedType}),qe}return hn(e.data)}}Rg.create=(e)=>new Rg({typeName:pe.ZodVoid,...nt(e)});class si extends ut{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==_e.array)return we(t,{code:ce.invalid_type,expected:_e.array,received:t.parsedType}),qe;if(n.exactLength!==null){let i=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;if(i||s)we(t,{code:i?ce.too_big:ce.too_small,minimum:s?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty()}if(n.minLength!==null){if(t.data.length<n.minLength.value)we(t,{code:ce.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()}if(n.maxLength!==null){if(t.data.length>n.maxLength.value)we(t,{code:ce.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()}if(t.common.async)return Promise.all([...t.data].map((i,s)=>n.type._parseAsync(new Oo(t,i,t.path,s)))).then((i)=>on.mergeArray(r,i));let o=[...t.data].map((i,s)=>n.type._parseSync(new Oo(t,i,t.path,s)));return on.mergeArray(r,o)}get element(){return this._def.type}min(e,t){return new si({...this._def,minLength:{value:e,message:Re.toString(t)}})}max(e,t){return new si({...this._def,maxLength:{value:e,message:Re.toString(t)}})}length(e,t){return new si({...this._def,exactLength:{value:e,message:Re.toString(t)}})}nonempty(e){return this.min(1,e)}}si.create=(e,t)=>new si({type:e,minLength:null,maxLength:null,exactLength:null,typeName:pe.ZodArray,...nt(t)});function ul(e){if(e instanceof fr){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=ai.create(ul(n))}return new fr({...e._def,shape:()=>t})}else if(e instanceof si)return new si({...e._def,type:ul(e.element)});else if(e instanceof ai)return ai.create(ul(e.unwrap()));else if(e instanceof pa)return pa.create(ul(e.unwrap()));else if(e instanceof ls)return ls.create(e.items.map((t)=>ul(t)));else return e}class fr extends ut{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=mt.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==_e.object){let c=this._getOrReturnCtx(e);return we(c,{code:ce.invalid_type,expected:_e.object,received:c.parsedType}),qe}let{status:r,ctx:n}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof us&&this._def.unknownKeys==="strip")){for(let c in n.data)if(!i.includes(c))s.push(c)}let a=[];for(let c of i){let l=o[c],d=n.data[c];a.push({key:{status:"valid",value:c},value:l._parse(new Oo(n,d,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof us){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of s)a.push({key:{status:"valid",value:l},value:{status:"valid",value:n.data[l]}});else if(c==="strict"){if(s.length>0)we(n,{code:ce.unrecognized_keys,keys:s}),r.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of s){let d=n.data[l];a.push({key:{status:"valid",value:l},value:c._parse(new Oo(n,d,n.path,l)),alwaysSet:l in n.data})}}if(n.common.async)return Promise.resolve().then(async()=>{let c=[];for(let l of a){let d=await l.key,f=await l.value;c.push({key:d,value:f,alwaysSet:l.alwaysSet})}return c}).then((c)=>on.mergeObjectSync(r,c));else return on.mergeObjectSync(r,a)}get shape(){return this._def.shape()}strict(e){return Re.errToObj,new fr({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let n=this._def.errorMap?.(t,r).message??r.defaultError;if(t.code==="unrecognized_keys")return{message:Re.errToObj(e).message??n};return{message:n}}}:{}})}strip(){return new fr({...this._def,unknownKeys:"strip"})}passthrough(){return new fr({...this._def,unknownKeys:"passthrough"})}extend(e){return new fr({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new fr({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:pe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new fr({...this._def,catchall:e})}pick(e){let t={};for(let r of mt.objectKeys(e))if(e[r]&&this.shape[r])t[r]=this.shape[r];return new fr({...this._def,shape:()=>t})}omit(e){let t={};for(let r of mt.objectKeys(this.shape))if(!e[r])t[r]=this.shape[r];return new fr({...this._def,shape:()=>t})}deepPartial(){return ul(this)}partial(e){let t={};for(let r of mt.objectKeys(this.shape)){let n=this.shape[r];if(e&&!e[r])t[r]=n;else t[r]=n.optional()}return new fr({...this._def,shape:()=>t})}required(e){let t={};for(let r of mt.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let o=this.shape[r];while(o instanceof ai)o=o._def.innerType;t[r]=o}return new fr({...this._def,shape:()=>t})}keyof(){return u6(mt.objectKeys(this.shape))}}fr.create=(e,t)=>new fr({shape:()=>e,unknownKeys:"strip",catchall:us.create(),typeName:pe.ZodObject,...nt(t)});fr.strictCreate=(e,t)=>new fr({shape:()=>e,unknownKeys:"strict",catchall:us.create(),typeName:pe.ZodObject,...nt(t)});fr.lazycreate=(e,t)=>new fr({shape:e,unknownKeys:"strip",catchall:us.create(),typeName:pe.ZodObject,...nt(t)});class mf extends ut{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function n(o){for(let s of o)if(s.result.status==="valid")return s.result;for(let s of o)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;let i=o.map((s)=>new Vn(s.ctx.common.issues));return we(t,{code:ce.invalid_union,unionErrors:i}),qe}if(t.common.async)return Promise.all(r.map(async(o)=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);else{let o=void 0,i=[];for(let a of r){let c={...t,common:{...t.common,issues:[]},parent:null},l=a._parseSync({data:t.data,path:t.path,parent:c});if(l.status==="valid")return l;else if(l.status==="dirty"&&!o)o={result:l,ctx:c};if(c.common.issues.length)i.push(c.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let s=i.map((a)=>new Vn(a));return we(t,{code:ce.invalid_union,unionErrors:s}),qe}}get options(){return this._def.options}}mf.create=(e,t)=>new mf({options:e,typeName:pe.ZodUnion,...nt(t)});var as=(e)=>{if(e instanceof gf)return as(e.schema);else if(e instanceof ci)return as(e.innerType());else if(e instanceof yf)return[e.value];else if(e instanceof zc)return e.options;else if(e instanceof bf)return mt.objectValues(e.enum);else if(e instanceof xf)return as(e._def.innerType);else if(e instanceof pf)return[void 0];else if(e instanceof ff)return[null];else if(e instanceof ai)return[void 0,...as(e.unwrap())];else if(e instanceof pa)return[null,...as(e.unwrap())];else if(e instanceof CS)return as(e.unwrap());else if(e instanceof Sf)return as(e.unwrap());else if(e instanceof wf)return as(e._def.innerType);else return[]};class RS extends ut{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==_e.object)return we(t,{code:ce.invalid_type,expected:_e.object,received:t.parsedType}),qe;let r=this.discriminator,n=t.data[r],o=this.optionsMap.get(n);if(!o)return we(t,{code:ce.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),qe;if(t.common.async)return o._parseAsync({data:t.data,path:t.path,parent:t});else return o._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let n=new Map;for(let o of t){let i=as(o.shape[e]);if(!i.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of i){if(n.has(s))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,o)}}return new RS({typeName:pe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...nt(r)})}}function kS(e,t){let r=ss(e),n=ss(t);if(e===t)return{valid:!0,data:e};else if(r===_e.object&&n===_e.object){let o=mt.objectKeys(t),i=mt.objectKeys(e).filter((a)=>o.indexOf(a)!==-1),s={...e,...t};for(let a of i){let c=kS(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===_e.array&&n===_e.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let i=0;i<e.length;i++){let s=e[i],a=t[i],c=kS(s,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else if(r===_e.date&&n===_e.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class hf extends ut{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(o,i)=>{if(PS(o)||PS(i))return qe;let s=kS(o.value,i.value);if(!s.valid)return we(r,{code:ce.invalid_intersection_types}),qe;if(AS(o)||AS(i))t.dirty();return{status:t.value,value:s.data}};if(r.common.async)return Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>n(o,i));else return n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}hf.create=(e,t,r)=>new hf({left:e,right:t,typeName:pe.ZodIntersection,...nt(r)});class ls extends ut{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==_e.array)return we(r,{code:ce.invalid_type,expected:_e.array,received:r.parsedType}),qe;if(r.data.length<this._def.items.length)return we(r,{code:ce.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),qe;if(!this._def.rest&&r.data.length>this._def.items.length)we(r,{code:ce.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let o=[...r.data].map((i,s)=>{let a=this._def.items[s]||this._def.rest;if(!a)return null;return a._parse(new Oo(r,i,r.path,s))}).filter((i)=>!!i);if(r.common.async)return Promise.all(o).then((i)=>on.mergeArray(t,i));else return on.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new ls({...this._def,rest:e})}}ls.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new ls({items:e,typeName:pe.ZodTuple,rest:null,...nt(t)})};class Cg extends ut{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==_e.object)return we(r,{code:ce.invalid_type,expected:_e.object,received:r.parsedType}),qe;let n=[],o=this._def.keyType,i=this._def.valueType;for(let s in r.data)n.push({key:o._parse(new Oo(r,s,r.path,s)),value:i._parse(new Oo(r,r.data[s],r.path,s)),alwaysSet:s in r.data});if(r.common.async)return on.mergeObjectAsync(t,n);else return on.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){if(t instanceof ut)return new Cg({keyType:e,valueType:t,typeName:pe.ZodRecord,...nt(r)});return new Cg({keyType:cs.create(),valueType:e,typeName:pe.ZodRecord,...nt(t)})}}class Og extends ut{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==_e.map)return we(r,{code:ce.invalid_type,expected:_e.map,received:r.parsedType}),qe;let n=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([s,a],c)=>({key:n._parse(new Oo(r,s,r.path,[c,"key"])),value:o._parse(new Oo(r,a,r.path,[c,"value"]))}));if(r.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let a of i){let c=await a.key,l=await a.value;if(c.status==="aborted"||l.status==="aborted")return qe;if(c.status==="dirty"||l.status==="dirty")t.dirty();s.set(c.value,l.value)}return{status:t.value,value:s}})}else{let s=new Map;for(let a of i){let{key:c,value:l}=a;if(c.status==="aborted"||l.status==="aborted")return qe;if(c.status==="dirty"||l.status==="dirty")t.dirty();s.set(c.value,l.value)}return{status:t.value,value:s}}}}Og.create=(e,t,r)=>new Og({valueType:t,keyType:e,typeName:pe.ZodMap,...nt(r)});class pl extends ut{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==_e.set)return we(r,{code:ce.invalid_type,expected:_e.set,received:r.parsedType}),qe;let n=this._def;if(n.minSize!==null){if(r.data.size<n.minSize.value)we(r,{code:ce.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()}if(n.maxSize!==null){if(r.data.size>n.maxSize.value)we(r,{code:ce.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty()}let o=this._def.valueType;function i(a){let c=new Set;for(let l of a){if(l.status==="aborted")return qe;if(l.status==="dirty")t.dirty();c.add(l.value)}return{status:t.value,value:c}}let s=[...r.data.values()].map((a,c)=>o._parse(new Oo(r,a,r.path,c)));if(r.common.async)return Promise.all(s).then((a)=>i(a));else return i(s)}min(e,t){return new pl({...this._def,minSize:{value:e,message:Re.toString(t)}})}max(e,t){return new pl({...this._def,maxSize:{value:e,message:Re.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}pl.create=(e,t)=>new pl({valueType:e,minSize:null,maxSize:null,typeName:pe.ZodSet,...nt(t)});class lf extends ut{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==_e.function)return we(t,{code:ce.invalid_type,expected:_e.function,received:t.parsedType}),qe;function r(s,a){return Pg({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,cf(),da].filter((c)=>!!c),issueData:{code:ce.invalid_arguments,argumentsError:a}})}function n(s,a){return Pg({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,cf(),da].filter((c)=>!!c),issueData:{code:ce.invalid_return_type,returnTypeError:a}})}let o={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof fl){let s=this;return hn(async function(...a){let c=new Vn([]),l=await s._def.args.parseAsync(a,o).catch((h)=>{throw c.addIssue(r(a,h)),c}),d=await Reflect.apply(i,this,l);return await s._def.returns._def.type.parseAsync(d,o).catch((h)=>{throw c.addIssue(n(d,h)),c})})}else{let s=this;return hn(function(...a){let c=s._def.args.safeParse(a,o);if(!c.success)throw new Vn([r(a,c.error)]);let l=Reflect.apply(i,this,c.data),d=s._def.returns.safeParse(l,o);if(!d.success)throw new Vn([n(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new lf({...this._def,args:ls.create(e).rest($c.create())})}returns(e){return new lf({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new lf({args:e?e:ls.create([]).rest($c.create()),returns:t||$c.create(),typeName:pe.ZodFunction,...nt(r)})}}class gf extends ut{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}gf.create=(e,t)=>new gf({getter:e,typeName:pe.ZodLazy,...nt(t)});class yf extends ut{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return we(t,{received:t.data,code:ce.invalid_literal,expected:this._def.value}),qe}return{status:"valid",value:e.data}}get value(){return this._def.value}}yf.create=(e,t)=>new yf({value:e,typeName:pe.ZodLiteral,...nt(t)});function u6(e,t){return new zc({values:e,typeName:pe.ZodEnum,...nt(t)})}class zc extends ut{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return we(t,{expected:mt.joinValues(r),received:t.parsedType,code:ce.invalid_type}),qe}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return we(t,{received:t.data,code:ce.invalid_enum_value,options:r}),qe}return hn(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return zc.create(e,{...this._def,...t})}exclude(e,t=this._def){return zc.create(this.options.filter((r)=>!e.includes(r)),{...this._def,...t})}}zc.create=u6;class bf extends ut{_parse(e){let t=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==_e.string&&r.parsedType!==_e.number){let n=mt.objectValues(t);return we(r,{expected:mt.joinValues(n),received:r.parsedType,code:ce.invalid_type}),qe}if(!this._cache)this._cache=new Set(mt.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let n=mt.objectValues(t);return we(r,{received:r.data,code:ce.invalid_enum_value,options:n}),qe}return hn(e.data)}get enum(){return this._def.values}}bf.create=(e,t)=>new bf({values:e,typeName:pe.ZodNativeEnum,...nt(t)});class fl extends ut{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==_e.promise&&t.common.async===!1)return we(t,{code:ce.invalid_type,expected:_e.promise,received:t.parsedType}),qe;let r=t.parsedType===_e.promise?t.data:Promise.resolve(t.data);return hn(r.then((n)=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}fl.create=(e,t)=>new fl({type:e,typeName:pe.ZodPromise,...nt(t)});class ci extends ut{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===pe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:(i)=>{if(we(r,i),i.fatal)t.abort();else t.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),n.type==="preprocess"){let i=n.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async(s)=>{if(t.value==="aborted")return qe;let a=await this._def.schema._parseAsync({data:s,path:r.path,parent:r});if(a.status==="aborted")return qe;if(a.status==="dirty")return cl(a.value);if(t.value==="dirty")return cl(a.value);return a});else{if(t.value==="aborted")return qe;let s=this._def.schema._parseSync({data:i,path:r.path,parent:r});if(s.status==="aborted")return qe;if(s.status==="dirty")return cl(s.value);if(t.value==="dirty")return cl(s.value);return s}}if(n.type==="refinement"){let i=(s)=>{let a=n.refinement(s,o);if(r.common.async)return Promise.resolve(a);if(a instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(s.status==="aborted")return qe;if(s.status==="dirty")t.dirty();return i(s.value),{status:t.value,value:s.value}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((s)=>{if(s.status==="aborted")return qe;if(s.status==="dirty")t.dirty();return i(s.value).then(()=>({status:t.value,value:s.value}))})}if(n.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Nc(i))return qe;let s=n.transform(i.value,o);if(s instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((i)=>{if(!Nc(i))return qe;return Promise.resolve(n.transform(i.value,o)).then((s)=>({status:t.value,value:s}))});mt.assertNever(n)}}ci.create=(e,t,r)=>new ci({schema:e,typeName:pe.ZodEffects,effect:t,...nt(r)});ci.createWithPreprocess=(e,t,r)=>new ci({schema:t,effect:{type:"preprocess",transform:e},typeName:pe.ZodEffects,...nt(r)});class ai extends ut{_parse(e){if(this._getType(e)===_e.undefined)return hn(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ai.create=(e,t)=>new ai({innerType:e,typeName:pe.ZodOptional,...nt(t)});class pa extends ut{_parse(e){if(this._getType(e)===_e.null)return hn(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pa.create=(e,t)=>new pa({innerType:e,typeName:pe.ZodNullable,...nt(t)});class xf extends ut{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;if(t.parsedType===_e.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}xf.create=(e,t)=>new xf({innerType:e,typeName:pe.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...nt(t)});class wf extends ut{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if(uf(n))return n.then((o)=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Vn(r.common.issues)},input:r.data})}));else return{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Vn(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}wf.create=(e,t)=>new wf({innerType:e,typeName:pe.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...nt(t)});class Mg extends ut{_parse(e){if(this._getType(e)!==_e.nan){let r=this._getOrReturnCtx(e);return we(r,{code:ce.invalid_type,expected:_e.nan,received:r.parsedType}),qe}return{status:"valid",value:e.data}}}Mg.create=(e)=>new Mg({typeName:pe.ZodNaN,...nt(e)});var Kye=Symbol("zod_brand");class CS extends ut{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ng extends ut{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(o.status==="aborted")return qe;if(o.status==="dirty")return t.dirty(),cl(o.value);else return this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();else{let n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(n.status==="aborted")return qe;if(n.status==="dirty")return t.dirty(),{status:"dirty",value:n.value};else return this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new Ng({in:e,out:t,typeName:pe.ZodPipeline})}}class Sf extends ut{_parse(e){let t=this._def.innerType._parse(e),r=(n)=>{if(Nc(n))n.value=Object.freeze(n.value);return n};return uf(t)?t.then((n)=>r(n)):r(t)}unwrap(){return this._def.innerType}}Sf.create=(e,t)=>new Sf({innerType:e,typeName:pe.ZodReadonly,...nt(t)});var Yye={object:fr.lazycreate},pe;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(pe||(pe={}));var Jye=cs.create,Qye=ll.create,Xye=Mg.create,e0e=dl.create,t0e=Ag.create,r0e=df.create,n0e=Ig.create,o0e=pf.create,i0e=ff.create,s0e=kg.create,a0e=$c.create,c0e=us.create,u0e=Rg.create,l0e=si.create,{create:l6,strictCreate:d0e}=fr,p0e=mf.create,f0e=RS.create,m0e=hf.create,h0e=ls.create,g0e=Cg.create,y0e=Og.create,b0e=pl.create,x0e=lf.create,w0e=gf.create,S0e=yf.create,_0e=zc.create,T0e=bf.create,v0e=fl.create,E0e=ci.create,P0e=ai.create,A0e=pa.create,I0e=ci.createWithPreprocess,k0e=Ng.create;var d6;function U(e,t,r){function n(a,c){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=s.prototype,d=Object.keys(l);for(let f=0;f<d.length;f++){let h=d[f];if(!(h in a))a[h]=l[h].bind(a)}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let d of l._zod.deferred)d();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:(a)=>{if(r?.Parent&&a instanceof r.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var C0e=Symbol("zod_brand");class ds extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class _f extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(d6=globalThis).__zod_globalConfig??(d6.__zod_globalConfig={});var ml=globalThis.__zod_globalConfig;function Zn(e){if(e)Object.assign(ml,e);return ml}function zg(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function MS(e,t="|"){return e.map((r)=>zS(r)).join(t)}function Tf(e,t){if(typeof t==="bigint")return t.toString();return t}function vf(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function Lg(e){return e===null||e===void 0}function Bg(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function f6(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-n)<o)return 0;return r-n}var p6=Symbol("evaluating");function Et(e,t,r){let n=void 0;Object.defineProperty(e,t,{get(){if(n===p6)return;if(n===void 0)n=p6,n=r();return n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Lc(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function fa(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function NS(e){return JSON.stringify(e)}function m6(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var $S="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function hl(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var h6=vf(()=>{if(ml.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Bc(e){if(hl(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(hl(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Dg(e){if(Bc(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var g6=new Set(["string","number","symbol"]);function ma(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function co(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function Ie(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function zS(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function y6(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var b6={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function x6(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=fa(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;s[a]=r.shape[a]}return Lc(this,"shape",s),s},checks:[]});return co(e,i)}function w6(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=fa(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete s[a]}return Lc(this,"shape",s),s},checks:[]});return co(e,i)}function S6(e,t){if(!Bc(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=fa(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Lc(this,"shape",i),i}});return co(e,o)}function _6(e,t){if(!Bc(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Lc(this,"shape",n),n}});return co(e,r)}function mY(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=fa(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Lc(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return co(e,r)}function T6(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let s=fa(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let l in r){if(!(l in a))throw Error(`Unrecognized key: "${l}"`);if(!r[l])continue;c[l]=e?new e({type:"optional",innerType:a[l]}):a[l]}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return Lc(this,"shape",c),c},checks:[]});return co(t,s)}function v6(e,t,r){let n=fa(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw Error(`Unrecognized key: "${s}"`);if(!r[s])continue;i[s]=new e({type:"nonoptional",innerType:o[s]})}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Lc(this,"shape",i),i}});return co(t,n)}function Dc(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function E6(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function ha(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function $g(e){return typeof e==="string"?e:e?.message}function Mo(e,t,r){let n=e.message?e.message:$g(e.inst?._zod.def?.error?.(e))??$g(t?.error?.(e))??$g(r.customError?.(e))??$g(r.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;if(a.path??(a.path=[]),a.message=n,t?.reportInput)a.input=s;return a}function Fg(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function P6(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Fc(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}var A6=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Tf,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ug=U("$ZodError",A6),Ef=U("$ZodError",A6,{Parent:Error});function I6(e,t=(r)=>r.message){let r={},n=[];for(let o of e.issues)if(o.path.length>0)r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o));else n.push(t(o));return{formErrors:n,fieldErrors:r}}function k6(e,t=(r)=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,l=0;while(l<a.length){let d=a[l];if(l!==a.length-1)c[d]=c[d]||{_errors:[]};else c[d]=c[d]||{_errors:[]},c[d]._errors.push(t(s));c=c[d],l++}}}};return n(e),r}var Pf=(e)=>(t,r,n,o)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new ds;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map((c)=>Mo(c,i,Zn())));throw $S(a,o?.callee),a}return s.value},jg=Pf(Ef),Af=(e)=>async(t,r,n,o)=>{let i=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)s=await s;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map((c)=>Mo(c,i,Zn())));throw $S(a,o?.callee),a}return s.value},qg=Af(Ef),If=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new ds;return i.issues.length?{success:!1,error:new(e??Ug)(i.issues.map((s)=>Mo(s,o,Zn())))}:{success:!0,data:i.value}},Uc=If(Ef),kf=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)i=await i;return i.issues.length?{success:!1,error:new e(i.issues.map((s)=>Mo(s,o,Zn())))}:{success:!0,data:i.value}},jc=kf(Ef),R6=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Pf(e)(t,r,o)};var C6=(e)=>(t,r,n)=>Pf(e)(t,r,n);var O6=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Af(e)(t,r,o)};var M6=(e)=>async(t,r,n)=>Af(e)(t,r,n);var N6=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return If(e)(t,r,o)};var $6=(e)=>(t,r,n)=>If(e)(t,r,n);var z6=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return kf(e)(t,r,o)};var L6=(e)=>async(t,r,n)=>kf(e)(t,r,n);var B6=/^[cC][0-9a-z]{6,}$/,D6=/^[0-9a-z]+$/,F6=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,U6=/^[0-9a-vA-V]{20}$/,j6=/^[A-Za-z0-9]{27}$/,q6=/^[a-zA-Z0-9_-]{21}$/,H6=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var G6=/^([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})$/,LS=(e)=>{if(!e)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)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var V6=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var gY="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Z6(){return new RegExp(gY,"u")}var W6=/^(?:(?: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])$/,K6=/^(([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}|:))$/;var Y6=/^((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])$/,J6=/^(([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])$/,Q6=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,BS=/^[A-Za-z0-9_-]*$/;var X6=/^https?$/,eC=/^\+[1-9]\d{6,14}$/,tC="(?:(?:\\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])))",rC=new RegExp(`^${tC}$`);function nC(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function oC(e){return new RegExp(`^${nC(e)}$`)}function iC(e){let t=nC({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${tC}T(?:${n})$`)}var sC=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},aC=/^-?\d+n?$/,cC=/^-?\d+$/,DS=/^-?\d+(?:\.\d+)?$/,uC=/^(?:true|false)$/i,lC=/^null$/i;var dC=/^[^A-Z]*$/,pC=/^[^a-z]*$/;var zr=U("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),fC={number:"number",bigint:"bigint",object:"date"},FS=U("$ZodCheckLessThan",(e,t)=>{zr.init(e,t);let r=fC[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<i)if(t.inclusive)o.maximum=t.value;else o.exclusiveMaximum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),US=U("$ZodCheckGreaterThan",(e,t)=>{zr.init(e,t);let r=fC[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>i)if(t.inclusive)o.minimum=t.value;else o.exclusiveMinimum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),mC=U("$ZodCheckMultipleOf",(e,t)=>{zr.init(e,t),e._zod.onattach.push((r)=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):f6(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),hC=U("$ZodCheckNumberFormat",(e,t)=>{zr.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=b6[t.format];e._zod.onattach.push((s)=>{let a=s._zod.bag;if(a.format=t.format,a.minimum=o,a.maximum=i,r)a.pattern=cC}),e._zod.check=(s)=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}if(a<o)s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(a>i)s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var gC=U("$ZodCheckMaxLength",(e,t)=>{var r;zr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Lg(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<o)n._zod.bag.maximum=t.maximum}),e._zod.check=(n)=>{let o=n.value;if(o.length<=t.maximum)return;let s=Fg(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),yC=U("$ZodCheckMinLength",(e,t)=>{var r;zr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Lg(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>o)n._zod.bag.minimum=t.minimum}),e._zod.check=(n)=>{let o=n.value;if(o.length>=t.minimum)return;let s=Fg(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),bC=U("$ZodCheckLengthEquals",(e,t)=>{var r;zr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Lg(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=(n)=>{let o=n.value,i=o.length;if(i===t.length)return;let s=Fg(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Cf=U("$ZodCheckStringFormat",(e,t)=>{var r,n;if(zr.init(e,t),e._zod.onattach.push((o)=>{let i=o._zod.bag;if(i.format=t.format,t.pattern)i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})}),xC=U("$ZodCheckRegex",(e,t)=>{Cf.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),wC=U("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=dC),Cf.init(e,t)}),SC=U("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=pC),Cf.init(e,t)}),_C=U("$ZodCheckIncludes",(e,t)=>{zr.init(e,t);let r=ma(t.includes),n=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push((o)=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),TC=U("$ZodCheckStartsWith",(e,t)=>{zr.init(e,t);let r=new RegExp(`^${ma(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),vC=U("$ZodCheckEndsWith",(e,t)=>{zr.init(e,t);let r=new RegExp(`.*${ma(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var EC=U("$ZodCheckOverwrite",(e,t)=>{zr.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class jS{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
68
68
  `).filter((i)=>i),n=Math.min(...r.map((i)=>i.length-i.trimStart().length)),o=r.map((i)=>i.slice(n)).map((i)=>" ".repeat(this.indent*2)+i);for(let i of o)this.content.push(i)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[""]).map((o)=>` ${o}`)];return new e(...t,n.join(`
69
- `))}}var A5={major:4,minor:4,patch:3};var Mt=U("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=A5;let n=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(s,a,c)=>{let l=Dc(s),d;for(let f of a){if(f._zod.def.when){if(E6(s))continue;if(!f._zod.def.when(s))continue}else if(l)continue;let h=s.issues.length,g=f._zod.check(s);if(g instanceof Promise&&c?.async===!1)throw new ds;if(d||g instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await g,s.issues.length===h)return;if(!l)l=Dc(s,h)});else{if(s.issues.length===h)continue;if(!l)l=Dc(s,h)}}if(d)return d.then(()=>s);return s},i=(s,a,c)=>{if(Dc(s))return s.aborted=!0,s;let l=o(a,n,c);if(l instanceof Promise){if(c.async===!1)throw new ds;return l.then((d)=>e._zod.parse(d,c))}return e._zod.parse(l,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let l=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});if(l instanceof Promise)return l.then((d)=>i(d,s,a));return i(l,s,a)}let c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new ds;return c.then((l)=>o(l,n,a))}return o(c,n,a)}}Et(e,"~standard",()=>({validate:(o)=>{try{let i=Uc(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch(i){return jc(e,o).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Of=U("$ZodString",(e,t)=>{Mt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??s5(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(o){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Zt=U("$ZodStringFormat",(e,t)=>{Cf.init(e,t),Of.init(e,t)}),HS=U("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=G6),Zt.init(e,t)}),GS=U("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=LS(n))}else t.pattern??(t.pattern=LS());Zt.init(e,t)}),VS=U("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=V6),Zt.init(e,t)}),ZS=U("$ZodURL",(e,t)=>{Zt.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===X6.source){if(!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let o=new URL(n);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(o.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})}if(t.normalize)r.value=o.href;else r.value=n;return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),WS=U("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Z6()),Zt.init(e,t)}),KS=U("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=q6),Zt.init(e,t)}),YS=U("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=B6),Zt.init(e,t)}),JS=U("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=D6),Zt.init(e,t)}),QS=U("$ZodULID",(e,t)=>{t.pattern??(t.pattern=F6),Zt.init(e,t)}),XS=U("$ZodXID",(e,t)=>{t.pattern??(t.pattern=U6),Zt.init(e,t)}),e_=U("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=j6),Zt.init(e,t)}),z5=U("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=i5(t)),Zt.init(e,t)}),L5=U("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=r5),Zt.init(e,t)}),B5=U("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=o5(t)),Zt.init(e,t)}),D5=U("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=H6),Zt.init(e,t)}),t_=U("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=W6),Zt.init(e,t),e._zod.bag.format="ipv4"}),r_=U("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=K6),Zt.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var n_=U("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Y6),Zt.init(e,t)}),o_=U("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=J6),Zt.init(e,t),e._zod.check=(r)=>{let n=r.value.split("/");try{if(n.length!==2)throw Error();let[o,i]=n;if(!i)throw Error();let s=Number(i);if(`${s}`!==i)throw Error();if(s<0||s>128)throw Error();new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function F5(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var i_=U("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Q6),Zt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(F5(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function yY(e){if(!BS.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return F5(r)}var s_=U("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=BS),Zt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(yY(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),a_=U("$ZodE164",(e,t)=>{t.pattern??(t.pattern=e5),Zt.init(e,t)});function bY(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&(!("alg"in o)||o.alg!==t))return!1;return!0}catch{return!1}}var c_=U("$ZodJWT",(e,t)=>{Zt.init(e,t),e._zod.check=(r)=>{if(bY(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Vg=U("$ZodNumber",(e,t)=>{Mt.init(e,t),e._zod.pattern=e._zod.bag.pattern??DS,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(s){}let o=r.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),u_=U("$ZodNumberFormat",(e,t)=>{h5.init(e,t),Vg.init(e,t)}),l_=U("$ZodBoolean",(e,t)=>{Mt.init(e,t),e._zod.pattern=u5,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(i){}let o=r.value;if(typeof o==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),d_=U("$ZodBigInt",(e,t)=>{Mt.init(e,t),e._zod.pattern=a5,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(o){}if(typeof r.value==="bigint")return r;return r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}});var p_=U("$ZodNull",(e,t)=>{Mt.init(e,t),e._zod.pattern=l5,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;if(o===null)return r;return r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}});var f_=U("$ZodUnknown",(e,t)=>{Mt.init(e,t),e._zod.parse=(r)=>r}),m_=U("$ZodNever",(e,t)=>{Mt.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function I5(e,t,r){if(e.issues.length)t.issues.push(...ha(r,e.issues));t.value[r]=e.value}var h_=U("$ZodArray",(e,t)=>{Mt.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},n);if(c instanceof Promise)i.push(c.then((l)=>I5(l,r,s)));else I5(c,r,s)}if(i.length)return Promise.all(i).then(()=>r);return r}});function Gg(e,t,r,n,o,i){let s=r in n;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...ha(r,e.issues))}if(!s&&!o){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(s)t.value[r]=void 0}else t.value[r]=e.value}function U5(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let r=y6(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function j5(e,t,r,n,o,i){let s=[],a=o.keySet,c=o.catchall._zod,l=c.def.type,d=c.optin==="optional",f=c.optout==="optional";for(let h in t){if(h==="__proto__")continue;if(a.has(h))continue;if(l==="never"){s.push(h);continue}let g=c.run({value:t[h],issues:[]},n);if(g instanceof Promise)e.push(g.then((x)=>Gg(x,r,h,t,d,f)));else Gg(g,r,h,t,d,f)}if(s.length)r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i});if(!e.length)return r;return Promise.all(e).then(()=>r)}var g_=U("$ZodObject",(e,t)=>{if(Mt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}let n=vf(()=>U5(t));Et(e._zod,"propValues",()=>{let a=t.shape,c={};for(let l in a){let d=a[l]._zod;if(d.values){c[l]??(c[l]=new Set);for(let f of d.values)c[l].add(f)}}return c});let o=hl,i=t.catchall,s;e._zod.parse=(a,c)=>{s??(s=n.value);let l=a.value;if(!o(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),a;a.value={};let d=[],f=s.shape;for(let h of s.keys){let g=f[h],x=g._zod.optin==="optional",w=g._zod.optout==="optional",S=g._zod.run({value:l[h],issues:[]},c);if(S instanceof Promise)d.push(S.then((_)=>Gg(_,a,h,l,x,w)));else Gg(S,a,h,l,x,w)}if(!i)return d.length?Promise.all(d).then(()=>a):a;return j5(d,l,a,c,n.value,e)}}),q5=U("$ZodObjectJIT",(e,t)=>{g_.init(e,t);let r=e._zod.parse,n=vf(()=>U5(t)),o=(h)=>{let g=new jS(["shape","payload","ctx"]),x=n.value,w=(T)=>{let v=NS(T);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};g.write("const input = payload.value;");let S=Object.create(null),_=0;for(let T of x.keys)S[T]=`key_${_++}`;g.write("const newResult = {};");for(let T of x.keys){let v=S[T],E=NS(T),k=h[T],O=k?._zod?.optin==="optional",B=k?._zod?.optout==="optional";if(g.write(`const ${v} = ${w(T)};`),O&&B)g.write(`
69
+ `))}}var AC={major:4,minor:4,patch:3};var Mt=U("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=AC;let n=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(s,a,c)=>{let l=Dc(s),d;for(let f of a){if(f._zod.def.when){if(E6(s))continue;if(!f._zod.def.when(s))continue}else if(l)continue;let h=s.issues.length,g=f._zod.check(s);if(g instanceof Promise&&c?.async===!1)throw new ds;if(d||g instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await g,s.issues.length===h)return;if(!l)l=Dc(s,h)});else{if(s.issues.length===h)continue;if(!l)l=Dc(s,h)}}if(d)return d.then(()=>s);return s},i=(s,a,c)=>{if(Dc(s))return s.aborted=!0,s;let l=o(a,n,c);if(l instanceof Promise){if(c.async===!1)throw new ds;return l.then((d)=>e._zod.parse(d,c))}return e._zod.parse(l,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let l=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});if(l instanceof Promise)return l.then((d)=>i(d,s,a));return i(l,s,a)}let c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new ds;return c.then((l)=>o(l,n,a))}return o(c,n,a)}}Et(e,"~standard",()=>({validate:(o)=>{try{let i=Uc(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch(i){return jc(e,o).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Of=U("$ZodString",(e,t)=>{Mt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??sC(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(o){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Zt=U("$ZodStringFormat",(e,t)=>{Cf.init(e,t),Of.init(e,t)}),HS=U("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=G6),Zt.init(e,t)}),GS=U("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=LS(n))}else t.pattern??(t.pattern=LS());Zt.init(e,t)}),VS=U("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=V6),Zt.init(e,t)}),ZS=U("$ZodURL",(e,t)=>{Zt.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===X6.source){if(!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let o=new URL(n);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(o.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})}if(t.normalize)r.value=o.href;else r.value=n;return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),WS=U("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Z6()),Zt.init(e,t)}),KS=U("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=q6),Zt.init(e,t)}),YS=U("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=B6),Zt.init(e,t)}),JS=U("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=D6),Zt.init(e,t)}),QS=U("$ZodULID",(e,t)=>{t.pattern??(t.pattern=F6),Zt.init(e,t)}),XS=U("$ZodXID",(e,t)=>{t.pattern??(t.pattern=U6),Zt.init(e,t)}),e_=U("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=j6),Zt.init(e,t)}),zC=U("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=iC(t)),Zt.init(e,t)}),LC=U("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=rC),Zt.init(e,t)}),BC=U("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=oC(t)),Zt.init(e,t)}),DC=U("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=H6),Zt.init(e,t)}),t_=U("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=W6),Zt.init(e,t),e._zod.bag.format="ipv4"}),r_=U("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=K6),Zt.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var n_=U("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Y6),Zt.init(e,t)}),o_=U("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=J6),Zt.init(e,t),e._zod.check=(r)=>{let n=r.value.split("/");try{if(n.length!==2)throw Error();let[o,i]=n;if(!i)throw Error();let s=Number(i);if(`${s}`!==i)throw Error();if(s<0||s>128)throw Error();new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function FC(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var i_=U("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Q6),Zt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(FC(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function yY(e){if(!BS.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return FC(r)}var s_=U("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=BS),Zt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(yY(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),a_=U("$ZodE164",(e,t)=>{t.pattern??(t.pattern=eC),Zt.init(e,t)});function bY(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&(!("alg"in o)||o.alg!==t))return!1;return!0}catch{return!1}}var c_=U("$ZodJWT",(e,t)=>{Zt.init(e,t),e._zod.check=(r)=>{if(bY(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Vg=U("$ZodNumber",(e,t)=>{Mt.init(e,t),e._zod.pattern=e._zod.bag.pattern??DS,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(s){}let o=r.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),u_=U("$ZodNumberFormat",(e,t)=>{hC.init(e,t),Vg.init(e,t)}),l_=U("$ZodBoolean",(e,t)=>{Mt.init(e,t),e._zod.pattern=uC,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(i){}let o=r.value;if(typeof o==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),d_=U("$ZodBigInt",(e,t)=>{Mt.init(e,t),e._zod.pattern=aC,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(o){}if(typeof r.value==="bigint")return r;return r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}});var p_=U("$ZodNull",(e,t)=>{Mt.init(e,t),e._zod.pattern=lC,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;if(o===null)return r;return r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}});var f_=U("$ZodUnknown",(e,t)=>{Mt.init(e,t),e._zod.parse=(r)=>r}),m_=U("$ZodNever",(e,t)=>{Mt.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function IC(e,t,r){if(e.issues.length)t.issues.push(...ha(r,e.issues));t.value[r]=e.value}var h_=U("$ZodArray",(e,t)=>{Mt.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},n);if(c instanceof Promise)i.push(c.then((l)=>IC(l,r,s)));else IC(c,r,s)}if(i.length)return Promise.all(i).then(()=>r);return r}});function Gg(e,t,r,n,o,i){let s=r in n;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...ha(r,e.issues))}if(!s&&!o){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(s)t.value[r]=void 0}else t.value[r]=e.value}function UC(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let r=y6(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function jC(e,t,r,n,o,i){let s=[],a=o.keySet,c=o.catchall._zod,l=c.def.type,d=c.optin==="optional",f=c.optout==="optional";for(let h in t){if(h==="__proto__")continue;if(a.has(h))continue;if(l==="never"){s.push(h);continue}let g=c.run({value:t[h],issues:[]},n);if(g instanceof Promise)e.push(g.then((x)=>Gg(x,r,h,t,d,f)));else Gg(g,r,h,t,d,f)}if(s.length)r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i});if(!e.length)return r;return Promise.all(e).then(()=>r)}var g_=U("$ZodObject",(e,t)=>{if(Mt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}let n=vf(()=>UC(t));Et(e._zod,"propValues",()=>{let a=t.shape,c={};for(let l in a){let d=a[l]._zod;if(d.values){c[l]??(c[l]=new Set);for(let f of d.values)c[l].add(f)}}return c});let o=hl,i=t.catchall,s;e._zod.parse=(a,c)=>{s??(s=n.value);let l=a.value;if(!o(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),a;a.value={};let d=[],f=s.shape;for(let h of s.keys){let g=f[h],x=g._zod.optin==="optional",w=g._zod.optout==="optional",S=g._zod.run({value:l[h],issues:[]},c);if(S instanceof Promise)d.push(S.then((_)=>Gg(_,a,h,l,x,w)));else Gg(S,a,h,l,x,w)}if(!i)return d.length?Promise.all(d).then(()=>a):a;return jC(d,l,a,c,n.value,e)}}),qC=U("$ZodObjectJIT",(e,t)=>{g_.init(e,t);let r=e._zod.parse,n=vf(()=>UC(t)),o=(h)=>{let g=new jS(["shape","payload","ctx"]),x=n.value,w=(T)=>{let v=NS(T);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};g.write("const input = payload.value;");let S=Object.create(null),_=0;for(let T of x.keys)S[T]=`key_${_++}`;g.write("const newResult = {};");for(let T of x.keys){let v=S[T],E=NS(T),k=h[T],O=k?._zod?.optin==="optional",B=k?._zod?.optout==="optional";if(g.write(`const ${v} = ${w(T)};`),O&&B)g.write(`
70
70
  if (${v}.issues.length) {
71
71
  if (${E} in input) {
72
72
  payload.issues = payload.issues.concat(${v}.issues.map(iss => ({
@@ -125,15 +125,15 @@ ${PD(h)}`;super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessag
125
125
  newResult[${E}] = ${v}.value;
126
126
  }
127
127
 
128
- `)}g.write("payload.value = newResult;"),g.write("return payload;");let A=g.compile();return(T,v)=>A(h,T,v)},i,s=hl,a=!ml.jitless,l=a&&h6.value,d=t.catchall,f;e._zod.parse=(h,g)=>{f??(f=n.value);let x=h.value;if(!s(x))return h.issues.push({expected:"object",code:"invalid_type",input:x,inst:e}),h;if(a&&l&&g?.async===!1&&g.jitless!==!0){if(!i)i=o(t.shape);if(h=i(h,g),!d)return h;return j5([],x,h,g,f,e)}return r(h,g)}});function k5(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter((i)=>!Dc(i));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((i)=>i.issues.map((s)=>Mo(s,n,Zn())))}),t}var Zg=U("$ZodUnion",(e,t)=>{Mt.init(e,t),Et(e._zod,"optin",()=>t.options.some((n)=>n._zod.optin==="optional")?"optional":void 0),Et(e._zod,"optout",()=>t.options.some((n)=>n._zod.optout==="optional")?"optional":void 0),Et(e._zod,"values",()=>{if(t.options.every((n)=>n._zod.values))return new Set(t.options.flatMap((n)=>Array.from(n._zod.values)));return}),Et(e._zod,"pattern",()=>{if(t.options.every((n)=>n._zod.pattern)){let n=t.options.map((o)=>o._zod.pattern);return new RegExp(`^(${n.map((o)=>Bg(o.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let i=!1,s=[];for(let a of t.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)s.push(c),i=!0;else{if(c.issues.length===0)return c;s.push(c)}}if(!i)return k5(s,n,e,o);return Promise.all(s).then((a)=>k5(a,n,e,o))}});var y_=U("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Zg.init(e,t);let r=e._zod.parse;Et(e._zod,"propValues",()=>{let o={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,c]of Object.entries(s)){if(!o[a])o[a]=new Set;for(let l of c)o[a].add(l)}}return o});let n=vf(()=>{let o=t.options,i=new Map;for(let s of o){let a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});e._zod.parse=(o,i)=>{let s=o.value;if(!hl(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;let a=n.value.get(s?.[t.discriminator]);if(a)return a._zod.run(o,i);if(t.unionFallback||i.direction==="backward")return r(o,i);return o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()),input:s,path:[t.discriminator],inst:e}),o}}),b_=U("$ZodIntersection",(e,t)=>{Mt.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);if(i instanceof Promise||s instanceof Promise)return Promise.all([i,s]).then(([c,l])=>R5(r,c,l));return R5(r,i,s)}});function qS(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Bc(e)&&Bc(t)){let r=Object.keys(t),n=Object.keys(e).filter((i)=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=qS(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n],s=qS(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function R5(e,t,r){let n=new Map,o;for(let a of t.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys){if(!n.has(c))n.set(c,{});n.get(c).l=!0}}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let c of a.keys){if(!n.has(c))n.set(c,{});n.get(c).r=!0}else e.issues.push(a);let i=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o)e.issues.push({...o,keys:i});if(Dc(e))return e;let s=qS(t.value,r.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var x_=U("$ZodRecord",(e,t)=>{Mt.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Bc(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[],s=t.keyType._zod.values;if(s){r.value={};let a=new Set;for(let l of s)if(typeof l==="string"||typeof l==="number"||typeof l==="symbol"){a.add(typeof l==="number"?l.toString():l);let d=t.keyType._zod.run({value:l,issues:[]},n);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((g)=>Mo(g,n,Zn())),input:l,path:[l],inst:e});continue}let f=d.value,h=t.valueType._zod.run({value:o[l],issues:[]},n);if(h instanceof Promise)i.push(h.then((g)=>{if(g.issues.length)r.issues.push(...ha(l,g.issues));r.value[f]=g.value}));else{if(h.issues.length)r.issues.push(...ha(l,h.issues));r.value[f]=h.value}}let c;for(let l in o)if(!a.has(l))c=c??[],c.push(l);if(c&&c.length>0)r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=t.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&DS.test(a)&&c.issues.length){let f=t.keyType._zod.run({value:Number(a),issues:[]},n);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(f.issues.length===0)c=f}if(c.issues.length){if(t.mode==="loose")r.value[a]=o[a];else r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map((f)=>Mo(f,n,Zn())),input:a,path:[a],inst:e});continue}let d=t.valueType._zod.run({value:o[a],issues:[]},n);if(d instanceof Promise)i.push(d.then((f)=>{if(f.issues.length)r.issues.push(...ha(a,f.issues));r.value[c.value]=f.value}));else{if(d.issues.length)r.issues.push(...ha(a,d.issues));r.value[c.value]=d.value}}}if(i.length)return Promise.all(i).then(()=>r);return r}});var w_=U("$ZodEnum",(e,t)=>{Mt.init(e,t);let r=zg(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter((o)=>g6.has(typeof o)).map((o)=>typeof o==="string"?ma(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{let s=o.value;if(n.has(s))return o;return o.issues.push({code:"invalid_value",values:r,input:s,inst:e}),o}}),S_=U("$ZodLiteral",(e,t)=>{if(Mt.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map((n)=>typeof n==="string"?ma(n):n?ma(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;if(r.has(i))return n;return n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}});var __=U("$ZodTransform",(e,t)=>{Mt.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new _f(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then((s)=>(r.value=s,r.fallback=!0,r));if(o instanceof Promise)throw new ds;return r.value=o,r.fallback=!0,r}});function C5(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var Wg=U("$ZodOptional",(e,t)=>{Mt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Et(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Et(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Bg(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let o=r.value,i=t.innerType._zod.run(r,n);if(i instanceof Promise)return i.then((s)=>C5(s,o));return C5(i,o)}if(r.value===void 0)return r;return t.innerType._zod.run(r,n)}}),T_=U("$ZodExactOptional",(e,t)=>{Wg.init(e,t),Et(e._zod,"values",()=>t.innerType._zod.values),Et(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),v_=U("$ZodNullable",(e,t)=>{Mt.init(e,t),Et(e._zod,"optin",()=>t.innerType._zod.optin),Et(e._zod,"optout",()=>t.innerType._zod.optout),Et(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Bg(r.source)}|null)$`):void 0}),Et(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>{if(r.value===null)return r;return t.innerType._zod.run(r,n)}}),E_=U("$ZodDefault",(e,t)=>{Mt.init(e,t),e._zod.optin="optional",Et(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>O5(i,t));return O5(o,t)}});function O5(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var P_=U("$ZodPrefault",(e,t)=>{Mt.init(e,t),e._zod.optin="optional",Et(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,n)}}),A_=U("$ZodNonOptional",(e,t)=>{Mt.init(e,t),Et(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter((n)=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>M5(i,e));return M5(o,e)}});function M5(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var I_=U("$ZodCatch",(e,t)=>{Mt.init(e,t),e._zod.optin="optional",Et(e._zod,"optout",()=>t.innerType._zod.optout),Et(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>{if(r.value=i.value,i.issues.length)r.value=t.catchValue({...r,error:{issues:i.issues.map((s)=>Mo(s,n,Zn()))},input:r.value}),r.issues=[],r.fallback=!0;return r});if(r.value=o.value,o.issues.length)r.value=t.catchValue({...r,error:{issues:o.issues.map((i)=>Mo(i,n,Zn()))},input:r.value}),r.issues=[],r.fallback=!0;return r}});var Kg=U("$ZodPipe",(e,t)=>{Mt.init(e,t),Et(e._zod,"values",()=>t.in._zod.values),Et(e._zod,"optin",()=>t.in._zod.optin),Et(e._zod,"optout",()=>t.out._zod.optout),Et(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let i=t.out._zod.run(r,n);if(i instanceof Promise)return i.then((s)=>Hg(s,t.in,n));return Hg(i,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>Hg(i,t.out,n));return Hg(o,t.out,n)}});function Hg(e,t,r){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var H5=U("$ZodPreprocess",(e,t)=>{Kg.init(e,t)}),k_=U("$ZodReadonly",(e,t)=>{Mt.init(e,t),Et(e._zod,"propValues",()=>t.innerType._zod.propValues),Et(e._zod,"values",()=>t.innerType._zod.values),Et(e._zod,"optin",()=>t.innerType?._zod?.optin),Et(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then(N5);return N5(o)}});function N5(e){return e.value=Object.freeze(e.value),e}var R_=U("$ZodCustom",(e,t)=>{zr.init(e,t),Mt.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=(r)=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then((i)=>$5(i,r,n,e));$5(o,r,n,e);return}});function $5(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};if(n._zod.def.params)o.params=n._zod.def.params;t.issues.push(Fc(o))}}var xY=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return(o)=>{switch(o.code){case"invalid_type":{let i=n[o.expected]??o.expected,s=P6(o.input),a=n[s]??s;return`Invalid input: expected ${i}, received ${a}`}case"invalid_value":if(o.values.length===1)return`Invalid input: expected ${zS(o.values[0])}`;return`Invalid option: expected one of ${MS(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=t(o.origin);if(s)return`Too big: expected ${o.origin??"value"} to have ${i}${o.maximum.toString()} ${s.unit??"elements"}`;return`Too big: expected ${o.origin??"value"} to be ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=t(o.origin);if(s)return`Too small: expected ${o.origin} to have ${i}${o.minimum.toString()} ${s.unit}`;return`Too small: expected ${o.origin} to be ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${MS(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":if(o.options&&Array.isArray(o.options)&&o.options.length>0)return`Invalid discriminator value. Expected ${o.options.map((s)=>`'${s}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function C_(){return{localeError:xY()}}var G5,K0e=Symbol("ZodOutput"),Y0e=Symbol("ZodInput");class V5{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function wY(){return new V5}(G5=globalThis).__zod_globalRegistry??(G5.__zod_globalRegistry=wY());var qc=globalThis.__zod_globalRegistry;function O_(e,t){return new e({type:"string",...Ie(t)})}function M_(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Ie(t)})}function Yg(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Ie(t)})}function Jg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Ie(t)})}function N_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ie(t)})}function $_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ie(t)})}function z_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ie(t)})}function L_(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Ie(t)})}function B_(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Ie(t)})}function D_(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ie(t)})}function F_(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Ie(t)})}function U_(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ie(t)})}function j_(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Ie(t)})}function q_(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Ie(t)})}function H_(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ie(t)})}function G_(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ie(t)})}function V_(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ie(t)})}function Z_(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ie(t)})}function W_(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ie(t)})}function K_(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Ie(t)})}function Y_(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Ie(t)})}function J_(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Ie(t)})}function Q_(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Ie(t)})}function Z5(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ie(t)})}function W5(e,t){return new e({type:"string",format:"date",check:"string_format",...Ie(t)})}function K5(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Ie(t)})}function Y5(e,t){return new e({type:"string",format:"duration",check:"string_format",...Ie(t)})}function X_(e,t){return new e({type:"number",checks:[],...Ie(t)})}function eT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Ie(t)})}function tT(e,t){return new e({type:"boolean",...Ie(t)})}function rT(e,t){return new e({type:"bigint",...Ie(t)})}function nT(e,t){return new e({type:"null",...Ie(t)})}function oT(e){return new e({type:"unknown"})}function iT(e,t){return new e({type:"never",...Ie(t)})}function gl(e,t){return new FS({check:"less_than",...Ie(t),value:e,inclusive:!1})}function ga(e,t){return new FS({check:"less_than",...Ie(t),value:e,inclusive:!0})}function yl(e,t){return new US({check:"greater_than",...Ie(t),value:e,inclusive:!1})}function li(e,t){return new US({check:"greater_than",...Ie(t),value:e,inclusive:!0})}function Mf(e,t){return new m5({check:"multiple_of",...Ie(t),value:e})}function Qg(e,t){return new g5({check:"max_length",...Ie(t),maximum:e})}function bl(e,t){return new y5({check:"min_length",...Ie(t),minimum:e})}function Xg(e,t){return new b5({check:"length_equals",...Ie(t),length:e})}function sT(e,t){return new x5({check:"string_format",format:"regex",...Ie(t),pattern:e})}function aT(e){return new w5({check:"string_format",format:"lowercase",...Ie(e)})}function cT(e){return new S5({check:"string_format",format:"uppercase",...Ie(e)})}function uT(e,t){return new _5({check:"string_format",format:"includes",...Ie(t),includes:e})}function lT(e,t){return new T5({check:"string_format",format:"starts_with",...Ie(t),prefix:e})}function dT(e,t){return new v5({check:"string_format",format:"ends_with",...Ie(t),suffix:e})}function ya(e){return new E5({check:"overwrite",tx:e})}function pT(e){return ya((t)=>t.normalize(e))}function fT(){return ya((e)=>e.trim())}function mT(){return ya((e)=>e.toLowerCase())}function hT(){return ya((e)=>e.toUpperCase())}function gT(){return ya((e)=>m6(e))}function J5(e,t,r){return new e({type:"array",element:t,...Ie(r)})}function yT(e,t,r){let n=Ie(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function bT(e,t,r){return new e({type:"custom",check:"custom",fn:t,...Ie(r)})}function xT(e,t){let r=SY((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Fc(o,n.value,r._zod.def));else{let i=o;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),n.issues.push(Fc(i))}},e(n.value,n)),t);return r}function SY(e,t){let r=new zr({check:"custom",...Ie(t)});return r._zod.check=e,r}function $f(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??qc,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function jt(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,i=t.seen.get(e);if(i){if(i.count++,r.schemaPath.includes(e))i.cycle=r.path;return i.schema}let s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s);let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,d);else{let h=s.schema,g=t.processors[o.type];if(!g)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);g(e,t,h,d)}let f=e._zod.parent;if(f){if(!s.ref)s.ref=f;jt(f,t,d),t.seen.get(f).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Object.assign(s.schema,c);if(t.io==="input"&&gn(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(n=s.schema).default??(n.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function zf(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let c=n.get(a);if(c&&c!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,s[0])}}let o=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let f=e.external.registry.get(s[0])?.id,h=e.external.uri??((x)=>x);if(f)return{ref:h(f)};let g=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=g,{defId:g,ref:`${h("__shared")}#/${a}/${g}`}}if(s[1]===r)return{ref:"#"};let l=`${"#"}/${a}/`,d=s[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:l+d}},i=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:l}=o(s);if(a.def={...a.schema},l)a.defId=l;let d=a.schema;for(let f in d)delete d[f];d.$ref=c};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
128
+ `)}g.write("payload.value = newResult;"),g.write("return payload;");let A=g.compile();return(T,v)=>A(h,T,v)},i,s=hl,a=!ml.jitless,l=a&&h6.value,d=t.catchall,f;e._zod.parse=(h,g)=>{f??(f=n.value);let x=h.value;if(!s(x))return h.issues.push({expected:"object",code:"invalid_type",input:x,inst:e}),h;if(a&&l&&g?.async===!1&&g.jitless!==!0){if(!i)i=o(t.shape);if(h=i(h,g),!d)return h;return jC([],x,h,g,f,e)}return r(h,g)}});function kC(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter((i)=>!Dc(i));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((i)=>i.issues.map((s)=>Mo(s,n,Zn())))}),t}var Zg=U("$ZodUnion",(e,t)=>{Mt.init(e,t),Et(e._zod,"optin",()=>t.options.some((n)=>n._zod.optin==="optional")?"optional":void 0),Et(e._zod,"optout",()=>t.options.some((n)=>n._zod.optout==="optional")?"optional":void 0),Et(e._zod,"values",()=>{if(t.options.every((n)=>n._zod.values))return new Set(t.options.flatMap((n)=>Array.from(n._zod.values)));return}),Et(e._zod,"pattern",()=>{if(t.options.every((n)=>n._zod.pattern)){let n=t.options.map((o)=>o._zod.pattern);return new RegExp(`^(${n.map((o)=>Bg(o.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let i=!1,s=[];for(let a of t.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)s.push(c),i=!0;else{if(c.issues.length===0)return c;s.push(c)}}if(!i)return kC(s,n,e,o);return Promise.all(s).then((a)=>kC(a,n,e,o))}});var y_=U("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Zg.init(e,t);let r=e._zod.parse;Et(e._zod,"propValues",()=>{let o={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,c]of Object.entries(s)){if(!o[a])o[a]=new Set;for(let l of c)o[a].add(l)}}return o});let n=vf(()=>{let o=t.options,i=new Map;for(let s of o){let a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});e._zod.parse=(o,i)=>{let s=o.value;if(!hl(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;let a=n.value.get(s?.[t.discriminator]);if(a)return a._zod.run(o,i);if(t.unionFallback||i.direction==="backward")return r(o,i);return o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()),input:s,path:[t.discriminator],inst:e}),o}}),b_=U("$ZodIntersection",(e,t)=>{Mt.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);if(i instanceof Promise||s instanceof Promise)return Promise.all([i,s]).then(([c,l])=>RC(r,c,l));return RC(r,i,s)}});function qS(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Bc(e)&&Bc(t)){let r=Object.keys(t),n=Object.keys(e).filter((i)=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=qS(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n],s=qS(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function RC(e,t,r){let n=new Map,o;for(let a of t.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys){if(!n.has(c))n.set(c,{});n.get(c).l=!0}}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let c of a.keys){if(!n.has(c))n.set(c,{});n.get(c).r=!0}else e.issues.push(a);let i=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o)e.issues.push({...o,keys:i});if(Dc(e))return e;let s=qS(t.value,r.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var x_=U("$ZodRecord",(e,t)=>{Mt.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Bc(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[],s=t.keyType._zod.values;if(s){r.value={};let a=new Set;for(let l of s)if(typeof l==="string"||typeof l==="number"||typeof l==="symbol"){a.add(typeof l==="number"?l.toString():l);let d=t.keyType._zod.run({value:l,issues:[]},n);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((g)=>Mo(g,n,Zn())),input:l,path:[l],inst:e});continue}let f=d.value,h=t.valueType._zod.run({value:o[l],issues:[]},n);if(h instanceof Promise)i.push(h.then((g)=>{if(g.issues.length)r.issues.push(...ha(l,g.issues));r.value[f]=g.value}));else{if(h.issues.length)r.issues.push(...ha(l,h.issues));r.value[f]=h.value}}let c;for(let l in o)if(!a.has(l))c=c??[],c.push(l);if(c&&c.length>0)r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=t.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&DS.test(a)&&c.issues.length){let f=t.keyType._zod.run({value:Number(a),issues:[]},n);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(f.issues.length===0)c=f}if(c.issues.length){if(t.mode==="loose")r.value[a]=o[a];else r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map((f)=>Mo(f,n,Zn())),input:a,path:[a],inst:e});continue}let d=t.valueType._zod.run({value:o[a],issues:[]},n);if(d instanceof Promise)i.push(d.then((f)=>{if(f.issues.length)r.issues.push(...ha(a,f.issues));r.value[c.value]=f.value}));else{if(d.issues.length)r.issues.push(...ha(a,d.issues));r.value[c.value]=d.value}}}if(i.length)return Promise.all(i).then(()=>r);return r}});var w_=U("$ZodEnum",(e,t)=>{Mt.init(e,t);let r=zg(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter((o)=>g6.has(typeof o)).map((o)=>typeof o==="string"?ma(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{let s=o.value;if(n.has(s))return o;return o.issues.push({code:"invalid_value",values:r,input:s,inst:e}),o}}),S_=U("$ZodLiteral",(e,t)=>{if(Mt.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map((n)=>typeof n==="string"?ma(n):n?ma(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;if(r.has(i))return n;return n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}});var __=U("$ZodTransform",(e,t)=>{Mt.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new _f(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then((s)=>(r.value=s,r.fallback=!0,r));if(o instanceof Promise)throw new ds;return r.value=o,r.fallback=!0,r}});function CC(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var Wg=U("$ZodOptional",(e,t)=>{Mt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Et(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Et(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Bg(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let o=r.value,i=t.innerType._zod.run(r,n);if(i instanceof Promise)return i.then((s)=>CC(s,o));return CC(i,o)}if(r.value===void 0)return r;return t.innerType._zod.run(r,n)}}),T_=U("$ZodExactOptional",(e,t)=>{Wg.init(e,t),Et(e._zod,"values",()=>t.innerType._zod.values),Et(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),v_=U("$ZodNullable",(e,t)=>{Mt.init(e,t),Et(e._zod,"optin",()=>t.innerType._zod.optin),Et(e._zod,"optout",()=>t.innerType._zod.optout),Et(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Bg(r.source)}|null)$`):void 0}),Et(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>{if(r.value===null)return r;return t.innerType._zod.run(r,n)}}),E_=U("$ZodDefault",(e,t)=>{Mt.init(e,t),e._zod.optin="optional",Et(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>OC(i,t));return OC(o,t)}});function OC(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var P_=U("$ZodPrefault",(e,t)=>{Mt.init(e,t),e._zod.optin="optional",Et(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,n)}}),A_=U("$ZodNonOptional",(e,t)=>{Mt.init(e,t),Et(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter((n)=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>MC(i,e));return MC(o,e)}});function MC(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var I_=U("$ZodCatch",(e,t)=>{Mt.init(e,t),e._zod.optin="optional",Et(e._zod,"optout",()=>t.innerType._zod.optout),Et(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>{if(r.value=i.value,i.issues.length)r.value=t.catchValue({...r,error:{issues:i.issues.map((s)=>Mo(s,n,Zn()))},input:r.value}),r.issues=[],r.fallback=!0;return r});if(r.value=o.value,o.issues.length)r.value=t.catchValue({...r,error:{issues:o.issues.map((i)=>Mo(i,n,Zn()))},input:r.value}),r.issues=[],r.fallback=!0;return r}});var Kg=U("$ZodPipe",(e,t)=>{Mt.init(e,t),Et(e._zod,"values",()=>t.in._zod.values),Et(e._zod,"optin",()=>t.in._zod.optin),Et(e._zod,"optout",()=>t.out._zod.optout),Et(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let i=t.out._zod.run(r,n);if(i instanceof Promise)return i.then((s)=>Hg(s,t.in,n));return Hg(i,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>Hg(i,t.out,n));return Hg(o,t.out,n)}});function Hg(e,t,r){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var HC=U("$ZodPreprocess",(e,t)=>{Kg.init(e,t)}),k_=U("$ZodReadonly",(e,t)=>{Mt.init(e,t),Et(e._zod,"propValues",()=>t.innerType._zod.propValues),Et(e._zod,"values",()=>t.innerType._zod.values),Et(e._zod,"optin",()=>t.innerType?._zod?.optin),Et(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then(NC);return NC(o)}});function NC(e){return e.value=Object.freeze(e.value),e}var R_=U("$ZodCustom",(e,t)=>{zr.init(e,t),Mt.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=(r)=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then((i)=>$C(i,r,n,e));$C(o,r,n,e);return}});function $C(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};if(n._zod.def.params)o.params=n._zod.def.params;t.issues.push(Fc(o))}}var xY=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return(o)=>{switch(o.code){case"invalid_type":{let i=n[o.expected]??o.expected,s=P6(o.input),a=n[s]??s;return`Invalid input: expected ${i}, received ${a}`}case"invalid_value":if(o.values.length===1)return`Invalid input: expected ${zS(o.values[0])}`;return`Invalid option: expected one of ${MS(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=t(o.origin);if(s)return`Too big: expected ${o.origin??"value"} to have ${i}${o.maximum.toString()} ${s.unit??"elements"}`;return`Too big: expected ${o.origin??"value"} to be ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=t(o.origin);if(s)return`Too small: expected ${o.origin} to have ${i}${o.minimum.toString()} ${s.unit}`;return`Too small: expected ${o.origin} to be ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${MS(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":if(o.options&&Array.isArray(o.options)&&o.options.length>0)return`Invalid discriminator value. Expected ${o.options.map((s)=>`'${s}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function C_(){return{localeError:xY()}}var GC,K0e=Symbol("ZodOutput"),Y0e=Symbol("ZodInput");class VC{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function wY(){return new VC}(GC=globalThis).__zod_globalRegistry??(GC.__zod_globalRegistry=wY());var qc=globalThis.__zod_globalRegistry;function O_(e,t){return new e({type:"string",...Ie(t)})}function M_(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Ie(t)})}function Yg(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Ie(t)})}function Jg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Ie(t)})}function N_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ie(t)})}function $_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ie(t)})}function z_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ie(t)})}function L_(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Ie(t)})}function B_(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Ie(t)})}function D_(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ie(t)})}function F_(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Ie(t)})}function U_(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ie(t)})}function j_(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Ie(t)})}function q_(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Ie(t)})}function H_(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ie(t)})}function G_(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ie(t)})}function V_(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ie(t)})}function Z_(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ie(t)})}function W_(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ie(t)})}function K_(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Ie(t)})}function Y_(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Ie(t)})}function J_(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Ie(t)})}function Q_(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Ie(t)})}function ZC(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ie(t)})}function WC(e,t){return new e({type:"string",format:"date",check:"string_format",...Ie(t)})}function KC(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Ie(t)})}function YC(e,t){return new e({type:"string",format:"duration",check:"string_format",...Ie(t)})}function X_(e,t){return new e({type:"number",checks:[],...Ie(t)})}function eT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Ie(t)})}function tT(e,t){return new e({type:"boolean",...Ie(t)})}function rT(e,t){return new e({type:"bigint",...Ie(t)})}function nT(e,t){return new e({type:"null",...Ie(t)})}function oT(e){return new e({type:"unknown"})}function iT(e,t){return new e({type:"never",...Ie(t)})}function gl(e,t){return new FS({check:"less_than",...Ie(t),value:e,inclusive:!1})}function ga(e,t){return new FS({check:"less_than",...Ie(t),value:e,inclusive:!0})}function yl(e,t){return new US({check:"greater_than",...Ie(t),value:e,inclusive:!1})}function li(e,t){return new US({check:"greater_than",...Ie(t),value:e,inclusive:!0})}function Mf(e,t){return new mC({check:"multiple_of",...Ie(t),value:e})}function Qg(e,t){return new gC({check:"max_length",...Ie(t),maximum:e})}function bl(e,t){return new yC({check:"min_length",...Ie(t),minimum:e})}function Xg(e,t){return new bC({check:"length_equals",...Ie(t),length:e})}function sT(e,t){return new xC({check:"string_format",format:"regex",...Ie(t),pattern:e})}function aT(e){return new wC({check:"string_format",format:"lowercase",...Ie(e)})}function cT(e){return new SC({check:"string_format",format:"uppercase",...Ie(e)})}function uT(e,t){return new _C({check:"string_format",format:"includes",...Ie(t),includes:e})}function lT(e,t){return new TC({check:"string_format",format:"starts_with",...Ie(t),prefix:e})}function dT(e,t){return new vC({check:"string_format",format:"ends_with",...Ie(t),suffix:e})}function ya(e){return new EC({check:"overwrite",tx:e})}function pT(e){return ya((t)=>t.normalize(e))}function fT(){return ya((e)=>e.trim())}function mT(){return ya((e)=>e.toLowerCase())}function hT(){return ya((e)=>e.toUpperCase())}function gT(){return ya((e)=>m6(e))}function JC(e,t,r){return new e({type:"array",element:t,...Ie(r)})}function yT(e,t,r){let n=Ie(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function bT(e,t,r){return new e({type:"custom",check:"custom",fn:t,...Ie(r)})}function xT(e,t){let r=SY((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Fc(o,n.value,r._zod.def));else{let i=o;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),n.issues.push(Fc(i))}},e(n.value,n)),t);return r}function SY(e,t){let r=new zr({check:"custom",...Ie(t)});return r._zod.check=e,r}function $f(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??qc,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function jt(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,i=t.seen.get(e);if(i){if(i.count++,r.schemaPath.includes(e))i.cycle=r.path;return i.schema}let s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s);let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,d);else{let h=s.schema,g=t.processors[o.type];if(!g)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);g(e,t,h,d)}let f=e._zod.parent;if(f){if(!s.ref)s.ref=f;jt(f,t,d),t.seen.get(f).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Object.assign(s.schema,c);if(t.io==="input"&&gn(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(n=s.schema).default??(n.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function zf(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let c=n.get(a);if(c&&c!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,s[0])}}let o=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let f=e.external.registry.get(s[0])?.id,h=e.external.uri??((x)=>x);if(f)return{ref:h(f)};let g=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=g,{defId:g,ref:`${h("__shared")}#/${a}/${g}`}}if(s[1]===r)return{ref:"#"};let l=`${"#"}/${a}/`,d=s[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:l+d}},i=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:l}=o(s);if(a.def={...a.schema},l)a.defId=l;let d=a.schema;for(let f in d)delete d[f];d.$ref=c};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
129
129
 
130
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){i(s);continue}if(e.external){let l=e.external.registry.get(s[0])?.id;if(t!==s[0]&&l){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1){if(e.reused==="ref"){i(s);continue}}}}function Lf(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let l=c.def??c.schema,d={...l},f=c.ref;if(c.ref=null,f){n(f);let g=e.seen.get(f),x=g.schema;if(x.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))l.allOf=l.allOf??[],l.allOf.push(x);else Object.assign(l,x);if(Object.assign(l,d),a._zod.parent===f)for(let S in l){if(S==="$ref"||S==="allOf")continue;if(!(S in d))delete l[S]}if(x.$ref&&g.def)for(let S in l){if(S==="$ref"||S==="allOf")continue;if(S in g.def&&JSON.stringify(l[S])===JSON.stringify(g.def[S]))delete l[S]}}let h=a._zod.parent;if(h&&h!==f){n(h);let g=e.seen.get(h);if(g?.schema.$ref){if(l.$ref=g.schema.$ref,g.def)for(let x in l){if(x==="$ref"||x==="allOf")continue;if(x in g.def&&JSON.stringify(l[x])===JSON.stringify(g.def[x]))delete l[x]}}}e.override({zodSchema:a,jsonSchema:l,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())n(a[0]);let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&o.id===i)delete o.id;let s=e.external?.defs??{};for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;s[c.defId]=c.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")o.$defs=s;else o.definitions=s;try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Nf(t,"input",e.processors),output:Nf(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function gn(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return gn(n.element,r);if(n.type==="set")return gn(n.valueType,r);if(n.type==="lazy")return gn(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return gn(n.innerType,r);if(n.type==="intersection")return gn(n.left,r)||gn(n.right,r);if(n.type==="record"||n.type==="map")return gn(n.keyType,r)||gn(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return gn(n.in,r)||gn(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(gn(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(gn(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(gn(o,r))return!0;if(n.rest&&gn(n.rest,r))return!0;return!1}return!1}var Q5=(e,t={})=>(r)=>{let n=$f({...r,processors:t});return jt(e,n),zf(n,e),Lf(n,e)},Nf=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:i}=n??{},s=$f({...o??{},target:i,io:t,processors:r});return jt(e,s),zf(s,e),Lf(s,e)};var _Y={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},wT=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof i==="number")o.minLength=i;if(typeof s==="number")o.maxLength=s;if(a){if(o.format=_Y[a]??a,o.format==="")delete o.format;if(a==="time")delete o.format}if(l)o.contentEncoding=l;if(c&&c.size>0){let d=[...c];if(d.length===1)o.pattern=d[0].source;else if(d.length>1)o.allOf=[...d.map((f)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))]}},ST=(e,t,r,n)=>{let o=r,{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:d}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))o.type="integer";else o.type="number";let f=typeof d==="number"&&d>=(i??Number.NEGATIVE_INFINITY),h=typeof l==="number"&&l<=(s??Number.POSITIVE_INFINITY),g=t.target==="draft-04"||t.target==="openapi-3.0";if(f)if(g)o.minimum=d,o.exclusiveMinimum=!0;else o.exclusiveMinimum=d;else if(typeof i==="number")o.minimum=i;if(h)if(g)o.maximum=l,o.exclusiveMaximum=!0;else o.exclusiveMaximum=l;else if(typeof s==="number")o.maximum=s;if(typeof c==="number")o.multipleOf=c},_T=(e,t,r,n)=>{r.type="boolean"},TT=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},eC=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},vT=(e,t,r,n)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},tC=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},rC=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},ET=(e,t,r,n)=>{r.not={}},nC=(e,t,r,n)=>{},PT=(e,t,r,n)=>{},oC=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},AT=(e,t,r,n)=>{let o=e._zod.def,i=zg(o.entries);if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";r.enum=i},IT=(e,t,r,n)=>{let o=e._zod.def,i=[];for(let s of o.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else i.push(Number(s));else i.push(s);if(i.length===0);else if(i.length===1){let s=i[0];if(r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[s];else r.const=s}else{if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";if(i.every((s)=>typeof s==="boolean"))r.type="boolean";if(i.every((s)=>s===null))r.type="null";r.enum=i}},iC=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},sC=(e,t,r,n)=>{let o=r,i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},aC=(e,t,r,n)=>{let o=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:c}=e._zod.bag;if(s!==void 0)i.minLength=s;if(a!==void 0)i.maxLength=a;if(c)if(c.length===1)i.contentMediaType=c[0],Object.assign(o,i);else Object.assign(o,i),o.anyOf=c.map((l)=>({contentMediaType:l}));else Object.assign(o,i)},cC=(e,t,r,n)=>{r.type="boolean"},kT=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},uC=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},RT=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},lC=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},dC=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},CT=(e,t,r,n)=>{let o=r,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")o.minItems=s;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=jt(i.element,t,{...n,path:[...n.path,"items"]})},OT=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object",o.properties={};let s=i.shape;for(let l in s)o.properties[l]=jt(s[l],t,{...n,path:[...n.path,"properties",l]});let a=new Set(Object.keys(s)),c=new Set([...a].filter((l)=>{let d=i.shape[l]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(c.size>0)o.required=Array.from(c);if(i.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")o.additionalProperties=!1}else if(i.catchall)o.additionalProperties=jt(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},MT=(e,t,r,n)=>{let o=e._zod.def,i=o.inclusive===!1,s=o.options.map((a,c)=>jt(a,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));if(i)r.oneOf=s;else r.anyOf=s},NT=(e,t,r,n)=>{let o=e._zod.def,i=jt(o.left,t,{...n,path:[...n.path,"allOf",0]}),s=jt(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=(l)=>("allOf"in l)&&Object.keys(l).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c},pC=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((h,g)=>jt(h,t,{...n,path:[...n.path,s,g]})),l=i.rest?jt(i.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(o.prefixItems=c,l)o.items=l}else if(t.target==="openapi-3.0"){if(o.items={anyOf:c},l)o.items.anyOf.push(l);if(o.minItems=c.length,!l)o.maxItems=c.length}else if(o.items=c,l)o.additionalItems=l;let{minimum:d,maximum:f}=e._zod.bag;if(typeof d==="number")o.minItems=d;if(typeof f==="number")o.maxItems=f},$T=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object";let s=i.keyType,c=s._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let d=jt(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let f of c)o.patternProperties[f.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")o.propertyNames=jt(i.keyType,t,{...n,path:[...n.path,"propertyNames"]});o.additionalProperties=jt(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let l=s._zod.values;if(l){let d=[...l].filter((f)=>typeof f==="string"||typeof f==="number");if(d.length>0)o.required=d}},zT=(e,t,r,n)=>{let o=e._zod.def,i=jt(o.innerType,t,n),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=o.innerType,r.nullable=!0;else r.anyOf=[i,{type:"null"}]},LT=(e,t,r,n)=>{let o=e._zod.def;jt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},BT=(e,t,r,n)=>{let o=e._zod.def;jt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},DT=(e,t,r,n)=>{let o=e._zod.def;jt(o.innerType,t,n);let i=t.seen.get(e);if(i.ref=o.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(o.defaultValue))},FT=(e,t,r,n)=>{let o=e._zod.def;jt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},UT=(e,t,r,n)=>{let o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?o.out:o.in:o.out;jt(s,t,n);let a=t.seen.get(e);a.ref=s},jT=(e,t,r,n)=>{let o=e._zod.def;jt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.readOnly=!0},fC=(e,t,r,n)=>{let o=e._zod.def;jt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},ey=(e,t,r,n)=>{let o=e._zod.def;jt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},mC=(e,t,r,n)=>{let o=e._zod.innerType;jt(o,t,n);let i=t.seen.get(e);i.ref=o},X5={string:wT,number:ST,boolean:_T,bigint:TT,symbol:eC,null:vT,undefined:tC,void:rC,never:ET,any:nC,unknown:PT,date:oC,enum:AT,literal:IT,nan:iC,template_literal:sC,file:aC,success:cC,custom:kT,function:uC,transform:RT,map:lC,set:dC,array:CT,object:OT,union:MT,intersection:NT,tuple:pC,record:$T,nullable:zT,nonoptional:LT,default:BT,prefault:DT,catch:FT,pipe:UT,readonly:jT,promise:fC,optional:ey,lazy:mC};function qT(e,t){if("_idmap"in e){let n=e,o=$f({...t,processors:X5}),i={};for(let c of n._idmap.entries()){let[l,d]=c;jt(d,o)}let s={},a={registry:n,uri:t?.uri,defs:i};o.external=a;for(let c of n._idmap.entries()){let[l,d]=c;zf(o,d),s[l]=Lf(o,d)}if(Object.keys(i).length>0){let c=o.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=$f({...t,processors:X5});return jt(e,r),zf(r,e),Lf(r,e)}var uJ=U("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");Mt.init(e,t),e.def=t,e.type=t.type,e.parse=(r,n)=>jg(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Uc(e,r,n),e.parseAsync=async(r,n)=>qg(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>jc(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),e.with=e.check,e.clone=(r,n)=>co(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.apply=(r)=>r(e)});var lJ=U("ZodMiniObject",(e,t)=>{g_.init(e,t),uJ.init(e,t),Et(e,"shape",()=>t.shape)});function HT(e,t){let r={type:"object",shape:e??{},...Ie(t)};return new lJ(r)}function uo(e){return!!e._zod}function Gc(e){let t=Object.values(e);if(t.length===0)return HT({});let r=t.every(uo),n=t.every((o)=>!uo(o));if(r)return HT(e);if(n)return l6(e);throw Error("Mixed Zod versions detected in object shape.")}function ba(e,t){if(uo(e))return Uc(e,t);return e.safeParse(t)}async function ty(e,t){if(uo(e))return await jc(e,t);return await e.safeParseAsync(t)}function xa(e){if(!e)return;let t;if(uo(e))t=e._zod?.def?.shape;else t=e.shape;if(!t)return;if(typeof t==="function")try{return t()}catch{return}return t}function xl(e){if(!e)return;if(typeof e==="object"){let t=e,r=e;if(!t._def&&!r._zod){let n=Object.values(e);if(n.length>0&&n.every((o)=>typeof o==="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse==="function")))return Gc(e)}}if(uo(e)){let r=e._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return e}else if(e.shape!==void 0)return e;return}function ry(e){if(e&&typeof e==="object"){if("message"in e&&typeof e.message==="string")return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==="object"&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function gC(e){return e.description}function yC(e){if(uo(e))return e._zod?.def?.type==="optional";let t=e;if(typeof e.isOptional==="function")return e.isOptional();return t._def?.typeName==="ZodOptional"}function ny(e){if(uo(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n;return}var bC=U("ZodISODateTime",(e,t)=>{z5.init(e,t),Xt.init(e,t)});function oy(e){return Z5(bC,e)}var xC=U("ZodISODate",(e,t)=>{L5.init(e,t),Xt.init(e,t)});function GT(e){return W5(xC,e)}var wC=U("ZodISOTime",(e,t)=>{B5.init(e,t),Xt.init(e,t)});function VT(e){return K5(wC,e)}var SC=U("ZodISODuration",(e,t)=>{D5.init(e,t),Xt.init(e,t)});function ZT(e){return Y5(SC,e)}var bJ=(e,t)=>{Ug.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>k6(e,r)},flatten:{value:(r)=>I6(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Tf,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Tf,2)}},isEmpty:{get(){return e.issues.length===0}}})};var Wn=U("ZodError",bJ,{Parent:Error});var _C=Pf(Wn),TC=Af(Wn),vC=If(Wn),EC=kf(Wn),PC=R6(Wn),AC=C6(Wn),IC=O6(Wn),kC=M6(Wn),RC=N6(Wn),CC=$6(Wn),OC=z6(Wn),MC=L6(Wn);var NC=new WeakMap;function Df(e,t,r){let n=Object.getPrototypeOf(e),o=NC.get(n);if(!o)o=new Set,NC.set(n,o);if(o.has(t))return;o.add(t);for(let i in r){let s=r[i];Object.defineProperty(n,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var Jt=U("ZodType",(e,t)=>(Mt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Nf(e,"input"),output:Nf(e,"output")}}),e.toJSONSchema=Q5(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,n)=>_C(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>vC(e,r,n),e.parseAsync=async(r,n)=>TC(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>EC(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>PC(e,r,n),e.decode=(r,n)=>AC(e,r,n),e.encodeAsync=async(r,n)=>IC(e,r,n),e.decodeAsync=async(r,n)=>kC(e,r,n),e.safeEncode=(r,n)=>RC(e,r,n),e.safeDecode=(r,n)=>CC(e,r,n),e.safeEncodeAsync=async(r,n)=>OC(e,r,n),e.safeDecodeAsync=async(r,n)=>MC(e,r,n),Df(e,"ZodType",{check(...r){let n=this.def;return this.clone(fa(n,{checks:[...n.checks??[],...r.map((o)=>typeof o==="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return co(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(cQ(r,n))},superRefine(r,n){return this.check(uQ(r,n))},overwrite(r){return this.check(ya(r))},optional(){return er(this)},exactOptional(){return YJ(this)},nullable(){return BC(this)},nullish(){return er(BC(this))},nonoptional(r){return rQ(this,r)},array(){return ie(this)},or(r){return pt([this,r])},and(r){return iy(this,r)},transform(r){return DC(this,ZC(r))},default(r){return XJ(this,r)},prefault(r){return tQ(this,r)},catch(r){return oQ(this,r)},pipe(r){return DC(this,r)},readonly(){return aQ(this)},describe(r){let n=this.clone();return qc.add(n,{description:r}),n},meta(...r){if(r.length===0)return qc.get(this);let n=this.clone();return qc.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return qc.get(e)?.description},configurable:!0}),e)),FC=U("_ZodString",(e,t)=>{Of.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>wT(e,n,o,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Df(e,"_ZodString",{regex(...n){return this.check(sT(...n))},includes(...n){return this.check(uT(...n))},startsWith(...n){return this.check(lT(...n))},endsWith(...n){return this.check(dT(...n))},min(...n){return this.check(bl(...n))},max(...n){return this.check(Qg(...n))},length(...n){return this.check(Xg(...n))},nonempty(...n){return this.check(bl(1,...n))},lowercase(n){return this.check(aT(n))},uppercase(n){return this.check(cT(n))},trim(){return this.check(fT())},normalize(...n){return this.check(pT(...n))},toLowerCase(){return this.check(mT())},toUpperCase(){return this.check(hT())},slugify(){return this.check(gT())}})}),wJ=U("ZodString",(e,t)=>{Of.init(e,t),FC.init(e,t),e.email=(r)=>e.check(M_(SJ,r)),e.url=(r)=>e.check(L_(_J,r)),e.jwt=(r)=>e.check(Q_(LJ,r)),e.emoji=(r)=>e.check(B_(TJ,r)),e.guid=(r)=>e.check(Yg($C,r)),e.uuid=(r)=>e.check(Jg(Bf,r)),e.uuidv4=(r)=>e.check(N_(Bf,r)),e.uuidv6=(r)=>e.check($_(Bf,r)),e.uuidv7=(r)=>e.check(z_(Bf,r)),e.nanoid=(r)=>e.check(D_(vJ,r)),e.guid=(r)=>e.check(Yg($C,r)),e.cuid=(r)=>e.check(F_(EJ,r)),e.cuid2=(r)=>e.check(U_(PJ,r)),e.ulid=(r)=>e.check(j_(AJ,r)),e.base64=(r)=>e.check(K_(NJ,r)),e.base64url=(r)=>e.check(Y_($J,r)),e.xid=(r)=>e.check(q_(IJ,r)),e.ksuid=(r)=>e.check(H_(kJ,r)),e.ipv4=(r)=>e.check(G_(RJ,r)),e.ipv6=(r)=>e.check(V_(CJ,r)),e.cidrv4=(r)=>e.check(Z_(OJ,r)),e.cidrv6=(r)=>e.check(W_(MJ,r)),e.e164=(r)=>e.check(J_(zJ,r)),e.datetime=(r)=>e.check(oy(r)),e.date=(r)=>e.check(GT(r)),e.time=(r)=>e.check(VT(r)),e.duration=(r)=>e.check(ZT(r))});function p(e){return O_(wJ,e)}var Xt=U("ZodStringFormat",(e,t)=>{Zt.init(e,t),FC.init(e,t)}),SJ=U("ZodEmail",(e,t)=>{VS.init(e,t),Xt.init(e,t)});var $C=U("ZodGUID",(e,t)=>{HS.init(e,t),Xt.init(e,t)});var Bf=U("ZodUUID",(e,t)=>{GS.init(e,t),Xt.init(e,t)});function UC(e){return Jg(Bf,e)}var _J=U("ZodURL",(e,t)=>{ZS.init(e,t),Xt.init(e,t)});var TJ=U("ZodEmoji",(e,t)=>{WS.init(e,t),Xt.init(e,t)});var vJ=U("ZodNanoID",(e,t)=>{KS.init(e,t),Xt.init(e,t)});var EJ=U("ZodCUID",(e,t)=>{YS.init(e,t),Xt.init(e,t)});var PJ=U("ZodCUID2",(e,t)=>{JS.init(e,t),Xt.init(e,t)});var AJ=U("ZodULID",(e,t)=>{QS.init(e,t),Xt.init(e,t)});var IJ=U("ZodXID",(e,t)=>{XS.init(e,t),Xt.init(e,t)});var kJ=U("ZodKSUID",(e,t)=>{e_.init(e,t),Xt.init(e,t)});var RJ=U("ZodIPv4",(e,t)=>{t_.init(e,t),Xt.init(e,t)});var CJ=U("ZodIPv6",(e,t)=>{r_.init(e,t),Xt.init(e,t)});var OJ=U("ZodCIDRv4",(e,t)=>{n_.init(e,t),Xt.init(e,t)});var MJ=U("ZodCIDRv6",(e,t)=>{o_.init(e,t),Xt.init(e,t)});var NJ=U("ZodBase64",(e,t)=>{i_.init(e,t),Xt.init(e,t)});var $J=U("ZodBase64URL",(e,t)=>{s_.init(e,t),Xt.init(e,t)});var zJ=U("ZodE164",(e,t)=>{a_.init(e,t),Xt.init(e,t)});var LJ=U("ZodJWT",(e,t)=>{c_.init(e,t),Xt.init(e,t)});var jC=U("ZodNumber",(e,t)=>{Vg.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>ST(e,n,o,i),Df(e,"ZodNumber",{gt(n,o){return this.check(yl(n,o))},gte(n,o){return this.check(li(n,o))},min(n,o){return this.check(li(n,o))},lt(n,o){return this.check(gl(n,o))},lte(n,o){return this.check(ga(n,o))},max(n,o){return this.check(ga(n,o))},int(n){return this.check(zC(n))},safe(n){return this.check(zC(n))},positive(n){return this.check(yl(0,n))},nonnegative(n){return this.check(li(0,n))},negative(n){return this.check(gl(0,n))},nonpositive(n){return this.check(ga(0,n))},multipleOf(n,o){return this.check(Mf(n,o))},step(n,o){return this.check(Mf(n,o))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??0.5),e.isFinite=!0,e.format=r.format??null});function I(e){return X_(jC,e)}var BJ=U("ZodNumberFormat",(e,t)=>{u_.init(e,t),jC.init(e,t)});function zC(e){return eT(BJ,e)}var DJ=U("ZodBoolean",(e,t)=>{l_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>_T(e,r,n,o)});function oe(e){return tT(DJ,e)}var FJ=U("ZodBigInt",(e,t)=>{d_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>TT(e,n,o,i),e.gte=(n,o)=>e.check(li(n,o)),e.min=(n,o)=>e.check(li(n,o)),e.gt=(n,o)=>e.check(yl(n,o)),e.gte=(n,o)=>e.check(li(n,o)),e.min=(n,o)=>e.check(li(n,o)),e.lt=(n,o)=>e.check(gl(n,o)),e.lte=(n,o)=>e.check(ga(n,o)),e.max=(n,o)=>e.check(ga(n,o)),e.positive=(n)=>e.check(yl(BigInt(0),n)),e.negative=(n)=>e.check(gl(BigInt(0),n)),e.nonpositive=(n)=>e.check(ga(BigInt(0),n)),e.nonnegative=(n)=>e.check(li(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(Mf(n,o));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function qC(e){return rT(FJ,e)}var UJ=U("ZodNull",(e,t)=>{p_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>vT(e,r,n,o)});function HC(e){return nT(UJ,e)}var jJ=U("ZodUnknown",(e,t)=>{f_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>PT(e,r,n,o)});function Nt(){return oT(jJ)}var qJ=U("ZodNever",(e,t)=>{m_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ET(e,r,n,o)});function Qe(e){return iT(qJ,e)}var HJ=U("ZodArray",(e,t)=>{h_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>CT(e,r,n,o),e.element=t.element,Df(e,"ZodArray",{min(r,n){return this.check(bl(r,n))},nonempty(r){return this.check(bl(1,r))},max(r,n){return this.check(Qg(r,n))},length(r,n){return this.check(Xg(r,n))},unwrap(){return this.element}})});function ie(e,t){return J5(HJ,e,t)}var GC=U("ZodObject",(e,t)=>{q5.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>OT(e,r,n,o),Et(e,"shape",()=>t.shape),Df(e,"ZodObject",{keyof(){return z(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Nt()})},loose(){return this.clone({...this._zod.def,catchall:Nt()})},strict(){return this.clone({...this._zod.def,catchall:Qe()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return S6(this,r)},safeExtend(r){return _6(this,r)},merge(r){return mY(this,r)},pick(r){return x6(this,r)},omit(r){return w6(this,r)},partial(...r){return T6(sy,this,r[0])},required(...r){return v6(WC,this,r[0])}})});function y(e,t){let r={type:"object",shape:e??{},...Ie(t)};return new GC(r)}function yn(e,t){return new GC({type:"object",shape:e,catchall:Nt(),...Ie(t)})}var VC=U("ZodUnion",(e,t)=>{Zg.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>MT(e,r,n,o),e.options=t.options});function pt(e,t){return new VC({type:"union",options:e,...Ie(t)})}var GJ=U("ZodDiscriminatedUnion",(e,t)=>{VC.init(e,t),y_.init(e,t)});function KT(e,t,r){return new GJ({type:"union",options:t,discriminator:e,...Ie(r)})}var VJ=U("ZodIntersection",(e,t)=>{b_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>NT(e,r,n,o)});function iy(e,t){return new VJ({type:"intersection",left:e,right:t})}var LC=U("ZodRecord",(e,t)=>{x_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>$T(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function Wt(e,t,r){if(!t||!t._zod)return new LC({type:"record",keyType:p(),valueType:e,...Ie(t)});return new LC({type:"record",keyType:e,valueType:t,...Ie(r)})}var WT=U("ZodEnum",(e,t)=>{w_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>AT(e,n,o,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new WT({...t,checks:[],...Ie(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new WT({...t,checks:[],...Ie(o),entries:i})}});function z(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new WT({type:"enum",entries:r,...Ie(t)})}var ZJ=U("ZodLiteral",(e,t)=>{S_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>IT(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Ae(e,t){return new ZJ({type:"literal",values:Array.isArray(e)?e:[e],...Ie(t)})}var WJ=U("ZodTransform",(e,t)=>{__.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>RT(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new _f(e.constructor.name);r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(Fc(i,r.value,t));else{let s=i;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),r.issues.push(Fc(s))}};let o=t.transform(r.value,r);if(o instanceof Promise)return o.then((i)=>(r.value=i,r.fallback=!0,r));return r.value=o,r.fallback=!0,r}});function ZC(e){return new WJ({type:"transform",transform:e})}var sy=U("ZodOptional",(e,t)=>{Wg.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ey(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function er(e){return new sy({type:"optional",innerType:e})}var KJ=U("ZodExactOptional",(e,t)=>{T_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ey(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function YJ(e){return new KJ({type:"optional",innerType:e})}var JJ=U("ZodNullable",(e,t)=>{v_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>zT(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function BC(e){return new JJ({type:"nullable",innerType:e})}var QJ=U("ZodDefault",(e,t)=>{E_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>BT(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function XJ(e,t){return new QJ({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Dg(t)}})}var eQ=U("ZodPrefault",(e,t)=>{P_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>DT(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function tQ(e,t){return new eQ({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Dg(t)}})}var WC=U("ZodNonOptional",(e,t)=>{A_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>LT(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function rQ(e,t){return new WC({type:"nonoptional",innerType:e,...Ie(t)})}var nQ=U("ZodCatch",(e,t)=>{I_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>FT(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function oQ(e,t){return new nQ({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var KC=U("ZodPipe",(e,t)=>{Kg.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>UT(e,r,n,o),e.in=t.in,e.out=t.out});function DC(e,t){return new KC({type:"pipe",in:e,out:t})}var iQ=U("ZodPreprocess",(e,t)=>{KC.init(e,t),H5.init(e,t)}),sQ=U("ZodReadonly",(e,t)=>{k_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>jT(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function aQ(e){return new sQ({type:"readonly",innerType:e})}var YC=U("ZodCustom",(e,t)=>{R_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>kT(e,r,n,o)});function JC(e,t){return yT(YC,e??(()=>!0),t)}function cQ(e,t={}){return bT(YC,e,t)}function uQ(e,t){return xT(e,t)}function Ff(e,t){return new iQ({type:"pipe",in:ZC(e),out:t})}var wa={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var QC;(function(e){})(QC||(QC={}));Zn(C_());var YT="2025-11-25";var XC=[YT,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Sa="io.modelcontextprotocol/related-task",cy="2.0",Ir=JC((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),eO=pt([p(),I().int()]),tO=p(),ixe=yn({ttl:I().optional(),pollInterval:I().optional()}),lQ=y({ttl:I().optional()}),dQ=y({taskId:p()}),JT=yn({progressToken:eO.optional(),[Sa]:dQ.optional()}),Kn=y({_meta:JT.optional()}),Uf=Kn.extend({task:lQ.optional()}),rO=(e)=>Uf.safeParse(e).success,Kr=y({method:p(),params:Kn.loose().optional()}),lo=y({_meta:JT.optional()}),po=y({method:p(),params:lo.loose().optional()}),Yr=yn({_meta:JT.optional()}),uy=pt([p(),I().int()]),nO=y({jsonrpc:Ae(cy),id:uy,...Kr.shape}).strict(),QT=(e)=>nO.safeParse(e).success,oO=y({jsonrpc:Ae(cy),...po.shape}).strict(),iO=(e)=>oO.safeParse(e).success,XT=y({jsonrpc:Ae(cy),id:uy,result:Yr}).strict(),jf=(e)=>XT.safeParse(e).success;var Be;(function(e){e[e.ConnectionClosed=-32000]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Be||(Be={}));var e1=y({jsonrpc:Ae(cy),id:uy.optional(),error:y({code:I().int(),message:p(),data:Nt().optional()})}).strict();var sO=(e)=>e1.safeParse(e).success;var aO=pt([nO,oO,XT,e1]),sxe=pt([XT,e1]),ly=Yr.strict(),pQ=lo.extend({requestId:uy.optional(),reason:p().optional()}),dy=po.extend({method:Ae("notifications/cancelled"),params:pQ}),fQ=y({src:p(),mimeType:p().optional(),sizes:ie(p()).optional(),theme:z(["light","dark"]).optional()}),qf=y({icons:ie(fQ).optional()}),Sl=y({name:p(),title:p().optional()}),cO=Sl.extend({...Sl.shape,...qf.shape,version:p(),websiteUrl:p().optional(),description:p().optional()}),mQ=iy(y({applyDefaults:oe().optional()}),Wt(p(),Nt())),hQ=Ff((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},iy(y({form:mQ.optional(),url:Ir.optional()}),Wt(p(),Nt()).optional())),gQ=yn({list:Ir.optional(),cancel:Ir.optional(),requests:yn({sampling:yn({createMessage:Ir.optional()}).optional(),elicitation:yn({create:Ir.optional()}).optional()}).optional()}),yQ=yn({list:Ir.optional(),cancel:Ir.optional(),requests:yn({tools:yn({call:Ir.optional()}).optional()}).optional()}),bQ=y({experimental:Wt(p(),Ir).optional(),sampling:y({context:Ir.optional(),tools:Ir.optional()}).optional(),elicitation:hQ.optional(),roots:y({listChanged:oe().optional()}).optional(),tasks:gQ.optional(),extensions:Wt(p(),Ir).optional()}),xQ=Kn.extend({protocolVersion:p(),capabilities:bQ,clientInfo:cO}),t1=Kr.extend({method:Ae("initialize"),params:xQ});var wQ=y({experimental:Wt(p(),Ir).optional(),logging:Ir.optional(),completions:Ir.optional(),prompts:y({listChanged:oe().optional()}).optional(),resources:y({subscribe:oe().optional(),listChanged:oe().optional()}).optional(),tools:y({listChanged:oe().optional()}).optional(),tasks:yQ.optional(),extensions:Wt(p(),Ir).optional()}),SQ=Yr.extend({protocolVersion:p(),capabilities:wQ,serverInfo:cO,instructions:p().optional()}),r1=po.extend({method:Ae("notifications/initialized"),params:lo.optional()});var py=Kr.extend({method:Ae("ping"),params:Kn.optional()}),_Q=y({progress:I(),total:er(I()),message:er(p())}),TQ=y({...lo.shape,..._Q.shape,progressToken:eO}),fy=po.extend({method:Ae("notifications/progress"),params:TQ}),vQ=Kn.extend({cursor:tO.optional()}),Hf=Kr.extend({params:vQ.optional()}),Gf=Yr.extend({nextCursor:tO.optional()}),EQ=z(["working","input_required","completed","failed","cancelled"]),Vf=y({taskId:p(),status:EQ,ttl:pt([I(),HC()]),createdAt:p(),lastUpdatedAt:p(),pollInterval:er(I()),statusMessage:er(p())}),_l=Yr.extend({task:Vf}),PQ=lo.merge(Vf),Zf=po.extend({method:Ae("notifications/tasks/status"),params:PQ}),my=Kr.extend({method:Ae("tasks/get"),params:Kn.extend({taskId:p()})}),hy=Yr.merge(Vf),gy=Kr.extend({method:Ae("tasks/result"),params:Kn.extend({taskId:p()})}),axe=Yr.loose(),yy=Hf.extend({method:Ae("tasks/list")}),by=Gf.extend({tasks:ie(Vf)}),xy=Kr.extend({method:Ae("tasks/cancel"),params:Kn.extend({taskId:p()})}),uO=Yr.merge(Vf),lO=y({uri:p(),mimeType:er(p()),_meta:Wt(p(),Nt()).optional()}),dO=lO.extend({text:p()}),n1=p().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),pO=lO.extend({blob:n1}),Wf=z(["user","assistant"]),Tl=y({audience:ie(Wf).optional(),priority:I().min(0).max(1).optional(),lastModified:oy({offset:!0}).optional()}),fO=y({...Sl.shape,...qf.shape,uri:p(),description:er(p()),mimeType:er(p()),size:er(I()),annotations:Tl.optional(),_meta:er(yn({}))}),AQ=y({...Sl.shape,...qf.shape,uriTemplate:p(),description:er(p()),mimeType:er(p()),annotations:Tl.optional(),_meta:er(yn({}))}),wy=Hf.extend({method:Ae("resources/list")}),IQ=Gf.extend({resources:ie(fO)}),Sy=Hf.extend({method:Ae("resources/templates/list")}),kQ=Gf.extend({resourceTemplates:ie(AQ)}),o1=Kn.extend({uri:p()}),RQ=o1,_y=Kr.extend({method:Ae("resources/read"),params:RQ}),CQ=Yr.extend({contents:ie(pt([dO,pO]))}),OQ=po.extend({method:Ae("notifications/resources/list_changed"),params:lo.optional()}),MQ=o1,NQ=Kr.extend({method:Ae("resources/subscribe"),params:MQ}),$Q=o1,zQ=Kr.extend({method:Ae("resources/unsubscribe"),params:$Q}),LQ=lo.extend({uri:p()}),BQ=po.extend({method:Ae("notifications/resources/updated"),params:LQ}),DQ=y({name:p(),description:er(p()),required:er(oe())}),FQ=y({...Sl.shape,...qf.shape,description:er(p()),arguments:er(ie(DQ)),_meta:er(yn({}))}),Ty=Hf.extend({method:Ae("prompts/list")}),UQ=Gf.extend({prompts:ie(FQ)}),jQ=Kn.extend({name:p(),arguments:Wt(p(),p()).optional()}),vy=Kr.extend({method:Ae("prompts/get"),params:jQ}),i1=y({type:Ae("text"),text:p(),annotations:Tl.optional(),_meta:Wt(p(),Nt()).optional()}),s1=y({type:Ae("image"),data:n1,mimeType:p(),annotations:Tl.optional(),_meta:Wt(p(),Nt()).optional()}),a1=y({type:Ae("audio"),data:n1,mimeType:p(),annotations:Tl.optional(),_meta:Wt(p(),Nt()).optional()}),qQ=y({type:Ae("tool_use"),name:p(),id:p(),input:Wt(p(),Nt()),_meta:Wt(p(),Nt()).optional()}),HQ=y({type:Ae("resource"),resource:pt([dO,pO]),annotations:Tl.optional(),_meta:Wt(p(),Nt()).optional()}),GQ=fO.extend({type:Ae("resource_link")}),c1=pt([i1,s1,a1,GQ,HQ]),VQ=y({role:Wf,content:c1}),ZQ=Yr.extend({description:p().optional(),messages:ie(VQ)}),WQ=po.extend({method:Ae("notifications/prompts/list_changed"),params:lo.optional()}),KQ=y({title:p().optional(),readOnlyHint:oe().optional(),destructiveHint:oe().optional(),idempotentHint:oe().optional(),openWorldHint:oe().optional()}),YQ=y({taskSupport:z(["required","optional","forbidden"]).optional()}),mO=y({...Sl.shape,...qf.shape,description:p().optional(),inputSchema:y({type:Ae("object"),properties:Wt(p(),Ir).optional(),required:ie(p()).optional()}).catchall(Nt()),outputSchema:y({type:Ae("object"),properties:Wt(p(),Ir).optional(),required:ie(p()).optional()}).catchall(Nt()).optional(),annotations:KQ.optional(),execution:YQ.optional(),_meta:Wt(p(),Nt()).optional()}),Ey=Hf.extend({method:Ae("tools/list")}),JQ=Gf.extend({tools:ie(mO)}),Py=Yr.extend({content:ie(c1).default([]),structuredContent:Wt(p(),Nt()).optional(),isError:oe().optional()}),cxe=Py.or(Yr.extend({toolResult:Nt()})),QQ=Uf.extend({name:p(),arguments:Wt(p(),Nt()).optional()}),vl=Kr.extend({method:Ae("tools/call"),params:QQ}),XQ=po.extend({method:Ae("notifications/tools/list_changed"),params:lo.optional()}),uxe=y({autoRefresh:oe().default(!0),debounceMs:I().int().nonnegative().default(300)}),Kf=z(["debug","info","notice","warning","error","critical","alert","emergency"]),eX=Kn.extend({level:Kf}),u1=Kr.extend({method:Ae("logging/setLevel"),params:eX}),tX=lo.extend({level:Kf,logger:p().optional(),data:Nt()}),rX=po.extend({method:Ae("notifications/message"),params:tX}),nX=y({name:p().optional()}),oX=y({hints:ie(nX).optional(),costPriority:I().min(0).max(1).optional(),speedPriority:I().min(0).max(1).optional(),intelligencePriority:I().min(0).max(1).optional()}),iX=y({mode:z(["auto","required","none"]).optional()}),sX=y({type:Ae("tool_result"),toolUseId:p().describe("The unique identifier for the corresponding tool call."),content:ie(c1).default([]),structuredContent:y({}).loose().optional(),isError:oe().optional(),_meta:Wt(p(),Nt()).optional()}),aX=KT("type",[i1,s1,a1]),ay=KT("type",[i1,s1,a1,qQ,sX]),cX=y({role:Wf,content:pt([ay,ie(ay)]),_meta:Wt(p(),Nt()).optional()}),uX=Uf.extend({messages:ie(cX),modelPreferences:oX.optional(),systemPrompt:p().optional(),includeContext:z(["none","thisServer","allServers"]).optional(),temperature:I().optional(),maxTokens:I().int(),stopSequences:ie(p()).optional(),metadata:Ir.optional(),tools:ie(mO).optional(),toolChoice:iX.optional()}),lX=Kr.extend({method:Ae("sampling/createMessage"),params:uX}),Yf=Yr.extend({model:p(),stopReason:er(z(["endTurn","stopSequence","maxTokens"]).or(p())),role:Wf,content:aX}),l1=Yr.extend({model:p(),stopReason:er(z(["endTurn","stopSequence","maxTokens","toolUse"]).or(p())),role:Wf,content:pt([ay,ie(ay)])}),dX=y({type:Ae("boolean"),title:p().optional(),description:p().optional(),default:oe().optional()}),pX=y({type:Ae("string"),title:p().optional(),description:p().optional(),minLength:I().optional(),maxLength:I().optional(),format:z(["email","uri","date","date-time"]).optional(),default:p().optional()}),fX=y({type:z(["number","integer"]),title:p().optional(),description:p().optional(),minimum:I().optional(),maximum:I().optional(),default:I().optional()}),mX=y({type:Ae("string"),title:p().optional(),description:p().optional(),enum:ie(p()),default:p().optional()}),hX=y({type:Ae("string"),title:p().optional(),description:p().optional(),oneOf:ie(y({const:p(),title:p()})),default:p().optional()}),gX=y({type:Ae("string"),title:p().optional(),description:p().optional(),enum:ie(p()),enumNames:ie(p()).optional(),default:p().optional()}),yX=pt([mX,hX]),bX=y({type:Ae("array"),title:p().optional(),description:p().optional(),minItems:I().optional(),maxItems:I().optional(),items:y({type:Ae("string"),enum:ie(p())}),default:ie(p()).optional()}),xX=y({type:Ae("array"),title:p().optional(),description:p().optional(),minItems:I().optional(),maxItems:I().optional(),items:y({anyOf:ie(y({const:p(),title:p()}))}),default:ie(p()).optional()}),wX=pt([bX,xX]),SX=pt([gX,yX,wX]),_X=pt([SX,dX,pX,fX]),TX=Uf.extend({mode:Ae("form").optional(),message:p(),requestedSchema:y({type:Ae("object"),properties:Wt(p(),_X),required:ie(p()).optional()})}),vX=Uf.extend({mode:Ae("url"),message:p(),elicitationId:p(),url:p().url()}),EX=pt([TX,vX]),PX=Kr.extend({method:Ae("elicitation/create"),params:EX}),AX=lo.extend({elicitationId:p()}),IX=po.extend({method:Ae("notifications/elicitation/complete"),params:AX}),El=Yr.extend({action:z(["accept","decline","cancel"]),content:Ff((e)=>e===null?void 0:e,Wt(p(),pt([p(),I(),oe(),ie(p())])).optional())}),kX=y({type:Ae("ref/resource"),uri:p()});var RX=y({type:Ae("ref/prompt"),name:p()}),CX=Kn.extend({ref:pt([RX,kX]),argument:y({name:p(),value:p()}),context:y({arguments:Wt(p(),p()).optional()}).optional()}),Ay=Kr.extend({method:Ae("completion/complete"),params:CX});function hO(e){if(e.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function gO(e){if(e.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var OX=Yr.extend({completion:yn({values:ie(p()).max(100),total:er(I().int()),hasMore:er(oe())})}),MX=y({uri:p().startsWith("file://"),name:p().optional(),_meta:Wt(p(),Nt()).optional()}),NX=Kr.extend({method:Ae("roots/list"),params:Kn.optional()}),d1=Yr.extend({roots:ie(MX)}),$X=po.extend({method:Ae("notifications/roots/list_changed"),params:lo.optional()}),lxe=pt([py,t1,Ay,u1,vy,Ty,wy,Sy,_y,NQ,zQ,vl,Ey,my,gy,yy,xy]),dxe=pt([dy,fy,r1,$X,Zf]),pxe=pt([ly,Yf,l1,El,d1,hy,by,_l]),fxe=pt([py,lX,PX,NX,my,gy,yy,xy]),mxe=pt([dy,fy,rX,BQ,OQ,XQ,WQ,Zf,IX]),hxe=pt([ly,SQ,OX,ZQ,UQ,IQ,kQ,CQ,Py,JQ,hy,by,_l]);class Ne extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`);this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,r){if(e===Be.UrlElicitationRequired&&r){let n=r;if(n.elicitations)return new yO(n.elicitations,t)}return new Ne(e,t,r)}}class yO extends Ne{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Be.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function _a(e){return e==="completed"||e==="failed"||e==="cancelled"}var xO=Symbol("Let zodToJsonSchema decide on which parser to use");var bO={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},wO=(e)=>typeof e==="string"?{...bO,name:e}:{...bO,...e};var SO=(e)=>{let t=wO(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function p1(e,t,r,n){if(!n?.errorMessages)return;if(r)e.errorMessage={...e.errorMessage,[t]:r}}function ht(e,t,r,n,o){e[t]=r,p1(e,t,n,o)}var Iy=(e,t)=>{let r=0;for(;r<e.length&&r<t.length;r++)if(e[r]!==t[r])break;return[(e.length-r).toString(),...t.slice(r)].join("/")};function tr(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Iy(t,e.currentPath):t.join("/")}}function _O(e,t){let r={type:"array"};if(e.type?._def&&e.type?._def?.typeName!==pe.ZodAny)r.items=He(e.type._def,{...t,currentPath:[...t.currentPath,"items"]});if(e.minLength)ht(r,"minItems",e.minLength.value,e.minLength.message,t);if(e.maxLength)ht(r,"maxItems",e.maxLength.value,e.maxLength.message,t);if(e.exactLength)ht(r,"minItems",e.exactLength.value,e.exactLength.message,t),ht(r,"maxItems",e.exactLength.value,e.exactLength.message,t);return r}function TO(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":if(t.target==="jsonSchema7")if(n.inclusive)ht(r,"minimum",n.value,n.message,t);else ht(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;ht(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)ht(r,"maximum",n.value,n.message,t);else ht(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;ht(r,"maximum",n.value,n.message,t)}break;case"multipleOf":ht(r,"multipleOf",n.value,n.message,t);break}return r}function vO(){return{type:"boolean"}}function ky(e,t){return He(e.type._def,t)}var EO=(e,t)=>He(e.innerType._def,t);function f1(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>f1(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return zX(e,t)}}var zX=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":ht(r,"minimum",n.value,n.message,t);break;case"max":ht(r,"maximum",n.value,n.message,t);break}return r};function PO(e,t){return{...He(e.innerType._def,t),default:e.defaultValue()}}function AO(e,t){return t.effectStrategy==="input"?He(e.schema._def,t):tr(t)}function IO(e){return{type:"string",enum:Array.from(e.values)}}var LX=(e)=>{if("type"in e&&e.type==="string")return!1;return"allOf"in e};function kO(e,t){let r=[He(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),He(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((i)=>!!i),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach((i)=>{if(LX(i)){if(o.push(...i.allOf),i.unevaluatedProperties===void 0)n=void 0}else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...c}=i;s=c}else n=void 0;o.push(s)}}),o.length?{allOf:o,...n}:void 0}function RO(e,t){let r=typeof e.value;if(r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string")return{type:Array.isArray(e.value)?"array":"object"};if(t.target==="openApi3")return{type:r==="bigint"?"integer":r,enum:[e.value]};return{type:r==="bigint"?"integer":r,const:e.value}}var m1=void 0,No={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(m1===void 0)m1=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return m1},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,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])$/,ipv4Cidr:/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ry(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":ht(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":ht(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":$o(r,"email",n.message,t);break;case"format:idn-email":$o(r,"idn-email",n.message,t);break;case"pattern:zod":bn(r,No.email,n.message,t);break}break;case"url":$o(r,"uri",n.message,t);break;case"uuid":$o(r,"uuid",n.message,t);break;case"regex":bn(r,n.regex,n.message,t);break;case"cuid":bn(r,No.cuid,n.message,t);break;case"cuid2":bn(r,No.cuid2,n.message,t);break;case"startsWith":bn(r,RegExp(`^${h1(n.value,t)}`),n.message,t);break;case"endsWith":bn(r,RegExp(`${h1(n.value,t)}$`),n.message,t);break;case"datetime":$o(r,"date-time",n.message,t);break;case"date":$o(r,"date",n.message,t);break;case"time":$o(r,"time",n.message,t);break;case"duration":$o(r,"duration",n.message,t);break;case"length":ht(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,n.value):n.value,n.message,t),ht(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{bn(r,RegExp(h1(n.value,t)),n.message,t);break}case"ip":{if(n.version!=="v6")$o(r,"ipv4",n.message,t);if(n.version!=="v4")$o(r,"ipv6",n.message,t);break}case"base64url":bn(r,No.base64url,n.message,t);break;case"jwt":bn(r,No.jwt,n.message,t);break;case"cidr":{if(n.version!=="v6")bn(r,No.ipv4Cidr,n.message,t);if(n.version!=="v4")bn(r,No.ipv6Cidr,n.message,t);break}case"emoji":bn(r,No.emoji(),n.message,t);break;case"ulid":{bn(r,No.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{$o(r,"binary",n.message,t);break}case"contentEncoding:base64":{ht(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{bn(r,No.base64,n.message,t);break}}break}case"nanoid":bn(r,No.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:((o)=>{})(n)}return r}function h1(e,t){return t.patternStrategy==="escape"?DX(e):e}var BX=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function DX(e){let t="";for(let r=0;r<e.length;r++){if(!BX.has(e[r]))t+="\\";t+=e[r]}return t}function $o(e,t,r,n){if(e.format||e.anyOf?.some((o)=>o.format)){if(!e.anyOf)e.anyOf=[];if(e.format){if(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage){if(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0)delete e.errorMessage}}e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})}else ht(e,"format",t,r,n)}function bn(e,t,r,n){if(e.pattern||e.allOf?.some((o)=>o.pattern)){if(!e.allOf)e.allOf=[];if(e.pattern){if(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage){if(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0)delete e.errorMessage}}e.allOf.push({pattern:CO(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})}else ht(e,"pattern",CO(t,n),r,n)}function CO(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source,o="",i=!1,s=!1,a=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(r.i){if(s){if(n[c].match(/[a-z]/)){if(a)o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1;else if(n[c+1]==="-"&&n[c+2]?.match(/[a-z]/))o+=n[c],a=!0;else o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
130
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){i(s);continue}if(e.external){let l=e.external.registry.get(s[0])?.id;if(t!==s[0]&&l){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1){if(e.reused==="ref"){i(s);continue}}}}function Lf(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let l=c.def??c.schema,d={...l},f=c.ref;if(c.ref=null,f){n(f);let g=e.seen.get(f),x=g.schema;if(x.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))l.allOf=l.allOf??[],l.allOf.push(x);else Object.assign(l,x);if(Object.assign(l,d),a._zod.parent===f)for(let S in l){if(S==="$ref"||S==="allOf")continue;if(!(S in d))delete l[S]}if(x.$ref&&g.def)for(let S in l){if(S==="$ref"||S==="allOf")continue;if(S in g.def&&JSON.stringify(l[S])===JSON.stringify(g.def[S]))delete l[S]}}let h=a._zod.parent;if(h&&h!==f){n(h);let g=e.seen.get(h);if(g?.schema.$ref){if(l.$ref=g.schema.$ref,g.def)for(let x in l){if(x==="$ref"||x==="allOf")continue;if(x in g.def&&JSON.stringify(l[x])===JSON.stringify(g.def[x]))delete l[x]}}}e.override({zodSchema:a,jsonSchema:l,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())n(a[0]);let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&o.id===i)delete o.id;let s=e.external?.defs??{};for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;s[c.defId]=c.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")o.$defs=s;else o.definitions=s;try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Nf(t,"input",e.processors),output:Nf(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function gn(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return gn(n.element,r);if(n.type==="set")return gn(n.valueType,r);if(n.type==="lazy")return gn(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return gn(n.innerType,r);if(n.type==="intersection")return gn(n.left,r)||gn(n.right,r);if(n.type==="record"||n.type==="map")return gn(n.keyType,r)||gn(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return gn(n.in,r)||gn(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(gn(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(gn(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(gn(o,r))return!0;if(n.rest&&gn(n.rest,r))return!0;return!1}return!1}var QC=(e,t={})=>(r)=>{let n=$f({...r,processors:t});return jt(e,n),zf(n,e),Lf(n,e)},Nf=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:i}=n??{},s=$f({...o??{},target:i,io:t,processors:r});return jt(e,s),zf(s,e),Lf(s,e)};var _Y={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},wT=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof i==="number")o.minLength=i;if(typeof s==="number")o.maxLength=s;if(a){if(o.format=_Y[a]??a,o.format==="")delete o.format;if(a==="time")delete o.format}if(l)o.contentEncoding=l;if(c&&c.size>0){let d=[...c];if(d.length===1)o.pattern=d[0].source;else if(d.length>1)o.allOf=[...d.map((f)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))]}},ST=(e,t,r,n)=>{let o=r,{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:d}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))o.type="integer";else o.type="number";let f=typeof d==="number"&&d>=(i??Number.NEGATIVE_INFINITY),h=typeof l==="number"&&l<=(s??Number.POSITIVE_INFINITY),g=t.target==="draft-04"||t.target==="openapi-3.0";if(f)if(g)o.minimum=d,o.exclusiveMinimum=!0;else o.exclusiveMinimum=d;else if(typeof i==="number")o.minimum=i;if(h)if(g)o.maximum=l,o.exclusiveMaximum=!0;else o.exclusiveMaximum=l;else if(typeof s==="number")o.maximum=s;if(typeof c==="number")o.multipleOf=c},_T=(e,t,r,n)=>{r.type="boolean"},TT=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},e5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},vT=(e,t,r,n)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},t5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},r5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},ET=(e,t,r,n)=>{r.not={}},n5=(e,t,r,n)=>{},PT=(e,t,r,n)=>{},o5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},AT=(e,t,r,n)=>{let o=e._zod.def,i=zg(o.entries);if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";r.enum=i},IT=(e,t,r,n)=>{let o=e._zod.def,i=[];for(let s of o.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else i.push(Number(s));else i.push(s);if(i.length===0);else if(i.length===1){let s=i[0];if(r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[s];else r.const=s}else{if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";if(i.every((s)=>typeof s==="boolean"))r.type="boolean";if(i.every((s)=>s===null))r.type="null";r.enum=i}},i5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},s5=(e,t,r,n)=>{let o=r,i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},a5=(e,t,r,n)=>{let o=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:c}=e._zod.bag;if(s!==void 0)i.minLength=s;if(a!==void 0)i.maxLength=a;if(c)if(c.length===1)i.contentMediaType=c[0],Object.assign(o,i);else Object.assign(o,i),o.anyOf=c.map((l)=>({contentMediaType:l}));else Object.assign(o,i)},c5=(e,t,r,n)=>{r.type="boolean"},kT=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},u5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},RT=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},l5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},d5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},CT=(e,t,r,n)=>{let o=r,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")o.minItems=s;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=jt(i.element,t,{...n,path:[...n.path,"items"]})},OT=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object",o.properties={};let s=i.shape;for(let l in s)o.properties[l]=jt(s[l],t,{...n,path:[...n.path,"properties",l]});let a=new Set(Object.keys(s)),c=new Set([...a].filter((l)=>{let d=i.shape[l]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(c.size>0)o.required=Array.from(c);if(i.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")o.additionalProperties=!1}else if(i.catchall)o.additionalProperties=jt(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},MT=(e,t,r,n)=>{let o=e._zod.def,i=o.inclusive===!1,s=o.options.map((a,c)=>jt(a,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));if(i)r.oneOf=s;else r.anyOf=s},NT=(e,t,r,n)=>{let o=e._zod.def,i=jt(o.left,t,{...n,path:[...n.path,"allOf",0]}),s=jt(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=(l)=>("allOf"in l)&&Object.keys(l).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c},p5=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((h,g)=>jt(h,t,{...n,path:[...n.path,s,g]})),l=i.rest?jt(i.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(o.prefixItems=c,l)o.items=l}else if(t.target==="openapi-3.0"){if(o.items={anyOf:c},l)o.items.anyOf.push(l);if(o.minItems=c.length,!l)o.maxItems=c.length}else if(o.items=c,l)o.additionalItems=l;let{minimum:d,maximum:f}=e._zod.bag;if(typeof d==="number")o.minItems=d;if(typeof f==="number")o.maxItems=f},$T=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object";let s=i.keyType,c=s._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let d=jt(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let f of c)o.patternProperties[f.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")o.propertyNames=jt(i.keyType,t,{...n,path:[...n.path,"propertyNames"]});o.additionalProperties=jt(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let l=s._zod.values;if(l){let d=[...l].filter((f)=>typeof f==="string"||typeof f==="number");if(d.length>0)o.required=d}},zT=(e,t,r,n)=>{let o=e._zod.def,i=jt(o.innerType,t,n),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=o.innerType,r.nullable=!0;else r.anyOf=[i,{type:"null"}]},LT=(e,t,r,n)=>{let o=e._zod.def;jt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},BT=(e,t,r,n)=>{let o=e._zod.def;jt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},DT=(e,t,r,n)=>{let o=e._zod.def;jt(o.innerType,t,n);let i=t.seen.get(e);if(i.ref=o.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(o.defaultValue))},FT=(e,t,r,n)=>{let o=e._zod.def;jt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},UT=(e,t,r,n)=>{let o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?o.out:o.in:o.out;jt(s,t,n);let a=t.seen.get(e);a.ref=s},jT=(e,t,r,n)=>{let o=e._zod.def;jt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.readOnly=!0},f5=(e,t,r,n)=>{let o=e._zod.def;jt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},ey=(e,t,r,n)=>{let o=e._zod.def;jt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},m5=(e,t,r,n)=>{let o=e._zod.innerType;jt(o,t,n);let i=t.seen.get(e);i.ref=o},XC={string:wT,number:ST,boolean:_T,bigint:TT,symbol:e5,null:vT,undefined:t5,void:r5,never:ET,any:n5,unknown:PT,date:o5,enum:AT,literal:IT,nan:i5,template_literal:s5,file:a5,success:c5,custom:kT,function:u5,transform:RT,map:l5,set:d5,array:CT,object:OT,union:MT,intersection:NT,tuple:p5,record:$T,nullable:zT,nonoptional:LT,default:BT,prefault:DT,catch:FT,pipe:UT,readonly:jT,promise:f5,optional:ey,lazy:m5};function qT(e,t){if("_idmap"in e){let n=e,o=$f({...t,processors:XC}),i={};for(let c of n._idmap.entries()){let[l,d]=c;jt(d,o)}let s={},a={registry:n,uri:t?.uri,defs:i};o.external=a;for(let c of n._idmap.entries()){let[l,d]=c;zf(o,d),s[l]=Lf(o,d)}if(Object.keys(i).length>0){let c=o.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=$f({...t,processors:XC});return jt(e,r),zf(r,e),Lf(r,e)}var uJ=U("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");Mt.init(e,t),e.def=t,e.type=t.type,e.parse=(r,n)=>jg(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Uc(e,r,n),e.parseAsync=async(r,n)=>qg(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>jc(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),e.with=e.check,e.clone=(r,n)=>co(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.apply=(r)=>r(e)});var lJ=U("ZodMiniObject",(e,t)=>{g_.init(e,t),uJ.init(e,t),Et(e,"shape",()=>t.shape)});function HT(e,t){let r={type:"object",shape:e??{},...Ie(t)};return new lJ(r)}function uo(e){return!!e._zod}function Gc(e){let t=Object.values(e);if(t.length===0)return HT({});let r=t.every(uo),n=t.every((o)=>!uo(o));if(r)return HT(e);if(n)return l6(e);throw Error("Mixed Zod versions detected in object shape.")}function ba(e,t){if(uo(e))return Uc(e,t);return e.safeParse(t)}async function ty(e,t){if(uo(e))return await jc(e,t);return await e.safeParseAsync(t)}function xa(e){if(!e)return;let t;if(uo(e))t=e._zod?.def?.shape;else t=e.shape;if(!t)return;if(typeof t==="function")try{return t()}catch{return}return t}function xl(e){if(!e)return;if(typeof e==="object"){let t=e,r=e;if(!t._def&&!r._zod){let n=Object.values(e);if(n.length>0&&n.every((o)=>typeof o==="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse==="function")))return Gc(e)}}if(uo(e)){let r=e._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return e}else if(e.shape!==void 0)return e;return}function ry(e){if(e&&typeof e==="object"){if("message"in e&&typeof e.message==="string")return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==="object"&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function g5(e){return e.description}function y5(e){if(uo(e))return e._zod?.def?.type==="optional";let t=e;if(typeof e.isOptional==="function")return e.isOptional();return t._def?.typeName==="ZodOptional"}function ny(e){if(uo(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n;return}var b5=U("ZodISODateTime",(e,t)=>{zC.init(e,t),Xt.init(e,t)});function oy(e){return ZC(b5,e)}var x5=U("ZodISODate",(e,t)=>{LC.init(e,t),Xt.init(e,t)});function GT(e){return WC(x5,e)}var w5=U("ZodISOTime",(e,t)=>{BC.init(e,t),Xt.init(e,t)});function VT(e){return KC(w5,e)}var S5=U("ZodISODuration",(e,t)=>{DC.init(e,t),Xt.init(e,t)});function ZT(e){return YC(S5,e)}var bJ=(e,t)=>{Ug.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>k6(e,r)},flatten:{value:(r)=>I6(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Tf,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Tf,2)}},isEmpty:{get(){return e.issues.length===0}}})};var Wn=U("ZodError",bJ,{Parent:Error});var _5=Pf(Wn),T5=Af(Wn),v5=If(Wn),E5=kf(Wn),P5=R6(Wn),A5=C6(Wn),I5=O6(Wn),k5=M6(Wn),R5=N6(Wn),C5=$6(Wn),O5=z6(Wn),M5=L6(Wn);var N5=new WeakMap;function Df(e,t,r){let n=Object.getPrototypeOf(e),o=N5.get(n);if(!o)o=new Set,N5.set(n,o);if(o.has(t))return;o.add(t);for(let i in r){let s=r[i];Object.defineProperty(n,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var Jt=U("ZodType",(e,t)=>(Mt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Nf(e,"input"),output:Nf(e,"output")}}),e.toJSONSchema=QC(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,n)=>_5(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>v5(e,r,n),e.parseAsync=async(r,n)=>T5(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>E5(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>P5(e,r,n),e.decode=(r,n)=>A5(e,r,n),e.encodeAsync=async(r,n)=>I5(e,r,n),e.decodeAsync=async(r,n)=>k5(e,r,n),e.safeEncode=(r,n)=>R5(e,r,n),e.safeDecode=(r,n)=>C5(e,r,n),e.safeEncodeAsync=async(r,n)=>O5(e,r,n),e.safeDecodeAsync=async(r,n)=>M5(e,r,n),Df(e,"ZodType",{check(...r){let n=this.def;return this.clone(fa(n,{checks:[...n.checks??[],...r.map((o)=>typeof o==="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return co(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(cQ(r,n))},superRefine(r,n){return this.check(uQ(r,n))},overwrite(r){return this.check(ya(r))},optional(){return er(this)},exactOptional(){return YJ(this)},nullable(){return B5(this)},nullish(){return er(B5(this))},nonoptional(r){return rQ(this,r)},array(){return ie(this)},or(r){return pt([this,r])},and(r){return iy(this,r)},transform(r){return D5(this,Z5(r))},default(r){return XJ(this,r)},prefault(r){return tQ(this,r)},catch(r){return oQ(this,r)},pipe(r){return D5(this,r)},readonly(){return aQ(this)},describe(r){let n=this.clone();return qc.add(n,{description:r}),n},meta(...r){if(r.length===0)return qc.get(this);let n=this.clone();return qc.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return qc.get(e)?.description},configurable:!0}),e)),F5=U("_ZodString",(e,t)=>{Of.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>wT(e,n,o,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Df(e,"_ZodString",{regex(...n){return this.check(sT(...n))},includes(...n){return this.check(uT(...n))},startsWith(...n){return this.check(lT(...n))},endsWith(...n){return this.check(dT(...n))},min(...n){return this.check(bl(...n))},max(...n){return this.check(Qg(...n))},length(...n){return this.check(Xg(...n))},nonempty(...n){return this.check(bl(1,...n))},lowercase(n){return this.check(aT(n))},uppercase(n){return this.check(cT(n))},trim(){return this.check(fT())},normalize(...n){return this.check(pT(...n))},toLowerCase(){return this.check(mT())},toUpperCase(){return this.check(hT())},slugify(){return this.check(gT())}})}),wJ=U("ZodString",(e,t)=>{Of.init(e,t),F5.init(e,t),e.email=(r)=>e.check(M_(SJ,r)),e.url=(r)=>e.check(L_(_J,r)),e.jwt=(r)=>e.check(Q_(LJ,r)),e.emoji=(r)=>e.check(B_(TJ,r)),e.guid=(r)=>e.check(Yg($5,r)),e.uuid=(r)=>e.check(Jg(Bf,r)),e.uuidv4=(r)=>e.check(N_(Bf,r)),e.uuidv6=(r)=>e.check($_(Bf,r)),e.uuidv7=(r)=>e.check(z_(Bf,r)),e.nanoid=(r)=>e.check(D_(vJ,r)),e.guid=(r)=>e.check(Yg($5,r)),e.cuid=(r)=>e.check(F_(EJ,r)),e.cuid2=(r)=>e.check(U_(PJ,r)),e.ulid=(r)=>e.check(j_(AJ,r)),e.base64=(r)=>e.check(K_(NJ,r)),e.base64url=(r)=>e.check(Y_($J,r)),e.xid=(r)=>e.check(q_(IJ,r)),e.ksuid=(r)=>e.check(H_(kJ,r)),e.ipv4=(r)=>e.check(G_(RJ,r)),e.ipv6=(r)=>e.check(V_(CJ,r)),e.cidrv4=(r)=>e.check(Z_(OJ,r)),e.cidrv6=(r)=>e.check(W_(MJ,r)),e.e164=(r)=>e.check(J_(zJ,r)),e.datetime=(r)=>e.check(oy(r)),e.date=(r)=>e.check(GT(r)),e.time=(r)=>e.check(VT(r)),e.duration=(r)=>e.check(ZT(r))});function p(e){return O_(wJ,e)}var Xt=U("ZodStringFormat",(e,t)=>{Zt.init(e,t),F5.init(e,t)}),SJ=U("ZodEmail",(e,t)=>{VS.init(e,t),Xt.init(e,t)});var $5=U("ZodGUID",(e,t)=>{HS.init(e,t),Xt.init(e,t)});var Bf=U("ZodUUID",(e,t)=>{GS.init(e,t),Xt.init(e,t)});function U5(e){return Jg(Bf,e)}var _J=U("ZodURL",(e,t)=>{ZS.init(e,t),Xt.init(e,t)});var TJ=U("ZodEmoji",(e,t)=>{WS.init(e,t),Xt.init(e,t)});var vJ=U("ZodNanoID",(e,t)=>{KS.init(e,t),Xt.init(e,t)});var EJ=U("ZodCUID",(e,t)=>{YS.init(e,t),Xt.init(e,t)});var PJ=U("ZodCUID2",(e,t)=>{JS.init(e,t),Xt.init(e,t)});var AJ=U("ZodULID",(e,t)=>{QS.init(e,t),Xt.init(e,t)});var IJ=U("ZodXID",(e,t)=>{XS.init(e,t),Xt.init(e,t)});var kJ=U("ZodKSUID",(e,t)=>{e_.init(e,t),Xt.init(e,t)});var RJ=U("ZodIPv4",(e,t)=>{t_.init(e,t),Xt.init(e,t)});var CJ=U("ZodIPv6",(e,t)=>{r_.init(e,t),Xt.init(e,t)});var OJ=U("ZodCIDRv4",(e,t)=>{n_.init(e,t),Xt.init(e,t)});var MJ=U("ZodCIDRv6",(e,t)=>{o_.init(e,t),Xt.init(e,t)});var NJ=U("ZodBase64",(e,t)=>{i_.init(e,t),Xt.init(e,t)});var $J=U("ZodBase64URL",(e,t)=>{s_.init(e,t),Xt.init(e,t)});var zJ=U("ZodE164",(e,t)=>{a_.init(e,t),Xt.init(e,t)});var LJ=U("ZodJWT",(e,t)=>{c_.init(e,t),Xt.init(e,t)});var j5=U("ZodNumber",(e,t)=>{Vg.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>ST(e,n,o,i),Df(e,"ZodNumber",{gt(n,o){return this.check(yl(n,o))},gte(n,o){return this.check(li(n,o))},min(n,o){return this.check(li(n,o))},lt(n,o){return this.check(gl(n,o))},lte(n,o){return this.check(ga(n,o))},max(n,o){return this.check(ga(n,o))},int(n){return this.check(z5(n))},safe(n){return this.check(z5(n))},positive(n){return this.check(yl(0,n))},nonnegative(n){return this.check(li(0,n))},negative(n){return this.check(gl(0,n))},nonpositive(n){return this.check(ga(0,n))},multipleOf(n,o){return this.check(Mf(n,o))},step(n,o){return this.check(Mf(n,o))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??0.5),e.isFinite=!0,e.format=r.format??null});function I(e){return X_(j5,e)}var BJ=U("ZodNumberFormat",(e,t)=>{u_.init(e,t),j5.init(e,t)});function z5(e){return eT(BJ,e)}var DJ=U("ZodBoolean",(e,t)=>{l_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>_T(e,r,n,o)});function oe(e){return tT(DJ,e)}var FJ=U("ZodBigInt",(e,t)=>{d_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>TT(e,n,o,i),e.gte=(n,o)=>e.check(li(n,o)),e.min=(n,o)=>e.check(li(n,o)),e.gt=(n,o)=>e.check(yl(n,o)),e.gte=(n,o)=>e.check(li(n,o)),e.min=(n,o)=>e.check(li(n,o)),e.lt=(n,o)=>e.check(gl(n,o)),e.lte=(n,o)=>e.check(ga(n,o)),e.max=(n,o)=>e.check(ga(n,o)),e.positive=(n)=>e.check(yl(BigInt(0),n)),e.negative=(n)=>e.check(gl(BigInt(0),n)),e.nonpositive=(n)=>e.check(ga(BigInt(0),n)),e.nonnegative=(n)=>e.check(li(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(Mf(n,o));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function q5(e){return rT(FJ,e)}var UJ=U("ZodNull",(e,t)=>{p_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>vT(e,r,n,o)});function H5(e){return nT(UJ,e)}var jJ=U("ZodUnknown",(e,t)=>{f_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>PT(e,r,n,o)});function Nt(){return oT(jJ)}var qJ=U("ZodNever",(e,t)=>{m_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ET(e,r,n,o)});function Qe(e){return iT(qJ,e)}var HJ=U("ZodArray",(e,t)=>{h_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>CT(e,r,n,o),e.element=t.element,Df(e,"ZodArray",{min(r,n){return this.check(bl(r,n))},nonempty(r){return this.check(bl(1,r))},max(r,n){return this.check(Qg(r,n))},length(r,n){return this.check(Xg(r,n))},unwrap(){return this.element}})});function ie(e,t){return JC(HJ,e,t)}var G5=U("ZodObject",(e,t)=>{qC.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>OT(e,r,n,o),Et(e,"shape",()=>t.shape),Df(e,"ZodObject",{keyof(){return z(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Nt()})},loose(){return this.clone({...this._zod.def,catchall:Nt()})},strict(){return this.clone({...this._zod.def,catchall:Qe()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return S6(this,r)},safeExtend(r){return _6(this,r)},merge(r){return mY(this,r)},pick(r){return x6(this,r)},omit(r){return w6(this,r)},partial(...r){return T6(sy,this,r[0])},required(...r){return v6(W5,this,r[0])}})});function y(e,t){let r={type:"object",shape:e??{},...Ie(t)};return new G5(r)}function yn(e,t){return new G5({type:"object",shape:e,catchall:Nt(),...Ie(t)})}var V5=U("ZodUnion",(e,t)=>{Zg.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>MT(e,r,n,o),e.options=t.options});function pt(e,t){return new V5({type:"union",options:e,...Ie(t)})}var GJ=U("ZodDiscriminatedUnion",(e,t)=>{V5.init(e,t),y_.init(e,t)});function KT(e,t,r){return new GJ({type:"union",options:t,discriminator:e,...Ie(r)})}var VJ=U("ZodIntersection",(e,t)=>{b_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>NT(e,r,n,o)});function iy(e,t){return new VJ({type:"intersection",left:e,right:t})}var L5=U("ZodRecord",(e,t)=>{x_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>$T(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function Wt(e,t,r){if(!t||!t._zod)return new L5({type:"record",keyType:p(),valueType:e,...Ie(t)});return new L5({type:"record",keyType:e,valueType:t,...Ie(r)})}var WT=U("ZodEnum",(e,t)=>{w_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>AT(e,n,o,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new WT({...t,checks:[],...Ie(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new WT({...t,checks:[],...Ie(o),entries:i})}});function z(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new WT({type:"enum",entries:r,...Ie(t)})}var ZJ=U("ZodLiteral",(e,t)=>{S_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>IT(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Ae(e,t){return new ZJ({type:"literal",values:Array.isArray(e)?e:[e],...Ie(t)})}var WJ=U("ZodTransform",(e,t)=>{__.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>RT(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new _f(e.constructor.name);r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(Fc(i,r.value,t));else{let s=i;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),r.issues.push(Fc(s))}};let o=t.transform(r.value,r);if(o instanceof Promise)return o.then((i)=>(r.value=i,r.fallback=!0,r));return r.value=o,r.fallback=!0,r}});function Z5(e){return new WJ({type:"transform",transform:e})}var sy=U("ZodOptional",(e,t)=>{Wg.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ey(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function er(e){return new sy({type:"optional",innerType:e})}var KJ=U("ZodExactOptional",(e,t)=>{T_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ey(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function YJ(e){return new KJ({type:"optional",innerType:e})}var JJ=U("ZodNullable",(e,t)=>{v_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>zT(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function B5(e){return new JJ({type:"nullable",innerType:e})}var QJ=U("ZodDefault",(e,t)=>{E_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>BT(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function XJ(e,t){return new QJ({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Dg(t)}})}var eQ=U("ZodPrefault",(e,t)=>{P_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>DT(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function tQ(e,t){return new eQ({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Dg(t)}})}var W5=U("ZodNonOptional",(e,t)=>{A_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>LT(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function rQ(e,t){return new W5({type:"nonoptional",innerType:e,...Ie(t)})}var nQ=U("ZodCatch",(e,t)=>{I_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>FT(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function oQ(e,t){return new nQ({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var K5=U("ZodPipe",(e,t)=>{Kg.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>UT(e,r,n,o),e.in=t.in,e.out=t.out});function D5(e,t){return new K5({type:"pipe",in:e,out:t})}var iQ=U("ZodPreprocess",(e,t)=>{K5.init(e,t),HC.init(e,t)}),sQ=U("ZodReadonly",(e,t)=>{k_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>jT(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function aQ(e){return new sQ({type:"readonly",innerType:e})}var Y5=U("ZodCustom",(e,t)=>{R_.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>kT(e,r,n,o)});function J5(e,t){return yT(Y5,e??(()=>!0),t)}function cQ(e,t={}){return bT(Y5,e,t)}function uQ(e,t){return xT(e,t)}function Ff(e,t){return new iQ({type:"pipe",in:Z5(e),out:t})}var wa={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var Q5;(function(e){})(Q5||(Q5={}));Zn(C_());var YT="2025-11-25";var X5=[YT,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Sa="io.modelcontextprotocol/related-task",cy="2.0",Ir=J5((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),eO=pt([p(),I().int()]),tO=p(),ixe=yn({ttl:I().optional(),pollInterval:I().optional()}),lQ=y({ttl:I().optional()}),dQ=y({taskId:p()}),JT=yn({progressToken:eO.optional(),[Sa]:dQ.optional()}),Kn=y({_meta:JT.optional()}),Uf=Kn.extend({task:lQ.optional()}),rO=(e)=>Uf.safeParse(e).success,Kr=y({method:p(),params:Kn.loose().optional()}),lo=y({_meta:JT.optional()}),po=y({method:p(),params:lo.loose().optional()}),Yr=yn({_meta:JT.optional()}),uy=pt([p(),I().int()]),nO=y({jsonrpc:Ae(cy),id:uy,...Kr.shape}).strict(),QT=(e)=>nO.safeParse(e).success,oO=y({jsonrpc:Ae(cy),...po.shape}).strict(),iO=(e)=>oO.safeParse(e).success,XT=y({jsonrpc:Ae(cy),id:uy,result:Yr}).strict(),jf=(e)=>XT.safeParse(e).success;var Be;(function(e){e[e.ConnectionClosed=-32000]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Be||(Be={}));var e1=y({jsonrpc:Ae(cy),id:uy.optional(),error:y({code:I().int(),message:p(),data:Nt().optional()})}).strict();var sO=(e)=>e1.safeParse(e).success;var aO=pt([nO,oO,XT,e1]),sxe=pt([XT,e1]),ly=Yr.strict(),pQ=lo.extend({requestId:uy.optional(),reason:p().optional()}),dy=po.extend({method:Ae("notifications/cancelled"),params:pQ}),fQ=y({src:p(),mimeType:p().optional(),sizes:ie(p()).optional(),theme:z(["light","dark"]).optional()}),qf=y({icons:ie(fQ).optional()}),Sl=y({name:p(),title:p().optional()}),cO=Sl.extend({...Sl.shape,...qf.shape,version:p(),websiteUrl:p().optional(),description:p().optional()}),mQ=iy(y({applyDefaults:oe().optional()}),Wt(p(),Nt())),hQ=Ff((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},iy(y({form:mQ.optional(),url:Ir.optional()}),Wt(p(),Nt()).optional())),gQ=yn({list:Ir.optional(),cancel:Ir.optional(),requests:yn({sampling:yn({createMessage:Ir.optional()}).optional(),elicitation:yn({create:Ir.optional()}).optional()}).optional()}),yQ=yn({list:Ir.optional(),cancel:Ir.optional(),requests:yn({tools:yn({call:Ir.optional()}).optional()}).optional()}),bQ=y({experimental:Wt(p(),Ir).optional(),sampling:y({context:Ir.optional(),tools:Ir.optional()}).optional(),elicitation:hQ.optional(),roots:y({listChanged:oe().optional()}).optional(),tasks:gQ.optional(),extensions:Wt(p(),Ir).optional()}),xQ=Kn.extend({protocolVersion:p(),capabilities:bQ,clientInfo:cO}),t1=Kr.extend({method:Ae("initialize"),params:xQ});var wQ=y({experimental:Wt(p(),Ir).optional(),logging:Ir.optional(),completions:Ir.optional(),prompts:y({listChanged:oe().optional()}).optional(),resources:y({subscribe:oe().optional(),listChanged:oe().optional()}).optional(),tools:y({listChanged:oe().optional()}).optional(),tasks:yQ.optional(),extensions:Wt(p(),Ir).optional()}),SQ=Yr.extend({protocolVersion:p(),capabilities:wQ,serverInfo:cO,instructions:p().optional()}),r1=po.extend({method:Ae("notifications/initialized"),params:lo.optional()});var py=Kr.extend({method:Ae("ping"),params:Kn.optional()}),_Q=y({progress:I(),total:er(I()),message:er(p())}),TQ=y({...lo.shape,..._Q.shape,progressToken:eO}),fy=po.extend({method:Ae("notifications/progress"),params:TQ}),vQ=Kn.extend({cursor:tO.optional()}),Hf=Kr.extend({params:vQ.optional()}),Gf=Yr.extend({nextCursor:tO.optional()}),EQ=z(["working","input_required","completed","failed","cancelled"]),Vf=y({taskId:p(),status:EQ,ttl:pt([I(),H5()]),createdAt:p(),lastUpdatedAt:p(),pollInterval:er(I()),statusMessage:er(p())}),_l=Yr.extend({task:Vf}),PQ=lo.merge(Vf),Zf=po.extend({method:Ae("notifications/tasks/status"),params:PQ}),my=Kr.extend({method:Ae("tasks/get"),params:Kn.extend({taskId:p()})}),hy=Yr.merge(Vf),gy=Kr.extend({method:Ae("tasks/result"),params:Kn.extend({taskId:p()})}),axe=Yr.loose(),yy=Hf.extend({method:Ae("tasks/list")}),by=Gf.extend({tasks:ie(Vf)}),xy=Kr.extend({method:Ae("tasks/cancel"),params:Kn.extend({taskId:p()})}),uO=Yr.merge(Vf),lO=y({uri:p(),mimeType:er(p()),_meta:Wt(p(),Nt()).optional()}),dO=lO.extend({text:p()}),n1=p().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),pO=lO.extend({blob:n1}),Wf=z(["user","assistant"]),Tl=y({audience:ie(Wf).optional(),priority:I().min(0).max(1).optional(),lastModified:oy({offset:!0}).optional()}),fO=y({...Sl.shape,...qf.shape,uri:p(),description:er(p()),mimeType:er(p()),size:er(I()),annotations:Tl.optional(),_meta:er(yn({}))}),AQ=y({...Sl.shape,...qf.shape,uriTemplate:p(),description:er(p()),mimeType:er(p()),annotations:Tl.optional(),_meta:er(yn({}))}),wy=Hf.extend({method:Ae("resources/list")}),IQ=Gf.extend({resources:ie(fO)}),Sy=Hf.extend({method:Ae("resources/templates/list")}),kQ=Gf.extend({resourceTemplates:ie(AQ)}),o1=Kn.extend({uri:p()}),RQ=o1,_y=Kr.extend({method:Ae("resources/read"),params:RQ}),CQ=Yr.extend({contents:ie(pt([dO,pO]))}),OQ=po.extend({method:Ae("notifications/resources/list_changed"),params:lo.optional()}),MQ=o1,NQ=Kr.extend({method:Ae("resources/subscribe"),params:MQ}),$Q=o1,zQ=Kr.extend({method:Ae("resources/unsubscribe"),params:$Q}),LQ=lo.extend({uri:p()}),BQ=po.extend({method:Ae("notifications/resources/updated"),params:LQ}),DQ=y({name:p(),description:er(p()),required:er(oe())}),FQ=y({...Sl.shape,...qf.shape,description:er(p()),arguments:er(ie(DQ)),_meta:er(yn({}))}),Ty=Hf.extend({method:Ae("prompts/list")}),UQ=Gf.extend({prompts:ie(FQ)}),jQ=Kn.extend({name:p(),arguments:Wt(p(),p()).optional()}),vy=Kr.extend({method:Ae("prompts/get"),params:jQ}),i1=y({type:Ae("text"),text:p(),annotations:Tl.optional(),_meta:Wt(p(),Nt()).optional()}),s1=y({type:Ae("image"),data:n1,mimeType:p(),annotations:Tl.optional(),_meta:Wt(p(),Nt()).optional()}),a1=y({type:Ae("audio"),data:n1,mimeType:p(),annotations:Tl.optional(),_meta:Wt(p(),Nt()).optional()}),qQ=y({type:Ae("tool_use"),name:p(),id:p(),input:Wt(p(),Nt()),_meta:Wt(p(),Nt()).optional()}),HQ=y({type:Ae("resource"),resource:pt([dO,pO]),annotations:Tl.optional(),_meta:Wt(p(),Nt()).optional()}),GQ=fO.extend({type:Ae("resource_link")}),c1=pt([i1,s1,a1,GQ,HQ]),VQ=y({role:Wf,content:c1}),ZQ=Yr.extend({description:p().optional(),messages:ie(VQ)}),WQ=po.extend({method:Ae("notifications/prompts/list_changed"),params:lo.optional()}),KQ=y({title:p().optional(),readOnlyHint:oe().optional(),destructiveHint:oe().optional(),idempotentHint:oe().optional(),openWorldHint:oe().optional()}),YQ=y({taskSupport:z(["required","optional","forbidden"]).optional()}),mO=y({...Sl.shape,...qf.shape,description:p().optional(),inputSchema:y({type:Ae("object"),properties:Wt(p(),Ir).optional(),required:ie(p()).optional()}).catchall(Nt()),outputSchema:y({type:Ae("object"),properties:Wt(p(),Ir).optional(),required:ie(p()).optional()}).catchall(Nt()).optional(),annotations:KQ.optional(),execution:YQ.optional(),_meta:Wt(p(),Nt()).optional()}),Ey=Hf.extend({method:Ae("tools/list")}),JQ=Gf.extend({tools:ie(mO)}),Py=Yr.extend({content:ie(c1).default([]),structuredContent:Wt(p(),Nt()).optional(),isError:oe().optional()}),cxe=Py.or(Yr.extend({toolResult:Nt()})),QQ=Uf.extend({name:p(),arguments:Wt(p(),Nt()).optional()}),vl=Kr.extend({method:Ae("tools/call"),params:QQ}),XQ=po.extend({method:Ae("notifications/tools/list_changed"),params:lo.optional()}),uxe=y({autoRefresh:oe().default(!0),debounceMs:I().int().nonnegative().default(300)}),Kf=z(["debug","info","notice","warning","error","critical","alert","emergency"]),eX=Kn.extend({level:Kf}),u1=Kr.extend({method:Ae("logging/setLevel"),params:eX}),tX=lo.extend({level:Kf,logger:p().optional(),data:Nt()}),rX=po.extend({method:Ae("notifications/message"),params:tX}),nX=y({name:p().optional()}),oX=y({hints:ie(nX).optional(),costPriority:I().min(0).max(1).optional(),speedPriority:I().min(0).max(1).optional(),intelligencePriority:I().min(0).max(1).optional()}),iX=y({mode:z(["auto","required","none"]).optional()}),sX=y({type:Ae("tool_result"),toolUseId:p().describe("The unique identifier for the corresponding tool call."),content:ie(c1).default([]),structuredContent:y({}).loose().optional(),isError:oe().optional(),_meta:Wt(p(),Nt()).optional()}),aX=KT("type",[i1,s1,a1]),ay=KT("type",[i1,s1,a1,qQ,sX]),cX=y({role:Wf,content:pt([ay,ie(ay)]),_meta:Wt(p(),Nt()).optional()}),uX=Uf.extend({messages:ie(cX),modelPreferences:oX.optional(),systemPrompt:p().optional(),includeContext:z(["none","thisServer","allServers"]).optional(),temperature:I().optional(),maxTokens:I().int(),stopSequences:ie(p()).optional(),metadata:Ir.optional(),tools:ie(mO).optional(),toolChoice:iX.optional()}),lX=Kr.extend({method:Ae("sampling/createMessage"),params:uX}),Yf=Yr.extend({model:p(),stopReason:er(z(["endTurn","stopSequence","maxTokens"]).or(p())),role:Wf,content:aX}),l1=Yr.extend({model:p(),stopReason:er(z(["endTurn","stopSequence","maxTokens","toolUse"]).or(p())),role:Wf,content:pt([ay,ie(ay)])}),dX=y({type:Ae("boolean"),title:p().optional(),description:p().optional(),default:oe().optional()}),pX=y({type:Ae("string"),title:p().optional(),description:p().optional(),minLength:I().optional(),maxLength:I().optional(),format:z(["email","uri","date","date-time"]).optional(),default:p().optional()}),fX=y({type:z(["number","integer"]),title:p().optional(),description:p().optional(),minimum:I().optional(),maximum:I().optional(),default:I().optional()}),mX=y({type:Ae("string"),title:p().optional(),description:p().optional(),enum:ie(p()),default:p().optional()}),hX=y({type:Ae("string"),title:p().optional(),description:p().optional(),oneOf:ie(y({const:p(),title:p()})),default:p().optional()}),gX=y({type:Ae("string"),title:p().optional(),description:p().optional(),enum:ie(p()),enumNames:ie(p()).optional(),default:p().optional()}),yX=pt([mX,hX]),bX=y({type:Ae("array"),title:p().optional(),description:p().optional(),minItems:I().optional(),maxItems:I().optional(),items:y({type:Ae("string"),enum:ie(p())}),default:ie(p()).optional()}),xX=y({type:Ae("array"),title:p().optional(),description:p().optional(),minItems:I().optional(),maxItems:I().optional(),items:y({anyOf:ie(y({const:p(),title:p()}))}),default:ie(p()).optional()}),wX=pt([bX,xX]),SX=pt([gX,yX,wX]),_X=pt([SX,dX,pX,fX]),TX=Uf.extend({mode:Ae("form").optional(),message:p(),requestedSchema:y({type:Ae("object"),properties:Wt(p(),_X),required:ie(p()).optional()})}),vX=Uf.extend({mode:Ae("url"),message:p(),elicitationId:p(),url:p().url()}),EX=pt([TX,vX]),PX=Kr.extend({method:Ae("elicitation/create"),params:EX}),AX=lo.extend({elicitationId:p()}),IX=po.extend({method:Ae("notifications/elicitation/complete"),params:AX}),El=Yr.extend({action:z(["accept","decline","cancel"]),content:Ff((e)=>e===null?void 0:e,Wt(p(),pt([p(),I(),oe(),ie(p())])).optional())}),kX=y({type:Ae("ref/resource"),uri:p()});var RX=y({type:Ae("ref/prompt"),name:p()}),CX=Kn.extend({ref:pt([RX,kX]),argument:y({name:p(),value:p()}),context:y({arguments:Wt(p(),p()).optional()}).optional()}),Ay=Kr.extend({method:Ae("completion/complete"),params:CX});function hO(e){if(e.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function gO(e){if(e.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var OX=Yr.extend({completion:yn({values:ie(p()).max(100),total:er(I().int()),hasMore:er(oe())})}),MX=y({uri:p().startsWith("file://"),name:p().optional(),_meta:Wt(p(),Nt()).optional()}),NX=Kr.extend({method:Ae("roots/list"),params:Kn.optional()}),d1=Yr.extend({roots:ie(MX)}),$X=po.extend({method:Ae("notifications/roots/list_changed"),params:lo.optional()}),lxe=pt([py,t1,Ay,u1,vy,Ty,wy,Sy,_y,NQ,zQ,vl,Ey,my,gy,yy,xy]),dxe=pt([dy,fy,r1,$X,Zf]),pxe=pt([ly,Yf,l1,El,d1,hy,by,_l]),fxe=pt([py,lX,PX,NX,my,gy,yy,xy]),mxe=pt([dy,fy,rX,BQ,OQ,XQ,WQ,Zf,IX]),hxe=pt([ly,SQ,OX,ZQ,UQ,IQ,kQ,CQ,Py,JQ,hy,by,_l]);class Ne extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`);this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,r){if(e===Be.UrlElicitationRequired&&r){let n=r;if(n.elicitations)return new yO(n.elicitations,t)}return new Ne(e,t,r)}}class yO extends Ne{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Be.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function _a(e){return e==="completed"||e==="failed"||e==="cancelled"}var xO=Symbol("Let zodToJsonSchema decide on which parser to use");var bO={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},wO=(e)=>typeof e==="string"?{...bO,name:e}:{...bO,...e};var SO=(e)=>{let t=wO(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function p1(e,t,r,n){if(!n?.errorMessages)return;if(r)e.errorMessage={...e.errorMessage,[t]:r}}function ht(e,t,r,n,o){e[t]=r,p1(e,t,n,o)}var Iy=(e,t)=>{let r=0;for(;r<e.length&&r<t.length;r++)if(e[r]!==t[r])break;return[(e.length-r).toString(),...t.slice(r)].join("/")};function tr(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Iy(t,e.currentPath):t.join("/")}}function _O(e,t){let r={type:"array"};if(e.type?._def&&e.type?._def?.typeName!==pe.ZodAny)r.items=He(e.type._def,{...t,currentPath:[...t.currentPath,"items"]});if(e.minLength)ht(r,"minItems",e.minLength.value,e.minLength.message,t);if(e.maxLength)ht(r,"maxItems",e.maxLength.value,e.maxLength.message,t);if(e.exactLength)ht(r,"minItems",e.exactLength.value,e.exactLength.message,t),ht(r,"maxItems",e.exactLength.value,e.exactLength.message,t);return r}function TO(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":if(t.target==="jsonSchema7")if(n.inclusive)ht(r,"minimum",n.value,n.message,t);else ht(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;ht(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)ht(r,"maximum",n.value,n.message,t);else ht(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;ht(r,"maximum",n.value,n.message,t)}break;case"multipleOf":ht(r,"multipleOf",n.value,n.message,t);break}return r}function vO(){return{type:"boolean"}}function ky(e,t){return He(e.type._def,t)}var EO=(e,t)=>He(e.innerType._def,t);function f1(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>f1(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return zX(e,t)}}var zX=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":ht(r,"minimum",n.value,n.message,t);break;case"max":ht(r,"maximum",n.value,n.message,t);break}return r};function PO(e,t){return{...He(e.innerType._def,t),default:e.defaultValue()}}function AO(e,t){return t.effectStrategy==="input"?He(e.schema._def,t):tr(t)}function IO(e){return{type:"string",enum:Array.from(e.values)}}var LX=(e)=>{if("type"in e&&e.type==="string")return!1;return"allOf"in e};function kO(e,t){let r=[He(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),He(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((i)=>!!i),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach((i)=>{if(LX(i)){if(o.push(...i.allOf),i.unevaluatedProperties===void 0)n=void 0}else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...c}=i;s=c}else n=void 0;o.push(s)}}),o.length?{allOf:o,...n}:void 0}function RO(e,t){let r=typeof e.value;if(r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string")return{type:Array.isArray(e.value)?"array":"object"};if(t.target==="openApi3")return{type:r==="bigint"?"integer":r,enum:[e.value]};return{type:r==="bigint"?"integer":r,const:e.value}}var m1=void 0,No={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(m1===void 0)m1=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return m1},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,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])$/,ipv4Cidr:/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ry(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":ht(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":ht(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":$o(r,"email",n.message,t);break;case"format:idn-email":$o(r,"idn-email",n.message,t);break;case"pattern:zod":bn(r,No.email,n.message,t);break}break;case"url":$o(r,"uri",n.message,t);break;case"uuid":$o(r,"uuid",n.message,t);break;case"regex":bn(r,n.regex,n.message,t);break;case"cuid":bn(r,No.cuid,n.message,t);break;case"cuid2":bn(r,No.cuid2,n.message,t);break;case"startsWith":bn(r,RegExp(`^${h1(n.value,t)}`),n.message,t);break;case"endsWith":bn(r,RegExp(`${h1(n.value,t)}$`),n.message,t);break;case"datetime":$o(r,"date-time",n.message,t);break;case"date":$o(r,"date",n.message,t);break;case"time":$o(r,"time",n.message,t);break;case"duration":$o(r,"duration",n.message,t);break;case"length":ht(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,n.value):n.value,n.message,t),ht(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{bn(r,RegExp(h1(n.value,t)),n.message,t);break}case"ip":{if(n.version!=="v6")$o(r,"ipv4",n.message,t);if(n.version!=="v4")$o(r,"ipv6",n.message,t);break}case"base64url":bn(r,No.base64url,n.message,t);break;case"jwt":bn(r,No.jwt,n.message,t);break;case"cidr":{if(n.version!=="v6")bn(r,No.ipv4Cidr,n.message,t);if(n.version!=="v4")bn(r,No.ipv6Cidr,n.message,t);break}case"emoji":bn(r,No.emoji(),n.message,t);break;case"ulid":{bn(r,No.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{$o(r,"binary",n.message,t);break}case"contentEncoding:base64":{ht(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{bn(r,No.base64,n.message,t);break}}break}case"nanoid":bn(r,No.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:((o)=>{})(n)}return r}function h1(e,t){return t.patternStrategy==="escape"?DX(e):e}var BX=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function DX(e){let t="";for(let r=0;r<e.length;r++){if(!BX.has(e[r]))t+="\\";t+=e[r]}return t}function $o(e,t,r,n){if(e.format||e.anyOf?.some((o)=>o.format)){if(!e.anyOf)e.anyOf=[];if(e.format){if(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage){if(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0)delete e.errorMessage}}e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})}else ht(e,"format",t,r,n)}function bn(e,t,r,n){if(e.pattern||e.allOf?.some((o)=>o.pattern)){if(!e.allOf)e.allOf=[];if(e.pattern){if(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage){if(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0)delete e.errorMessage}}e.allOf.push({pattern:CO(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})}else ht(e,"pattern",CO(t,n),r,n)}function CO(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source,o="",i=!1,s=!1,a=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(r.i){if(s){if(n[c].match(/[a-z]/)){if(a)o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1;else if(n[c+1]==="-"&&n[c+2]?.match(/[a-z]/))o+=n[c],a=!0;else o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
131
131
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
132
132
  ]))`;continue}}if(r.s&&n[c]==="."){o+=s?`${n[c]}\r
133
133
  `:`[${n[c]}\r
134
- ]`;continue}if(o+=n[c],n[c]==="\\")i=!0;else if(s&&n[c]==="]")s=!1;else if(!s&&n[c]==="[")s=!0}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function Cy(e,t){if(t.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(t.target==="openApi3"&&e.keyType?._def.typeName===pe.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:He(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??tr(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:He(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===pe.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Ry(e.keyType._def,t);return{...r,propertyNames:o}}else if(e.keyType?._def.typeName===pe.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===pe.ZodBranded&&e.keyType._def.type._def.typeName===pe.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=ky(e.keyType._def,t);return{...r,propertyNames:o}}return r}function OO(e,t){if(t.mapStrategy==="record")return Cy(e,t);let r=He(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||tr(t),n=He(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||tr(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function MO(e){let t=e.values,n=Object.keys(e.values).filter((i)=>typeof t[t[i]]!=="number").map((i)=>t[i]),o=Array.from(new Set(n.map((i)=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function NO(e){return e.target==="openAi"?void 0:{not:tr({...e,currentPath:[...e.currentPath,"not"]})}}function $O(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Jf={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function LO(e,t){if(t.target==="openApi3")return zO(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((n)=>(n._def.typeName in Jf)&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=Jf[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every((n)=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every((n)=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter((i)=>!n.includes(i))],[])};return zO(e,t)}var zO=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>He(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter((n)=>!!n&&(!t.strictUnions||typeof n==="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function BO(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length)){if(t.target==="openApi3")return{type:Jf[e.innerType._def.typeName],nullable:!0};return{type:[Jf[e.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let n=He(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(n&&"$ref"in n)return{allOf:[n],nullable:!0};return n&&{...n,nullable:!0}}let r=He(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function DO(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",p1(r,"type",n.message,t);break;case"min":if(t.target==="jsonSchema7")if(n.inclusive)ht(r,"minimum",n.value,n.message,t);else ht(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;ht(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)ht(r,"maximum",n.value,n.message,t);else ht(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;ht(r,"maximum",n.value,n.message,t)}break;case"multipleOf":ht(r,"multipleOf",n.value,n.message,t);break}return r}function FO(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],i=e.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let l=UX(c);if(l&&r){if(c._def.typeName==="ZodOptional")c=c._def.innerType;if(!c.isNullable())c=c.nullable();l=!1}let d=He(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});if(d===void 0)continue;if(n.properties[a]=d,!l)o.push(a)}if(o.length)n.required=o;let s=FX(e,t);if(s!==void 0)n.additionalProperties=s;return n}function FX(e,t){if(e.catchall._def.typeName!=="ZodNever")return He(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function UX(e){try{return e.isOptional()}catch{return!0}}var UO=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return He(e.innerType._def,t);let r=He(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:tr(t)},r]}:tr(t)};var jO=(e,t)=>{if(t.pipeStrategy==="input")return He(e.in._def,t);else if(t.pipeStrategy==="output")return He(e.out._def,t);let r=He(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=He(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter((o)=>o!==void 0)}};function qO(e,t){return He(e.type._def,t)}function HO(e,t){let n={type:"array",uniqueItems:!0,items:He(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)ht(n,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)ht(n,"maxItems",e.maxSize.value,e.maxSize.message,t);return n}function GO(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>He(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:He(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})};else return{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>He(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function VO(e){return{not:tr(e)}}function ZO(e){return tr(e)}var WO=(e,t)=>He(e.innerType._def,t);var KO=(e,t,r)=>{switch(t){case pe.ZodString:return Ry(e,r);case pe.ZodNumber:return DO(e,r);case pe.ZodObject:return FO(e,r);case pe.ZodBigInt:return TO(e,r);case pe.ZodBoolean:return vO();case pe.ZodDate:return f1(e,r);case pe.ZodUndefined:return VO(r);case pe.ZodNull:return $O(r);case pe.ZodArray:return _O(e,r);case pe.ZodUnion:case pe.ZodDiscriminatedUnion:return LO(e,r);case pe.ZodIntersection:return kO(e,r);case pe.ZodTuple:return GO(e,r);case pe.ZodRecord:return Cy(e,r);case pe.ZodLiteral:return RO(e,r);case pe.ZodEnum:return IO(e);case pe.ZodNativeEnum:return MO(e);case pe.ZodNullable:return BO(e,r);case pe.ZodOptional:return UO(e,r);case pe.ZodMap:return OO(e,r);case pe.ZodSet:return HO(e,r);case pe.ZodLazy:return()=>e.getter()._def;case pe.ZodPromise:return qO(e,r);case pe.ZodNaN:case pe.ZodNever:return NO(r);case pe.ZodEffects:return AO(e,r);case pe.ZodAny:return tr(r);case pe.ZodUnknown:return ZO(r);case pe.ZodDefault:return PO(e,r);case pe.ZodBranded:return ky(e,r);case pe.ZodReadonly:return WO(e,r);case pe.ZodCatch:return EO(e,r);case pe.ZodPipeline:return jO(e,r);case pe.ZodFunction:case pe.ZodVoid:case pe.ZodSymbol:return;default:return((n)=>{return})(t)}};function He(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==xO)return a}if(n&&!r){let a=jX(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let i=KO(e,e.typeName,t),s=typeof i==="function"?He(i(),t):i;if(s)qX(e,t,s);if(t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var jX=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Iy(t.currentPath,e.path)};case"none":case"seen":{if(e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),tr(t);return t.$refStrategy==="seen"?tr(t):void 0}}},qX=(e,t,r)=>{if(e.description){if(r.description=e.description,t.markdownDescription)r.markdownDescription=e.description}return r};var g1=(e,t)=>{let r=SO(t),n=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[l,d])=>({...c,[l]:He(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??tr(r)}),{}):void 0,o=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=He(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??tr(r),s=typeof t==="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;if(s!==void 0)i.title=s;if(r.flags.hasReferencedOpenAiAnyType){if(!n)n={};if(!n[r.openAiAnyTypeName])n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}}let a=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};if(r.target==="jsonSchema7")a.$schema="http://json-schema.org/draft-07/schema#";else if(r.target==="jsonSchema2019-09"||r.target==="openAi")a.$schema="https://json-schema.org/draft/2019-09/schema#";if(r.target==="openAi"&&(("anyOf"in a)||("oneOf"in a)||("allOf"in a)||("type"in a)&&Array.isArray(a.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return a};function HX(e){if(!e)return"draft-7";if(e==="jsonSchema7"||e==="draft-7")return"draft-7";if(e==="jsonSchema2019-09"||e==="draft-2020-12")return"draft-2020-12";return"draft-7"}function y1(e,t){if(uo(e))return qT(e,{target:HX(t?.target),io:t?.pipeStrategy??"input"});return g1(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function b1(e){let r=xa(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=ny(r);if(typeof n!=="string")throw Error("Schema method literal must be a string");return n}function x1(e,t){let r=ba(e,t);if(!r.success)throw r.error;return r.data}var GX=60000;class w1{constructor(e){if(this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(dy,(t)=>{this._oncancel(t)}),this.setNotificationHandler(fy,(t)=>{this._onprogress(t)}),this.setRequestHandler(py,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(my,async(t,r)=>{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ne(Be.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(gy,async(t,r)=>{let n=async()=>{let o=t.params.taskId;if(this._taskMessageQueue){let s;while(s=await this._taskMessageQueue.dequeue(o,r.sessionId)){if(s.type==="response"||s.type==="error"){let a=s.message,c=a.id,l=this._requestResolvers.get(c);if(l)if(this._requestResolvers.delete(c),s.type==="response")l(a);else{let d=a,f=new Ne(d.error.code,d.error.message,d.error.data);l(f)}else{let d=s.type==="response"?"Response":"Error";this._onerror(Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new Ne(Be.InvalidParams,`Task not found: ${o}`);if(!_a(i.status))return await this._waitForTaskUpdate(o,r.signal),await n();if(_a(i.status)){let s=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[Sa]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(yy,async(t,r)=>{try{let{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new Ne(Be.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(xy,async(t,r)=>{try{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ne(Be.InvalidParams,`Task not found: ${t.params.taskId}`);if(_a(n.status))throw new Ne(Be.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId);let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Ne(Be.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){if(n instanceof Ne)throw n;throw new Ne(Be.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Ne.fromError(Be.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=(o)=>{r?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{if(n?.(o,i),jf(o)||sO(o))this._onresponse(o);else if(QT(o))this._onrequest(o,i);else if(iO(o))this._onnotification(o);else this._onerror(Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let t=Ne.fromError(Be.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;if(t===void 0)return;Promise.resolve().then(()=>t(e)).catch((r)=>this._onerror(Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[Sa]?.taskId;if(r===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Be.MethodNotFound,message:"Method not found"}};if(o&&this._taskMessageQueue)this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch((d)=>this._onerror(Error(`Failed to enqueue error response: ${d}`)));else n?.send(l).catch((d)=>this._onerror(Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let s=rO(e.params)?e.params.task:void 0,a=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,c={signal:i.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async(l)=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};if(o)d.relatedTask={taskId:o};await this.notification(l,d)},sendRequest:async(l,d,f)=>{if(i.signal.aborted)throw new Ne(Be.ConnectionClosed,"Request was cancelled");let h={...f,relatedRequestId:e.id};if(o&&!h.relatedTask)h.relatedTask={taskId:o};let g=h.relatedTask?.taskId??o;if(g&&a)await a.updateTaskStatus(g,"input_required");return await this.request(l,d,h)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:a,taskRequestedTtl:s?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(s)this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,c)).then(async(l)=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},n?.sessionId);else await n?.send(d)},async(l)=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:Be.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},n?.sessionId);else await n?.send(d)}).catch((l)=>this._onerror(Error(`Failed to send response: ${l}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===i)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(a);return}o(r)}_onresponse(e){let t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),jf(e))r(e);else{let i=new Ne(e.error.code,e.error.message,e.error.data);r(i)}return}let n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(jf(e)&&e.result&&typeof e.result==="object"){let i=e.result;if(i.task&&typeof i.task==="object"){let s=i.task;if(typeof s.taskId==="string")o=!0,this._taskProgressTokens.set(s.taskId,t)}}if(!o)this._progressHandlers.delete(t);if(jf(e))n(e);else{let i=Ne.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){let{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(i){yield{type:"error",error:i instanceof Ne?i:new Ne(Be.InternalError,String(i))}}return}let o;try{let i=await this.request(e,_l,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Ne(Be.InternalError,"Task creation did not return a task");while(!0){let s=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:s},_a(s.status)){if(s.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};else if(s.status==="failed")yield{type:"error",error:new Ne(Be.InternalError,`Task ${o} failed`)};else if(s.status==="cancelled")yield{type:"error",error:new Ne(Be.InternalError,`Task ${o} was cancelled`)};return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}let a=s.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((c)=>setTimeout(c,a)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Ne?i:new Ne(Be.InternalError,String(i))}}}request(e,t,r){let{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((c,l)=>{let d=(_)=>{l(_)};if(!this._transport){d(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),s)this.assertTaskCapability(e.method)}catch(_){d(_);return}r?.signal?.throwIfAborted();let f=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:f};if(r?.onprogress)this._progressHandlers.set(f,r.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}};if(s)h.params={...h.params,task:s};if(a)h.params={...h.params,_meta:{...h.params?._meta||{},[Sa]:a}};let g=(_)=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(_)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((T)=>this._onerror(Error(`Failed to send cancellation: ${T}`)));let A=_ instanceof Ne?_:new Ne(Be.RequestTimeout,String(_));l(A)};this._responseHandlers.set(f,(_)=>{if(r?.signal?.aborted)return;if(_ instanceof Error)return l(_);try{let A=ba(t,_.result);if(!A.success)l(A.error);else c(A.data)}catch(A){l(A)}}),r?.signal?.addEventListener("abort",()=>{g(r?.signal?.reason)});let x=r?.timeout??GX,w=()=>g(Ne.fromError(Be.RequestTimeout,"Request timed out",{timeout:x}));this._setupTimeout(f,x,r?.maxTotalTimeout,w,r?.resetTimeoutOnProgress??!1);let S=a?.taskId;if(S){let _=(A)=>{let T=this._responseHandlers.get(f);if(T)T(A);else this._onerror(Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,_),this._enqueueTaskMessage(S,{type:"request",message:h,timestamp:Date.now()}).catch((A)=>{this._cleanupTimeout(f),l(A)})}else this._transport.send(h,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((_)=>{this._cleanupTimeout(f),l(_)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},hy,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},by,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},uO,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let r=t?.relatedTask?.taskId;if(r){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Sa]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};if(t?.relatedTask)s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Sa]:t.relatedTask}}};this._transport?.send(s,t).catch((a)=>this._onerror(a))});return}let i={...e,jsonrpc:"2.0"};if(t?.relatedTask)i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Sa]:t.relatedTask}}};await this._transport.send(i,t)}setRequestHandler(e,t){let r=b1(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{let i=x1(e,n);return Promise.resolve(t(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let r=b1(e);this._notificationHandlers.set(r,(n)=>{let o=x1(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);if(t!==void 0)this._progressHandlers.delete(t),this._taskProgressTokens.delete(e)}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,t);for(let n of r)if(n.type==="request"&&QT(n.message)){let o=n.message.id,i=this._requestResolvers.get(o);if(i)i(new Ne(Be.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o);else this._onerror(Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1000;try{let n=await this._taskStore?.getTask(e);if(n?.pollInterval)r=n.pollInterval}catch{}return new Promise((n,o)=>{if(t.aborted){o(new Ne(Be.InvalidRequest,"Request cancelled"));return}let i=setTimeout(n,r);t.addEventListener("abort",()=>{clearTimeout(i),o(new Ne(Be.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let r=this._taskStore;if(!r)throw Error("No task store configured");return{createTask:async(n)=>{if(!e)throw Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async(n)=>{let o=await r.getTask(n,t);if(!o)throw new Ne(Be.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,i)=>{await r.storeTaskResult(n,o,i,t);let s=await r.getTask(n,t);if(s){let a=Zf.parse({method:"notifications/tasks/status",params:s});if(await this.notification(a),_a(s.status))this._cleanupTaskProgressHandler(n)}},getTaskResult:(n)=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,i)=>{let s=await r.getTask(n,t);if(!s)throw new Ne(Be.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(_a(s.status))throw new Ne(Be.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,i,t);let a=await r.getTask(n,t);if(a){let c=Zf.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),_a(a.status))this._cleanupTaskProgressHandler(n)}},listTasks:(n)=>r.listTasks(n,t)}}}function YO(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function JO(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];if(YO(s)&&YO(i))r[o]={...s,...i};else r[o]=i}return r}var e4=pn(ov(),1),t4=pn(XL(),1);function kae(){let e=new e4.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return t4.default(e),e}class fv{constructor(e){this._ajv=e??kae()}getValidator(e){let t="$id"in e&&typeof e.$id==="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return(r)=>{if(t(r))return{valid:!0,data:r,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}class mv{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some((l)=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some((l)=>l.type==="tool_use");if(i){if(o.some((l)=>l.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!c)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter((f)=>f.type==="tool_use").map((f)=>f.id)),d=new Set(o.filter((f)=>f.type==="tool_result").map((f)=>f.toolUseId));if(l.size!==d.size||![...l].every((f)=>d.has(f)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Yf,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!r?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let o=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},El,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}function r4(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function n4(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}class hv extends w1{constructor(e,t){super(t);if(this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Kf.options.map((r,n)=>[r,n])),this.isMessageIgnored=(r,n)=>{let o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new fv,this.setRequestHandler(t1,(r)=>this._oninitialize(r)),this.setNotificationHandler(r1,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(u1,async(r,n)=>{let o=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,s=Kf.safeParse(i);if(s.success)this._loggingLevels.set(o,s.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new mv(this)};return this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=JO(this._capabilities,e)}setRequestHandler(e,t){let n=xa(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o;if(uo(n)){let s=n;o=s._zod?.def?.value??s.value}else{let s=n;o=s._def?.value??s.value}if(typeof o!=="string")throw Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(a,c)=>{let l=ba(vl,a);if(!l.success){let g=l.error instanceof Error?l.error.message:String(l.error);throw new Ne(Be.InvalidParams,`Invalid tools/call request: ${g}`)}let{params:d}=l.data,f=await Promise.resolve(t(a,c));if(d.task){let g=ba(_l,f);if(!g.success){let x=g.error instanceof Error?g.error.message:String(g.error);throw new Ne(Be.InvalidParams,`Invalid task creation result: ${x}`)}return g.data}let h=ba(Py,f);if(!h.success){let g=h.error instanceof Error?h.error.message:String(h.error);throw new Ne(Be.InvalidParams,`Invalid tools/call result: ${g}`)}return h.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(!this._capabilities)return;switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){n4(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;r4(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:XC.includes(t)?t:YT,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},ly)}async createMessage(e,t){if(e.tools||e.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(e.messages.length>0){let r=e.messages[e.messages.length-1],n=Array.isArray(r.content)?r.content:[r.content],o=n.some((c)=>c.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=i?Array.isArray(i.content)?i.content:[i.content]:[],a=s.some((c)=>c.type==="tool_use");if(o){if(n.some((c)=>c.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!a)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){let c=new Set(s.filter((d)=>d.type==="tool_use").map((d)=>d.id)),l=new Set(n.filter((d)=>d.type==="tool_result").map((d)=>d.toolUseId));if(c.size!==l.size||![...c].every((d)=>l.has(d)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(e.tools)return this.request({method:"sampling/createMessage",params:e},l1,t);return this.request({method:"sampling/createMessage",params:e},Yf,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let n=e;return this.request({method:"elicitation/create",params:n},El,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:n},El,t);if(o.action==="accept"&&o.content&&n.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(n.requestedSchema)(o.content);if(!s.valid)throw new Ne(Be.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(i){if(i instanceof Ne)throw i;throw new Ne(Be.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},d1,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging){if(!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var i4=Symbol.for("mcp.completable");function gv(e){return!!e&&typeof e==="object"&&i4 in e}function s4(e){return e[i4]?.complete}var o4;(function(e){e.Completable="McpCompletable"})(o4||(o4={}));var Rae=/^[A-Za-z0-9._-]{1,128}$/;function Cae(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" "))t.push("Tool name contains spaces, which may cause parsing issues");if(e.includes(","))t.push("Tool name contains commas, which may cause parsing issues");if(e.startsWith("-")||e.endsWith("-"))t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(e.startsWith(".")||e.endsWith("."))t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!Rae.test(e)){let r=e.split("").filter((n)=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map((n)=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Oae(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function yv(e){let t=Cae(e);return Oae(e,t.warnings),t.isValid}class bv{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let n={taskSupport:"required",...t.execution};if(n.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,n,t._meta,r)}}class wv{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new hv(e,t)}get experimental(){if(!this._experimental)this._experimental={tasks:new bv(this)};return this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(ja(Ey)),this.server.assertCanSetRequestHandler(ja(vl)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ey,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let n=xl(t.inputSchema);return n?y1(n,{strictUnions:!0,pipeStrategy:"input"}):Mae})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let n=xl(t.outputSchema);if(n)r.outputSchema=y1(n,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(vl,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new Ne(Be.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Ne(Be.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,o=r.execution?.taskSupport,i="createTask"in r.handler;if((o==="required"||o==="optional")&&!i)throw new Ne(Be.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!n)throw new Ne(Be.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!n&&i)return await this.handleAutomaticTaskPolling(r,e,t);let s=await this.validateToolInput(r,e.params.arguments,e.params.name),a=await this.executeToolHandler(r,s,t);if(n)return a;return await this.validateToolOutput(r,a,e.params.name),a}catch(r){if(r instanceof Ne){if(r.code===Be.UrlElicitationRequired)throw r}return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(!e.inputSchema)return;let o=xl(e.inputSchema)??e.inputSchema,i=await ty(o,t);if(!i.success){let s="error"in i?i.error:"Unknown error",a=ry(s);throw new Ne(Be.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${a}`)}return i.data}async validateToolOutput(e,t,r){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new Ne(Be.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=xl(e.outputSchema),o=await ty(n,t.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",s=ry(i);throw new Ne(Be.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${s}`)}}async executeToolHandler(e,t,r){let n=e.handler;if("createTask"in n){if(!r.taskStore)throw Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema)return await Promise.resolve(n.createTask(t,i));else return await Promise.resolve(n.createTask(i))}if(e.inputSchema)return await Promise.resolve(n(t,r));else return await Promise.resolve(n(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,t.params.arguments,t.params.name),o=e.handler,i={...r,taskStore:r.taskStore},s=n?await Promise.resolve(o.createTask(n,i)):await Promise.resolve(o.createTask(i)),a=s.task.taskId,c=s.task,l=c.pollInterval??5000;while(c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled"){await new Promise((f)=>setTimeout(f,l));let d=await r.taskStore.getTask(a);if(!d)throw new Ne(Be.InternalError,`Task ${a} not found during polling`);c=d}return await r.taskStore.getTaskResult(a)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(ja(Ay)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ay,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return hO(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return gO(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Ne(Be.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new Ne(Be.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new Ne(Be.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return lm;let o=xa(r.argsSchema)?.[e.params.argument.name];if(!gv(o))return lm;let i=s4(o);if(!i)return lm;let s=await i(e.params.argument.value,e.params.context);return c4(s)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find((i)=>i.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return lm;throw new Ne(Be.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return lm;let o=await n(e.params.argument.value,e.params.context);return c4(o)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(ja(wy)),this.server.assertCanSetRequestHandler(ja(Sy)),this.server.assertCanSetRequestHandler(ja(_y)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(wy,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),n=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(t);for(let s of i.resources)n.push({...o.metadata,...s})}return{resources:[...r,...n]}}),this.server.setRequestHandler(Sy,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(_y,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new Ne(Be.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(r.toString());if(i)return o.readCallback(r,i,t)}throw new Ne(Be.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(ja(Ty)),this.server.assertCanSetRequestHandler(ja(vy)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ty,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Nae(t.argsSchema):void 0}))})),this.server.setRequestHandler(vy,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new Ne(Be.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Ne(Be.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=xl(r.argsSchema),o=await ty(n,e.params.arguments);if(!o.success){let a="error"in o?o.error:"Unknown error",c=ry(a);throw new Ne(Be.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}let i=o.data,s=r.callback;return await Promise.resolve(s(i,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this._promptHandlersInitialized=!0}resource(e,t,...r){let n;if(typeof r[0]==="object")n=r.shift();let o=r[0];if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,t,r,n){if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,r,n,o){let i={name:e,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:(s)=>{if(typeof s.uri<"u"&&s.uri!==r){if(delete this._registeredResources[r],s.uri)this._registeredResources[s.uri]=i}if(typeof s.name<"u")i.name=s.name;if(typeof s.title<"u")i.title=s.title;if(typeof s.metadata<"u")i.metadata=s.metadata;if(typeof s.callback<"u")i.readCallback=s.callback;if(typeof s.enabled<"u")i.enabled=s.enabled;this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,t,r,n,o){let i={resourceTemplate:r,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(c)=>{if(typeof c.name<"u"&&c.name!==e){if(delete this._registeredResourceTemplates[e],c.name)this._registeredResourceTemplates[c.name]=i}if(typeof c.title<"u")i.title=c.title;if(typeof c.template<"u")i.resourceTemplate=c.template;if(typeof c.metadata<"u")i.metadata=c.metadata;if(typeof c.callback<"u")i.readCallback=c.callback;if(typeof c.enabled<"u")i.enabled=c.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let s=r.uriTemplate.variableNames;if(Array.isArray(s)&&s.some((c)=>!!r.completeCallback(c)))this.setCompletionRequestHandler();return i}_createRegisteredPrompt(e,t,r,n,o){let i={title:t,description:r,argsSchema:n===void 0?void 0:Gc(n),callback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(s)=>{if(typeof s.name<"u"&&s.name!==e){if(delete this._registeredPrompts[e],s.name)this._registeredPrompts[s.name]=i}if(typeof s.title<"u")i.title=s.title;if(typeof s.description<"u")i.description=s.description;if(typeof s.argsSchema<"u")i.argsSchema=Gc(s.argsSchema);if(typeof s.callback<"u")i.callback=s.callback;if(typeof s.enabled<"u")i.enabled=s.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[e]=i,n){if(Object.values(n).some((a)=>{let c=a instanceof sy?a._def?.innerType:a;return gv(c)}))this.setCompletionRequestHandler()}return i}_createRegisteredTool(e,t,r,n,o,i,s,a,c){yv(e);let l={title:t,description:r,inputSchema:a4(n),outputSchema:a4(o),annotations:i,execution:s,_meta:a,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:(d)=>{if(typeof d.name<"u"&&d.name!==e){if(typeof d.name==="string")yv(d.name);if(delete this._registeredTools[e],d.name)this._registeredTools[d.name]=l}if(typeof d.title<"u")l.title=d.title;if(typeof d.description<"u")l.description=d.description;if(typeof d.paramsSchema<"u")l.inputSchema=Gc(d.paramsSchema);if(typeof d.outputSchema<"u")l.outputSchema=Gc(d.outputSchema);if(typeof d.callback<"u")l.handler=d.callback;if(typeof d.annotations<"u")l.annotations=d.annotations;if(typeof d._meta<"u")l._meta=d._meta;if(typeof d.enabled<"u")l.enabled=d.enabled;this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r,n,o,i;if(typeof t[0]==="string")r=t.shift();if(t.length>1){let a=t[0];if(xv(a)){if(n=t.shift(),t.length>1&&typeof t[0]==="object"&&t[0]!==null&&!xv(t[0]))i=t.shift()}else if(typeof a==="object"&&a!==null){if(Object.values(a).some((c)=>typeof c==="object"&&c!==null))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let s=t[0];return this._createRegisteredTool(e,void 0,r,n,o,i,{taskSupport:"forbidden"},void 0,s)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:n,description:o,inputSchema:i,outputSchema:s,annotations:a,_meta:c}=t;return this._createRegisteredTool(e,n,o,i,s,a,{taskSupport:"forbidden"},c,r)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let r;if(typeof t[0]==="string")r=t.shift();let n;if(t.length>1)n=t.shift();let o=t[0],i=this._createRegisteredPrompt(e,void 0,r,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:n,description:o,argsSchema:i}=t,s=this._createRegisteredPrompt(e,n,o,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var Mae={type:"object",properties:{}};function u4(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function l4(e){return"_def"in e||"_zod"in e||u4(e)}function xv(e){if(typeof e!=="object"||e===null)return!1;if(l4(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some(u4)}function a4(e){if(!e)return;if(xv(e))return Gc(e);if(!l4(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function Nae(e){let t=xa(e);if(!t)return[];return Object.entries(t).map(([r,n])=>{let o=gC(n),i=yC(n);return{name:r,description:o,required:!i}})}function ja(e){let r=xa(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=ny(r);if(typeof n==="string")return n;throw Error("Schema method literal must be a string")}function c4(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var lm={completion:{values:[],hasMore:!1}};import p4 from"node:process";class Sv{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
134
+ ]`;continue}if(o+=n[c],n[c]==="\\")i=!0;else if(s&&n[c]==="]")s=!1;else if(!s&&n[c]==="[")s=!0}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function Cy(e,t){if(t.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(t.target==="openApi3"&&e.keyType?._def.typeName===pe.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:He(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??tr(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:He(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===pe.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Ry(e.keyType._def,t);return{...r,propertyNames:o}}else if(e.keyType?._def.typeName===pe.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===pe.ZodBranded&&e.keyType._def.type._def.typeName===pe.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=ky(e.keyType._def,t);return{...r,propertyNames:o}}return r}function OO(e,t){if(t.mapStrategy==="record")return Cy(e,t);let r=He(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||tr(t),n=He(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||tr(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function MO(e){let t=e.values,n=Object.keys(e.values).filter((i)=>typeof t[t[i]]!=="number").map((i)=>t[i]),o=Array.from(new Set(n.map((i)=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function NO(e){return e.target==="openAi"?void 0:{not:tr({...e,currentPath:[...e.currentPath,"not"]})}}function $O(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Jf={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function LO(e,t){if(t.target==="openApi3")return zO(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((n)=>(n._def.typeName in Jf)&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=Jf[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every((n)=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every((n)=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter((i)=>!n.includes(i))],[])};return zO(e,t)}var zO=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>He(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter((n)=>!!n&&(!t.strictUnions||typeof n==="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function BO(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length)){if(t.target==="openApi3")return{type:Jf[e.innerType._def.typeName],nullable:!0};return{type:[Jf[e.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let n=He(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(n&&"$ref"in n)return{allOf:[n],nullable:!0};return n&&{...n,nullable:!0}}let r=He(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function DO(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",p1(r,"type",n.message,t);break;case"min":if(t.target==="jsonSchema7")if(n.inclusive)ht(r,"minimum",n.value,n.message,t);else ht(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;ht(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)ht(r,"maximum",n.value,n.message,t);else ht(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;ht(r,"maximum",n.value,n.message,t)}break;case"multipleOf":ht(r,"multipleOf",n.value,n.message,t);break}return r}function FO(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],i=e.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let l=UX(c);if(l&&r){if(c._def.typeName==="ZodOptional")c=c._def.innerType;if(!c.isNullable())c=c.nullable();l=!1}let d=He(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});if(d===void 0)continue;if(n.properties[a]=d,!l)o.push(a)}if(o.length)n.required=o;let s=FX(e,t);if(s!==void 0)n.additionalProperties=s;return n}function FX(e,t){if(e.catchall._def.typeName!=="ZodNever")return He(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function UX(e){try{return e.isOptional()}catch{return!0}}var UO=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return He(e.innerType._def,t);let r=He(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:tr(t)},r]}:tr(t)};var jO=(e,t)=>{if(t.pipeStrategy==="input")return He(e.in._def,t);else if(t.pipeStrategy==="output")return He(e.out._def,t);let r=He(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=He(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter((o)=>o!==void 0)}};function qO(e,t){return He(e.type._def,t)}function HO(e,t){let n={type:"array",uniqueItems:!0,items:He(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)ht(n,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)ht(n,"maxItems",e.maxSize.value,e.maxSize.message,t);return n}function GO(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>He(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:He(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})};else return{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>He(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function VO(e){return{not:tr(e)}}function ZO(e){return tr(e)}var WO=(e,t)=>He(e.innerType._def,t);var KO=(e,t,r)=>{switch(t){case pe.ZodString:return Ry(e,r);case pe.ZodNumber:return DO(e,r);case pe.ZodObject:return FO(e,r);case pe.ZodBigInt:return TO(e,r);case pe.ZodBoolean:return vO();case pe.ZodDate:return f1(e,r);case pe.ZodUndefined:return VO(r);case pe.ZodNull:return $O(r);case pe.ZodArray:return _O(e,r);case pe.ZodUnion:case pe.ZodDiscriminatedUnion:return LO(e,r);case pe.ZodIntersection:return kO(e,r);case pe.ZodTuple:return GO(e,r);case pe.ZodRecord:return Cy(e,r);case pe.ZodLiteral:return RO(e,r);case pe.ZodEnum:return IO(e);case pe.ZodNativeEnum:return MO(e);case pe.ZodNullable:return BO(e,r);case pe.ZodOptional:return UO(e,r);case pe.ZodMap:return OO(e,r);case pe.ZodSet:return HO(e,r);case pe.ZodLazy:return()=>e.getter()._def;case pe.ZodPromise:return qO(e,r);case pe.ZodNaN:case pe.ZodNever:return NO(r);case pe.ZodEffects:return AO(e,r);case pe.ZodAny:return tr(r);case pe.ZodUnknown:return ZO(r);case pe.ZodDefault:return PO(e,r);case pe.ZodBranded:return ky(e,r);case pe.ZodReadonly:return WO(e,r);case pe.ZodCatch:return EO(e,r);case pe.ZodPipeline:return jO(e,r);case pe.ZodFunction:case pe.ZodVoid:case pe.ZodSymbol:return;default:return((n)=>{return})(t)}};function He(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==xO)return a}if(n&&!r){let a=jX(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let i=KO(e,e.typeName,t),s=typeof i==="function"?He(i(),t):i;if(s)qX(e,t,s);if(t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var jX=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Iy(t.currentPath,e.path)};case"none":case"seen":{if(e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),tr(t);return t.$refStrategy==="seen"?tr(t):void 0}}},qX=(e,t,r)=>{if(e.description){if(r.description=e.description,t.markdownDescription)r.markdownDescription=e.description}return r};var g1=(e,t)=>{let r=SO(t),n=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[l,d])=>({...c,[l]:He(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??tr(r)}),{}):void 0,o=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=He(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??tr(r),s=typeof t==="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;if(s!==void 0)i.title=s;if(r.flags.hasReferencedOpenAiAnyType){if(!n)n={};if(!n[r.openAiAnyTypeName])n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}}let a=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};if(r.target==="jsonSchema7")a.$schema="http://json-schema.org/draft-07/schema#";else if(r.target==="jsonSchema2019-09"||r.target==="openAi")a.$schema="https://json-schema.org/draft/2019-09/schema#";if(r.target==="openAi"&&(("anyOf"in a)||("oneOf"in a)||("allOf"in a)||("type"in a)&&Array.isArray(a.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return a};function HX(e){if(!e)return"draft-7";if(e==="jsonSchema7"||e==="draft-7")return"draft-7";if(e==="jsonSchema2019-09"||e==="draft-2020-12")return"draft-2020-12";return"draft-7"}function y1(e,t){if(uo(e))return qT(e,{target:HX(t?.target),io:t?.pipeStrategy??"input"});return g1(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function b1(e){let r=xa(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=ny(r);if(typeof n!=="string")throw Error("Schema method literal must be a string");return n}function x1(e,t){let r=ba(e,t);if(!r.success)throw r.error;return r.data}var GX=60000;class w1{constructor(e){if(this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(dy,(t)=>{this._oncancel(t)}),this.setNotificationHandler(fy,(t)=>{this._onprogress(t)}),this.setRequestHandler(py,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(my,async(t,r)=>{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ne(Be.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(gy,async(t,r)=>{let n=async()=>{let o=t.params.taskId;if(this._taskMessageQueue){let s;while(s=await this._taskMessageQueue.dequeue(o,r.sessionId)){if(s.type==="response"||s.type==="error"){let a=s.message,c=a.id,l=this._requestResolvers.get(c);if(l)if(this._requestResolvers.delete(c),s.type==="response")l(a);else{let d=a,f=new Ne(d.error.code,d.error.message,d.error.data);l(f)}else{let d=s.type==="response"?"Response":"Error";this._onerror(Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new Ne(Be.InvalidParams,`Task not found: ${o}`);if(!_a(i.status))return await this._waitForTaskUpdate(o,r.signal),await n();if(_a(i.status)){let s=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[Sa]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(yy,async(t,r)=>{try{let{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new Ne(Be.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(xy,async(t,r)=>{try{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ne(Be.InvalidParams,`Task not found: ${t.params.taskId}`);if(_a(n.status))throw new Ne(Be.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId);let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Ne(Be.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){if(n instanceof Ne)throw n;throw new Ne(Be.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Ne.fromError(Be.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=(o)=>{r?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{if(n?.(o,i),jf(o)||sO(o))this._onresponse(o);else if(QT(o))this._onrequest(o,i);else if(iO(o))this._onnotification(o);else this._onerror(Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let t=Ne.fromError(Be.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;if(t===void 0)return;Promise.resolve().then(()=>t(e)).catch((r)=>this._onerror(Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[Sa]?.taskId;if(r===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Be.MethodNotFound,message:"Method not found"}};if(o&&this._taskMessageQueue)this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch((d)=>this._onerror(Error(`Failed to enqueue error response: ${d}`)));else n?.send(l).catch((d)=>this._onerror(Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let s=rO(e.params)?e.params.task:void 0,a=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,c={signal:i.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async(l)=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};if(o)d.relatedTask={taskId:o};await this.notification(l,d)},sendRequest:async(l,d,f)=>{if(i.signal.aborted)throw new Ne(Be.ConnectionClosed,"Request was cancelled");let h={...f,relatedRequestId:e.id};if(o&&!h.relatedTask)h.relatedTask={taskId:o};let g=h.relatedTask?.taskId??o;if(g&&a)await a.updateTaskStatus(g,"input_required");return await this.request(l,d,h)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:a,taskRequestedTtl:s?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(s)this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,c)).then(async(l)=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},n?.sessionId);else await n?.send(d)},async(l)=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:Be.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},n?.sessionId);else await n?.send(d)}).catch((l)=>this._onerror(Error(`Failed to send response: ${l}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===i)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(a);return}o(r)}_onresponse(e){let t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),jf(e))r(e);else{let i=new Ne(e.error.code,e.error.message,e.error.data);r(i)}return}let n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(jf(e)&&e.result&&typeof e.result==="object"){let i=e.result;if(i.task&&typeof i.task==="object"){let s=i.task;if(typeof s.taskId==="string")o=!0,this._taskProgressTokens.set(s.taskId,t)}}if(!o)this._progressHandlers.delete(t);if(jf(e))n(e);else{let i=Ne.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){let{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(i){yield{type:"error",error:i instanceof Ne?i:new Ne(Be.InternalError,String(i))}}return}let o;try{let i=await this.request(e,_l,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Ne(Be.InternalError,"Task creation did not return a task");while(!0){let s=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:s},_a(s.status)){if(s.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};else if(s.status==="failed")yield{type:"error",error:new Ne(Be.InternalError,`Task ${o} failed`)};else if(s.status==="cancelled")yield{type:"error",error:new Ne(Be.InternalError,`Task ${o} was cancelled`)};return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}let a=s.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((c)=>setTimeout(c,a)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Ne?i:new Ne(Be.InternalError,String(i))}}}request(e,t,r){let{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((c,l)=>{let d=(_)=>{l(_)};if(!this._transport){d(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),s)this.assertTaskCapability(e.method)}catch(_){d(_);return}r?.signal?.throwIfAborted();let f=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:f};if(r?.onprogress)this._progressHandlers.set(f,r.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}};if(s)h.params={...h.params,task:s};if(a)h.params={...h.params,_meta:{...h.params?._meta||{},[Sa]:a}};let g=(_)=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(_)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((T)=>this._onerror(Error(`Failed to send cancellation: ${T}`)));let A=_ instanceof Ne?_:new Ne(Be.RequestTimeout,String(_));l(A)};this._responseHandlers.set(f,(_)=>{if(r?.signal?.aborted)return;if(_ instanceof Error)return l(_);try{let A=ba(t,_.result);if(!A.success)l(A.error);else c(A.data)}catch(A){l(A)}}),r?.signal?.addEventListener("abort",()=>{g(r?.signal?.reason)});let x=r?.timeout??GX,w=()=>g(Ne.fromError(Be.RequestTimeout,"Request timed out",{timeout:x}));this._setupTimeout(f,x,r?.maxTotalTimeout,w,r?.resetTimeoutOnProgress??!1);let S=a?.taskId;if(S){let _=(A)=>{let T=this._responseHandlers.get(f);if(T)T(A);else this._onerror(Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,_),this._enqueueTaskMessage(S,{type:"request",message:h,timestamp:Date.now()}).catch((A)=>{this._cleanupTimeout(f),l(A)})}else this._transport.send(h,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((_)=>{this._cleanupTimeout(f),l(_)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},hy,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},by,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},uO,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let r=t?.relatedTask?.taskId;if(r){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Sa]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};if(t?.relatedTask)s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Sa]:t.relatedTask}}};this._transport?.send(s,t).catch((a)=>this._onerror(a))});return}let i={...e,jsonrpc:"2.0"};if(t?.relatedTask)i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Sa]:t.relatedTask}}};await this._transport.send(i,t)}setRequestHandler(e,t){let r=b1(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{let i=x1(e,n);return Promise.resolve(t(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let r=b1(e);this._notificationHandlers.set(r,(n)=>{let o=x1(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);if(t!==void 0)this._progressHandlers.delete(t),this._taskProgressTokens.delete(e)}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,t);for(let n of r)if(n.type==="request"&&QT(n.message)){let o=n.message.id,i=this._requestResolvers.get(o);if(i)i(new Ne(Be.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o);else this._onerror(Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1000;try{let n=await this._taskStore?.getTask(e);if(n?.pollInterval)r=n.pollInterval}catch{}return new Promise((n,o)=>{if(t.aborted){o(new Ne(Be.InvalidRequest,"Request cancelled"));return}let i=setTimeout(n,r);t.addEventListener("abort",()=>{clearTimeout(i),o(new Ne(Be.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let r=this._taskStore;if(!r)throw Error("No task store configured");return{createTask:async(n)=>{if(!e)throw Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async(n)=>{let o=await r.getTask(n,t);if(!o)throw new Ne(Be.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,i)=>{await r.storeTaskResult(n,o,i,t);let s=await r.getTask(n,t);if(s){let a=Zf.parse({method:"notifications/tasks/status",params:s});if(await this.notification(a),_a(s.status))this._cleanupTaskProgressHandler(n)}},getTaskResult:(n)=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,i)=>{let s=await r.getTask(n,t);if(!s)throw new Ne(Be.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(_a(s.status))throw new Ne(Be.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,i,t);let a=await r.getTask(n,t);if(a){let c=Zf.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),_a(a.status))this._cleanupTaskProgressHandler(n)}},listTasks:(n)=>r.listTasks(n,t)}}}function YO(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function JO(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];if(YO(s)&&YO(i))r[o]={...s,...i};else r[o]=i}return r}var e4=pn(ov(),1),t4=pn(XL(),1);function kae(){let e=new e4.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return t4.default(e),e}class fv{constructor(e){this._ajv=e??kae()}getValidator(e){let t="$id"in e&&typeof e.$id==="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return(r)=>{if(t(r))return{valid:!0,data:r,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}class mv{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some((l)=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some((l)=>l.type==="tool_use");if(i){if(o.some((l)=>l.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!c)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter((f)=>f.type==="tool_use").map((f)=>f.id)),d=new Set(o.filter((f)=>f.type==="tool_result").map((f)=>f.toolUseId));if(l.size!==d.size||![...l].every((f)=>d.has(f)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Yf,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!r?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let o=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},El,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}function r4(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function n4(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}class hv extends w1{constructor(e,t){super(t);if(this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Kf.options.map((r,n)=>[r,n])),this.isMessageIgnored=(r,n)=>{let o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new fv,this.setRequestHandler(t1,(r)=>this._oninitialize(r)),this.setNotificationHandler(r1,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(u1,async(r,n)=>{let o=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,s=Kf.safeParse(i);if(s.success)this._loggingLevels.set(o,s.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new mv(this)};return this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=JO(this._capabilities,e)}setRequestHandler(e,t){let n=xa(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o;if(uo(n)){let s=n;o=s._zod?.def?.value??s.value}else{let s=n;o=s._def?.value??s.value}if(typeof o!=="string")throw Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(a,c)=>{let l=ba(vl,a);if(!l.success){let g=l.error instanceof Error?l.error.message:String(l.error);throw new Ne(Be.InvalidParams,`Invalid tools/call request: ${g}`)}let{params:d}=l.data,f=await Promise.resolve(t(a,c));if(d.task){let g=ba(_l,f);if(!g.success){let x=g.error instanceof Error?g.error.message:String(g.error);throw new Ne(Be.InvalidParams,`Invalid task creation result: ${x}`)}return g.data}let h=ba(Py,f);if(!h.success){let g=h.error instanceof Error?h.error.message:String(h.error);throw new Ne(Be.InvalidParams,`Invalid tools/call result: ${g}`)}return h.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(!this._capabilities)return;switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){n4(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;r4(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:X5.includes(t)?t:YT,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},ly)}async createMessage(e,t){if(e.tools||e.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(e.messages.length>0){let r=e.messages[e.messages.length-1],n=Array.isArray(r.content)?r.content:[r.content],o=n.some((c)=>c.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=i?Array.isArray(i.content)?i.content:[i.content]:[],a=s.some((c)=>c.type==="tool_use");if(o){if(n.some((c)=>c.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!a)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){let c=new Set(s.filter((d)=>d.type==="tool_use").map((d)=>d.id)),l=new Set(n.filter((d)=>d.type==="tool_result").map((d)=>d.toolUseId));if(c.size!==l.size||![...c].every((d)=>l.has(d)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(e.tools)return this.request({method:"sampling/createMessage",params:e},l1,t);return this.request({method:"sampling/createMessage",params:e},Yf,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let n=e;return this.request({method:"elicitation/create",params:n},El,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:n},El,t);if(o.action==="accept"&&o.content&&n.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(n.requestedSchema)(o.content);if(!s.valid)throw new Ne(Be.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(i){if(i instanceof Ne)throw i;throw new Ne(Be.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},d1,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging){if(!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var i4=Symbol.for("mcp.completable");function gv(e){return!!e&&typeof e==="object"&&i4 in e}function s4(e){return e[i4]?.complete}var o4;(function(e){e.Completable="McpCompletable"})(o4||(o4={}));var Rae=/^[A-Za-z0-9._-]{1,128}$/;function Cae(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" "))t.push("Tool name contains spaces, which may cause parsing issues");if(e.includes(","))t.push("Tool name contains commas, which may cause parsing issues");if(e.startsWith("-")||e.endsWith("-"))t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(e.startsWith(".")||e.endsWith("."))t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!Rae.test(e)){let r=e.split("").filter((n)=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map((n)=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Oae(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function yv(e){let t=Cae(e);return Oae(e,t.warnings),t.isValid}class bv{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let n={taskSupport:"required",...t.execution};if(n.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,n,t._meta,r)}}class wv{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new hv(e,t)}get experimental(){if(!this._experimental)this._experimental={tasks:new bv(this)};return this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(ja(Ey)),this.server.assertCanSetRequestHandler(ja(vl)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ey,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let n=xl(t.inputSchema);return n?y1(n,{strictUnions:!0,pipeStrategy:"input"}):Mae})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let n=xl(t.outputSchema);if(n)r.outputSchema=y1(n,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(vl,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new Ne(Be.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Ne(Be.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,o=r.execution?.taskSupport,i="createTask"in r.handler;if((o==="required"||o==="optional")&&!i)throw new Ne(Be.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!n)throw new Ne(Be.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!n&&i)return await this.handleAutomaticTaskPolling(r,e,t);let s=await this.validateToolInput(r,e.params.arguments,e.params.name),a=await this.executeToolHandler(r,s,t);if(n)return a;return await this.validateToolOutput(r,a,e.params.name),a}catch(r){if(r instanceof Ne){if(r.code===Be.UrlElicitationRequired)throw r}return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(!e.inputSchema)return;let o=xl(e.inputSchema)??e.inputSchema,i=await ty(o,t);if(!i.success){let s="error"in i?i.error:"Unknown error",a=ry(s);throw new Ne(Be.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${a}`)}return i.data}async validateToolOutput(e,t,r){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new Ne(Be.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=xl(e.outputSchema),o=await ty(n,t.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",s=ry(i);throw new Ne(Be.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${s}`)}}async executeToolHandler(e,t,r){let n=e.handler;if("createTask"in n){if(!r.taskStore)throw Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema)return await Promise.resolve(n.createTask(t,i));else return await Promise.resolve(n.createTask(i))}if(e.inputSchema)return await Promise.resolve(n(t,r));else return await Promise.resolve(n(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,t.params.arguments,t.params.name),o=e.handler,i={...r,taskStore:r.taskStore},s=n?await Promise.resolve(o.createTask(n,i)):await Promise.resolve(o.createTask(i)),a=s.task.taskId,c=s.task,l=c.pollInterval??5000;while(c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled"){await new Promise((f)=>setTimeout(f,l));let d=await r.taskStore.getTask(a);if(!d)throw new Ne(Be.InternalError,`Task ${a} not found during polling`);c=d}return await r.taskStore.getTaskResult(a)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(ja(Ay)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ay,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return hO(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return gO(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Ne(Be.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new Ne(Be.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new Ne(Be.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return lm;let o=xa(r.argsSchema)?.[e.params.argument.name];if(!gv(o))return lm;let i=s4(o);if(!i)return lm;let s=await i(e.params.argument.value,e.params.context);return c4(s)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find((i)=>i.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return lm;throw new Ne(Be.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return lm;let o=await n(e.params.argument.value,e.params.context);return c4(o)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(ja(wy)),this.server.assertCanSetRequestHandler(ja(Sy)),this.server.assertCanSetRequestHandler(ja(_y)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(wy,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),n=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(t);for(let s of i.resources)n.push({...o.metadata,...s})}return{resources:[...r,...n]}}),this.server.setRequestHandler(Sy,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(_y,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new Ne(Be.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(r.toString());if(i)return o.readCallback(r,i,t)}throw new Ne(Be.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(ja(Ty)),this.server.assertCanSetRequestHandler(ja(vy)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ty,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Nae(t.argsSchema):void 0}))})),this.server.setRequestHandler(vy,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new Ne(Be.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Ne(Be.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=xl(r.argsSchema),o=await ty(n,e.params.arguments);if(!o.success){let a="error"in o?o.error:"Unknown error",c=ry(a);throw new Ne(Be.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}let i=o.data,s=r.callback;return await Promise.resolve(s(i,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this._promptHandlersInitialized=!0}resource(e,t,...r){let n;if(typeof r[0]==="object")n=r.shift();let o=r[0];if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,t,r,n){if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,r,n,o){let i={name:e,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:(s)=>{if(typeof s.uri<"u"&&s.uri!==r){if(delete this._registeredResources[r],s.uri)this._registeredResources[s.uri]=i}if(typeof s.name<"u")i.name=s.name;if(typeof s.title<"u")i.title=s.title;if(typeof s.metadata<"u")i.metadata=s.metadata;if(typeof s.callback<"u")i.readCallback=s.callback;if(typeof s.enabled<"u")i.enabled=s.enabled;this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,t,r,n,o){let i={resourceTemplate:r,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(c)=>{if(typeof c.name<"u"&&c.name!==e){if(delete this._registeredResourceTemplates[e],c.name)this._registeredResourceTemplates[c.name]=i}if(typeof c.title<"u")i.title=c.title;if(typeof c.template<"u")i.resourceTemplate=c.template;if(typeof c.metadata<"u")i.metadata=c.metadata;if(typeof c.callback<"u")i.readCallback=c.callback;if(typeof c.enabled<"u")i.enabled=c.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let s=r.uriTemplate.variableNames;if(Array.isArray(s)&&s.some((c)=>!!r.completeCallback(c)))this.setCompletionRequestHandler();return i}_createRegisteredPrompt(e,t,r,n,o){let i={title:t,description:r,argsSchema:n===void 0?void 0:Gc(n),callback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(s)=>{if(typeof s.name<"u"&&s.name!==e){if(delete this._registeredPrompts[e],s.name)this._registeredPrompts[s.name]=i}if(typeof s.title<"u")i.title=s.title;if(typeof s.description<"u")i.description=s.description;if(typeof s.argsSchema<"u")i.argsSchema=Gc(s.argsSchema);if(typeof s.callback<"u")i.callback=s.callback;if(typeof s.enabled<"u")i.enabled=s.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[e]=i,n){if(Object.values(n).some((a)=>{let c=a instanceof sy?a._def?.innerType:a;return gv(c)}))this.setCompletionRequestHandler()}return i}_createRegisteredTool(e,t,r,n,o,i,s,a,c){yv(e);let l={title:t,description:r,inputSchema:a4(n),outputSchema:a4(o),annotations:i,execution:s,_meta:a,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:(d)=>{if(typeof d.name<"u"&&d.name!==e){if(typeof d.name==="string")yv(d.name);if(delete this._registeredTools[e],d.name)this._registeredTools[d.name]=l}if(typeof d.title<"u")l.title=d.title;if(typeof d.description<"u")l.description=d.description;if(typeof d.paramsSchema<"u")l.inputSchema=Gc(d.paramsSchema);if(typeof d.outputSchema<"u")l.outputSchema=Gc(d.outputSchema);if(typeof d.callback<"u")l.handler=d.callback;if(typeof d.annotations<"u")l.annotations=d.annotations;if(typeof d._meta<"u")l._meta=d._meta;if(typeof d.enabled<"u")l.enabled=d.enabled;this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r,n,o,i;if(typeof t[0]==="string")r=t.shift();if(t.length>1){let a=t[0];if(xv(a)){if(n=t.shift(),t.length>1&&typeof t[0]==="object"&&t[0]!==null&&!xv(t[0]))i=t.shift()}else if(typeof a==="object"&&a!==null){if(Object.values(a).some((c)=>typeof c==="object"&&c!==null))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let s=t[0];return this._createRegisteredTool(e,void 0,r,n,o,i,{taskSupport:"forbidden"},void 0,s)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:n,description:o,inputSchema:i,outputSchema:s,annotations:a,_meta:c}=t;return this._createRegisteredTool(e,n,o,i,s,a,{taskSupport:"forbidden"},c,r)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let r;if(typeof t[0]==="string")r=t.shift();let n;if(t.length>1)n=t.shift();let o=t[0],i=this._createRegisteredPrompt(e,void 0,r,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:n,description:o,argsSchema:i}=t,s=this._createRegisteredPrompt(e,n,o,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var Mae={type:"object",properties:{}};function u4(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function l4(e){return"_def"in e||"_zod"in e||u4(e)}function xv(e){if(typeof e!=="object"||e===null)return!1;if(l4(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some(u4)}function a4(e){if(!e)return;if(xv(e))return Gc(e);if(!l4(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function Nae(e){let t=xa(e);if(!t)return[];return Object.entries(t).map(([r,n])=>{let o=g5(n),i=y5(n);return{name:r,description:o,required:!i}})}function ja(e){let r=xa(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=ny(r);if(typeof n==="string")return n;throw Error("Schema method literal must be a string")}function c4(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var lm={completion:{values:[],hasMore:!1}};import p4 from"node:process";class Sv{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
135
135
  `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),$ae(t)}clear(){this._buffer=void 0}}function $ae(e){return aO.parse(JSON.parse(e))}function d4(e){return JSON.stringify(e)+`
136
- `}class _v{constructor(e=p4.stdin,t=p4.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Sv,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise((t)=>{let r=d4(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var x0={name:"@0xmonaco/mcp-server",version:"1.0.85",type:"module",homepage:"https://docs.0xmonaco.com/sdk/typescript",description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"1.0.85","@0xmonaco/types":"1.0.85","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.56.3",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var w0=["read","market-maker","full"],Ti=[{name:"search_docs",description:"Search the Monaco documentation for protocol, SDK, trading, and development guides.",category:"search",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pairs",description:"List trading pairs with optional filters (market type, base/quote token, active status).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pair_by_symbol",description:"Look up a trading pair by symbol (e.g. `BTC/USDC`).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_candlesticks",description:"Fetch OHLCV candlestick data for a trading pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_metadata",description:"Get tick size, minimum order size, and trading rules for a pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_screener",description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_stats",description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_config",description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_summary",description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_mark_price",description:"Get the current mark price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_index_price",description:"Get the current index (oracle) price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_state",description:"Get the current funding rate and next funding time for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_open_interest",description:"Get the current gross open interest (longs plus shorts) for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_history",description:"List historical funding-rate records for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_all_funding_history",description:"List historical funding-rate records across all perpetual markets.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_orderbook",description:"Fetch a current orderbook snapshot with bids and asks.",category:"orderbook",authMode:"public",sideEffect:"read-only"},{name:"get_trades",description:"Fetch historical trades for a trading pair.",category:"trades",authMode:"public",sideEffect:"read-only"},{name:"place_limit_order",description:"Place a limit order with price, quantity, and time-in-force. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 24 hours of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"place_market_order",description:"Place a market order — executes immediately inside a mandatory 1,000 bps protective price band, so it may partially fill or be rejected. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 24 hours of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — an ambiguous failure (timeout/network error/5xx with no order) cannot be resolved from inside MCP, which has no order-stream tool; never retry, and report the ambiguity instead.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"cancel_order",description:"Cancel a single order by ID.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_orders",description:"Cancel multiple orders by ID (non-atomic — a failed leg does not stop the others).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_all_orders",description:"Cancel all open orders, optionally filtered to a trading pair (unfiltered, it cancels your entire open-order book).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_close_all_positions",description:"Close all open perpetual positions with market reduce-only orders (best-effort, optional pair-set and side filters).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_orders",description:"List your orders with optional filters.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_order",description:"Get details for a specific order by ID.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_positions",description:"List your perpetual positions with optional filters (margin account, trading pair, status).",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position",description:"Get details for a specific perpetual position by ID.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_risk",description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_history",description:"List historical (closed/reduced) perpetual position records with optional filters.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_pnl_history",description:"Get the PnL history time series for a perpetual position over an interval.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"close_position",description:"Close a perpetual position with a market, limit, or IOC reduce order.",category:"positions",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_profile",description:"Fetch your core profile (address, username, account type, withdrawal status).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balances",description:"List token balances with pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balance_by_asset",description:"Get balance for a specific asset.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_movements",description:"Fetch transaction and movement history with optional filters.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_user_trades",description:"List your own trade fills with optional filters and cursor pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_funding_payments",description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_summary",description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_performance",description:"Get your portfolio performance time series over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_realized_pnl",description:"Get your realized PnL breakdown over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_assets",description:"Get your per-asset portfolio allocation and balances over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_margin",description:"Get your portfolio margin overview (collateral, maintenance margin, health).",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_margin_accounts",description:"List your margin accounts with optional filters (state, trading pair).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_summary",description:"Get your parent (cross) margin account summary.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_available_collateral",description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_movements",description:"List collateral movements for your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_parent_margin_order_risk",description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_risk_bucket_order_risk",description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_collateral_to_parent_margin_account",description:"Move collateral from spot into your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_parent_margin_account",description:"Move collateral out of your parent (cross) margin account back to spot.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_risk_bucket",description:"Allocate collateral into an isolated or cross risk bucket.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_sub_account",description:"Move collateral from your default (parent) margin account into one of your margin sub-accounts.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_sub_account",description:"Move collateral from one of your margin sub-accounts back to your default (parent) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"simulate_fees",description:"Simulate fees for an order before placing it.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_fee_tier",description:"Get your current fee tier, rolling 14-day volumes, and a pair's fee schedule.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_approve",description:"Approve the vault contract to spend a token.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_deposit",description:"Deposit tokens into the vault (optional `target`: `spot` default, or `margin` to route into collateral).",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_withdraw",description:"Withdraw tokens from the vault.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_get_allowance",description:"Check current token allowance for the vault.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_needs_approval",description:"Check whether an approval transaction is needed before depositing.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_pending_withdrawals",description:"List your pending withdrawals still awaiting on-chain root confirmation.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"request_faucet",description:"Request test tokens for all trading pairs.",category:"faucet",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",excludedOnMainnet:!0},{name:"get_faucet_info",description:"Check remaining faucet quota, next-request time, and recent mint history.",category:"faucet",authMode:"authenticated",capability:"read",sideEffect:"read-only",excludedOnMainnet:!0},{name:"get_trader_code_info",description:"Look up a trader code's details (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"check_trader_code_availability",description:"Public advisory check of whether a custom TraderCode handle is available (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"get_my_trader_code",description:"Fetch your own trader code.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"set_trader_code",description:"Claim or edit your custom (vanity) TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your TraderCodes rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned TraderCodes rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"list_lead_traders",description:"Public copy trading leaderboard: lead traders ranked by ROI, PnL, followers, allocated AUM, marked AUM or win rate over a stats window (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"get_lead_trader",description:"Public profile, follow summary and stats of one lead trader, by custom TraderCode handle (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"list_lead_trader_closed_trades",description:"Public list of a lead trader's closed trades, newest first (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"list_lead_trader_open_positions",description:"Open positions of a lead trader you currently follow (followers only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_lead_trader",description:"Fetch your own lead trader profile, follow summary and stats.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_my_followers",description:"List your followers, as a lead trader.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_my_follows",description:"List your copy trading follows and their settings.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_follow",description:"Fetch one of your follows with its most recent skipped mirrors and its copy account's marked equity.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"preview_follow",description:"Preview what following a lead trader with copyExisting would open: estimated margin and fees and how many positions would be copied (read-only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_follow_leader_positions",description:"Open positions of the lead trader one of your follows copies (live follows only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"upsert_lead_trader",description:"Register as a lead trader, or edit your lead profile (profit share, bio, status, minimum allocation).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"upsert_follow",description:"Follow a lead trader (moves the allocation into a new copy account) or edit one of your follows.",category:"copy-trading",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"stop_follow",description:"Stop one of your follows: the leader's fills stop being mirrored.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"close_follow_positions",description:"Close one follow's copy positions at market and keep the follow (it keeps mirroring).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"close_all_copy_positions",description:"Close the copy positions of all your follows at market and keep the follows.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"add_follow_position_margin",description:"Add margin to one of your copy positions from the follow's copy account (lowers its leverage; your margin account is never touched; no reduction). Not idempotent — after a timeout, read the follow before retrying, or the amount may be added twice.",category:"copy-trading",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_pulse",description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags.",category:"pulse",authMode:"public",sideEffect:"read-only"}],B1e=Ti.map((e)=>e.name),f4=Ti.filter((e)=>e.authMode==="public").map((e)=>e.name),D1e=Ti.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),F1e=Ti.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),U1e=Ti.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),j1e=Ti.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),m4=Ti.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name);var Lae=new Map(Ti.map((e)=>[e.name,e.sideEffect]));function h4(e){let t=Lae.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var g4={read:0,"market-maker":1,full:2},Tv=f4,vv=Object.fromEntries(Ti.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),y4=Object.fromEntries(Object.entries(vv).map(([e,t])=>[e,t.capability])),G1e=new Set(m4);function b4(e){let t=vv[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function x4(e){return b4(e)==="read"}function w4(e,t){if(t.network==="mainnet"&&vv[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(Tv.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return g4[t.capability]>=g4[b4(e)]}var Bae=new Set([...Tv,...Object.keys(y4)]),Dae={mainnet:"https://evm-rpc.sei-apis.com",development:"https://evm-rpc-testnet.sei-apis.com",staging:"https://evm-rpc-testnet.sei-apis.com",local:"http://localhost:8545"};function S4(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function Jc(e=process.env){let t=e.MONACO_PRIVATE_KEY||null;if(t&&!t.startsWith("0x"))throw Error("MONACO_PRIVATE_KEY must start with '0x'.");let r=e.MONACO_CLIENT_ID||null;if(t&&!r)throw Error("MONACO_CLIENT_ID is required when MONACO_PRIVATE_KEY is set.");let n=["mainnet","development","staging","local"],o=e.MONACO_NETWORK;if(t&&!o)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${n.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=o||"mainnet";if(!n.includes(i))throw Error(`MONACO_NETWORK must be one of: ${n.join(", ")}.`);let s=i,a=e.MONACO_CAPABILITY;if(a&&!w0.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${w0.join(", ")}.`);let c=a||"read",l=S4(e.MONACO_TOOL_ALLOWLIST),d=S4(e.MONACO_TOOL_DENYLIST),f=[...l,...d].filter((x)=>!Bae.has(x)).length;if(f>0)throw Error(`${f} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let h=e.MONACO_RPC_URL||Dae[s],g=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let x=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!x)throw Error("MONACO_DELEGATED_OWNER_USER_ID must be a non-empty owner user id when set.");if(!t||!r)throw Error("MONACO_DELEGATED_OWNER_USER_ID requires MONACO_PRIVATE_KEY and MONACO_CLIENT_ID (the agent authenticates as itself before adopting the owner).");g=x}return{privateKey:t,clientId:r,network:s,seiRpcUrl:h,capability:c,allow:l,deny:d,delegatedOwnerUserId:g}}function Fae(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function Jr(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>Jr(r));let t={};for(let[r,n]of Object.entries(e))t[Fae(r)]=typeof n==="object"&&n!==null?Jr(n):n;return t}function _4(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Ev=(e)=>e?`"${e}" `:"";function Uae(e,t=""){if(typeof e!=="number")throw TypeError(Ev(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(Ev(t)+"expected integer >= 0, got "+e);return e}function S0(e,t,r=""){if(_4(e)&&(t===void 0||e.length===t))return e;if(t!==void 0)Uae(t,"length");let n=_4(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=Ev(r)+"expected Uint8Array"+o+", got "+i;if(!n)throw TypeError(s);throw RangeError(s)}var jae=(e,t)=>{if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},T4=(e,t)=>{jae(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw TypeError(`"${t}.__proto__" is not allowed`)};function Pv(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function E4(e,t){S0(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw RangeError('"output" expected length >= '+r)}function _0(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function T0(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Lo(e,t){return e<<32-t|e>>>t}var P4=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),qae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function hs(e){if(S0(e),P4)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=qae[e[r]];return t}function v4(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function dm(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(P4)try{return Uint8Array.fromHex(e)}catch(o){if(o instanceof SyntaxError)throw RangeError(o.message);throw o}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=v4(e.charCodeAt(i)),a=v4(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function Qc(e){if(typeof e!=="string")throw TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{_0(t)}}function Hae(e,t,r="opts"){if(T4(e,"defaults"),t!==void 0)T4(t,r);return Object.assign(Object.create(null),e,t)}function A4(e,t={}){if(typeof e!=="function")throw TypeError('"hashCons" expected function, got type='+typeof e);t=Hae({},t,"info");let r=(o,i)=>e(i).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=(o)=>e(o),Object.assign(r,t),Object.freeze(r)}var I4=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Cv();tu();Gv();Ql();bm();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Pi=BigInt(0),Sn=BigInt(1),mB=BigInt(2),cce=BigInt(8),uce={zip215:!0};function lce(e){let t=xm(e);return Ss(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function hB(e){let t=lce(e),{Fp:r,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,l=mB<<BigInt(a*8)-Sn,d=r.create,f=_s(t.n,t.nBitLength);function h(D,q){let Q=r.sqr(D),ke=r.sqr(q),ne=r.add(r.mul(t.a,Q),ke),Le=r.add(r.ONE,r.mul(t.d,r.mul(Q,ke)));return r.eql(ne,Le)}if(!h(t.Gx,t.Gy))throw Error("bad curve params: generator point");let g=t.uvRatio||((D,q)=>{try{return{isValid:!0,value:r.sqrt(D*r.inv(q))}}catch(Q){return{isValid:!1,value:Pi}}}),x=t.adjustScalarBytes||((D)=>D),w=t.domain||((D,q,Q)=>{if(Ei("phflag",Q),q.length||Q)throw Error("Contexts/pre-hash are not supported");return D});function S(D,q,Q=!1){let ke=Q?Sn:Pi;Yn("coordinate "+D,q,ke,l)}function _(D){if(!(D instanceof v))throw Error("ExtendedPoint expected")}let A=Yl((D,q)=>{let{ex:Q,ey:ke,ez:ne}=D,Le=D.is0();if(q==null)q=Le?cce:r.inv(ne);let Ce=d(Q*q),Oe=d(ke*q),ct=d(ne*q);if(Le)return{x:Pi,y:Sn};if(ct!==Sn)throw Error("invZ was invalid");return{x:Ce,y:Oe}}),T=Yl((D)=>{let{a:q,d:Q}=t;if(D.is0())throw Error("bad point: ZERO");let{ex:ke,ey:ne,ez:Le,et:Ce}=D,Oe=d(ke*ke),ct=d(ne*ne),gt=d(Le*Le),yt=d(gt*gt),Ft=d(Oe*q),Kt=d(gt*d(Ft+ct)),pr=d(yt+d(Q*d(Oe*ct)));if(Kt!==pr)throw Error("bad point: equation left != right (1)");let _r=d(ke*ne),ir=d(Le*Ce);if(_r!==ir)throw Error("bad point: equation left != right (2)");return!0});class v{constructor(D,q,Q,ke){S("x",D),S("y",q),S("z",Q,!0),S("t",ke),this.ex=D,this.ey=q,this.ez=Q,this.et=ke,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(D){if(D instanceof v)throw Error("extended point not allowed");let{x:q,y:Q}=D||{};return S("x",q),S("y",Q),new v(q,Q,Sn,d(q*Q))}static normalizeZ(D){let q=Jl(r,D.map((Q)=>Q.ez));return D.map((Q,ke)=>Q.toAffine(q[ke])).map(v.fromAffine)}static msm(D,q){return O0(v,f,D,q)}_setWindowSize(D){O.setWindowSize(this,D)}assertValidity(){T(this)}equals(D){_(D);let{ex:q,ey:Q,ez:ke}=this,{ex:ne,ey:Le,ez:Ce}=D,Oe=d(q*Ce),ct=d(ne*ke),gt=d(Q*Ce),yt=d(Le*ke);return Oe===ct&&gt===yt}is0(){return this.equals(v.ZERO)}negate(){return new v(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:D}=t,{ex:q,ey:Q,ez:ke}=this,ne=d(q*q),Le=d(Q*Q),Ce=d(mB*d(ke*ke)),Oe=d(D*ne),ct=q+Q,gt=d(d(ct*ct)-ne-Le),yt=Oe+Le,Ft=yt-Ce,Kt=Oe-Le,pr=d(gt*Ft),_r=d(yt*Kt),ir=d(gt*Kt),At=d(Ft*yt);return new v(pr,_r,At,ir)}add(D){_(D);let{a:q,d:Q}=t,{ex:ke,ey:ne,ez:Le,et:Ce}=this,{ex:Oe,ey:ct,ez:gt,et:yt}=D,Ft=d(ke*Oe),Kt=d(ne*ct),pr=d(Ce*Q*yt),_r=d(Le*gt),ir=d((ke+ne)*(Oe+ct)-Ft-Kt),At=_r-pr,Vr=_r+pr,Vi=d(Kt-q*Ft),Lu=d(ir*At),xc=d(Vr*Vi),$p=d(ir*Vi),no=d(At*Vr);return new v(Lu,xc,no,$p)}subtract(D){return this.add(D.negate())}wNAF(D){return O.wNAFCached(this,D,v.normalizeZ)}multiply(D){let q=D;Yn("scalar",q,Sn,n);let{p:Q,f:ke}=this.wNAF(q);return v.normalizeZ([Q,ke])[0]}multiplyUnsafe(D,q=v.ZERO){let Q=D;if(Yn("scalar",Q,Pi,n),Q===Pi)return k;if(this.is0()||Q===Sn)return this;return O.wNAFCachedUnsafe(this,Q,v.normalizeZ,q)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,n).is0()}toAffine(D){return A(this,D)}clearCofactor(){let{h:D}=t;if(D===Sn)return this;return this.multiplyUnsafe(D)}static fromHex(D,q=!1){let{d:Q,a:ke}=t,ne=r.BYTES;D=nr("pointHex",D,ne),Ei("zip215",q);let Le=D.slice(),Ce=D[ne-1];Le[ne-1]=Ce&-129;let Oe=ou(Le),ct=q?l:r.ORDER;Yn("pointHex.y",Oe,Pi,ct);let gt=d(Oe*Oe),yt=d(gt-Sn),Ft=d(Q*gt-ke),{isValid:Kt,value:pr}=g(yt,Ft);if(!Kt)throw Error("Point.fromHex: invalid y coordinate");let _r=(pr&Sn)===Sn,ir=(Ce&128)!==0;if(!q&&pr===Pi&&ir)throw Error("Point.fromHex: x=0 and x_0=1");if(ir!==_r)pr=d(-pr);return v.fromAffine({x:pr,y:Oe})}static fromPrivateKey(D){let{scalar:q}=M(D);return E.multiply(q)}toRawBytes(){let{x:D,y:q}=this.toAffine(),Q=Kl(q,r.BYTES);return Q[Q.length-1]|=D&Sn?128:0,Q}toHex(){return Va(this.toRawBytes())}}v.BASE=new v(t.Gx,t.Gy,Sn,d(t.Gx*t.Gy)),v.ZERO=new v(Pi,Sn,Sn,Pi);let{BASE:E,ZERO:k}=v,O=C0(v,a*8);function B(D){return Lt(D,n)}function G(D){return B(ou(D))}function M(D){let q=r.BYTES;D=nr("private key",D,q);let Q=nr("hashed private key",i(D),2*q),ke=x(Q.slice(0,q)),ne=Q.slice(q,2*q),Le=G(ke);return{head:ke,prefix:ne,scalar:Le}}function J(D){let{head:q,prefix:Q,scalar:ke}=M(D),ne=E.multiply(ke),Le=ne.toRawBytes();return{head:q,prefix:Q,scalar:ke,point:ne,pointBytes:Le}}function W(D){return J(D).pointBytes}function he(D=Uint8Array.of(),...q){let Q=Za(...q);return G(i(w(Q,nr("context",D),!!o)))}function ge(D,q,Q={}){if(D=nr("message",D),o)D=o(D);let{prefix:ke,scalar:ne,pointBytes:Le}=J(q),Ce=he(Q.context,ke,D),Oe=E.multiply(Ce).toRawBytes(),ct=he(Q.context,Oe,Le,D),gt=B(Ce+ct*ne);Yn("signature.s",gt,Pi,n);let yt=Za(Oe,Kl(gt,r.BYTES));return nr("result",yt,r.BYTES*2)}let j=uce;function se(D,q,Q,ke=j){let{context:ne,zip215:Le}=ke,Ce=r.BYTES;if(D=nr("signature",D,2*Ce),q=nr("message",q),Q=nr("publicKey",Q,Ce),Le!==void 0)Ei("zip215",Le);if(o)q=o(q);let Oe=ou(D.slice(Ce,2*Ce)),ct,gt,yt;try{ct=v.fromHex(Q,Le),gt=v.fromHex(D.slice(0,Ce),Le),yt=E.multiplyUnsafe(Oe)}catch(pr){return!1}if(!Le&&ct.isSmallOrder())return!1;let Ft=he(ne,gt.toRawBytes(),ct.toRawBytes(),q);return gt.add(ct.multiplyUnsafe(Ft)).subtract(yt).clearCofactor().equals(v.ZERO)}return E._setWindowSize(8),{CURVE:t,getPublicKey:W,sign:ge,verify:se,ExtendedPoint:v,utils:{getExtendedPublicKey:J,randomPrivateKey:()=>s(r.BYTES),precompute(D=8,q=v.BASE){return q._setWindowSize(D),q.multiply(BigInt(3)),q}}}}Ql();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Vv=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),gB=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Eve=BigInt(0),dce=BigInt(1),yB=BigInt(2),Pve=BigInt(3),pce=BigInt(5),fce=BigInt(8);function mce(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=Vv,a=e*e%i*e%i,c=or(a,yB,i)*a%i,l=or(c,dce,i)*e%i,d=or(l,pce,i)*l%i,f=or(d,t,i)*d%i,h=or(f,r,i)*f%i,g=or(h,n,i)*h%i,x=or(g,o,i)*g%i,w=or(x,o,i)*g%i,S=or(w,t,i)*d%i;return{pow_p_5_8:or(S,yB,i)*e%i,b2:a}}function hce(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function gce(e,t){let r=Vv,n=Lt(t*t*t,r),o=Lt(n*n*t,r),i=mce(e*o).pow_p_5_8,s=Lt(e*n*i,r),a=Lt(t*s*s,r),c=s,l=Lt(s*gB,r),d=a===e,f=a===Lt(-e,r),h=a===Lt(-e*gB,r);if(d)s=c;if(f||h)s=l;if(aB(s,r))s=Lt(-s,r);return{isValid:d||f,value:s}}var bB=(()=>_s(Vv,void 0,!0))(),yce=(()=>({a:bB.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:bB,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:fce,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:K4,randomBytes:P0,adjustScalarBytes:hce,uvRatio:gce}))(),Xl=(()=>hB(yce))();var bce=(e)=>e/4294967296|0,xce=(e)=>e>>>0;function xB(e,t,r,n){let o=bce(r),i=xce(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}function wB(e,t,r){return e&t^~e&r}function SB(e,t,r){return e&t^e&r^t&r}class Zv{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=T0(this.buffer)}update(e){Pv(this),S0(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length,i=!1;for(let s=0;s<o;){let a=Math.min(n-this.pos,o-s);if(a===n){let c=T0(e);for(;n<=o-s;s+=n)this.process(c,s);i=!0;continue}if(r.set(s===0&&a===o?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n)this.process(t,0),this.pos=0,i=!0}if(this.length+=e.length,i)this.roundClean();return this}digestInto(e){Pv(this),E4(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,t.fill(0,i),this.padOffset>n-i)this.process(r,0),t.fill(0);xB(r,n-8,this.length*8,o),this.process(r,0),this.roundClean();let s=e===t?r:T0(e),a=this.outputLen,c=a/4,l=this.get();if(a%4||c>l.length)throw Error("invalid outputLen");for(let d=0;d<c;d++)s.setUint32(4*d,l[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:o,pos:i}=this;if(e.destroyed=o,e.finished=n,e.length=r,e.pos=i,i)e.buffer.set(t);return e}clone(){return this._cloneInto()}}var _B=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var wce=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Wa=new Uint32Array(64);class TB extends Zv{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1);this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)Wa[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=Wa[d-15],h=Wa[d-2],g=Lo(f,7)^Lo(f,18)^f>>>3,x=Lo(h,17)^Lo(h,19)^h>>>10;Wa[d]=x+Wa[d-7]+g+Wa[d-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:l}=this;for(let d=0;d<64;d++){let f=Lo(s,6)^Lo(s,11)^Lo(s,25),h=l+f+wB(s,a,c)+wce[d]+Wa[d]|0,x=(Lo(r,2)^Lo(r,13)^Lo(r,22))+SB(r,n,o)|0;l=c,c=a,a=s,s=i+h|0,i=o,o=n,n=r,r=h+x|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,o,i,s,a,c,l)}roundClean(){_0(Wa)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),_0(this.buffer)}}class vB extends TB{constructor(){super(32,_B)}}var M0=A4(()=>new vB,I4(1));function N0(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=Xl.utils.randomPrivateKey();return{publicKey:Xl.getPublicKey(e),privateKey:e}}function $0(e){return hs(e.publicKey)}function z0(e){return hs(e.privateKey)}function EB(e,t){return{publicKey:dm(e),privateKey:dm(t)}}function PB(e){return hs(M0(e))}function AB(e,t,r,n){return`${e.toUpperCase()}
136
+ `}class _v{constructor(e=p4.stdin,t=p4.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Sv,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise((t)=>{let r=d4(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var x0={name:"@0xmonaco/mcp-server",version:"1.0.86",type:"module",homepage:"https://docs.0xmonaco.com/sdk/typescript",description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"1.0.86","@0xmonaco/types":"1.0.86","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.56.3",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var w0=["read","market-maker","full"],Ti=[{name:"search_docs",description:"Search the Monaco documentation for protocol, SDK, trading, and development guides.",category:"search",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pairs",description:"List trading pairs with optional filters (market type, base/quote token, active status).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pair_by_symbol",description:"Look up a trading pair by symbol (e.g. `BTC/USDC`).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_candlesticks",description:"Fetch OHLCV candlestick data for a trading pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_metadata",description:"Get tick size, minimum order size, and trading rules for a pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_screener",description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_stats",description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_config",description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_summary",description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_mark_price",description:"Get the current mark price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_index_price",description:"Get the current index (oracle) price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_state",description:"Get the current funding rate and next funding time for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_open_interest",description:"Get the current one-sided LONG open interest (each contract counted once) for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_history",description:"List historical funding-rate records for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_all_funding_history",description:"List historical funding-rate records across all perpetual markets.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_orderbook",description:"Fetch a current orderbook snapshot with bids and asks.",category:"orderbook",authMode:"public",sideEffect:"read-only"},{name:"get_trades",description:"Fetch historical trades for a trading pair.",category:"trades",authMode:"public",sideEffect:"read-only"},{name:"place_limit_order",description:"Place a limit order with price, quantity, and time-in-force. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 24 hours of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"place_market_order",description:"Place a market order — executes immediately inside a mandatory 1,000 bps protective price band, so it may partially fill or be rejected. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 24 hours of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — an ambiguous failure (timeout/network error/5xx with no order) cannot be resolved from inside MCP, which has no order-stream tool; never retry, and report the ambiguity instead.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"cancel_order",description:"Cancel a single order by ID.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_orders",description:"Cancel multiple orders by ID (non-atomic — a failed leg does not stop the others).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_all_orders",description:"Cancel all open orders, optionally filtered to a trading pair (unfiltered, it cancels your entire open-order book).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_close_all_positions",description:"Close all open perpetual positions with market reduce-only orders (best-effort, optional pair-set and side filters).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_orders",description:"List your orders with optional filters.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_order",description:"Get details for a specific order by ID.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_positions",description:"List your perpetual positions with optional filters (margin account, trading pair, status).",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position",description:"Get details for a specific perpetual position by ID.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_risk",description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_history",description:"List historical (closed/reduced) perpetual position records with optional filters.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_pnl_history",description:"Get the PnL history time series for a perpetual position over an interval.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"close_position",description:"Close a perpetual position with a market, limit, or IOC reduce order.",category:"positions",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_profile",description:"Fetch your core profile (address, username, account type, withdrawal status).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balances",description:"List token balances with pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balance_by_asset",description:"Get balance for a specific asset.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_movements",description:"Fetch transaction and movement history with optional filters.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_user_trades",description:"List your own trade fills with optional filters and cursor pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_funding_payments",description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_summary",description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_performance",description:"Get your portfolio performance time series over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_realized_pnl",description:"Get your realized PnL breakdown over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_assets",description:"Get your per-asset portfolio allocation and balances over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_margin",description:"Get your portfolio margin overview (collateral, maintenance margin, health).",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_margin_accounts",description:"List your margin accounts with optional filters (state, trading pair).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_summary",description:"Get your parent (cross) margin account summary.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_available_collateral",description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_movements",description:"List collateral movements for your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_parent_margin_order_risk",description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_risk_bucket_order_risk",description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_collateral_to_parent_margin_account",description:"Move collateral from spot into your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_parent_margin_account",description:"Move collateral out of your parent (cross) margin account back to spot.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_risk_bucket",description:"Allocate collateral into an isolated or cross risk bucket.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_sub_account",description:"Move collateral from your default (parent) margin account into one of your margin sub-accounts.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_sub_account",description:"Move collateral from one of your margin sub-accounts back to your default (parent) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"simulate_fees",description:"Simulate fees for an order before placing it.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_fee_tier",description:"Get your current fee tier, rolling 14-day volumes, and a pair's fee schedule.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_approve",description:"Approve the vault contract to spend a token.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_deposit",description:"Deposit tokens into the vault (optional `target`: `spot` default, or `margin` to route into collateral).",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_withdraw",description:"Withdraw tokens from the vault.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_get_allowance",description:"Check current token allowance for the vault.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_needs_approval",description:"Check whether an approval transaction is needed before depositing.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_pending_withdrawals",description:"List your pending withdrawals still awaiting on-chain root confirmation.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"request_faucet",description:"Request test tokens for all trading pairs.",category:"faucet",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",excludedOnMainnet:!0},{name:"get_faucet_info",description:"Check remaining faucet quota, next-request time, and recent mint history.",category:"faucet",authMode:"authenticated",capability:"read",sideEffect:"read-only",excludedOnMainnet:!0},{name:"get_trader_code_info",description:"Look up a trader code's details (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"check_trader_code_availability",description:"Public advisory check of whether a custom TraderCode handle is available (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"get_my_trader_code",description:"Fetch your own trader code.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"set_trader_code",description:"Claim or edit your custom (vanity) TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your TraderCodes rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned TraderCodes rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"list_lead_traders",description:"Public copy trading leaderboard: lead traders ranked by ROI, PnL, followers, allocated AUM, marked AUM or win rate over a stats window (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"get_lead_trader",description:"Public profile, follow summary and stats of one lead trader, by custom TraderCode handle (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"list_lead_trader_closed_trades",description:"Public list of a lead trader's closed trades, newest first (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"list_lead_trader_open_positions",description:"Open positions of a lead trader you currently follow (followers only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_lead_trader",description:"Fetch your own lead trader profile, follow summary and stats.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_my_followers",description:"List your followers, as a lead trader.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_my_follows",description:"List your copy trading follows and their settings.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_follow",description:"Fetch one of your follows with its most recent skipped mirrors and its copy account's marked equity.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"preview_follow",description:"Preview what following a lead trader with copyExisting would open: estimated margin and fees and how many positions would be copied (read-only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_follow_leader_positions",description:"Open positions of the lead trader one of your follows copies (live follows only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"upsert_lead_trader",description:"Register as a lead trader, or edit your lead profile (profit share, bio, status, minimum allocation).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"upsert_follow",description:"Follow a lead trader (moves the allocation into a new copy account) or edit one of your follows.",category:"copy-trading",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"stop_follow",description:"Stop one of your follows: the leader's fills stop being mirrored.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"close_follow_positions",description:"Close one follow's copy positions at market and keep the follow (it keeps mirroring).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"close_all_copy_positions",description:"Close the copy positions of all your follows at market and keep the follows.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"add_follow_position_margin",description:"Add margin to one of your copy positions from the follow's copy account (lowers its leverage; your margin account is never touched; no reduction). Not idempotent — after a timeout, read the follow before retrying, or the amount may be added twice.",category:"copy-trading",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_pulse",description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags.",category:"pulse",authMode:"public",sideEffect:"read-only"}],B1e=Ti.map((e)=>e.name),f4=Ti.filter((e)=>e.authMode==="public").map((e)=>e.name),D1e=Ti.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),F1e=Ti.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),U1e=Ti.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),j1e=Ti.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),m4=Ti.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name);var Lae=new Map(Ti.map((e)=>[e.name,e.sideEffect]));function h4(e){let t=Lae.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var g4={read:0,"market-maker":1,full:2},Tv=f4,vv=Object.fromEntries(Ti.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),y4=Object.fromEntries(Object.entries(vv).map(([e,t])=>[e,t.capability])),G1e=new Set(m4);function b4(e){let t=vv[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function x4(e){return b4(e)==="read"}function w4(e,t){if(t.network==="mainnet"&&vv[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(Tv.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return g4[t.capability]>=g4[b4(e)]}var Bae=new Set([...Tv,...Object.keys(y4)]),Dae={mainnet:"https://evm-rpc.sei-apis.com",development:"https://evm-rpc-testnet.sei-apis.com",staging:"https://evm-rpc-testnet.sei-apis.com",local:"http://localhost:8545"};function S4(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function Jc(e=process.env){let t=e.MONACO_PRIVATE_KEY||null;if(t&&!t.startsWith("0x"))throw Error("MONACO_PRIVATE_KEY must start with '0x'.");let r=e.MONACO_CLIENT_ID||null;if(t&&!r)throw Error("MONACO_CLIENT_ID is required when MONACO_PRIVATE_KEY is set.");let n=["mainnet","development","staging","local"],o=e.MONACO_NETWORK;if(t&&!o)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${n.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=o||"mainnet";if(!n.includes(i))throw Error(`MONACO_NETWORK must be one of: ${n.join(", ")}.`);let s=i,a=e.MONACO_CAPABILITY;if(a&&!w0.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${w0.join(", ")}.`);let c=a||"read",l=S4(e.MONACO_TOOL_ALLOWLIST),d=S4(e.MONACO_TOOL_DENYLIST),f=[...l,...d].filter((x)=>!Bae.has(x)).length;if(f>0)throw Error(`${f} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let h=e.MONACO_RPC_URL||Dae[s],g=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let x=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!x)throw Error("MONACO_DELEGATED_OWNER_USER_ID must be a non-empty owner user id when set.");if(!t||!r)throw Error("MONACO_DELEGATED_OWNER_USER_ID requires MONACO_PRIVATE_KEY and MONACO_CLIENT_ID (the agent authenticates as itself before adopting the owner).");g=x}return{privateKey:t,clientId:r,network:s,seiRpcUrl:h,capability:c,allow:l,deny:d,delegatedOwnerUserId:g}}function Fae(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function Jr(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>Jr(r));let t={};for(let[r,n]of Object.entries(e))t[Fae(r)]=typeof n==="object"&&n!==null?Jr(n):n;return t}function _4(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Ev=(e)=>e?`"${e}" `:"";function Uae(e,t=""){if(typeof e!=="number")throw TypeError(Ev(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(Ev(t)+"expected integer >= 0, got "+e);return e}function S0(e,t,r=""){if(_4(e)&&(t===void 0||e.length===t))return e;if(t!==void 0)Uae(t,"length");let n=_4(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=Ev(r)+"expected Uint8Array"+o+", got "+i;if(!n)throw TypeError(s);throw RangeError(s)}var jae=(e,t)=>{if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},T4=(e,t)=>{jae(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw TypeError(`"${t}.__proto__" is not allowed`)};function Pv(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function E4(e,t){S0(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw RangeError('"output" expected length >= '+r)}function _0(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function T0(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Lo(e,t){return e<<32-t|e>>>t}var P4=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),qae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function hs(e){if(S0(e),P4)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=qae[e[r]];return t}function v4(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function dm(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(P4)try{return Uint8Array.fromHex(e)}catch(o){if(o instanceof SyntaxError)throw RangeError(o.message);throw o}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=v4(e.charCodeAt(i)),a=v4(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function Qc(e){if(typeof e!=="string")throw TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{_0(t)}}function Hae(e,t,r="opts"){if(T4(e,"defaults"),t!==void 0)T4(t,r);return Object.assign(Object.create(null),e,t)}function A4(e,t={}){if(typeof e!=="function")throw TypeError('"hashCons" expected function, got type='+typeof e);t=Hae({},t,"info");let r=(o,i)=>e(i).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=(o)=>e(o),Object.assign(r,t),Object.freeze(r)}var I4=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Cv();tu();Gv();Ql();bm();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Pi=BigInt(0),Sn=BigInt(1),mB=BigInt(2),cce=BigInt(8),uce={zip215:!0};function lce(e){let t=xm(e);return Ss(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function hB(e){let t=lce(e),{Fp:r,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,l=mB<<BigInt(a*8)-Sn,d=r.create,f=_s(t.n,t.nBitLength);function h(D,q){let Q=r.sqr(D),ke=r.sqr(q),ne=r.add(r.mul(t.a,Q),ke),Le=r.add(r.ONE,r.mul(t.d,r.mul(Q,ke)));return r.eql(ne,Le)}if(!h(t.Gx,t.Gy))throw Error("bad curve params: generator point");let g=t.uvRatio||((D,q)=>{try{return{isValid:!0,value:r.sqrt(D*r.inv(q))}}catch(Q){return{isValid:!1,value:Pi}}}),x=t.adjustScalarBytes||((D)=>D),w=t.domain||((D,q,Q)=>{if(Ei("phflag",Q),q.length||Q)throw Error("Contexts/pre-hash are not supported");return D});function S(D,q,Q=!1){let ke=Q?Sn:Pi;Yn("coordinate "+D,q,ke,l)}function _(D){if(!(D instanceof v))throw Error("ExtendedPoint expected")}let A=Yl((D,q)=>{let{ex:Q,ey:ke,ez:ne}=D,Le=D.is0();if(q==null)q=Le?cce:r.inv(ne);let Ce=d(Q*q),Oe=d(ke*q),ct=d(ne*q);if(Le)return{x:Pi,y:Sn};if(ct!==Sn)throw Error("invZ was invalid");return{x:Ce,y:Oe}}),T=Yl((D)=>{let{a:q,d:Q}=t;if(D.is0())throw Error("bad point: ZERO");let{ex:ke,ey:ne,ez:Le,et:Ce}=D,Oe=d(ke*ke),ct=d(ne*ne),gt=d(Le*Le),yt=d(gt*gt),Ft=d(Oe*q),Kt=d(gt*d(Ft+ct)),pr=d(yt+d(Q*d(Oe*ct)));if(Kt!==pr)throw Error("bad point: equation left != right (1)");let _r=d(ke*ne),ir=d(Le*Ce);if(_r!==ir)throw Error("bad point: equation left != right (2)");return!0});class v{constructor(D,q,Q,ke){S("x",D),S("y",q),S("z",Q,!0),S("t",ke),this.ex=D,this.ey=q,this.ez=Q,this.et=ke,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(D){if(D instanceof v)throw Error("extended point not allowed");let{x:q,y:Q}=D||{};return S("x",q),S("y",Q),new v(q,Q,Sn,d(q*Q))}static normalizeZ(D){let q=Jl(r,D.map((Q)=>Q.ez));return D.map((Q,ke)=>Q.toAffine(q[ke])).map(v.fromAffine)}static msm(D,q){return O0(v,f,D,q)}_setWindowSize(D){O.setWindowSize(this,D)}assertValidity(){T(this)}equals(D){_(D);let{ex:q,ey:Q,ez:ke}=this,{ex:ne,ey:Le,ez:Ce}=D,Oe=d(q*Ce),ct=d(ne*ke),gt=d(Q*Ce),yt=d(Le*ke);return Oe===ct&&gt===yt}is0(){return this.equals(v.ZERO)}negate(){return new v(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:D}=t,{ex:q,ey:Q,ez:ke}=this,ne=d(q*q),Le=d(Q*Q),Ce=d(mB*d(ke*ke)),Oe=d(D*ne),ct=q+Q,gt=d(d(ct*ct)-ne-Le),yt=Oe+Le,Ft=yt-Ce,Kt=Oe-Le,pr=d(gt*Ft),_r=d(yt*Kt),ir=d(gt*Kt),At=d(Ft*yt);return new v(pr,_r,At,ir)}add(D){_(D);let{a:q,d:Q}=t,{ex:ke,ey:ne,ez:Le,et:Ce}=this,{ex:Oe,ey:ct,ez:gt,et:yt}=D,Ft=d(ke*Oe),Kt=d(ne*ct),pr=d(Ce*Q*yt),_r=d(Le*gt),ir=d((ke+ne)*(Oe+ct)-Ft-Kt),At=_r-pr,Vr=_r+pr,Vi=d(Kt-q*Ft),Lu=d(ir*At),xc=d(Vr*Vi),$p=d(ir*Vi),no=d(At*Vr);return new v(Lu,xc,no,$p)}subtract(D){return this.add(D.negate())}wNAF(D){return O.wNAFCached(this,D,v.normalizeZ)}multiply(D){let q=D;Yn("scalar",q,Sn,n);let{p:Q,f:ke}=this.wNAF(q);return v.normalizeZ([Q,ke])[0]}multiplyUnsafe(D,q=v.ZERO){let Q=D;if(Yn("scalar",Q,Pi,n),Q===Pi)return k;if(this.is0()||Q===Sn)return this;return O.wNAFCachedUnsafe(this,Q,v.normalizeZ,q)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,n).is0()}toAffine(D){return A(this,D)}clearCofactor(){let{h:D}=t;if(D===Sn)return this;return this.multiplyUnsafe(D)}static fromHex(D,q=!1){let{d:Q,a:ke}=t,ne=r.BYTES;D=nr("pointHex",D,ne),Ei("zip215",q);let Le=D.slice(),Ce=D[ne-1];Le[ne-1]=Ce&-129;let Oe=ou(Le),ct=q?l:r.ORDER;Yn("pointHex.y",Oe,Pi,ct);let gt=d(Oe*Oe),yt=d(gt-Sn),Ft=d(Q*gt-ke),{isValid:Kt,value:pr}=g(yt,Ft);if(!Kt)throw Error("Point.fromHex: invalid y coordinate");let _r=(pr&Sn)===Sn,ir=(Ce&128)!==0;if(!q&&pr===Pi&&ir)throw Error("Point.fromHex: x=0 and x_0=1");if(ir!==_r)pr=d(-pr);return v.fromAffine({x:pr,y:Oe})}static fromPrivateKey(D){let{scalar:q}=M(D);return E.multiply(q)}toRawBytes(){let{x:D,y:q}=this.toAffine(),Q=Kl(q,r.BYTES);return Q[Q.length-1]|=D&Sn?128:0,Q}toHex(){return Va(this.toRawBytes())}}v.BASE=new v(t.Gx,t.Gy,Sn,d(t.Gx*t.Gy)),v.ZERO=new v(Pi,Sn,Sn,Pi);let{BASE:E,ZERO:k}=v,O=C0(v,a*8);function B(D){return Lt(D,n)}function G(D){return B(ou(D))}function M(D){let q=r.BYTES;D=nr("private key",D,q);let Q=nr("hashed private key",i(D),2*q),ke=x(Q.slice(0,q)),ne=Q.slice(q,2*q),Le=G(ke);return{head:ke,prefix:ne,scalar:Le}}function J(D){let{head:q,prefix:Q,scalar:ke}=M(D),ne=E.multiply(ke),Le=ne.toRawBytes();return{head:q,prefix:Q,scalar:ke,point:ne,pointBytes:Le}}function W(D){return J(D).pointBytes}function he(D=Uint8Array.of(),...q){let Q=Za(...q);return G(i(w(Q,nr("context",D),!!o)))}function ge(D,q,Q={}){if(D=nr("message",D),o)D=o(D);let{prefix:ke,scalar:ne,pointBytes:Le}=J(q),Ce=he(Q.context,ke,D),Oe=E.multiply(Ce).toRawBytes(),ct=he(Q.context,Oe,Le,D),gt=B(Ce+ct*ne);Yn("signature.s",gt,Pi,n);let yt=Za(Oe,Kl(gt,r.BYTES));return nr("result",yt,r.BYTES*2)}let j=uce;function se(D,q,Q,ke=j){let{context:ne,zip215:Le}=ke,Ce=r.BYTES;if(D=nr("signature",D,2*Ce),q=nr("message",q),Q=nr("publicKey",Q,Ce),Le!==void 0)Ei("zip215",Le);if(o)q=o(q);let Oe=ou(D.slice(Ce,2*Ce)),ct,gt,yt;try{ct=v.fromHex(Q,Le),gt=v.fromHex(D.slice(0,Ce),Le),yt=E.multiplyUnsafe(Oe)}catch(pr){return!1}if(!Le&&ct.isSmallOrder())return!1;let Ft=he(ne,gt.toRawBytes(),ct.toRawBytes(),q);return gt.add(ct.multiplyUnsafe(Ft)).subtract(yt).clearCofactor().equals(v.ZERO)}return E._setWindowSize(8),{CURVE:t,getPublicKey:W,sign:ge,verify:se,ExtendedPoint:v,utils:{getExtendedPublicKey:J,randomPrivateKey:()=>s(r.BYTES),precompute(D=8,q=v.BASE){return q._setWindowSize(D),q.multiply(BigInt(3)),q}}}}Ql();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Vv=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),gB=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Eve=BigInt(0),dce=BigInt(1),yB=BigInt(2),Pve=BigInt(3),pce=BigInt(5),fce=BigInt(8);function mce(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=Vv,a=e*e%i*e%i,c=or(a,yB,i)*a%i,l=or(c,dce,i)*e%i,d=or(l,pce,i)*l%i,f=or(d,t,i)*d%i,h=or(f,r,i)*f%i,g=or(h,n,i)*h%i,x=or(g,o,i)*g%i,w=or(x,o,i)*g%i,S=or(w,t,i)*d%i;return{pow_p_5_8:or(S,yB,i)*e%i,b2:a}}function hce(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function gce(e,t){let r=Vv,n=Lt(t*t*t,r),o=Lt(n*n*t,r),i=mce(e*o).pow_p_5_8,s=Lt(e*n*i,r),a=Lt(t*s*s,r),c=s,l=Lt(s*gB,r),d=a===e,f=a===Lt(-e,r),h=a===Lt(-e*gB,r);if(d)s=c;if(f||h)s=l;if(aB(s,r))s=Lt(-s,r);return{isValid:d||f,value:s}}var bB=(()=>_s(Vv,void 0,!0))(),yce=(()=>({a:bB.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:bB,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:fce,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:K4,randomBytes:P0,adjustScalarBytes:hce,uvRatio:gce}))(),Xl=(()=>hB(yce))();var bce=(e)=>e/4294967296|0,xce=(e)=>e>>>0;function xB(e,t,r,n){let o=bce(r),i=xce(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}function wB(e,t,r){return e&t^~e&r}function SB(e,t,r){return e&t^e&r^t&r}class Zv{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=T0(this.buffer)}update(e){Pv(this),S0(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length,i=!1;for(let s=0;s<o;){let a=Math.min(n-this.pos,o-s);if(a===n){let c=T0(e);for(;n<=o-s;s+=n)this.process(c,s);i=!0;continue}if(r.set(s===0&&a===o?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n)this.process(t,0),this.pos=0,i=!0}if(this.length+=e.length,i)this.roundClean();return this}digestInto(e){Pv(this),E4(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,t.fill(0,i),this.padOffset>n-i)this.process(r,0),t.fill(0);xB(r,n-8,this.length*8,o),this.process(r,0),this.roundClean();let s=e===t?r:T0(e),a=this.outputLen,c=a/4,l=this.get();if(a%4||c>l.length)throw Error("invalid outputLen");for(let d=0;d<c;d++)s.setUint32(4*d,l[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:o,pos:i}=this;if(e.destroyed=o,e.finished=n,e.length=r,e.pos=i,i)e.buffer.set(t);return e}clone(){return this._cloneInto()}}var _B=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var wce=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Wa=new Uint32Array(64);class TB extends Zv{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1);this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)Wa[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=Wa[d-15],h=Wa[d-2],g=Lo(f,7)^Lo(f,18)^f>>>3,x=Lo(h,17)^Lo(h,19)^h>>>10;Wa[d]=x+Wa[d-7]+g+Wa[d-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:l}=this;for(let d=0;d<64;d++){let f=Lo(s,6)^Lo(s,11)^Lo(s,25),h=l+f+wB(s,a,c)+wce[d]+Wa[d]|0,x=(Lo(r,2)^Lo(r,13)^Lo(r,22))+SB(r,n,o)|0;l=c,c=a,a=s,s=i+h|0,i=o,o=n,n=r,r=h+x|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,o,i,s,a,c,l)}roundClean(){_0(Wa)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),_0(this.buffer)}}class vB extends TB{constructor(){super(32,_B)}}var M0=A4(()=>new vB,I4(1));function N0(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=Xl.utils.randomPrivateKey();return{publicKey:Xl.getPublicKey(e),privateKey:e}}function $0(e){return hs(e.publicKey)}function z0(e){return hs(e.privateKey)}function EB(e,t){return{publicKey:dm(e),privateKey:dm(t)}}function PB(e){return hs(M0(e))}function AB(e,t,r,n){return`${e.toUpperCase()}
137
137
  ${t}
138
138
  ${r}
139
139
  ${n}`}function IB(e,t){return`WS-AUTH
@@ -142,11 +142,11 @@ ${t}`}function L0(e,t){return hs(Xl.sign(Qc(t),e))}var wm=[0.0001,0.001,0.01,0.1
142
142
  `));Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class jA extends $e{constructor(e){super(`Value \`${e}\` is not a valid array.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class ph extends $e{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}Fn();function YF(...e){let[t,r]=(()=>{if(Array.isArray(e[0])){let[i,s]=e;return[epe(i),s]}return e})(),{bytecode:n,args:o}=r;return Fr(n,t.inputs?.length&&o?.length?Ou(t.inputs,o):"0x")}function JF(e){return up(e)}function epe(e){let t=e.find((r)=>r.type==="constructor");if(!t)throw new fc({name:"constructor"});return t}function QF(e,t={}){return up(e,t)}function XF(e){return pc(e)}Fn();function eU(...e){let[t,r,n={}]=(()=>{if(Array.isArray(e[0])){let[i,s,a,c]=e;return[VA(i,s),a,c]}return e})(),o=pp(t.outputs,r,n);if(o&&Object.keys(o).length===0)return;if(o&&Object.keys(o).length===1){if(Array.isArray(o))return o[0];return Object.values(o)[0]}return o}function mc(...e){let[t,r=[]]=(()=>{if(Array.isArray(e[0])){let[l,d,f]=e;return[VA(l,d,{args:f}),f]}let[a,c]=e;return[a,c]})(),{overloads:n}=t,o=n?VA([t,...n],t.name,{args:r}):t,i=npe(o),s=r.length>0?Ou(o.inputs,r):void 0;return s?Fr(i,s):i}function Mu(e,t={}){return up(e,t)}function VA(e,t,r){let n=lp(e,t,r);if(n.type!=="function")throw new fc({name:t,type:"function"});return n}function npe(e){return $A(e)}var fx="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",mx="0x0000000000000000000000000000000000000000";et();$s();js();Im();Rr();sc();var ipe="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033",aU="0x608060405234801561000f575f5ffd5b5060043610610029575f3560e01c8063fd00430c1461002d575b5f5ffd5b6100476004803603810190610042919061012b565b610049565b005b80825f375f5f825f865afa610060573d5f5f3e3d5ffd5b3d5f5f3e3d5ff35b5f5ffd5b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61009982610070565b9050919050565b6100a98161008f565b81146100b3575f5ffd5b50565b5f813590506100c4816100a0565b92915050565b5f5ffd5b5f5ffd5b5f5ffd5b5f5f83601f8401126100eb576100ea6100ca565b5b8235905067ffffffffffffffff811115610108576101076100ce565b5b602083019150836001820283011115610124576101236100d2565b5b9250929050565b5f5f5f6040848603121561014257610141610068565b5b5f61014f868287016100b6565b935050602084013567ffffffffffffffff8111156101705761016f61006c565b5b61017c868287016100d6565b9250925050925092509256fea2646970667358221220635ed99185cacf3f2acba6921f23687c969cec2bbaf5f9ad599f507e6e105e6964736f6c63430008230033",spe=0x00000000000000000000000000000000deadbeefn,ape=XF(QF("event Transfer(address indexed from, address indexed to, uint256 value)")),tU=Mu("function balanceOf(address) returns (uint256)"),rU=Mu("function decimals() returns (uint256)"),nU=Mu("function tokenURI(uint256) returns (string)"),oU=Mu("function symbol() returns (string)"),cpe=Mu("function query(address target, bytes data)");async function cU(e,t){let{blockNumber:r,blockTag:n,calls:o,stateOverrides:i,traceAssetChanges:s,traceTransfers:a,validation:c}=t,l=t.account?je(t.account):void 0;if(s&&!l)throw new N("`account` is required when `traceAssetChanges` is true");let d=l?YF(JF("constructor(bytes, bytes)"),{bytecode:Db,args:[ipe,mc(Mu("function getBalance(address)"),[l.address])]}):void 0,f=n??e.experimental_blockTag??"latest",h=r;if(s&&typeof h!=="bigint"&&f!=="earliest"&&f!=="pending")if(f==="latest")h=await Po(e,{cacheTime:0});else{let ne=await Pr(e,{blockTag:f});if(typeof ne.number!=="bigint")throw new N(`Block tag \`${f}\` did not resolve to a number.`);h=ne.number}let g=typeof h==="bigint"?{blockNumber:h}:{blockTag:f},x=s?await ap(e,{...g,blocks:[{calls:o.map((ne)=>({...ne,from:l.address})),stateOverrides:i}],traceTransfers:a,validation:c}):void 0,w=x?[...new Set([...upe(x[0].calls.flatMap((ne)=>ne.logs??[]),l.address),...t.calls.map((ne)=>ne.to?.toLowerCase())])].filter((ne)=>Boolean(ne)&&ne!==fx&&ne!==mx):[],S=lpe([...l?[l.address]:[],...w,...i?.map(({address:ne})=>ne)??[]]),_=[{address:S,code:aU}],[A,T]=await Promise.all([s?Promise.all([sU(e,{account:l.address,...g,data:d,stateOverride:i}),...w.map((ne)=>sU(e,{account:l.address,address:ne,...g,data:mc(tU,[l.address]),staticCallAddress:S,stateOverride:i}))]):[],ap(e,{...g,blocks:[{calls:[...o,{to:mx}].map((ne)=>({...ne,from:l?.address})),stateOverrides:i},...s?[{calls:[{data:d}]},{calls:w.map((ne)=>({to:S,data:mh(ne,mc(tU,[l.address]))})),stateOverrides:_},{calls:w.map((ne)=>({to:S,data:mh(ne,mc(rU))})),stateOverrides:_},{calls:w.map((ne)=>({to:S,data:mh(ne,mc(nU,[0n]))})),stateOverrides:_},{calls:w.map((ne)=>({to:S,data:mh(ne,mc(oU))})),stateOverrides:_}]:[]],traceTransfers:a,validation:c})]),v=T[0],[E,k,O,B,G]=s?T.slice(1):[],{calls:M,...J}=v,W=M.slice(0,-1),he=A.map((ne)=>iU(ne)?xr(ne.data):null),ge=E?.calls??[],j=k?.calls??[],Se=[...ge,...j].map((ne)=>iU(ne)?xr(ne.data):null),D=(O?.calls??[]).map((ne)=>ZA(ne,rU)),q=(G?.calls??[]).map((ne)=>ZA(ne,oU)),Q=(B?.calls??[]).map((ne)=>ZA(ne,nU)),ke=[];for(let[ne,Le]of Se.entries()){let Ce=he[ne],Oe=A[ne],ct=typeof Ce==="bigint"?Ce:ne>0&&Oe?.status==="success"&&Oe.data==="0x"?0n:null;if(typeof Le!=="bigint")continue;if(typeof ct!=="bigint")continue;let gt=D[ne-1],yt=q[ne-1],Ft=Q[ne-1],Kt=(()=>{if(ne===0)return{address:fx,decimals:18,symbol:"ETH"};return{address:w[ne-1],decimals:Ft||gt?Number(gt??1):void 0,symbol:yt??void 0}})();ke.push({token:Kt,value:{pre:ct,post:Le,diff:Le-ct}})}return{assetChanges:ke,block:J,results:W}}function mh(e,t){return mc(cpe,[e,t])}function upe(e,t){let r=Ci(t.toLowerCase(),{size:32});return e.filter((n)=>{if(n.topics[0]?.toLowerCase()!==ape)return!1;if(n.address.toLowerCase()===fx)return!1;return n.topics[1]?.toLowerCase()===r||n.topics[2]?.toLowerCase()===r}).map((n)=>n.address.toLowerCase())}function iU(e){return e.status==="success"&&/^0x[\da-f]{64}$/i.test(e.data)}function ZA(e,t){if(e.status==="failure"||e.data==="0x")return null;try{return eU(t,e.data)}catch{return null}}async function sU(e,t){let{account:r,address:n,blockNumber:o,blockTag:i,data:s,staticCallAddress:a,stateOverride:c}=t;try{return{data:(await Un({...e,ccipRead:!1},{account:n?mx:r,data:n?mh(n,s):s,stateOverride:n&&a?[...c??[],{address:a,code:aU}]:c,...n?{to:a}:{},...typeof o==="bigint"?{blockNumber:o}:{blockTag:i}})).data??"0x",status:"success"}}catch(l){if(!(l instanceof bu)||!(l.cause instanceof Li))throw l;return{data:"0x",status:"failure"}}}function lpe(e){let t=new Set(e.map((n)=>n.toLowerCase())),r=spe;while(t.has(`0x${r.toString(16).padStart(40,"0")}`))r++;return`0x${r.toString(16).padStart(40,"0")}`}Ms();Bn();sc();async function fp(e,t){let{abi:r,address:n,args:o,functionName:i,dataSuffix:s=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=a.account?je(a.account):e.account,l=Dt({abi:r,args:o,functionName:i});try{let{data:d}=await re(e,Un,"call")({batch:!1,data:`${l}${s?s.replace("0x",""):""}`,to:n,...a,account:c}),f=sn({abi:r,args:o,functionName:i,data:d||"0x"}),h=r.filter((g)=>("name"in g)&&g.name===t.functionName);return{result:f,request:{abi:h,address:n,args:o,dataSuffix:s,functionName:i,...a,account:c}}}catch(d){throw eo(d,{abi:r,address:n,args:o,docsPath:"/docs/contract/simulateContract",functionName:i,sender:c?.address})}}async function hc(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}To();Fn();var uU="0x6492649264926492649264926492649264926492649264926492649264926492";function dpe(e){if(cn(e,-32)!==uU)throw new lU(e)}function ppe(e){let{data:t,signature:r,to:n}=e;return Fr(Ou(px("address, bytes, bytes"),[n,t,r]),uU)}function fpe(e){try{return dpe(e),!0}catch{return!1}}class lU extends $e{constructor(e){super(`Value \`${e}\` is an invalid ERC-6492 wrapped signature.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}To();Fn();function WA(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new hx({signature:e});if(typeof e.s>"u")throw new hx({signature:e});if(r&&typeof e.yParity>"u")throw new hx({signature:e});if(e.r<0n||e.r>LA)throw new gU({value:e.r});if(e.s<0n||e.s>LA)throw new yU({value:e.s});if(typeof e.yParity==="number"&&e.yParity!==0&&e.yParity!==1)throw new gx({value:e.yParity})}function mpe(e){return pU(an(e))}function pU(e){if(e.length!==130&&e.length!==132)throw new hU({signature:e});let t=BigInt(cn(e,0,32)),r=BigInt(cn(e,32,64)),n=(()=>{let o=Number(`0x${e.slice(130)}`);if(Number.isNaN(o))return;try{return KA(o)}catch{throw new gx({value:o})}})();if(typeof n>"u")return{r:t,s:r};return{r:t,s:r,yParity:n}}function fU(e){if(typeof e.r>"u")return;if(typeof e.s>"u")return;return mU(e)}function mU(e){let t=(()=>{if(typeof e==="string")return pU(e);if(e instanceof Uint8Array)return mpe(e);if(typeof e.r==="string")return gpe(e);if(e.v)return hpe(e);return{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}}})();return WA(t),t}function hpe(e){return{r:e.r,s:e.s,yParity:KA(e.v)}}function gpe(e){let t=(()=>{let r=e.v?Number(e.v):void 0,n=e.yParity?Number(e.yParity):void 0;if(typeof r==="number"&&typeof n!=="number")n=KA(r);if(typeof n!=="number")throw new gx({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function KA(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new bU({value:e})}class hU extends $e{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Er(e9(e))} bytes.`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class hx extends $e{constructor({signature:e}){super(`Signature \`${Nb(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class gU extends $e{constructor({value:e}){super(`Value \`${e}\` is an invalid r value. r must be a positive integer less than 2^256.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}}class yU extends $e{constructor({value:e}){super(`Value \`${e}\` is an invalid s value. s must be a positive integer less than 2^256.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}}class gx extends $e{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class bU extends $e{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function wU(e,t={}){if(typeof e.chainId==="string")return ype(e);return{...e,...t.signature}}function ype(e){let{address:t,chainId:r,nonce:n}=e,o=fU(e);return{address:t,chainId:Number(r),nonce:BigInt(n),...o}}To();Fn();var xpe="0x8010801080108010801080108010801080108010801080108010801080108010",wpe=px("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function SU(e){if(typeof e==="string"){if(cn(e,-32)!==xpe)throw new _U(e)}else WA(e.authorization)}function Spe(e){SU(e);let t=$b(cn(e,-64,-32)),r=cn(e,-t-64,-64),n=cn(e,0,-t-64),[o,i,s]=pp(wpe,r);return{authorization:wU({address:o.delegation,chainId:Number(o.chainId),nonce:o.nonce,yParity:o.yParity,r:o.r,s:o.s}),signature:n,...s&&s!=="0x"?{data:s,to:i}:{}}}function _pe(e){try{return SU(e),!0}catch{return!1}}class _U extends $e{constructor(e){super(`Value \`${e}\` is an invalid ERC-8010 wrapped signature.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}}en();$s();Fb();Bn();Oi();Fs();Oi();Fs();async function vU({address:e,authorization:t,signature:r}){return Ur(qo(e),await cc({authorization:t,signature:r}))}Rr();Ke();ih();Rr();Dr();function yx({r:e,s:t,to:r="hex",v:n,yParity:o}){let i=(()=>{if(o===0||o===1)return o;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw Error("Invalid `v` or `yParity` value")})(),s=`0x${new Vs.Signature(xr(e),xr(t)).toCompactHex()}${i===0?"1b":"1c"}`;if(r==="hex")return s;return Cr(s)}sc();async function yc(e,t){let{address:r,chain:n=e.chain,hash:o,erc6492VerifierAddress:i=t.universalSignatureVerifierAddress??n?.contracts?.erc6492Verifier?.address,multicallAddress:s=t.multicallAddress??n?.contracts?.multicall3?.address,mode:a="auto"}=t;if(n?.verifyHash)return await n.verifyHash(e,t);let c=(()=>{let l=t.signature;if(cr(l))return l;if(typeof l==="object"&&"r"in l&&"s"in l)return yx(l);return St(l)})();try{if(a==="eoa")try{if(Ur(qo(r),await sh({hash:o,signature:c})))return!0}catch{}if(_pe(c))return await Tpe(e,{...t,multicallAddress:s,signature:c});return await vpe(e,{...t,verifierAddress:i,signature:c})}catch(l){if(a!=="eoa")try{if(Ur(qo(r),await sh({hash:o,signature:c})))return!0}catch{}if(l instanceof gc)return!1;throw l}}async function Tpe(e,t){let{address:r,blockHash:n,blockNumber:o,blockTag:i,hash:s,multicallAddress:a,requireCanonical:c}=t,{authorization:l,data:d,signature:f,to:h}=Spe(t.signature);if(await ku(e,{address:r,blockHash:n,blockNumber:o,blockTag:i,requireCanonical:c})===dr(["0xef0100",l.address]))return await Epe(e,{...t,signature:f});let x={address:l.address,chainId:Number(l.chainId),nonce:Number(l.nonce),r:Z(l.r,{size:32}),s:Z(l.s,{size:32}),yParity:l.yParity};if(!await vU({address:r,authorization:x}))throw new gc;let S=await re(e,Tt,"readContract")({...a?{address:a}:{code:Tu},authorizationList:[x],abi:bo,blockHash:n,blockNumber:o,blockTag:"pending",functionName:"aggregate3",requireCanonical:c,args:[[...d?[{allowFailure:!0,target:h??r,callData:d}]:[],{allowFailure:!0,target:r,callData:Dt({abi:uE,functionName:"isValidSignature",args:[s,f]})}]]});if(S[S.length-1]?.returnData?.startsWith("0x1626ba7e"))return!0;throw new gc}async function vpe(e,t){let{address:r,factory:n,factoryData:o,hash:i,signature:s,verifierAddress:a,...c}=t,l=await(async()=>{if(!n&&!o)return s;if(fpe(s))return s;return ppe({data:o,signature:s,to:n})})(),d=a?{to:a,data:Dt({abi:_m,functionName:"isValidSig",args:[r,i,l]}),...c}:{data:vu({abi:_m,args:[r,i,l],bytecode:s9}),...c},{data:f}=await re(e,Un,"call")(d).catch((h)=>{if(h instanceof bu)throw new gc;throw h});if(IE(f??"0x0"))return!0;throw new gc}async function Epe(e,t){let{address:r,blockHash:n,blockNumber:o,blockTag:i,hash:s,requireCanonical:a,signature:c}=t;if((await re(e,Tt,"readContract")({address:r,abi:uE,args:[s,c],blockHash:n,blockNumber:o,blockTag:i,functionName:"isValidSignature",requireCanonical:a}).catch((d)=>{if(d instanceof Gm)throw new gc;throw d})).startsWith("0x1626ba7e"))return!0;throw new gc}class gc extends Error{}wo();var EU=`\x19Ethereum Signed Message:
143
143
  `;Mn();Ke();function PU(e){let t=(()=>{if(typeof e==="string")return Ja(e);if(typeof e.raw==="string")return e.raw;return St(e.raw)})(),r=Ja(`${EU}${lt(t)}`);return Or([r,t])}function mp(e,t){return Ot(PU(e),t)}async function AU(e,{address:t,message:r,factory:n,factoryData:o,signature:i,...s}){let a=mp(r);return re(e,yc,"verifyHash")({address:t,factory:n,factoryData:o,hash:a,signature:i,...s})}ks();Ke();wo();Tr();Ri();et();class YA extends N{constructor({domain:e}){super(`Invalid domain "${at(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class JA extends N{constructor({primaryType:e,types:t}){super(`Invalid primary type \`${e}\` must be one of \`${JSON.stringify(Object.keys(t))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class QA extends N{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}class XA extends N{constructor({type:e}){let t=e.replace(/^(u?int)/,"$&256");super(`Type "${e}" is not a valid EIP-712 type.`,{metaMessages:[`Use "${t}" instead.`],name:"InvalidTypedDataTypeError"})}}Qn();Mn();Ke();BE();function IU(e){let{domain:t,message:r,primaryType:n,types:o}=e,i=(c,l)=>{let d={...l};for(let f of c){let{name:h,type:g}=f;if(g==="address")d[h]=d[h].toLowerCase()}return d},s=(()=>{if(!o.EIP712Domain)return{};if(!t)return{};return i(o.EIP712Domain,t)})(),a=(()=>{if(n==="EIP712Domain")return;return i(o[n],r)})();return at({domain:s,message:a,primaryType:n,types:o})}function bx(e){let{domain:t,message:r,primaryType:n,types:o}=e,i=(s,a)=>{for(let c of s){let{name:l,type:d}=c,f=a[l],h=d.replace(/(\[[0-9]*\])+$/,"");if(h==="int"||h==="uint")throw new XA({type:d});let g=d.match(lb);if(g&&(typeof f==="number"||typeof f==="bigint")){let[S,_,A]=g;Z(f,{signed:_==="int",size:Number.parseInt(A,10)/8})}if(d==="address"&&typeof f==="string"&&!_t(f))throw new Qt({address:f});let x=d.match(I3);if(x){let[S,_]=x;if(_&&lt(f)!==Number.parseInt(_,10))throw new _E({expectedSize:Number.parseInt(_,10),givenSize:lt(f)})}let w=o[d];if(w)Ppe(d),i(w,f)}};if(o.EIP712Domain&&t){if(typeof t!=="object")throw new YA({domain:t});i(o.EIP712Domain,t)}if(n!=="EIP712Domain")if(o[n])i(o[n],r);else throw new JA({primaryType:n,types:o})}function xx({domain:e}){return[typeof e?.name==="string"&&{name:"name",type:"string"},e?.version&&{name:"version",type:"string"},(typeof e?.chainId==="number"||typeof e?.chainId==="bigint")&&{name:"chainId",type:"uint256"},e?.verifyingContract&&{name:"verifyingContract",type:"address"},e?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function Ppe(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new QA({type:e})}function wx(e){let{domain:t={},message:r,primaryType:n}=e,o={EIP712Domain:xx({domain:t}),...e.types};bx({domain:t,message:r,primaryType:n,types:o});let i=["0x1901"];if(t)i.push(Ape({domain:t,types:o}));if(n!=="EIP712Domain")i.push(kU({data:r,primaryType:n,types:o}));return Ot(Or(i))}function Ape({domain:e,types:t}){return kU({data:e,primaryType:"EIP712Domain",types:t})}function kU({data:e,primaryType:t,types:r}){let n=RU({data:e,primaryType:t,types:r});return Ot(n)}function RU({data:e,primaryType:t,types:r}){let n=[{type:"bytes32"}],o=[Ipe({primaryType:t,types:r})];for(let i of r[t]){let[s,a]=OU({types:r,name:i.name,type:i.type,value:e[i.name]});n.push(s),o.push(a)}return _n(n,o)}function Ipe({primaryType:e,types:t}){let r=lr(kpe({primaryType:e,types:t}));return Ot(r)}function kpe({primaryType:e,types:t}){let r="",n=CU({primaryType:e,types:t});n.delete(e);let o=[e,...Array.from(n).sort()];for(let i of o)r+=`${i}(${t[i].map(({name:s,type:a})=>`${a} ${s}`).join(",")})`;return r}function CU({primaryType:e,types:t},r=new Set){let o=e.match(/^\w*/u)?.[0];if(r.has(o)||t[o]===void 0)return r;r.add(o);for(let i of t[o])CU({primaryType:i.type,types:t},r);return r}function OU({types:e,name:t,type:r,value:n}){if(e[r]!==void 0)return[{type:"bytes32"},Ot(RU({data:n,primaryType:r,types:e}))];if(r==="bytes")return[{type:"bytes32"},Ot(n)];if(r==="string")return[{type:"bytes32"},Ot(lr(n))];if(r.lastIndexOf("]")===r.length-1){let o=r.slice(0,r.lastIndexOf("[")),i=n.map((s)=>OU({name:t,type:o,types:e,value:s}));return[{type:"bytes32"},Ot(_n(i.map(([s])=>s),i.map(([,s])=>s)))]}return[{type:r},n]}async function MU(e,t){let{address:r,factory:n,factoryData:o,signature:i,message:s,primaryType:a,types:c,domain:l,...d}=t,f=wx({message:s,primaryType:a,types:c,domain:l});return re(e,yc,"verifyHash")({address:r,factory:n,factoryData:o,hash:f,signature:i,...d})}Tn();var Sx=new Map,eI=new Map,Rpe=0;function Gr(e,t,r){let n=++Rpe,o=()=>Sx.get(e)||[],i=()=>{let f=o().filter((h)=>h.id!==n);if(f.length===0){Sx.delete(e),eI.delete(e);return}Sx.set(e,f)},s=()=>{let d=o();if(!d.some((h)=>h.id===n))return;let f=eI.get(e);if(d.length===1&&f){let h=f();if(h instanceof Promise)h.catch(()=>{})}i()},a=o();if(Sx.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return s;let c={};for(let d in t)c[d]=(...f)=>{let h=o();if(h.length===0)return;for(let g of h)g.fns[d]?.(...f)};let l=r(c);if(typeof l==="function")eI.set(e,l);return s}async function hh(e,{signal:t}={}){return new Promise((r,n)=>{if(t?.aborted){n(rn(t));return}let o=()=>t?.removeEventListener("abort",s),i=setTimeout(()=>{o(),r()},e),s=()=>{clearTimeout(i),o(),n(rn(t))};t?.addEventListener("abort",s,{once:!0})})}function Nu(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0,signal:o}={}){return new Promise((i,s)=>{let a=async({count:c=0}={})=>{if(o?.aborted){s(rn(o));return}let l=async({error:d})=>{let f=typeof t==="function"?t({count:c,error:d}):t;if(f)try{await hh(f,{signal:o})}catch(h){s(h);return}return a({count:c+1})};try{let d=await e();i(d)}catch(d){if(o?.aborted){s(rn(o));return}if(Dn(d)){s(d);return}if(c<r&&await n({count:c,error:d}))return l({error:d});s(d)}};a().catch(s)})}Rr();function Ao(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let o=!0,i=()=>o=!1;return(async()=>{let a;if(t)a=await e({unpoll:i});let c=await r?.(a)??n;await hh(c);let l=async()=>{if(!o)return;await e({unpoll:i}),await hh(n),l()};l()})(),i}function _x(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:n,onError:o,poll:i,pollingInterval:s=e.pollingInterval}){let a=(()=>{if(typeof i<"u")return i;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})(),c;return a?(()=>{let f=at(["watchBlockNumber",e.uid,t,r,s]);return Gr(f,{onBlockNumber:n,onError:o},(h)=>Ao(async()=>{try{let g=await re(e,Po,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(g===c)return;if(g-c>1&&r)for(let x=c+1n;x<g;x++)h.onBlockNumber(x,c),c=x}if(c===void 0||g>c)h.onBlockNumber(g,c),c=g}catch(g){h.onError?.(g)}},{emitOnBegin:t,interval:s}))})():(()=>{let f=at(["watchBlockNumber",e.uid,t,r]);return Gr(f,{onBlockNumber:n,onError:o},(h)=>{let g=!0,x=()=>g=!1;return(async()=>{try{let w=(()=>{if(e.transport.type==="fallback"){let _=e.transport.transports.find((A)=>A.config.type==="webSocket"||A.config.type==="ipc");if(!_)return e.transport;return _.value}return e.transport})(),{unsubscribe:S}=await w.subscribe({params:["newHeads"],onData(_){if(!g)return;let A=xr(_.result?.number);h.onBlockNumber(A,c),c=A},onError(_){h.onError?.(_)}});if(x=S,!g)x()}catch(w){o?.(w)}})(),()=>x()})})()}async function Tx(e,t){let{checkReplacement:r=e.chain?.supportsTransactionReplacementDetection??!0,confirmations:n=1,hash:o,onReplaced:i,retryCount:s=6,retryDelay:a=({count:E})=>~~(1<<E)*200,timeout:c=180000}=t,l=at(["waitForTransactionReceipt",e.uid,o]),d=(()=>{if(t.pollingInterval)return t.pollingInterval;if(e.chain?.experimental_preconfirmationTime)return e.chain.experimental_preconfirmationTime;return e.pollingInterval})(),f,h,g,x=!1,w,S,{promise:_,resolve:A,reject:T}=Hd(),v=c?setTimeout(()=>{S?.(),w?.(),T(new TP({hash:o}))},c):void 0;return w=Gr(l,{onReplaced:i,resolve:A,reject:T},async(E)=>{if(g=await re(e,sp,"getTransactionReceipt")({hash:o}).catch(()=>{return}),g&&n<=1){clearTimeout(v),E.resolve(g),w?.();return}S=re(e,_x,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:d,async onBlockNumber(k){let O=(G)=>{clearTimeout(v),S?.(),G(),w?.()},B=k;if(x)return;try{if(g){if(n>1&&(!g.blockNumber||B-g.blockNumber+1n<n))return;O(()=>E.resolve(g));return}if(r&&!f)x=!0,await Nu(async()=>{if(f=await re(e,ip,"getTransaction")({hash:o}),f.blockNumber)B=f.blockNumber},{delay:a,retryCount:s}),x=!1;if(g=await re(e,sp,"getTransactionReceipt")({hash:o}),n>1&&(!g.blockNumber||B-g.blockNumber+1n<n))return;O(()=>E.resolve(g))}catch(G){if(G instanceof gu||G instanceof Hm){if(!f){x=!1;return}try{h=f,x=!0;let M=await Nu(()=>re(e,Pr,"getBlock")({blockNumber:B,includeTransactions:!0}),{delay:a,retryCount:s,shouldRetry:({error:he})=>he instanceof Iu});x=!1;let J=M.transactions.find(({from:he,nonce:ge})=>he===h.from&&ge===h.nonce);if(!J)return;if(g=await re(e,sp,"getTransactionReceipt")({hash:J.hash}),n>1&&(!g.blockNumber||B-g.blockNumber+1n<n))return;let W="replaced";if(J.to===h.to&&J.value===h.value&&J.input===h.input)W="repriced";else if(J.from===J.to&&J.value===0n)W="cancelled";O(()=>{E.onReplaced?.({reason:W,replacedTransaction:h,transaction:J,transactionReceipt:g}),E.resolve(g)})}catch(M){O(()=>E.reject(M))}}else O(()=>E.reject(G))}}})}),_}var Cpe=["size","totalDifficulty","transactions","uncles","withdrawals"];function NU(e,{onBlockHeader:t,onError:r}){let n,o=at(["watchBlockHeaders",e.uid]);return Gr(o,{onBlockHeader:t,onError:r},(i)=>{let s=!0,a=!1,c=()=>s=!1;return(async()=>{try{let l=(()=>{if(e.transport.type==="fallback"){let f=e.transport.transports.find((h)=>h.config.type==="webSocket"||h.config.type==="ipc");if(!f)return e.transport;return f.value}return e.transport})(),{unsubscribe:d}=await l.subscribe({params:["newHeads"],onData(f){if(!s)return;let h=(e.chain?.formatters?.block?.format||Kd)(f.result,"watchBlockHeaders");for(let g of Cpe)delete h[g];i.onBlockHeader(h,n),n=h},onError(f){if(a)i.onError?.(f)}});if(a=!0,c=d,!s)c()}catch(l){i.onError?.(l)}})(),()=>c()})}function $U(e,{blockTag:t=e.experimental_blockTag??"latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:o,onError:i,includeTransactions:s,poll:a,pollingInterval:c=e.pollingInterval}){let l=(()=>{if(typeof a<"u")return a;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})(),d=s??!1,f;return l?(()=>{let x=at(["watchBlocks",e.uid,t,r,n,d,c]);return Gr(x,{onBlock:o,onError:i},(w)=>Ao(async()=>{try{let S=await re(e,Pr,"getBlock")({blockTag:t,includeTransactions:d});if(S.number!==null&&f?.number!=null){if(S.number===f.number)return;if(S.number-f.number>1&&r)for(let _=f?.number+1n;_<S.number;_++){let A=await re(e,Pr,"getBlock")({blockNumber:_,includeTransactions:d});w.onBlock(A,f),f=A}}if(f?.number==null||t==="pending"&&S?.number==null||S.number!==null&&S.number>f.number)w.onBlock(S,f),f=S}catch(S){w.onError?.(S)}},{emitOnBegin:n,interval:c}))})():(()=>{let x=!0,w=!0,S=()=>x=!1;return(async()=>{try{if(n)re(e,Pr,"getBlock")({blockTag:t,includeTransactions:d}).then((T)=>{if(!x)return;if(!w)return;o(T,void 0),w=!1}).catch(i);let _=(()=>{if(e.transport.type==="fallback"){let T=e.transport.transports.find((v)=>v.config.type==="webSocket"||v.config.type==="ipc");if(!T)return e.transport;return T.value}return e.transport})(),{unsubscribe:A}=await _.subscribe({params:["newHeads"],async onData(T){if(!x)return;let v=await re(e,Pr,"getBlock")({blockNumber:T.result?.number,includeTransactions:d}).catch(()=>{});if(!x)return;o(v,f),w=!1,f=v},onError(T){i?.(T)}});if(S=A,!x)S()}catch(_){i?.(_)}})(),()=>S()})()}Tr();Dd();function zU(e,t){let{abi:r,address:n,args:o,batch:i=!0,eventName:s,fromBlock:a,onError:c,onLogs:l,poll:d,pollingInterval:f=e.pollingInterval,strict:h}=t;return(()=>{if(typeof d<"u")return d;if(typeof a==="bigint")return!0;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})()?(()=>{let S=h??!1,_=at(["watchContractEvent",n,o,i,e.uid,s,f,S,a]);return Gr(_,{onLogs:l,onError:c},(A)=>{let T;if(a!==void 0)T=a-1n;let v,E=!1,k=Ao(async()=>{if(!E){try{v=await re(e,Vb,"createContractEventFilter")({abi:r,address:n,args:o,eventName:s,strict:S,fromBlock:a})}catch{}E=!0;return}try{let O;if(v)O=await re(e,dc,"getFilterChanges")({filter:v});else{let B=await re(e,Po,"getBlockNumber")({});if(T&&T<B)O=await re(e,rx,"getContractEvents")({abi:r,address:n,args:o,eventName:s,fromBlock:T+1n,toBlock:B,strict:S});else O=[];T=B}if(O.length===0)return;if(i)A.onLogs(O);else for(let B of O)A.onLogs([B])}catch(O){if(v&&O instanceof _o)E=!1;A.onError?.(O)}},{emitOnBegin:!0,interval:f});return async()=>{if(v)await re(e,hc,"uninstallFilter")({filter:v});k()}})})():(()=>{let S=h??!1,_=at(["watchContractEvent",n,o,i,e.uid,s,f,S]),A=!0,T=()=>A=!1;return Gr(_,{onLogs:l,onError:c},(v)=>((async()=>{try{let E=(()=>{if(e.transport.type==="fallback"){let B=e.transport.transports.find((G)=>G.config.type==="webSocket"||G.config.type==="ipc");if(!B)return e.transport;return B.value}return e.transport})(),k=s?Di({abi:r,eventName:s,args:o}):[],{unsubscribe:O}=await E.subscribe({params:["logs",{address:n,topics:k}],onData(B){if(!A)return;let G=B.result;try{let{eventName:M,args:J}=Ru({abi:r,data:G.data,topics:G.topics,strict:h}),W=Hr(G,{args:J,eventName:M});v.onLogs([W])}catch(M){let J,W;if(M instanceof Ya||M instanceof uu){if(h)return;J=M.abiItem.name,W=M.abiItem.inputs?.some((ge)=>!(("name"in ge)&&ge.name))}let he=Hr(G,{args:W?[]:{},eventName:J});v.onLogs([he])}},onError(B){v.onError?.(B)}});if(T=O,!A)T()}catch(E){c?.(E)}})(),()=>T()))})()}Tr();Dd();function LU(e,{address:t,args:r,batch:n=!0,event:o,events:i,fromBlock:s,onError:a,onLogs:c,poll:l,pollingInterval:d=e.pollingInterval,strict:f}){let h=(()=>{if(typeof l<"u")return l;if(typeof s==="bigint")return!0;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})(),g=f??!1;return h?(()=>{let S=at(["watchEvent",t,r,n,e.uid,o,d,s]);return Gr(S,{onLogs:c,onError:a},(_)=>{let A;if(s!==void 0)A=s-1n;let T,v=!1,E=Ao(async()=>{if(!v){try{T=await re(e,Zb,"createEventFilter")({address:t,args:r,event:o,events:i,strict:g,fromBlock:s})}catch{}v=!0;return}try{let k;if(T)k=await re(e,dc,"getFilterChanges")({filter:T});else{let O=await re(e,Po,"getBlockNumber")({});if(A&&A!==O)k=await re(e,op,"getLogs")({address:t,args:r,event:o,events:i,fromBlock:A+1n,toBlock:O});else k=[];A=O}if(k.length===0)return;if(n)_.onLogs(k);else for(let O of k)_.onLogs([O])}catch(k){if(T&&k instanceof _o)v=!1;_.onError?.(k)}},{emitOnBegin:!0,interval:d});return async()=>{if(T)await re(e,hc,"uninstallFilter")({filter:T});E()}})})():(()=>{let S=!0,_=()=>S=!1;return(async()=>{try{let A=(()=>{if(e.transport.type==="fallback"){let k=e.transport.transports.find((O)=>O.config.type==="webSocket"||O.config.type==="ipc");if(!k)return e.transport;return k.value}return e.transport})(),T=i??(o?[o]:void 0),v=[];if(T){if(v=[T.flatMap((O)=>Di({abi:[O],eventName:O.name,args:r}))],o)v=v[0]}let{unsubscribe:E}=await A.subscribe({params:["logs",{address:t,topics:v}],onData(k){if(!S)return;let O=k.result;try{let{eventName:B,args:G}=Ru({abi:T??[],data:O.data,topics:O.topics,strict:g}),M=Hr(O,{args:G,eventName:B});c([M])}catch(B){let G,M;if(B instanceof Ya||B instanceof uu){if(f)return;G=B.abiItem.name,M=B.abiItem.inputs?.some((W)=>!(("name"in W)&&W.name))}let J=Hr(O,{args:M?[]:{},eventName:G});c([J])}},onError(k){a?.(k)}});if(_=E,!S)_()}catch(A){a?.(A)}})(),()=>_()})()}function BU(e,{batch:t=!0,onError:r,onTransactions:n,poll:o,pollingInterval:i=e.pollingInterval}){return(typeof o<"u"?o:e.transport.type!=="webSocket"&&e.transport.type!=="ipc")?(()=>{let l=at(["watchPendingTransactions",e.uid,t,i]);return Gr(l,{onTransactions:n,onError:r},(d)=>{let f,h=Ao(async()=>{try{if(!f)try{f=await re(e,Wb,"createPendingTransactionFilter")({});return}catch(x){throw h(),x}let g=await re(e,dc,"getFilterChanges")({filter:f});if(g.length===0)return;if(t)d.onTransactions(g);else for(let x of g)d.onTransactions([x])}catch(g){d.onError?.(g)}},{emitOnBegin:!0,interval:i});return async()=>{if(f)await re(e,hc,"uninstallFilter")({filter:f});h()}})})():(()=>{let l=!0,d=()=>l=!1;return(async()=>{try{let{unsubscribe:f}=await e.transport.subscribe({params:["newPendingTransactions"],onData(h){if(!l)return;let g=h.result;n([g])},onError(h){r?.(h)}});if(d=f,!l)d()}catch(f){r?.(f)}})(),()=>d()})()}var Ope=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function Mpe(e){if(!Ope.test(e))return!1;return!Number.isNaN(new Date(e).getTime())}function tI(e){if(!Mpe(e))return new Date(Number.NaN);return new Date(e)}function DU(e){let{scheme:t,statement:r,...n}=e.match(Npe)?.groups??{},{chainId:o,expirationTime:i,issuedAt:s,notBefore:a,requestId:c,...l}=e.match($pe)?.groups??{},d=e.split("Resources:")[1]?.split(`
144
144
  - `).slice(1);return{...n,...l,...o?{chainId:Number(o)}:{},...i?{expirationTime:tI(i)}:{},...s?{issuedAt:tI(s)}:{},...a?{notBefore:tI(a)}:{},...c?{requestId:c}:{},...d?{resources:d}:{},...t?{scheme:t}:{},...r?{statement:r}:{}}}var Npe=/^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?<address>0x[a-fA-F0-9]{40})\n\n(?:(?<statement>.*)\n\n)?/,$pe=/(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.+))?/;Qn();Fs();function FU(e){let{address:t,domain:r,message:n,nonce:o,scheme:i,time:s=new Date}=e;if(r&&n.domain!==r)return!1;if(o&&n.nonce!==o)return!1;if(i&&n.scheme!==i)return!1;if(Number.isNaN(s.getTime()))return!1;if(n.expirationTime){if(Number.isNaN(n.expirationTime.getTime()))return!1;if(s>=n.expirationTime)return!1}if(n.notBefore){if(Number.isNaN(n.notBefore.getTime()))return!1;if(s<n.notBefore)return!1}try{if(!n.address)return!1;if(!_t(n.address,{strict:!1}))return!1;if(t&&!Ur(n.address,t))return!1}catch{return!1}return!0}async function UU(e,t){let{address:r,domain:n,message:o,nonce:i,scheme:s,signature:a,time:c=new Date,...l}=t,d=DU(o);if(!d.address)return!1;if(!FU({address:r,domain:n,message:d,nonce:i,scheme:s,time:c}))return!1;let h=mp(o);return yc(e,{address:d.address,hash:h,signature:a,...l})}en();et();class Ar extends N{constructor({docsPath:e}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
145
- `),{docsPath:e,docsSlug:"account",name:"AccountNotFoundError"})}}class Ko extends N{constructor({docsPath:e,metaMessages:t,type:r}){super(`Account type "${r}" is not supported.`,{docsPath:e,metaMessages:t,name:"AccountTypeNotSupportedError"})}}Bn();et();Um();function hp({chain:e,currentChainId:t}){if(!e)throw new pP;if(t!==e.id)throw new dP({chain:e,currentChainId:t})}qs();pu();Bi();async function gp(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}var rI=new Jn(128);async function bc(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:i,authorizationList:s,blobs:a,data:c,dataSuffix:l=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:f,maxFeePerBlobGas:h,maxFeePerGas:g,maxPriorityFeePerGas:x,nonce:w,type:S,value:_,...A}=t;if(typeof r>"u")throw new Ar({docsPath:"/docs/actions/wallet/sendTransaction"});let T=r?je(r):null,v;try{jr(t);let E=await(async()=>{if(t.to)return t.to;if(t.to===null)return;if(s&&s.length>0)return await cc({authorization:s[0]}).catch(()=>{throw new N("`to` is required. Could not infer from `authorizationList`.")});return})();if(T?.type==="json-rpc"||T===null){let k;if(o!==null){if(k=await re(e,ln,"getChainId")({}),n)hp({currentChainId:k,chain:o})}let O=e.chain?.formatters?.transactionRequest?.format,G=(O||un)({...Eo(A,{format:O}),accessList:i,account:T,authorizationList:s,blobs:a,chainId:k,data:l?Or([c??"0x",l]):c,gas:d,gasPrice:f,maxFeePerBlobGas:h,maxFeePerGas:g,maxPriorityFeePerGas:x,nonce:w,to:E,type:S,value:_},"sendTransaction"),M=rI.get(e.uid),J=M?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:J,params:[G]},{retryCount:0})}catch(W){if(M===!1)throw W;let he=W;if(he.name==="InvalidInputRpcError"||he.name==="InvalidParamsRpcError"||he.name==="MethodNotFoundRpcError"||he.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[G]},{retryCount:0}).then((ge)=>(rI.set(e.uid,!0),ge)).catch((ge)=>{let j=ge;if(j.name==="MethodNotFoundRpcError"||j.name==="MethodNotSupportedRpcError")throw rI.set(e.uid,!1),he;throw j});throw he}}if(T?.type==="local"){let k=(()=>{if(!T.nonceManager||typeof w<"u")return T.nonceManager;let W=T.nonceManager;return{consume(he){return v={address:he.address,chainId:he.chainId},W.consume(he)},get(he){return W.get(he)},increment(he){return W.increment(he)},reset(he){return W.reset(he)}}})(),O=await re(e,Fi,"prepareTransactionRequest")({account:T,accessList:i,authorizationList:s,blobs:a,chain:o,data:l?Or([c??"0x",l]):c,gas:d,gasPrice:f,maxFeePerBlobGas:h,maxFeePerGas:g,maxPriorityFeePerGas:x,nonce:w,nonceManager:k,parameters:[...uh,"sidecars"],type:S,value:_,...A,to:E}),B=o?.serializers?.transaction,G=await T.signTransaction(O,{serializer:B}),M=(o??e.chain)?.serializers?.transactionEnvelope,J=M?await M({serializedTransaction:G,transaction:O}):G;return await re(e,gp,"sendRawTransaction")({serializedTransaction:J})}if(T?.type==="smart")throw new Ko({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"});throw new Ko({docsPath:"/docs/actions/wallet/sendTransaction",type:T?.type})}catch(E){if(E instanceof Ko)throw E;if(v)T?.nonceManager?.reset(v);throw lc(E,{...t,account:T,chain:t.chain||void 0})}}async function Yo(e,t){return Yo.internal(e,bc,"sendTransaction",t)}(function(e){async function t(r,n,o,i){let{abi:s,account:a=r.account,address:c,args:l,functionName:d,...f}=i;if(typeof a>"u")throw new Ar({docsPath:"/docs/contract/writeContract"});let h=a?je(a):null,g=Dt({abi:s,args:l,functionName:d});try{return await re(r,n,o)({data:g,to:c,account:h,...f})}catch(x){throw eo(x,{abi:s,address:c,args:l,docsPath:"/docs/contract/writeContract",functionName:d,sender:h?.address})}}e.internal=t})(Yo||(Yo={}));en();Qn();Fs();jm();function yp(e,t){return Ab(e,t)}jm();function jU(e,t){return TD(e,t)}function bp(e,t){return{amount:e,decimals:t,formatted:yp(e,t)}}function vx(e,t){if(typeof e==="bigint")return e;let r=e.decimals??t;return jU(e.formatted,zpe(r))}function zpe(e){if(e===void 0)throw Error("Token decimals are required. Pass `amount.decimals` or select a declared token.");return e}function Ex(e,t){if(typeof e==="bigint")return t;return e.decimals??t}function nn(e,t){let{decimals:r,token:n}=t,o=oI(e,n);if(o)return{address:o.address,decimals:r??o.decimals};if(_t(n,{strict:!1}))return{address:n,decimals:r??Bpe(e,n)};throw Error(`Token "${n}" is not a declared ERC-20 token on the client's \`tokens\` array (with an address for the client's chain), and is not a valid address.`)}function oI(e,t){let r=e.tokens,n=e.chain?.id;if(!r||n===void 0)return;let o=Lpe(r,t);if(o)return nI(o,n);if(_t(t,{strict:!1}))for(let i of r){let s=nI(i,n);if(s&&Ur(s.address,t))return s}return}function nI(e,t){let r=e.addresses[t];if(!r)return;return{address:r,currency:e.currency,decimals:e.decimals,name:e.name,popular:e.popular,symbol:e.symbol}}function Lpe(e,t){let r=t.toLowerCase();for(let n of e)if(n.symbol?.toLowerCase()===r)return n;return}function Bpe(e,t){let r=e.tokens,n=e.chain?.id;if(r&&n!==void 0)for(let o of r){let i=nI(o,n);if(i&&Ur(i.address,t))return i.decimals}return}async function xp(e,t){let{address:r,decimals:n}=nn(e,t);if(n!==void 0)return{address:r,decimals:n};return{address:r,decimals:await Tt(e,{abi:ar,address:r,functionName:"decimals"})}}function wp(e){let{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:i,nonce:s}=e;return{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:i,nonce:s}}function ji(e){return{...e,data:Dt(e),to:e.address}}async function Ks(e,t){return Ks.inner(Yo,e,t)}(function(e){async function t(s,a,c){return await s(a,{...c,...e.call(a,c)})}e.inner=t;function r(s,a){return ji(Dpe(s,a))}e.call=r;async function n(s,a){return rp(s,{...wp(a),...e.call(s,a)})}e.estimateGas=n;async function o(s,a){return fp(s,{...wp(a),...e.call(s,a)})}e.simulate=o;function i(s){let[a]=Ui({abi:ar,logs:s,eventName:"Approval",strict:!0});if(!a)throw Error("`Approval` event not found.");return a}e.extractEvent=i})(Ks||(Ks={}));function Dpe(e,t){let{amount:r,spender:n,token:o}=t,{address:i,decimals:s}=nn(e,{token:o});return{abi:ar,address:i,args:[n,vx(r,s)],functionName:"approve"}}et();Tn();qs();pu();Bi();Tn();async function Sp(e,{serializedTransaction:t,throwOnReceiptRevert:r,timeout:n}){let o=await e.request({method:"eth_sendRawTransactionSync",params:n?[t,n]:[t]},{retryCount:0}),s=(e.chain?.formatters?.transactionReceipt?.format||np)(o);if(s.status==="reverted"&&r)throw new hd({receipt:s});return s}var iI=new Jn(128);async function Px(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:i,authorizationList:s,blobs:a,data:c,dataSuffix:l=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:f,maxFeePerBlobGas:h,maxFeePerGas:g,maxPriorityFeePerGas:x,nonce:w,pollingInterval:S,throwOnReceiptRevert:_,type:A,value:T,...v}=t,E=t.timeout??Math.max((o?.blockTime??0)*3,5000);if(typeof r>"u")throw new Ar({docsPath:"/docs/actions/wallet/sendTransactionSync"});let k=r?je(r):null,O;try{jr(t);let B=await(async()=>{if(t.to)return t.to;if(t.to===null)return;if(s&&s.length>0)return await cc({authorization:s[0]}).catch(()=>{throw new N("`to` is required. Could not infer from `authorizationList`.")});return})();if(k?.type==="json-rpc"||k===null){let G;if(o!==null){if(G=await re(e,ln,"getChainId")({}),n)hp({currentChainId:G,chain:o})}let M=e.chain?.formatters?.transactionRequest?.format,W=(M||un)({...Eo(v,{format:M}),accessList:i,account:k,authorizationList:s,blobs:a,chainId:G,data:l?Or([c??"0x",l]):c,gas:d,gasPrice:f,maxFeePerBlobGas:h,maxFeePerGas:g,maxPriorityFeePerGas:x,nonce:w,to:B,type:A,value:T},"sendTransaction"),he=iI.get(e.uid),ge=he?"wallet_sendTransaction":"eth_sendTransaction",j=await(async()=>{try{return await e.request({method:ge,params:[W]},{retryCount:0})}catch(Se){if(he===!1)throw Se;let D=Se;if(D.name==="InvalidInputRpcError"||D.name==="InvalidParamsRpcError"||D.name==="MethodNotFoundRpcError"||D.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[W]},{retryCount:0}).then((q)=>(iI.set(e.uid,!0),q)).catch((q)=>{let Q=q;if(Q.name==="MethodNotFoundRpcError"||Q.name==="MethodNotSupportedRpcError")throw iI.set(e.uid,!1),D;throw Q});throw D}})(),se=await re(e,Tx,"waitForTransactionReceipt")({checkReplacement:!1,hash:j,pollingInterval:S,timeout:E});if(_&&se.status==="reverted")throw new hd({receipt:se});return se}if(k?.type==="local"){let G=(()=>{if(!k.nonceManager||typeof w<"u")return k.nonceManager;let j=k.nonceManager;return{consume(se){return O={address:se.address,chainId:se.chainId},j.consume(se)},get(se){return j.get(se)},increment(se){return j.increment(se)},reset(se){return j.reset(se)}}})(),M=await re(e,Fi,"prepareTransactionRequest")({account:k,accessList:i,authorizationList:s,blobs:a,chain:o,data:l?Or([c??"0x",l]):c,gas:d,gasPrice:f,maxFeePerBlobGas:h,maxFeePerGas:g,maxPriorityFeePerGas:x,nonce:w,nonceManager:G,parameters:[...uh,"sidecars"],type:A,value:T,...v,to:B}),J=o?.serializers?.transaction,W=await k.signTransaction(M,{serializer:J}),he=(o??e.chain)?.serializers?.transactionEnvelope,ge=he?await he({serializedTransaction:W,transaction:M}):W;return await re(e,Sp,"sendRawTransactionSync")({serializedTransaction:ge,throwOnReceiptRevert:_,timeout:t.timeout})}if(k?.type==="smart")throw new Ko({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"});throw new Ko({docsPath:"/docs/actions/wallet/sendTransactionSync",type:k?.type})}catch(B){if(B instanceof Ko)throw B;if(O&&!(B instanceof hd))k?.nonceManager?.reset(O);throw lc(B,{...t,account:k,chain:t.chain||void 0})}}async function _p(e,t){return Yo.internal(e,Px,"sendTransactionSync",t)}async function sI(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:i}=nn(e,{token:n}),s=Ex(r,i),a=await Ks.inner(_p,e,{...t,throwOnReceiptRevert:o}),{args:c}=Ks.extractEvent(a.logs);return{...c,...s===void 0?{}:{decimals:s,formatted:yp(c.value,s)},receipt:a}}en();async function Tp(e,t){let{account:r,decimals:n,spender:o,token:i,...s}=t,[a,{decimals:c}]=await Promise.all([Tt(e,{...s,...Tp.call(e,{account:r,spender:o,token:i})}),xp(e,{decimals:n,token:i})]);return bp(a,c)}(function(e){function t(r,n){return ji({address:nn(r,n).address,abi:ar,functionName:"allowance",args:[n.account,n.spender]})}e.call=t})(Tp||(Tp={}));en();async function vp(e,t){let{account:r=e.account,decimals:n,token:o,...i}=t;if(!r)throw new Ar;let s=je(r).address,[a,{decimals:c}]=await Promise.all([Tt(e,{...i,...vp.call(e,{account:s,token:o})}),xp(e,{decimals:n,token:o})]);return bp(a,c)}(function(e){function t(r,n){let o=n.account??r.account;if(!o)throw new Ar;let i=je(o).address;return ji({address:nn(r,n).address,abi:ar,functionName:"balanceOf",args:[i]})}e.call=t})(vp||(vp={}));en();async function aI(e,t){let{token:r,...n}=t,{address:o}=nn(e,{token:r}),i=oI(e,r),[s,a,c]=await Promise.all([i?.decimals??Tt(e,{...n,abi:ar,address:o,functionName:"decimals"}),i?.name??Tt(e,{...n,abi:ar,address:o,functionName:"name"}),i?.symbol??Tt(e,{...n,abi:ar,address:o,functionName:"symbol"})]);return{decimals:s,name:a,symbol:c}}en();async function Ep(e,t){let{decimals:r,token:n,...o}=t,[i,{decimals:s}]=await Promise.all([Tt(e,{...o,...Ep.call(e,{token:n})}),xp(e,{decimals:r,token:n})]);return bp(i,s)}(function(e){function t(r,n){return ji({address:nn(r,n).address,abi:ar,args:[],functionName:"totalSupply"})}e.call=t})(Ep||(Ep={}));en();async function Ys(e,t){return Ys.inner(Yo,e,t)}(function(e){async function t(s,a,c){return await s(a,{...c,...e.call(a,c)})}e.inner=t;function r(s,a){return ji(Fpe(s,a))}e.call=r;async function n(s,a){return rp(s,{...wp(a),...e.call(s,a)})}e.estimateGas=n;async function o(s,a){return fp(s,{...wp(a),...e.call(s,a)})}e.simulate=o;function i(s){let[a]=Ui({abi:ar,logs:s,eventName:"Transfer",strict:!0});if(!a)throw Error("`Transfer` event not found.");return a}e.extractEvent=i})(Ys||(Ys={}));function Fpe(e,t){let{amount:r,from:n,to:o,token:i}=t,{address:s,decimals:a}=nn(e,{token:i}),c=vx(r,a);if(n)return{abi:ar,address:s,args:[n,o,c],functionName:"transferFrom"};return{abi:ar,address:s,args:[o,c],functionName:"transfer"}}async function cI(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:i}=nn(e,{token:n}),s=Ex(r,i),a=await Ys.inner(_p,e,{...t,throwOnReceiptRevert:o}),{args:c}=Ys.extractEvent(a.logs);return{...c,...s===void 0?{}:{decimals:s,formatted:yp(c.value,s)},receipt:a}}function qU(e){return{call:(t)=>Un(e,t),createAccessList:(t)=>v9(e,t),createBlockFilter:()=>E9(e),createContractEventFilter:(t)=>Vb(e,t),createEventFilter:(t)=>Zb(e,t),createPendingTransactionFilter:()=>Wb(e),estimateContractGas:(t)=>rp(e,t),estimateGas:(t)=>tp(e,t),getBalance:(t)=>rF(e,t),getBlobBaseFee:()=>nF(e),getBlock:(t)=>Pr(e,t),getBlockNumber:(t)=>Po(e,t),getBlockReceipts:(t)=>sF(e,t),getBlockTransactionCount:(t)=>aF(e,t),getBytecode:(t)=>ku(e,t),getChainId:()=>ln(e),getCode:(t)=>ku(e,t),getContractEvents:(t)=>rx(e,t),getDelegation:(t)=>uF(e,t),getEip712Domain:(t)=>lF(e,t),getEnsAddress:(t)=>h9(e,t),getEnsAvatar:(t)=>S9(e,t),getEnsName:(t)=>_9(e,t),getEnsResolver:(t)=>T9(e,t),getEnsText:(t)=>Gb(e,t),getFeeHistory:(t)=>pF(e,t),estimateFeesPerGas:(t)=>H9(e,t),getFilterChanges:(t)=>dc(e,t),getFilterLogs:(t)=>fF(e,t),getGasPrice:()=>Yd(e),getLogs:(t)=>op(e,t),getProof:(t)=>hF(e,t),estimateMaxPriorityFeePerGas:(t)=>q9(e,t),fillTransaction:(t)=>ep(e,t),getRawTransaction:(t)=>gF(e,t),getStorageAt:(t)=>yF(e,t),getTransaction:(t)=>ip(e,t),getTransactionConfirmations:(t)=>bF(e,t),getTransactionCount:(t)=>Jd(e,t),getTransactionReceipt:(t)=>sp(e,t),multicall:(t)=>xF(e,t),prepareTransactionRequest:(t)=>Fi(e,t),readContract:(t)=>Tt(e,t),sendRawTransaction:(t)=>gp(e,t),sendRawTransactionSync:(t)=>Sp(e,t),simulate:(t)=>ap(e,t),simulateBlocks:(t)=>ap(e,t),simulateCalls:(t)=>cU(e,t),simulateContract:(t)=>fp(e,t),verifyHash:(t)=>yc(e,t),verifyMessage:(t)=>AU(e,t),verifySiweMessage:(t)=>UU(e,t),verifyTypedData:(t)=>MU(e,t),uninstallFilter:(t)=>hc(e,t),waitForTransactionReceipt:(t)=>Tx(e,t),watchBlockHeaders:(t)=>NU(e,t),watchBlocks:(t)=>$U(e,t),watchBlockNumber:(t)=>_x(e,t),watchContractEvent:(t)=>zU(e,t),watchEvent:(t)=>LU(e,t),watchPendingTransactions:(t)=>BU(e,t),token:Upe(e)}}function Upe(e){return{getAllowance:Ii(e,Tp),getBalance:Ii(e,vp),getMetadata:Ii(e,aI),getTotalSupply:Ii(e,Ep)}}function uI(e){let{key:t="public",name:r="Public Client"}=e;return V0({...e,key:t,name:r,type:"publicClient"}).extend(qU)}Ke();async function HU(e,{chain:t}){let{id:r,name:n,nativeCurrency:o,rpcUrls:i,blockExplorers:s}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:Z(r),chainName:n,nativeCurrency:o,rpcUrls:i.default.http,blockExplorerUrls:s?Object.values(s).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}Fb();function GU(e,t){let{abi:r,args:n,bytecode:o,...i}=t,s=vu({abi:r,args:n,bytecode:o});return bc(e,{...i,...i.authorizationList?{to:null}:{},data:s})}Oi();async function VU(e){if(e.account?.type==="local")return[e.account.address];return(await e.request({method:"eth_accounts"},{dedupe:!0})).map((r)=>As(r))}Is();Rr();et();Dd();Bn();Rr();Ke();var lI="0x5792579257925792579257925792579257925792579257925792579257925792",dI=Z(0,{size:32});async function Ax(e,t){let{account:r=e.account,chain:n=e.chain,experimental_fallback:o,experimental_fallbackDelay:i=32,forceAtomic:s=!1,id:a,version:c="2.0.0"}=t,l=r?je(r):null,d=t.capabilities;if(e.dataSuffix&&!t.capabilities?.dataSuffix)if(typeof e.dataSuffix==="string")d={...t.capabilities,dataSuffix:{value:e.dataSuffix,optional:!0}};else d={...t.capabilities,dataSuffix:{value:e.dataSuffix.value,...e.dataSuffix.required?{}:{optional:!0}}};let f=t.calls.map((h)=>{let g=h,x=g.abi?Dt({abi:g.abi,functionName:g.functionName,args:g.args}):g.data;return{data:g.dataSuffix&&x?Or([x,g.dataSuffix]):x,to:g.to,value:g.value?Z(g.value):void 0}});try{let h=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:s,calls:f,capabilities:d,chainId:Z(n.id),from:l?.address,id:a,version:c}]},{retryCount:0});if(typeof h==="string")return{id:h};return h}catch(h){let g=h;if(o&&(g.name==="MethodNotFoundRpcError"||g.name==="MethodNotSupportedRpcError"||g.name==="UnknownRpcError"||g.details.toLowerCase().includes("does not exist / is not available")||g.details.toLowerCase().includes("missing or invalid. request()")||g.details.toLowerCase().includes("did not match any variant of untagged enum")||g.details.toLowerCase().includes("account upgraded to unsupported contract")||g.details.toLowerCase().includes("eip-7702 not supported")||g.details.toLowerCase().includes("unsupported wc_ method")||g.details.toLowerCase().includes("feature toggled misconfigured")||g.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(d){if(Object.values(d).some((_)=>!_.optional))throw new nc(new N("non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.",{details:"non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`."}))}if(s&&f.length>1)throw new oc(new N("`forceAtomic` is not supported on fallback to `eth_sendTransaction`.",{details:"`forceAtomic` is not supported on fallback to `eth_sendTransaction`."}));let x=[];for(let S of f){try{let _=await bc(e,{account:l,chain:n,data:S.data,to:S.to,value:S.value?xr(S.value):void 0});x.push({status:"fulfilled",value:_})}catch(_){x.push({reason:_,status:"rejected"})}if(i>0)await new Promise((_)=>setTimeout(_,i))}if(x.every((S)=>S.status==="rejected"))throw x[0].reason;let w=x.map((S)=>{if(S.status==="fulfilled")return S.value;return dI});return{id:Or([...w,Z(n.id,{size:32}),lI])}}throw lc(h,{...t,account:l,chain:t.chain})}}async function Ix(e,t){async function r(d){if(d.endsWith(lI.slice(2))){let h=tn(ub(d,-64,-32)),g=ub(d,0,-64).slice(2).match(/.{1,64}/g),x=await Promise.all(g.map((S)=>dI.slice(2)!==S?e.request({method:"eth_getTransactionReceipt",params:[`0x${S}`]},{dedupe:!0}):void 0)),w=(()=>{if(x.some((S)=>S===null))return 100;if(x.every((S)=>S?.status==="0x1"))return 200;if(x.every((S)=>S?.status==="0x0"))return 500;return 600})();return{atomic:!1,chainId:ur(h),receipts:x.filter(Boolean),status:w,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[d]})}let{atomic:n=!1,chainId:o,receipts:i,version:s="2.0.0",...a}=await r(t.id),[c,l]=(()=>{let d=a.status;if(d>=100&&d<200)return["pending",d];if(d>=200&&d<300)return["success",d];if(d>=300&&d<700)return["failure",d];if(d==="CONFIRMED")return["success",200];if(d==="PENDING")return["pending",100];return[void 0,d]})();return{...a,atomic:n,chainId:o?ur(o):void 0,receipts:i?.map((d)=>({...d,blockNumber:xr(d.blockNumber),gasUsed:xr(d.gasUsed),status:SA[d.status]}))??[],statusCode:l,status:c,version:s}}Ke();async function ZU(e,t={}){let{account:r=e.account,chainId:n}=t,o=r?je(r):void 0,i=n?[o?.address,[Z(n)]]:[o?.address],s=await e.request({method:"wallet_getCapabilities",params:i}),a={};for(let[c,l]of Object.entries(s)){a[Number(c)]={};for(let[d,f]of Object.entries(l)){if(d==="addSubAccount")d="unstable_addSubAccount";a[Number(c)][d]=f}}return typeof n==="number"?a[n]:a}async function WU(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}Fs();async function kx(e,t){let{account:r=e.account,chainId:n,nonce:o}=t;if(!r)throw new Ar({docsPath:"/docs/eip7702/prepareAuthorization"});let i=je(r),s=(()=>{if(!t.executor)return;if(t.executor==="self")return t.executor;return je(t.executor)})(),a={address:t.contractAddress??t.address,chainId:n,nonce:o};if(typeof a.chainId>"u")a.chainId=e.chain?.id??await re(e,ln,"getChainId")({});if(typeof a.nonce>"u"){if(a.nonce=await re(e,Jd,"getTransactionCount")({address:i.address,blockTag:"pending"}),s==="self"||s?.address&&Ur(s.address,i.address))a.nonce+=1}return a}Oi();async function KU(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map((r)=>qo(r))}async function YU(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}et();et();class pI extends N{constructor(e){super(`Call bundle failed with status: ${e.statusCode}`,{name:"BundleFailedError"});Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=e}}async function Rx(e,t){let{id:r,pollingInterval:n=e.pollingInterval,status:o=({statusCode:w})=>w===200||w>=300,retryCount:i=4,retryDelay:s=({count:w})=>~~(1<<w)*200,timeout:a=60000,throwOnFailure:c=!1}=t,l=at(["waitForCallsStatus",e.uid,r]),{promise:d,resolve:f,reject:h}=Hd(),g,x=Gr(l,{resolve:f,reject:h},(w)=>{let S=Ao(async()=>{let _=(A)=>{clearTimeout(g),S(),A(),x()};try{let A=await Nu(async()=>{let T=await re(e,Ix,"getCallsStatus")({id:r});if(c&&T.status==="failure")throw new pI(T);return T},{retryCount:i,delay:s});if(!o(A))return;_(()=>w.resolve(A))}catch(A){_(()=>w.reject(A))}},{interval:n,emitOnBegin:!0});return S});return g=a?setTimeout(()=>{x(),clearTimeout(g),h(new JU({id:r}))},a):void 0,await d}class JU extends N{constructor({id:e}){super(`Timed out while waiting for call bundle with id "${e}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}async function QU(e,t){let{chain:r=e.chain}=t,n=t.timeout??Math.max((r?.blockTime??0)*3,5000),o=await re(e,Ax,"sendCalls")(t);return await re(e,Rx,"waitForCallsStatus")({...t,id:o.id,timeout:n})}async function XU(e,t){let{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]});return}async function ej(e,t){let{account:r=e.account}=t;if(!r)throw new Ar({docsPath:"/docs/eip7702/signAuthorization"});let n=je(r);if(!n.signAuthorization)throw new Ko({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});let o=await kx(e,t);return n.signAuthorization(o)}Ke();async function tj(e,{account:t=e.account,message:r}){if(!t)throw new Ar({docsPath:"/docs/actions/wallet/signMessage"});let n=je(t);if(n.signMessage)return n.signMessage({message:r});let o=(()=>{if(typeof r==="string")return Ja(r);if(r.raw instanceof Uint8Array)return lr(r.raw);return r.raw})();return e.request({method:"personal_sign",params:[o,n.address]},{retryCount:0})}Ke();qs();Bi();async function rj(e,t){let{account:r=e.account,chain:n=e.chain,...o}=t;if(!r)throw new Ar({docsPath:"/docs/actions/wallet/signTransaction"});let i=je(r);jr({account:i,...t});let s=await re(e,ln,"getChainId")({});if(n!==null)hp({currentChainId:s,chain:n});let c=(n?.formatters||e.chain?.formatters)?.transactionRequest?.format||un;if(i.signTransaction)return i.signTransaction({...o,account:i,chainId:s},{serializer:e.chain?.serializers?.transaction});return await e.request({method:"eth_signTransaction",params:[{...c({...o,account:i},"signTransaction"),chainId:Z(s),from:i.address}]},{retryCount:0})}async function nj(e,t){let{account:r=e.account,domain:n,message:o,primaryType:i}=t;if(!r)throw new Ar({docsPath:"/docs/actions/wallet/signTypedData"});let s=je(r),a={EIP712Domain:xx({domain:n}),...t.types};if(bx({domain:n,message:o,primaryType:i,types:a}),s.signTypedData)return s.signTypedData({domain:n,message:o,primaryType:i,types:a});let c=IU({domain:n,message:o,primaryType:i,types:a});return e.request({method:"eth_signTypedData_v4",params:[s.address,c]},{retryCount:0})}Ke();async function oj(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:Z(t)}]},{retryCount:0})}async function ij(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}function sj(e){return{addChain:(t)=>HU(e,t),deployContract:(t)=>GU(e,t),fillTransaction:(t)=>ep(e,t),getAddresses:()=>VU(e),getCallsStatus:(t)=>Ix(e,t),getCapabilities:(t)=>ZU(e,t),getChainId:()=>ln(e),getPermissions:()=>WU(e),prepareAuthorization:(t)=>kx(e,t),prepareTransactionRequest:(t)=>Fi(e,t),requestAddresses:()=>KU(e),requestPermissions:(t)=>YU(e,t),sendCalls:(t)=>Ax(e,t),sendCallsSync:(t)=>QU(e,t),sendRawTransaction:(t)=>gp(e,t),sendRawTransactionSync:(t)=>Sp(e,t),sendTransaction:(t)=>bc(e,t),sendTransactionSync:(t)=>Px(e,t),showCallsStatus:(t)=>XU(e,t),signAuthorization:(t)=>ej(e,t),signMessage:(t)=>tj(e,t),signTransaction:(t)=>rj(e,t),signTypedData:(t)=>nj(e,t),switchChain:(t)=>oj(e,t),waitForCallsStatus:(t)=>Rx(e,t),watchAsset:(t)=>ij(e,t),writeContract:(t)=>Yo(e,t),writeContractSync:(t)=>_p(e,t),token:{approve:Ii(e,Ks),approveSync:Ii(e,sI),transfer:Ii(e,Ys),transferSync:Ii(e,cI)}}}function fI(e){let{key:t="wallet",name:r="Wallet Client",transport:n}=e;return V0({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(sj)}wu();et();class mI extends N{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}jb();wu();function aj(e,{errorInstance:t=Error("timed out"),timeout:r,signal:n}){return new Promise((o,i)=>{(async()=>{let s,a=new AbortController;try{if(r>0)s=setTimeout(()=>{if(n)a.abort();else i(t)},r);o(await e({signal:a?.signal||null}))}catch(c){if(a?.signal.aborted&&Dn(c)){i(t);return}i(c)}finally{clearTimeout(s)}})()})}function jpe(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var hI=jpe();var qpe=10485760;function cj(e,t={}){let{url:r,headers:n}=Gpe(e);return{async request(o){let{body:i,fetchFn:s=t.fetchFn??fetch,maxResponseBodySize:a=t.maxResponseBodySize??qpe,onRequest:c=t.onRequest,onResponse:l=t.onResponse,timeout:d=t.timeout??1e4}=o,f={...t.fetchOptions??{},...o.fetchOptions??{}},{headers:h,method:g,signal:x}=f;try{let w=await aj(async({signal:A})=>{let T={...f,body:Array.isArray(i)?at(i.map((O)=>({jsonrpc:"2.0",id:O.id??hI.take(),...O}))):at({jsonrpc:"2.0",id:i.id??hI.take(),...i}),headers:{...n,"Content-Type":"application/json",...h},method:g||"POST",signal:x||(d>0?A:null)},v=new Request(r,T),E=await c?.(v,T)??{...T,url:r};return await s(E.url??r,E)},{errorInstance:new Cb({body:i,url:r}),timeout:d,signal:!0});if(l)await l(w);let S,_=await Hpe(w,{maxResponseBodySize:a});if(w.headers.get("Content-Type")?.startsWith("application/json"))S=JSON.parse(_);else{S=_;try{S=JSON.parse(S||"{}")}catch(A){if(w.ok)throw A;S={error:S}}}if(!w.ok){if(typeof S.error?.code==="number"&&typeof S.error?.message==="string")return S;throw new Go({body:i,details:at(S.error)||w.statusText,headers:w.headers,status:w.status,url:r})}return S}catch(w){if(x?.aborted)throw rn(x);if(Dn(w))throw w;if(w instanceof Go)throw w;if(w instanceof xd)throw w;if(w instanceof Cb)throw w;throw new Go({body:i,cause:w,url:r})}}}}async function Hpe(e,{maxResponseBodySize:t}){if(t===!1)return e.text();let r=e.headers.get("Content-Length");if(r){let a=Number(r);if(a>t)throw new xd({maxSize:t,size:a})}if(!e.body){let a=await e.text(),c=new TextEncoder().encode(a).length;if(c>t)throw new xd({maxSize:t,size:c});return a}let n=e.body.getReader(),o=new TextDecoder,i="",s=0;try{while(!0){let{done:a,value:c}=await n.read();if(a)break;if(s+=c.byteLength,s>t)throw await n.cancel(),new xd({maxSize:t,size:s});i+=o.decode(c,{stream:!0})}return i+=o.decode(),i}finally{n.releaseLock()}}function Gpe(e){try{let t=new URL(e),r=(()=>{if(t.username){let n=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;return t.username="",t.password="",{url:t.toString(),headers:{Authorization:`Basic ${btoa(n)}`}}}return})();return{url:t.toString(),...r}}catch{return{url:e}}}et();wu();Dd();pu();var Cx=new Jn(8192);function uj(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(Cx.get(r))return Cx.get(r);let n=e().finally(()=>Cx.delete(r));return Cx.set(r,n),n}function lj(e,t={}){return async(r,n={})=>{let{dedupe:o=!1,methods:i,retryDelay:s=150,retryCount:a=3,signal:c,uid:l}={...t,...n},{method:d}=r;if(i?.exclude?.includes(d))throw new rc(Error("method not supported"),{method:d});if(i?.include&&!i.include.includes(d))throw new rc(Error("method not supported"),{method:d});if(c?.aborted)throw rn(c);let f=o?Zpe(`${l}.${at(r)}`):void 0;return uj(()=>Nu(async()=>{try{return await e(r,c?{signal:c}:void 0)}catch(h){if(c?.aborted)throw rn(c);if(Dn(h))throw h;let g=h;switch(g.code){case wd.code:throw new wd(g);case Sd.code:throw new Sd(g);case _d.code:throw new _d(g,{method:r.method});case Td.code:throw new Td(g);case Ls.code:throw new Ls(g);case _o.code:throw new _o(g);case vd.code:throw new vd(g);case Ed.code:throw new Ed(g);case Pd.code:throw new Pd(g);case rc.code:throw new rc(g,{method:r.method});case Su.code:throw new Su(g);case Ad.code:throw new Ad(g);case _u.code:throw new _u(g);case Id.code:throw new Id(g);case kd.code:throw new kd(g);case Rd.code:throw new Rd(g);case Cd.code:throw new Cd(g);case Od.code:throw new Od(g);case nc.code:throw new nc(g);case Md.code:throw new Md(g);case Nd.code:throw new Nd(g);case $d.code:throw new $d(g);case zd.code:throw new zd(g);case Ld.code:throw new Ld(g);case oc.code:throw new oc(g);case 5000:throw new _u(g);case Bd.code:throw new Bd(g);default:if(h instanceof N)throw h;throw new RP(g)}}},{delay:({count:h,error:g})=>{if(g&&g instanceof Go){let x=g?.headers?.get("Retry-After");if(x?.match(/\d/))return Number.parseInt(x,10)*1000}return~~(1<<h)*s},retryCount:a,signal:c,shouldRetry:({error:h})=>Vpe(h)}),{enabled:o,id:f})}}function Vpe(e){if(Dn(e))return!1;if("code"in e&&typeof e.code==="number"){if(e.code===-1)return!0;if(e.code===Su.code)return!0;if(e.code===Ls.code)return!0;if(e.code===429)return!0;return!1}if(e instanceof Go&&e.status){if(e.status===403)return!0;if(e.status===408)return!0;if(e.status===413)return!0;if(e.status===429)return!0;if(e.status===500)return!0;if(e.status===502)return!0;if(e.status===503)return!0;if(e.status===504)return!0;return!1}return!0}function Zpe(e,t=0){let r=3735928559^t,n=1103547991^t;for(let o=0;o<e.length;o++){let i=e.charCodeAt(o);r=Math.imul(r^i,2654435761),n=Math.imul(n^i,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>16,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>16,3266489909),(4294967296*(2097151&n)+(r>>>0)).toString(36)}function dj({key:e,methods:t,name:r,request:n,retryCount:o=3,retryDelay:i=150,timeout:s,type:a},c){let l=G0();return{config:{key:e,methods:t,name:r,request:n,retryCount:o,retryDelay:i,timeout:s,type:a},request:lj(n,{methods:t,retryCount:o,retryDelay:i,uid:l}),value:c}}var Wpe=0,pj=new WeakMap;function Kpe(e){if(!e)return"default";let t=pj.get(e);if(t!==void 0)return t;let r=Wpe++;return pj.set(e,r),r}function gh(e,t={}){let{batch:r,fetchFn:n,fetchOptions:o,key:i="http",maxResponseBodySize:s,methods:a,name:c="HTTP JSON-RPC",onFetchRequest:l,onFetchResponse:d,retryDelay:f,raw:h}=t;return({chain:g,retryCount:x,timeout:w})=>{let{batchSize:S=1000,wait:_=0}=typeof r==="object"?r:{},A=t.retryCount??x,T=w??t.timeout??1e4,v=e||g?.rpcUrls.default.http[0];if(!v)throw new mI;let E=cj(v,{fetchFn:n,fetchOptions:o,maxResponseBodySize:s,onRequest:l,onResponse:d,timeout:T});return dj({key:i,methods:a,name:c,async request({method:k,params:O},B){let G={method:k,params:O},M=B?.signal?{signal:B.signal}:void 0,{schedule:J}=Gd({id:`${v}.${Kpe(B?.signal)}`,wait:_,shouldSplitBatch(j){return j.length>S},fn:(j)=>E.request({body:j,fetchOptions:M}),sort:(j,se)=>j.id-se.id}),W=async(j)=>r?J(j):[await E.request({body:j,fetchOptions:M})],[{error:he,result:ge}]=await W(G);if(h)return{error:he,result:ge};if(he)throw new xu({body:G,error:he,url:v});return ge},retryCount:A,retryDelay:f,timeout:T,type:"http"},{fetchOptions:o,url:v})}}en();function Ox(e){let t={formatters:void 0,fees:void 0,serializers:void 0,...e};function r(n){return(o)=>{let i=typeof o==="function"?o(n):o,s={...n,...i};return Object.assign(s,{extend:r(s)})}}return Object.assign(t,{extend:r(t)})}var yh=Ox({id:1329,name:"Sei Network",nativeCurrency:{name:"Sei",symbol:"SEI",decimals:18},rpcUrls:{default:{http:["https://evm-rpc.sei-apis.com/"],webSocket:["wss://evm-ws.sei-apis.com/"]}},blockExplorers:{default:{name:"Seiscan",url:"https://seiscan.io",apiUrl:"https://api.etherscan.io/v2/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11"}}});var bh=Ox({id:1328,name:"Sei Testnet",nativeCurrency:{name:"Sei",symbol:"SEI",decimals:18},rpcUrls:{default:{http:["https://evm-rpc-testnet.sei-apis.com"],webSocket:["wss://evm-ws-testnet.sei-apis.com"]}},blockExplorers:{default:{name:"Seiscan",url:"https://testnet.seiscan.io",apiUrl:"https://api.etherscan.io/v2/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:98697651}},testnet:!0});var Ype=y({applicationId:p().uuid(),enrolled:oe(),payoutAddress:p().nullable().optional(),buildercodesEnabled:oe(),buildercodesBudgetBps:I().int().min(0).max(1e4),builderFeeEnabled:oe(),builderFeeBps:I().int().min(0).max(100),builderFeeCapBps:I().int().min(0).max(100),changesRemaining:I().int().min(0).max(2),nextChangeAllowedAt:p().nullable().optional()}),gI=y({bps:I().int().min(0).max(100)}),Jpe=y({builderFeeBps:I().int().min(0).max(100),previousBuilderFeeBps:I().int().min(0).max(100),changesRemaining:I().int().min(0).max(2),nextChangeAllowedAt:p().nullable().optional()}),fj=z(["BUILDER","ADMIN"]),mj=y({actorType:fj,actor:p(),oldBps:I().int().min(0).max(100),newBps:I().int().min(0).max(100),createdAt:p()}),yI=y({pageSize:I().int().min(1).max(100).optional(),pageToken:p().optional()}),Qpe=y({changes:ie(mj),nextPageToken:p()}),Mx=z(["REVENUE_SHARE","BUILDER_FEE"]),bI=y({page:Qe().optional(),pageSize:I().int().min(1).max(1000).optional(),pageToken:p().optional(),kind:Mx.optional()}),hj=y({tradeId:p().uuid(),payoutAddress:p(),token:p(),amount:p(),appliedBps:I().int(),createdAt:p(),kind:Mx.optional()}),Xpe=y({payouts:ie(hj),total:I().int().nonnegative(),pageSize:I().int().positive(),totalPages:I().int().nonnegative(),nextPageToken:p()}),gj=y({token:p(),totalAmount:p(),payoutCount:I().int().nonnegative(),lastCreditedAt:p()}),yj=y({token:p(),kind:Mx,totalAmount:p(),payoutCount:I().int().nonnegative(),lastCreditedAt:p()}),efe=y({totalPayouts:I().int().nonnegative(),lastCreditedAt:p().nullable().optional(),byToken:ie(gj),byTokenAndKind:ie(yj).optional()}),bj=y({token:p(),available:p()}),tfe=y({balances:ie(bj)}),xI=y({token:p().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:p().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),rfe=y({payoutBalance:p(),tradingBalance:p()});function Jo(){return p()}var wI=y({walletAddress:p(),handle:p().nullish(),display:p()}),SI=y({leader:wI,status:Jo(),shareBps:I(),bio:p(),minAllocation:p().nullish(),registeredAt:p()}),_I=y({followerCount:I(),allocated:p(),aumEquity:p().nullish()}),TI=y({window:Jo(),pnl:p(),roiPct:p().nullish(),maxDrawdownPct:p().nullish(),winRatePct:p().nullish(),closedTrades:I()}),nfe=y({profile:SI,followSummary:_I,stats:ie(TI)}),xj=y({profile:SI,followSummary:_I,stats:TI}),ofe=y({leaders:ie(xj),nextPageToken:p(),asOf:p()}),ife=y({created:oe(),status:Jo(),shareBps:I()}),wj=y({walletAddress:p(),display:p(),status:Jo(),allocation:p(),startedAt:p()}),sfe=y({followers:ie(wj),nextPageToken:p()}),Sj=y({tradingPairId:p(),positionSide:p(),action:Jo(),size:p().nullish(),exitPrice:p().nullish(),entryPrice:p().nullish(),realizedPnl:p().nullish(),netRealizedPnl:p().nullish(),realizedRoe:p().nullish(),closedAt:p()}),afe=y({closedTrades:ie(Sj),nextPageToken:p()}),vI=y({tradingPairId:p(),side:p(),size:p(),entryPrice:p(),markPrice:p().nullish(),unrealizedPnl:p().nullish(),leverage:p().nullish(),marginMode:p()}),cfe=y({positions:ie(vI)}),EI=y({followId:p(),leader:wI,status:Jo(),marginModePolicy:Jo(),sizingMode:Jo(),sizingParam:p().nullish(),leverageMode:Jo(),fixedLeverage:p().nullish(),allocation:p(),slPct:p().nullish(),copyExisting:oe(),tradingPairIds:ie(p()),consecutiveSkips:I(),copyRiskBucketId:p(),startedAt:p(),stoppedAt:p().nullish(),stopReason:Jo().nullish()}),ufe=y({follows:ie(EI),nextPageToken:p()}),_j=y({tradingPairId:p(),reason:Jo(),requestedQuantity:p(),skippedAt:p()}),lfe=y({follow:EI,recentSkips:ie(_j),copyAccountEquity:p().nullish()}),dfe=y({positions:ie(vI)}),pfe=y({followId:p(),copyRiskBucketId:p(),created:oe()}),ffe=y({estimatedMargin:p(),estimatedFee:p(),copiedPositions:I(),skippedPositions:I(),truncated:oe()}),mfe=y({followId:p()}),Tj=y({followId:p(),closeOrdersPlaced:I(),positionsNotClosed:I()}),vj=y({followId:p(),reason:p()}),hfe=y({follows:ie(Tj),stoppingFollowIds:ie(p()),failedFollows:ie(vj)}),gfe=y({followId:p(),tradingPairId:p(),riskBucketId:p(),positionId:p(),positionMargin:p(),copyAccountAvailable:p()});var PI=y({tradingPairId:p().trim().min(1,"Trading pair ID is required and cannot be empty"),side:z(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:p().trim().min(1,"Price is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Price must be a valid number").refine((e)=>Number(e)>0,"Price must be greater than 0"),quantity:p().trim().min(1,"Quantity is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Quantity must be a valid number").refine((e)=>Number(e)>0,"Quantity must be greater than 0"),orderType:z(["LIMIT","MARKET"]).optional(),slippageToleranceBps:I().int().min(0,"Slippage tolerance must be between 0 and 1000 bps").max(1000,"Slippage tolerance must be between 0 and 1000 bps").optional()}).superRefine((e,t)=>{if(e.slippageToleranceBps!==void 0&&e.orderType!=="MARKET")t.addIssue({code:wa.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),yfe=y({applicationName:p().nullable().optional(),applicationTakerFee:p(),applicationTakerFeeBps:I(),buyOrderLockAmount:p().nullable().optional(),makerTotalReceipt:p(),monacoMakerRebate:p(),monacoMakerRebateBps:I(),monacoMakerRebateBpsExact:p(),monacoTakerFee:p(),monacoTakerFeeBps:I(),monacoTakerFeeBpsExact:p(),notional:p(),takerTotalPayment:p(),totalTakerFees:p(),maxQuantity:p().nullable(),maxQuantityRaw:p().nullable(),slippageToleranceBps:I().nullable()}),AI=y({tradingPairId:p().trim().min(1,"Trading pair ID is required and cannot be empty")}),Ej=y({tierLevel:I().int(),minVolumeThreshold:p(),makerFeeBps:p(),takerFeeBps:p()}),bfe=y({currentTierLevel:I().int(),weightedVolume14d:p(),spotVolume14d:p(),perpVolume14d:p(),volumeToNextTier:p().nullable().optional(),nextTierLevel:I().int().nullable().optional(),feeSchedule:ie(Ej)});var Pj=y({token:p(),available:p()}),xfe=y({balances:ie(Pj)}),wfe=y({code:p(),createdAt:p(),customCode:p(),isCustom:oe(),display:p()}),Aj=z(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),Sfe=y({available:oe(),reason:Ff((e)=>e===""||e===null?void 0:e,Aj.optional())}),II=y({code:p().trim().min(1,"code is required").regex(/^[A-Za-z][A-Za-z0-9_]{4,19}$/,"code must start with a letter and be 5–20 chars of letters, digits, or underscores")}),_fe=y({code:p()}),kI=y({token:p().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:p().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),Tfe=y({rewardsBalance:p(),tradingBalance:p()}),Ij=y({source:p(),sourceDisplay:p(),level:I(),amount:p(),token:p(),rateApplied:p(),createdAt:p()}),kj=y({wallet:p(),display:p(),level:I()}),vfe=y({referrer:p(),referrerDisplay:p(),totalEarned:p(),rewards:ie(Ij),upline:ie(kj)}),Rj=y({source:p(),sourceDisplay:p(),level:I(),totalEarned:p(),token:p()}),Cj=y({wallet:p(),display:p(),referredAt:p(),totalEarned:p()}),Oj=y({level:I(),earned:p()}),Mj=y({totalEarned:p(),level1Earned:p(),level2Earned:p(),level3Earned:p(),byLevel:ie(Oj)}),RI=y({pageSize:I().int().min(1).max(500).optional(),pageToken:p().optional()}),Efe=y({earningsBySource:ie(Rj),directReferees:ie(Cj),summary:Mj,nextPageToken:p()}),CI=y({parent:p().optional(),pageSize:I().int().min(1).max(200).optional(),pageToken:p().optional()}),Nj=y({wallet:p(),display:p(),level:I(),parent:p(),referredAt:p(),refereeCount:I(),totalEarned:p()}),Pfe=y({parent:p(),parentLevel:I(),nodes:ie(Nj),nextPageToken:p()});var Nx=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var Pp=z(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),xh=z(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),Bx=z(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),wh=z(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),$j=z(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),OI=z(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),$u=z(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"],{message:'Self-trade prevention mode must be "CANCEL_MAKER", "CANCEL_TAKER", "CANCEL_BOTH", or "SKIP"'}),Ap=z(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),Ve=p().trim().min(1,"Value cannot be empty").regex(/^\d+(\.\d+)?$/,"Value must be a positive decimal number (e.g., '1.5', '100')").refine((e)=>Number.parseFloat(e)>0,{message:"Value must be greater than 0"}),be=UC({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),Js=wl.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),zj=I().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),Ip=I().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),Lj=I().int().min(0,"Slippage tolerance must be at least 0 bps").max(1000,"Slippage tolerance cannot exceed 1000 bps"),Afe=I().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),$x=y({triggerPrice:Ve,orderType:Ap,limitPrice:Ve.optional(),quantity:Ve.optional(),closePosition:oe().optional(),timeInForce:OI.optional(),slippageToleranceBps:Ip.optional(),expiresAt:Js.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT parent TP/SL",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET parent TP/SL",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),Ife=I().int("trailBps must be an integer number of basis points").min(10,"trailBps must be at least 10 bps").max(2000,"trailBps cannot exceed 2000 bps"),MI=y({trailBps:Ife,activationPrice:Ve.optional(),quantity:Ve.optional(),closePosition:oe().optional(),slippageToleranceBps:Ip.optional(),expiresAt:Js.optional()}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),Bj=MI,zx=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0||e?.trailingStop!==void 0,NI=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),$I=p().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/,"idempotencyKey must contain only letters, digits, or . _ : -"),Dj=y({tradingPairId:be,side:Pp,quantity:Ve,price:Ve,options:y({idempotencyKey:$I.optional(),tradingMode:xh.optional(),useMasterBalance:oe().optional(),expirationDate:Js.optional(),timeInForce:$j.optional(),marginAccountId:be.optional(),marginMode:Bx.optional(),riskBucketId:be.optional(),riskBucketCollateral:Ve.optional(),strategyKey:p().min(1).max(128).optional(),positionSide:wh.optional(),leverage:Ve.optional(),reduceOnly:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:$u.optional(),takeProfit:$x.optional(),stopLoss:$x.optional(),trailingStop:Bj.optional()}).optional()}).refine((e)=>NI(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!zx(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss/trailingStop are only supported for MARGIN orders",path:["options"]}).refine((e)=>!zx(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss/trailingStop cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}).refine((e)=>e.options?.postOnly!==!0||e.options?.timeInForce===void 0||e.options.timeInForce!=="IOC"&&e.options.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["options","timeInForce"]}),Fj=y({tradingPairId:be,side:Pp,quantity:Ve,options:y({idempotencyKey:$I.optional(),tradingMode:xh.optional(),slippageTolerance:zj,marginAccountId:be.optional(),marginMode:Bx.optional(),riskBucketId:be.optional(),riskBucketCollateral:Ve.optional(),strategyKey:p().min(1).max(128).optional(),positionSide:wh.optional(),leverage:Ve.optional(),reduceOnly:oe().optional(),selfTradePreventionMode:$u.optional(),takeProfit:$x.optional(),stopLoss:$x.optional(),trailingStop:Bj.optional()}).optional()}).refine((e)=>NI(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!zx(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss/trailingStop are only supported for MARGIN orders",path:["options"]}).refine((e)=>!zx(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss/trailingStop cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),Uj=y({orderId:be,remainingQuantityTarget:Ve.optional()}),jj=y({orderId:be,newOrder:y({price:Ve.optional(),quantity:Ve.optional(),useMasterBalance:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:$u.optional()})}),qj=y({page:Qe().optional(),status:pt([z(Nx),ie(z(Nx)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:be.optional(),tradingMode:xh.optional(),marginAccountId:be.optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),S2t=z(["STOP_LOSS","TAKE_PROFIT","TRAILING_STOP"],{message:'conditionType must be "STOP_LOSS", "TAKE_PROFIT", or "TRAILING_STOP"'}),_2t=z(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),kfe=z(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),Hj=z(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),zI=y({conditionalOrderId:be}),Gj=y({page:Qe().optional(),marginAccountId:be.optional(),tradingPairId:be.optional(),state:kfe.optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),Rfe=z(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),Cfe=pt([I().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),p().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),Ofe=2592000000,Vj=y({tradingPairId:be,side:Pp,quantity:Ve,options:y({durationSeconds:Cfe.optional(),startTime:Js.optional(),endTime:Js.optional(),limitPrice:Ve.optional(),slippageToleranceBps:Afe.optional(),randomize:oe().optional(),executionStyle:z(["TAKER","PASSIVE"]).optional(),reduceOnly:oe().optional(),tradingMode:xh.optional(),marginAccountId:be.optional(),riskBucketId:be.optional(),marginMode:Bx.optional(),leverage:Ve.optional(),strategyKey:p().min(1).max(128).optional(),useMasterBalance:oe().optional(),clientTwapId:p().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional(),triggerPrice:Ve.optional(),triggerDirection:z(["ABOVE","BELOW"]).optional(),conditionalExpiry:Js.optional()})}).refine((e)=>e.options.durationSeconds!==void 0!==(e.options.endTime!==void 0),{message:"Exactly one of durationSeconds or endTime must be set",path:["options","durationSeconds"]}).refine((e)=>e.options.startTime===void 0||e.options.endTime!==void 0,{message:"startTime is only valid together with endTime",path:["options","startTime"]}).refine((e)=>e.options.marginMode===void 0||e.options.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode==="MARGIN",{message:"riskBucketId is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}).refine((e)=>e.options.triggerPrice!==void 0===(e.options.triggerDirection!==void 0),{message:"triggerPrice and triggerDirection are both-or-neither",path:["options","triggerDirection"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.durationSeconds!==void 0,{message:"conditional TWAP (triggerPrice) requires durationSeconds — the window floats from the trigger instant",path:["options","durationSeconds"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.startTime===void 0&&e.options.endTime===void 0,{message:"triggerPrice is incompatible with startTime/endTime",path:["options","triggerPrice"]}).refine((e)=>e.options.conditionalExpiry===void 0||e.options.triggerPrice!==void 0,{message:"conditionalExpiry is only valid together with triggerPrice",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r>Date.now()},{message:"conditionalExpiry must be in the future",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r-Date.now()<=Ofe},{message:"conditionalExpiry cannot be more than 30 days after creation (the maximum window)",path:["options","conditionalExpiry"]}),Dx=y({twapOrderId:be}),Zj=y({page:Qe().optional(),state:Rfe.optional(),tradingPairId:be.optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),Wj=y({page:Qe().optional(),twapOrderId:be,orderBy:z(["ASC","DESC"]).optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),Mfe=y({tradingPairId:be,orderType:Ap,side:Pp,price:Ve.optional(),quantity:Ve,idempotencyKey:$I.optional(),tradingMode:xh.optional(),slippageTolerance:zj,useMasterBalance:oe().optional(),expirationDate:Js.optional(),timeInForce:$j.optional(),marginAccountId:be.optional(),marginMode:Bx.optional(),riskBucketId:be.optional(),riskBucketCollateral:Ve.optional(),strategyKey:p().min(1).max(128).optional(),positionSide:wh.optional(),leverage:Ve.optional(),reduceOnly:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:$u.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).refine((e)=>e.orderType!=="MARKET"||e.postOnly!==!0,{message:"postOnly must not be provided for MARKET orders",path:["postOnly"]}).refine((e)=>e.postOnly!==!0||e.timeInForce===void 0||e.timeInForce!=="IOC"&&e.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["postOnly"]}).refine((e)=>e.riskBucketCollateral===void 0||e.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode!=="CROSS"||e.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine((e)=>e.marginMode!=="CROSS"||e.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine((e)=>e.riskBucketCollateral===void 0||e.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.riskBucketCollateral===void 0||e.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine((e)=>NI(e.side,e.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["positionSide"]}).refine((e)=>e.tradingMode!=="MARGIN"||e.reduceOnly===!0||e.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["leverage"]}),Lx=100,Kj=y({orders:ie(Mfe).min(1,"At least one order is required").max(Lx,`At most ${Lx} orders per batch request`)}),Nfe=y({orderId:be,price:Ve.optional(),quantity:Ve.optional(),useMasterBalance:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:$u.optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),Yj=y({orders:ie(Nfe).min(1,"At least one order is required").max(Lx,`At most ${Lx} orders per batch request`)});var Fx=y({clientId:p().trim().min(1,"Client ID is required"),page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),Jj=Fx.extend({status:p().trim().min(1,"Status cannot be empty").optional(),userId:be.optional(),tradingPairId:be.optional(),side:p().trim().min(1,"Side cannot be empty").optional(),orderType:p().trim().min(1,"Order type cannot be empty").optional()}),Qj=Fx.extend({isActive:oe().optional(),accountType:p().trim().min(1,"Account type cannot be empty").optional(),address:p().trim().min(1,"Address filter cannot be empty").optional()}),Xj=Fx.extend({userId:be.optional(),transactionType:p().trim().min(1,"Transaction type cannot be empty").optional(),entryType:p().trim().min(1,"Entry type cannot be empty").optional(),assetId:be.optional()}),eq=Fx.extend({userId:be.optional(),assetId:be.optional()});class tq extends Error{issues;constructor(e){let t=e.issues.map((r)=>{let n=r.path.join(".");return`${n?`${n}: `:""}${r.message}`});super(`Validation failed:
145
+ `),{docsPath:e,docsSlug:"account",name:"AccountNotFoundError"})}}class Ko extends N{constructor({docsPath:e,metaMessages:t,type:r}){super(`Account type "${r}" is not supported.`,{docsPath:e,metaMessages:t,name:"AccountTypeNotSupportedError"})}}Bn();et();Um();function hp({chain:e,currentChainId:t}){if(!e)throw new pP;if(t!==e.id)throw new dP({chain:e,currentChainId:t})}qs();pu();Bi();async function gp(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}var rI=new Jn(128);async function bc(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:i,authorizationList:s,blobs:a,data:c,dataSuffix:l=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:f,maxFeePerBlobGas:h,maxFeePerGas:g,maxPriorityFeePerGas:x,nonce:w,type:S,value:_,...A}=t;if(typeof r>"u")throw new Ar({docsPath:"/docs/actions/wallet/sendTransaction"});let T=r?je(r):null,v;try{jr(t);let E=await(async()=>{if(t.to)return t.to;if(t.to===null)return;if(s&&s.length>0)return await cc({authorization:s[0]}).catch(()=>{throw new N("`to` is required. Could not infer from `authorizationList`.")});return})();if(T?.type==="json-rpc"||T===null){let k;if(o!==null){if(k=await re(e,ln,"getChainId")({}),n)hp({currentChainId:k,chain:o})}let O=e.chain?.formatters?.transactionRequest?.format,G=(O||un)({...Eo(A,{format:O}),accessList:i,account:T,authorizationList:s,blobs:a,chainId:k,data:l?Or([c??"0x",l]):c,gas:d,gasPrice:f,maxFeePerBlobGas:h,maxFeePerGas:g,maxPriorityFeePerGas:x,nonce:w,to:E,type:S,value:_},"sendTransaction"),M=rI.get(e.uid),J=M?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:J,params:[G]},{retryCount:0})}catch(W){if(M===!1)throw W;let he=W;if(he.name==="InvalidInputRpcError"||he.name==="InvalidParamsRpcError"||he.name==="MethodNotFoundRpcError"||he.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[G]},{retryCount:0}).then((ge)=>(rI.set(e.uid,!0),ge)).catch((ge)=>{let j=ge;if(j.name==="MethodNotFoundRpcError"||j.name==="MethodNotSupportedRpcError")throw rI.set(e.uid,!1),he;throw j});throw he}}if(T?.type==="local"){let k=(()=>{if(!T.nonceManager||typeof w<"u")return T.nonceManager;let W=T.nonceManager;return{consume(he){return v={address:he.address,chainId:he.chainId},W.consume(he)},get(he){return W.get(he)},increment(he){return W.increment(he)},reset(he){return W.reset(he)}}})(),O=await re(e,Fi,"prepareTransactionRequest")({account:T,accessList:i,authorizationList:s,blobs:a,chain:o,data:l?Or([c??"0x",l]):c,gas:d,gasPrice:f,maxFeePerBlobGas:h,maxFeePerGas:g,maxPriorityFeePerGas:x,nonce:w,nonceManager:k,parameters:[...uh,"sidecars"],type:S,value:_,...A,to:E}),B=o?.serializers?.transaction,G=await T.signTransaction(O,{serializer:B}),M=(o??e.chain)?.serializers?.transactionEnvelope,J=M?await M({serializedTransaction:G,transaction:O}):G;return await re(e,gp,"sendRawTransaction")({serializedTransaction:J})}if(T?.type==="smart")throw new Ko({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"});throw new Ko({docsPath:"/docs/actions/wallet/sendTransaction",type:T?.type})}catch(E){if(E instanceof Ko)throw E;if(v)T?.nonceManager?.reset(v);throw lc(E,{...t,account:T,chain:t.chain||void 0})}}async function Yo(e,t){return Yo.internal(e,bc,"sendTransaction",t)}(function(e){async function t(r,n,o,i){let{abi:s,account:a=r.account,address:c,args:l,functionName:d,...f}=i;if(typeof a>"u")throw new Ar({docsPath:"/docs/contract/writeContract"});let h=a?je(a):null,g=Dt({abi:s,args:l,functionName:d});try{return await re(r,n,o)({data:g,to:c,account:h,...f})}catch(x){throw eo(x,{abi:s,address:c,args:l,docsPath:"/docs/contract/writeContract",functionName:d,sender:h?.address})}}e.internal=t})(Yo||(Yo={}));en();Qn();Fs();jm();function yp(e,t){return Ab(e,t)}jm();function jU(e,t){return TD(e,t)}function bp(e,t){return{amount:e,decimals:t,formatted:yp(e,t)}}function vx(e,t){if(typeof e==="bigint")return e;let r=e.decimals??t;return jU(e.formatted,zpe(r))}function zpe(e){if(e===void 0)throw Error("Token decimals are required. Pass `amount.decimals` or select a declared token.");return e}function Ex(e,t){if(typeof e==="bigint")return t;return e.decimals??t}function nn(e,t){let{decimals:r,token:n}=t,o=oI(e,n);if(o)return{address:o.address,decimals:r??o.decimals};if(_t(n,{strict:!1}))return{address:n,decimals:r??Bpe(e,n)};throw Error(`Token "${n}" is not a declared ERC-20 token on the client's \`tokens\` array (with an address for the client's chain), and is not a valid address.`)}function oI(e,t){let r=e.tokens,n=e.chain?.id;if(!r||n===void 0)return;let o=Lpe(r,t);if(o)return nI(o,n);if(_t(t,{strict:!1}))for(let i of r){let s=nI(i,n);if(s&&Ur(s.address,t))return s}return}function nI(e,t){let r=e.addresses[t];if(!r)return;return{address:r,currency:e.currency,decimals:e.decimals,name:e.name,popular:e.popular,symbol:e.symbol}}function Lpe(e,t){let r=t.toLowerCase();for(let n of e)if(n.symbol?.toLowerCase()===r)return n;return}function Bpe(e,t){let r=e.tokens,n=e.chain?.id;if(r&&n!==void 0)for(let o of r){let i=nI(o,n);if(i&&Ur(i.address,t))return i.decimals}return}async function xp(e,t){let{address:r,decimals:n}=nn(e,t);if(n!==void 0)return{address:r,decimals:n};return{address:r,decimals:await Tt(e,{abi:ar,address:r,functionName:"decimals"})}}function wp(e){let{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:i,nonce:s}=e;return{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:i,nonce:s}}function ji(e){return{...e,data:Dt(e),to:e.address}}async function Ks(e,t){return Ks.inner(Yo,e,t)}(function(e){async function t(s,a,c){return await s(a,{...c,...e.call(a,c)})}e.inner=t;function r(s,a){return ji(Dpe(s,a))}e.call=r;async function n(s,a){return rp(s,{...wp(a),...e.call(s,a)})}e.estimateGas=n;async function o(s,a){return fp(s,{...wp(a),...e.call(s,a)})}e.simulate=o;function i(s){let[a]=Ui({abi:ar,logs:s,eventName:"Approval",strict:!0});if(!a)throw Error("`Approval` event not found.");return a}e.extractEvent=i})(Ks||(Ks={}));function Dpe(e,t){let{amount:r,spender:n,token:o}=t,{address:i,decimals:s}=nn(e,{token:o});return{abi:ar,address:i,args:[n,vx(r,s)],functionName:"approve"}}et();Tn();qs();pu();Bi();Tn();async function Sp(e,{serializedTransaction:t,throwOnReceiptRevert:r,timeout:n}){let o=await e.request({method:"eth_sendRawTransactionSync",params:n?[t,n]:[t]},{retryCount:0}),s=(e.chain?.formatters?.transactionReceipt?.format||np)(o);if(s.status==="reverted"&&r)throw new hd({receipt:s});return s}var iI=new Jn(128);async function Px(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:i,authorizationList:s,blobs:a,data:c,dataSuffix:l=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:f,maxFeePerBlobGas:h,maxFeePerGas:g,maxPriorityFeePerGas:x,nonce:w,pollingInterval:S,throwOnReceiptRevert:_,type:A,value:T,...v}=t,E=t.timeout??Math.max((o?.blockTime??0)*3,5000);if(typeof r>"u")throw new Ar({docsPath:"/docs/actions/wallet/sendTransactionSync"});let k=r?je(r):null,O;try{jr(t);let B=await(async()=>{if(t.to)return t.to;if(t.to===null)return;if(s&&s.length>0)return await cc({authorization:s[0]}).catch(()=>{throw new N("`to` is required. Could not infer from `authorizationList`.")});return})();if(k?.type==="json-rpc"||k===null){let G;if(o!==null){if(G=await re(e,ln,"getChainId")({}),n)hp({currentChainId:G,chain:o})}let M=e.chain?.formatters?.transactionRequest?.format,W=(M||un)({...Eo(v,{format:M}),accessList:i,account:k,authorizationList:s,blobs:a,chainId:G,data:l?Or([c??"0x",l]):c,gas:d,gasPrice:f,maxFeePerBlobGas:h,maxFeePerGas:g,maxPriorityFeePerGas:x,nonce:w,to:B,type:A,value:T},"sendTransaction"),he=iI.get(e.uid),ge=he?"wallet_sendTransaction":"eth_sendTransaction",j=await(async()=>{try{return await e.request({method:ge,params:[W]},{retryCount:0})}catch(Se){if(he===!1)throw Se;let D=Se;if(D.name==="InvalidInputRpcError"||D.name==="InvalidParamsRpcError"||D.name==="MethodNotFoundRpcError"||D.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[W]},{retryCount:0}).then((q)=>(iI.set(e.uid,!0),q)).catch((q)=>{let Q=q;if(Q.name==="MethodNotFoundRpcError"||Q.name==="MethodNotSupportedRpcError")throw iI.set(e.uid,!1),D;throw Q});throw D}})(),se=await re(e,Tx,"waitForTransactionReceipt")({checkReplacement:!1,hash:j,pollingInterval:S,timeout:E});if(_&&se.status==="reverted")throw new hd({receipt:se});return se}if(k?.type==="local"){let G=(()=>{if(!k.nonceManager||typeof w<"u")return k.nonceManager;let j=k.nonceManager;return{consume(se){return O={address:se.address,chainId:se.chainId},j.consume(se)},get(se){return j.get(se)},increment(se){return j.increment(se)},reset(se){return j.reset(se)}}})(),M=await re(e,Fi,"prepareTransactionRequest")({account:k,accessList:i,authorizationList:s,blobs:a,chain:o,data:l?Or([c??"0x",l]):c,gas:d,gasPrice:f,maxFeePerBlobGas:h,maxFeePerGas:g,maxPriorityFeePerGas:x,nonce:w,nonceManager:G,parameters:[...uh,"sidecars"],type:A,value:T,...v,to:B}),J=o?.serializers?.transaction,W=await k.signTransaction(M,{serializer:J}),he=(o??e.chain)?.serializers?.transactionEnvelope,ge=he?await he({serializedTransaction:W,transaction:M}):W;return await re(e,Sp,"sendRawTransactionSync")({serializedTransaction:ge,throwOnReceiptRevert:_,timeout:t.timeout})}if(k?.type==="smart")throw new Ko({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"});throw new Ko({docsPath:"/docs/actions/wallet/sendTransactionSync",type:k?.type})}catch(B){if(B instanceof Ko)throw B;if(O&&!(B instanceof hd))k?.nonceManager?.reset(O);throw lc(B,{...t,account:k,chain:t.chain||void 0})}}async function _p(e,t){return Yo.internal(e,Px,"sendTransactionSync",t)}async function sI(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:i}=nn(e,{token:n}),s=Ex(r,i),a=await Ks.inner(_p,e,{...t,throwOnReceiptRevert:o}),{args:c}=Ks.extractEvent(a.logs);return{...c,...s===void 0?{}:{decimals:s,formatted:yp(c.value,s)},receipt:a}}en();async function Tp(e,t){let{account:r,decimals:n,spender:o,token:i,...s}=t,[a,{decimals:c}]=await Promise.all([Tt(e,{...s,...Tp.call(e,{account:r,spender:o,token:i})}),xp(e,{decimals:n,token:i})]);return bp(a,c)}(function(e){function t(r,n){return ji({address:nn(r,n).address,abi:ar,functionName:"allowance",args:[n.account,n.spender]})}e.call=t})(Tp||(Tp={}));en();async function vp(e,t){let{account:r=e.account,decimals:n,token:o,...i}=t;if(!r)throw new Ar;let s=je(r).address,[a,{decimals:c}]=await Promise.all([Tt(e,{...i,...vp.call(e,{account:s,token:o})}),xp(e,{decimals:n,token:o})]);return bp(a,c)}(function(e){function t(r,n){let o=n.account??r.account;if(!o)throw new Ar;let i=je(o).address;return ji({address:nn(r,n).address,abi:ar,functionName:"balanceOf",args:[i]})}e.call=t})(vp||(vp={}));en();async function aI(e,t){let{token:r,...n}=t,{address:o}=nn(e,{token:r}),i=oI(e,r),[s,a,c]=await Promise.all([i?.decimals??Tt(e,{...n,abi:ar,address:o,functionName:"decimals"}),i?.name??Tt(e,{...n,abi:ar,address:o,functionName:"name"}),i?.symbol??Tt(e,{...n,abi:ar,address:o,functionName:"symbol"})]);return{decimals:s,name:a,symbol:c}}en();async function Ep(e,t){let{decimals:r,token:n,...o}=t,[i,{decimals:s}]=await Promise.all([Tt(e,{...o,...Ep.call(e,{token:n})}),xp(e,{decimals:r,token:n})]);return bp(i,s)}(function(e){function t(r,n){return ji({address:nn(r,n).address,abi:ar,args:[],functionName:"totalSupply"})}e.call=t})(Ep||(Ep={}));en();async function Ys(e,t){return Ys.inner(Yo,e,t)}(function(e){async function t(s,a,c){return await s(a,{...c,...e.call(a,c)})}e.inner=t;function r(s,a){return ji(Fpe(s,a))}e.call=r;async function n(s,a){return rp(s,{...wp(a),...e.call(s,a)})}e.estimateGas=n;async function o(s,a){return fp(s,{...wp(a),...e.call(s,a)})}e.simulate=o;function i(s){let[a]=Ui({abi:ar,logs:s,eventName:"Transfer",strict:!0});if(!a)throw Error("`Transfer` event not found.");return a}e.extractEvent=i})(Ys||(Ys={}));function Fpe(e,t){let{amount:r,from:n,to:o,token:i}=t,{address:s,decimals:a}=nn(e,{token:i}),c=vx(r,a);if(n)return{abi:ar,address:s,args:[n,o,c],functionName:"transferFrom"};return{abi:ar,address:s,args:[o,c],functionName:"transfer"}}async function cI(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:i}=nn(e,{token:n}),s=Ex(r,i),a=await Ys.inner(_p,e,{...t,throwOnReceiptRevert:o}),{args:c}=Ys.extractEvent(a.logs);return{...c,...s===void 0?{}:{decimals:s,formatted:yp(c.value,s)},receipt:a}}function qU(e){return{call:(t)=>Un(e,t),createAccessList:(t)=>v9(e,t),createBlockFilter:()=>E9(e),createContractEventFilter:(t)=>Vb(e,t),createEventFilter:(t)=>Zb(e,t),createPendingTransactionFilter:()=>Wb(e),estimateContractGas:(t)=>rp(e,t),estimateGas:(t)=>tp(e,t),getBalance:(t)=>rF(e,t),getBlobBaseFee:()=>nF(e),getBlock:(t)=>Pr(e,t),getBlockNumber:(t)=>Po(e,t),getBlockReceipts:(t)=>sF(e,t),getBlockTransactionCount:(t)=>aF(e,t),getBytecode:(t)=>ku(e,t),getChainId:()=>ln(e),getCode:(t)=>ku(e,t),getContractEvents:(t)=>rx(e,t),getDelegation:(t)=>uF(e,t),getEip712Domain:(t)=>lF(e,t),getEnsAddress:(t)=>h9(e,t),getEnsAvatar:(t)=>S9(e,t),getEnsName:(t)=>_9(e,t),getEnsResolver:(t)=>T9(e,t),getEnsText:(t)=>Gb(e,t),getFeeHistory:(t)=>pF(e,t),estimateFeesPerGas:(t)=>H9(e,t),getFilterChanges:(t)=>dc(e,t),getFilterLogs:(t)=>fF(e,t),getGasPrice:()=>Yd(e),getLogs:(t)=>op(e,t),getProof:(t)=>hF(e,t),estimateMaxPriorityFeePerGas:(t)=>q9(e,t),fillTransaction:(t)=>ep(e,t),getRawTransaction:(t)=>gF(e,t),getStorageAt:(t)=>yF(e,t),getTransaction:(t)=>ip(e,t),getTransactionConfirmations:(t)=>bF(e,t),getTransactionCount:(t)=>Jd(e,t),getTransactionReceipt:(t)=>sp(e,t),multicall:(t)=>xF(e,t),prepareTransactionRequest:(t)=>Fi(e,t),readContract:(t)=>Tt(e,t),sendRawTransaction:(t)=>gp(e,t),sendRawTransactionSync:(t)=>Sp(e,t),simulate:(t)=>ap(e,t),simulateBlocks:(t)=>ap(e,t),simulateCalls:(t)=>cU(e,t),simulateContract:(t)=>fp(e,t),verifyHash:(t)=>yc(e,t),verifyMessage:(t)=>AU(e,t),verifySiweMessage:(t)=>UU(e,t),verifyTypedData:(t)=>MU(e,t),uninstallFilter:(t)=>hc(e,t),waitForTransactionReceipt:(t)=>Tx(e,t),watchBlockHeaders:(t)=>NU(e,t),watchBlocks:(t)=>$U(e,t),watchBlockNumber:(t)=>_x(e,t),watchContractEvent:(t)=>zU(e,t),watchEvent:(t)=>LU(e,t),watchPendingTransactions:(t)=>BU(e,t),token:Upe(e)}}function Upe(e){return{getAllowance:Ii(e,Tp),getBalance:Ii(e,vp),getMetadata:Ii(e,aI),getTotalSupply:Ii(e,Ep)}}function uI(e){let{key:t="public",name:r="Public Client"}=e;return V0({...e,key:t,name:r,type:"publicClient"}).extend(qU)}Ke();async function HU(e,{chain:t}){let{id:r,name:n,nativeCurrency:o,rpcUrls:i,blockExplorers:s}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:Z(r),chainName:n,nativeCurrency:o,rpcUrls:i.default.http,blockExplorerUrls:s?Object.values(s).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}Fb();function GU(e,t){let{abi:r,args:n,bytecode:o,...i}=t,s=vu({abi:r,args:n,bytecode:o});return bc(e,{...i,...i.authorizationList?{to:null}:{},data:s})}Oi();async function VU(e){if(e.account?.type==="local")return[e.account.address];return(await e.request({method:"eth_accounts"},{dedupe:!0})).map((r)=>As(r))}Is();Rr();et();Dd();Bn();Rr();Ke();var lI="0x5792579257925792579257925792579257925792579257925792579257925792",dI=Z(0,{size:32});async function Ax(e,t){let{account:r=e.account,chain:n=e.chain,experimental_fallback:o,experimental_fallbackDelay:i=32,forceAtomic:s=!1,id:a,version:c="2.0.0"}=t,l=r?je(r):null,d=t.capabilities;if(e.dataSuffix&&!t.capabilities?.dataSuffix)if(typeof e.dataSuffix==="string")d={...t.capabilities,dataSuffix:{value:e.dataSuffix,optional:!0}};else d={...t.capabilities,dataSuffix:{value:e.dataSuffix.value,...e.dataSuffix.required?{}:{optional:!0}}};let f=t.calls.map((h)=>{let g=h,x=g.abi?Dt({abi:g.abi,functionName:g.functionName,args:g.args}):g.data;return{data:g.dataSuffix&&x?Or([x,g.dataSuffix]):x,to:g.to,value:g.value?Z(g.value):void 0}});try{let h=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:s,calls:f,capabilities:d,chainId:Z(n.id),from:l?.address,id:a,version:c}]},{retryCount:0});if(typeof h==="string")return{id:h};return h}catch(h){let g=h;if(o&&(g.name==="MethodNotFoundRpcError"||g.name==="MethodNotSupportedRpcError"||g.name==="UnknownRpcError"||g.details.toLowerCase().includes("does not exist / is not available")||g.details.toLowerCase().includes("missing or invalid. request()")||g.details.toLowerCase().includes("did not match any variant of untagged enum")||g.details.toLowerCase().includes("account upgraded to unsupported contract")||g.details.toLowerCase().includes("eip-7702 not supported")||g.details.toLowerCase().includes("unsupported wc_ method")||g.details.toLowerCase().includes("feature toggled misconfigured")||g.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(d){if(Object.values(d).some((_)=>!_.optional))throw new nc(new N("non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.",{details:"non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`."}))}if(s&&f.length>1)throw new oc(new N("`forceAtomic` is not supported on fallback to `eth_sendTransaction`.",{details:"`forceAtomic` is not supported on fallback to `eth_sendTransaction`."}));let x=[];for(let S of f){try{let _=await bc(e,{account:l,chain:n,data:S.data,to:S.to,value:S.value?xr(S.value):void 0});x.push({status:"fulfilled",value:_})}catch(_){x.push({reason:_,status:"rejected"})}if(i>0)await new Promise((_)=>setTimeout(_,i))}if(x.every((S)=>S.status==="rejected"))throw x[0].reason;let w=x.map((S)=>{if(S.status==="fulfilled")return S.value;return dI});return{id:Or([...w,Z(n.id,{size:32}),lI])}}throw lc(h,{...t,account:l,chain:t.chain})}}async function Ix(e,t){async function r(d){if(d.endsWith(lI.slice(2))){let h=tn(ub(d,-64,-32)),g=ub(d,0,-64).slice(2).match(/.{1,64}/g),x=await Promise.all(g.map((S)=>dI.slice(2)!==S?e.request({method:"eth_getTransactionReceipt",params:[`0x${S}`]},{dedupe:!0}):void 0)),w=(()=>{if(x.some((S)=>S===null))return 100;if(x.every((S)=>S?.status==="0x1"))return 200;if(x.every((S)=>S?.status==="0x0"))return 500;return 600})();return{atomic:!1,chainId:ur(h),receipts:x.filter(Boolean),status:w,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[d]})}let{atomic:n=!1,chainId:o,receipts:i,version:s="2.0.0",...a}=await r(t.id),[c,l]=(()=>{let d=a.status;if(d>=100&&d<200)return["pending",d];if(d>=200&&d<300)return["success",d];if(d>=300&&d<700)return["failure",d];if(d==="CONFIRMED")return["success",200];if(d==="PENDING")return["pending",100];return[void 0,d]})();return{...a,atomic:n,chainId:o?ur(o):void 0,receipts:i?.map((d)=>({...d,blockNumber:xr(d.blockNumber),gasUsed:xr(d.gasUsed),status:SA[d.status]}))??[],statusCode:l,status:c,version:s}}Ke();async function ZU(e,t={}){let{account:r=e.account,chainId:n}=t,o=r?je(r):void 0,i=n?[o?.address,[Z(n)]]:[o?.address],s=await e.request({method:"wallet_getCapabilities",params:i}),a={};for(let[c,l]of Object.entries(s)){a[Number(c)]={};for(let[d,f]of Object.entries(l)){if(d==="addSubAccount")d="unstable_addSubAccount";a[Number(c)][d]=f}}return typeof n==="number"?a[n]:a}async function WU(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}Fs();async function kx(e,t){let{account:r=e.account,chainId:n,nonce:o}=t;if(!r)throw new Ar({docsPath:"/docs/eip7702/prepareAuthorization"});let i=je(r),s=(()=>{if(!t.executor)return;if(t.executor==="self")return t.executor;return je(t.executor)})(),a={address:t.contractAddress??t.address,chainId:n,nonce:o};if(typeof a.chainId>"u")a.chainId=e.chain?.id??await re(e,ln,"getChainId")({});if(typeof a.nonce>"u"){if(a.nonce=await re(e,Jd,"getTransactionCount")({address:i.address,blockTag:"pending"}),s==="self"||s?.address&&Ur(s.address,i.address))a.nonce+=1}return a}Oi();async function KU(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map((r)=>qo(r))}async function YU(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}et();et();class pI extends N{constructor(e){super(`Call bundle failed with status: ${e.statusCode}`,{name:"BundleFailedError"});Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=e}}async function Rx(e,t){let{id:r,pollingInterval:n=e.pollingInterval,status:o=({statusCode:w})=>w===200||w>=300,retryCount:i=4,retryDelay:s=({count:w})=>~~(1<<w)*200,timeout:a=60000,throwOnFailure:c=!1}=t,l=at(["waitForCallsStatus",e.uid,r]),{promise:d,resolve:f,reject:h}=Hd(),g,x=Gr(l,{resolve:f,reject:h},(w)=>{let S=Ao(async()=>{let _=(A)=>{clearTimeout(g),S(),A(),x()};try{let A=await Nu(async()=>{let T=await re(e,Ix,"getCallsStatus")({id:r});if(c&&T.status==="failure")throw new pI(T);return T},{retryCount:i,delay:s});if(!o(A))return;_(()=>w.resolve(A))}catch(A){_(()=>w.reject(A))}},{interval:n,emitOnBegin:!0});return S});return g=a?setTimeout(()=>{x(),clearTimeout(g),h(new JU({id:r}))},a):void 0,await d}class JU extends N{constructor({id:e}){super(`Timed out while waiting for call bundle with id "${e}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}async function QU(e,t){let{chain:r=e.chain}=t,n=t.timeout??Math.max((r?.blockTime??0)*3,5000),o=await re(e,Ax,"sendCalls")(t);return await re(e,Rx,"waitForCallsStatus")({...t,id:o.id,timeout:n})}async function XU(e,t){let{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]});return}async function ej(e,t){let{account:r=e.account}=t;if(!r)throw new Ar({docsPath:"/docs/eip7702/signAuthorization"});let n=je(r);if(!n.signAuthorization)throw new Ko({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});let o=await kx(e,t);return n.signAuthorization(o)}Ke();async function tj(e,{account:t=e.account,message:r}){if(!t)throw new Ar({docsPath:"/docs/actions/wallet/signMessage"});let n=je(t);if(n.signMessage)return n.signMessage({message:r});let o=(()=>{if(typeof r==="string")return Ja(r);if(r.raw instanceof Uint8Array)return lr(r.raw);return r.raw})();return e.request({method:"personal_sign",params:[o,n.address]},{retryCount:0})}Ke();qs();Bi();async function rj(e,t){let{account:r=e.account,chain:n=e.chain,...o}=t;if(!r)throw new Ar({docsPath:"/docs/actions/wallet/signTransaction"});let i=je(r);jr({account:i,...t});let s=await re(e,ln,"getChainId")({});if(n!==null)hp({currentChainId:s,chain:n});let c=(n?.formatters||e.chain?.formatters)?.transactionRequest?.format||un;if(i.signTransaction)return i.signTransaction({...o,account:i,chainId:s},{serializer:e.chain?.serializers?.transaction});return await e.request({method:"eth_signTransaction",params:[{...c({...o,account:i},"signTransaction"),chainId:Z(s),from:i.address}]},{retryCount:0})}async function nj(e,t){let{account:r=e.account,domain:n,message:o,primaryType:i}=t;if(!r)throw new Ar({docsPath:"/docs/actions/wallet/signTypedData"});let s=je(r),a={EIP712Domain:xx({domain:n}),...t.types};if(bx({domain:n,message:o,primaryType:i,types:a}),s.signTypedData)return s.signTypedData({domain:n,message:o,primaryType:i,types:a});let c=IU({domain:n,message:o,primaryType:i,types:a});return e.request({method:"eth_signTypedData_v4",params:[s.address,c]},{retryCount:0})}Ke();async function oj(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:Z(t)}]},{retryCount:0})}async function ij(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}function sj(e){return{addChain:(t)=>HU(e,t),deployContract:(t)=>GU(e,t),fillTransaction:(t)=>ep(e,t),getAddresses:()=>VU(e),getCallsStatus:(t)=>Ix(e,t),getCapabilities:(t)=>ZU(e,t),getChainId:()=>ln(e),getPermissions:()=>WU(e),prepareAuthorization:(t)=>kx(e,t),prepareTransactionRequest:(t)=>Fi(e,t),requestAddresses:()=>KU(e),requestPermissions:(t)=>YU(e,t),sendCalls:(t)=>Ax(e,t),sendCallsSync:(t)=>QU(e,t),sendRawTransaction:(t)=>gp(e,t),sendRawTransactionSync:(t)=>Sp(e,t),sendTransaction:(t)=>bc(e,t),sendTransactionSync:(t)=>Px(e,t),showCallsStatus:(t)=>XU(e,t),signAuthorization:(t)=>ej(e,t),signMessage:(t)=>tj(e,t),signTransaction:(t)=>rj(e,t),signTypedData:(t)=>nj(e,t),switchChain:(t)=>oj(e,t),waitForCallsStatus:(t)=>Rx(e,t),watchAsset:(t)=>ij(e,t),writeContract:(t)=>Yo(e,t),writeContractSync:(t)=>_p(e,t),token:{approve:Ii(e,Ks),approveSync:Ii(e,sI),transfer:Ii(e,Ys),transferSync:Ii(e,cI)}}}function fI(e){let{key:t="wallet",name:r="Wallet Client",transport:n}=e;return V0({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(sj)}wu();et();class mI extends N{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}jb();wu();function aj(e,{errorInstance:t=Error("timed out"),timeout:r,signal:n}){return new Promise((o,i)=>{(async()=>{let s,a=new AbortController;try{if(r>0)s=setTimeout(()=>{if(n)a.abort();else i(t)},r);o(await e({signal:a?.signal||null}))}catch(c){if(a?.signal.aborted&&Dn(c)){i(t);return}i(c)}finally{clearTimeout(s)}})()})}function jpe(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var hI=jpe();var qpe=10485760;function cj(e,t={}){let{url:r,headers:n}=Gpe(e);return{async request(o){let{body:i,fetchFn:s=t.fetchFn??fetch,maxResponseBodySize:a=t.maxResponseBodySize??qpe,onRequest:c=t.onRequest,onResponse:l=t.onResponse,timeout:d=t.timeout??1e4}=o,f={...t.fetchOptions??{},...o.fetchOptions??{}},{headers:h,method:g,signal:x}=f;try{let w=await aj(async({signal:A})=>{let T={...f,body:Array.isArray(i)?at(i.map((O)=>({jsonrpc:"2.0",id:O.id??hI.take(),...O}))):at({jsonrpc:"2.0",id:i.id??hI.take(),...i}),headers:{...n,"Content-Type":"application/json",...h},method:g||"POST",signal:x||(d>0?A:null)},v=new Request(r,T),E=await c?.(v,T)??{...T,url:r};return await s(E.url??r,E)},{errorInstance:new Cb({body:i,url:r}),timeout:d,signal:!0});if(l)await l(w);let S,_=await Hpe(w,{maxResponseBodySize:a});if(w.headers.get("Content-Type")?.startsWith("application/json"))S=JSON.parse(_);else{S=_;try{S=JSON.parse(S||"{}")}catch(A){if(w.ok)throw A;S={error:S}}}if(!w.ok){if(typeof S.error?.code==="number"&&typeof S.error?.message==="string")return S;throw new Go({body:i,details:at(S.error)||w.statusText,headers:w.headers,status:w.status,url:r})}return S}catch(w){if(x?.aborted)throw rn(x);if(Dn(w))throw w;if(w instanceof Go)throw w;if(w instanceof xd)throw w;if(w instanceof Cb)throw w;throw new Go({body:i,cause:w,url:r})}}}}async function Hpe(e,{maxResponseBodySize:t}){if(t===!1)return e.text();let r=e.headers.get("Content-Length");if(r){let a=Number(r);if(a>t)throw new xd({maxSize:t,size:a})}if(!e.body){let a=await e.text(),c=new TextEncoder().encode(a).length;if(c>t)throw new xd({maxSize:t,size:c});return a}let n=e.body.getReader(),o=new TextDecoder,i="",s=0;try{while(!0){let{done:a,value:c}=await n.read();if(a)break;if(s+=c.byteLength,s>t)throw await n.cancel(),new xd({maxSize:t,size:s});i+=o.decode(c,{stream:!0})}return i+=o.decode(),i}finally{n.releaseLock()}}function Gpe(e){try{let t=new URL(e),r=(()=>{if(t.username){let n=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;return t.username="",t.password="",{url:t.toString(),headers:{Authorization:`Basic ${btoa(n)}`}}}return})();return{url:t.toString(),...r}}catch{return{url:e}}}et();wu();Dd();pu();var Cx=new Jn(8192);function uj(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(Cx.get(r))return Cx.get(r);let n=e().finally(()=>Cx.delete(r));return Cx.set(r,n),n}function lj(e,t={}){return async(r,n={})=>{let{dedupe:o=!1,methods:i,retryDelay:s=150,retryCount:a=3,signal:c,uid:l}={...t,...n},{method:d}=r;if(i?.exclude?.includes(d))throw new rc(Error("method not supported"),{method:d});if(i?.include&&!i.include.includes(d))throw new rc(Error("method not supported"),{method:d});if(c?.aborted)throw rn(c);let f=o?Zpe(`${l}.${at(r)}`):void 0;return uj(()=>Nu(async()=>{try{return await e(r,c?{signal:c}:void 0)}catch(h){if(c?.aborted)throw rn(c);if(Dn(h))throw h;let g=h;switch(g.code){case wd.code:throw new wd(g);case Sd.code:throw new Sd(g);case _d.code:throw new _d(g,{method:r.method});case Td.code:throw new Td(g);case Ls.code:throw new Ls(g);case _o.code:throw new _o(g);case vd.code:throw new vd(g);case Ed.code:throw new Ed(g);case Pd.code:throw new Pd(g);case rc.code:throw new rc(g,{method:r.method});case Su.code:throw new Su(g);case Ad.code:throw new Ad(g);case _u.code:throw new _u(g);case Id.code:throw new Id(g);case kd.code:throw new kd(g);case Rd.code:throw new Rd(g);case Cd.code:throw new Cd(g);case Od.code:throw new Od(g);case nc.code:throw new nc(g);case Md.code:throw new Md(g);case Nd.code:throw new Nd(g);case $d.code:throw new $d(g);case zd.code:throw new zd(g);case Ld.code:throw new Ld(g);case oc.code:throw new oc(g);case 5000:throw new _u(g);case Bd.code:throw new Bd(g);default:if(h instanceof N)throw h;throw new RP(g)}}},{delay:({count:h,error:g})=>{if(g&&g instanceof Go){let x=g?.headers?.get("Retry-After");if(x?.match(/\d/))return Number.parseInt(x,10)*1000}return~~(1<<h)*s},retryCount:a,signal:c,shouldRetry:({error:h})=>Vpe(h)}),{enabled:o,id:f})}}function Vpe(e){if(Dn(e))return!1;if("code"in e&&typeof e.code==="number"){if(e.code===-1)return!0;if(e.code===Su.code)return!0;if(e.code===Ls.code)return!0;if(e.code===429)return!0;return!1}if(e instanceof Go&&e.status){if(e.status===403)return!0;if(e.status===408)return!0;if(e.status===413)return!0;if(e.status===429)return!0;if(e.status===500)return!0;if(e.status===502)return!0;if(e.status===503)return!0;if(e.status===504)return!0;return!1}return!0}function Zpe(e,t=0){let r=3735928559^t,n=1103547991^t;for(let o=0;o<e.length;o++){let i=e.charCodeAt(o);r=Math.imul(r^i,2654435761),n=Math.imul(n^i,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>16,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>16,3266489909),(4294967296*(2097151&n)+(r>>>0)).toString(36)}function dj({key:e,methods:t,name:r,request:n,retryCount:o=3,retryDelay:i=150,timeout:s,type:a},c){let l=G0();return{config:{key:e,methods:t,name:r,request:n,retryCount:o,retryDelay:i,timeout:s,type:a},request:lj(n,{methods:t,retryCount:o,retryDelay:i,uid:l}),value:c}}var Wpe=0,pj=new WeakMap;function Kpe(e){if(!e)return"default";let t=pj.get(e);if(t!==void 0)return t;let r=Wpe++;return pj.set(e,r),r}function gh(e,t={}){let{batch:r,fetchFn:n,fetchOptions:o,key:i="http",maxResponseBodySize:s,methods:a,name:c="HTTP JSON-RPC",onFetchRequest:l,onFetchResponse:d,retryDelay:f,raw:h}=t;return({chain:g,retryCount:x,timeout:w})=>{let{batchSize:S=1000,wait:_=0}=typeof r==="object"?r:{},A=t.retryCount??x,T=w??t.timeout??1e4,v=e||g?.rpcUrls.default.http[0];if(!v)throw new mI;let E=cj(v,{fetchFn:n,fetchOptions:o,maxResponseBodySize:s,onRequest:l,onResponse:d,timeout:T});return dj({key:i,methods:a,name:c,async request({method:k,params:O},B){let G={method:k,params:O},M=B?.signal?{signal:B.signal}:void 0,{schedule:J}=Gd({id:`${v}.${Kpe(B?.signal)}`,wait:_,shouldSplitBatch(j){return j.length>S},fn:(j)=>E.request({body:j,fetchOptions:M}),sort:(j,se)=>j.id-se.id}),W=async(j)=>r?J(j):[await E.request({body:j,fetchOptions:M})],[{error:he,result:ge}]=await W(G);if(h)return{error:he,result:ge};if(he)throw new xu({body:G,error:he,url:v});return ge},retryCount:A,retryDelay:f,timeout:T,type:"http"},{fetchOptions:o,url:v})}}en();function Ox(e){let t={formatters:void 0,fees:void 0,serializers:void 0,...e};function r(n){return(o)=>{let i=typeof o==="function"?o(n):o,s={...n,...i};return Object.assign(s,{extend:r(s)})}}return Object.assign(t,{extend:r(t)})}var yh=Ox({id:1329,name:"Sei Network",nativeCurrency:{name:"Sei",symbol:"SEI",decimals:18},rpcUrls:{default:{http:["https://evm-rpc.sei-apis.com/"],webSocket:["wss://evm-ws.sei-apis.com/"]}},blockExplorers:{default:{name:"Seiscan",url:"https://seiscan.io",apiUrl:"https://api.etherscan.io/v2/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11"}}});var bh=Ox({id:1328,name:"Sei Testnet",nativeCurrency:{name:"Sei",symbol:"SEI",decimals:18},rpcUrls:{default:{http:["https://evm-rpc-testnet.sei-apis.com"],webSocket:["wss://evm-ws-testnet.sei-apis.com"]}},blockExplorers:{default:{name:"Seiscan",url:"https://testnet.seiscan.io",apiUrl:"https://api.etherscan.io/v2/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:98697651}},testnet:!0});var Ype=y({applicationId:p().uuid(),enrolled:oe(),payoutAddress:p().nullable().optional(),buildercodesEnabled:oe(),buildercodesBudgetBps:I().int().min(0).max(1e4),builderFeeEnabled:oe(),builderFeeBps:I().int().min(0).max(100),builderFeeCapBps:I().int().min(0).max(100),changesRemaining:I().int().min(0).max(2),nextChangeAllowedAt:p().nullable().optional()}),gI=y({bps:I().int().min(0).max(100)}),Jpe=y({builderFeeBps:I().int().min(0).max(100),previousBuilderFeeBps:I().int().min(0).max(100),changesRemaining:I().int().min(0).max(2),nextChangeAllowedAt:p().nullable().optional()}),fj=z(["BUILDER","ADMIN"]),mj=y({actorType:fj,actor:p(),oldBps:I().int().min(0).max(100),newBps:I().int().min(0).max(100),createdAt:p()}),yI=y({pageSize:I().int().min(1).max(100).optional(),pageToken:p().optional()}),Qpe=y({changes:ie(mj),nextPageToken:p()}),Mx=z(["REVENUE_SHARE","BUILDER_FEE"]),bI=y({page:Qe().optional(),pageSize:I().int().min(1).max(1000).optional(),pageToken:p().optional(),kind:Mx.optional()}),hj=y({tradeId:p().uuid(),payoutAddress:p(),token:p(),amount:p(),appliedBps:I().int(),createdAt:p(),kind:Mx.optional()}),Xpe=y({payouts:ie(hj),total:I().int().nonnegative(),pageSize:I().int().positive(),totalPages:I().int().nonnegative(),nextPageToken:p()}),gj=y({token:p(),totalAmount:p(),payoutCount:I().int().nonnegative(),lastCreditedAt:p()}),yj=y({token:p(),kind:Mx,totalAmount:p(),payoutCount:I().int().nonnegative(),lastCreditedAt:p()}),efe=y({totalPayouts:I().int().nonnegative(),lastCreditedAt:p().nullable().optional(),byToken:ie(gj),byTokenAndKind:ie(yj).optional()}),bj=y({token:p(),available:p()}),tfe=y({balances:ie(bj)}),xI=y({token:p().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:p().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),rfe=y({payoutBalance:p(),tradingBalance:p()});function Jo(){return p()}var wI=y({walletAddress:p(),handle:p().nullish(),display:p()}),SI=y({leader:wI,status:Jo(),shareBps:I(),bio:p(),minAllocation:p().nullish(),registeredAt:p()}),_I=y({followerCount:I(),allocated:p(),aumEquity:p().nullish()}),TI=y({window:Jo(),pnl:p(),roiPct:p().nullish(),maxDrawdownPct:p().nullish(),winRatePct:p().nullish(),closedTrades:I()}),nfe=y({profile:SI,followSummary:_I,stats:ie(TI)}),xj=y({profile:SI,followSummary:_I,stats:TI}),ofe=y({leaders:ie(xj),nextPageToken:p(),asOf:p()}),ife=y({created:oe(),status:Jo(),shareBps:I()}),wj=y({walletAddress:p(),display:p(),status:Jo(),allocation:p(),startedAt:p()}),sfe=y({followers:ie(wj),nextPageToken:p()}),Sj=y({tradingPairId:p(),positionSide:p(),action:Jo(),size:p().nullish(),exitPrice:p().nullish(),entryPrice:p().nullish(),realizedPnl:p().nullish(),netRealizedPnl:p().nullish(),realizedRoe:p().nullish(),closedAt:p()}),afe=y({closedTrades:ie(Sj),nextPageToken:p()}),vI=y({tradingPairId:p(),side:p(),size:p(),entryPrice:p(),markPrice:p().nullish(),unrealizedPnl:p().nullish(),leverage:p().nullish(),marginMode:p()}),cfe=y({positions:ie(vI)}),EI=y({followId:p(),leader:wI,status:Jo(),marginModePolicy:Jo(),sizingMode:Jo(),sizingParam:p().nullish(),leverageMode:Jo(),fixedLeverage:p().nullish(),allocation:p(),slPct:p().nullish(),copyExisting:oe(),tradingPairIds:ie(p()),consecutiveSkips:I(),copyRiskBucketId:p(),startedAt:p(),stoppedAt:p().nullish(),stopReason:Jo().nullish()}),ufe=y({follows:ie(EI),nextPageToken:p()}),_j=y({tradingPairId:p(),reason:Jo(),requestedQuantity:p(),skippedAt:p()}),lfe=y({follow:EI,recentSkips:ie(_j),copyAccountEquity:p().nullish()}),dfe=y({positions:ie(vI)}),pfe=y({followId:p(),copyRiskBucketId:p(),created:oe()}),ffe=y({estimatedMargin:p(),estimatedFee:p(),copiedPositions:I(),skippedPositions:I(),truncated:oe()}),mfe=y({followId:p()}),Tj=y({followId:p(),closeOrdersPlaced:I(),positionsNotClosed:I()}),vj=y({followId:p(),reason:p()}),hfe=y({follows:ie(Tj),stoppingFollowIds:ie(p()),failedFollows:ie(vj)}),gfe=y({followId:p(),tradingPairId:p(),riskBucketId:p(),positionId:p(),positionMargin:p(),copyAccountAvailable:p()});var PI=y({tradingPairId:p().trim().min(1,"Trading pair ID is required and cannot be empty"),side:z(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:p().trim().min(1,"Price is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Price must be a valid number").refine((e)=>Number(e)>0,"Price must be greater than 0"),quantity:p().trim().min(1,"Quantity is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Quantity must be a valid number").refine((e)=>Number(e)>0,"Quantity must be greater than 0"),orderType:z(["LIMIT","MARKET"]).optional(),slippageToleranceBps:I().int().min(0,"Slippage tolerance must be between 0 and 1000 bps").max(1000,"Slippage tolerance must be between 0 and 1000 bps").optional()}).superRefine((e,t)=>{if(e.slippageToleranceBps!==void 0&&e.orderType!=="MARKET")t.addIssue({code:wa.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),yfe=y({applicationName:p().nullable().optional(),applicationTakerFee:p(),applicationTakerFeeBps:I(),buyOrderLockAmount:p().nullable().optional(),makerTotalReceipt:p(),monacoMakerRebate:p(),monacoMakerRebateBps:I(),monacoMakerRebateBpsExact:p(),monacoTakerFee:p(),monacoTakerFeeBps:I(),monacoTakerFeeBpsExact:p(),notional:p(),takerTotalPayment:p(),totalTakerFees:p(),maxQuantity:p().nullable(),maxQuantityRaw:p().nullable(),slippageToleranceBps:I().nullable()}),AI=y({tradingPairId:p().trim().min(1,"Trading pair ID is required and cannot be empty")}),Ej=y({tierLevel:I().int(),minVolumeThreshold:p(),makerFeeBps:p(),takerFeeBps:p()}),bfe=y({currentTierLevel:I().int(),weightedVolume14d:p(),spotVolume14d:p(),perpVolume14d:p(),volumeToNextTier:p().nullable().optional(),nextTierLevel:I().int().nullable().optional(),feeSchedule:ie(Ej)});var Pj=y({token:p(),available:p()}),xfe=y({balances:ie(Pj)}),wfe=y({code:p(),createdAt:p(),customCode:p(),isCustom:oe(),display:p()}),Aj=z(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),Sfe=y({available:oe(),reason:Ff((e)=>e===""||e===null?void 0:e,Aj.optional())}),II=y({code:p().trim().min(1,"code is required").regex(/^[A-Za-z][A-Za-z0-9_]{4,19}$/,"code must start with a letter and be 5–20 chars of letters, digits, or underscores")}),_fe=y({code:p()}),kI=y({token:p().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:p().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),Tfe=y({rewardsBalance:p(),tradingBalance:p()}),Ij=y({source:p(),sourceDisplay:p(),level:I(),amount:p(),token:p(),rateApplied:p(),createdAt:p()}),kj=y({wallet:p(),display:p(),level:I()}),vfe=y({referrer:p(),referrerDisplay:p(),totalEarned:p(),rewards:ie(Ij),upline:ie(kj)}),Rj=y({source:p(),sourceDisplay:p(),level:I(),totalEarned:p(),token:p()}),Cj=y({wallet:p(),display:p(),referredAt:p(),totalEarned:p()}),Oj=y({level:I(),earned:p()}),Mj=y({totalEarned:p(),level1Earned:p(),level2Earned:p(),level3Earned:p(),byLevel:ie(Oj)}),RI=y({pageSize:I().int().min(1).max(500).optional(),pageToken:p().optional()}),Efe=y({earningsBySource:ie(Rj),directReferees:ie(Cj),summary:Mj,nextPageToken:p()}),CI=y({parent:p().optional(),pageSize:I().int().min(1).max(200).optional(),pageToken:p().optional()}),Nj=y({wallet:p(),display:p(),level:I(),parent:p(),referredAt:p(),refereeCount:I(),totalEarned:p()}),Pfe=y({parent:p(),parentLevel:I(),nodes:ie(Nj),nextPageToken:p()});var Nx=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var Pp=z(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),xh=z(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),Bx=z(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),wh=z(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),$j=z(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),OI=z(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),$u=z(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"],{message:'Self-trade prevention mode must be "CANCEL_MAKER", "CANCEL_TAKER", "CANCEL_BOTH", or "SKIP"'}),Ap=z(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),Ve=p().trim().min(1,"Value cannot be empty").regex(/^\d+(\.\d+)?$/,"Value must be a positive decimal number (e.g., '1.5', '100')").refine((e)=>Number.parseFloat(e)>0,{message:"Value must be greater than 0"}),be=U5({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),Js=wl.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),zj=I().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),Ip=I().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),Lj=I().int().min(0,"Slippage tolerance must be at least 0 bps").max(1000,"Slippage tolerance cannot exceed 1000 bps"),Afe=I().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),$x=y({triggerPrice:Ve,orderType:Ap,limitPrice:Ve.optional(),quantity:Ve.optional(),closePosition:oe().optional(),timeInForce:OI.optional(),slippageToleranceBps:Ip.optional(),expiresAt:Js.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT parent TP/SL",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET parent TP/SL",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),Ife=I().int("trailBps must be an integer number of basis points").min(10,"trailBps must be at least 10 bps").max(2000,"trailBps cannot exceed 2000 bps"),MI=y({trailBps:Ife,activationPrice:Ve.optional(),quantity:Ve.optional(),closePosition:oe().optional(),slippageToleranceBps:Ip.optional(),expiresAt:Js.optional()}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),Bj=MI,zx=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0||e?.trailingStop!==void 0,NI=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),$I=p().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/,"idempotencyKey must contain only letters, digits, or . _ : -"),Dj=y({tradingPairId:be,side:Pp,quantity:Ve,price:Ve,options:y({idempotencyKey:$I.optional(),tradingMode:xh.optional(),useMasterBalance:oe().optional(),expirationDate:Js.optional(),timeInForce:$j.optional(),marginAccountId:be.optional(),marginMode:Bx.optional(),riskBucketId:be.optional(),riskBucketCollateral:Ve.optional(),strategyKey:p().min(1).max(128).optional(),positionSide:wh.optional(),leverage:Ve.optional(),reduceOnly:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:$u.optional(),takeProfit:$x.optional(),stopLoss:$x.optional(),trailingStop:Bj.optional()}).optional()}).refine((e)=>NI(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!zx(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss/trailingStop are only supported for MARGIN orders",path:["options"]}).refine((e)=>!zx(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss/trailingStop cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}).refine((e)=>e.options?.postOnly!==!0||e.options?.timeInForce===void 0||e.options.timeInForce!=="IOC"&&e.options.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["options","timeInForce"]}),Fj=y({tradingPairId:be,side:Pp,quantity:Ve,options:y({idempotencyKey:$I.optional(),tradingMode:xh.optional(),slippageTolerance:zj,marginAccountId:be.optional(),marginMode:Bx.optional(),riskBucketId:be.optional(),riskBucketCollateral:Ve.optional(),strategyKey:p().min(1).max(128).optional(),positionSide:wh.optional(),leverage:Ve.optional(),reduceOnly:oe().optional(),selfTradePreventionMode:$u.optional(),takeProfit:$x.optional(),stopLoss:$x.optional(),trailingStop:Bj.optional()}).optional()}).refine((e)=>NI(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!zx(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss/trailingStop are only supported for MARGIN orders",path:["options"]}).refine((e)=>!zx(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss/trailingStop cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),Uj=y({orderId:be,remainingQuantityTarget:Ve.optional()}),jj=y({orderId:be,newOrder:y({price:Ve.optional(),quantity:Ve.optional(),useMasterBalance:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:$u.optional()})}),qj=y({page:Qe().optional(),status:pt([z(Nx),ie(z(Nx)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:be.optional(),tradingMode:xh.optional(),marginAccountId:be.optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),S2t=z(["STOP_LOSS","TAKE_PROFIT","TRAILING_STOP"],{message:'conditionType must be "STOP_LOSS", "TAKE_PROFIT", or "TRAILING_STOP"'}),_2t=z(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),kfe=z(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),Hj=z(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),zI=y({conditionalOrderId:be}),Gj=y({page:Qe().optional(),marginAccountId:be.optional(),tradingPairId:be.optional(),state:kfe.optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),Rfe=z(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),Cfe=pt([I().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),p().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),Ofe=2592000000,Vj=y({tradingPairId:be,side:Pp,quantity:Ve,options:y({durationSeconds:Cfe.optional(),startTime:Js.optional(),endTime:Js.optional(),limitPrice:Ve.optional(),slippageToleranceBps:Afe.optional(),randomize:oe().optional(),executionStyle:z(["TAKER","PASSIVE"]).optional(),reduceOnly:oe().optional(),tradingMode:xh.optional(),marginAccountId:be.optional(),riskBucketId:be.optional(),marginMode:Bx.optional(),leverage:Ve.optional(),strategyKey:p().min(1).max(128).optional(),useMasterBalance:oe().optional(),clientTwapId:p().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional(),triggerPrice:Ve.optional(),triggerDirection:z(["ABOVE","BELOW"]).optional(),conditionalExpiry:Js.optional()})}).refine((e)=>e.options.durationSeconds!==void 0!==(e.options.endTime!==void 0),{message:"Exactly one of durationSeconds or endTime must be set",path:["options","durationSeconds"]}).refine((e)=>e.options.startTime===void 0||e.options.endTime!==void 0,{message:"startTime is only valid together with endTime",path:["options","startTime"]}).refine((e)=>e.options.marginMode===void 0||e.options.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode==="MARGIN",{message:"riskBucketId is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}).refine((e)=>e.options.triggerPrice!==void 0===(e.options.triggerDirection!==void 0),{message:"triggerPrice and triggerDirection are both-or-neither",path:["options","triggerDirection"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.durationSeconds!==void 0,{message:"conditional TWAP (triggerPrice) requires durationSeconds — the window floats from the trigger instant",path:["options","durationSeconds"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.startTime===void 0&&e.options.endTime===void 0,{message:"triggerPrice is incompatible with startTime/endTime",path:["options","triggerPrice"]}).refine((e)=>e.options.conditionalExpiry===void 0||e.options.triggerPrice!==void 0,{message:"conditionalExpiry is only valid together with triggerPrice",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r>Date.now()},{message:"conditionalExpiry must be in the future",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r-Date.now()<=Ofe},{message:"conditionalExpiry cannot be more than 30 days after creation (the maximum window)",path:["options","conditionalExpiry"]}),Dx=y({twapOrderId:be}),Zj=y({page:Qe().optional(),state:Rfe.optional(),tradingPairId:be.optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),Wj=y({page:Qe().optional(),twapOrderId:be,orderBy:z(["ASC","DESC"]).optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),Mfe=y({tradingPairId:be,orderType:Ap,side:Pp,price:Ve.optional(),quantity:Ve,idempotencyKey:$I.optional(),tradingMode:xh.optional(),slippageTolerance:zj,useMasterBalance:oe().optional(),expirationDate:Js.optional(),timeInForce:$j.optional(),marginAccountId:be.optional(),marginMode:Bx.optional(),riskBucketId:be.optional(),riskBucketCollateral:Ve.optional(),strategyKey:p().min(1).max(128).optional(),positionSide:wh.optional(),leverage:Ve.optional(),reduceOnly:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:$u.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).refine((e)=>e.orderType!=="MARKET"||e.postOnly!==!0,{message:"postOnly must not be provided for MARKET orders",path:["postOnly"]}).refine((e)=>e.postOnly!==!0||e.timeInForce===void 0||e.timeInForce!=="IOC"&&e.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["postOnly"]}).refine((e)=>e.riskBucketCollateral===void 0||e.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode!=="CROSS"||e.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine((e)=>e.marginMode!=="CROSS"||e.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine((e)=>e.riskBucketCollateral===void 0||e.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.riskBucketCollateral===void 0||e.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine((e)=>NI(e.side,e.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["positionSide"]}).refine((e)=>e.tradingMode!=="MARGIN"||e.reduceOnly===!0||e.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["leverage"]}),Lx=100,Kj=y({orders:ie(Mfe).min(1,"At least one order is required").max(Lx,`At most ${Lx} orders per batch request`)}),Nfe=y({orderId:be,price:Ve.optional(),quantity:Ve.optional(),useMasterBalance:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:$u.optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),Yj=y({orders:ie(Nfe).min(1,"At least one order is required").max(Lx,`At most ${Lx} orders per batch request`)});var Fx=y({clientId:p().trim().min(1,"Client ID is required"),page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),Jj=Fx.extend({status:p().trim().min(1,"Status cannot be empty").optional(),userId:be.optional(),tradingPairId:be.optional(),side:p().trim().min(1,"Side cannot be empty").optional(),orderType:p().trim().min(1,"Order type cannot be empty").optional()}),Qj=Fx.extend({isActive:oe().optional(),accountType:p().trim().min(1,"Account type cannot be empty").optional(),address:p().trim().min(1,"Address filter cannot be empty").optional()}),Xj=Fx.extend({userId:be.optional(),transactionType:p().trim().min(1,"Transaction type cannot be empty").optional(),entryType:p().trim().min(1,"Entry type cannot be empty").optional(),assetId:be.optional()}),eq=Fx.extend({userId:be.optional(),assetId:be.optional()});class tq extends Error{issues;constructor(e){let t=e.issues.map((r)=>{let n=r.path.join(".");return`${n?`${n}: `:""}${r.message}`});super(`Validation failed:
146
146
  - ${t.join(`
147
- - `)}`);this.name="ValidationError",this.issues=e.issues}getErrors(){let e={};for(let t of this.issues){let r=t.path.join(".");e[r||"root"]=t.message}return e}}function te(e,t){let r=e.safeParse(t);if(!r.success)throw new tq(r.error);return r.data}var Ux=p().trim().min(1,"leader handle is required"),$fe=p().trim().regex(/^\d+(\.\d+)?$/,"slPct must be a decimal fraction (e.g. '0.25')").refine((e)=>{let t=Number.parseFloat(e);return t>0&&t<=1},"slPct must be greater than 0 and at most 1");function jx(e){return{pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(e,`Page size cannot exceed ${e}`).optional(),pageToken:p().optional()}}var rq=y({shareBps:I().int("shareBps must be an integer").min(0,"shareBps cannot be negative").max(1e4,"shareBps cannot exceed 10000").optional(),bio:p().refine((e)=>new TextEncoder().encode(e).length<=2000,"bio cannot exceed 2,000 bytes").optional(),status:z(["ACTIVE","PAUSED"]).optional(),minAllocation:Ve.optional()}).strict(),nq=y({followId:be.optional(),leader:Ux.optional(),marginModePolicy:z(["FOLLOW","CROSS","ISOLATED"]).optional(),sizingMode:z(["PROPORTIONAL","FIXED_MARGIN"]).optional(),sizingParam:Ve.optional(),leverageMode:z(["FOLLOW","FIXED"]).optional(),fixedLeverage:Ve.optional(),allocation:Ve,slPct:$fe.optional(),tradingPairIds:ie(be).max(256,"at most 256 markets can be copied").optional(),copyExisting:oe().optional()}).strict().superRefine((e,t)=>{if(e.followId===void 0&&e.leader===void 0)t.addIssue({code:"custom",message:"leader is required when creating a follow",path:["leader"]});if(e.followId!==void 0&&e.copyExisting===!0)t.addIssue({code:"custom",message:"copyExisting applies only when creating a follow",path:["copyExisting"]});oq(e,t)});function oq(e,t){let r=e.sizingMode==="FIXED_MARGIN";if(r&&e.sizingParam===void 0)t.addIssue({code:"custom",message:"sizingParam is required for FIXED_MARGIN sizing",path:["sizingParam"]});if(!r&&e.sizingParam!==void 0)t.addIssue({code:"custom",message:"sizingParam is only accepted with FIXED_MARGIN sizing",path:["sizingParam"]});let n=e.leverageMode==="FIXED";if(n&&e.fixedLeverage===void 0)t.addIssue({code:"custom",message:"fixedLeverage is required for FIXED leverage",path:["fixedLeverage"]});if(!n&&e.fixedLeverage!==void 0)t.addIssue({code:"custom",message:"fixedLeverage is only accepted with FIXED leverage",path:["fixedLeverage"]})}var iq=y({leader:Ux,marginModePolicy:z(["FOLLOW","CROSS","ISOLATED"]).optional(),sizingMode:z(["PROPORTIONAL","FIXED_MARGIN"]).optional(),sizingParam:Ve.optional(),leverageMode:z(["FOLLOW","FIXED"]).optional(),fixedLeverage:Ve.optional(),allocation:Ve,tradingPairIds:ie(be).max(256,"at most 256 markets can be copied").optional()}).strict().superRefine((e,t)=>oq(e,t)),sq=y({followId:be,tradingPairId:be,amount:Ve}).strict(),aq=y({sort:z(["roi","pnl","followers","allocated","aum","win_rate"]).optional(),window:z(["7d","30d","90d","all"]).optional(),...jx(100)}).strict(),cq=y(jx(100)).strict(),uq=y(jx(1000)).strict(),lq=y(jx(1000)).strict();var dq=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});var LI=y({page:Qe().optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),fq=LI.extend({state:p().trim().min(1,"State cannot be empty").optional(),tradingPairId:be.optional()}),mq=y({marginAccountId:be,tradingPairId:be.optional()}),hq=y({tradingPairId:be.optional()}).optional(),gq=y({asset:p().trim().min(1,"Asset cannot be empty").optional()}).optional(),zfe=y({asset:p().trim().min(1,"Asset cannot be empty"),amount:Ve,tradingPairId:be.optional(),strategyKey:p().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:z(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),qx=y({asset:p().trim().min(1,"Asset cannot be empty"),amount:Ve}),Lfe=y({tradingPairId:be,strategyKey:p().trim().min(1,"Strategy key cannot be empty").optional()}),yq=Lfe.extend({marginMode:Ae("ISOLATED").optional(),marginAccountId:be.optional(),selectedTradingPairIds:Qe().optional(),applyToPositionMargin:oe().optional()}),Bfe=y({marginMode:Ae("CROSS"),marginAccountId:be.optional(),selectedTradingPairIds:Qe().optional(),strategyKey:Qe().optional()}),Dfe=y({marginMode:Ae("CROSS"),marginAccountId:be.optional(),selectedTradingPairIds:Qe().optional(),strategyKey:Qe().optional(),tradingPairId:Qe().optional()}),BI=y({marginAccountId:be,request:zfe}),bq=y({request:qx}),Ffe=y({marginMode:z(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Nt().optional()}).loose().superRefine((e,t)=>{if(e.selectedTradingPairIds===void 0)return;t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:e.marginMode==="CROSS"?"selectedTradingPairIds is not accepted on a CROSS transfer: cross scope is derived from trading, so a funding call has nothing to declare":"selectedTradingPairIds is not supported for ISOLATED risk buckets"})}),xq=y({request:Ffe.pipe(pt([qx.merge(yq).strict(),qx.merge(Dfe).strict()]))}),wq=y({request:qx}),Sq=LI.extend({marginAccountId:be,movementType:p().trim().min(1,"Movement type cannot be empty").optional()}),_q=LI.extend({movementType:p().trim().min(1,"Movement type cannot be empty").optional()}).optional(),DI=y({tradingPairId:be,side:Pp,positionSide:wh.optional(),orderType:Ap,price:Ve.optional(),quantity:Ve,leverage:Ve.optional(),reduceOnly:oe().optional(),slippageToleranceBps:Lj.optional()}),FI=(e,t)=>{if(e.orderType!=="MARKET"&&e.slippageToleranceBps!==void 0)t.addIssue({code:wa.custom,message:"slippageToleranceBps is only supported for MARKET orders",path:["slippageToleranceBps"]});if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:wa.custom,message:"positionSide must match side when provided (BUY=LONG, SELL=SHORT)",path:["positionSide"]})}if(e.reduceOnly!==!0&&e.leverage===void 0)t.addIssue({code:wa.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},Tq=DI.strict().superRefine(FI),Ufe=DI.merge(yq).strict().superRefine(FI),jfe=DI.merge(Bfe).strict().superRefine(FI),qfe=y({marginMode:z(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Nt().optional()}).loose().superRefine((e,t)=>{if(e.selectedTradingPairIds===void 0)return;t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:e.marginMode==="CROSS"?"selectedTradingPairIds is not accepted on a CROSS preview: cross scope is derived from trading, so a preview has nothing to declare":"selectedTradingPairIds is not supported for ISOLATED risk buckets"})}),Hfe=qfe.pipe(pt([Ufe,jfe])),vq=y({marginAccountId:be,request:Tq}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),Eq=y({request:Tq}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),Pq=y({request:Hfe}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),Aq=y({request:y({subaccountKey:p().trim().min(1,"subaccountKey is required").max(64,"subaccountKey must be at most 64 characters").regex(/^[A-Za-z0-9_.:-]+$/,"subaccountKey may contain only letters, digits, '_', '-', '.' and ':'").refine((e)=>!e.toLowerCase().startsWith("copy:"),"sub-account keys starting with copy: are reserved").refine((e)=>e!=="default","default names the default margin account"),label:p().optional()}).strict()}),Iq=y({marginAccountId:be}),UI=y({marginAccountId:be,amount:Ve}),kq=y({marginAccountId:be}),pq=pt([y({wallet:Ae(!0)}).strict(),y({marginAccountId:be,riskBucketId:be.optional()}).strict()]),Rq=y({request:y({asset:p().trim().min(1,"Asset is required"),amount:Ve,from:pq,to:pq}).strict()});var Cq=z(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),Gfe=31536000000,Vfe=946684800000,Hx=I().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(Vfe,{message:"Timestamp must be at least Jan 1, 2000 (946684800000 ms). Did you pass seconds instead of milliseconds?"}).max(Number.MAX_SAFE_INTEGER,{message:"Timestamp must not exceed JavaScript's maximum safe integer"}).refine((e)=>e<=Date.now()+Gfe,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),B2t=y({tradingPairId:be,interval:Cq,startTime:Hx,endTime:Hx}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),D2t=p().min(1,"Trading pair symbol cannot be empty").regex(/^[A-Za-z0-9]{1,10}\/[A-Za-z0-9]{1,10}$/,{message:'Trading pair symbol must be in format "BASE/QUOTE" (e.g., "BTC/USDT", "ETH/USD")'}),Zfe=I().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),Oq=y({tradingPairId:be,interval:Cq,startTime:Hx.optional(),endTime:Hx.optional(),limit:Zfe,priceType:z(["trade","mark"]).optional()}).refine((e)=>{if(e.startTime!==void 0&&e.endTime!==void 0)return e.startTime<e.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var F2t=y({tradingPairId:be}),U2t=y({query:p().min(1,"Search query cannot be empty").optional(),pageSize:I().int().min(1).max(100).optional(),page:I().int().min(1).optional()}),qi=y({tradingPairId:be}),Mq=y({page:Qe().optional(),startTime:p().optional(),endTime:p().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),orderBy:z(["ASC","DESC"],{message:'orderBy must be "ASC" or "DESC"'}).optional()}),Nq=Mq,$q=Mq,zq=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});var Bq=y({page:Qe().optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),Wfe=z(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),Kfe=z(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),Sh=y({positionId:be}),Dq=Bq.extend({marginAccountId:be.optional(),tradingPairId:be.optional(),status:Wfe.optional()}),Fq=Sh,Uq=Sh.extend({request:y({closeType:Kfe,limitPrice:Ve.optional(),slippageToleranceBps:Ip.optional(),quantity:Ve.optional()})}).refine((e)=>e.request.closeType==="MARKET"||e.request.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["request","limitPrice"]}).refine((e)=>e.request.closeType!=="MARKET"||e.request.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["request","limitPrice"]}),jq=y({tradingPairId:be.optional(),tradingPairIds:ie(be).min(1,{message:"tradingPairIds must list at least one trading pair; omit it to close every pair"}).max(256,{message:"tradingPairIds accepts at most 256 trading pairs"}).optional(),side:Hj.optional(),slippageToleranceBps:Ip.optional()}).strict().refine((e)=>e.tradingPairId===void 0||e.tradingPairIds===void 0,{message:"Pass tradingPairId or tradingPairIds, not both",path:["tradingPairIds"]}),qq=Sh,Lq=y({triggerPrice:Ve,orderType:Ap,limitPrice:Ve.optional(),quantity:Ve.optional(),closePosition:oe().optional(),timeInForce:OI.optional(),slippageToleranceBps:Ip.optional(),expiresAt:Js.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT TP/SL legs",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET TP/SL legs",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),Hq=Sh.extend({request:y({takeProfit:Lq.optional(),stopLoss:Lq.optional(),trailingStop:MI.optional(),oco:oe().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0||e.trailingStop!==void 0,{message:"At least one of takeProfit, stopLoss, or trailingStop is required"}).refine((e)=>e.oco!==!0||e.takeProfit!==void 0&&e.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),Gq=Bq.extend({positionId:be.optional(),marginAccountId:be.optional(),tradingPairId:be.optional(),reductionOnly:oe().optional()}),Yfe=z(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),Vq=Sh.extend({params:y({interval:Yfe,startTime:I().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:I().int().min(0,"endTime must be a non-negative millisecond timestamp").optional()}).refine((e)=>e.startTime===void 0||e.endTime===void 0||e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["startTime"]})});var Jfe=z(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),Qfe=z(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),Zq=y({mode:$u}),Wq=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),orderBy:z(["ASC","DESC"]).optional(),entryType:Jfe.optional(),transactionType:Qfe.optional(),assetId:be.optional()}),Kq=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),tradingPairId:be.optional(),pageToken:p().optional()}),Yq=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),Jq=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),tradingPairId:be.optional(),positionId:be.optional(),marginAccountId:be.optional()});var J2t=p().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),jI=pt([p().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),qC().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),Qq=y({assetId:be,amount:jI,autoWait:oe().optional()}),Xq=y({assetId:be,amount:jI,autoWait:oe().optional(),target:z(["spot","margin"]).optional(),options:y({asErc20:oe().optional()}).optional()}),e7=y({assetId:be,amount:jI,destination:p().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:oe().optional(),source:z(["spot","margin"]).optional()}),Q2t=y({assetId:be}),t7=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});var Gx=pn(j0(),1);function r7(e){return btoa(String.fromCharCode(...e))}function n7(e,t,r,n,o){if(!Number.isSafeInteger(o)||o<0||o>999999999999999)throw Error("Invalid signature creation time");if(!/^[A-Z]+$/.test(t)||!r.startsWith("/")||/[\s#\u0000-\u001f\u007f]/.test(r))throw Error("Invalid signature request target");let i=r.indexOf("?"),s=i<0?r:r.slice(0,i),a=i<0?"?":r.slice(i),c=`sha-256=:${r7(M0(n))}:`,l=`("@method" "@path" "@query" "content-digest");created=${o};keyid="${hs(e.publicKey)}";alg="ed25519"`,d=`"@method": ${t}
147
+ - `)}`);this.name="ValidationError",this.issues=e.issues}getErrors(){let e={};for(let t of this.issues){let r=t.path.join(".");e[r||"root"]=t.message}return e}}function te(e,t){let r=e.safeParse(t);if(!r.success)throw new tq(r.error);return r.data}var Ux=p().trim().min(1,"leader handle is required"),$fe=p().trim().regex(/^\d+(\.\d+)?$/,"slPct must be a decimal fraction (e.g. '0.25')").refine((e)=>{let t=Number.parseFloat(e);return t>0&&t<=1},"slPct must be greater than 0 and at most 1");function jx(e){return{pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(e,`Page size cannot exceed ${e}`).optional(),pageToken:p().optional()}}var rq=y({shareBps:I().int("shareBps must be an integer").min(0,"shareBps cannot be negative").max(1e4,"shareBps cannot exceed 10000").optional(),bio:p().refine((e)=>new TextEncoder().encode(e).length<=2000,"bio cannot exceed 2,000 bytes").optional(),status:z(["ACTIVE","PAUSED"]).optional(),minAllocation:Ve.optional()}).strict(),nq=y({followId:be.optional(),leader:Ux.optional(),marginModePolicy:z(["FOLLOW","CROSS","ISOLATED"]).optional(),sizingMode:z(["PROPORTIONAL","FIXED_MARGIN"]).optional(),sizingParam:Ve.optional(),leverageMode:z(["FOLLOW","FIXED"]).optional(),fixedLeverage:Ve.optional(),allocation:Ve,slPct:$fe.optional(),tradingPairIds:ie(be).max(256,"at most 256 markets can be copied").optional(),copyExisting:oe().optional()}).strict().superRefine((e,t)=>{if(e.followId===void 0&&e.leader===void 0)t.addIssue({code:"custom",message:"leader is required when creating a follow",path:["leader"]});if(e.followId!==void 0&&e.copyExisting===!0)t.addIssue({code:"custom",message:"copyExisting applies only when creating a follow",path:["copyExisting"]});oq(e,t)});function oq(e,t){let r=e.sizingMode==="FIXED_MARGIN";if(r&&e.sizingParam===void 0)t.addIssue({code:"custom",message:"sizingParam is required for FIXED_MARGIN sizing",path:["sizingParam"]});if(!r&&e.sizingParam!==void 0)t.addIssue({code:"custom",message:"sizingParam is only accepted with FIXED_MARGIN sizing",path:["sizingParam"]});let n=e.leverageMode==="FIXED";if(n&&e.fixedLeverage===void 0)t.addIssue({code:"custom",message:"fixedLeverage is required for FIXED leverage",path:["fixedLeverage"]});if(!n&&e.fixedLeverage!==void 0)t.addIssue({code:"custom",message:"fixedLeverage is only accepted with FIXED leverage",path:["fixedLeverage"]})}var iq=y({leader:Ux,marginModePolicy:z(["FOLLOW","CROSS","ISOLATED"]).optional(),sizingMode:z(["PROPORTIONAL","FIXED_MARGIN"]).optional(),sizingParam:Ve.optional(),leverageMode:z(["FOLLOW","FIXED"]).optional(),fixedLeverage:Ve.optional(),allocation:Ve,tradingPairIds:ie(be).max(256,"at most 256 markets can be copied").optional()}).strict().superRefine((e,t)=>oq(e,t)),sq=y({followId:be,tradingPairId:be,amount:Ve}).strict(),aq=y({sort:z(["roi","pnl","followers","allocated","aum","win_rate"]).optional(),window:z(["7d","30d","90d","all"]).optional(),...jx(100)}).strict(),cq=y(jx(100)).strict(),uq=y(jx(1000)).strict(),lq=y(jx(1000)).strict();var dq=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});var LI=y({page:Qe().optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),fq=LI.extend({state:p().trim().min(1,"State cannot be empty").optional(),tradingPairId:be.optional()}),mq=y({marginAccountId:be,tradingPairId:be.optional()}),hq=y({tradingPairId:be.optional()}).optional(),gq=y({asset:p().trim().min(1,"Asset cannot be empty").optional()}).optional(),zfe=y({asset:p().trim().min(1,"Asset cannot be empty"),amount:Ve,tradingPairId:be.optional(),strategyKey:p().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:z(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),qx=y({asset:p().trim().min(1,"Asset cannot be empty"),amount:Ve}),Lfe=y({tradingPairId:be,strategyKey:p().trim().min(1,"Strategy key cannot be empty").optional()}),yq=Lfe.extend({marginMode:Ae("ISOLATED").optional(),marginAccountId:be.optional(),selectedTradingPairIds:Qe().optional(),applyToPositionMargin:oe().optional()}),Bfe=y({marginMode:Ae("CROSS"),marginAccountId:be.optional(),selectedTradingPairIds:Qe().optional(),strategyKey:Qe().optional()}),Dfe=y({marginMode:Ae("CROSS"),marginAccountId:be.optional(),selectedTradingPairIds:Qe().optional(),strategyKey:Qe().optional(),tradingPairId:Qe().optional()}),BI=y({marginAccountId:be,request:zfe}),bq=y({request:qx}),Ffe=y({marginMode:z(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Nt().optional()}).loose().superRefine((e,t)=>{if(e.selectedTradingPairIds===void 0)return;t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:e.marginMode==="CROSS"?"selectedTradingPairIds is not accepted on a CROSS transfer: cross scope is derived from trading, so a funding call has nothing to declare":"selectedTradingPairIds is not supported for ISOLATED risk buckets"})}),xq=y({request:Ffe.pipe(pt([qx.merge(yq).strict(),qx.merge(Dfe).strict()]))}),wq=y({request:qx}),Sq=LI.extend({marginAccountId:be,movementType:p().trim().min(1,"Movement type cannot be empty").optional()}),_q=LI.extend({movementType:p().trim().min(1,"Movement type cannot be empty").optional()}).optional(),DI=y({tradingPairId:be,side:Pp,positionSide:wh.optional(),orderType:Ap,price:Ve.optional(),quantity:Ve,leverage:Ve.optional(),reduceOnly:oe().optional(),slippageToleranceBps:Lj.optional()}),FI=(e,t)=>{if(e.orderType!=="MARKET"&&e.slippageToleranceBps!==void 0)t.addIssue({code:wa.custom,message:"slippageToleranceBps is only supported for MARKET orders",path:["slippageToleranceBps"]});if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:wa.custom,message:"positionSide must match side when provided (BUY=LONG, SELL=SHORT)",path:["positionSide"]})}if(e.reduceOnly!==!0&&e.leverage===void 0)t.addIssue({code:wa.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},Tq=DI.strict().superRefine(FI),Ufe=DI.merge(yq).strict().superRefine(FI),jfe=DI.merge(Bfe).strict().superRefine(FI),qfe=y({marginMode:z(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Nt().optional()}).loose().superRefine((e,t)=>{if(e.selectedTradingPairIds===void 0)return;t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:e.marginMode==="CROSS"?"selectedTradingPairIds is not accepted on a CROSS preview: cross scope is derived from trading, so a preview has nothing to declare":"selectedTradingPairIds is not supported for ISOLATED risk buckets"})}),Hfe=qfe.pipe(pt([Ufe,jfe])),vq=y({marginAccountId:be,request:Tq}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),Eq=y({request:Tq}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),Pq=y({request:Hfe}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),Aq=y({request:y({subaccountKey:p().trim().min(1,"subaccountKey is required").max(64,"subaccountKey must be at most 64 characters").regex(/^[A-Za-z0-9_.:-]+$/,"subaccountKey may contain only letters, digits, '_', '-', '.' and ':'").refine((e)=>!e.toLowerCase().startsWith("copy:"),"sub-account keys starting with copy: are reserved").refine((e)=>e!=="default","default names the default margin account"),label:p().optional()}).strict()}),Iq=y({marginAccountId:be}),UI=y({marginAccountId:be,amount:Ve}),kq=y({marginAccountId:be}),pq=pt([y({wallet:Ae(!0)}).strict(),y({marginAccountId:be,riskBucketId:be.optional()}).strict()]),Rq=y({request:y({asset:p().trim().min(1,"Asset is required"),amount:Ve,from:pq,to:pq}).strict()});var Cq=z(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),Gfe=31536000000,Vfe=946684800000,Hx=I().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(Vfe,{message:"Timestamp must be at least Jan 1, 2000 (946684800000 ms). Did you pass seconds instead of milliseconds?"}).max(Number.MAX_SAFE_INTEGER,{message:"Timestamp must not exceed JavaScript's maximum safe integer"}).refine((e)=>e<=Date.now()+Gfe,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),B2t=y({tradingPairId:be,interval:Cq,startTime:Hx,endTime:Hx}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),D2t=p().min(1,"Trading pair symbol cannot be empty").regex(/^[A-Za-z0-9]{1,10}\/[A-Za-z0-9]{1,10}$/,{message:'Trading pair symbol must be in format "BASE/QUOTE" (e.g., "BTC/USDT", "ETH/USD")'}),Zfe=I().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),Oq=y({tradingPairId:be,interval:Cq,startTime:Hx.optional(),endTime:Hx.optional(),limit:Zfe,priceType:z(["trade","mark"]).optional()}).refine((e)=>{if(e.startTime!==void 0&&e.endTime!==void 0)return e.startTime<e.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var F2t=y({tradingPairId:be}),U2t=y({query:p().min(1,"Search query cannot be empty").optional(),pageSize:I().int().min(1).max(100).optional(),page:I().int().min(1).optional()}),qi=y({tradingPairId:be}),Mq=y({page:Qe().optional(),startTime:p().optional(),endTime:p().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),orderBy:z(["ASC","DESC"],{message:'orderBy must be "ASC" or "DESC"'}).optional()}),Nq=Mq,$q=Mq,zq=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});var Bq=y({page:Qe().optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),Wfe=z(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),Kfe=z(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),Sh=y({positionId:be}),Dq=Bq.extend({marginAccountId:be.optional(),tradingPairId:be.optional(),status:Wfe.optional()}),Fq=Sh,Uq=Sh.extend({request:y({closeType:Kfe,limitPrice:Ve.optional(),slippageToleranceBps:Ip.optional(),quantity:Ve.optional()})}).refine((e)=>e.request.closeType==="MARKET"||e.request.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["request","limitPrice"]}).refine((e)=>e.request.closeType!=="MARKET"||e.request.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["request","limitPrice"]}),jq=y({tradingPairId:be.optional(),tradingPairIds:ie(be).min(1,{message:"tradingPairIds must list at least one trading pair; omit it to close every pair"}).max(256,{message:"tradingPairIds accepts at most 256 trading pairs"}).optional(),side:Hj.optional(),slippageToleranceBps:Ip.optional()}).strict().refine((e)=>e.tradingPairId===void 0||e.tradingPairIds===void 0,{message:"Pass tradingPairId or tradingPairIds, not both",path:["tradingPairIds"]}),qq=Sh,Lq=y({triggerPrice:Ve,orderType:Ap,limitPrice:Ve.optional(),quantity:Ve.optional(),closePosition:oe().optional(),timeInForce:OI.optional(),slippageToleranceBps:Ip.optional(),expiresAt:Js.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT TP/SL legs",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET TP/SL legs",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),Hq=Sh.extend({request:y({takeProfit:Lq.optional(),stopLoss:Lq.optional(),trailingStop:MI.optional(),oco:oe().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0||e.trailingStop!==void 0,{message:"At least one of takeProfit, stopLoss, or trailingStop is required"}).refine((e)=>e.oco!==!0||e.takeProfit!==void 0&&e.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),Gq=Bq.extend({positionId:be.optional(),marginAccountId:be.optional(),tradingPairId:be.optional(),reductionOnly:oe().optional()}),Yfe=z(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),Vq=Sh.extend({params:y({interval:Yfe,startTime:I().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:I().int().min(0,"endTime must be a non-negative millisecond timestamp").optional()}).refine((e)=>e.startTime===void 0||e.endTime===void 0||e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["startTime"]})});var Jfe=z(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),Qfe=z(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),Zq=y({mode:$u}),Wq=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),orderBy:z(["ASC","DESC"]).optional(),entryType:Jfe.optional(),transactionType:Qfe.optional(),assetId:be.optional()}),Kq=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),tradingPairId:be.optional(),pageToken:p().optional()}),Yq=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),Jq=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),tradingPairId:be.optional(),positionId:be.optional(),marginAccountId:be.optional()});var J2t=p().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),jI=pt([p().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),q5().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),Qq=y({assetId:be,amount:jI,autoWait:oe().optional()}),Xq=y({assetId:be,amount:jI,autoWait:oe().optional(),target:z(["spot","margin"]).optional(),options:y({asErc20:oe().optional()}).optional()}),e7=y({assetId:be,amount:jI,destination:p().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:oe().optional(),source:z(["spot","margin"]).optional()}),Q2t=y({assetId:be}),t7=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});var Gx=pn(j0(),1);function r7(e){return btoa(String.fromCharCode(...e))}function n7(e,t,r,n,o){if(!Number.isSafeInteger(o)||o<0||o>999999999999999)throw Error("Invalid signature creation time");if(!/^[A-Z]+$/.test(t)||!r.startsWith("/")||/[\s#\u0000-\u001f\u007f]/.test(r))throw Error("Invalid signature request target");let i=r.indexOf("?"),s=i<0?r:r.slice(0,i),a=i<0?"?":r.slice(i),c=`sha-256=:${r7(M0(n))}:`,l=`("@method" "@path" "@query" "content-digest");created=${o};keyid="${hs(e.publicKey)}";alg="ed25519"`,d=`"@method": ${t}
148
148
  "@path": ${s}
149
149
  "@query": ${a}
150
150
  "content-digest": ${c}
151
- "@signature-params": ${l}`;return{"Signature-Input":`monaco=${l}`,Signature:`monaco=:${r7(Xl.sign(Qc(d),e.privateKey))}:`,"Content-Digest":c}}var Xfe="@0xmonaco/core";class Ye{apiUrl;sessionKeypair;requestSigning="legacy";redirectPolicy;serverClock=new cu;setRequestSigning(e){if(e!=="legacy"&&e!=="rfc9421")throw Error("Unsupported request signing protocol");this.requestSigning=e}setRedirectPolicy(e){this.redirectPolicy=e}retryOptions;setServerClock(e){this.serverClock=e}constructor(e,t){this.apiUrl=e,this.retryOptions={maxRetries:t?.maxRetries??3,baseDelayMs:t?.baseDelayMs??1000}}setSessionKeypair(e){this.sessionKeypair=e?EB(e.publicKey,e.privateKey):void 0}parseRequestBody(e){if(!e)return;if(typeof e==="string")try{return JSON.parse(e)}catch{return e}if(e instanceof FormData){let t={};return e.forEach((r,n)=>{t[n]=r instanceof File?`[File: ${r.name}]`:r}),t}if(e instanceof URLSearchParams){let t={};return e.forEach((r,n)=>{t[n]=r}),t}if(e instanceof Blob)return{type:"[Blob]",size:e.size,contentType:e.type};if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return{type:"[ArrayBuffer]",size:e instanceof ArrayBuffer?e.byteLength:e.byteLength};if(typeof ReadableStream<"u"&&e instanceof ReadableStream)return{type:"[ReadableStream]",note:"Stream body not captured for logging"};return{type:"[Unknown]",bodyType:typeof e}}extractResponseMetadata(e){if(!e)return{};let t=e.get("x-request-id")||e.get("request-id")||e.get("x-correlation-id")||void 0,r=e.get("retry-after"),n;if(r!==null){let o=r.trim();if(/^\d+$/.test(o))n=Number.parseInt(o,10);else{let i=B0(o);if(i!==void 0)n=Math.max(0,Math.ceil((i-Date.now())/1000))}}return{requestId:t,retryAfter:n}}async executeRequest(e,t,r,n){let o,i={"User-Agent":Xfe,...r.headers};try{o=await fetch(e,{...r,headers:i,...this.redirectPolicy?{redirect:this.redirectPolicy}:{}})}catch(l){throw new sr(`Network request failed for ${t}`,{endpoint:e,cause:l instanceof Error?l:Error(String(l)),requestBody:n})}this.serverClock.observeResponse(o.headers,Date.now());let s,a=o.headers?.get("content-type")||"unknown",c=o.clone?o.clone():o;try{s=await o.json()}catch(l){let d;try{d=await c.text()}catch{d="[Unable to read response body]"}if(!o.ok){let f=`API request failed: ${o.status}. Response is not JSON (Content-Type: ${a})`,{requestId:h,retryAfter:g}=this.extractResponseMetadata(o.headers);throw new sr(f,{endpoint:e,statusCode:o.status,responseBody:{rawResponse:d.substring(0,500),contentType:a,parseError:l instanceof Error?l.message:String(l)},cause:l instanceof Error?l:void 0,requestBody:n,requestId:h,retryAfter:g})}if(d.trim()==="")return;throw new sr(`Expected JSON response but received ${a}`,{endpoint:e,statusCode:o.status,responseBody:{rawResponse:d.substring(0,500),contentType:a},cause:l instanceof Error?l:void 0,requestBody:n})}if(!o.ok){let l=s!==null&&typeof s==="object"?s:void 0,d=(typeof l?.message==="string"?l.message:void 0)||(typeof l?.error==="string"?l.error:void 0)||`API request failed: ${o.status}`,{requestId:f,retryAfter:h}=this.extractResponseMetadata(o.headers);throw new sr(d,{endpoint:e,statusCode:o.status,responseBody:s,requestBody:n,requestId:f,retryAfter:h})}return s}async makeAuthenticatedRequest(e,t={}){if(!this.sessionKeypair)throw new sr("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:Gx.StatusCodes.UNAUTHORIZED});let r=`${this.apiUrl}${e}`,n=this.parseRequestBody(t.body),o=t.headers;if(this.requestSigning==="rfc9421"){let a={};new Headers(t.headers).forEach((c,l)=>{a[l]=c}),o=a}let i=()=>this.executeRequest(r,e,{...t,...this.requestSigning==="rfc9421"?{redirect:"error"}:{},headers:{"Content-Type":"application/json",...o,...this.buildSignatureHeaders(e,t)}},n),s=this.serverClock.offsetMs;try{return await i()}catch(a){let c=Math.abs(this.serverClock.offsetMs-s)>=Kv;if(a instanceof sr&&a.statusCode===Gx.StatusCodes.UNAUTHORIZED&&c)return i();throw a}}buildSignatureHeaders(e,t){if(!this.sessionKeypair)throw new sr("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:Gx.StatusCodes.UNAUTHORIZED});let r=(t.method??"GET").toUpperCase();if(this.requestSigning==="rfc9421"){if(t.body!=null&&typeof t.body!=="string")throw Error("Signed requests require a string body");let c=new Headers(t.headers);for(let d of["signature","signature-input","content-digest","x-monaco-publickey","x-monaco-timestamp","x-monaco-signature"])if(c.has(d))throw Error("Signature headers are managed by the SDK");let l=new URL(`${this.apiUrl}${e}`);return n7(this.sessionKeypair,r,l.pathname+l.search,Qc(t.body??""),Math.floor(this.serverClock.now()/1000))}let n=this.serverClock.now(),o=typeof t.body==="string"?Qc(t.body):new Uint8Array(0),i=PB(o),s=AB(r,e,n,i),a=L0(this.sessionKeypair.privateKey,s);return{"X-Monaco-PublicKey":hs(this.sessionKeypair.publicKey),"X-Monaco-Timestamp":String(n),"X-Monaco-Signature":a}}async makePublicRequest(e,t={}){let r=`${this.apiUrl}${e}`,n=this.parseRequestBody(t.body);return this.executeRequest(r,e,{...t,headers:{"Content-Type":"application/json",...t.headers}},n)}}function it(e){return encodeURIComponent(e)}function Ht(e,t){if(!t)return e;let r=new URLSearchParams;for(let[o,i]of Object.entries(t))if(i!==void 0)r.set(o,String(i));let n=r.toString();return n?`${e}?${n}`:e}var ue={orders:{create:()=>"/api/v1/orders",list:(e)=>Ht("/api/v1/orders",e),get:(e)=>`/api/v1/orders/${it(e)}`,replace:(e)=>`/api/v1/orders/${it(e)}`,cancel:()=>"/api/v1/orders/cancel",batchCancel:()=>"/api/v1/orders/batch-cancel",batchCancelAll:()=>"/api/v1/orders/batch-cancel-all",batchCancelAllByPair:(e)=>`/api/v1/orders/batch-cancel-all/${it(e)}`,batchCreate:()=>"/api/v1/orders/batch-create",batchReplace:()=>"/api/v1/orders/batch-replace",listConditional:(e)=>Ht("/api/v1/orders/conditional",e),cancelConditional:(e)=>`/api/v1/orders/conditional/${it(e)}`,getConditional:(e)=>`/api/v1/orders/conditional/${it(e)}`,createTwap:()=>"/api/v1/orders/twap",listTwap:(e)=>Ht("/api/v1/orders/twap",e),getTwap:(e)=>`/api/v1/orders/twap/${it(e)}`,getTwapTca:(e)=>`/api/v1/orders/twap/${it(e)}/tca`,listTwapSlices:(e,t)=>Ht(`/api/v1/orders/twap/${it(e)}/slices`,t),cancelTwap:(e)=>`/api/v1/orders/twap/${it(e)}/cancel`},delegatedAgents:{list:()=>"/api/v1/delegated-agents",owners:()=>"/api/v1/delegated-agents/owners",byId:(e)=>`/api/v1/delegated-agents/${it(e)}`,sessions:()=>"/api/v1/delegated-agents/sessions"},withdrawals:{initiate:()=>"/api/v1/withdrawals",byIndex:(e)=>`/api/v1/withdrawals/${it(String(e))}`,list:(e)=>Ht("/api/v1/withdrawals",e)},market:{listTradingPairs:(e)=>Ht("/api/v1/market/pairs",e),getTradingPair:(e)=>`/api/v1/market/pairs/${it(e)}`,getCandles:(e,t,r)=>Ht(`/api/v1/market/pairs/charts/candlestick/${it(e)}/${it(t)}`,r),getMarketMetadata:(e)=>`/api/v1/market/pairs/${it(e)}/metadata`,getPerpMarketConfig:(e)=>`/api/v1/market/pairs/${it(e)}/perp/config`,getPerpMarketSummary:(e)=>`/api/v1/market/pairs/${it(e)}/perp/summary`,getMarkPrice:(e)=>`/api/v1/market/pairs/${it(e)}/mark-price`,getIndexPrice:(e)=>`/api/v1/market/pairs/${it(e)}/index-price`,getFundingState:(e)=>`/api/v1/market/pairs/${it(e)}/funding`,listFundingHistory:(e,t)=>Ht(`/api/v1/market/pairs/${it(e)}/funding/history`,t),listAllFundingHistory:(e)=>Ht("/api/v1/market/funding/history",e),getOpenInterest:(e)=>`/api/v1/market/pairs/${it(e)}/open-interest`,getScreener:(e)=>Ht("/api/v1/market/screener",e),getMarketStats:()=>"/api/v1/market/stats"},orderbook:{get:(e,t)=>Ht(`/api/v1/orderbook/${it(e)}`,t)},trades:{publicByPair:(e,t)=>Ht(`/api/v1/trades/${it(e)}`,t),byId:(e)=>`/api/v1/trades/by-id/${it(e)}`,user:(e)=>Ht("/api/v1/accounts/trades",e)},applications:{orders:(e)=>Ht("/api/v1/applications/orders",e),users:(e)=>Ht("/api/v1/applications/users",e),movements:(e)=>Ht("/api/v1/applications/movements",e),balances:(e)=>Ht("/api/v1/applications/balances",e),stats:(e)=>Ht("/api/v1/applications/stats",e)},subAccounts:{list:()=>"/api/v1/accounts/sub-accounts",createLimit:()=>"/api/v1/accounts/sub-accounts/limits",getLimits:(e)=>`/api/v1/accounts/sub-accounts/${it(e)}/limits`,limit:(e,t)=>`/api/v1/accounts/sub-accounts/${it(e)}/limits/${it(t)}`},faucet:{mint:()=>"/api/v1/faucet/mint",info:()=>"/api/v1/faucet/info"},sweeper:{register:()=>"/api/v1/sweeper/register",chains:()=>"/api/v1/sweeper/chains"},whitelist:{submit:()=>"/api/v1/whitelist"},positions:{list:(e)=>Ht("/api/v1/positions",e),get:(e)=>`/api/v1/positions/${it(e)}`,close:(e)=>`/api/v1/positions/${it(e)}/close`,batchCloseAll:()=>"/api/v1/positions/batch-close-all",risk:(e)=>`/api/v1/positions/${it(e)}/risk`,attachTpSl:(e)=>`/api/v1/positions/${it(e)}/tp-sl`,history:(e)=>Ht("/api/v1/positions/history",e),pnlHistory:(e,t)=>Ht(`/api/v1/positions/${it(e)}/pnl/history`,t)},marginAccounts:{list:(e)=>Ht("/api/v1/margin/accounts",e),parentSummary:(e)=>Ht("/api/v1/margin/parent-margin-account",e),summary:(e,t)=>Ht(`/api/v1/margin/accounts/${it(e)}`,t),availableCollateral:(e)=>Ht("/api/v1/margin/collateral/available",e),transferIn:(e)=>`/api/v1/margin/accounts/${it(e)}/collateral/transfer-in`,transferInParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-in",transferInRiskBucket:()=>"/api/v1/margin/risk-buckets/collateral/transfer-in",transferOut:(e)=>`/api/v1/margin/accounts/${it(e)}/collateral/transfer-out`,transferOutParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-out",movements:(e,t)=>Ht(`/api/v1/margin/accounts/${it(e)}/movements`,t),parentMovements:(e)=>Ht("/api/v1/margin/parent-margin-account/movements",e),simulateParentMarginOrderRisk:()=>"/api/v1/margin/parent-margin-account/simulate-order-risk",simulateOrderRisk:(e)=>`/api/v1/margin/accounts/${it(e)}/simulate-order-risk`,simulateRiskBucketOrderRisk:()=>"/api/v1/margin/risk-buckets/simulate-order-risk",createSubAccount:()=>"/api/v1/margin/sub-accounts",closeSubAccount:(e)=>`/api/v1/margin/sub-accounts/${it(e)}/close`,subAccountTransferIn:(e)=>`/api/v1/margin/sub-accounts/${it(e)}/collateral/transfer-in`,subAccountTransferOut:(e)=>`/api/v1/margin/sub-accounts/${it(e)}/collateral/transfer-out`,pnl:(e)=>`/api/v1/margin/accounts/${it(e)}/pnl`,transferCollateral:()=>"/api/v1/margin/collateral/transfer"},streams:{orderbook:()=>"/api/v1/streaming/orderbook",trades:()=>"/api/v1/streaming/trades",perpMarketSummaries:()=>"/api/v1/streaming/perp-market-summaries",markPrices:()=>"/api/v1/streaming/mark-prices",privateTrades:()=>"/api/v1/streaming/private-trades",orders:()=>"/api/v1/streaming/orders",positions:()=>"/api/v1/streaming/positions",funding:()=>"/api/v1/streaming/funding",liquidationAlerts:()=>"/api/v1/streaming/liquidation-alerts"}};class Vx extends Ye{async getApplicationConfig(){let e=await this.makeAuthenticatedRequest("/api/v1/applications/config",{method:"GET"});return{id:e.id,name:e.name,allowedOrigins:e.allowedOrigins,webhookUrl:e.webhookUrl,vaultContractAddress:e.vaultContractAddress,clientId:e.clientId}}async listApplicationOrders(e){return te(Jj,e),await this.makePublicRequest(ue.applications.orders({clientId:e.clientId,pageSize:e.pageSize,pageToken:e.pageToken,status:e.status,userId:e.userId,tradingPairId:e.tradingPairId,side:e.side,orderType:e.orderType}))}async listApplicationUsers(e){return te(Qj,e),await this.makePublicRequest(ue.applications.users({clientId:e.clientId,pageSize:e.pageSize,pageToken:e.pageToken,isActive:e.isActive,accountType:e.accountType,address:e.address}))}async listApplicationMovements(e){return te(Xj,e),await this.makePublicRequest(ue.applications.movements({clientId:e.clientId,pageSize:e.pageSize,pageToken:e.pageToken,userId:e.userId,transactionType:e.transactionType,entryType:e.entryType,assetId:e.assetId}))}async listApplicationBalances(e){return te(eq,e),await this.makePublicRequest(ue.applications.balances({clientId:e.clientId,pageSize:e.pageSize,pageToken:e.pageToken,userId:e.userId,assetId:e.assetId}))}async getApplicationStats(e){return await this.makePublicRequest(ue.applications.stats({clientId:e.clientId,since:e.since}))}}var eme="OPERATIONS_BLOCKED",tme="OVERLOADED";function rme(e){if(!(e instanceof sr)||!e.retryable)return e;if(!(e.statusCode===void 0||e.statusCode>=500)||nme(e))return e;return e.retryable=!1,e.suggestion="The claim's outcome is unknown: it may have committed after this failure. Do not retry automatically, and do not rely on a balance read to decide — an admitted claim can still be queued, so an unchanged balance does not prove it will not commit. Treat the claim as pending and reconcile before issuing another; this endpoint has no idempotency key, so a retry can claim a second time.",e}function nme(e){let t=e.responseBody;if(t===null||typeof t!=="object")return!1;let{error:r,code:n}=t;return r===eme||n===tme}class Zx extends Ye{async getConfig(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/config",{method:"GET"})}async setBuilderFee(e){let t=te(gI,e);return this.makeAuthenticatedRequest("/api/v1/buildercodes/builder-fee",{method:"PUT",body:JSON.stringify({bps:t.bps})})}async listBuilderFeeChanges(e){if(e)te(yI,e);let t=new URLSearchParams;if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.pageToken!==void 0)t.append("pageToken",e.pageToken);let r=t.toString(),n=r?`/api/v1/buildercodes/builder-fee/changes?${r}`:"/api/v1/buildercodes/builder-fee/changes";return this.makeAuthenticatedRequest(n,{method:"GET"})}async listPayouts(e){if(e)te(bI,e);let t=new URLSearchParams;if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.pageToken!==void 0)t.append("pageToken",e.pageToken);if(e?.kind!==void 0)t.append("kind",e.kind);let r=t.toString(),n=r?`/api/v1/buildercodes/payouts?${r}`:"/api/v1/buildercodes/payouts";return this.makeAuthenticatedRequest(n,{method:"GET"})}async getPayoutSummary(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/payouts/summary",{method:"GET"})}async getRewardsBalance(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/rewards/balance",{method:"GET"})}async claimBuildercodeRewards(e){let t=te(xI,e);try{return await this.makeAuthenticatedRequest("/api/v1/buildercodes/rewards/claim",{method:"POST",body:JSON.stringify({token:t.token,amount:t.amount})})}catch(r){throw rme(r)}}}var Hi="/api/v1/copy-trading";function Wx(e){let t=new URLSearchParams;for(let[n,o]of Object.entries(e))if(o!==void 0)t.append(n,String(o));let r=t.toString();return r?`?${r}`:""}function qI(e){return`${Hi}/leaders/${encodeURIComponent(te(Ux,e))}`}function _h(e){return`${Hi}/follows/${te(be,e)}`}class Kx extends Ye{async listLeadTraders(e={}){let{sort:t,window:r,pageSize:n,pageToken:o}=te(aq,e);return await this.makePublicRequest(`${Hi}/leaders${Wx({sort:t,window:r,pageSize:n,pageToken:o})}`,{method:"GET"})}async getLeadTrader(e){return await this.makePublicRequest(qI(e),{method:"GET"})}async listLeadTraderClosedTrades(e,t={}){let r=qI(e),{pageSize:n,pageToken:o}=te(cq,t);return await this.makePublicRequest(`${r}/closed-trades${Wx({pageSize:n,pageToken:o})}`,{method:"GET"})}async listLeadTraderOpenPositions(e){return await this.makeAuthenticatedRequest(`${qI(e)}/positions`,{method:"GET"})}async upsertLeadTrader(e={}){let{shareBps:t,bio:r,status:n,minAllocation:o}=te(rq,e),i={};if(t!==void 0)i.shareBps=t;if(r!==void 0)i.bio=r;if(n!==void 0)i.status=n;if(o!==void 0)i.minAllocation=o;return await this.makeAuthenticatedRequest(`${Hi}/leaders/me`,{method:"PUT",body:JSON.stringify(i)})}async getMyLeadTrader(){return await this.makeAuthenticatedRequest(`${Hi}/leaders/me`,{method:"GET"})}async listMyFollowers(e={}){let{pageSize:t,pageToken:r}=te(lq,e);return await this.makeAuthenticatedRequest(`${Hi}/leaders/me/followers${Wx({pageSize:t,pageToken:r})}`,{method:"GET"})}async upsertFollow(e){let t=te(nq,e),r={};if(t.followId!==void 0)r.followId=t.followId;if(r.leader=t.leader??"",r.allocation=t.allocation,t.marginModePolicy!==void 0)r.marginModePolicy=t.marginModePolicy;if(t.sizingMode!==void 0)r.sizingMode=t.sizingMode;if(t.sizingParam!==void 0)r.sizingParam=t.sizingParam;if(t.leverageMode!==void 0)r.leverageMode=t.leverageMode;if(t.fixedLeverage!==void 0)r.fixedLeverage=t.fixedLeverage;if(t.slPct!==void 0)r.slPct=t.slPct;if(t.tradingPairIds!==void 0)r.markets={tradingPairIds:t.tradingPairIds};if(t.copyExisting!==void 0)r.copyExisting=t.copyExisting;return await this.makeAuthenticatedRequest(`${Hi}/follows`,{method:"POST",body:JSON.stringify(r)})}async previewFollow(e){let t=te(iq,e),r={leader:t.leader,allocation:t.allocation};if(t.marginModePolicy!==void 0)r.marginModePolicy=t.marginModePolicy;if(t.sizingMode!==void 0)r.sizingMode=t.sizingMode;if(t.sizingParam!==void 0)r.sizingParam=t.sizingParam;if(t.leverageMode!==void 0)r.leverageMode=t.leverageMode;if(t.fixedLeverage!==void 0)r.fixedLeverage=t.fixedLeverage;if(t.tradingPairIds!==void 0)r.markets={tradingPairIds:t.tradingPairIds};return await this.makeAuthenticatedRequest(`${Hi}/follows/preview`,{method:"POST",body:JSON.stringify(r)})}async stopFollow(e){return await this.makeAuthenticatedRequest(`${_h(e)}/stop`,{method:"POST"})}async closeFollowPositions(e){return await this.makeAuthenticatedRequest(`${_h(e)}/close-positions`,{method:"POST"})}async closeAllCopyPositions(){return await this.makeAuthenticatedRequest(`${Hi}/follows/close-positions`,{method:"POST"})}async addFollowPositionMargin(e){let{followId:t,tradingPairId:r,amount:n}=te(sq,e),o={tradingPairId:r,amount:n};return await this.makeAuthenticatedRequest(`${_h(t)}/position-margin`,{method:"POST",body:JSON.stringify(o)})}async listMyFollows(e={}){let{pageSize:t,pageToken:r}=te(uq,e);return await this.makeAuthenticatedRequest(`${Hi}/follows${Wx({pageSize:t,pageToken:r})}`,{method:"GET"})}async getFollow(e){return await this.makeAuthenticatedRequest(_h(e),{method:"GET"})}async listFollowLeaderPositions(e){return await this.makeAuthenticatedRequest(`${_h(e)}/leader-positions`,{method:"GET"})}}class HI extends Ye{async upsertDelegatedAgent(e){return this.makeAuthenticatedRequest(ue.delegatedAgents.list(),{method:"POST",body:JSON.stringify({agentAddress:e.agentAddress,name:e.name,expiresAt:e.expiresAt,allowedActions:e.allowedActions,allowedTradingPairIds:e.allowedTradingPairIds,allowedMarginAccountIds:e.allowedMarginAccountIds,allowedOrderTypes:e.allowedOrderTypes,allowedTimeInForce:e.allowedTimeInForce,maxLeverage:e.maxLeverage,maxOrderNotional:e.maxOrderNotional,maxOpenOrders:e.maxOpenOrders,ipAllowlist:e.ipAllowlist})})}async listDelegatedAgents(){return this.makeAuthenticatedRequest(ue.delegatedAgents.list())}async listDelegatedOwners(){return this.makeAuthenticatedRequest(ue.delegatedAgents.owners())}async revokeDelegatedAgent(e){return this.makeAuthenticatedRequest(ue.delegatedAgents.byId(e),{method:"DELETE"})}async createDelegatedSession(e){return this.makeAuthenticatedRequest(ue.delegatedAgents.sessions(),{method:"POST",body:JSON.stringify({ownerUserId:e.ownerUserId,sessionPublicKey:e.sessionPublicKey})})}}class Yx extends Ye{async mint(e){return await this.makeAuthenticatedRequest(ue.faucet.mint(),{method:"POST",body:JSON.stringify({turnstileToken:e.turnstileToken})})}async getInfo(){return await this.makeAuthenticatedRequest(ue.faucet.info(),{method:"GET"})}}class Jx extends Ye{async simulateFees(e){let t=te(PI,e),r=new URLSearchParams;if(r.append("tradingPairId",t.tradingPairId),r.append("side",t.side),r.append("price",t.price),r.append("quantity",t.quantity),t.orderType!==void 0)r.append("orderType",t.orderType);if(t.slippageToleranceBps!==void 0)r.append("slippageToleranceBps",String(t.slippageToleranceBps));let n=`/api/v1/fees/simulate?${r.toString()}`;return await this.makeAuthenticatedRequest(n,{method:"GET"})}async getMyFeeTier(e){let t=te(AI,e),r=new URLSearchParams;r.append("tradingPairId",t.tradingPairId);let n=`/api/v1/fees/tier?${r.toString()}`;return await this.makeAuthenticatedRequest(n,{method:"GET"})}}class GI extends Ye{async listAssignments(e={}){te(dq,e);let t=new URLSearchParams;if(e.pageSize!==void 0)t.set("pageSize",String(e.pageSize));if(e.pageToken!==void 0)t.set("pageToken",e.pageToken);return this.makeAuthenticatedRequest(`/api/v1/managed-markets/assignments${t.size?`?${t}`:""}`)}async claimLease(e,t){return this.makeAuthenticatedRequest(`/api/v1/managed-markets/${encodeURIComponent(e)}/lease`,{method:"POST",body:JSON.stringify(t)})}async refreshQuotes(e,t){return this.makeAuthenticatedRequest(`/api/v1/managed-markets/${encodeURIComponent(e)}/quotes`,{method:"POST",body:JSON.stringify(t)})}}class Qx extends Ye{async createMarginSubAccount(e){return te(Aq,{request:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.createSubAccount(),{method:"POST",body:JSON.stringify({subaccountKey:e.subaccountKey,label:e.label})})}async closeMarginSubAccount(e){return te(Iq,{marginAccountId:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.closeSubAccount(e),{method:"POST",body:JSON.stringify({})})}async getMarginAccountPnl(e){return te(kq,{marginAccountId:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.pnl(e))}async transferMarginCollateral(e){return te(Rq,{request:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.transferCollateral(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount,from:e.from,to:e.to})})}async transferCollateralToSubAccount(e,t){return te(UI,{marginAccountId:e,amount:t}),await this.makeAuthenticatedRequest(ue.marginAccounts.subAccountTransferIn(e),{method:"POST",body:JSON.stringify({amount:t})})}async transferCollateralFromSubAccount(e,t){return te(UI,{marginAccountId:e,amount:t}),await this.makeAuthenticatedRequest(ue.marginAccounts.subAccountTransferOut(e),{method:"POST",body:JSON.stringify({amount:t})})}async listMarginAccounts(e){if(e)te(fq,e);return await this.makeAuthenticatedRequest(ue.marginAccounts.list(e?{pageSize:e.pageSize,pageToken:e.pageToken,state:e.state,tradingPairId:e.tradingPairId}:void 0))}async getMarginAccountSummary(e,t){return te(mq,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(ue.marginAccounts.summary(e,{tradingPairId:t?.tradingPairId}))}async getParentMarginAccountSummary(e){return te(hq,e),await this.makeAuthenticatedRequest(ue.marginAccounts.parentSummary({tradingPairId:e?.tradingPairId}))}async getAvailableCollateral(e){return te(gq,e),await this.makeAuthenticatedRequest(ue.marginAccounts.availableCollateral(e))}async transferCollateralToMarginAccount(e,t){return te(BI,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ue.marginAccounts.transferIn(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey})})}async transferCollateralToParentMarginAccount(e){return te(bq,{request:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.transferInParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async transferCollateralToRiskBucket(e){return te(xq,{request:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.transferInRiskBucket(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount,tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,marginAccountId:e.marginAccountId,applyToPositionMargin:e.applyToPositionMargin})})}async transferCollateralFromMarginAccount(e,t){return te(BI,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ue.marginAccounts.transferOut(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey,marginMode:t.marginMode})})}async transferCollateralFromParentMarginAccount(e){return te(wq,{request:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.transferOutParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async getMarginAccountMovements(e,t){return te(Sq,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(ue.marginAccounts.movements(e,t))}async getParentMarginAccountMovements(e){return te(_q,e),await this.makeAuthenticatedRequest(ue.marginAccounts.parentMovements(e))}async simulateOrderRisk(e,t){return te(vq,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ue.marginAccounts.simulateOrderRisk(e),{method:"POST",body:JSON.stringify({tradingPairId:t.tradingPairId,side:t.side,positionSide:t.positionSide,orderType:t.orderType,price:t.price,quantity:t.quantity,leverage:t.leverage,reduceOnly:t.reduceOnly,slippageToleranceBps:t.slippageToleranceBps})})}async simulateParentMarginOrderRisk(e){return te(Eq,{request:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.simulateParentMarginOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly,slippageToleranceBps:e.slippageToleranceBps})})}async simulateRiskBucketOrderRisk(e){return te(Pq,{request:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.simulateRiskBucketOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,marginAccountId:e.marginAccountId,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly,slippageToleranceBps:e.slippageToleranceBps})})}}class Xx extends Ye{async getPaginatedTradingPairs(e){let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.marketType)t.append("marketType",e.marketType);if(e?.baseToken)t.append("baseToken",e.baseToken);if(e?.quoteToken)t.append("quoteToken",e.quoteToken);if(e?.isActive!==void 0)t.append("isActive",e.isActive.toString());if(e?.category)t.append("category",e.category);let r=t.toString(),n=r?`/api/v1/market/pairs?${r}`:"/api/v1/market/pairs";return await this.makePublicRequest(n)}async getTradingPair(e){return te(qi,{tradingPairId:e}),(await this.makePublicRequest(ue.market.getTradingPair(e))).tradingPair}async getTradingPairBySymbol(e,t){return(await this.getPaginatedTradingPairs({pageSize:100,marketType:t})).tradingPairs.find((n)=>n.symbol===e)}async getCandlesticks(e,t,r){te(Oq,{tradingPairId:e,interval:t,startTime:r?.startTime,endTime:r?.endTime,limit:r?.limit,priceType:r?.priceType});let n=new URLSearchParams;if(r?.startTime!==void 0)n.append("startTime",r.startTime.toString());if(r?.endTime!==void 0)n.append("endTime",r.endTime.toString());if(r?.limit!==void 0)n.append("limit",r.limit.toString());if(r?.priceType!==void 0)n.append("priceType",r.priceType);let o=n.toString(),i=o?`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}?${o}`:`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}`;return(await this.makePublicRequest(i)).data||[]}async getMarketMetadata(e){return te(qi,{tradingPairId:e}),await this.makePublicRequest(ue.market.getMarketMetadata(e))}async getPerpMarketConfig(e){return te(qi,{tradingPairId:e}),await this.makePublicRequest(ue.market.getPerpMarketConfig(e))}async getPerpMarketSummary(e){return te(qi,{tradingPairId:e}),await this.makePublicRequest(ue.market.getPerpMarketSummary(e))}async getMarkPrice(e){return te(qi,{tradingPairId:e}),await this.makePublicRequest(ue.market.getMarkPrice(e))}async getIndexPrice(e){return te(qi,{tradingPairId:e}),await this.makePublicRequest(ue.market.getIndexPrice(e))}async getFundingState(e){return te(qi,{tradingPairId:e}),await this.makePublicRequest(ue.market.getFundingState(e))}async listFundingHistory(e,t){return te(qi,{tradingPairId:e}),te(Nq,t??{}),await this.makePublicRequest(ue.market.listFundingHistory(e,t))}async listAllFundingHistory(e){return te($q,e??{}),await this.makePublicRequest(ue.market.listAllFundingHistory(e))}async getOpenInterest(e){return te(qi,{tradingPairId:e}),await this.makePublicRequest(ue.market.getOpenInterest(e))}async getScreener(e){return await this.makePublicRequest(ue.market.getScreener(e))}async getMarketStats(){return await this.makePublicRequest(ue.market.getMarketStats())}}class ew extends Ye{async getOrderbook(e,t={}){let{depth:r=10,tradingMode:n,magnitude:o,denomination:i}=t,s=new URLSearchParams;if(s.set("levels",String(r)),n)s.set("tradingMode",n);if(o!==void 0)s.set("magnitude",String(o));if(i)s.set("denomination",i.toLowerCase());let a=await this.makePublicRequest(`/api/v1/orderbook/${encodeURIComponent(e)}?${s.toString()}`);return{tradingPairId:a.tradingPairId,tradingMode:a.tradingMode,bids:a.data.bids.map((c)=>({price:c.price,quantity:c.quantity,orderCount:c.orderCount})),asks:a.data.asks.map((c)=>({price:c.price,quantity:c.quantity,orderCount:c.orderCount})),bestBid:a.data.bestBid,bestAsk:a.data.bestAsk,bidVolume:a.data.bidVolume,askVolume:a.data.askVolume,baseDecimals:a.baseDecimals,quoteDecimals:a.quoteDecimals,timestamp:a.timestamp,sequence:a.sequenceNumber}}}class Th extends Ye{async getMyTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/tradercodes/codes/me",{method:"GET"})}async setTraderCode(e){let t=te(II,{code:e});return await this.makeAuthenticatedRequest("/api/v1/tradercodes/codes/me/custom",{method:"PUT",body:JSON.stringify({code:t.code})})}async clearTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/tradercodes/codes/me/custom",{method:"DELETE"})}async checkTraderCodeAvailability(e){let t=new URLSearchParams({code:e.trim()}).toString(),r=await this.makePublicRequest(`/api/v1/tradercodes/codes/available?${t}`,{method:"GET"});return{available:r.available,reason:r.reason?r.reason:void 0}}async getTraderCodeInfo(e){let t=encodeURIComponent(e.trim());return await this.makePublicRequest(`/api/v1/tradercodes/codes/${t}`,{method:"GET"})}async getRewardsBalance(){return await this.makeAuthenticatedRequest("/api/v1/tradercodes/rewards/balance",{method:"GET"})}async transferRewards(e){let t=te(kI,e);return await this.makeAuthenticatedRequest("/api/v1/tradercodes/rewards/transfer",{method:"POST",body:JSON.stringify({token:t.token,amount:t.amount})})}async getMyReferralPosition(){return await this.makeAuthenticatedRequest("/api/v1/tradercodes/referrals/me",{method:"GET"})}async getMyReferralDownline(e){if(e)te(RI,e);let t=new URLSearchParams;if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.pageToken!==void 0)t.append("pageToken",e.pageToken);let r=t.toString(),n=r?`/api/v1/tradercodes/referrals/me/downline?${r}`:"/api/v1/tradercodes/referrals/me/downline";return await this.makeAuthenticatedRequest(n,{method:"GET"})}async getMyReferralTree(e){if(e)te(CI,e);let t=new URLSearchParams;if(e?.parent!==void 0)t.append("parent",e.parent);if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.pageToken!==void 0)t.append("pageToken",e.pageToken);let r=t.toString(),n=r?`/api/v1/tradercodes/referrals/me/tree?${r}`:"/api/v1/tradercodes/referrals/me/tree";return await this.makeAuthenticatedRequest(n,{method:"GET"})}}var vh="/api/v1/accounts/me/portfolio";function tw(e,t){if(!t?.period)return e;return`${e}?${new URLSearchParams({period:t.period})}`}class rw extends Ye{async getSummary(e){return await this.makeAuthenticatedRequest(tw(`${vh}/summary`,e))}async getPerformance(e){return await this.makeAuthenticatedRequest(tw(`${vh}/performance`,e))}async getRealizedPnl(e){return await this.makeAuthenticatedRequest(tw(`${vh}/realized-pnl`,e))}async getAssets(e){return await this.makeAuthenticatedRequest(tw(`${vh}/assets`,e))}async getMargin(e){let t=new URLSearchParams;if(e?.marginAccountId)t.set("marginAccountId",e.marginAccountId);if(e?.includeAccounts!==void 0)t.set("includeAccounts",String(e.includeAccounts));let r=t.toString(),n=r?`?${r}`:"";return await this.makeAuthenticatedRequest(`${vh}/margin${n}`)}}class nw extends Ye{async listPositions(e){if(e)te(Dq,e);return await this.makeAuthenticatedRequest(ue.positions.list(e))}async getPosition(e){return te(Fq,{positionId:e}),await this.makeAuthenticatedRequest(ue.positions.get(e))}async closePosition(e,t){return te(Uq,{positionId:e,request:t}),await this.makeAuthenticatedRequest(ue.positions.close(e),{method:"POST",body:JSON.stringify({closeType:t.closeType,limitPrice:t.limitPrice,slippageToleranceBps:t.slippageToleranceBps,quantity:t.quantity})})}async batchCloseAllPositions(e){if(e)te(jq,e);return await this.makeAuthenticatedRequest(ue.positions.batchCloseAll(),{method:"POST",body:JSON.stringify({tradingPairId:e?.tradingPairId,tradingPairIds:e?.tradingPairIds,side:e?.side,slippageToleranceBps:e?.slippageToleranceBps})})}async getPositionRisk(e){return te(qq,{positionId:e}),await this.makeAuthenticatedRequest(ue.positions.risk(e))}async attachPositionTpSl(e,t){return te(Hq,{positionId:e,request:t}),await this.makeAuthenticatedRequest(ue.positions.attachTpSl(e),{method:"POST",body:JSON.stringify({takeProfit:t.takeProfit?{triggerPrice:t.takeProfit.triggerPrice,orderType:t.takeProfit.orderType,limitPrice:t.takeProfit.limitPrice,quantity:t.takeProfit.quantity,closePosition:t.takeProfit.closePosition,timeInForce:t.takeProfit.timeInForce,slippageToleranceBps:t.takeProfit.slippageToleranceBps,expiresAt:t.takeProfit.expiresAt}:void 0,stopLoss:t.stopLoss?{triggerPrice:t.stopLoss.triggerPrice,orderType:t.stopLoss.orderType,limitPrice:t.stopLoss.limitPrice,quantity:t.stopLoss.quantity,closePosition:t.stopLoss.closePosition,timeInForce:t.stopLoss.timeInForce,slippageToleranceBps:t.stopLoss.slippageToleranceBps,expiresAt:t.stopLoss.expiresAt}:void 0,trailingStop:t.trailingStop?{trailBps:t.trailingStop.trailBps,activationPrice:t.trailingStop.activationPrice,quantity:t.trailingStop.quantity,closePosition:t.trailingStop.closePosition,slippageToleranceBps:t.trailingStop.slippageToleranceBps,expiresAt:t.trailingStop.expiresAt}:void 0,oco:t.oco})})}async listPositionHistory(e){if(e)te(Gq,e);return await this.makeAuthenticatedRequest(ue.positions.history(e))}async getPositionPnlHistory(e,t){return te(Vq,{positionId:e,params:t}),await this.makeAuthenticatedRequest(ue.positions.pnlHistory(e,t))}}class VI extends Ye{async getProfile(){return await this.makeAuthenticatedRequest("/api/v1/accounts/me")}async getPaginatedUserMovements(e){if(e)te(Wq,e);let t=new URLSearchParams;if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.pageToken!==void 0)t.append("pageToken",e.pageToken);if(e?.orderBy!==void 0)t.append("orderBy",e.orderBy);if(e?.entryType!==void 0)t.append("entryType",e.entryType);if(e?.transactionType!==void 0)t.append("transactionType",e.transactionType);if(e?.assetId!==void 0)t.append("assetId",e.assetId);let r=t.toString(),n=r?`/api/v1/accounts/movements?${r}`:"/api/v1/accounts/movements";return await this.makeAuthenticatedRequest(n)}async getUserBalances(e){if(e)te(Yq,e);let t=new URLSearchParams;if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.pageToken!==void 0)t.append("pageToken",e.pageToken);let r=t.toString(),n=r?`/api/v1/accounts/balances?${r}`:"/api/v1/accounts/balances";return await this.makeAuthenticatedRequest(n)}async getUserBalanceByAssetId(e){if(!e||e.trim()==="")throw new sr("assetId is required and cannot be empty",{endpoint:"/api/v1/accounts/balances/{assetId}"});let t=`/api/v1/accounts/balances/${e}`;return await this.makeAuthenticatedRequest(t)}async getPortfolioStats(e){let t=new URLSearchParams({period:e});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio?${t}`)}async getPortfolioChart(e,t){let r=new URLSearchParams({period:e,metric:t});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio/chart?${r}`)}async getUserTrades(e){if(e)te(Kq,e);let t=new URLSearchParams;if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.tradingPairId!==void 0)t.append("tradingPairId",e.tradingPairId);t.append("pageToken",e?.pageToken??"");let r=t.toString(),n=r?`/api/v1/accounts/trades?${r}`:"/api/v1/accounts/trades";return await this.makeAuthenticatedRequest(n)}async*iterateUserTrades(e){let t="";for(;;){let r=await this.getUserTrades({...e,pageToken:t});if(yield*r.trades,!r.nextPageToken)return;t=r.nextPageToken}}async listFundingPayments(e){if(e)te(Jq,e);let t=new URLSearchParams;if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.pageToken!==void 0)t.append("pageToken",e.pageToken);if(e?.tradingPairId!==void 0)t.append("tradingPairId",e.tradingPairId);if(e?.positionId!==void 0)t.append("positionId",e.positionId);if(e?.marginAccountId!==void 0)t.append("marginAccountId",e.marginAccountId);let r=t.toString(),n=r?`/api/v1/accounts/funding-payments?${r}`:"/api/v1/accounts/funding-payments";return await this.makeAuthenticatedRequest(n)}async getSelfTradePreventionDefault(){return await this.makeAuthenticatedRequest("/api/v1/accounts/self-trade-prevention")}async setSelfTradePreventionDefault(e){let t=te(Zq,{mode:e});return await this.makeAuthenticatedRequest("/api/v1/accounts/self-trade-prevention",{method:"PUT",body:JSON.stringify(t)})}}class ow extends Ye{async getPulse(){return await this.makePublicRequest("/api/v1/pulse",{method:"GET"})}}class iw extends Ye{async list(){return await this.makeAuthenticatedRequest(ue.subAccounts.list())}async createLimit(e){return await this.makeAuthenticatedRequest(ue.subAccounts.createLimit(),{method:"POST",body:JSON.stringify(e)})}async getLimits(e){return await this.makeAuthenticatedRequest(ue.subAccounts.getLimits(e))}async updateLimit(e,t,r){return await this.makeAuthenticatedRequest(ue.subAccounts.limit(e,t),{method:"PUT",body:JSON.stringify(r)})}async deleteLimit(e,t){await this.makeAuthenticatedRequest(ue.subAccounts.limit(e,t),{method:"DELETE"})}}function ome(e){if(e==="spot")return"SPOT";if(e==="margin")return"MARGIN";throw new Bt(`Invalid deposit target: ${JSON.stringify(e)}. Expected "spot" or "margin".`)}class sw extends Ye{async register(e={}){let{depositTarget:t,...r}=e,n=t===void 0?r:{...r,depositTarget:ome(t)};return await this.makeAuthenticatedRequest(ue.sweeper.register(),{method:"POST",body:JSON.stringify(n)})}async getChains(){return await this.makePublicRequest(ue.sweeper.chains(),{method:"GET"})}}function o7(e){return{eventType:"trade",tradingPairId:e.tradingPairId,tradingMode:e.tradingMode.toUpperCase(),data:{tradeId:e.data.tradeId,price:e.data.price,quantity:e.data.quantity,makerSide:e.data.makerSide.toUpperCase(),executedAt:e.data.executedAt??""}}}class ZI extends Ye{async getTrades(e,t={}){te(zq,t);let r=new URLSearchParams;if(t.pageSize!=null)r.set("pageSize",String(t.pageSize));if(t.pageToken!=null&&t.pageToken!=="")r.set("pageToken",t.pageToken);let n=r.toString(),o=await this.makePublicRequest(`/api/v1/trades/${encodeURIComponent(e)}${n===""?"":`?${n}`}`);return{trades:(o.trades??[]).map(o7),nextPageToken:o.nextPageToken??""}}async getTradeById(e){let t=await this.makePublicRequest(ue.trades.byId(e));return o7(t)}}function aw(e){if(!e)return;return{triggerPrice:e.triggerPrice,orderType:e.orderType,limitPrice:e.limitPrice,timeInForce:e.timeInForce,slippageToleranceBps:e.slippageToleranceBps,expiresAt:e.expiresAt,quantity:e.quantity,closePosition:e.closePosition}}function i7(e){if(!e)return;return{trailBps:e.trailBps,activationPrice:e.activationPrice,quantity:e.quantity,closePosition:e.closePosition,slippageToleranceBps:e.slippageToleranceBps,expiresAt:e.expiresAt}}class cw extends Ye{async placeLimitOrder(e,t,r,n,o){te(Dj,{tradingPairId:e,side:t,quantity:r,price:n,options:o});let i={tradingPairId:e,orderType:"LIMIT",side:t,price:n,quantity:r,tradingMode:o?.tradingMode||"SPOT",useMasterBalance:o?.useMasterBalance,expirationDate:o?.expirationDate,timeInForce:o?.timeInForce,marginAccountId:o?.marginAccountId,marginMode:o?.marginMode,riskBucketId:o?.riskBucketId,riskBucketCollateral:o?.riskBucketCollateral,strategyKey:o?.strategyKey,positionSide:o?.positionSide,leverage:o?.leverage,reduceOnly:o?.reduceOnly,postOnly:o?.postOnly,selfTradePreventionMode:o?.selfTradePreventionMode,clientOrderId:o?.clientOrderId,idempotencyKey:o?.idempotencyKey===void 0?crypto.randomUUID():o.idempotencyKey,takeProfit:aw(o?.takeProfit),stopLoss:aw(o?.stopLoss),trailingStop:i7(o?.trailingStop)};return await this.makeAuthenticatedRequest(ue.orders.create(),{method:"POST",body:JSON.stringify(i)})}async placeMarketOrder(e,t,r,n){te(Fj,{tradingPairId:e,side:t,quantity:r,options:n});let o={tradingPairId:e,orderType:"MARKET",side:t,slippageToleranceBps:n?.slippageTolerance!==void 0?Math.round(n.slippageTolerance*1e4):void 0,price:null,quantity:r,tradingMode:n?.tradingMode||"SPOT",marginAccountId:n?.marginAccountId,marginMode:n?.marginMode,riskBucketId:n?.riskBucketId,riskBucketCollateral:n?.riskBucketCollateral,strategyKey:n?.strategyKey,positionSide:n?.positionSide,leverage:n?.leverage,reduceOnly:n?.reduceOnly,selfTradePreventionMode:n?.selfTradePreventionMode,takeProfit:aw(n?.takeProfit),stopLoss:aw(n?.stopLoss),trailingStop:i7(n?.trailingStop),clientOrderId:n?.clientOrderId,idempotencyKey:n?.idempotencyKey===void 0?crypto.randomUUID():n.idempotencyKey};return await this.makeAuthenticatedRequest(ue.orders.create(),{method:"POST",body:JSON.stringify(o)})}async cancelOrder(e,t){te(Uj,{orderId:e,remainingQuantityTarget:t?.remainingQuantityTarget});let r={orderId:e,...t?.remainingQuantityTarget!==void 0&&{remainingQuantityTarget:t.remainingQuantityTarget}};return await this.makeAuthenticatedRequest(ue.orders.cancel(),{method:"POST",body:JSON.stringify(r)})}async cancelConditionalOrder(e){return te(zI,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(ue.orders.cancelConditional(e),{method:"DELETE"})}async getConditionalOrder(e){return te(zI,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(ue.orders.getConditional(e),{method:"GET"})}async listConditionalOrders(e){if(e)te(Gj,e);let{pageSize:t=20,marginAccountId:r,tradingPairId:n,state:o,pageToken:i}=e||{},s=Math.min(Math.max(t,1),1000);return await this.makeAuthenticatedRequest(ue.orders.listConditional({marginAccountId:r,tradingPairId:n,state:o,pageSize:s,pageToken:i??""}),{method:"GET"})}async batchCancel(e){if(!e||e.length===0)throw Error("orderIds is required and must not be empty");return this.makeAuthenticatedRequest(ue.orders.batchCancel(),{method:"POST",body:JSON.stringify({orderIds:e})})}async batchCancelAll(e){let t=e?ue.orders.batchCancelAllByPair(e):ue.orders.batchCancelAll();return this.makeAuthenticatedRequest(t,{method:"POST"})}async replaceOrder(e,t){te(jj,{orderId:e,newOrder:t});let r={useMasterBalance:t.useMasterBalance??!1};if(t.price!==void 0)r.price=t.price;if(t.quantity!==void 0)r.quantity=t.quantity;if(t.postOnly!==void 0)r.postOnly=t.postOnly;if(t.selfTradePreventionMode!==void 0)r.selfTradePreventionMode=t.selfTradePreventionMode;if(t.clientOrderId!==void 0)r.clientOrderId=t.clientOrderId;return await this.makeAuthenticatedRequest(ue.orders.replace(e),{method:"PUT",body:JSON.stringify(r)})}async batchCreate(e){te(Kj,{orders:e});let t={orders:e.map((r)=>({tradingPairId:r.tradingPairId,orderType:r.orderType,side:r.side,price:r.price,quantity:r.quantity,tradingMode:r.tradingMode||"SPOT",slippageToleranceBps:r.slippageTolerance!==void 0?Math.round(r.slippageTolerance*1e4):void 0,useMasterBalance:r.useMasterBalance,expirationDate:r.expirationDate,timeInForce:r.timeInForce,marginAccountId:r.marginAccountId,marginMode:r.marginMode,riskBucketId:r.riskBucketId,riskBucketCollateral:r.riskBucketCollateral,strategyKey:r.strategyKey,positionSide:r.positionSide,leverage:r.leverage,reduceOnly:r.reduceOnly,postOnly:r.postOnly,selfTradePreventionMode:r.selfTradePreventionMode,clientOrderId:r.clientOrderId,idempotencyKey:r.idempotencyKey===void 0?crypto.randomUUID():r.idempotencyKey}))};return this.makeAuthenticatedRequest(ue.orders.batchCreate(),{method:"POST",body:JSON.stringify(t)})}async batchReplace(e){te(Yj,{orders:e});let t={orders:e.map((r)=>({orderId:r.orderId,price:r.price,quantity:r.quantity,useMasterBalance:r.useMasterBalance,postOnly:r.postOnly,selfTradePreventionMode:r.selfTradePreventionMode,clientOrderId:r.clientOrderId}))};return this.makeAuthenticatedRequest(ue.orders.batchReplace(),{method:"POST",body:JSON.stringify(t)})}async getPaginatedOrders(e){if(e)te(qj,e);let{pageSize:t=10,status:r,tradingPairId:n,tradingMode:o,marginAccountId:i,pageToken:s}=e||{},a=t>0?t:10,c=Math.min(a,1000),l=new URLSearchParams;l.append("pageSize",c.toString());let d=typeof r==="string"?r:r?.join(",");if(d)l.append("status",d);if(n)l.append("tradingPairId",n);if(o)l.append("tradingMode",o);if(i)l.append("marginAccountId",i);l.append("pageToken",s??"");let f=`/api/v1/orders?${l.toString()}`;return await this.makeAuthenticatedRequest(f,{method:"GET"})}async*iterateOrders(e){let t="";for(;;){let r=await this.getPaginatedOrders({...e,pageToken:t});if(yield*r.orders,!r.nextPageToken)return;t=r.nextPageToken}}async getOrder(e){return{order:await this.makeAuthenticatedRequest(ue.orders.get(e),{method:"GET"}),status:"SUCCESS"}}async createTwapOrder(e,t,r,n){te(Vj,{tradingPairId:e,side:t,quantity:r,options:n});let o={tradingPairId:e,side:t,quantity:r,durationSeconds:n.durationSeconds!==void 0?Number(n.durationSeconds):void 0,startTime:n.startTime,endTime:n.endTime,limitPrice:n.limitPrice,slippageToleranceBps:n.slippageToleranceBps,randomize:n.randomize,reduceOnly:n.reduceOnly,tradingMode:n.tradingMode||"SPOT",marginAccountId:n.marginAccountId,riskBucketId:n.riskBucketId,marginMode:n.marginMode,leverage:n.leverage,strategyKey:n.strategyKey,useMasterBalance:n.useMasterBalance,clientTwapId:n.clientTwapId,executionStyle:n.executionStyle,triggerPrice:n.triggerPrice,triggerDirection:n.triggerDirection,conditionalExpiry:n.conditionalExpiry};return await this.makeAuthenticatedRequest(ue.orders.createTwap(),{method:"POST",body:JSON.stringify(o)})}async cancelTwapOrder(e){return te(Dx,{twapOrderId:e}),await this.makeAuthenticatedRequest(ue.orders.cancelTwap(e),{method:"POST"})}async getTwapOrder(e){return te(Dx,{twapOrderId:e}),await this.makeAuthenticatedRequest(ue.orders.getTwap(e),{method:"GET"})}async getTwapOrderTca(e){return te(Dx,{twapOrderId:e}),await this.makeAuthenticatedRequest(ue.orders.getTwapTca(e),{method:"GET"})}async listTwapOrders(e){if(e)te(Zj,e);let{pageSize:t=20,state:r,tradingPairId:n,pageToken:o}=e||{},i=Math.min(Math.max(t,1),1000);return await this.makeAuthenticatedRequest(ue.orders.listTwap({state:r,tradingPairId:n,pageSize:i,pageToken:o??""}),{method:"GET"})}async listTwapOrderSlices(e,t){te(Wj,{...t,twapOrderId:e});let{orderBy:r,pageSize:n=20,pageToken:o}=t||{};return await this.makeAuthenticatedRequest(ue.orders.listTwapSlices(e,{orderBy:r,pageSize:n,pageToken:o??""}),{method:"GET"})}}var WI=[{inputs:[{internalType:"address",name:"factory_",type:"address"},{internalType:"address",name:"unwrapHelper_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"BridgeFeeTooHigh",type:"error"},{inputs:[],name:"ChainNotConfigured",type:"error"},{inputs:[],name:"ComposeNotSupported",type:"error"},{inputs:[],name:"ComposeSourceMismatch",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"NativeNotAccepted",type:"error"},{inputs:[],name:"NativeTransferFailed",type:"error"},{inputs:[],name:"NoRoute",type:"error"},{inputs:[],name:"NotExecutor",type:"error"},{inputs:[],name:"NotHub",type:"error"},{inputs:[],name:"NotRemote",type:"error"},{inputs:[],name:"NothingToSweep",type:"error"},{inputs:[],name:"OftCannotUnwrap",type:"error"},{inputs:[],name:"OnlyClone",type:"error"},{inputs:[],name:"QuoteNotBound",type:"error"},{inputs:[],name:"RoutedToken",type:"error"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"SafeERC20FailedOperation",type:"error"},{inputs:[],name:"StaleQuote",type:"error"},{inputs:[],name:"SweepParamsRequired",type:"error"},{inputs:[],name:"UnexpectedBridgeDebit",type:"error"},{inputs:[],name:"UnexpectedParams",type:"error"},{inputs:[],name:"UnexpectedValue",type:"error"},{inputs:[],name:"UnswapPathMissing",type:"error"},{inputs:[],name:"UntrustedComposeCaller",type:"error"},{inputs:[],name:"UntrustedComposeSource",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amountIn",type:"uint256"},{indexed:!1,internalType:"address",name:"bridgeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"amountBridged",type:"uint256"},{indexed:!1,internalType:"address",name:"destination",type:"address"}],name:"Bridged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Refunded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"RefundedNative",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Swept",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"tokenIn",type:"address"},{indexed:!0,internalType:"address",name:"tokenOut",type:"address"},{indexed:!1,internalType:"uint256",name:"amountIn",type:"uint256"},{indexed:!1,internalType:"uint256",name:"amountOut",type:"uint256"}],name:"Unswapped",type:"event"},{inputs:[],name:"config",outputs:[{internalType:"address",name:"user",type:"address"},{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"hubToken",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{internalType:"contract ISweeperFactory",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"bytes32",name:"",type:"bytes32"},{internalType:"bytes",name:"message",type:"bytes"},{internalType:"address",name:"",type:"address"},{internalType:"bytes",name:"",type:"bytes"}],name:"lzCompose",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{components:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"minSwapOut",type:"uint256"},{internalType:"uint256",name:"minBridgeOut",type:"uint256"},{internalType:"bytes",name:"lzExtraOptions",type:"bytes"}],internalType:"struct SweepParams",name:"params",type:"tuple"}],name:"sweep",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"address",name:"feeRefundAddress",type:"address"}],name:"sweepWithRefund",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"unwrapHelper",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{stateMutability:"payable",type:"receive"}];var KI=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{inputs:[{internalType:"address",name:"target",type:"address"}],name:"AddressEmptyCode",type:"error"},{inputs:[],name:"CloneArgumentsTooLong",type:"error"},{inputs:[],name:"Create2EmptyBytecode",type:"error"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"ERC1967InvalidImplementation",type:"error"},{inputs:[],name:"ERC1967NonPayable",type:"error"},{inputs:[],name:"FailedCall",type:"error"},{inputs:[],name:"FailedDeployment",type:"error"},{inputs:[],name:"ImplementationNotSet",type:"error"},{inputs:[{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"InvalidFeeCap",type:"error"},{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[],name:"NotExecutor",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{inputs:[],name:"UUPSUnauthorizedCallContext",type:"error"},{inputs:[{internalType:"bytes32",name:"slot",type:"bytes32"}],name:"UUPSUnsupportedProxiableUUID",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousExecutor",type:"address"},{indexed:!0,internalType:"address",name:"newExecutor",type:"address"}],name:"ExecutorUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"rollup",type:"address"},{indexed:!1,internalType:"address",name:"bridgedStable",type:"address"},{indexed:!1,internalType:"address",name:"swapRouter",type:"address"},{indexed:!1,internalType:"address",name:"lzEndpoint",type:"address"}],name:"HubConfigured",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferStarted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint16",name:"previousCapBps",type:"uint16"},{indexed:!1,internalType:"uint16",name:"newCapBps",type:"uint16"}],name:"PermissionlessBridgeFeeCapUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"swapRouter",type:"address"},{indexed:!1,internalType:"uint32",name:"cctpDestinationDomain",type:"uint32"},{indexed:!1,internalType:"uint32",name:"stargateDestinationEid",type:"uint32"}],name:"RemoteConfigured",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"uint32",name:"dstEid",type:"uint32"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],indexed:!1,internalType:"struct BridgeRoute",name:"route",type:"tuple"}],name:"RouteSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"sweeper",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"string",name:"applicationId",type:"string"},{indexed:!1,internalType:"address",name:"hubToken",type:"address"}],name:"SweeperDeployed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousImplementation",type:"address"},{indexed:!0,internalType:"address",name:"newImplementation",type:"address"}],name:"SweeperImplementationUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"stargate",type:"address"},{indexed:!1,internalType:"address",name:"token",type:"address"}],name:"TrustedStargateSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"hubToken",type:"address"},{indexed:!1,internalType:"bytes",name:"path",type:"bytes"}],name:"UnswapPathSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{inputs:[],name:"UPGRADE_INTERFACE_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"acceptOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"bridgedStable",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"cctpDestinationDomain",outputs:[{internalType:"uint32",name:"",type:"uint32"}],stateMutability:"view",type:"function"},{inputs:[],name:"chainMode",outputs:[{internalType:"enum ChainMode",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"rollup_",type:"address"},{internalType:"address",name:"bridgedStable_",type:"address"},{internalType:"address",name:"swapRouter_",type:"address"},{internalType:"address",name:"lzEndpoint_",type:"address"}],name:"configureHub",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"swapRouter_",type:"address"},{internalType:"uint32",name:"cctpDestinationDomain_",type:"uint32"},{internalType:"uint32",name:"stargateDestinationEid_",type:"uint32"}],name:"configureRemote",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"deploy",outputs:[{internalType:"address",name:"sweeper",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"}],name:"deployReceiver",outputs:[{internalType:"address",name:"sweeper",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"executor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"forwarder",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner_",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"isDeployed",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"lzEndpoint",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pendingOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"permissionlessBridgeFeeCapBps",outputs:[{internalType:"uint16",name:"",type:"uint16"}],stateMutability:"view",type:"function"},{inputs:[],name:"proxiableUUID",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"}],name:"receiverFor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"refundToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"rollup",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"route",outputs:[{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"uint32",name:"dstEid",type:"uint32"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],internalType:"struct BridgeRoute",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"executor_",type:"address"}],name:"setExecutor",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint16",name:"capBps",type:"uint16"}],name:"setPermissionlessBridgeFeeCapBps",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"uint32",name:"dstEid",type:"uint32"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],internalType:"struct BridgeRoute",name:"route_",type:"tuple"}],name:"setRoute",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"setSweeperImplementation",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"stargate",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"setTrustedStargate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"path",type:"bytes"}],name:"setUnswapPath",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"stargateDestinationEid",outputs:[{internalType:"uint32",name:"",type:"uint32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"stargate",type:"address"}],name:"stargateToken",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"swapRouter",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"address",name:"token",type:"address"},{components:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"minSwapOut",type:"uint256"},{internalType:"uint256",name:"minBridgeOut",type:"uint256"},{internalType:"bytes",name:"lzExtraOptions",type:"bytes"}],internalType:"struct SweepParams",name:"params",type:"tuple"}],name:"sweepWithParams",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"sweeperFor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"sweeperImplementation",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"hubToken",type:"address"}],name:"unswapPath",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[],name:"unwrapHelper",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],name:"upgradeToAndCall",outputs:[],stateMutability:"payable",type:"function"}];var YI=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"AccessControlBadConfirmation",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"bytes32",name:"neededRole",type:"bytes32"}],name:"AccessControlUnauthorizedAccount",type:"error"},{inputs:[{internalType:"address",name:"target",type:"address"}],name:"AddressEmptyCode",type:"error"},{inputs:[],name:"ECDSAInvalidSignature",type:"error"},{inputs:[{internalType:"uint256",name:"length",type:"uint256"}],name:"ECDSAInvalidSignatureLength",type:"error"},{inputs:[{internalType:"bytes32",name:"s",type:"bytes32"}],name:"ECDSAInvalidSignatureS",type:"error"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"ERC1967InvalidImplementation",type:"error"},{inputs:[],name:"ERC1967NonPayable",type:"error"},{inputs:[],name:"EnforcedPause",type:"error"},{inputs:[],name:"ExpectedPause",type:"error"},{inputs:[],name:"FailedCall",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientBalance",type:"error"},{inputs:[],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[],name:"InvalidSeed",type:"error"},{inputs:[],name:"InvalidSignature",type:"error"},{inputs:[],name:"InvalidTimestamp",type:"error"},{inputs:[],name:"NonceAlreadyUsed",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[],name:"ReentrancyGuardReentrantCall",type:"error"},{inputs:[],name:"TransferFailed",type:"error"},{inputs:[],name:"UUPSUnauthorizedCallContext",type:"error"},{inputs:[{internalType:"bytes32",name:"slot",type:"bytes32"}],name:"UUPSUnsupportedProxiableUUID",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Deposit",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newFeeCollector",type:"address"}],name:"FeeCollectorChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"previousAdminRole",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"newAdminRole",type:"bytes32"}],name:"RoleAdminChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleGranted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleRevoked",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newSettlementContract",type:"address"}],name:"SettlementContractChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"maker",type:"address"},{indexed:!0,internalType:"address",name:"taker",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"fee",type:"uint256"}],name:"SettlementTransfer",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdrawal",type:"event"},{inputs:[],name:"DEBUGGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"DEFAULT_ADMIN_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"FEE_MANAGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"PAUSER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"SETTLEMENT_MANAGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"UPGRADER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"UPGRADE_INTERFACE_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"seed",type:"bytes"}],name:"decodeSeed",outputs:[{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"destination",type:"address"},{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"depositERC20",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"destination",type:"address"},{internalType:"string",name:"applicationId",type:"string"}],name:"depositNative",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"feeCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getChainID",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"}],name:"getRoleAdmin",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"grantRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"hasRole",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_admin",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"proxiableUUID",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"callerConfirmation",type:"address"}],name:"renounceRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"revokeRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_newFeeCollector",type:"address"}],name:"setFeeCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_settlementContract",type:"address"}],name:"setSettlementContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"settlementContract",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"maker",type:"address"},{internalType:"address",name:"taker",type:"address"},{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"fee",type:"uint256"}],name:"transferOnSettlement",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],name:"upgradeToAndCall",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"seed",type:"bytes"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"withdraw",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"seed",type:"bytes"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"withdrawNative",outputs:[],stateMutability:"nonpayable",type:"function"}];var xOt=new Uint8Array(32);function uw(e,t){return ime(t),t==="margin"?JSON.stringify({clientId:e,depositTarget:"MARGIN"}):e}function ime(e){if(e!=="spot"&&e!=="margin")throw Error(`Invalid deposit target: ${JSON.stringify(e)}. `+'Expected "spot" or "margin" — lowercase, not the wire form "SPOT"/"MARGIN".')}var JI={vault:YI,sweeper:WI,sweeperFactory:KI};var sme=5000,ame=300000,cme=(e)=>new Promise((t)=>setTimeout(t,e));class lw extends Ye{publicClient;chain;applicationsAPI;profileAPI;walletClient;constructor(e,t,r,n,o,i){super(i);this.publicClient=e,this.chain=r,this.walletClient=t,this.applicationsAPI=n,this.profileAPI=o}setWalletClient(e){this.walletClient=e}async getVaultAddress(){return(await this.applicationsAPI.getApplicationConfig()).vaultContractAddress}async getClientId(){return(await this.applicationsAPI.getApplicationConfig()).clientId}async resolveAsset(e){let t,r;try{let n=await this.profileAPI.getUserBalanceByAssetId(e);t=n.token,r=n.wrappedNative===!0}catch(n){if(n instanceof sr){if(n.statusCode===404)throw new Ts(`Asset ID '${e}' does not exist`,{revertReason:"ASSET_NOT_FOUND",cause:n});throw new Ts(`Failed to resolve asset ID '${e}': ${n.retryable?"Network error occurred":"API request failed"}`,{revertReason:n.retryable?"NETWORK_ERROR":"API_ERROR",cause:n})}throw new Ts(`Failed to resolve asset ID '${e}': Unexpected error`,{revertReason:"UNKNOWN_ERROR",cause:n instanceof Error?n:void 0})}return{tokenAddress:t,isWrappedNative:r}}async approve(e,t,r=!0){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");te(Qq,{assetId:e,amount:t,autoWait:r});let n=await this.getVaultAddress(),{tokenAddress:o}=await this.resolveAsset(e),i=this.walletClient.account;if(!i)throw new Bt("No account available in wallet client","account");let s=i.getNonce?await i.getNonce():0n,a=await this.walletClient.writeContract({address:o,abi:ar,functionName:"approve",args:[n,t],chain:this.chain,account:i}),c={nonce:s,hash:a,status:"pending"};return await this.waitForTransaction(c,r)}async deposit(e,t,r=!0,n="spot",o={}){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");te(Xq,{assetId:e,amount:t,autoWait:r,target:n,options:o});let i=await this.getVaultAddress(),s=await this.getClientId(),a=uw(s,n),{tokenAddress:c,isWrappedNative:l}=await this.resolveAsset(e),d=l&&o.asErc20!==!0;if(!d){if(await this.needsApproval(e,t,o))throw new Ts(`Approval required before deposit. Please invoke approve() first for asset ${e} (token address: ${c}).`,{revertReason:"APPROVAL_REQUIRED"})}let f=this.walletClient.account;if(!f)throw new Bt("No account available in wallet client","account");let h;if(d)h=await this.walletClient.writeContract({address:i,abi:JI.vault,functionName:"depositNative",args:[f.address,a],account:f,chain:this.chain,value:t});else h=await this.walletClient.writeContract({address:i,abi:JI.vault,functionName:"depositERC20",args:[f.address,a,c,t],account:f,chain:this.chain});let g=f.getNonce?await f.getNonce():0n,x={hash:h,status:"pending",nonce:g};return await this.waitForTransaction(x,r)}async pollWithdrawalCalldata(e,t){let r=t?.pollIntervalMs??sme,n=t?.timeoutMs??ame,o=Date.now()+n;for(;;){try{let{vaultAddress:i,calldata:s}=await this.makePublicRequest(`/api/v1/withdrawals/${e}`);if(s&&s!=="0x")return{vaultAddress:i,calldata:s}}catch(i){if(!(i instanceof sr&&(i.statusCode===404||i.statusCode===409)))throw i}if(Date.now()+r>o)return null;await cme(r)}}async withdraw(e,t,r=!0,n,o){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");let i=this.walletClient.account;if(!i)throw new Bt("No account available in wallet client","account");let s=i.address.toLowerCase(),a=typeof n==="string"?n:"spot",c=typeof n==="string"?o:n;te(e7,{assetId:e,amount:t,destination:s,autoWait:r,source:a});let{withdrawalIndex:l}=await this.makeAuthenticatedRequest("/api/v1/withdrawals",{method:"POST",body:JSON.stringify({assetId:e,amount:t.toString(),destination:s,source:a})});if(!r)return{withdrawalIndex:l,status:"awaiting_proof"};let d=await this.pollWithdrawalCalldata(l,c);if(!d)return{withdrawalIndex:l,status:"awaiting_proof"};let{vaultAddress:f,calldata:h}=d,g;try{g=await this.walletClient.sendTransaction({to:f,data:h,account:i,chain:this.chain})}catch(_){throw new Ts(`Failed to submit executeWithdrawal for withdrawal ${l}: ${_ instanceof Error?_.message:"unknown error"}`,{cause:_ instanceof Error?_:void 0})}let x=i.getNonce?await i.getNonce():0n,w={hash:g,status:"pending",nonce:x};return{...await this.waitForTransaction(w,r),withdrawalIndex:l}}async retryWithdrawal(e,t=!0,r){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");let n=this.walletClient.account;if(!n)throw new Bt("No account available in wallet client","account");let o=await this.pollWithdrawalCalldata(e,r);if(!o)return{withdrawalIndex:e,status:"awaiting_proof"};let{vaultAddress:i,calldata:s}=o,a;try{a=await this.walletClient.sendTransaction({to:i,data:s,account:n,chain:this.chain})}catch(f){throw new Ts(`Failed to resubmit executeWithdrawal for withdrawal ${e}: ${f instanceof Error?f.message:"unknown error"}`,{cause:f instanceof Error?f:void 0})}let c=n.getNonce?await n.getNonce():0n,l={hash:a,status:"pending",nonce:c};return{...await this.waitForTransaction(l,t),withdrawalIndex:e}}async getBalance(e){throw new sr("getBalance() is deprecated and no longer supported. Please use profileAPI.getUserBalances() or profileAPI.getUserBalanceByAssetId() instead for balance data.",{statusCode:410})}async getAllowance(e){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");let t=await this.getVaultAddress(),n=(await this.walletClient.getAddresses())[0];if(!n)throw new Bt("No account found in wallet client.","walletClient");let{tokenAddress:o}=await this.resolveAsset(e);return await this.publicClient.readContract({address:o,abi:ar,functionName:"allowance",args:[n,t]})}async needsApproval(e,t,r={}){let{isWrappedNative:n}=await this.resolveAsset(e);if(n&&r.asErc20!==!0)return!1;return await this.getAllowance(e)<t}async waitForTransaction(e,t=!0,r={}){if(!t)return e;let{confirmations:n=1,timeout:o=60000}=r;try{let i=await this.publicClient.waitForTransactionReceipt({hash:e.hash,confirmations:n,timeout:o});return{...e,status:i.status==="success"?"confirmed":"failed",receipt:i}}catch{return{...e,status:"failed"}}}}class dw extends Ye{async submit(e){return await this.makePublicRequest(ue.whitelist.submit(),{method:"POST",body:JSON.stringify(e)})}}class QI extends Ye{async initiateWithdrawal(e){return this.makeAuthenticatedRequest(ue.withdrawals.initiate(),{method:"POST",body:JSON.stringify({assetId:e.assetId,amount:e.amount,destination:e.destination,source:e.source??"spot"})})}async getWithdrawal(e){return this.makePublicRequest(ue.withdrawals.byIndex(e))}async listPendingWithdrawals(e){return te(t7,e??{}),this.makeAuthenticatedRequest(ue.withdrawals.list({pageSize:e?.pageSize,pageToken:e?.pageToken}))}}class pw extends Ye{chain;walletClient;constructor(e,t,r){super(r);this.chain=t,this.walletClient=e}setWalletClient(e){this.walletClient=e}async authenticate(e,t,r){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");let n=this.walletClient.account;if(!n)throw new Bt("No account available in wallet client","account");let o=N0(),i={publicKey:$0(o),privateKey:z0(o)},s=await this.createChallenge(n.address,e,i.publicKey),a=await this.signChallenge(s.message);return await this.verifySignature(n.address,a,s.nonce,e,i,t,r)}async signChallenge(e){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");let t=this.walletClient.account;if(!t)throw new Bt("No account available in wallet client","account");return await this.walletClient.signMessage({account:t,message:e})}async createChallenge(e,t,r){let n=await this.makePublicRequest("/api/v1/auth/challenge",{method:"POST",body:JSON.stringify({address:e,clientId:t,chainId:this.chain.id,sessionPublicKey:r})});return{nonce:n.nonce,message:n.message,expiresAt:n.expiresAt}}async verifySignature(e,t,r,n,o,i,s){let a=await this.makePublicRequest("/api/v1/auth/verify",{method:"POST",body:JSON.stringify({address:e,signature:t,nonce:r,clientId:n,chainId:this.chain.id,sessionPublicKey:o.publicKey,...i?{referralCode:i}:{},...s?{inviteCode:s}:{}})});return{sessionPublicKey:o.publicKey,sessionPrivateKey:o.privateKey,expiresAt:a.expiresAt,user:{id:a.user.id,address:a.user.address,username:a.user.username},...a.isNewUser!==void 0?{isNewUser:a.isNewUser}:{},...a.referralApplied!==void 0?{referralApplied:a.referralApplied}:{}}}async requestInviteCodes(){return await this.makeAuthenticatedRequest("/api/v1/invite-codes/requests",{method:"POST",body:JSON.stringify({})})}async listInviteCodes(){return await this.makeAuthenticatedRequest("/api/v1/invite-codes",{method:"GET"})}async refreshSession(){return{expiresAt:(await this.makeAuthenticatedRequest("/api/v1/auth/refresh",{method:"POST"})).expiresAt}}async revokeSession(){await this.makeAuthenticatedRequest("/api/v1/auth/revoke",{method:"POST"})}}var ume=750;function s7(e,t){try{new URL(e)}catch(r){throw new Bt(`${t} must be a valid URL, got: ${e}`,t)}return e}class ek{auth;delegatedAgents;applications;fees;buildercodes;copyTrading;tradercodes;pitpass;vault;withdrawals;trading;market;marginAccounts;positions;portfolio;subAccounts;faucet;sweeper;managedMarkets;whitelist;profile;pulse;orderbook;trades;ws;walletClient;publicClient;authState;network;chain;propagateSession(e){this.auth.setSessionKeypair(e),this.delegatedAgents.setSessionKeypair(e),this.applications.setSessionKeypair(e),this.fees.setSessionKeypair(e),this.buildercodes.setSessionKeypair(e),this.copyTrading.setSessionKeypair(e),this.tradercodes.setSessionKeypair(e),this.vault.setSessionKeypair(e),this.withdrawals.setSessionKeypair(e),this.trading.setSessionKeypair(e),this.market.setSessionKeypair(e),this.marginAccounts.setSessionKeypair(e),this.positions.setSessionKeypair(e),this.portfolio.setSessionKeypair(e),this.subAccounts.setSessionKeypair(e),this.faucet.setSessionKeypair(e),this.sweeper.setSessionKeypair(e),this.managedMarkets.setSessionKeypair(e),this.whitelist.setSessionKeypair(e),this.pulse.setSessionKeypair(e),this.profile.setSessionKeypair(e),this.orderbook.setSessionKeypair(e),this.trades.setSessionKeypair(e),this.ws.setSessionKeypair(e)}sessionFromAuthState(e){return{publicKey:e.sessionPublicKey,privateKey:e.sessionPrivateKey}}constructor(e){let t=["mainnet","development","staging","local"];if(!e.network||!t.includes(e.network))throw new Bt(`network must be one of: ${t.join(", ")}. Got: ${e.network}`,"network");if(this.network=e.network,!e.seiRpcUrl)throw new Bt("seiRpcUrl is required","seiRpcUrl");try{new URL(e.seiRpcUrl)}catch(c){throw new Bt(`seiRpcUrl must be a valid URL, got: ${e.seiRpcUrl}`,"seiRpcUrl")}let r=e.wsUrl?s7(e.wsUrl,"wsUrl"):sE(this.network),n=this.network==="mainnet"?yh:bh;if(this.chain=n,e.pollingInterval!==void 0&&(!Number.isFinite(e.pollingInterval)||e.pollingInterval<=0))throw new Bt(`pollingInterval must be a positive number of milliseconds, got: ${e.pollingInterval}`,"pollingInterval");let o=gh(e.seiRpcUrl);this.publicClient=uI({chain:n,transport:o,pollingInterval:e.pollingInterval??ume});let i=e.apiUrl?s7(e.apiUrl,"apiUrl"):iE(this.network);if(e.walletClient){if(e.walletClient.chain?.id!==n.id)throw new Bt(`Wallet client chain mismatch. Expected ${n.id}, got ${e.walletClient.chain?.id}`,"walletClient");this.walletClient=e.walletClient}let s=new cu,a=(c)=>(c.setRequestSigning(e.requestSigning??"legacy"),c.setServerClock(s),c);this.applications=a(new Vx(i)),this.market=a(new Xx(i)),this.marginAccounts=a(new Qx(i)),this.positions=a(new nw(i)),this.portfolio=a(new rw(i)),this.subAccounts=a(new iw(i)),this.faucet=a(new Yx(i)),this.sweeper=a(new sw(i)),this.managedMarkets=a(new GI(i)),this.whitelist=a(new dw(i)),this.pulse=a(new ow(i)),this.auth=a(new pw(this.walletClient,this.chain,i)),this.delegatedAgents=a(new HI(i)),this.fees=a(new Jx(i)),this.buildercodes=a(new Zx(i)),this.copyTrading=a(new Kx(i)),this.tradercodes=a(new Th(i)),this.pitpass=this.tradercodes,this.profile=a(new VI(i)),this.vault=a(new lw(this.publicClient,this.walletClient,this.chain,this.applications,this.profile,i)),this.withdrawals=a(new QI(i)),this.trading=a(new cw(i)),this.orderbook=a(new ew(i)),this.trades=a(new ZI(i)),this.ws=Qv(r,e.ws,s),this.ws.connect().catch(console.error)}async login(e,t){if(this.authState=await this.auth.authenticate(e,void 0,t?.inviteCode),this.propagateSession(this.sessionFromAuthState(this.authState)),t?.connectWebSocket)await this.ws.connect();return this.authState}async loginAsDelegatedOwner(e){if(!this.authState)throw new sr("No active agent session to create delegated session",{endpoint:"delegated-agents/sessions",statusCode:XI.StatusCodes.UNAUTHORIZED});let t=N0(),r={publicKey:$0(t),privateKey:z0(t)},n=await this.delegatedAgents.createDelegatedSession({ownerUserId:e,sessionPublicKey:r.publicKey});return this.authState={sessionPublicKey:r.publicKey,sessionPrivateKey:r.privateKey,expiresAt:n.expiresAt,user:{id:n.ownerUserId,address:n.agentAddress}},this.propagateSession(this.sessionFromAuthState(this.authState)),this.authState}getAuthState(){return this.authState}setAuthState(e){this.authState=e,this.propagateSession(this.sessionFromAuthState(e))}async logout(){if(this.authState)try{await this.auth.revokeSession()}catch(e){console.warn("Failed to revoke session on logout:",e)}this.authState=void 0,this.propagateSession(void 0),this.ws.disconnect()}async refreshAuth(){if(!this.authState)throw new sr("No active session to refresh",{endpoint:"auth/refresh",statusCode:XI.StatusCodes.UNAUTHORIZED});try{let e=await this.auth.refreshSession();return this.authState={...this.authState,expiresAt:e.expiresAt},this.authState}catch(e){throw this.authState=void 0,this.propagateSession(void 0),e}}isAuthenticated(){return!!this.authState}isConnected(){return!!this.walletClient&&!!this.publicClient}setWalletClient(e){if(e.chain?.id!==this.chain.id)throw new Bt(`Wallet client chain mismatch. Expected ${this.chain.id}, got ${e.chain?.id}`,"walletClient");this.walletClient=e,this.auth.setWalletClient(e),this.vault.setWalletClient(e)}getAccountAddress(){if(!this.walletClient)throw new Sm("Wallet client not set","walletClient");if(this.walletClient.account)return this.walletClient.account.address;throw new Sm("No account available","account")}getNetwork(){return this.network}getChainId(){return this.chain.id}async waitForTransaction(e,t,r){return this.publicClient.waitForTransactionReceipt({hash:e,confirmations:t,timeout:r})}}function tk(e){return new ek(e)}ih();Ke();Ri();Qn();function a7(e){if(typeof e==="string"){if(!_t(e,{strict:!1}))throw new Qt({address:e});return{address:e,type:"json-rpc"}}if(!_t(e.address,{strict:!1}))throw new Qt({address:e.address});return{address:e.address,nonceManager:e.nonceManager,sign:e.sign,signAuthorization:e.signAuthorization,signMessage:e.signMessage,signTransaction:e.signTransaction,signTypedData:e.signTypedData,source:"custom",type:"local"}}ih();Dr();Ke();var rk=!1;async function Gi({hash:e,privateKey:t,to:r="object"}){let{r:n,s:o,recovery:i}=Vs.sign(e.slice(2),t.slice(2),{lowS:!0,extraEntropy:cr(rk,{strict:!1})?Cr(rk):rk}),s={r:Z(n,{size:32}),s:Z(o,{size:32}),v:i?28n:27n,yParity:i};return(()=>{if(r==="bytes"||r==="hex")return yx({...s,to:r});return s})()}async function c7(e){let{chainId:t,nonce:r,privateKey:n,to:o="object"}=e,i=e.contractAddress??e.address,s=await Gi({hash:Yb({address:i,chainId:t,nonce:r}),privateKey:n,to:o});if(o==="object")return{address:i,chainId:t,nonce:r,...s};return s}async function u7({message:e,privateKey:t}){return await Gi({hash:mp(e),privateKey:t,to:"hex"})}wo();Tn();Ke();function l7(e){if(!e||e.length===0)return[];let t=[];for(let r of e){let{chainId:n,nonce:o,...i}=r,s=r.address;t.push([n?lr(n):"0x",s,o?lr(o):"0x",...kp({},i)])}return t}Ke();KP();Ri();et();Um();js();Qn();Mn();Is();Rr();function d7(e){let{authorizationList:t}=e;if(t)for(let r of t){let{chainId:n}=r,o=r.address;if(!_t(o))throw new Qt({address:o});if(n<0)throw new pd({chainId:n})}fw(e)}function p7(e){let{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new ch;for(let r of t){let n=lt(r),o=ur($n(r,0,1));if(n!==32)throw new bA({hash:r,size:n});if(o!==Xb)throw new xA({hash:r,version:o})}}fw(e)}function fw(e){let{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:o}=e;if(t<=0)throw new pd({chainId:t});if(o&&!_t(o))throw new Qt({address:o});if(n&&n>Zd)throw new Zo({maxFeePerGas:n});if(r&&n&&r>n)throw new Us({maxFeePerGas:n,maxPriorityFeePerGas:r})}function f7(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:i}=e;if(t<=0)throw new pd({chainId:t});if(i&&!_t(i))throw new Qt({address:i});if(r||o)throw new N("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Zd)throw new Zo({maxFeePerGas:n})}function m7(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:i}=e;if(i&&!_t(i))throw new Qt({address:i});if(typeof t<"u"&&t<=0)throw new pd({chainId:t});if(r||o)throw new N("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Zd)throw new Zo({maxFeePerGas:n})}Ri();Tn();Qn();function Eh(e){if(!e||e.length===0)return[];let t=[];for(let r=0;r<e.length;r++){let{address:n,storageKeys:o}=e[r];for(let i=0;i<o.length;i++)if(o[i].length-2!==64)throw new SP({storageKey:o[i]});if(!_t(n,{strict:!1}))throw new Qt({address:n});t.push([n,o])}return t}function h7(e,t){let r=tx(e);if(r==="eip1559")return pme(e,t);if(r==="eip2930")return fme(e,t);if(r==="eip4844")return dme(e,t);if(r==="eip7702")return lme(e,t);return mme(e,t)}function lme(e,t){let{authorizationList:r,chainId:n,gas:o,nonce:i,to:s,value:a,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:d,data:f}=e;d7(e);let h=Eh(d),g=l7(r);return dr(["0x04",Zs([Z(n),i?Z(i):"0x",l?Z(l):"0x",c?Z(c):"0x",o?Z(o):"0x",s??"0x",a?Z(a):"0x",f??"0x",h,g,...kp(e,t)])])}function dme(e,t){let{chainId:r,gas:n,nonce:o,to:i,value:s,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:d,data:f}=e;p7(e);let{blobVersionedHashes:h,sidecars:g}=e;if(e.blobs&&(typeof h>"u"||typeof g>"u")){let T=typeof e.blobs[0]==="string"?e.blobs:e.blobs.map((k)=>St(k)),v=e.kzg,E=Qd({blobs:T,kzg:v});if(typeof h>"u")h=Qb({commitments:E});if(typeof g>"u"){let k=Xd({blobs:T,commitments:E,kzg:v});g=ex({blobs:T,commitments:E,proofs:k})}}let x=Eh(d),w=[Z(r),o?Z(o):"0x",l?Z(l):"0x",c?Z(c):"0x",n?Z(n):"0x",i??"0x",s?Z(s):"0x",f??"0x",x,a?Z(a):"0x",h??[],...kp(e,t)],S=[],_=[],A=[];if(g)for(let T=0;T<g.length;T++){let{blob:v,commitment:E,proof:k}=g[T];S.push(v),_.push(E),A.push(k)}return dr(["0x03",g?Zs([w,S,_,A]):Zs(w)])}function pme(e,t){let{chainId:r,gas:n,nonce:o,to:i,value:s,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:l,data:d}=e;fw(e);let f=Eh(l),h=[Z(r),o?Z(o):"0x",c?Z(c):"0x",a?Z(a):"0x",n?Z(n):"0x",i??"0x",s?Z(s):"0x",d??"0x",f,...kp(e,t)];return dr(["0x02",Zs(h)])}function fme(e,t){let{chainId:r,gas:n,data:o,nonce:i,to:s,value:a,accessList:c,gasPrice:l}=e;f7(e);let d=Eh(c),f=[Z(r),i?Z(i):"0x",l?Z(l):"0x",n?Z(n):"0x",s??"0x",a?Z(a):"0x",o??"0x",d,...kp(e,t)];return dr(["0x01",Zs(f)])}function mme(e,t){let{chainId:r=0,gas:n,data:o,nonce:i,to:s,value:a,gasPrice:c}=e;m7(e);let l=[i?Z(i):"0x",c?Z(c):"0x",n?Z(n):"0x",s??"0x",a?Z(a):"0x",o??"0x"];if(t){let d=(()=>{if(t.v>=35n){if((t.v-35n)/2n>0)return t.v;return 27n+(t.v===35n?0n:1n)}if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);let g=27n+(t.v===27n?0n:1n);if(t.v!==g)throw new xP({v:t.v});return g})(),f=tn(t.r),h=tn(t.s);l=[...l,Z(d),f==="0x00"?"0x":f,h==="0x00"?"0x":h]}else if(r>0)l=[...l,Z(r),"0x","0x"];return Zs(l)}function kp(e,t){let r=t??e,{v:n,yParity:o}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof o>"u")return[];let i=tn(r.r),s=tn(r.s);return[(()=>{if(typeof o==="number")return o?Z(1):"0x";if(n===0n)return"0x";if(n===1n)return Z(1);return n===27n?"0x":Z(1)})(),i==="0x00"?"0x":i,s==="0x00"?"0x":s]}async function g7(e){let{privateKey:t,transaction:r,serializer:n=h7}=e,o=(()=>{if(r.type==="eip4844")return{...r,sidecars:!1};return r})(),i=await Gi({hash:Ot(await n(o)),privateKey:t});return await n(r,i)}async function y7(e){let{privateKey:t,...r}=e;return await Gi({hash:wx(r),privateKey:t,to:"hex"})}function nk(e,t={}){let{nonceManager:r}=t,n=lr(Vs.getPublicKey(e.slice(2),!1)),o=Kb(n);return{...a7({address:o,nonceManager:r,async sign({hash:s}){return Gi({hash:s,privateKey:e,to:"hex"})},async signAuthorization(s){return c7({...s,privateKey:e})},async signMessage({message:s}){return u7({message:s,privateKey:e})},async signTransaction(s,{serializer:a}={}){return g7({privateKey:e,transaction:s,serializer:a})},async signTypedData(s){return y7({...s,privateKey:e})}}),publicKey:n,source:"privateKey"}}var ok=null;var hme={privateKeyToAccount:nk,createWalletClient:fI,http:gh,createMonacoSDK:tk,sei:yh,seiTestnet:bh};function gme(e,t=hme){let r=e.network==="mainnet"?t.sei:t.seiTestnet,n;if(e.privateKey){let o=t.privateKeyToAccount(e.privateKey);n=t.createWalletClient({account:o,chain:r,transport:t.http(e.seiRpcUrl)})}return t.createMonacoSDK({walletClient:n,network:e.network,seiRpcUrl:e.seiRpcUrl})}function Ge(e){if(!ok){let t=e??Jc();ok=gme(t)}return ok}var yme=60,mw=null;function bme(){return Math.floor(Date.now()/1000)}function b7(e){return e-yme<=bme()}function xme(e){for(let t=e,r=0;t instanceof Error&&r<5;r++){if(t instanceof sr&&t.statusCode===401)return!0;t=t.cause}return!1}function ik(e){if(!mw)mw=e().finally(()=>{mw=null});return mw}async function x7(e,t){if(await e.login(t.clientId),t.delegatedOwnerUserId){try{let r=await e.loginAsDelegatedOwner(t.delegatedOwnerUserId);console.error(`Adopted delegated owner ${r.user.id} (session expires at ${new Date(r.expiresAt*1000).toISOString()})`)}catch(r){throw await e.logout().catch(()=>{}),r}return}console.error(`Authenticated as ${e.getAccountAddress()}`)}async function w7(e,t){try{await e.refreshAuth()}catch{await x7(e,t)}}async function H(e){let t=Ge(e),r=e??Jc(),n=t.getAuthState(),o=r.delegatedOwnerUserId!=null&&n?.user?.id!==r.delegatedOwnerUserId;if(!n||o)return await ik(()=>x7(t,r)),t;if(b7(n.expiresAt))await ik(()=>w7(t,r));return t}async function wme(e){let t=e??Jc();if(!t.privateKey)return!1;let r=Ge(e);return await ik(()=>w7(r,t)),!0}function S7(e,t){async function r(...n){let o=Ge(t).getAuthState(),i=o!==void 0&&!b7(o.expiresAt);try{return await e(...n)}catch(s){if(!xme(s))throw s;if(!(i&&Ge(t).getAuthState()!==o)){if(!await wme(t))throw s}return await e(...n)}}return r}function C(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function hw(e){return{content:[{type:"text",text:e}]}}function _7(e){e.registerTool("add_follow_position_margin",{description:"Add margin to one of your copy positions. MOVES FUNDS: moves `amount` from the follow's copy account into the margin of its isolated copy position on one trading pair; the position's margin rises by exactly `amount`, the copy account's remaining collateral falls by the same, and your margin account is never touched. It lowers the position's leverage and moves its liquidation price away; it opens no exposure, so it works while copy trading is switched off and on a CLOSE_ONLY follow. There is no margin reduction: a follow exits by being stopped. Refused for a follow that is stopping or stopped (409), and when the follow holds no copy position on the pair, the position or the margin account is being liquidated, the position has lost more than its margin, or the amount is more than the copy account holds (400). Not idempotent: do not retry a timed-out call without first reading the follow, or the amount may be added twice. Only your own follows; delegated agent and sub-account sessions cannot add margin.",inputSchema:y({followId:p().uuid().describe("The follow's id (UUID), from list_my_follows"),tradingPairId:p().uuid().describe("Trading pair UUID of the copy position to add margin to"),amount:p().describe("Margin to add, in quote units (positive decimal string), taken from the follow's copy account")}).strict()},async({followId:t,tradingPairId:r,amount:n})=>{let i=await(await H()).copyTrading.addFollowPositionMargin({followId:t,tradingPairId:r,amount:n});return C(i)})}function T7(e){e.registerTool("close_all_copy_positions",{description:"Close the copy positions of every live copy trading follow of yours at market (reduce-only, immediate-or-cancel), KEEPING the follows: their leaders' next trades keep mirroring, so this is not a flatten guarantee. Proceeds stay in each copy account. Works even with copy trading switched off; shares close_follow_positions' per-account rate limit. Returns each follow's close orders placed and positions still open, the follows whose stop is in progress (left to their stop), and the follows whose close could not run (failedFollows, with a reason; retry them).",inputSchema:y({}).strict()},async()=>{let r=await(await H()).copyTrading.closeAllCopyPositions();return C(r)})}function v7(e){e.registerTool("close_follow_positions",{description:"Close every position in one of your copy trading follows' copy accounts at market (reduce-only, immediate-or-cancel) and cancel the resting orders and TP/SL orders on its copy risk buckets, KEEPING the follow: the leader's next trades keep mirroring, so this is not a flatten guarantee (use stop_follow to close and stop). Proceeds stay in the copy account. Works even with copy trading switched off; rate limited per account (about one close per second, burst 5, shared with close_all_copy_positions). Returns how many close orders were placed and how many positions remain open (a thin or halted market can leave some); fills arrive on the order, position and copy channels. 404 for a follow that is not yours; 409 for a stopped follow or one whose stop is in progress.",inputSchema:y({followId:p().uuid().describe("The follow's id (UUID), from list_my_follows")}).strict()},async({followId:t})=>{let n=await(await H()).copyTrading.closeFollowPositions(t);return C(n)})}function E7(e){e.registerTool("get_follow",{description:"Get one of your copy trading follows with its most recent skipped mirrors (up to 100): leader fills the follow could not copy, with the reason (e.g. INSUFFICIENT_MARGIN) and the quantity that was not placed, plus copyAccountEquity: the copy account's equity at the engine's marks (a balance, not trading PnL; absent when it could not be read). 404 for a follow that is not yours.",inputSchema:y({followId:p().uuid().describe("The follow's id (UUID), from list_my_follows")})},async({followId:t})=>{let n=await(await H()).copyTrading.getFollow(t);return C(n)})}function P7(e){e.registerTool("get_lead_trader",{description:"Public lookup of one copy trading lead trader by custom TraderCode handle (no credentials required): profile (status, profit share in bps, bio, minimum allocation), follow summary, and stats for the 7d, 30d, 90d and all windows. 404 for an unknown or suspended leader.",inputSchema:y({handle:p().min(1).describe("The leader's custom TraderCode handle")})},async({handle:t})=>{let n=await Ge().copyTrading.getLeadTrader(t);return C(n)})}function A7(e){e.registerTool("get_my_lead_trader",{description:"Get your own copy trading lead trader profile, follow summary and stats. 404 when you are not a lead trader.",inputSchema:y({})},async()=>{let r=await(await H()).copyTrading.getMyLeadTrader();return C(r)})}function I7(e){e.registerTool("list_follow_leader_positions",{description:"List the open positions of the lead trader one of your follows copies. The leader comes from the follow, so this works even after the leader releases their handle. 404 for a follow that is not yours; 403 for a stopped follow.",inputSchema:y({followId:p().uuid().describe("The follow's id (UUID), from list_my_follows")})},async({followId:t})=>{let n=await(await H()).copyTrading.listFollowLeaderPositions(t);return C(n)})}function k7(e){e.registerTool("list_lead_trader_closed_trades",{description:"Public list of a copy trading lead trader's closed trades (no credentials required): the leader's reducing executions (partial and full closes, liquidations, auto-deleveraging), newest first, with size, entry and exit price, gross and net realized PnL, and realized ROE. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({handle:p().min(1).describe("The leader's custom TraderCode handle"),pageSize:I().int().min(1).max(100).optional().describe("Trades per page (default 20, max 100)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")})},async({handle:t,pageSize:r,pageToken:n})=>{let i=await Ge().copyTrading.listLeadTraderClosedTrades(t,{pageSize:r,pageToken:n});return C(i)})}function R7(e){e.registerTool("list_lead_trader_open_positions",{description:"List the open positions of a copy trading lead trader you currently follow (side, size, entry and mark price, unrealized PnL, leverage, margin mode). Only current followers of that leader may read them; anyone else gets 403.",inputSchema:y({handle:p().min(1).describe("The leader's custom TraderCode handle")})},async({handle:t})=>{let n=await(await H()).copyTrading.listLeadTraderOpenPositions(t);return C(n)})}function C7(e){e.registerTool("list_lead_traders",{description:"Public copy trading leaderboard (no credentials required): lead traders ranked highest first by a metric over a stats window, each with profile, follow summary (follower count, allocated AUM and marked AUM equity) and stats (PnL, ROI %, max drawdown %, win rate %, closed trades). Leaders are identified by wallet and custom TraderCode handle; use the handle with the other copy trading tools. Cursor paged: pass the previous response's nextPageToken with the SAME sort and window; an empty nextPageToken means the end.",inputSchema:y({sort:z(["roi","pnl","followers","allocated","aum","win_rate"]).optional().describe("Metric to rank by, highest first (default roi); aum ranks by the marked equity of live follows' copy accounts"),window:z(["7d","30d","90d","all"]).optional().describe("Stats window (default 30d)"),pageSize:I().int().min(1).max(100).optional().describe("Leaders per page (default 20, max 100)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")})},async({sort:t,window:r,pageSize:n,pageToken:o})=>{let s=await Ge().copyTrading.listLeadTraders({sort:t,window:r,pageSize:n,pageToken:o});return C(s)})}function O7(e){e.registerTool("list_my_followers",{description:"List your copy trading followers, as a lead trader: each follower's wallet, display name, status (ACTIVE or CLOSE_ONLY), allocation and start time. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({pageSize:I().int().min(1).max(1000).optional().describe("Followers per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")})},async({pageSize:t,pageToken:r})=>{let o=await(await H()).copyTrading.listMyFollowers({pageSize:t,pageToken:r});return C(o)})}function M7(e){e.registerTool("list_my_follows",{description:"List your copy trading follows, newest first: leader, status (ACTIVE, CLOSE_ONLY or STOPPED), sizing, leverage and margin mode settings, allocation, stop-loss, market filter, consecutive skips, and the copy risk bucket id. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({pageSize:I().int().min(1).max(1000).optional().describe("Follows per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")})},async({pageSize:t,pageToken:r})=>{let o=await(await H()).copyTrading.listMyFollows({pageSize:t,pageToken:r});return C(o)})}function N7(e){e.registerTool("preview_follow",{description:"Preview what following a copy trading lead trader with copyExisting would open, as totals only: the estimated margin and fees, and how many of the leader's open positions would and would not be copied (no markets, sides or reasons). At most 64 positions are sized (truncated is true when the leader holds more). It refuses terms a follow would refuse and spends the order-risk preview budget. Read-only: nothing is placed, reserved or moved.",inputSchema:y({leader:p().describe("The leader's custom TraderCode handle"),allocation:p().describe("Collateral the copy account would start with, in quote units (decimal string)"),marginModePolicy:z(["FOLLOW","CROSS","ISOLATED"]).optional().describe("FOLLOW (default: the leader's mode per market), CROSS or ISOLATED"),sizingMode:z(["PROPORTIONAL","FIXED_MARGIN"]).optional().describe("PROPORTIONAL (default) or FIXED_MARGIN"),sizingParam:p().optional().describe("Margin per leader order in quote units; required for FIXED_MARGIN, not allowed otherwise"),leverageMode:z(["FOLLOW","FIXED"]).optional().describe("FOLLOW (default: the leader's leverage) or FIXED"),fixedLeverage:p().optional().describe("Leverage for every copy; required for FIXED, not allowed otherwise"),tradingPairIds:ie(p()).optional().describe("Trading pair UUIDs to copy; omit to copy every market the leader trades")}).strict().refine((t)=>t.sizingMode==="FIXED_MARGIN"===(t.sizingParam!==void 0),{message:"sizingParam is required for FIXED_MARGIN sizing and not allowed otherwise",path:["sizingParam"]}).refine((t)=>t.leverageMode==="FIXED"===(t.fixedLeverage!==void 0),{message:"fixedLeverage is required for FIXED leverage and not allowed otherwise",path:["fixedLeverage"]})},async({leader:t,allocation:r,marginModePolicy:n,sizingMode:o,sizingParam:i,leverageMode:s,fixedLeverage:a,tradingPairIds:c})=>{let d=await(await H()).copyTrading.previewFollow({leader:t,allocation:r,marginModePolicy:n,sizingMode:o,sizingParam:i,leverageMode:s,fixedLeverage:a,tradingPairIds:c});return C(d)})}function $7(e){e.registerTool("stop_follow",{description:"Stop one of your copy trading follows: the leader's fills stop being mirrored into its copy account. Only your own follows; a delegated agent session cannot stop a follow.",inputSchema:y({followId:p().uuid().describe("The follow's id (UUID), from list_my_follows")})},async({followId:t})=>{let n=await(await H()).copyTrading.stopFollow(t);return C(n)})}function z7(e){e.registerTool("upsert_follow",{description:"Follow a copy trading lead trader, or edit one of your follows. MOVES FUNDS: a new follow moves `allocation` from your margin account into a new copy account (a cross risk bucket) and from then on every fill the leader makes is mirrored into it with market orders. Omit followId to create (leader required); set followId to edit. An edit REPLACES the follow's settings: every optional setting left out reverts to its default (an edit without slPct removes the stop-loss), so send the full configuration.",inputSchema:y({followId:p().uuid().optional().describe("Omit to create a follow; set to edit one of your follows"),leader:p().optional().describe("The leader's custom TraderCode handle; required on a create, optional on an edit"),allocation:p().describe("Collateral for the copy account, in quote units (decimal string), at or above the minimum"),marginModePolicy:z(["FOLLOW","CROSS","ISOLATED"]).optional().describe("FOLLOW (default: the leader's mode per market), CROSS or ISOLATED"),sizingMode:z(["PROPORTIONAL","FIXED_MARGIN"]).optional().describe("PROPORTIONAL (default: scaled by copy account equity over the leader's equity) or FIXED_MARGIN"),sizingParam:p().optional().describe("Margin per leader order in quote units; required for FIXED_MARGIN, not allowed otherwise"),leverageMode:z(["FOLLOW","FIXED"]).optional().describe("FOLLOW (default: the leader's leverage) or FIXED"),fixedLeverage:p().optional().describe("Leverage for every copy; required for FIXED, not allowed otherwise"),slPct:p().optional().describe("Copy stop-loss as a fraction of the allocation in (0, 1], e.g. '0.25'; omit for none"),tradingPairIds:ie(p()).optional().describe("Trading pair UUIDs to copy; omit to copy every market the leader trades"),copyExisting:oe().optional().describe("On a create, also copy the leader's currently open positions into the new copy account (preview_follow shows the cost); refused on an edit")}).strict().refine((t)=>t.followId!==void 0||t.leader!==void 0,{message:"leader is required when creating a follow",path:["leader"]}).refine((t)=>t.followId===void 0||t.copyExisting!==!0,{message:"copyExisting applies only when creating a follow",path:["copyExisting"]}).refine((t)=>t.sizingMode==="FIXED_MARGIN"===(t.sizingParam!==void 0),{message:"sizingParam is required for FIXED_MARGIN sizing and not allowed otherwise",path:["sizingParam"]}).refine((t)=>t.leverageMode==="FIXED"===(t.fixedLeverage!==void 0),{message:"fixedLeverage is required for FIXED leverage and not allowed otherwise",path:["fixedLeverage"]})},async({followId:t,leader:r,allocation:n,marginModePolicy:o,sizingMode:i,sizingParam:s,leverageMode:a,fixedLeverage:c,slPct:l,tradingPairIds:d,copyExisting:f})=>{let g=await(await H()).copyTrading.upsertFollow({followId:t,leader:r,allocation:n,marginModePolicy:o,sizingMode:i,sizingParam:s,leverageMode:a,fixedLeverage:c,slPct:l,tradingPairIds:d,copyExisting:f});return C(g)})}function L7(e){e.registerTool("upsert_lead_trader",{description:"Register as a copy trading lead trader, or edit your lead profile. Registration is checked against the platform's eligibility rules (account equity, trading history, closed positions, a claimed custom TraderCode handle); a refusal names the rule. A wallet with a live follow cannot register. The profile is replaced as sent: an omitted bio or minAllocation is cleared and an omitted status means ACTIVE; an omitted shareBps keeps the current profit share.",inputSchema:y({shareBps:I().int().min(0).max(1e4).optional().describe("Your share of followers' realized profit, in basis points"),bio:p().optional().describe("Free-text profile description, at most 2,000 bytes; omit to clear"),status:z(["ACTIVE","PAUSED"]).optional().describe("ACTIVE accepts new follows; PAUSED keeps existing follows mirroring but accepts no new ones (default ACTIVE)"),minAllocation:p().optional().describe("Minimum follow allocation in quote units (decimal string); omit to clear")}).strict()},async({shareBps:t,bio:r,status:n,minAllocation:o})=>{let s=await(await H()).copyTrading.upsertLeadTrader({shareBps:t,bio:r,status:n,minAllocation:o});return C(s)})}function B7(e){C7(e),P7(e),k7(e)}function D7(e){R7(e),A7(e),O7(e),M7(e),E7(e),I7(e),N7(e),L7(e),z7(e),$7(e),v7(e),T7(e),_7(e)}function F7(e,t){if(t.network==="mainnet")return;e.registerTool("get_faucet_info",{description:"Get the authenticated wallet's faucet quota: remaining requests in the rolling 24h window, when the next request becomes available, and the 5 most recent faucet requests. Check this before request_faucet to avoid rate-limit errors. Only available on non-mainnet networks (development, staging, local).",inputSchema:{}},async()=>{let n=await(await H()).faucet.getInfo();return C(n)})}function U7(e,t){if(t.network==="mainnet")return;e.registerTool("request_faucet",{description:"Request test funds from the faucet for all active trading pairs. Requires a Cloudflare Turnstile token (the faucet rejects requests without one). Only available on non-mainnet networks (development, staging, local).",inputSchema:y({turnstileToken:p().describe("Cloudflare Turnstile token proving the request came from a real client (required by the faucet).")})},async({turnstileToken:r})=>{let o=await(await H()).faucet.mint({turnstileToken:r});return C(o)})}function j7(e,t){U7(e,t),F7(e,t)}function q7(e){e.registerTool("get_my_fee_tier",{description:"Get the authenticated user's current fee tier, rolling 14-day volumes (with spot/perp breakdown), the volume needed to reach the next tier, and the requested pair's six-row fee schedule.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID whose fee schedule to return")})},async({tradingPairId:t})=>{let n=await(await H()).fees.getMyFeeTier({tradingPairId:t});return C(n)})}function H7(e){e.registerTool("simulate_fees",{description:"Simulate the fees for an order before placing it. Returns Monaco protocol fees, application fees, and total amounts.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),side:z(["BUY","SELL"]).describe("Order side"),price:p().describe("Price per unit as a decimal string"),quantity:p().describe("Quantity to trade as a decimal string")})},async({tradingPairId:t,side:r,price:n,quantity:o})=>{let s=await(await H()).fees.simulateFees({tradingPairId:t,side:r,price:n,quantity:o});return C(s)})}function G7(e){H7(e),q7(e)}function V7(e){e.registerTool("get_available_collateral",{description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",inputSchema:y({asset:p().optional().describe("Optional collateral asset symbol or ID to scope the query")})},async({asset:t})=>{let n=await(await H()).marginAccounts.getAvailableCollateral({asset:t});return C(n)})}function Z7(e){e.registerTool("get_margin_accounts",{description:"List your margin accounts with optional filters (state, trading pair). Cursor paged; an empty nextPageToken means the end.",inputSchema:y({pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page"),state:p().optional().describe("Filter by margin account state"),tradingPairId:p().optional().describe("Filter by trading pair UUID")})},async({pageSize:t,pageToken:r,state:n,tradingPairId:o})=>{let s=await(await H()).marginAccounts.listMarginAccounts({pageSize:t,pageToken:r,state:n,tradingPairId:o});return C(s)})}function W7(e){e.registerTool("get_parent_margin_account_movements",{description:"List collateral movements for your parent (cross) margin account. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({movementType:p().optional().describe("Filter by movement type"),pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")})},async({movementType:t,pageSize:r,pageToken:n})=>{let i=await(await H()).marginAccounts.getParentMarginAccountMovements({movementType:t,pageSize:r,pageToken:n});return C(i)})}function K7(e){e.registerTool("get_parent_margin_account_summary",{description:"Get your parent (cross) margin account summary.",inputSchema:y({tradingPairId:p().optional().describe("Optional trading pair UUID to scope the summary")})},async({tradingPairId:t})=>{let n=await(await H()).marginAccounts.getParentMarginAccountSummary({tradingPairId:t});return C(n)})}var Sme=y({applicationId:p().uuid(),enrolled:oe(),payoutAddress:p().nullable().optional(),buildercodesEnabled:oe(),buildercodesBudgetBps:I().int().min(0).max(1e4),builderFeeEnabled:oe(),builderFeeBps:I().int().min(0).max(100),builderFeeCapBps:I().int().min(0).max(100),changesRemaining:I().int().min(0).max(2),nextChangeAllowedAt:p().nullable().optional()}),_me=y({bps:I().int().min(0).max(100)}),Tme=y({builderFeeBps:I().int().min(0).max(100),previousBuilderFeeBps:I().int().min(0).max(100),changesRemaining:I().int().min(0).max(2),nextChangeAllowedAt:p().nullable().optional()}),Y7=z(["BUILDER","ADMIN"]),J7=y({actorType:Y7,actor:p(),oldBps:I().int().min(0).max(100),newBps:I().int().min(0).max(100),createdAt:p()}),vme=y({pageSize:I().int().min(1).max(100).optional(),pageToken:p().optional()}),Eme=y({changes:ie(J7),nextPageToken:p()}),gw=z(["REVENUE_SHARE","BUILDER_FEE"]),Pme=y({page:Qe().optional(),pageSize:I().int().min(1).max(1000).optional(),pageToken:p().optional(),kind:gw.optional()}),Q7=y({tradeId:p().uuid(),payoutAddress:p(),token:p(),amount:p(),appliedBps:I().int(),createdAt:p(),kind:gw.optional()}),Ame=y({payouts:ie(Q7),total:I().int().nonnegative(),pageSize:I().int().positive(),totalPages:I().int().nonnegative(),nextPageToken:p()}),X7=y({token:p(),totalAmount:p(),payoutCount:I().int().nonnegative(),lastCreditedAt:p()}),eH=y({token:p(),kind:gw,totalAmount:p(),payoutCount:I().int().nonnegative(),lastCreditedAt:p()}),Ime=y({totalPayouts:I().int().nonnegative(),lastCreditedAt:p().nullable().optional(),byToken:ie(X7),byTokenAndKind:ie(eH).optional()}),tH=y({token:p(),available:p()}),kme=y({balances:ie(tH)}),Rme=y({token:p().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:p().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),Cme=y({payoutBalance:p(),tradingBalance:p()});function Qo(){return p()}var sk=y({walletAddress:p(),handle:p().nullish(),display:p()}),ak=y({leader:sk,status:Qo(),shareBps:I(),bio:p(),minAllocation:p().nullish(),registeredAt:p()}),ck=y({followerCount:I(),allocated:p(),aumEquity:p().nullish()}),uk=y({window:Qo(),pnl:p(),roiPct:p().nullish(),maxDrawdownPct:p().nullish(),winRatePct:p().nullish(),closedTrades:I()}),Ome=y({profile:ak,followSummary:ck,stats:ie(uk)}),rH=y({profile:ak,followSummary:ck,stats:uk}),Mme=y({leaders:ie(rH),nextPageToken:p(),asOf:p()}),Nme=y({created:oe(),status:Qo(),shareBps:I()}),nH=y({walletAddress:p(),display:p(),status:Qo(),allocation:p(),startedAt:p()}),$me=y({followers:ie(nH),nextPageToken:p()}),oH=y({tradingPairId:p(),positionSide:p(),action:Qo(),size:p().nullish(),exitPrice:p().nullish(),entryPrice:p().nullish(),realizedPnl:p().nullish(),netRealizedPnl:p().nullish(),realizedRoe:p().nullish(),closedAt:p()}),zme=y({closedTrades:ie(oH),nextPageToken:p()}),lk=y({tradingPairId:p(),side:p(),size:p(),entryPrice:p(),markPrice:p().nullish(),unrealizedPnl:p().nullish(),leverage:p().nullish(),marginMode:p()}),Lme=y({positions:ie(lk)}),dk=y({followId:p(),leader:sk,status:Qo(),marginModePolicy:Qo(),sizingMode:Qo(),sizingParam:p().nullish(),leverageMode:Qo(),fixedLeverage:p().nullish(),allocation:p(),slPct:p().nullish(),copyExisting:oe(),tradingPairIds:ie(p()),consecutiveSkips:I(),copyRiskBucketId:p(),startedAt:p(),stoppedAt:p().nullish(),stopReason:Qo().nullish()}),Bme=y({follows:ie(dk),nextPageToken:p()}),iH=y({tradingPairId:p(),reason:Qo(),requestedQuantity:p(),skippedAt:p()}),Dme=y({follow:dk,recentSkips:ie(iH),copyAccountEquity:p().nullish()}),Fme=y({positions:ie(lk)}),Ume=y({followId:p(),copyRiskBucketId:p(),created:oe()}),jme=y({estimatedMargin:p(),estimatedFee:p(),copiedPositions:I(),skippedPositions:I(),truncated:oe()}),qme=y({followId:p()}),sH=y({followId:p(),closeOrdersPlaced:I(),positionsNotClosed:I()}),aH=y({followId:p(),reason:p()}),Hme=y({follows:ie(sH),stoppingFollowIds:ie(p()),failedFollows:ie(aH)}),Gme=y({followId:p(),tradingPairId:p(),riskBucketId:p(),positionId:p(),positionMargin:p(),copyAccountAvailable:p()});var Vme=y({tradingPairId:p().trim().min(1,"Trading pair ID is required and cannot be empty"),side:z(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:p().trim().min(1,"Price is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Price must be a valid number").refine((e)=>Number(e)>0,"Price must be greater than 0"),quantity:p().trim().min(1,"Quantity is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Quantity must be a valid number").refine((e)=>Number(e)>0,"Quantity must be greater than 0"),orderType:z(["LIMIT","MARKET"]).optional(),slippageToleranceBps:I().int().min(0,"Slippage tolerance must be between 0 and 1000 bps").max(1000,"Slippage tolerance must be between 0 and 1000 bps").optional()}).superRefine((e,t)=>{if(e.slippageToleranceBps!==void 0&&e.orderType!=="MARKET")t.addIssue({code:wa.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),Zme=y({applicationName:p().nullable().optional(),applicationTakerFee:p(),applicationTakerFeeBps:I(),buyOrderLockAmount:p().nullable().optional(),makerTotalReceipt:p(),monacoMakerRebate:p(),monacoMakerRebateBps:I(),monacoMakerRebateBpsExact:p(),monacoTakerFee:p(),monacoTakerFeeBps:I(),monacoTakerFeeBpsExact:p(),notional:p(),takerTotalPayment:p(),totalTakerFees:p(),maxQuantity:p().nullable(),maxQuantityRaw:p().nullable(),slippageToleranceBps:I().nullable()}),Wme=y({tradingPairId:p().trim().min(1,"Trading pair ID is required and cannot be empty")}),cH=y({tierLevel:I().int(),minVolumeThreshold:p(),makerFeeBps:p(),takerFeeBps:p()}),Kme=y({currentTierLevel:I().int(),weightedVolume14d:p(),spotVolume14d:p(),perpVolume14d:p(),volumeToNextTier:p().nullable().optional(),nextTierLevel:I().int().nullable().optional(),feeSchedule:ie(cH)});var uH=y({token:p(),available:p()}),Yme=y({balances:ie(uH)}),Jme=y({code:p(),createdAt:p(),customCode:p(),isCustom:oe(),display:p()}),lH=z(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),Qme=y({available:oe(),reason:Ff((e)=>e===""||e===null?void 0:e,lH.optional())}),Xme=y({code:p().trim().min(1,"code is required").regex(/^[A-Za-z][A-Za-z0-9_]{4,19}$/,"code must start with a letter and be 5–20 chars of letters, digits, or underscores")}),ehe=y({code:p()}),the=y({token:p().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:p().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),rhe=y({rewardsBalance:p(),tradingBalance:p()}),dH=y({source:p(),sourceDisplay:p(),level:I(),amount:p(),token:p(),rateApplied:p(),createdAt:p()}),pH=y({wallet:p(),display:p(),level:I()}),nhe=y({referrer:p(),referrerDisplay:p(),totalEarned:p(),rewards:ie(dH),upline:ie(pH)}),fH=y({source:p(),sourceDisplay:p(),level:I(),totalEarned:p(),token:p()}),mH=y({wallet:p(),display:p(),referredAt:p(),totalEarned:p()}),hH=y({level:I(),earned:p()}),gH=y({totalEarned:p(),level1Earned:p(),level2Earned:p(),level3Earned:p(),byLevel:ie(hH)}),ohe=y({pageSize:I().int().min(1).max(500).optional(),pageToken:p().optional()}),ihe=y({earningsBySource:ie(fH),directReferees:ie(mH),summary:gH,nextPageToken:p()}),she=y({parent:p().optional(),pageSize:I().int().min(1).max(200).optional(),pageToken:p().optional()}),yH=y({wallet:p(),display:p(),level:I(),parent:p(),referredAt:p(),refereeCount:I(),totalEarned:p()}),ahe=y({parent:p(),parentLevel:I(),nodes:ie(yH),nextPageToken:p()});var Rp=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var Cp=z(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),Ph=z(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),ww=z(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),Ah=z(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),bH=z(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),pk=z(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),zu=z(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"],{message:'Self-trade prevention mode must be "CANCEL_MAKER", "CANCEL_TAKER", "CANCEL_BOTH", or "SKIP"'}),Op=z(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),Ze=p().trim().min(1,"Value cannot be empty").regex(/^\d+(\.\d+)?$/,"Value must be a positive decimal number (e.g., '1.5', '100')").refine((e)=>Number.parseFloat(e)>0,{message:"Value must be greater than 0"}),xe=UC({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),Qs=wl.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),xH=I().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),Mp=I().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),Np=I().int().min(0,"Slippage tolerance must be at least 0 bps").max(1000,"Slippage tolerance cannot exceed 1000 bps"),che=I().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),yw=y({triggerPrice:Ze,orderType:Op,limitPrice:Ze.optional(),quantity:Ze.optional(),closePosition:oe().optional(),timeInForce:pk.optional(),slippageToleranceBps:Mp.optional(),expiresAt:Qs.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT parent TP/SL",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET parent TP/SL",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),uhe=I().int("trailBps must be an integer number of basis points").min(10,"trailBps must be at least 10 bps").max(2000,"trailBps cannot exceed 2000 bps"),fk=y({trailBps:uhe,activationPrice:Ze.optional(),quantity:Ze.optional(),closePosition:oe().optional(),slippageToleranceBps:Mp.optional(),expiresAt:Qs.optional()}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),wH=fk,bw=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0||e?.trailingStop!==void 0,mk=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),hk=p().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/,"idempotencyKey must contain only letters, digits, or . _ : -"),mBt=y({tradingPairId:xe,side:Cp,quantity:Ze,price:Ze,options:y({idempotencyKey:hk.optional(),tradingMode:Ph.optional(),useMasterBalance:oe().optional(),expirationDate:Qs.optional(),timeInForce:bH.optional(),marginAccountId:xe.optional(),marginMode:ww.optional(),riskBucketId:xe.optional(),riskBucketCollateral:Ze.optional(),strategyKey:p().min(1).max(128).optional(),positionSide:Ah.optional(),leverage:Ze.optional(),reduceOnly:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:zu.optional(),takeProfit:yw.optional(),stopLoss:yw.optional(),trailingStop:wH.optional()}).optional()}).refine((e)=>mk(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!bw(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss/trailingStop are only supported for MARGIN orders",path:["options"]}).refine((e)=>!bw(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss/trailingStop cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}).refine((e)=>e.options?.postOnly!==!0||e.options?.timeInForce===void 0||e.options.timeInForce!=="IOC"&&e.options.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["options","timeInForce"]}),hBt=y({tradingPairId:xe,side:Cp,quantity:Ze,options:y({idempotencyKey:hk.optional(),tradingMode:Ph.optional(),slippageTolerance:xH,marginAccountId:xe.optional(),marginMode:ww.optional(),riskBucketId:xe.optional(),riskBucketCollateral:Ze.optional(),strategyKey:p().min(1).max(128).optional(),positionSide:Ah.optional(),leverage:Ze.optional(),reduceOnly:oe().optional(),selfTradePreventionMode:zu.optional(),takeProfit:yw.optional(),stopLoss:yw.optional(),trailingStop:wH.optional()}).optional()}).refine((e)=>mk(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!bw(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss/trailingStop are only supported for MARGIN orders",path:["options"]}).refine((e)=>!bw(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss/trailingStop cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),gBt=y({orderId:xe,remainingQuantityTarget:Ze.optional()}),yBt=y({orderId:xe,newOrder:y({price:Ze.optional(),quantity:Ze.optional(),useMasterBalance:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:zu.optional()})}),bBt=y({page:Qe().optional(),status:pt([z(Rp),ie(z(Rp)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:xe.optional(),tradingMode:Ph.optional(),marginAccountId:xe.optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),xBt=z(["STOP_LOSS","TAKE_PROFIT","TRAILING_STOP"],{message:'conditionType must be "STOP_LOSS", "TAKE_PROFIT", or "TRAILING_STOP"'}),wBt=z(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),lhe=z(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),SH=z(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),SBt=y({conditionalOrderId:xe}),_Bt=y({page:Qe().optional(),marginAccountId:xe.optional(),tradingPairId:xe.optional(),state:lhe.optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),dhe=z(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),phe=pt([I().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),p().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),fhe=2592000000,TBt=y({tradingPairId:xe,side:Cp,quantity:Ze,options:y({durationSeconds:phe.optional(),startTime:Qs.optional(),endTime:Qs.optional(),limitPrice:Ze.optional(),slippageToleranceBps:che.optional(),randomize:oe().optional(),executionStyle:z(["TAKER","PASSIVE"]).optional(),reduceOnly:oe().optional(),tradingMode:Ph.optional(),marginAccountId:xe.optional(),riskBucketId:xe.optional(),marginMode:ww.optional(),leverage:Ze.optional(),strategyKey:p().min(1).max(128).optional(),useMasterBalance:oe().optional(),clientTwapId:p().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional(),triggerPrice:Ze.optional(),triggerDirection:z(["ABOVE","BELOW"]).optional(),conditionalExpiry:Qs.optional()})}).refine((e)=>e.options.durationSeconds!==void 0!==(e.options.endTime!==void 0),{message:"Exactly one of durationSeconds or endTime must be set",path:["options","durationSeconds"]}).refine((e)=>e.options.startTime===void 0||e.options.endTime!==void 0,{message:"startTime is only valid together with endTime",path:["options","startTime"]}).refine((e)=>e.options.marginMode===void 0||e.options.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode==="MARGIN",{message:"riskBucketId is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}).refine((e)=>e.options.triggerPrice!==void 0===(e.options.triggerDirection!==void 0),{message:"triggerPrice and triggerDirection are both-or-neither",path:["options","triggerDirection"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.durationSeconds!==void 0,{message:"conditional TWAP (triggerPrice) requires durationSeconds — the window floats from the trigger instant",path:["options","durationSeconds"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.startTime===void 0&&e.options.endTime===void 0,{message:"triggerPrice is incompatible with startTime/endTime",path:["options","triggerPrice"]}).refine((e)=>e.options.conditionalExpiry===void 0||e.options.triggerPrice!==void 0,{message:"conditionalExpiry is only valid together with triggerPrice",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r>Date.now()},{message:"conditionalExpiry must be in the future",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r-Date.now()<=fhe},{message:"conditionalExpiry cannot be more than 30 days after creation (the maximum window)",path:["options","conditionalExpiry"]}),vBt=y({twapOrderId:xe}),EBt=y({page:Qe().optional(),state:dhe.optional(),tradingPairId:xe.optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),PBt=y({page:Qe().optional(),twapOrderId:xe,orderBy:z(["ASC","DESC"]).optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),mhe=y({tradingPairId:xe,orderType:Op,side:Cp,price:Ze.optional(),quantity:Ze,idempotencyKey:hk.optional(),tradingMode:Ph.optional(),slippageTolerance:xH,useMasterBalance:oe().optional(),expirationDate:Qs.optional(),timeInForce:bH.optional(),marginAccountId:xe.optional(),marginMode:ww.optional(),riskBucketId:xe.optional(),riskBucketCollateral:Ze.optional(),strategyKey:p().min(1).max(128).optional(),positionSide:Ah.optional(),leverage:Ze.optional(),reduceOnly:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:zu.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).refine((e)=>e.orderType!=="MARKET"||e.postOnly!==!0,{message:"postOnly must not be provided for MARKET orders",path:["postOnly"]}).refine((e)=>e.postOnly!==!0||e.timeInForce===void 0||e.timeInForce!=="IOC"&&e.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["postOnly"]}).refine((e)=>e.riskBucketCollateral===void 0||e.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode!=="CROSS"||e.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine((e)=>e.marginMode!=="CROSS"||e.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine((e)=>e.riskBucketCollateral===void 0||e.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.riskBucketCollateral===void 0||e.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine((e)=>mk(e.side,e.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["positionSide"]}).refine((e)=>e.tradingMode!=="MARGIN"||e.reduceOnly===!0||e.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["leverage"]}),xw=100,ABt=y({orders:ie(mhe).min(1,"At least one order is required").max(xw,`At most ${xw} orders per batch request`)}),hhe=y({orderId:xe,price:Ze.optional(),quantity:Ze.optional(),useMasterBalance:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:zu.optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),IBt=y({orders:ie(hhe).min(1,"At least one order is required").max(xw,`At most ${xw} orders per batch request`)});var Sw=y({clientId:p().trim().min(1,"Client ID is required"),page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),OBt=Sw.extend({status:p().trim().min(1,"Status cannot be empty").optional(),userId:xe.optional(),tradingPairId:xe.optional(),side:p().trim().min(1,"Side cannot be empty").optional(),orderType:p().trim().min(1,"Order type cannot be empty").optional()}),MBt=Sw.extend({isActive:oe().optional(),accountType:p().trim().min(1,"Account type cannot be empty").optional(),address:p().trim().min(1,"Address filter cannot be empty").optional()}),NBt=Sw.extend({userId:xe.optional(),transactionType:p().trim().min(1,"Transaction type cannot be empty").optional(),entryType:p().trim().min(1,"Entry type cannot be empty").optional(),assetId:xe.optional()}),$Bt=Sw.extend({userId:xe.optional(),assetId:xe.optional()});var _H=p().trim().min(1,"leader handle is required"),ghe=p().trim().regex(/^\d+(\.\d+)?$/,"slPct must be a decimal fraction (e.g. '0.25')").refine((e)=>{let t=Number.parseFloat(e);return t>0&&t<=1},"slPct must be greater than 0 and at most 1");function _w(e){return{pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(e,`Page size cannot exceed ${e}`).optional(),pageToken:p().optional()}}var FBt=y({shareBps:I().int("shareBps must be an integer").min(0,"shareBps cannot be negative").max(1e4,"shareBps cannot exceed 10000").optional(),bio:p().refine((e)=>new TextEncoder().encode(e).length<=2000,"bio cannot exceed 2,000 bytes").optional(),status:z(["ACTIVE","PAUSED"]).optional(),minAllocation:Ze.optional()}).strict(),UBt=y({followId:xe.optional(),leader:_H.optional(),marginModePolicy:z(["FOLLOW","CROSS","ISOLATED"]).optional(),sizingMode:z(["PROPORTIONAL","FIXED_MARGIN"]).optional(),sizingParam:Ze.optional(),leverageMode:z(["FOLLOW","FIXED"]).optional(),fixedLeverage:Ze.optional(),allocation:Ze,slPct:ghe.optional(),tradingPairIds:ie(xe).max(256,"at most 256 markets can be copied").optional(),copyExisting:oe().optional()}).strict().superRefine((e,t)=>{if(e.followId===void 0&&e.leader===void 0)t.addIssue({code:"custom",message:"leader is required when creating a follow",path:["leader"]});if(e.followId!==void 0&&e.copyExisting===!0)t.addIssue({code:"custom",message:"copyExisting applies only when creating a follow",path:["copyExisting"]});TH(e,t)});function TH(e,t){let r=e.sizingMode==="FIXED_MARGIN";if(r&&e.sizingParam===void 0)t.addIssue({code:"custom",message:"sizingParam is required for FIXED_MARGIN sizing",path:["sizingParam"]});if(!r&&e.sizingParam!==void 0)t.addIssue({code:"custom",message:"sizingParam is only accepted with FIXED_MARGIN sizing",path:["sizingParam"]});let n=e.leverageMode==="FIXED";if(n&&e.fixedLeverage===void 0)t.addIssue({code:"custom",message:"fixedLeverage is required for FIXED leverage",path:["fixedLeverage"]});if(!n&&e.fixedLeverage!==void 0)t.addIssue({code:"custom",message:"fixedLeverage is only accepted with FIXED leverage",path:["fixedLeverage"]})}var jBt=y({leader:_H,marginModePolicy:z(["FOLLOW","CROSS","ISOLATED"]).optional(),sizingMode:z(["PROPORTIONAL","FIXED_MARGIN"]).optional(),sizingParam:Ze.optional(),leverageMode:z(["FOLLOW","FIXED"]).optional(),fixedLeverage:Ze.optional(),allocation:Ze,tradingPairIds:ie(xe).max(256,"at most 256 markets can be copied").optional()}).strict().superRefine((e,t)=>TH(e,t)),qBt=y({followId:xe,tradingPairId:xe,amount:Ze}).strict(),HBt=y({sort:z(["roi","pnl","followers","allocated","aum","win_rate"]).optional(),window:z(["7d","30d","90d","all"]).optional(),..._w(100)}).strict(),GBt=y(_w(100)).strict(),VBt=y(_w(1000)).strict(),ZBt=y(_w(1000)).strict();var YBt=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});var gk=y({page:Qe().optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),e8t=gk.extend({state:p().trim().min(1,"State cannot be empty").optional(),tradingPairId:xe.optional()}),t8t=y({marginAccountId:xe,tradingPairId:xe.optional()}),r8t=y({tradingPairId:xe.optional()}).optional(),n8t=y({asset:p().trim().min(1,"Asset cannot be empty").optional()}).optional(),yhe=y({asset:p().trim().min(1,"Asset cannot be empty"),amount:Ze,tradingPairId:xe.optional(),strategyKey:p().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:z(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),Tw=y({asset:p().trim().min(1,"Asset cannot be empty"),amount:Ze}),bhe=y({tradingPairId:xe,strategyKey:p().trim().min(1,"Strategy key cannot be empty").optional()}),EH=bhe.extend({marginMode:Ae("ISOLATED").optional(),marginAccountId:xe.optional(),selectedTradingPairIds:Qe().optional(),applyToPositionMargin:oe().optional()}),xhe=y({marginMode:Ae("CROSS"),marginAccountId:xe.optional(),selectedTradingPairIds:Qe().optional(),strategyKey:Qe().optional()}),whe=y({marginMode:Ae("CROSS"),marginAccountId:xe.optional(),selectedTradingPairIds:Qe().optional(),strategyKey:Qe().optional(),tradingPairId:Qe().optional()}),o8t=y({marginAccountId:xe,request:yhe}),i8t=y({request:Tw}),She=y({marginMode:z(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Nt().optional()}).loose().superRefine((e,t)=>{if(e.selectedTradingPairIds===void 0)return;t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:e.marginMode==="CROSS"?"selectedTradingPairIds is not accepted on a CROSS transfer: cross scope is derived from trading, so a funding call has nothing to declare":"selectedTradingPairIds is not supported for ISOLATED risk buckets"})}),s8t=y({request:She.pipe(pt([Tw.merge(EH).strict(),Tw.merge(whe).strict()]))}),a8t=y({request:Tw}),c8t=gk.extend({marginAccountId:xe,movementType:p().trim().min(1,"Movement type cannot be empty").optional()}),u8t=gk.extend({movementType:p().trim().min(1,"Movement type cannot be empty").optional()}).optional(),yk=y({tradingPairId:xe,side:Cp,positionSide:Ah.optional(),orderType:Op,price:Ze.optional(),quantity:Ze,leverage:Ze.optional(),reduceOnly:oe().optional(),slippageToleranceBps:Np.optional()}),bk=(e,t)=>{if(e.orderType!=="MARKET"&&e.slippageToleranceBps!==void 0)t.addIssue({code:wa.custom,message:"slippageToleranceBps is only supported for MARKET orders",path:["slippageToleranceBps"]});if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:wa.custom,message:"positionSide must match side when provided (BUY=LONG, SELL=SHORT)",path:["positionSide"]})}if(e.reduceOnly!==!0&&e.leverage===void 0)t.addIssue({code:wa.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},PH=yk.strict().superRefine(bk),_he=yk.merge(EH).strict().superRefine(bk),The=yk.merge(xhe).strict().superRefine(bk),vhe=y({marginMode:z(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Nt().optional()}).loose().superRefine((e,t)=>{if(e.selectedTradingPairIds===void 0)return;t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:e.marginMode==="CROSS"?"selectedTradingPairIds is not accepted on a CROSS preview: cross scope is derived from trading, so a preview has nothing to declare":"selectedTradingPairIds is not supported for ISOLATED risk buckets"})}),Ehe=vhe.pipe(pt([_he,The])),l8t=y({marginAccountId:xe,request:PH}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),d8t=y({request:PH}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),p8t=y({request:Ehe}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),f8t=y({request:y({subaccountKey:p().trim().min(1,"subaccountKey is required").max(64,"subaccountKey must be at most 64 characters").regex(/^[A-Za-z0-9_.:-]+$/,"subaccountKey may contain only letters, digits, '_', '-', '.' and ':'").refine((e)=>!e.toLowerCase().startsWith("copy:"),"sub-account keys starting with copy: are reserved").refine((e)=>e!=="default","default names the default margin account"),label:p().optional()}).strict()}),m8t=y({marginAccountId:xe}),h8t=y({marginAccountId:xe,amount:Ze}),g8t=y({marginAccountId:xe}),vH=pt([y({wallet:Ae(!0)}).strict(),y({marginAccountId:xe,riskBucketId:xe.optional()}).strict()]),y8t=y({request:y({asset:p().trim().min(1,"Asset is required"),amount:Ze,from:vH,to:vH}).strict()});var AH=z(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),Phe=31536000000,Ahe=946684800000,vw=I().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(Ahe,{message:"Timestamp must be at least Jan 1, 2000 (946684800000 ms). Did you pass seconds instead of milliseconds?"}).max(Number.MAX_SAFE_INTEGER,{message:"Timestamp must not exceed JavaScript's maximum safe integer"}).refine((e)=>e<=Date.now()+Phe,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),S8t=y({tradingPairId:xe,interval:AH,startTime:vw,endTime:vw}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),_8t=p().min(1,"Trading pair symbol cannot be empty").regex(/^[A-Za-z0-9]{1,10}\/[A-Za-z0-9]{1,10}$/,{message:'Trading pair symbol must be in format "BASE/QUOTE" (e.g., "BTC/USDT", "ETH/USD")'}),Ihe=I().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),T8t=y({tradingPairId:xe,interval:AH,startTime:vw.optional(),endTime:vw.optional(),limit:Ihe,priceType:z(["trade","mark"]).optional()}).refine((e)=>{if(e.startTime!==void 0&&e.endTime!==void 0)return e.startTime<e.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var v8t=y({tradingPairId:xe}),E8t=y({query:p().min(1,"Search query cannot be empty").optional(),pageSize:I().int().min(1).max(100).optional(),page:I().int().min(1).optional()}),P8t=y({tradingPairId:xe}),A8t=y({page:Qe().optional(),startTime:p().optional(),endTime:p().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),orderBy:z(["ASC","DESC"],{message:'orderBy must be "ASC" or "DESC"'}).optional()});var I8t=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});var kH=y({page:Qe().optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),khe=z(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),Rhe=z(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),xk=y({positionId:xe}),O8t=kH.extend({marginAccountId:xe.optional(),tradingPairId:xe.optional(),status:khe.optional()});var M8t=xk.extend({request:y({closeType:Rhe,limitPrice:Ze.optional(),slippageToleranceBps:Mp.optional(),quantity:Ze.optional()})}).refine((e)=>e.request.closeType==="MARKET"||e.request.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["request","limitPrice"]}).refine((e)=>e.request.closeType!=="MARKET"||e.request.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["request","limitPrice"]}),N8t=y({tradingPairId:xe.optional(),tradingPairIds:ie(xe).min(1,{message:"tradingPairIds must list at least one trading pair; omit it to close every pair"}).max(256,{message:"tradingPairIds accepts at most 256 trading pairs"}).optional(),side:SH.optional(),slippageToleranceBps:Mp.optional()}).strict().refine((e)=>e.tradingPairId===void 0||e.tradingPairIds===void 0,{message:"Pass tradingPairId or tradingPairIds, not both",path:["tradingPairIds"]});var IH=y({triggerPrice:Ze,orderType:Op,limitPrice:Ze.optional(),quantity:Ze.optional(),closePosition:oe().optional(),timeInForce:pk.optional(),slippageToleranceBps:Mp.optional(),expiresAt:Qs.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT TP/SL legs",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET TP/SL legs",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),$8t=xk.extend({request:y({takeProfit:IH.optional(),stopLoss:IH.optional(),trailingStop:fk.optional(),oco:oe().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0||e.trailingStop!==void 0,{message:"At least one of takeProfit, stopLoss, or trailingStop is required"}).refine((e)=>e.oco!==!0||e.takeProfit!==void 0&&e.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),z8t=kH.extend({positionId:xe.optional(),marginAccountId:xe.optional(),tradingPairId:xe.optional(),reductionOnly:oe().optional()}),Che=z(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),L8t=xk.extend({params:y({interval:Che,startTime:I().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:I().int().min(0,"endTime must be a non-negative millisecond timestamp").optional()}).refine((e)=>e.startTime===void 0||e.endTime===void 0||e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["startTime"]})});var Ohe=z(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),Mhe=z(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),U8t=y({mode:zu}),j8t=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),orderBy:z(["ASC","DESC"]).optional(),entryType:Ohe.optional(),transactionType:Mhe.optional(),assetId:xe.optional()}),q8t=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),tradingPairId:xe.optional(),pageToken:p().optional()}),H8t=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),G8t=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),tradingPairId:xe.optional(),positionId:xe.optional(),marginAccountId:xe.optional()});var K8t=p().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),wk=pt([p().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),qC().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),Y8t=y({assetId:xe,amount:wk,autoWait:oe().optional()}),J8t=y({assetId:xe,amount:wk,autoWait:oe().optional(),target:z(["spot","margin"]).optional(),options:y({asErc20:oe().optional()}).optional()}),Q8t=y({assetId:xe,amount:wk,destination:p().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:oe().optional(),source:z(["spot","margin"]).optional()}),X8t=y({assetId:xe}),e3t=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});function RH(e){e.registerTool("simulate_parent_margin_order_risk",{description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),side:z(["BUY","SELL"]).describe("Order side (authoritative: BUY=LONG, SELL=SHORT)"),orderType:z(["LIMIT","MARKET"]).describe("Order type"),quantity:p().describe("Order quantity as a decimal string"),price:p().optional().describe("Limit price as a decimal string — required for LIMIT"),leverage:p().optional().describe("Leverage as a decimal string — required unless reduceOnly is true"),reduceOnly:oe().optional().describe("Whether the order can only reduce exposure"),slippageToleranceBps:Np.optional().describe("MARKET only: slippage tolerance in bps (0..1000), tightening the previewed walk to the band placement will use; the response's expectedMatchResult (the engine's simulated fill, in the same shape as a placement's matchResult) and estimatedFee price under it")}).refine((t)=>t.orderType!=="LIMIT"||t.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["price"]}).refine((t)=>t.reduceOnly===!0||t.leverage!==void 0,{message:"leverage is required for normal (non-reduce-only) margin orders",path:["leverage"]}).refine((t)=>t.orderType==="MARKET"||t.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only supported for MARKET orders",path:["slippageToleranceBps"]})},async({tradingPairId:t,side:r,orderType:n,quantity:o,price:i,leverage:s,reduceOnly:a,slippageToleranceBps:c})=>{let d=await(await H()).marginAccounts.simulateParentMarginOrderRisk({tradingPairId:t,side:r,orderType:n,quantity:o,price:i,leverage:s,reduceOnly:a,slippageToleranceBps:c});return C(d)})}function CH(e){e.registerTool("simulate_risk_bucket_order_risk",{description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation). A CROSS preview names no pairs: cross scope is derived from trading (a pair joins the cross risk bucket when a cross order on it succeeds and, once its positions close, stays listed until a later successful cross order on another pair reconciles the bucket), and the response's selectedTradingPairIds reports the derived scope the preview ran against. Unknown input keys are rejected.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),side:z(["BUY","SELL"]).describe("Order side (authoritative: BUY=LONG, SELL=SHORT)"),positionSide:z(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),orderType:z(["LIMIT","MARKET"]).describe("Order type"),quantity:p().describe("Order quantity as a decimal string"),price:p().optional().describe("Limit price as a decimal string — required for LIMIT"),leverage:p().optional().describe("Leverage as a decimal string — required unless reduceOnly is true"),reduceOnly:oe().optional().describe("Whether the order can only reduce exposure"),slippageToleranceBps:Np.optional().describe("MARKET only: slippage tolerance in bps (0..1000), tightening the previewed walk to the band placement will use; the response's expectedMatchResult (the engine's simulated fill, in the same shape as a placement's matchResult) and estimatedFee price under it"),marginMode:z(["ISOLATED","CROSS"]).optional().describe("Risk bucket margin mode (default ISOLATED)"),strategyKey:p().optional().describe("Isolated risk bucket strategy key (ISOLATED only)")}).strict().refine((t)=>t.orderType!=="LIMIT"||t.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["price"]}).refine((t)=>t.reduceOnly===!0||t.leverage!==void 0,{message:"leverage is required for normal (non-reduce-only) margin orders",path:["leverage"]}).refine((t)=>t.orderType==="MARKET"||t.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only supported for MARKET orders",path:["slippageToleranceBps"]}).refine((t)=>t.marginMode!=="CROSS"||t.strategyKey===void 0,{message:"strategyKey is not allowed for CROSS risk buckets",path:["strategyKey"]})},async({tradingPairId:t,side:r,positionSide:n,orderType:o,quantity:i,price:s,leverage:a,reduceOnly:c,slippageToleranceBps:l,marginMode:d,strategyKey:f})=>{let h=await H(),g={tradingPairId:t,side:r,positionSide:n,orderType:o,quantity:i,price:s,leverage:a,reduceOnly:c,slippageToleranceBps:l},x=d==="CROSS"?await h.marginAccounts.simulateRiskBucketOrderRisk({...g,marginMode:d}):await h.marginAccounts.simulateRiskBucketOrderRisk({...g,marginMode:d,strategyKey:f});return C(x)})}function OH(e){e.registerTool("transfer_collateral_from_parent_margin_account",{description:"Move collateral out of your parent (cross) margin account back to spot.",inputSchema:y({asset:p().describe("Collateral asset symbol or ID"),amount:p().describe("Amount to transfer as a decimal string")})},async({asset:t,amount:r})=>{let o=await(await H()).marginAccounts.transferCollateralFromParentMarginAccount({asset:t,amount:r});return C(o)})}function MH(e){e.registerTool("transfer_collateral_from_sub_account",{description:"Move collateral from one of your margin sub-accounts back to your default (parent) margin account.",inputSchema:y({marginAccountId:p().describe("The margin sub-account ID (not the default margin account)"),amount:p().describe("Amount to transfer as a decimal string")})},async({marginAccountId:t,amount:r})=>{let o=await(await H()).marginAccounts.transferCollateralFromSubAccount(t,r);return C(o)})}function NH(e){e.registerTool("transfer_collateral_to_parent_margin_account",{description:"Move collateral from spot into your parent (cross) margin account.",inputSchema:y({asset:p().describe("Collateral asset symbol or ID"),amount:p().describe("Amount to transfer as a decimal string")})},async({asset:t,amount:r})=>{let o=await(await H()).marginAccounts.transferCollateralToParentMarginAccount({asset:t,amount:r});return C(o)})}function $H(e){e.registerTool("transfer_collateral_to_risk_bucket",{description:"Allocate collateral into an isolated or cross risk bucket. A cross transfer names no pairs: cross scope is derived from trading (a pair joins the cross bucket when a cross order on it succeeds and leaves when its positions close).",inputSchema:y({asset:p().describe("Collateral asset symbol or ID"),amount:p().describe("Amount to transfer as a decimal string"),marginMode:z(["ISOLATED","CROSS"]).optional().describe("Risk bucket margin mode (default ISOLATED)"),tradingPairId:p().optional().describe("Trading pair UUID (required for ISOLATED; not allowed for CROSS)"),strategyKey:p().optional().describe("Isolated risk bucket strategy key (ISOLATED only)"),applyToPositionMargin:oe().optional().describe("ISOLATED only. Omitted/true (Adjust Margin, the default): commit the amount to the sole open position's stored margin — leverage drops and stays down, initial margin required rises, free collateral is unchanged. false: plain allocation — free collateral rises and the next order can spend it; funding loops targeting free collateral MUST pass false.")}).strict().refine((t)=>t.marginMode==="CROSS"||t.tradingPairId!==void 0,{message:"tradingPairId is required for ISOLATED risk buckets",path:["tradingPairId"]}).refine((t)=>t.marginMode!=="CROSS"||t.tradingPairId===void 0,{message:"tradingPairId is not allowed for CROSS risk buckets",path:["tradingPairId"]}).refine((t)=>t.marginMode!=="CROSS"||t.strategyKey===void 0,{message:"strategyKey is not allowed for CROSS risk buckets",path:["strategyKey"]}).refine((t)=>t.marginMode!=="CROSS"||t.applyToPositionMargin===void 0,{message:"applyToPositionMargin is only allowed for ISOLATED risk buckets",path:["applyToPositionMargin"]})},async({asset:t,amount:r,marginMode:n,tradingPairId:o,strategyKey:i,applyToPositionMargin:s})=>{let a=await H(),c=n==="CROSS"?await a.marginAccounts.transferCollateralToRiskBucket({asset:t,amount:r,marginMode:n}):await a.marginAccounts.transferCollateralToRiskBucket({asset:t,amount:r,marginMode:n,tradingPairId:o??"",strategyKey:i,applyToPositionMargin:s});return C(c)})}function zH(e){e.registerTool("transfer_collateral_to_sub_account",{description:"Move collateral from your default (parent) margin account into one of your margin sub-accounts.",inputSchema:y({marginAccountId:p().describe("The margin sub-account ID (not the default margin account)"),amount:p().describe("Amount to transfer as a decimal string")})},async({marginAccountId:t,amount:r})=>{let o=await(await H()).marginAccounts.transferCollateralToSubAccount(t,r);return C(o)})}function LH(e){Z7(e),K7(e),V7(e),W7(e),RH(e),CH(e),NH(e),OH(e),$H(e),zH(e),MH(e)}function BH(e){e.registerTool("get_candlesticks",{description:"Get OHLCV candlestick data for a trading pair. Useful for charting and price analysis.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),interval:z(["1m","5m","15m","1h","4h","1d"]).describe("Candlestick interval"),startTime:I().optional().describe("Start time as Unix timestamp (seconds)"),endTime:I().optional().describe("End time as Unix timestamp (seconds)"),limit:I().optional().describe("Max number of candlesticks to return")})},async({tradingPairId:t,interval:r,startTime:n,endTime:o,limit:i})=>{let a=await Ge().market.getCandlesticks(t,r,{startTime:n,endTime:o,limit:i});return C(a)})}function DH(e){e.registerTool("get_market_metadata",{description:"Get metadata for a specific trading pair including tick size, min order size, and trading rules.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ge().market.getMarketMetadata(t);return C(n)})}function FH(e){e.registerTool("get_market_stats",{description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets."},async()=>{let r=await Ge().market.getMarketStats();return C(r)})}function UH(e){e.registerTool("get_screener",{description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",inputSchema:y({page:I().optional().describe("Page number (1-based)"),pageSize:I().optional().describe("Items per page"),marketType:z(["SPOT","MARGIN"]).optional().describe("Filter by market type"),isActive:oe().optional().describe("Filter by active status"),category:p().optional().describe("Filter by category (e.g. crypto, equities, commodities)")})},async({page:t,pageSize:r,marketType:n,isActive:o,category:i})=>{let a=await Ge().market.getScreener({page:t,pageSize:r,marketType:n,isActive:o,category:i});return C(a)})}function jH(e){e.registerTool("get_trading_pair_by_symbol",{description:"Look up a specific trading pair by its symbol (e.g. 'BTC/USDC'). Returns the pair's full details including its UUID.",inputSchema:y({symbol:p().describe("Trading pair symbol (e.g. 'BTC/USDC')")})},async({symbol:t})=>{let n=await Ge().market.getTradingPairBySymbol(t);if(!n)return hw(`Trading pair '${t}' not found.`);return C(n)})}function qH(e){e.registerTool("get_trading_pairs",{description:"Get a paginated list of trading pairs available on Monaco. Returns pair IDs, symbols, base/quote tokens, and status.",inputSchema:y({page:I().optional().describe("Page number (starts from 1)"),pageSize:I().optional().describe("Number of items per page (max 100)"),marketType:z(["SPOT","MARGIN"]).optional().describe("Filter by market type"),baseToken:p().optional().describe("Filter by base token"),quoteToken:p().optional().describe("Filter by quote token"),isActive:oe().optional().describe("Filter by active status"),category:p().optional().describe("Filter by category (e.g. crypto, equities, commodities)")})},async(t)=>{let n=await Ge().market.getPaginatedTradingPairs(t);return C(n)})}function HH(e){qH(e),jH(e),BH(e),DH(e),UH(e),FH(e)}function GH(e){e.registerTool("get_orderbook",{description:"Get the current orderbook snapshot for a trading pair. Shows bids, asks, best bid/ask, and volumes.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),depth:I().optional().describe("Number of price levels to return (max 100, default 10)"),tradingMode:z(["SPOT"]).optional().describe("Trading mode (default: SPOT)"),magnitude:I().optional().describe("Price grouping magnitude (e.g. 0.01, 0.1, 1, 10, 100)"),denomination:z(["BASE","QUOTE"]).optional().describe("Quantity denomination: BASE or QUOTE")})},async({tradingPairId:t,depth:r,tradingMode:n,magnitude:o,denomination:i})=>{let a=await Ge().orderbook.getOrderbook(t,{depth:r,tradingMode:n,magnitude:o,denomination:i});return C(a)})}function VH(e){GH(e)}function ZH(e){e.registerTool("get_all_funding_history",{description:"List historical funding-rate records across all perpetual markets. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({startTime:p().optional().describe('Start time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),endTime:p().optional().describe('End time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 50, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page"),orderBy:z(["ASC","DESC"]).optional().describe("Sort order by time")}).strict()},async({startTime:t,endTime:r,pageSize:n,pageToken:o,orderBy:i})=>{let a=await Ge().market.listAllFundingHistory({startTime:t,endTime:r,pageSize:n,pageToken:o,orderBy:i});return C(a)})}function WH(e){e.registerTool("get_funding_history",{description:"List historical funding-rate records for a perpetual market. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),startTime:p().optional().describe('Start time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),endTime:p().optional().describe('End time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 50, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page"),orderBy:z(["ASC","DESC"]).optional().describe("Sort order by time")}).strict()},async({tradingPairId:t,startTime:r,endTime:n,pageSize:o,pageToken:i,orderBy:s})=>{let c=await Ge().market.listFundingHistory(t,{startTime:r,endTime:n,pageSize:o,pageToken:i,orderBy:s});return C(c)})}function KH(e){e.registerTool("get_funding_state",{description:"Get the current funding rate and next funding time for a perpetual market.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ge().market.getFundingState(t);return C(n)})}function YH(e){e.registerTool("get_index_price",{description:"Get the current index (oracle) price for a perpetual market.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ge().market.getIndexPrice(t);return C(n)})}function JH(e){e.registerTool("get_mark_price",{description:"Get the current mark price for a perpetual market.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ge().market.getMarkPrice(t);return C(n)})}function QH(e){e.registerTool("get_open_interest",{description:"Get the current gross open interest (longs plus shorts) for a perpetual market.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ge().market.getOpenInterest(t);return C(n)})}function XH(e){e.registerTool("get_perp_market_config",{description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",inputSchema:y({tradingPairId:p().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ge().market.getPerpMarketConfig(t);return C(n)})}function eG(e){e.registerTool("get_perp_market_summary",{description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",inputSchema:y({tradingPairId:p().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ge().market.getPerpMarketSummary(t);return C(n)})}function tG(e){XH(e),eG(e),JH(e),YH(e),KH(e),QH(e),WH(e),ZH(e)}function rG(e){e.registerTool("get_portfolio_assets",{description:"Get your per-asset portfolio allocation and balances over a period.",inputSchema:y({period:z(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await H()).portfolio.getAssets({period:t});return C(n)})}function nG(e){e.registerTool("get_portfolio_margin",{description:"Get your portfolio margin overview (collateral, maintenance margin, health)."},async()=>{let r=await(await H()).portfolio.getMargin();return C(r)})}function oG(e){e.registerTool("get_portfolio_performance",{description:"Get your portfolio performance time series over a period.",inputSchema:y({period:z(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await H()).portfolio.getPerformance({period:t});return C(n)})}function iG(e){e.registerTool("get_portfolio_realized_pnl",{description:"Get your realized PnL breakdown over a period.",inputSchema:y({period:z(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await H()).portfolio.getRealizedPnl({period:t});return C(n)})}function sG(e){e.registerTool("get_portfolio_summary",{description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",inputSchema:y({period:z(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await H()).portfolio.getSummary({period:t});return C(n)})}function aG(e){sG(e),oG(e),iG(e),rG(e),nG(e)}function cG(e){e.registerTool("close_position",{description:"Close a perpetual position with a market, limit, or IOC reduce order.",inputSchema:y({positionId:p().describe("Position UUID"),closeType:z(["MARKET","LIMIT","IOC"]).describe("Close order type"),limitPrice:p().optional().describe("Limit price as a decimal string — required for LIMIT and IOC, not allowed for MARKET"),slippageToleranceBps:I().optional().describe("Slippage tolerance in basis points (MARKET/IOC)"),quantity:p().optional().describe("Quantity to close as a decimal string (defaults to full position)")}).refine((t)=>t.closeType==="MARKET"||t.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["limitPrice"]}).refine((t)=>t.closeType!=="MARKET"||t.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["limitPrice"]})},async({positionId:t,closeType:r,limitPrice:n,slippageToleranceBps:o,quantity:i})=>{let a=await(await H()).positions.closePosition(t,{closeType:r,limitPrice:n,slippageToleranceBps:o,quantity:i});return C(a)})}function uG(e){e.registerTool("get_position",{description:"Get details for a specific perpetual position by ID. lifetimeTotalsStatus says whether the lifetime totals (exitPrice, realizedRoe, feesPaid, fundingPaid, cumFees, netRealizedPnl) are served: COMPLETE means they follow their own rules, PENDING means history is still catching up or the row changed while it was being read, so retry in a few seconds, INCOMPLETE means the lifetime totals are not complete now and a quick retry will not change that: a legacy-history gap (or reductions that do not reconcile) is permanent, while a missing or drifted maintained-totals row is repaired by the background reconcile (at startup and daily); every total that is present comes from the maintained totals, which are cross-checked against each other and repaired by the background reconcile (e.g. exitPrice can be present while cumFees is absent). OPEN and LIQUIDATING positions are checked against realized PnL too: an OPEN or LIQUIDATING row whose reductions do not account for it is INCOMPLETE with no cumFees. Never read an absent total as zero.",inputSchema:y({positionId:p().describe("Position UUID")})},async({positionId:t})=>{let n=await(await H()).positions.getPosition(t);return C(n)})}function lG(e){e.registerTool("get_position_history",{description:"List historical (closed/reduced) perpetual position records with optional filters. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({positionId:p().optional().describe("Filter by position UUID"),marginAccountId:p().optional().describe("Filter by margin account UUID"),tradingPairId:p().optional().describe("Filter by trading pair UUID"),pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page"),reductionOnly:oe().optional().describe("Only include reduction events")})},async({positionId:t,marginAccountId:r,tradingPairId:n,pageSize:o,pageToken:i,reductionOnly:s})=>{let c=await(await H()).positions.listPositionHistory({positionId:t,marginAccountId:r,tradingPairId:n,pageSize:o,pageToken:i,reductionOnly:s});return C(c)})}function dG(e){e.registerTool("get_position_pnl_history",{description:"Get the PnL history time series for a perpetual position over an interval.",inputSchema:y({positionId:p().describe("Position UUID"),interval:z(["1m","5m","15m","1h","4h","1d"]).describe("Sampling interval"),startTime:I().int().min(0).optional().describe("Start time as a Unix timestamp in milliseconds"),endTime:I().int().min(0).optional().describe("End time as a Unix timestamp in milliseconds")}).refine((t)=>t.startTime===void 0||t.endTime===void 0||t.startTime<t.endTime,{message:"startTime must be less than endTime",path:["startTime"]})},async({positionId:t,interval:r,startTime:n,endTime:o})=>{let s=await(await H()).positions.getPositionPnlHistory(t,{interval:r,startTime:n,endTime:o});return C(s)})}function pG(e){e.registerTool("get_position_risk",{description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",inputSchema:y({positionId:p().describe("Position UUID")})},async({positionId:t})=>{let n=await(await H()).positions.getPositionRisk(t);return C(n)})}function fG(e){e.registerTool("get_positions",{description:"List your perpetual positions with optional filters (margin account, trading pair, status). Cursor paged; an empty nextPageToken means the end. Each row's lifetimeTotalsStatus says whether the lifetime totals (exitPrice, realizedRoe, feesPaid, fundingPaid, cumFees, netRealizedPnl) are served: COMPLETE means they follow their own rules, PENDING means history is still catching up or the row changed while it was being read, so retry in a few seconds, INCOMPLETE means the lifetime totals are not complete now and a quick retry will not change that: a legacy-history gap (or reductions that do not reconcile) is permanent, while a missing or drifted maintained-totals row is repaired by the background reconcile (at startup and daily); every total that is present comes from the maintained totals, which are cross-checked against each other and repaired by the background reconcile (e.g. exitPrice can be present while cumFees is absent). OPEN and LIQUIDATING positions are checked against realized PnL too: an OPEN or LIQUIDATING row whose reductions do not account for it is INCOMPLETE with no cumFees. Never read an absent total as zero.",inputSchema:y({marginAccountId:p().optional().describe("Filter by margin account UUID"),tradingPairId:p().optional().describe("Filter by trading pair UUID"),status:z(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"]).optional().describe("Filter by position status"),pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")})},async({marginAccountId:t,tradingPairId:r,status:n,pageSize:o,pageToken:i})=>{let a=await(await H()).positions.listPositions({marginAccountId:t,tradingPairId:r,status:n,pageSize:o,pageToken:i});return C(a)})}function mG(e){fG(e),uG(e),pG(e),lG(e),dG(e),cG(e)}function hG(e){e.registerTool("get_balance_by_asset",{description:"Get the authenticated user's balance for a specific asset by its UUID.",inputSchema:y({assetId:p().describe("The asset UUID")})},async({assetId:t})=>{let n=await(await H()).profile.getUserBalanceByAssetId(t);return C(n)})}function gG(e){e.registerTool("get_balances",{description:"Get the authenticated user's token balances. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")})},async({pageSize:t,pageToken:r})=>{let o=await(await H()).profile.getUserBalances({pageSize:t,pageToken:r});return C(o)})}function yG(e){e.registerTool("get_funding_payments",{description:"List your perpetual funding payments with optional filters (trading pair, position, margin account). Cursor paged; an empty nextPageToken means the end.",inputSchema:y({tradingPairId:p().optional().describe("Filter by trading pair UUID"),positionId:p().optional().describe("Filter by position UUID"),marginAccountId:p().optional().describe("Filter by margin account UUID"),pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")}).strict()},async({tradingPairId:t,positionId:r,marginAccountId:n,pageSize:o,pageToken:i})=>{let a=await(await H()).profile.listFundingPayments({tradingPairId:t,positionId:r,marginAccountId:n,pageSize:o,pageToken:i});return C(a)})}function bG(e){e.registerTool("get_movements",{description:"Get the authenticated user's ledger movements (transaction history). Cursor paged; an empty nextPageToken means the end.",inputSchema:y({pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page"),orderBy:z(["ASC","DESC"]).optional().describe("Sort direction for createdAt (default DESC)"),entryType:z(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"]).optional().describe("Filter by entry type (e.g. CREDIT, DEBIT, LOCK, UNLOCK, FEE)"),transactionType:z(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"]).optional().describe("Filter by transaction type (e.g. DEPOSIT, WITHDRAWAL, TRADE, FEE, FUNDING, LIQUIDATION, INTEREST, REWARD)"),assetId:p().uuid().optional().describe("Filter by asset ID (UUID)")})},async({pageSize:t,pageToken:r,orderBy:n,entryType:o,transactionType:i,assetId:s})=>{let c=await(await H()).profile.getPaginatedUserMovements({pageSize:t,pageToken:r,orderBy:n,entryType:o,transactionType:i,assetId:s});return C(c)})}function xG(e){e.registerTool("get_profile",{description:"Get the authenticated user's profile including address, username, account type, and withdrawal status. Use get_balances, get_movements, and get_orders for detailed account data."},async()=>{let r=await(await H()).profile.getProfile();return C(r)})}function wG(e){e.registerTool("get_user_trades",{description:"List your own trade fills with optional filters and cursor pagination.",inputSchema:y({tradingPairId:p().optional().describe("Filter by trading pair UUID"),pageSize:I().optional().describe("Items per page"),pageToken:p().optional().describe("Cursor for the next page")})},async({tradingPairId:t,pageSize:r,pageToken:n})=>{let i=await(await H()).profile.getUserTrades({tradingPairId:t,pageSize:r,pageToken:n});return C(i)})}function SG(e){xG(e),gG(e),hG(e),bG(e),wG(e),yG(e)}function _G(e){e.registerTool("get_pulse",{description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags."},async()=>{let r=await Ge().pulse.getPulse();return C(r)})}function TG(e){_G(e)}var Nhe="https://docs.0xmonaco.com/mcp",$he="SearchMonacoDocs",Ew=null;async function vG(e,t,r){let n=await fetch(Nhe,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...Ew?{"Mcp-Session-Id":Ew}:{}},body:JSON.stringify({jsonrpc:"2.0",id:r,method:e,params:t})});if(!n.ok)throw Error(`Mintlify MCP error: ${n.status}`);let o=n.headers.get("mcp-session-id");if(o)Ew=o;let s=(await n.text()).split(`
151
+ "@signature-params": ${l}`;return{"Signature-Input":`monaco=${l}`,Signature:`monaco=:${r7(Xl.sign(Qc(d),e.privateKey))}:`,"Content-Digest":c}}var Xfe="@0xmonaco/core";class Ye{apiUrl;sessionKeypair;requestSigning="legacy";redirectPolicy;serverClock=new cu;setRequestSigning(e){if(e!=="legacy"&&e!=="rfc9421")throw Error("Unsupported request signing protocol");this.requestSigning=e}setRedirectPolicy(e){this.redirectPolicy=e}retryOptions;setServerClock(e){this.serverClock=e}constructor(e,t){this.apiUrl=e,this.retryOptions={maxRetries:t?.maxRetries??3,baseDelayMs:t?.baseDelayMs??1000}}setSessionKeypair(e){this.sessionKeypair=e?EB(e.publicKey,e.privateKey):void 0}parseRequestBody(e){if(!e)return;if(typeof e==="string")try{return JSON.parse(e)}catch{return e}if(e instanceof FormData){let t={};return e.forEach((r,n)=>{t[n]=r instanceof File?`[File: ${r.name}]`:r}),t}if(e instanceof URLSearchParams){let t={};return e.forEach((r,n)=>{t[n]=r}),t}if(e instanceof Blob)return{type:"[Blob]",size:e.size,contentType:e.type};if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return{type:"[ArrayBuffer]",size:e instanceof ArrayBuffer?e.byteLength:e.byteLength};if(typeof ReadableStream<"u"&&e instanceof ReadableStream)return{type:"[ReadableStream]",note:"Stream body not captured for logging"};return{type:"[Unknown]",bodyType:typeof e}}extractResponseMetadata(e){if(!e)return{};let t=e.get("x-request-id")||e.get("request-id")||e.get("x-correlation-id")||void 0,r=e.get("retry-after"),n;if(r!==null){let o=r.trim();if(/^\d+$/.test(o))n=Number.parseInt(o,10);else{let i=B0(o);if(i!==void 0)n=Math.max(0,Math.ceil((i-Date.now())/1000))}}return{requestId:t,retryAfter:n}}async executeRequest(e,t,r,n){let o,i={"User-Agent":Xfe,...r.headers};try{o=await fetch(e,{...r,headers:i,...this.redirectPolicy?{redirect:this.redirectPolicy}:{}})}catch(l){throw new sr(`Network request failed for ${t}`,{endpoint:e,cause:l instanceof Error?l:Error(String(l)),requestBody:n})}this.serverClock.observeResponse(o.headers,Date.now());let s,a=o.headers?.get("content-type")||"unknown",c=o.clone?o.clone():o;try{s=await o.json()}catch(l){let d;try{d=await c.text()}catch{d="[Unable to read response body]"}if(!o.ok){let f=`API request failed: ${o.status}. Response is not JSON (Content-Type: ${a})`,{requestId:h,retryAfter:g}=this.extractResponseMetadata(o.headers);throw new sr(f,{endpoint:e,statusCode:o.status,responseBody:{rawResponse:d.substring(0,500),contentType:a,parseError:l instanceof Error?l.message:String(l)},cause:l instanceof Error?l:void 0,requestBody:n,requestId:h,retryAfter:g})}if(d.trim()==="")return;throw new sr(`Expected JSON response but received ${a}`,{endpoint:e,statusCode:o.status,responseBody:{rawResponse:d.substring(0,500),contentType:a},cause:l instanceof Error?l:void 0,requestBody:n})}if(!o.ok){let l=s!==null&&typeof s==="object"?s:void 0,d=(typeof l?.message==="string"?l.message:void 0)||(typeof l?.error==="string"?l.error:void 0)||`API request failed: ${o.status}`,{requestId:f,retryAfter:h}=this.extractResponseMetadata(o.headers);throw new sr(d,{endpoint:e,statusCode:o.status,responseBody:s,requestBody:n,requestId:f,retryAfter:h})}return s}async makeAuthenticatedRequest(e,t={}){if(!this.sessionKeypair)throw new sr("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:Gx.StatusCodes.UNAUTHORIZED});let r=`${this.apiUrl}${e}`,n=this.parseRequestBody(t.body),o=t.headers;if(this.requestSigning==="rfc9421"){let a={};new Headers(t.headers).forEach((c,l)=>{a[l]=c}),o=a}let i=()=>this.executeRequest(r,e,{...t,...this.requestSigning==="rfc9421"?{redirect:"error"}:{},headers:{"Content-Type":"application/json",...o,...this.buildSignatureHeaders(e,t)}},n),s=this.serverClock.offsetMs;try{return await i()}catch(a){let c=Math.abs(this.serverClock.offsetMs-s)>=Kv;if(a instanceof sr&&a.statusCode===Gx.StatusCodes.UNAUTHORIZED&&c)return i();throw a}}buildSignatureHeaders(e,t){if(!this.sessionKeypair)throw new sr("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:Gx.StatusCodes.UNAUTHORIZED});let r=(t.method??"GET").toUpperCase();if(this.requestSigning==="rfc9421"){if(t.body!=null&&typeof t.body!=="string")throw Error("Signed requests require a string body");let c=new Headers(t.headers);for(let d of["signature","signature-input","content-digest","x-monaco-publickey","x-monaco-timestamp","x-monaco-signature"])if(c.has(d))throw Error("Signature headers are managed by the SDK");let l=new URL(`${this.apiUrl}${e}`);return n7(this.sessionKeypair,r,l.pathname+l.search,Qc(t.body??""),Math.floor(this.serverClock.now()/1000))}let n=this.serverClock.now(),o=typeof t.body==="string"?Qc(t.body):new Uint8Array(0),i=PB(o),s=AB(r,e,n,i),a=L0(this.sessionKeypair.privateKey,s);return{"X-Monaco-PublicKey":hs(this.sessionKeypair.publicKey),"X-Monaco-Timestamp":String(n),"X-Monaco-Signature":a}}async makePublicRequest(e,t={}){let r=`${this.apiUrl}${e}`,n=this.parseRequestBody(t.body);return this.executeRequest(r,e,{...t,headers:{"Content-Type":"application/json",...t.headers}},n)}}function it(e){return encodeURIComponent(e)}function Ht(e,t){if(!t)return e;let r=new URLSearchParams;for(let[o,i]of Object.entries(t))if(i!==void 0)r.set(o,String(i));let n=r.toString();return n?`${e}?${n}`:e}var ue={orders:{create:()=>"/api/v1/orders",list:(e)=>Ht("/api/v1/orders",e),get:(e)=>`/api/v1/orders/${it(e)}`,replace:(e)=>`/api/v1/orders/${it(e)}`,cancel:()=>"/api/v1/orders/cancel",batchCancel:()=>"/api/v1/orders/batch-cancel",batchCancelAll:()=>"/api/v1/orders/batch-cancel-all",batchCancelAllByPair:(e)=>`/api/v1/orders/batch-cancel-all/${it(e)}`,batchCreate:()=>"/api/v1/orders/batch-create",batchReplace:()=>"/api/v1/orders/batch-replace",listConditional:(e)=>Ht("/api/v1/orders/conditional",e),cancelConditional:(e)=>`/api/v1/orders/conditional/${it(e)}`,getConditional:(e)=>`/api/v1/orders/conditional/${it(e)}`,createTwap:()=>"/api/v1/orders/twap",listTwap:(e)=>Ht("/api/v1/orders/twap",e),getTwap:(e)=>`/api/v1/orders/twap/${it(e)}`,getTwapTca:(e)=>`/api/v1/orders/twap/${it(e)}/tca`,listTwapSlices:(e,t)=>Ht(`/api/v1/orders/twap/${it(e)}/slices`,t),cancelTwap:(e)=>`/api/v1/orders/twap/${it(e)}/cancel`},delegatedAgents:{list:()=>"/api/v1/delegated-agents",owners:()=>"/api/v1/delegated-agents/owners",byId:(e)=>`/api/v1/delegated-agents/${it(e)}`,sessions:()=>"/api/v1/delegated-agents/sessions"},withdrawals:{initiate:()=>"/api/v1/withdrawals",byIndex:(e)=>`/api/v1/withdrawals/${it(String(e))}`,list:(e)=>Ht("/api/v1/withdrawals",e)},market:{listTradingPairs:(e)=>Ht("/api/v1/market/pairs",e),getTradingPair:(e)=>`/api/v1/market/pairs/${it(e)}`,getCandles:(e,t,r)=>Ht(`/api/v1/market/pairs/charts/candlestick/${it(e)}/${it(t)}`,r),getMarketMetadata:(e)=>`/api/v1/market/pairs/${it(e)}/metadata`,getPerpMarketConfig:(e)=>`/api/v1/market/pairs/${it(e)}/perp/config`,getPerpMarketSummary:(e)=>`/api/v1/market/pairs/${it(e)}/perp/summary`,getMarkPrice:(e)=>`/api/v1/market/pairs/${it(e)}/mark-price`,getIndexPrice:(e)=>`/api/v1/market/pairs/${it(e)}/index-price`,getFundingState:(e)=>`/api/v1/market/pairs/${it(e)}/funding`,listFundingHistory:(e,t)=>Ht(`/api/v1/market/pairs/${it(e)}/funding/history`,t),listAllFundingHistory:(e)=>Ht("/api/v1/market/funding/history",e),getOpenInterest:(e)=>`/api/v1/market/pairs/${it(e)}/open-interest`,getScreener:(e)=>Ht("/api/v1/market/screener",e),getMarketStats:()=>"/api/v1/market/stats"},orderbook:{get:(e,t)=>Ht(`/api/v1/orderbook/${it(e)}`,t)},trades:{publicByPair:(e,t)=>Ht(`/api/v1/trades/${it(e)}`,t),byId:(e)=>`/api/v1/trades/by-id/${it(e)}`,user:(e)=>Ht("/api/v1/accounts/trades",e)},applications:{orders:(e)=>Ht("/api/v1/applications/orders",e),users:(e)=>Ht("/api/v1/applications/users",e),movements:(e)=>Ht("/api/v1/applications/movements",e),balances:(e)=>Ht("/api/v1/applications/balances",e),stats:(e)=>Ht("/api/v1/applications/stats",e)},subAccounts:{list:()=>"/api/v1/accounts/sub-accounts",createLimit:()=>"/api/v1/accounts/sub-accounts/limits",getLimits:(e)=>`/api/v1/accounts/sub-accounts/${it(e)}/limits`,limit:(e,t)=>`/api/v1/accounts/sub-accounts/${it(e)}/limits/${it(t)}`},faucet:{mint:()=>"/api/v1/faucet/mint",info:()=>"/api/v1/faucet/info"},sweeper:{register:()=>"/api/v1/sweeper/register",chains:()=>"/api/v1/sweeper/chains"},whitelist:{submit:()=>"/api/v1/whitelist"},positions:{list:(e)=>Ht("/api/v1/positions",e),get:(e)=>`/api/v1/positions/${it(e)}`,close:(e)=>`/api/v1/positions/${it(e)}/close`,batchCloseAll:()=>"/api/v1/positions/batch-close-all",risk:(e)=>`/api/v1/positions/${it(e)}/risk`,attachTpSl:(e)=>`/api/v1/positions/${it(e)}/tp-sl`,history:(e)=>Ht("/api/v1/positions/history",e),pnlHistory:(e,t)=>Ht(`/api/v1/positions/${it(e)}/pnl/history`,t)},marginAccounts:{list:(e)=>Ht("/api/v1/margin/accounts",e),parentSummary:(e)=>Ht("/api/v1/margin/parent-margin-account",e),summary:(e,t)=>Ht(`/api/v1/margin/accounts/${it(e)}`,t),availableCollateral:(e)=>Ht("/api/v1/margin/collateral/available",e),transferIn:(e)=>`/api/v1/margin/accounts/${it(e)}/collateral/transfer-in`,transferInParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-in",transferInRiskBucket:()=>"/api/v1/margin/risk-buckets/collateral/transfer-in",transferOut:(e)=>`/api/v1/margin/accounts/${it(e)}/collateral/transfer-out`,transferOutParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-out",movements:(e,t)=>Ht(`/api/v1/margin/accounts/${it(e)}/movements`,t),parentMovements:(e)=>Ht("/api/v1/margin/parent-margin-account/movements",e),simulateParentMarginOrderRisk:()=>"/api/v1/margin/parent-margin-account/simulate-order-risk",simulateOrderRisk:(e)=>`/api/v1/margin/accounts/${it(e)}/simulate-order-risk`,simulateRiskBucketOrderRisk:()=>"/api/v1/margin/risk-buckets/simulate-order-risk",createSubAccount:()=>"/api/v1/margin/sub-accounts",closeSubAccount:(e)=>`/api/v1/margin/sub-accounts/${it(e)}/close`,subAccountTransferIn:(e)=>`/api/v1/margin/sub-accounts/${it(e)}/collateral/transfer-in`,subAccountTransferOut:(e)=>`/api/v1/margin/sub-accounts/${it(e)}/collateral/transfer-out`,pnl:(e)=>`/api/v1/margin/accounts/${it(e)}/pnl`,transferCollateral:()=>"/api/v1/margin/collateral/transfer"},streams:{orderbook:()=>"/api/v1/streaming/orderbook",trades:()=>"/api/v1/streaming/trades",perpMarketSummaries:()=>"/api/v1/streaming/perp-market-summaries",markPrices:()=>"/api/v1/streaming/mark-prices",privateTrades:()=>"/api/v1/streaming/private-trades",orders:()=>"/api/v1/streaming/orders",positions:()=>"/api/v1/streaming/positions",funding:()=>"/api/v1/streaming/funding",liquidationAlerts:()=>"/api/v1/streaming/liquidation-alerts"}};class Vx extends Ye{async getApplicationConfig(){let e=await this.makeAuthenticatedRequest("/api/v1/applications/config",{method:"GET"});return{id:e.id,name:e.name,allowedOrigins:e.allowedOrigins,webhookUrl:e.webhookUrl,vaultContractAddress:e.vaultContractAddress,clientId:e.clientId}}async listApplicationOrders(e){return te(Jj,e),await this.makePublicRequest(ue.applications.orders({clientId:e.clientId,pageSize:e.pageSize,pageToken:e.pageToken,status:e.status,userId:e.userId,tradingPairId:e.tradingPairId,side:e.side,orderType:e.orderType}))}async listApplicationUsers(e){return te(Qj,e),await this.makePublicRequest(ue.applications.users({clientId:e.clientId,pageSize:e.pageSize,pageToken:e.pageToken,isActive:e.isActive,accountType:e.accountType,address:e.address}))}async listApplicationMovements(e){return te(Xj,e),await this.makePublicRequest(ue.applications.movements({clientId:e.clientId,pageSize:e.pageSize,pageToken:e.pageToken,userId:e.userId,transactionType:e.transactionType,entryType:e.entryType,assetId:e.assetId}))}async listApplicationBalances(e){return te(eq,e),await this.makePublicRequest(ue.applications.balances({clientId:e.clientId,pageSize:e.pageSize,pageToken:e.pageToken,userId:e.userId,assetId:e.assetId}))}async getApplicationStats(e){return await this.makePublicRequest(ue.applications.stats({clientId:e.clientId,since:e.since}))}}var eme="OPERATIONS_BLOCKED",tme="OVERLOADED";function rme(e){if(!(e instanceof sr)||!e.retryable)return e;if(!(e.statusCode===void 0||e.statusCode>=500)||nme(e))return e;return e.retryable=!1,e.suggestion="The claim's outcome is unknown: it may have committed after this failure. Do not retry automatically, and do not rely on a balance read to decide — an admitted claim can still be queued, so an unchanged balance does not prove it will not commit. Treat the claim as pending and reconcile before issuing another; this endpoint has no idempotency key, so a retry can claim a second time.",e}function nme(e){let t=e.responseBody;if(t===null||typeof t!=="object")return!1;let{error:r,code:n}=t;return r===eme||n===tme}class Zx extends Ye{async getConfig(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/config",{method:"GET"})}async setBuilderFee(e){let t=te(gI,e);return this.makeAuthenticatedRequest("/api/v1/buildercodes/builder-fee",{method:"PUT",body:JSON.stringify({bps:t.bps})})}async listBuilderFeeChanges(e){if(e)te(yI,e);let t=new URLSearchParams;if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.pageToken!==void 0)t.append("pageToken",e.pageToken);let r=t.toString(),n=r?`/api/v1/buildercodes/builder-fee/changes?${r}`:"/api/v1/buildercodes/builder-fee/changes";return this.makeAuthenticatedRequest(n,{method:"GET"})}async listPayouts(e){if(e)te(bI,e);let t=new URLSearchParams;if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.pageToken!==void 0)t.append("pageToken",e.pageToken);if(e?.kind!==void 0)t.append("kind",e.kind);let r=t.toString(),n=r?`/api/v1/buildercodes/payouts?${r}`:"/api/v1/buildercodes/payouts";return this.makeAuthenticatedRequest(n,{method:"GET"})}async getPayoutSummary(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/payouts/summary",{method:"GET"})}async getRewardsBalance(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/rewards/balance",{method:"GET"})}async claimBuildercodeRewards(e){let t=te(xI,e);try{return await this.makeAuthenticatedRequest("/api/v1/buildercodes/rewards/claim",{method:"POST",body:JSON.stringify({token:t.token,amount:t.amount})})}catch(r){throw rme(r)}}}var Hi="/api/v1/copy-trading";function Wx(e){let t=new URLSearchParams;for(let[n,o]of Object.entries(e))if(o!==void 0)t.append(n,String(o));let r=t.toString();return r?`?${r}`:""}function qI(e){return`${Hi}/leaders/${encodeURIComponent(te(Ux,e))}`}function _h(e){return`${Hi}/follows/${te(be,e)}`}class Kx extends Ye{async listLeadTraders(e={}){let{sort:t,window:r,pageSize:n,pageToken:o}=te(aq,e);return await this.makePublicRequest(`${Hi}/leaders${Wx({sort:t,window:r,pageSize:n,pageToken:o})}`,{method:"GET"})}async getLeadTrader(e){return await this.makePublicRequest(qI(e),{method:"GET"})}async listLeadTraderClosedTrades(e,t={}){let r=qI(e),{pageSize:n,pageToken:o}=te(cq,t);return await this.makePublicRequest(`${r}/closed-trades${Wx({pageSize:n,pageToken:o})}`,{method:"GET"})}async listLeadTraderOpenPositions(e){return await this.makeAuthenticatedRequest(`${qI(e)}/positions`,{method:"GET"})}async upsertLeadTrader(e={}){let{shareBps:t,bio:r,status:n,minAllocation:o}=te(rq,e),i={};if(t!==void 0)i.shareBps=t;if(r!==void 0)i.bio=r;if(n!==void 0)i.status=n;if(o!==void 0)i.minAllocation=o;return await this.makeAuthenticatedRequest(`${Hi}/leaders/me`,{method:"PUT",body:JSON.stringify(i)})}async getMyLeadTrader(){return await this.makeAuthenticatedRequest(`${Hi}/leaders/me`,{method:"GET"})}async listMyFollowers(e={}){let{pageSize:t,pageToken:r}=te(lq,e);return await this.makeAuthenticatedRequest(`${Hi}/leaders/me/followers${Wx({pageSize:t,pageToken:r})}`,{method:"GET"})}async upsertFollow(e){let t=te(nq,e),r={};if(t.followId!==void 0)r.followId=t.followId;if(r.leader=t.leader??"",r.allocation=t.allocation,t.marginModePolicy!==void 0)r.marginModePolicy=t.marginModePolicy;if(t.sizingMode!==void 0)r.sizingMode=t.sizingMode;if(t.sizingParam!==void 0)r.sizingParam=t.sizingParam;if(t.leverageMode!==void 0)r.leverageMode=t.leverageMode;if(t.fixedLeverage!==void 0)r.fixedLeverage=t.fixedLeverage;if(t.slPct!==void 0)r.slPct=t.slPct;if(t.tradingPairIds!==void 0)r.markets={tradingPairIds:t.tradingPairIds};if(t.copyExisting!==void 0)r.copyExisting=t.copyExisting;return await this.makeAuthenticatedRequest(`${Hi}/follows`,{method:"POST",body:JSON.stringify(r)})}async previewFollow(e){let t=te(iq,e),r={leader:t.leader,allocation:t.allocation};if(t.marginModePolicy!==void 0)r.marginModePolicy=t.marginModePolicy;if(t.sizingMode!==void 0)r.sizingMode=t.sizingMode;if(t.sizingParam!==void 0)r.sizingParam=t.sizingParam;if(t.leverageMode!==void 0)r.leverageMode=t.leverageMode;if(t.fixedLeverage!==void 0)r.fixedLeverage=t.fixedLeverage;if(t.tradingPairIds!==void 0)r.markets={tradingPairIds:t.tradingPairIds};return await this.makeAuthenticatedRequest(`${Hi}/follows/preview`,{method:"POST",body:JSON.stringify(r)})}async stopFollow(e){return await this.makeAuthenticatedRequest(`${_h(e)}/stop`,{method:"POST"})}async closeFollowPositions(e){return await this.makeAuthenticatedRequest(`${_h(e)}/close-positions`,{method:"POST"})}async closeAllCopyPositions(){return await this.makeAuthenticatedRequest(`${Hi}/follows/close-positions`,{method:"POST"})}async addFollowPositionMargin(e){let{followId:t,tradingPairId:r,amount:n}=te(sq,e),o={tradingPairId:r,amount:n};return await this.makeAuthenticatedRequest(`${_h(t)}/position-margin`,{method:"POST",body:JSON.stringify(o)})}async listMyFollows(e={}){let{pageSize:t,pageToken:r}=te(uq,e);return await this.makeAuthenticatedRequest(`${Hi}/follows${Wx({pageSize:t,pageToken:r})}`,{method:"GET"})}async getFollow(e){return await this.makeAuthenticatedRequest(_h(e),{method:"GET"})}async listFollowLeaderPositions(e){return await this.makeAuthenticatedRequest(`${_h(e)}/leader-positions`,{method:"GET"})}}class HI extends Ye{async upsertDelegatedAgent(e){return this.makeAuthenticatedRequest(ue.delegatedAgents.list(),{method:"POST",body:JSON.stringify({agentAddress:e.agentAddress,name:e.name,expiresAt:e.expiresAt,allowedActions:e.allowedActions,allowedTradingPairIds:e.allowedTradingPairIds,allowedMarginAccountIds:e.allowedMarginAccountIds,allowedOrderTypes:e.allowedOrderTypes,allowedTimeInForce:e.allowedTimeInForce,maxLeverage:e.maxLeverage,maxOrderNotional:e.maxOrderNotional,maxOpenOrders:e.maxOpenOrders,ipAllowlist:e.ipAllowlist})})}async listDelegatedAgents(){return this.makeAuthenticatedRequest(ue.delegatedAgents.list())}async listDelegatedOwners(){return this.makeAuthenticatedRequest(ue.delegatedAgents.owners())}async revokeDelegatedAgent(e){return this.makeAuthenticatedRequest(ue.delegatedAgents.byId(e),{method:"DELETE"})}async createDelegatedSession(e){return this.makeAuthenticatedRequest(ue.delegatedAgents.sessions(),{method:"POST",body:JSON.stringify({ownerUserId:e.ownerUserId,sessionPublicKey:e.sessionPublicKey})})}}class Yx extends Ye{async mint(e){return await this.makeAuthenticatedRequest(ue.faucet.mint(),{method:"POST",body:JSON.stringify({turnstileToken:e.turnstileToken})})}async getInfo(){return await this.makeAuthenticatedRequest(ue.faucet.info(),{method:"GET"})}}class Jx extends Ye{async simulateFees(e){let t=te(PI,e),r=new URLSearchParams;if(r.append("tradingPairId",t.tradingPairId),r.append("side",t.side),r.append("price",t.price),r.append("quantity",t.quantity),t.orderType!==void 0)r.append("orderType",t.orderType);if(t.slippageToleranceBps!==void 0)r.append("slippageToleranceBps",String(t.slippageToleranceBps));let n=`/api/v1/fees/simulate?${r.toString()}`;return await this.makeAuthenticatedRequest(n,{method:"GET"})}async getMyFeeTier(e){let t=te(AI,e),r=new URLSearchParams;r.append("tradingPairId",t.tradingPairId);let n=`/api/v1/fees/tier?${r.toString()}`;return await this.makeAuthenticatedRequest(n,{method:"GET"})}}class GI extends Ye{async listAssignments(e={}){te(dq,e);let t=new URLSearchParams;if(e.pageSize!==void 0)t.set("pageSize",String(e.pageSize));if(e.pageToken!==void 0)t.set("pageToken",e.pageToken);return this.makeAuthenticatedRequest(`/api/v1/managed-markets/assignments${t.size?`?${t}`:""}`)}async claimLease(e,t){return this.makeAuthenticatedRequest(`/api/v1/managed-markets/${encodeURIComponent(e)}/lease`,{method:"POST",body:JSON.stringify(t)})}async refreshQuotes(e,t){return this.makeAuthenticatedRequest(`/api/v1/managed-markets/${encodeURIComponent(e)}/quotes`,{method:"POST",body:JSON.stringify(t)})}}class Qx extends Ye{async createMarginSubAccount(e){return te(Aq,{request:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.createSubAccount(),{method:"POST",body:JSON.stringify({subaccountKey:e.subaccountKey,label:e.label})})}async closeMarginSubAccount(e){return te(Iq,{marginAccountId:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.closeSubAccount(e),{method:"POST",body:JSON.stringify({})})}async getMarginAccountPnl(e){return te(kq,{marginAccountId:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.pnl(e))}async transferMarginCollateral(e){return te(Rq,{request:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.transferCollateral(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount,from:e.from,to:e.to})})}async transferCollateralToSubAccount(e,t){return te(UI,{marginAccountId:e,amount:t}),await this.makeAuthenticatedRequest(ue.marginAccounts.subAccountTransferIn(e),{method:"POST",body:JSON.stringify({amount:t})})}async transferCollateralFromSubAccount(e,t){return te(UI,{marginAccountId:e,amount:t}),await this.makeAuthenticatedRequest(ue.marginAccounts.subAccountTransferOut(e),{method:"POST",body:JSON.stringify({amount:t})})}async listMarginAccounts(e){if(e)te(fq,e);return await this.makeAuthenticatedRequest(ue.marginAccounts.list(e?{pageSize:e.pageSize,pageToken:e.pageToken,state:e.state,tradingPairId:e.tradingPairId}:void 0))}async getMarginAccountSummary(e,t){return te(mq,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(ue.marginAccounts.summary(e,{tradingPairId:t?.tradingPairId}))}async getParentMarginAccountSummary(e){return te(hq,e),await this.makeAuthenticatedRequest(ue.marginAccounts.parentSummary({tradingPairId:e?.tradingPairId}))}async getAvailableCollateral(e){return te(gq,e),await this.makeAuthenticatedRequest(ue.marginAccounts.availableCollateral(e))}async transferCollateralToMarginAccount(e,t){return te(BI,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ue.marginAccounts.transferIn(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey})})}async transferCollateralToParentMarginAccount(e){return te(bq,{request:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.transferInParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async transferCollateralToRiskBucket(e){return te(xq,{request:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.transferInRiskBucket(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount,tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,marginAccountId:e.marginAccountId,applyToPositionMargin:e.applyToPositionMargin})})}async transferCollateralFromMarginAccount(e,t){return te(BI,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ue.marginAccounts.transferOut(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey,marginMode:t.marginMode})})}async transferCollateralFromParentMarginAccount(e){return te(wq,{request:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.transferOutParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async getMarginAccountMovements(e,t){return te(Sq,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(ue.marginAccounts.movements(e,t))}async getParentMarginAccountMovements(e){return te(_q,e),await this.makeAuthenticatedRequest(ue.marginAccounts.parentMovements(e))}async simulateOrderRisk(e,t){return te(vq,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ue.marginAccounts.simulateOrderRisk(e),{method:"POST",body:JSON.stringify({tradingPairId:t.tradingPairId,side:t.side,positionSide:t.positionSide,orderType:t.orderType,price:t.price,quantity:t.quantity,leverage:t.leverage,reduceOnly:t.reduceOnly,slippageToleranceBps:t.slippageToleranceBps})})}async simulateParentMarginOrderRisk(e){return te(Eq,{request:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.simulateParentMarginOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly,slippageToleranceBps:e.slippageToleranceBps})})}async simulateRiskBucketOrderRisk(e){return te(Pq,{request:e}),await this.makeAuthenticatedRequest(ue.marginAccounts.simulateRiskBucketOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,marginAccountId:e.marginAccountId,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly,slippageToleranceBps:e.slippageToleranceBps})})}}class Xx extends Ye{async getPaginatedTradingPairs(e){let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.marketType)t.append("marketType",e.marketType);if(e?.baseToken)t.append("baseToken",e.baseToken);if(e?.quoteToken)t.append("quoteToken",e.quoteToken);if(e?.isActive!==void 0)t.append("isActive",e.isActive.toString());if(e?.category)t.append("category",e.category);let r=t.toString(),n=r?`/api/v1/market/pairs?${r}`:"/api/v1/market/pairs";return await this.makePublicRequest(n)}async getTradingPair(e){return te(qi,{tradingPairId:e}),(await this.makePublicRequest(ue.market.getTradingPair(e))).tradingPair}async getTradingPairBySymbol(e,t){return(await this.getPaginatedTradingPairs({pageSize:100,marketType:t})).tradingPairs.find((n)=>n.symbol===e)}async getCandlesticks(e,t,r){te(Oq,{tradingPairId:e,interval:t,startTime:r?.startTime,endTime:r?.endTime,limit:r?.limit,priceType:r?.priceType});let n=new URLSearchParams;if(r?.startTime!==void 0)n.append("startTime",r.startTime.toString());if(r?.endTime!==void 0)n.append("endTime",r.endTime.toString());if(r?.limit!==void 0)n.append("limit",r.limit.toString());if(r?.priceType!==void 0)n.append("priceType",r.priceType);let o=n.toString(),i=o?`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}?${o}`:`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}`;return(await this.makePublicRequest(i)).data||[]}async getMarketMetadata(e){return te(qi,{tradingPairId:e}),await this.makePublicRequest(ue.market.getMarketMetadata(e))}async getPerpMarketConfig(e){return te(qi,{tradingPairId:e}),await this.makePublicRequest(ue.market.getPerpMarketConfig(e))}async getPerpMarketSummary(e){return te(qi,{tradingPairId:e}),await this.makePublicRequest(ue.market.getPerpMarketSummary(e))}async getMarkPrice(e){return te(qi,{tradingPairId:e}),await this.makePublicRequest(ue.market.getMarkPrice(e))}async getIndexPrice(e){return te(qi,{tradingPairId:e}),await this.makePublicRequest(ue.market.getIndexPrice(e))}async getFundingState(e){return te(qi,{tradingPairId:e}),await this.makePublicRequest(ue.market.getFundingState(e))}async listFundingHistory(e,t){return te(qi,{tradingPairId:e}),te(Nq,t??{}),await this.makePublicRequest(ue.market.listFundingHistory(e,t))}async listAllFundingHistory(e){return te($q,e??{}),await this.makePublicRequest(ue.market.listAllFundingHistory(e))}async getOpenInterest(e){return te(qi,{tradingPairId:e}),await this.makePublicRequest(ue.market.getOpenInterest(e))}async getScreener(e){return await this.makePublicRequest(ue.market.getScreener(e))}async getMarketStats(){return await this.makePublicRequest(ue.market.getMarketStats())}}class ew extends Ye{async getOrderbook(e,t={}){let{depth:r=10,tradingMode:n,magnitude:o,denomination:i}=t,s=new URLSearchParams;if(s.set("levels",String(r)),n)s.set("tradingMode",n);if(o!==void 0)s.set("magnitude",String(o));if(i)s.set("denomination",i.toLowerCase());let a=await this.makePublicRequest(`/api/v1/orderbook/${encodeURIComponent(e)}?${s.toString()}`);return{tradingPairId:a.tradingPairId,tradingMode:a.tradingMode,bids:a.data.bids.map((c)=>({price:c.price,quantity:c.quantity,orderCount:c.orderCount})),asks:a.data.asks.map((c)=>({price:c.price,quantity:c.quantity,orderCount:c.orderCount})),bestBid:a.data.bestBid,bestAsk:a.data.bestAsk,bidVolume:a.data.bidVolume,askVolume:a.data.askVolume,baseDecimals:a.baseDecimals,quoteDecimals:a.quoteDecimals,timestamp:a.timestamp,sequence:a.sequenceNumber}}}class Th extends Ye{async getMyTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/tradercodes/codes/me",{method:"GET"})}async setTraderCode(e){let t=te(II,{code:e});return await this.makeAuthenticatedRequest("/api/v1/tradercodes/codes/me/custom",{method:"PUT",body:JSON.stringify({code:t.code})})}async clearTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/tradercodes/codes/me/custom",{method:"DELETE"})}async checkTraderCodeAvailability(e){let t=new URLSearchParams({code:e.trim()}).toString(),r=await this.makePublicRequest(`/api/v1/tradercodes/codes/available?${t}`,{method:"GET"});return{available:r.available,reason:r.reason?r.reason:void 0}}async getTraderCodeInfo(e){let t=encodeURIComponent(e.trim());return await this.makePublicRequest(`/api/v1/tradercodes/codes/${t}`,{method:"GET"})}async getRewardsBalance(){return await this.makeAuthenticatedRequest("/api/v1/tradercodes/rewards/balance",{method:"GET"})}async transferRewards(e){let t=te(kI,e);return await this.makeAuthenticatedRequest("/api/v1/tradercodes/rewards/transfer",{method:"POST",body:JSON.stringify({token:t.token,amount:t.amount})})}async getMyReferralPosition(){return await this.makeAuthenticatedRequest("/api/v1/tradercodes/referrals/me",{method:"GET"})}async getMyReferralDownline(e){if(e)te(RI,e);let t=new URLSearchParams;if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.pageToken!==void 0)t.append("pageToken",e.pageToken);let r=t.toString(),n=r?`/api/v1/tradercodes/referrals/me/downline?${r}`:"/api/v1/tradercodes/referrals/me/downline";return await this.makeAuthenticatedRequest(n,{method:"GET"})}async getMyReferralTree(e){if(e)te(CI,e);let t=new URLSearchParams;if(e?.parent!==void 0)t.append("parent",e.parent);if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.pageToken!==void 0)t.append("pageToken",e.pageToken);let r=t.toString(),n=r?`/api/v1/tradercodes/referrals/me/tree?${r}`:"/api/v1/tradercodes/referrals/me/tree";return await this.makeAuthenticatedRequest(n,{method:"GET"})}}var vh="/api/v1/accounts/me/portfolio";function tw(e,t){if(!t?.period)return e;return`${e}?${new URLSearchParams({period:t.period})}`}class rw extends Ye{async getSummary(e){return await this.makeAuthenticatedRequest(tw(`${vh}/summary`,e))}async getPerformance(e){return await this.makeAuthenticatedRequest(tw(`${vh}/performance`,e))}async getRealizedPnl(e){return await this.makeAuthenticatedRequest(tw(`${vh}/realized-pnl`,e))}async getAssets(e){return await this.makeAuthenticatedRequest(tw(`${vh}/assets`,e))}async getMargin(e){let t=new URLSearchParams;if(e?.marginAccountId)t.set("marginAccountId",e.marginAccountId);if(e?.includeAccounts!==void 0)t.set("includeAccounts",String(e.includeAccounts));let r=t.toString(),n=r?`?${r}`:"";return await this.makeAuthenticatedRequest(`${vh}/margin${n}`)}}class nw extends Ye{async listPositions(e){if(e)te(Dq,e);return await this.makeAuthenticatedRequest(ue.positions.list(e))}async getPosition(e){return te(Fq,{positionId:e}),await this.makeAuthenticatedRequest(ue.positions.get(e))}async closePosition(e,t){return te(Uq,{positionId:e,request:t}),await this.makeAuthenticatedRequest(ue.positions.close(e),{method:"POST",body:JSON.stringify({closeType:t.closeType,limitPrice:t.limitPrice,slippageToleranceBps:t.slippageToleranceBps,quantity:t.quantity})})}async batchCloseAllPositions(e){if(e)te(jq,e);return await this.makeAuthenticatedRequest(ue.positions.batchCloseAll(),{method:"POST",body:JSON.stringify({tradingPairId:e?.tradingPairId,tradingPairIds:e?.tradingPairIds,side:e?.side,slippageToleranceBps:e?.slippageToleranceBps})})}async getPositionRisk(e){return te(qq,{positionId:e}),await this.makeAuthenticatedRequest(ue.positions.risk(e))}async attachPositionTpSl(e,t){return te(Hq,{positionId:e,request:t}),await this.makeAuthenticatedRequest(ue.positions.attachTpSl(e),{method:"POST",body:JSON.stringify({takeProfit:t.takeProfit?{triggerPrice:t.takeProfit.triggerPrice,orderType:t.takeProfit.orderType,limitPrice:t.takeProfit.limitPrice,quantity:t.takeProfit.quantity,closePosition:t.takeProfit.closePosition,timeInForce:t.takeProfit.timeInForce,slippageToleranceBps:t.takeProfit.slippageToleranceBps,expiresAt:t.takeProfit.expiresAt}:void 0,stopLoss:t.stopLoss?{triggerPrice:t.stopLoss.triggerPrice,orderType:t.stopLoss.orderType,limitPrice:t.stopLoss.limitPrice,quantity:t.stopLoss.quantity,closePosition:t.stopLoss.closePosition,timeInForce:t.stopLoss.timeInForce,slippageToleranceBps:t.stopLoss.slippageToleranceBps,expiresAt:t.stopLoss.expiresAt}:void 0,trailingStop:t.trailingStop?{trailBps:t.trailingStop.trailBps,activationPrice:t.trailingStop.activationPrice,quantity:t.trailingStop.quantity,closePosition:t.trailingStop.closePosition,slippageToleranceBps:t.trailingStop.slippageToleranceBps,expiresAt:t.trailingStop.expiresAt}:void 0,oco:t.oco})})}async listPositionHistory(e){if(e)te(Gq,e);return await this.makeAuthenticatedRequest(ue.positions.history(e))}async getPositionPnlHistory(e,t){return te(Vq,{positionId:e,params:t}),await this.makeAuthenticatedRequest(ue.positions.pnlHistory(e,t))}}class VI extends Ye{async getProfile(){return await this.makeAuthenticatedRequest("/api/v1/accounts/me")}async getPaginatedUserMovements(e){if(e)te(Wq,e);let t=new URLSearchParams;if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.pageToken!==void 0)t.append("pageToken",e.pageToken);if(e?.orderBy!==void 0)t.append("orderBy",e.orderBy);if(e?.entryType!==void 0)t.append("entryType",e.entryType);if(e?.transactionType!==void 0)t.append("transactionType",e.transactionType);if(e?.assetId!==void 0)t.append("assetId",e.assetId);let r=t.toString(),n=r?`/api/v1/accounts/movements?${r}`:"/api/v1/accounts/movements";return await this.makeAuthenticatedRequest(n)}async getUserBalances(e){if(e)te(Yq,e);let t=new URLSearchParams;if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.pageToken!==void 0)t.append("pageToken",e.pageToken);let r=t.toString(),n=r?`/api/v1/accounts/balances?${r}`:"/api/v1/accounts/balances";return await this.makeAuthenticatedRequest(n)}async getUserBalanceByAssetId(e){if(!e||e.trim()==="")throw new sr("assetId is required and cannot be empty",{endpoint:"/api/v1/accounts/balances/{assetId}"});let t=`/api/v1/accounts/balances/${e}`;return await this.makeAuthenticatedRequest(t)}async getPortfolioStats(e){let t=new URLSearchParams({period:e});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio?${t}`)}async getPortfolioChart(e,t){let r=new URLSearchParams({period:e,metric:t});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio/chart?${r}`)}async getUserTrades(e){if(e)te(Kq,e);let t=new URLSearchParams;if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.tradingPairId!==void 0)t.append("tradingPairId",e.tradingPairId);t.append("pageToken",e?.pageToken??"");let r=t.toString(),n=r?`/api/v1/accounts/trades?${r}`:"/api/v1/accounts/trades";return await this.makeAuthenticatedRequest(n)}async*iterateUserTrades(e){let t="";for(;;){let r=await this.getUserTrades({...e,pageToken:t});if(yield*r.trades,!r.nextPageToken)return;t=r.nextPageToken}}async listFundingPayments(e){if(e)te(Jq,e);let t=new URLSearchParams;if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.pageToken!==void 0)t.append("pageToken",e.pageToken);if(e?.tradingPairId!==void 0)t.append("tradingPairId",e.tradingPairId);if(e?.positionId!==void 0)t.append("positionId",e.positionId);if(e?.marginAccountId!==void 0)t.append("marginAccountId",e.marginAccountId);let r=t.toString(),n=r?`/api/v1/accounts/funding-payments?${r}`:"/api/v1/accounts/funding-payments";return await this.makeAuthenticatedRequest(n)}async getSelfTradePreventionDefault(){return await this.makeAuthenticatedRequest("/api/v1/accounts/self-trade-prevention")}async setSelfTradePreventionDefault(e){let t=te(Zq,{mode:e});return await this.makeAuthenticatedRequest("/api/v1/accounts/self-trade-prevention",{method:"PUT",body:JSON.stringify(t)})}}class ow extends Ye{async getPulse(){return await this.makePublicRequest("/api/v1/pulse",{method:"GET"})}}class iw extends Ye{async list(){return await this.makeAuthenticatedRequest(ue.subAccounts.list())}async createLimit(e){return await this.makeAuthenticatedRequest(ue.subAccounts.createLimit(),{method:"POST",body:JSON.stringify(e)})}async getLimits(e){return await this.makeAuthenticatedRequest(ue.subAccounts.getLimits(e))}async updateLimit(e,t,r){return await this.makeAuthenticatedRequest(ue.subAccounts.limit(e,t),{method:"PUT",body:JSON.stringify(r)})}async deleteLimit(e,t){await this.makeAuthenticatedRequest(ue.subAccounts.limit(e,t),{method:"DELETE"})}}function ome(e){if(e==="spot")return"SPOT";if(e==="margin")return"MARGIN";throw new Bt(`Invalid deposit target: ${JSON.stringify(e)}. Expected "spot" or "margin".`)}class sw extends Ye{async register(e={}){let{depositTarget:t,...r}=e,n=t===void 0?r:{...r,depositTarget:ome(t)};return await this.makeAuthenticatedRequest(ue.sweeper.register(),{method:"POST",body:JSON.stringify(n)})}async getChains(){return await this.makePublicRequest(ue.sweeper.chains(),{method:"GET"})}}function o7(e){return{eventType:"trade",tradingPairId:e.tradingPairId,tradingMode:e.tradingMode.toUpperCase(),data:{tradeId:e.data.tradeId,price:e.data.price,quantity:e.data.quantity,makerSide:e.data.makerSide.toUpperCase(),executedAt:e.data.executedAt??""}}}class ZI extends Ye{async getTrades(e,t={}){te(zq,t);let r=new URLSearchParams;if(t.pageSize!=null)r.set("pageSize",String(t.pageSize));if(t.pageToken!=null&&t.pageToken!=="")r.set("pageToken",t.pageToken);let n=r.toString(),o=await this.makePublicRequest(`/api/v1/trades/${encodeURIComponent(e)}${n===""?"":`?${n}`}`);return{trades:(o.trades??[]).map(o7),nextPageToken:o.nextPageToken??""}}async getTradeById(e){let t=await this.makePublicRequest(ue.trades.byId(e));return o7(t)}}function aw(e){if(!e)return;return{triggerPrice:e.triggerPrice,orderType:e.orderType,limitPrice:e.limitPrice,timeInForce:e.timeInForce,slippageToleranceBps:e.slippageToleranceBps,expiresAt:e.expiresAt,quantity:e.quantity,closePosition:e.closePosition}}function i7(e){if(!e)return;return{trailBps:e.trailBps,activationPrice:e.activationPrice,quantity:e.quantity,closePosition:e.closePosition,slippageToleranceBps:e.slippageToleranceBps,expiresAt:e.expiresAt}}class cw extends Ye{async placeLimitOrder(e,t,r,n,o){te(Dj,{tradingPairId:e,side:t,quantity:r,price:n,options:o});let i={tradingPairId:e,orderType:"LIMIT",side:t,price:n,quantity:r,tradingMode:o?.tradingMode||"SPOT",useMasterBalance:o?.useMasterBalance,expirationDate:o?.expirationDate,timeInForce:o?.timeInForce,marginAccountId:o?.marginAccountId,marginMode:o?.marginMode,riskBucketId:o?.riskBucketId,riskBucketCollateral:o?.riskBucketCollateral,strategyKey:o?.strategyKey,positionSide:o?.positionSide,leverage:o?.leverage,reduceOnly:o?.reduceOnly,postOnly:o?.postOnly,selfTradePreventionMode:o?.selfTradePreventionMode,clientOrderId:o?.clientOrderId,idempotencyKey:o?.idempotencyKey===void 0?crypto.randomUUID():o.idempotencyKey,takeProfit:aw(o?.takeProfit),stopLoss:aw(o?.stopLoss),trailingStop:i7(o?.trailingStop)};return await this.makeAuthenticatedRequest(ue.orders.create(),{method:"POST",body:JSON.stringify(i)})}async placeMarketOrder(e,t,r,n){te(Fj,{tradingPairId:e,side:t,quantity:r,options:n});let o={tradingPairId:e,orderType:"MARKET",side:t,slippageToleranceBps:n?.slippageTolerance!==void 0?Math.round(n.slippageTolerance*1e4):void 0,price:null,quantity:r,tradingMode:n?.tradingMode||"SPOT",marginAccountId:n?.marginAccountId,marginMode:n?.marginMode,riskBucketId:n?.riskBucketId,riskBucketCollateral:n?.riskBucketCollateral,strategyKey:n?.strategyKey,positionSide:n?.positionSide,leverage:n?.leverage,reduceOnly:n?.reduceOnly,selfTradePreventionMode:n?.selfTradePreventionMode,takeProfit:aw(n?.takeProfit),stopLoss:aw(n?.stopLoss),trailingStop:i7(n?.trailingStop),clientOrderId:n?.clientOrderId,idempotencyKey:n?.idempotencyKey===void 0?crypto.randomUUID():n.idempotencyKey};return await this.makeAuthenticatedRequest(ue.orders.create(),{method:"POST",body:JSON.stringify(o)})}async cancelOrder(e,t){te(Uj,{orderId:e,remainingQuantityTarget:t?.remainingQuantityTarget});let r={orderId:e,...t?.remainingQuantityTarget!==void 0&&{remainingQuantityTarget:t.remainingQuantityTarget}};return await this.makeAuthenticatedRequest(ue.orders.cancel(),{method:"POST",body:JSON.stringify(r)})}async cancelConditionalOrder(e){return te(zI,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(ue.orders.cancelConditional(e),{method:"DELETE"})}async getConditionalOrder(e){return te(zI,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(ue.orders.getConditional(e),{method:"GET"})}async listConditionalOrders(e){if(e)te(Gj,e);let{pageSize:t=20,marginAccountId:r,tradingPairId:n,state:o,pageToken:i}=e||{},s=Math.min(Math.max(t,1),1000);return await this.makeAuthenticatedRequest(ue.orders.listConditional({marginAccountId:r,tradingPairId:n,state:o,pageSize:s,pageToken:i??""}),{method:"GET"})}async batchCancel(e){if(!e||e.length===0)throw Error("orderIds is required and must not be empty");return this.makeAuthenticatedRequest(ue.orders.batchCancel(),{method:"POST",body:JSON.stringify({orderIds:e})})}async batchCancelAll(e){let t=e?ue.orders.batchCancelAllByPair(e):ue.orders.batchCancelAll();return this.makeAuthenticatedRequest(t,{method:"POST"})}async replaceOrder(e,t){te(jj,{orderId:e,newOrder:t});let r={useMasterBalance:t.useMasterBalance??!1};if(t.price!==void 0)r.price=t.price;if(t.quantity!==void 0)r.quantity=t.quantity;if(t.postOnly!==void 0)r.postOnly=t.postOnly;if(t.selfTradePreventionMode!==void 0)r.selfTradePreventionMode=t.selfTradePreventionMode;if(t.clientOrderId!==void 0)r.clientOrderId=t.clientOrderId;return await this.makeAuthenticatedRequest(ue.orders.replace(e),{method:"PUT",body:JSON.stringify(r)})}async batchCreate(e){te(Kj,{orders:e});let t={orders:e.map((r)=>({tradingPairId:r.tradingPairId,orderType:r.orderType,side:r.side,price:r.price,quantity:r.quantity,tradingMode:r.tradingMode||"SPOT",slippageToleranceBps:r.slippageTolerance!==void 0?Math.round(r.slippageTolerance*1e4):void 0,useMasterBalance:r.useMasterBalance,expirationDate:r.expirationDate,timeInForce:r.timeInForce,marginAccountId:r.marginAccountId,marginMode:r.marginMode,riskBucketId:r.riskBucketId,riskBucketCollateral:r.riskBucketCollateral,strategyKey:r.strategyKey,positionSide:r.positionSide,leverage:r.leverage,reduceOnly:r.reduceOnly,postOnly:r.postOnly,selfTradePreventionMode:r.selfTradePreventionMode,clientOrderId:r.clientOrderId,idempotencyKey:r.idempotencyKey===void 0?crypto.randomUUID():r.idempotencyKey}))};return this.makeAuthenticatedRequest(ue.orders.batchCreate(),{method:"POST",body:JSON.stringify(t)})}async batchReplace(e){te(Yj,{orders:e});let t={orders:e.map((r)=>({orderId:r.orderId,price:r.price,quantity:r.quantity,useMasterBalance:r.useMasterBalance,postOnly:r.postOnly,selfTradePreventionMode:r.selfTradePreventionMode,clientOrderId:r.clientOrderId}))};return this.makeAuthenticatedRequest(ue.orders.batchReplace(),{method:"POST",body:JSON.stringify(t)})}async getPaginatedOrders(e){if(e)te(qj,e);let{pageSize:t=10,status:r,tradingPairId:n,tradingMode:o,marginAccountId:i,pageToken:s}=e||{},a=t>0?t:10,c=Math.min(a,1000),l=new URLSearchParams;l.append("pageSize",c.toString());let d=typeof r==="string"?r:r?.join(",");if(d)l.append("status",d);if(n)l.append("tradingPairId",n);if(o)l.append("tradingMode",o);if(i)l.append("marginAccountId",i);l.append("pageToken",s??"");let f=`/api/v1/orders?${l.toString()}`;return await this.makeAuthenticatedRequest(f,{method:"GET"})}async*iterateOrders(e){let t="";for(;;){let r=await this.getPaginatedOrders({...e,pageToken:t});if(yield*r.orders,!r.nextPageToken)return;t=r.nextPageToken}}async getOrder(e){return{order:await this.makeAuthenticatedRequest(ue.orders.get(e),{method:"GET"}),status:"SUCCESS"}}async createTwapOrder(e,t,r,n){te(Vj,{tradingPairId:e,side:t,quantity:r,options:n});let o={tradingPairId:e,side:t,quantity:r,durationSeconds:n.durationSeconds!==void 0?Number(n.durationSeconds):void 0,startTime:n.startTime,endTime:n.endTime,limitPrice:n.limitPrice,slippageToleranceBps:n.slippageToleranceBps,randomize:n.randomize,reduceOnly:n.reduceOnly,tradingMode:n.tradingMode||"SPOT",marginAccountId:n.marginAccountId,riskBucketId:n.riskBucketId,marginMode:n.marginMode,leverage:n.leverage,strategyKey:n.strategyKey,useMasterBalance:n.useMasterBalance,clientTwapId:n.clientTwapId,executionStyle:n.executionStyle,triggerPrice:n.triggerPrice,triggerDirection:n.triggerDirection,conditionalExpiry:n.conditionalExpiry};return await this.makeAuthenticatedRequest(ue.orders.createTwap(),{method:"POST",body:JSON.stringify(o)})}async cancelTwapOrder(e){return te(Dx,{twapOrderId:e}),await this.makeAuthenticatedRequest(ue.orders.cancelTwap(e),{method:"POST"})}async getTwapOrder(e){return te(Dx,{twapOrderId:e}),await this.makeAuthenticatedRequest(ue.orders.getTwap(e),{method:"GET"})}async getTwapOrderTca(e){return te(Dx,{twapOrderId:e}),await this.makeAuthenticatedRequest(ue.orders.getTwapTca(e),{method:"GET"})}async listTwapOrders(e){if(e)te(Zj,e);let{pageSize:t=20,state:r,tradingPairId:n,pageToken:o}=e||{},i=Math.min(Math.max(t,1),1000);return await this.makeAuthenticatedRequest(ue.orders.listTwap({state:r,tradingPairId:n,pageSize:i,pageToken:o??""}),{method:"GET"})}async listTwapOrderSlices(e,t){te(Wj,{...t,twapOrderId:e});let{orderBy:r,pageSize:n=20,pageToken:o}=t||{};return await this.makeAuthenticatedRequest(ue.orders.listTwapSlices(e,{orderBy:r,pageSize:n,pageToken:o??""}),{method:"GET"})}}var WI=[{inputs:[{internalType:"address",name:"factory_",type:"address"},{internalType:"address",name:"unwrapHelper_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"BridgeFeeTooHigh",type:"error"},{inputs:[],name:"ChainNotConfigured",type:"error"},{inputs:[],name:"ComposeNotSupported",type:"error"},{inputs:[],name:"ComposeSourceMismatch",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"NativeNotAccepted",type:"error"},{inputs:[],name:"NativeTransferFailed",type:"error"},{inputs:[],name:"NoRoute",type:"error"},{inputs:[],name:"NotExecutor",type:"error"},{inputs:[],name:"NotHub",type:"error"},{inputs:[],name:"NotRemote",type:"error"},{inputs:[],name:"NothingToSweep",type:"error"},{inputs:[],name:"OftCannotUnwrap",type:"error"},{inputs:[],name:"OnlyClone",type:"error"},{inputs:[],name:"QuoteNotBound",type:"error"},{inputs:[],name:"RoutedToken",type:"error"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"SafeERC20FailedOperation",type:"error"},{inputs:[],name:"StaleQuote",type:"error"},{inputs:[],name:"SweepParamsRequired",type:"error"},{inputs:[],name:"UnexpectedBridgeDebit",type:"error"},{inputs:[],name:"UnexpectedParams",type:"error"},{inputs:[],name:"UnexpectedValue",type:"error"},{inputs:[],name:"UnswapPathMissing",type:"error"},{inputs:[],name:"UntrustedComposeCaller",type:"error"},{inputs:[],name:"UntrustedComposeSource",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amountIn",type:"uint256"},{indexed:!1,internalType:"address",name:"bridgeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"amountBridged",type:"uint256"},{indexed:!1,internalType:"address",name:"destination",type:"address"}],name:"Bridged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Refunded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"RefundedNative",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Swept",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"tokenIn",type:"address"},{indexed:!0,internalType:"address",name:"tokenOut",type:"address"},{indexed:!1,internalType:"uint256",name:"amountIn",type:"uint256"},{indexed:!1,internalType:"uint256",name:"amountOut",type:"uint256"}],name:"Unswapped",type:"event"},{inputs:[],name:"config",outputs:[{internalType:"address",name:"user",type:"address"},{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"hubToken",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{internalType:"contract ISweeperFactory",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"bytes32",name:"",type:"bytes32"},{internalType:"bytes",name:"message",type:"bytes"},{internalType:"address",name:"",type:"address"},{internalType:"bytes",name:"",type:"bytes"}],name:"lzCompose",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{components:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"minSwapOut",type:"uint256"},{internalType:"uint256",name:"minBridgeOut",type:"uint256"},{internalType:"bytes",name:"lzExtraOptions",type:"bytes"}],internalType:"struct SweepParams",name:"params",type:"tuple"}],name:"sweep",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"address",name:"feeRefundAddress",type:"address"}],name:"sweepWithRefund",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"unwrapHelper",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{stateMutability:"payable",type:"receive"}];var KI=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{inputs:[{internalType:"address",name:"target",type:"address"}],name:"AddressEmptyCode",type:"error"},{inputs:[],name:"CloneArgumentsTooLong",type:"error"},{inputs:[],name:"Create2EmptyBytecode",type:"error"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"ERC1967InvalidImplementation",type:"error"},{inputs:[],name:"ERC1967NonPayable",type:"error"},{inputs:[],name:"FailedCall",type:"error"},{inputs:[],name:"FailedDeployment",type:"error"},{inputs:[],name:"ImplementationNotSet",type:"error"},{inputs:[{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"InvalidFeeCap",type:"error"},{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[],name:"NotExecutor",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{inputs:[],name:"UUPSUnauthorizedCallContext",type:"error"},{inputs:[{internalType:"bytes32",name:"slot",type:"bytes32"}],name:"UUPSUnsupportedProxiableUUID",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousExecutor",type:"address"},{indexed:!0,internalType:"address",name:"newExecutor",type:"address"}],name:"ExecutorUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"rollup",type:"address"},{indexed:!1,internalType:"address",name:"bridgedStable",type:"address"},{indexed:!1,internalType:"address",name:"swapRouter",type:"address"},{indexed:!1,internalType:"address",name:"lzEndpoint",type:"address"}],name:"HubConfigured",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferStarted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint16",name:"previousCapBps",type:"uint16"},{indexed:!1,internalType:"uint16",name:"newCapBps",type:"uint16"}],name:"PermissionlessBridgeFeeCapUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"swapRouter",type:"address"},{indexed:!1,internalType:"uint32",name:"cctpDestinationDomain",type:"uint32"},{indexed:!1,internalType:"uint32",name:"stargateDestinationEid",type:"uint32"}],name:"RemoteConfigured",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"uint32",name:"dstEid",type:"uint32"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],indexed:!1,internalType:"struct BridgeRoute",name:"route",type:"tuple"}],name:"RouteSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"sweeper",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"string",name:"applicationId",type:"string"},{indexed:!1,internalType:"address",name:"hubToken",type:"address"}],name:"SweeperDeployed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousImplementation",type:"address"},{indexed:!0,internalType:"address",name:"newImplementation",type:"address"}],name:"SweeperImplementationUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"stargate",type:"address"},{indexed:!1,internalType:"address",name:"token",type:"address"}],name:"TrustedStargateSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"hubToken",type:"address"},{indexed:!1,internalType:"bytes",name:"path",type:"bytes"}],name:"UnswapPathSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{inputs:[],name:"UPGRADE_INTERFACE_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"acceptOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"bridgedStable",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"cctpDestinationDomain",outputs:[{internalType:"uint32",name:"",type:"uint32"}],stateMutability:"view",type:"function"},{inputs:[],name:"chainMode",outputs:[{internalType:"enum ChainMode",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"rollup_",type:"address"},{internalType:"address",name:"bridgedStable_",type:"address"},{internalType:"address",name:"swapRouter_",type:"address"},{internalType:"address",name:"lzEndpoint_",type:"address"}],name:"configureHub",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"swapRouter_",type:"address"},{internalType:"uint32",name:"cctpDestinationDomain_",type:"uint32"},{internalType:"uint32",name:"stargateDestinationEid_",type:"uint32"}],name:"configureRemote",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"deploy",outputs:[{internalType:"address",name:"sweeper",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"}],name:"deployReceiver",outputs:[{internalType:"address",name:"sweeper",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"executor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"forwarder",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner_",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"isDeployed",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"lzEndpoint",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pendingOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"permissionlessBridgeFeeCapBps",outputs:[{internalType:"uint16",name:"",type:"uint16"}],stateMutability:"view",type:"function"},{inputs:[],name:"proxiableUUID",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"}],name:"receiverFor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"refundToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"rollup",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"route",outputs:[{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"uint32",name:"dstEid",type:"uint32"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],internalType:"struct BridgeRoute",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"executor_",type:"address"}],name:"setExecutor",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint16",name:"capBps",type:"uint16"}],name:"setPermissionlessBridgeFeeCapBps",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"uint32",name:"dstEid",type:"uint32"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],internalType:"struct BridgeRoute",name:"route_",type:"tuple"}],name:"setRoute",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"setSweeperImplementation",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"stargate",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"setTrustedStargate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"path",type:"bytes"}],name:"setUnswapPath",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"stargateDestinationEid",outputs:[{internalType:"uint32",name:"",type:"uint32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"stargate",type:"address"}],name:"stargateToken",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"swapRouter",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"address",name:"token",type:"address"},{components:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"minSwapOut",type:"uint256"},{internalType:"uint256",name:"minBridgeOut",type:"uint256"},{internalType:"bytes",name:"lzExtraOptions",type:"bytes"}],internalType:"struct SweepParams",name:"params",type:"tuple"}],name:"sweepWithParams",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"sweeperFor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"sweeperImplementation",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"hubToken",type:"address"}],name:"unswapPath",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[],name:"unwrapHelper",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],name:"upgradeToAndCall",outputs:[],stateMutability:"payable",type:"function"}];var YI=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"AccessControlBadConfirmation",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"bytes32",name:"neededRole",type:"bytes32"}],name:"AccessControlUnauthorizedAccount",type:"error"},{inputs:[{internalType:"address",name:"target",type:"address"}],name:"AddressEmptyCode",type:"error"},{inputs:[],name:"ECDSAInvalidSignature",type:"error"},{inputs:[{internalType:"uint256",name:"length",type:"uint256"}],name:"ECDSAInvalidSignatureLength",type:"error"},{inputs:[{internalType:"bytes32",name:"s",type:"bytes32"}],name:"ECDSAInvalidSignatureS",type:"error"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"ERC1967InvalidImplementation",type:"error"},{inputs:[],name:"ERC1967NonPayable",type:"error"},{inputs:[],name:"EnforcedPause",type:"error"},{inputs:[],name:"ExpectedPause",type:"error"},{inputs:[],name:"FailedCall",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientBalance",type:"error"},{inputs:[],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[],name:"InvalidSeed",type:"error"},{inputs:[],name:"InvalidSignature",type:"error"},{inputs:[],name:"InvalidTimestamp",type:"error"},{inputs:[],name:"NonceAlreadyUsed",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[],name:"ReentrancyGuardReentrantCall",type:"error"},{inputs:[],name:"TransferFailed",type:"error"},{inputs:[],name:"UUPSUnauthorizedCallContext",type:"error"},{inputs:[{internalType:"bytes32",name:"slot",type:"bytes32"}],name:"UUPSUnsupportedProxiableUUID",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Deposit",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newFeeCollector",type:"address"}],name:"FeeCollectorChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"previousAdminRole",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"newAdminRole",type:"bytes32"}],name:"RoleAdminChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleGranted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleRevoked",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newSettlementContract",type:"address"}],name:"SettlementContractChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"maker",type:"address"},{indexed:!0,internalType:"address",name:"taker",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"fee",type:"uint256"}],name:"SettlementTransfer",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdrawal",type:"event"},{inputs:[],name:"DEBUGGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"DEFAULT_ADMIN_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"FEE_MANAGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"PAUSER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"SETTLEMENT_MANAGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"UPGRADER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"UPGRADE_INTERFACE_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"seed",type:"bytes"}],name:"decodeSeed",outputs:[{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"destination",type:"address"},{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"depositERC20",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"destination",type:"address"},{internalType:"string",name:"applicationId",type:"string"}],name:"depositNative",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"feeCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getChainID",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"}],name:"getRoleAdmin",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"grantRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"hasRole",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_admin",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"proxiableUUID",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"callerConfirmation",type:"address"}],name:"renounceRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"revokeRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_newFeeCollector",type:"address"}],name:"setFeeCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_settlementContract",type:"address"}],name:"setSettlementContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"settlementContract",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"maker",type:"address"},{internalType:"address",name:"taker",type:"address"},{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"fee",type:"uint256"}],name:"transferOnSettlement",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],name:"upgradeToAndCall",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"seed",type:"bytes"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"withdraw",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"seed",type:"bytes"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"withdrawNative",outputs:[],stateMutability:"nonpayable",type:"function"}];var xOt=new Uint8Array(32);function uw(e,t){return ime(t),t==="margin"?JSON.stringify({clientId:e,depositTarget:"MARGIN"}):e}function ime(e){if(e!=="spot"&&e!=="margin")throw Error(`Invalid deposit target: ${JSON.stringify(e)}. `+'Expected "spot" or "margin" — lowercase, not the wire form "SPOT"/"MARGIN".')}var JI={vault:YI,sweeper:WI,sweeperFactory:KI};var sme=5000,ame=300000,cme=(e)=>new Promise((t)=>setTimeout(t,e));class lw extends Ye{publicClient;chain;applicationsAPI;profileAPI;walletClient;constructor(e,t,r,n,o,i){super(i);this.publicClient=e,this.chain=r,this.walletClient=t,this.applicationsAPI=n,this.profileAPI=o}setWalletClient(e){this.walletClient=e}async getVaultAddress(){return(await this.applicationsAPI.getApplicationConfig()).vaultContractAddress}async getClientId(){return(await this.applicationsAPI.getApplicationConfig()).clientId}async resolveAsset(e){let t,r;try{let n=await this.profileAPI.getUserBalanceByAssetId(e);t=n.token,r=n.wrappedNative===!0}catch(n){if(n instanceof sr){if(n.statusCode===404)throw new Ts(`Asset ID '${e}' does not exist`,{revertReason:"ASSET_NOT_FOUND",cause:n});throw new Ts(`Failed to resolve asset ID '${e}': ${n.retryable?"Network error occurred":"API request failed"}`,{revertReason:n.retryable?"NETWORK_ERROR":"API_ERROR",cause:n})}throw new Ts(`Failed to resolve asset ID '${e}': Unexpected error`,{revertReason:"UNKNOWN_ERROR",cause:n instanceof Error?n:void 0})}return{tokenAddress:t,isWrappedNative:r}}async approve(e,t,r=!0){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");te(Qq,{assetId:e,amount:t,autoWait:r});let n=await this.getVaultAddress(),{tokenAddress:o}=await this.resolveAsset(e),i=this.walletClient.account;if(!i)throw new Bt("No account available in wallet client","account");let s=i.getNonce?await i.getNonce():0n,a=await this.walletClient.writeContract({address:o,abi:ar,functionName:"approve",args:[n,t],chain:this.chain,account:i}),c={nonce:s,hash:a,status:"pending"};return await this.waitForTransaction(c,r)}async deposit(e,t,r=!0,n="spot",o={}){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");te(Xq,{assetId:e,amount:t,autoWait:r,target:n,options:o});let i=await this.getVaultAddress(),s=await this.getClientId(),a=uw(s,n),{tokenAddress:c,isWrappedNative:l}=await this.resolveAsset(e),d=l&&o.asErc20!==!0;if(!d){if(await this.needsApproval(e,t,o))throw new Ts(`Approval required before deposit. Please invoke approve() first for asset ${e} (token address: ${c}).`,{revertReason:"APPROVAL_REQUIRED"})}let f=this.walletClient.account;if(!f)throw new Bt("No account available in wallet client","account");let h;if(d)h=await this.walletClient.writeContract({address:i,abi:JI.vault,functionName:"depositNative",args:[f.address,a],account:f,chain:this.chain,value:t});else h=await this.walletClient.writeContract({address:i,abi:JI.vault,functionName:"depositERC20",args:[f.address,a,c,t],account:f,chain:this.chain});let g=f.getNonce?await f.getNonce():0n,x={hash:h,status:"pending",nonce:g};return await this.waitForTransaction(x,r)}async pollWithdrawalCalldata(e,t){let r=t?.pollIntervalMs??sme,n=t?.timeoutMs??ame,o=Date.now()+n;for(;;){try{let{vaultAddress:i,calldata:s}=await this.makePublicRequest(`/api/v1/withdrawals/${e}`);if(s&&s!=="0x")return{vaultAddress:i,calldata:s}}catch(i){if(!(i instanceof sr&&(i.statusCode===404||i.statusCode===409)))throw i}if(Date.now()+r>o)return null;await cme(r)}}async withdraw(e,t,r=!0,n,o){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");let i=this.walletClient.account;if(!i)throw new Bt("No account available in wallet client","account");let s=i.address.toLowerCase(),a=typeof n==="string"?n:"spot",c=typeof n==="string"?o:n;te(e7,{assetId:e,amount:t,destination:s,autoWait:r,source:a});let{withdrawalIndex:l}=await this.makeAuthenticatedRequest("/api/v1/withdrawals",{method:"POST",body:JSON.stringify({assetId:e,amount:t.toString(),destination:s,source:a})});if(!r)return{withdrawalIndex:l,status:"awaiting_proof"};let d=await this.pollWithdrawalCalldata(l,c);if(!d)return{withdrawalIndex:l,status:"awaiting_proof"};let{vaultAddress:f,calldata:h}=d,g;try{g=await this.walletClient.sendTransaction({to:f,data:h,account:i,chain:this.chain})}catch(_){throw new Ts(`Failed to submit executeWithdrawal for withdrawal ${l}: ${_ instanceof Error?_.message:"unknown error"}`,{cause:_ instanceof Error?_:void 0})}let x=i.getNonce?await i.getNonce():0n,w={hash:g,status:"pending",nonce:x};return{...await this.waitForTransaction(w,r),withdrawalIndex:l}}async retryWithdrawal(e,t=!0,r){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");let n=this.walletClient.account;if(!n)throw new Bt("No account available in wallet client","account");let o=await this.pollWithdrawalCalldata(e,r);if(!o)return{withdrawalIndex:e,status:"awaiting_proof"};let{vaultAddress:i,calldata:s}=o,a;try{a=await this.walletClient.sendTransaction({to:i,data:s,account:n,chain:this.chain})}catch(f){throw new Ts(`Failed to resubmit executeWithdrawal for withdrawal ${e}: ${f instanceof Error?f.message:"unknown error"}`,{cause:f instanceof Error?f:void 0})}let c=n.getNonce?await n.getNonce():0n,l={hash:a,status:"pending",nonce:c};return{...await this.waitForTransaction(l,t),withdrawalIndex:e}}async getBalance(e){throw new sr("getBalance() is deprecated and no longer supported. Please use profileAPI.getUserBalances() or profileAPI.getUserBalanceByAssetId() instead for balance data.",{statusCode:410})}async getAllowance(e){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");let t=await this.getVaultAddress(),n=(await this.walletClient.getAddresses())[0];if(!n)throw new Bt("No account found in wallet client.","walletClient");let{tokenAddress:o}=await this.resolveAsset(e);return await this.publicClient.readContract({address:o,abi:ar,functionName:"allowance",args:[n,t]})}async needsApproval(e,t,r={}){let{isWrappedNative:n}=await this.resolveAsset(e);if(n&&r.asErc20!==!0)return!1;return await this.getAllowance(e)<t}async waitForTransaction(e,t=!0,r={}){if(!t)return e;let{confirmations:n=1,timeout:o=60000}=r;try{let i=await this.publicClient.waitForTransactionReceipt({hash:e.hash,confirmations:n,timeout:o});return{...e,status:i.status==="success"?"confirmed":"failed",receipt:i}}catch{return{...e,status:"failed"}}}}class dw extends Ye{async submit(e){return await this.makePublicRequest(ue.whitelist.submit(),{method:"POST",body:JSON.stringify(e)})}}class QI extends Ye{async initiateWithdrawal(e){return this.makeAuthenticatedRequest(ue.withdrawals.initiate(),{method:"POST",body:JSON.stringify({assetId:e.assetId,amount:e.amount,destination:e.destination,source:e.source??"spot"})})}async getWithdrawal(e){return this.makePublicRequest(ue.withdrawals.byIndex(e))}async listPendingWithdrawals(e){return te(t7,e??{}),this.makeAuthenticatedRequest(ue.withdrawals.list({pageSize:e?.pageSize,pageToken:e?.pageToken}))}}class pw extends Ye{chain;walletClient;constructor(e,t,r){super(r);this.chain=t,this.walletClient=e}setWalletClient(e){this.walletClient=e}async authenticate(e,t,r){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");let n=this.walletClient.account;if(!n)throw new Bt("No account available in wallet client","account");let o=N0(),i={publicKey:$0(o),privateKey:z0(o)},s=await this.createChallenge(n.address,e,i.publicKey),a=await this.signChallenge(s.message);return await this.verifySignature(n.address,a,s.nonce,e,i,t,r)}async signChallenge(e){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");let t=this.walletClient.account;if(!t)throw new Bt("No account available in wallet client","account");return await this.walletClient.signMessage({account:t,message:e})}async createChallenge(e,t,r){let n=await this.makePublicRequest("/api/v1/auth/challenge",{method:"POST",body:JSON.stringify({address:e,clientId:t,chainId:this.chain.id,sessionPublicKey:r})});return{nonce:n.nonce,message:n.message,expiresAt:n.expiresAt}}async verifySignature(e,t,r,n,o,i,s){let a=await this.makePublicRequest("/api/v1/auth/verify",{method:"POST",body:JSON.stringify({address:e,signature:t,nonce:r,clientId:n,chainId:this.chain.id,sessionPublicKey:o.publicKey,...i?{referralCode:i}:{},...s?{inviteCode:s}:{}})});return{sessionPublicKey:o.publicKey,sessionPrivateKey:o.privateKey,expiresAt:a.expiresAt,user:{id:a.user.id,address:a.user.address,username:a.user.username},...a.isNewUser!==void 0?{isNewUser:a.isNewUser}:{},...a.referralApplied!==void 0?{referralApplied:a.referralApplied}:{}}}async requestInviteCodes(){return await this.makeAuthenticatedRequest("/api/v1/invite-codes/requests",{method:"POST",body:JSON.stringify({})})}async listInviteCodes(){return await this.makeAuthenticatedRequest("/api/v1/invite-codes",{method:"GET"})}async refreshSession(){return{expiresAt:(await this.makeAuthenticatedRequest("/api/v1/auth/refresh",{method:"POST"})).expiresAt}}async revokeSession(){await this.makeAuthenticatedRequest("/api/v1/auth/revoke",{method:"POST"})}}var ume=750;function s7(e,t){try{new URL(e)}catch(r){throw new Bt(`${t} must be a valid URL, got: ${e}`,t)}return e}class ek{auth;delegatedAgents;applications;fees;buildercodes;copyTrading;tradercodes;pitpass;vault;withdrawals;trading;market;marginAccounts;positions;portfolio;subAccounts;faucet;sweeper;managedMarkets;whitelist;profile;pulse;orderbook;trades;ws;walletClient;publicClient;authState;network;chain;propagateSession(e){this.auth.setSessionKeypair(e),this.delegatedAgents.setSessionKeypair(e),this.applications.setSessionKeypair(e),this.fees.setSessionKeypair(e),this.buildercodes.setSessionKeypair(e),this.copyTrading.setSessionKeypair(e),this.tradercodes.setSessionKeypair(e),this.vault.setSessionKeypair(e),this.withdrawals.setSessionKeypair(e),this.trading.setSessionKeypair(e),this.market.setSessionKeypair(e),this.marginAccounts.setSessionKeypair(e),this.positions.setSessionKeypair(e),this.portfolio.setSessionKeypair(e),this.subAccounts.setSessionKeypair(e),this.faucet.setSessionKeypair(e),this.sweeper.setSessionKeypair(e),this.managedMarkets.setSessionKeypair(e),this.whitelist.setSessionKeypair(e),this.pulse.setSessionKeypair(e),this.profile.setSessionKeypair(e),this.orderbook.setSessionKeypair(e),this.trades.setSessionKeypair(e),this.ws.setSessionKeypair(e)}sessionFromAuthState(e){return{publicKey:e.sessionPublicKey,privateKey:e.sessionPrivateKey}}constructor(e){let t=["mainnet","development","staging","local"];if(!e.network||!t.includes(e.network))throw new Bt(`network must be one of: ${t.join(", ")}. Got: ${e.network}`,"network");if(this.network=e.network,!e.seiRpcUrl)throw new Bt("seiRpcUrl is required","seiRpcUrl");try{new URL(e.seiRpcUrl)}catch(c){throw new Bt(`seiRpcUrl must be a valid URL, got: ${e.seiRpcUrl}`,"seiRpcUrl")}let r=e.wsUrl?s7(e.wsUrl,"wsUrl"):sE(this.network),n=this.network==="mainnet"?yh:bh;if(this.chain=n,e.pollingInterval!==void 0&&(!Number.isFinite(e.pollingInterval)||e.pollingInterval<=0))throw new Bt(`pollingInterval must be a positive number of milliseconds, got: ${e.pollingInterval}`,"pollingInterval");let o=gh(e.seiRpcUrl);this.publicClient=uI({chain:n,transport:o,pollingInterval:e.pollingInterval??ume});let i=e.apiUrl?s7(e.apiUrl,"apiUrl"):iE(this.network);if(e.walletClient){if(e.walletClient.chain?.id!==n.id)throw new Bt(`Wallet client chain mismatch. Expected ${n.id}, got ${e.walletClient.chain?.id}`,"walletClient");this.walletClient=e.walletClient}let s=new cu,a=(c)=>(c.setRequestSigning(e.requestSigning??"legacy"),c.setServerClock(s),c);this.applications=a(new Vx(i)),this.market=a(new Xx(i)),this.marginAccounts=a(new Qx(i)),this.positions=a(new nw(i)),this.portfolio=a(new rw(i)),this.subAccounts=a(new iw(i)),this.faucet=a(new Yx(i)),this.sweeper=a(new sw(i)),this.managedMarkets=a(new GI(i)),this.whitelist=a(new dw(i)),this.pulse=a(new ow(i)),this.auth=a(new pw(this.walletClient,this.chain,i)),this.delegatedAgents=a(new HI(i)),this.fees=a(new Jx(i)),this.buildercodes=a(new Zx(i)),this.copyTrading=a(new Kx(i)),this.tradercodes=a(new Th(i)),this.pitpass=this.tradercodes,this.profile=a(new VI(i)),this.vault=a(new lw(this.publicClient,this.walletClient,this.chain,this.applications,this.profile,i)),this.withdrawals=a(new QI(i)),this.trading=a(new cw(i)),this.orderbook=a(new ew(i)),this.trades=a(new ZI(i)),this.ws=Qv(r,e.ws,s),this.ws.connect().catch(console.error)}async login(e,t){if(this.authState=await this.auth.authenticate(e,void 0,t?.inviteCode),this.propagateSession(this.sessionFromAuthState(this.authState)),t?.connectWebSocket)await this.ws.connect();return this.authState}async loginAsDelegatedOwner(e){if(!this.authState)throw new sr("No active agent session to create delegated session",{endpoint:"delegated-agents/sessions",statusCode:XI.StatusCodes.UNAUTHORIZED});let t=N0(),r={publicKey:$0(t),privateKey:z0(t)},n=await this.delegatedAgents.createDelegatedSession({ownerUserId:e,sessionPublicKey:r.publicKey});return this.authState={sessionPublicKey:r.publicKey,sessionPrivateKey:r.privateKey,expiresAt:n.expiresAt,user:{id:n.ownerUserId,address:n.agentAddress}},this.propagateSession(this.sessionFromAuthState(this.authState)),this.authState}getAuthState(){return this.authState}setAuthState(e){this.authState=e,this.propagateSession(this.sessionFromAuthState(e))}async logout(){if(this.authState)try{await this.auth.revokeSession()}catch(e){console.warn("Failed to revoke session on logout:",e)}this.authState=void 0,this.propagateSession(void 0),this.ws.disconnect()}async refreshAuth(){if(!this.authState)throw new sr("No active session to refresh",{endpoint:"auth/refresh",statusCode:XI.StatusCodes.UNAUTHORIZED});try{let e=await this.auth.refreshSession();return this.authState={...this.authState,expiresAt:e.expiresAt},this.authState}catch(e){throw this.authState=void 0,this.propagateSession(void 0),e}}isAuthenticated(){return!!this.authState}isConnected(){return!!this.walletClient&&!!this.publicClient}setWalletClient(e){if(e.chain?.id!==this.chain.id)throw new Bt(`Wallet client chain mismatch. Expected ${this.chain.id}, got ${e.chain?.id}`,"walletClient");this.walletClient=e,this.auth.setWalletClient(e),this.vault.setWalletClient(e)}getAccountAddress(){if(!this.walletClient)throw new Sm("Wallet client not set","walletClient");if(this.walletClient.account)return this.walletClient.account.address;throw new Sm("No account available","account")}getNetwork(){return this.network}getChainId(){return this.chain.id}async waitForTransaction(e,t,r){return this.publicClient.waitForTransactionReceipt({hash:e,confirmations:t,timeout:r})}}function tk(e){return new ek(e)}ih();Ke();Ri();Qn();function a7(e){if(typeof e==="string"){if(!_t(e,{strict:!1}))throw new Qt({address:e});return{address:e,type:"json-rpc"}}if(!_t(e.address,{strict:!1}))throw new Qt({address:e.address});return{address:e.address,nonceManager:e.nonceManager,sign:e.sign,signAuthorization:e.signAuthorization,signMessage:e.signMessage,signTransaction:e.signTransaction,signTypedData:e.signTypedData,source:"custom",type:"local"}}ih();Dr();Ke();var rk=!1;async function Gi({hash:e,privateKey:t,to:r="object"}){let{r:n,s:o,recovery:i}=Vs.sign(e.slice(2),t.slice(2),{lowS:!0,extraEntropy:cr(rk,{strict:!1})?Cr(rk):rk}),s={r:Z(n,{size:32}),s:Z(o,{size:32}),v:i?28n:27n,yParity:i};return(()=>{if(r==="bytes"||r==="hex")return yx({...s,to:r});return s})()}async function c7(e){let{chainId:t,nonce:r,privateKey:n,to:o="object"}=e,i=e.contractAddress??e.address,s=await Gi({hash:Yb({address:i,chainId:t,nonce:r}),privateKey:n,to:o});if(o==="object")return{address:i,chainId:t,nonce:r,...s};return s}async function u7({message:e,privateKey:t}){return await Gi({hash:mp(e),privateKey:t,to:"hex"})}wo();Tn();Ke();function l7(e){if(!e||e.length===0)return[];let t=[];for(let r of e){let{chainId:n,nonce:o,...i}=r,s=r.address;t.push([n?lr(n):"0x",s,o?lr(o):"0x",...kp({},i)])}return t}Ke();KP();Ri();et();Um();js();Qn();Mn();Is();Rr();function d7(e){let{authorizationList:t}=e;if(t)for(let r of t){let{chainId:n}=r,o=r.address;if(!_t(o))throw new Qt({address:o});if(n<0)throw new pd({chainId:n})}fw(e)}function p7(e){let{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new ch;for(let r of t){let n=lt(r),o=ur($n(r,0,1));if(n!==32)throw new bA({hash:r,size:n});if(o!==Xb)throw new xA({hash:r,version:o})}}fw(e)}function fw(e){let{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:o}=e;if(t<=0)throw new pd({chainId:t});if(o&&!_t(o))throw new Qt({address:o});if(n&&n>Zd)throw new Zo({maxFeePerGas:n});if(r&&n&&r>n)throw new Us({maxFeePerGas:n,maxPriorityFeePerGas:r})}function f7(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:i}=e;if(t<=0)throw new pd({chainId:t});if(i&&!_t(i))throw new Qt({address:i});if(r||o)throw new N("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Zd)throw new Zo({maxFeePerGas:n})}function m7(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:i}=e;if(i&&!_t(i))throw new Qt({address:i});if(typeof t<"u"&&t<=0)throw new pd({chainId:t});if(r||o)throw new N("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Zd)throw new Zo({maxFeePerGas:n})}Ri();Tn();Qn();function Eh(e){if(!e||e.length===0)return[];let t=[];for(let r=0;r<e.length;r++){let{address:n,storageKeys:o}=e[r];for(let i=0;i<o.length;i++)if(o[i].length-2!==64)throw new SP({storageKey:o[i]});if(!_t(n,{strict:!1}))throw new Qt({address:n});t.push([n,o])}return t}function h7(e,t){let r=tx(e);if(r==="eip1559")return pme(e,t);if(r==="eip2930")return fme(e,t);if(r==="eip4844")return dme(e,t);if(r==="eip7702")return lme(e,t);return mme(e,t)}function lme(e,t){let{authorizationList:r,chainId:n,gas:o,nonce:i,to:s,value:a,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:d,data:f}=e;d7(e);let h=Eh(d),g=l7(r);return dr(["0x04",Zs([Z(n),i?Z(i):"0x",l?Z(l):"0x",c?Z(c):"0x",o?Z(o):"0x",s??"0x",a?Z(a):"0x",f??"0x",h,g,...kp(e,t)])])}function dme(e,t){let{chainId:r,gas:n,nonce:o,to:i,value:s,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:d,data:f}=e;p7(e);let{blobVersionedHashes:h,sidecars:g}=e;if(e.blobs&&(typeof h>"u"||typeof g>"u")){let T=typeof e.blobs[0]==="string"?e.blobs:e.blobs.map((k)=>St(k)),v=e.kzg,E=Qd({blobs:T,kzg:v});if(typeof h>"u")h=Qb({commitments:E});if(typeof g>"u"){let k=Xd({blobs:T,commitments:E,kzg:v});g=ex({blobs:T,commitments:E,proofs:k})}}let x=Eh(d),w=[Z(r),o?Z(o):"0x",l?Z(l):"0x",c?Z(c):"0x",n?Z(n):"0x",i??"0x",s?Z(s):"0x",f??"0x",x,a?Z(a):"0x",h??[],...kp(e,t)],S=[],_=[],A=[];if(g)for(let T=0;T<g.length;T++){let{blob:v,commitment:E,proof:k}=g[T];S.push(v),_.push(E),A.push(k)}return dr(["0x03",g?Zs([w,S,_,A]):Zs(w)])}function pme(e,t){let{chainId:r,gas:n,nonce:o,to:i,value:s,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:l,data:d}=e;fw(e);let f=Eh(l),h=[Z(r),o?Z(o):"0x",c?Z(c):"0x",a?Z(a):"0x",n?Z(n):"0x",i??"0x",s?Z(s):"0x",d??"0x",f,...kp(e,t)];return dr(["0x02",Zs(h)])}function fme(e,t){let{chainId:r,gas:n,data:o,nonce:i,to:s,value:a,accessList:c,gasPrice:l}=e;f7(e);let d=Eh(c),f=[Z(r),i?Z(i):"0x",l?Z(l):"0x",n?Z(n):"0x",s??"0x",a?Z(a):"0x",o??"0x",d,...kp(e,t)];return dr(["0x01",Zs(f)])}function mme(e,t){let{chainId:r=0,gas:n,data:o,nonce:i,to:s,value:a,gasPrice:c}=e;m7(e);let l=[i?Z(i):"0x",c?Z(c):"0x",n?Z(n):"0x",s??"0x",a?Z(a):"0x",o??"0x"];if(t){let d=(()=>{if(t.v>=35n){if((t.v-35n)/2n>0)return t.v;return 27n+(t.v===35n?0n:1n)}if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);let g=27n+(t.v===27n?0n:1n);if(t.v!==g)throw new xP({v:t.v});return g})(),f=tn(t.r),h=tn(t.s);l=[...l,Z(d),f==="0x00"?"0x":f,h==="0x00"?"0x":h]}else if(r>0)l=[...l,Z(r),"0x","0x"];return Zs(l)}function kp(e,t){let r=t??e,{v:n,yParity:o}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof o>"u")return[];let i=tn(r.r),s=tn(r.s);return[(()=>{if(typeof o==="number")return o?Z(1):"0x";if(n===0n)return"0x";if(n===1n)return Z(1);return n===27n?"0x":Z(1)})(),i==="0x00"?"0x":i,s==="0x00"?"0x":s]}async function g7(e){let{privateKey:t,transaction:r,serializer:n=h7}=e,o=(()=>{if(r.type==="eip4844")return{...r,sidecars:!1};return r})(),i=await Gi({hash:Ot(await n(o)),privateKey:t});return await n(r,i)}async function y7(e){let{privateKey:t,...r}=e;return await Gi({hash:wx(r),privateKey:t,to:"hex"})}function nk(e,t={}){let{nonceManager:r}=t,n=lr(Vs.getPublicKey(e.slice(2),!1)),o=Kb(n);return{...a7({address:o,nonceManager:r,async sign({hash:s}){return Gi({hash:s,privateKey:e,to:"hex"})},async signAuthorization(s){return c7({...s,privateKey:e})},async signMessage({message:s}){return u7({message:s,privateKey:e})},async signTransaction(s,{serializer:a}={}){return g7({privateKey:e,transaction:s,serializer:a})},async signTypedData(s){return y7({...s,privateKey:e})}}),publicKey:n,source:"privateKey"}}var ok=null;var hme={privateKeyToAccount:nk,createWalletClient:fI,http:gh,createMonacoSDK:tk,sei:yh,seiTestnet:bh};function gme(e,t=hme){let r=e.network==="mainnet"?t.sei:t.seiTestnet,n;if(e.privateKey){let o=t.privateKeyToAccount(e.privateKey);n=t.createWalletClient({account:o,chain:r,transport:t.http(e.seiRpcUrl)})}return t.createMonacoSDK({walletClient:n,network:e.network,seiRpcUrl:e.seiRpcUrl})}function Ge(e){if(!ok){let t=e??Jc();ok=gme(t)}return ok}var yme=60,mw=null;function bme(){return Math.floor(Date.now()/1000)}function b7(e){return e-yme<=bme()}function xme(e){for(let t=e,r=0;t instanceof Error&&r<5;r++){if(t instanceof sr&&t.statusCode===401)return!0;t=t.cause}return!1}function ik(e){if(!mw)mw=e().finally(()=>{mw=null});return mw}async function x7(e,t){if(await e.login(t.clientId),t.delegatedOwnerUserId){try{let r=await e.loginAsDelegatedOwner(t.delegatedOwnerUserId);console.error(`Adopted delegated owner ${r.user.id} (session expires at ${new Date(r.expiresAt*1000).toISOString()})`)}catch(r){throw await e.logout().catch(()=>{}),r}return}console.error(`Authenticated as ${e.getAccountAddress()}`)}async function w7(e,t){try{await e.refreshAuth()}catch{await x7(e,t)}}async function H(e){let t=Ge(e),r=e??Jc(),n=t.getAuthState(),o=r.delegatedOwnerUserId!=null&&n?.user?.id!==r.delegatedOwnerUserId;if(!n||o)return await ik(()=>x7(t,r)),t;if(b7(n.expiresAt))await ik(()=>w7(t,r));return t}async function wme(e){let t=e??Jc();if(!t.privateKey)return!1;let r=Ge(e);return await ik(()=>w7(r,t)),!0}function S7(e,t){async function r(...n){let o=Ge(t).getAuthState(),i=o!==void 0&&!b7(o.expiresAt);try{return await e(...n)}catch(s){if(!xme(s))throw s;if(!(i&&Ge(t).getAuthState()!==o)){if(!await wme(t))throw s}return await e(...n)}}return r}function C(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function hw(e){return{content:[{type:"text",text:e}]}}function _7(e){e.registerTool("add_follow_position_margin",{description:"Add margin to one of your copy positions. MOVES FUNDS: moves `amount` from the follow's copy account into the margin of its isolated copy position on one trading pair; the position's margin rises by exactly `amount`, the copy account's remaining collateral falls by the same, and your margin account is never touched. It lowers the position's leverage and moves its liquidation price away; it opens no exposure, so it works while copy trading is switched off and on a CLOSE_ONLY follow. There is no margin reduction: a follow exits by being stopped. Refused for a follow that is stopping or stopped (409), and when the follow holds no copy position on the pair, the position or the margin account is being liquidated, the position has lost more than its margin, or the amount is more than the copy account holds (400). Not idempotent: do not retry a timed-out call without first reading the follow, or the amount may be added twice. Only your own follows; delegated agent and sub-account sessions cannot add margin.",inputSchema:y({followId:p().uuid().describe("The follow's id (UUID), from list_my_follows"),tradingPairId:p().uuid().describe("Trading pair UUID of the copy position to add margin to"),amount:p().describe("Margin to add, in quote units (positive decimal string), taken from the follow's copy account")}).strict()},async({followId:t,tradingPairId:r,amount:n})=>{let i=await(await H()).copyTrading.addFollowPositionMargin({followId:t,tradingPairId:r,amount:n});return C(i)})}function T7(e){e.registerTool("close_all_copy_positions",{description:"Close the copy positions of every live copy trading follow of yours at market (reduce-only, immediate-or-cancel), KEEPING the follows: their leaders' next trades keep mirroring, so this is not a flatten guarantee. Proceeds stay in each copy account. Works even with copy trading switched off; shares close_follow_positions' per-account rate limit. Returns each follow's close orders placed and positions still open, the follows whose stop is in progress (left to their stop), and the follows whose close could not run (failedFollows, with a reason; retry them).",inputSchema:y({}).strict()},async()=>{let r=await(await H()).copyTrading.closeAllCopyPositions();return C(r)})}function v7(e){e.registerTool("close_follow_positions",{description:"Close every position in one of your copy trading follows' copy accounts at market (reduce-only, immediate-or-cancel) and cancel the resting orders and TP/SL orders on its copy risk buckets, KEEPING the follow: the leader's next trades keep mirroring, so this is not a flatten guarantee (use stop_follow to close and stop). Proceeds stay in the copy account. Works even with copy trading switched off; rate limited per account (about one close per second, burst 5, shared with close_all_copy_positions). Returns how many close orders were placed and how many positions remain open (a thin or halted market can leave some); fills arrive on the order, position and copy channels. 404 for a follow that is not yours; 409 for a stopped follow or one whose stop is in progress.",inputSchema:y({followId:p().uuid().describe("The follow's id (UUID), from list_my_follows")}).strict()},async({followId:t})=>{let n=await(await H()).copyTrading.closeFollowPositions(t);return C(n)})}function E7(e){e.registerTool("get_follow",{description:"Get one of your copy trading follows with its most recent skipped mirrors (up to 100): leader fills the follow could not copy, with the reason (e.g. INSUFFICIENT_MARGIN) and the quantity that was not placed, plus copyAccountEquity: the copy account's equity at the engine's marks (a balance, not trading PnL; absent when it could not be read). 404 for a follow that is not yours.",inputSchema:y({followId:p().uuid().describe("The follow's id (UUID), from list_my_follows")})},async({followId:t})=>{let n=await(await H()).copyTrading.getFollow(t);return C(n)})}function P7(e){e.registerTool("get_lead_trader",{description:"Public lookup of one copy trading lead trader by custom TraderCode handle (no credentials required): profile (status, profit share in bps, bio, minimum allocation), follow summary, and stats for the 7d, 30d, 90d and all windows. 404 for an unknown or suspended leader.",inputSchema:y({handle:p().min(1).describe("The leader's custom TraderCode handle")})},async({handle:t})=>{let n=await Ge().copyTrading.getLeadTrader(t);return C(n)})}function A7(e){e.registerTool("get_my_lead_trader",{description:"Get your own copy trading lead trader profile, follow summary and stats. 404 when you are not a lead trader.",inputSchema:y({})},async()=>{let r=await(await H()).copyTrading.getMyLeadTrader();return C(r)})}function I7(e){e.registerTool("list_follow_leader_positions",{description:"List the open positions of the lead trader one of your follows copies. The leader comes from the follow, so this works even after the leader releases their handle. 404 for a follow that is not yours; 403 for a stopped follow.",inputSchema:y({followId:p().uuid().describe("The follow's id (UUID), from list_my_follows")})},async({followId:t})=>{let n=await(await H()).copyTrading.listFollowLeaderPositions(t);return C(n)})}function k7(e){e.registerTool("list_lead_trader_closed_trades",{description:"Public list of a copy trading lead trader's closed trades (no credentials required): the leader's reducing executions (partial and full closes, liquidations, auto-deleveraging), newest first, with size, entry and exit price, gross and net realized PnL, and realized ROE. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({handle:p().min(1).describe("The leader's custom TraderCode handle"),pageSize:I().int().min(1).max(100).optional().describe("Trades per page (default 20, max 100)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")})},async({handle:t,pageSize:r,pageToken:n})=>{let i=await Ge().copyTrading.listLeadTraderClosedTrades(t,{pageSize:r,pageToken:n});return C(i)})}function R7(e){e.registerTool("list_lead_trader_open_positions",{description:"List the open positions of a copy trading lead trader you currently follow (side, size, entry and mark price, unrealized PnL, leverage, margin mode). Only current followers of that leader may read them; anyone else gets 403.",inputSchema:y({handle:p().min(1).describe("The leader's custom TraderCode handle")})},async({handle:t})=>{let n=await(await H()).copyTrading.listLeadTraderOpenPositions(t);return C(n)})}function C7(e){e.registerTool("list_lead_traders",{description:"Public copy trading leaderboard (no credentials required): lead traders ranked highest first by a metric over a stats window, each with profile, follow summary (follower count, allocated AUM and marked AUM equity) and stats (PnL, ROI %, max drawdown %, win rate %, closed trades). Leaders are identified by wallet and custom TraderCode handle; use the handle with the other copy trading tools. Cursor paged: pass the previous response's nextPageToken with the SAME sort and window; an empty nextPageToken means the end.",inputSchema:y({sort:z(["roi","pnl","followers","allocated","aum","win_rate"]).optional().describe("Metric to rank by, highest first (default roi); aum ranks by the marked equity of live follows' copy accounts"),window:z(["7d","30d","90d","all"]).optional().describe("Stats window (default 30d)"),pageSize:I().int().min(1).max(100).optional().describe("Leaders per page (default 20, max 100)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")})},async({sort:t,window:r,pageSize:n,pageToken:o})=>{let s=await Ge().copyTrading.listLeadTraders({sort:t,window:r,pageSize:n,pageToken:o});return C(s)})}function O7(e){e.registerTool("list_my_followers",{description:"List your copy trading followers, as a lead trader: each follower's wallet, display name, status (ACTIVE or CLOSE_ONLY), allocation and start time. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({pageSize:I().int().min(1).max(1000).optional().describe("Followers per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")})},async({pageSize:t,pageToken:r})=>{let o=await(await H()).copyTrading.listMyFollowers({pageSize:t,pageToken:r});return C(o)})}function M7(e){e.registerTool("list_my_follows",{description:"List your copy trading follows, newest first: leader, status (ACTIVE, CLOSE_ONLY or STOPPED), sizing, leverage and margin mode settings, allocation, stop-loss, market filter, consecutive skips, and the copy risk bucket id. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({pageSize:I().int().min(1).max(1000).optional().describe("Follows per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")})},async({pageSize:t,pageToken:r})=>{let o=await(await H()).copyTrading.listMyFollows({pageSize:t,pageToken:r});return C(o)})}function N7(e){e.registerTool("preview_follow",{description:"Preview what following a copy trading lead trader with copyExisting would open, as totals only: the estimated margin and fees, and how many of the leader's open positions would and would not be copied (no markets, sides or reasons). At most 64 positions are sized (truncated is true when the leader holds more). It refuses terms a follow would refuse and spends the order-risk preview budget. Read-only: nothing is placed, reserved or moved.",inputSchema:y({leader:p().describe("The leader's custom TraderCode handle"),allocation:p().describe("Collateral the copy account would start with, in quote units (decimal string)"),marginModePolicy:z(["FOLLOW","CROSS","ISOLATED"]).optional().describe("FOLLOW (default: the leader's mode per market), CROSS or ISOLATED"),sizingMode:z(["PROPORTIONAL","FIXED_MARGIN"]).optional().describe("PROPORTIONAL (default) or FIXED_MARGIN"),sizingParam:p().optional().describe("Margin per leader order in quote units; required for FIXED_MARGIN, not allowed otherwise"),leverageMode:z(["FOLLOW","FIXED"]).optional().describe("FOLLOW (default: the leader's leverage) or FIXED"),fixedLeverage:p().optional().describe("Leverage for every copy; required for FIXED, not allowed otherwise"),tradingPairIds:ie(p()).optional().describe("Trading pair UUIDs to copy; omit to copy every market the leader trades")}).strict().refine((t)=>t.sizingMode==="FIXED_MARGIN"===(t.sizingParam!==void 0),{message:"sizingParam is required for FIXED_MARGIN sizing and not allowed otherwise",path:["sizingParam"]}).refine((t)=>t.leverageMode==="FIXED"===(t.fixedLeverage!==void 0),{message:"fixedLeverage is required for FIXED leverage and not allowed otherwise",path:["fixedLeverage"]})},async({leader:t,allocation:r,marginModePolicy:n,sizingMode:o,sizingParam:i,leverageMode:s,fixedLeverage:a,tradingPairIds:c})=>{let d=await(await H()).copyTrading.previewFollow({leader:t,allocation:r,marginModePolicy:n,sizingMode:o,sizingParam:i,leverageMode:s,fixedLeverage:a,tradingPairIds:c});return C(d)})}function $7(e){e.registerTool("stop_follow",{description:"Stop one of your copy trading follows: the leader's fills stop being mirrored into its copy account. Only your own follows; a delegated agent session cannot stop a follow.",inputSchema:y({followId:p().uuid().describe("The follow's id (UUID), from list_my_follows")})},async({followId:t})=>{let n=await(await H()).copyTrading.stopFollow(t);return C(n)})}function z7(e){e.registerTool("upsert_follow",{description:"Follow a copy trading lead trader, or edit one of your follows. MOVES FUNDS: a new follow moves `allocation` from your margin account into a new copy account (a cross risk bucket) and from then on every fill the leader makes is mirrored into it with market orders. Omit followId to create (leader required); set followId to edit. An edit REPLACES the follow's settings: every optional setting left out reverts to its default (an edit without slPct removes the stop-loss), so send the full configuration.",inputSchema:y({followId:p().uuid().optional().describe("Omit to create a follow; set to edit one of your follows"),leader:p().optional().describe("The leader's custom TraderCode handle; required on a create, optional on an edit"),allocation:p().describe("Collateral for the copy account, in quote units (decimal string), at or above the minimum"),marginModePolicy:z(["FOLLOW","CROSS","ISOLATED"]).optional().describe("FOLLOW (default: the leader's mode per market), CROSS or ISOLATED"),sizingMode:z(["PROPORTIONAL","FIXED_MARGIN"]).optional().describe("PROPORTIONAL (default: scaled by copy account equity over the leader's equity) or FIXED_MARGIN"),sizingParam:p().optional().describe("Margin per leader order in quote units; required for FIXED_MARGIN, not allowed otherwise"),leverageMode:z(["FOLLOW","FIXED"]).optional().describe("FOLLOW (default: the leader's leverage) or FIXED"),fixedLeverage:p().optional().describe("Leverage for every copy; required for FIXED, not allowed otherwise"),slPct:p().optional().describe("Copy stop-loss as a fraction of the allocation in (0, 1], e.g. '0.25'; omit for none"),tradingPairIds:ie(p()).optional().describe("Trading pair UUIDs to copy; omit to copy every market the leader trades"),copyExisting:oe().optional().describe("On a create, also copy the leader's currently open positions into the new copy account (preview_follow shows the cost); refused on an edit")}).strict().refine((t)=>t.followId!==void 0||t.leader!==void 0,{message:"leader is required when creating a follow",path:["leader"]}).refine((t)=>t.followId===void 0||t.copyExisting!==!0,{message:"copyExisting applies only when creating a follow",path:["copyExisting"]}).refine((t)=>t.sizingMode==="FIXED_MARGIN"===(t.sizingParam!==void 0),{message:"sizingParam is required for FIXED_MARGIN sizing and not allowed otherwise",path:["sizingParam"]}).refine((t)=>t.leverageMode==="FIXED"===(t.fixedLeverage!==void 0),{message:"fixedLeverage is required for FIXED leverage and not allowed otherwise",path:["fixedLeverage"]})},async({followId:t,leader:r,allocation:n,marginModePolicy:o,sizingMode:i,sizingParam:s,leverageMode:a,fixedLeverage:c,slPct:l,tradingPairIds:d,copyExisting:f})=>{let g=await(await H()).copyTrading.upsertFollow({followId:t,leader:r,allocation:n,marginModePolicy:o,sizingMode:i,sizingParam:s,leverageMode:a,fixedLeverage:c,slPct:l,tradingPairIds:d,copyExisting:f});return C(g)})}function L7(e){e.registerTool("upsert_lead_trader",{description:"Register as a copy trading lead trader, or edit your lead profile. Registration is checked against the platform's eligibility rules (account equity, trading history, closed positions, a claimed custom TraderCode handle); a refusal names the rule. A wallet with a live follow cannot register. The profile is replaced as sent: an omitted bio or minAllocation is cleared and an omitted status means ACTIVE; an omitted shareBps keeps the current profit share.",inputSchema:y({shareBps:I().int().min(0).max(1e4).optional().describe("Your share of followers' realized profit, in basis points"),bio:p().optional().describe("Free-text profile description, at most 2,000 bytes; omit to clear"),status:z(["ACTIVE","PAUSED"]).optional().describe("ACTIVE accepts new follows; PAUSED keeps existing follows mirroring but accepts no new ones (default ACTIVE)"),minAllocation:p().optional().describe("Minimum follow allocation in quote units (decimal string); omit to clear")}).strict()},async({shareBps:t,bio:r,status:n,minAllocation:o})=>{let s=await(await H()).copyTrading.upsertLeadTrader({shareBps:t,bio:r,status:n,minAllocation:o});return C(s)})}function B7(e){C7(e),P7(e),k7(e)}function D7(e){R7(e),A7(e),O7(e),M7(e),E7(e),I7(e),N7(e),L7(e),z7(e),$7(e),v7(e),T7(e),_7(e)}function F7(e,t){if(t.network==="mainnet")return;e.registerTool("get_faucet_info",{description:"Get the authenticated wallet's faucet quota: remaining requests in the rolling 24h window, when the next request becomes available, and the 5 most recent faucet requests. Check this before request_faucet to avoid rate-limit errors. Only available on non-mainnet networks (development, staging, local).",inputSchema:{}},async()=>{let n=await(await H()).faucet.getInfo();return C(n)})}function U7(e,t){if(t.network==="mainnet")return;e.registerTool("request_faucet",{description:"Request test funds from the faucet for all active trading pairs. Requires a Cloudflare Turnstile token (the faucet rejects requests without one). Only available on non-mainnet networks (development, staging, local).",inputSchema:y({turnstileToken:p().describe("Cloudflare Turnstile token proving the request came from a real client (required by the faucet).")})},async({turnstileToken:r})=>{let o=await(await H()).faucet.mint({turnstileToken:r});return C(o)})}function j7(e,t){U7(e,t),F7(e,t)}function q7(e){e.registerTool("get_my_fee_tier",{description:"Get the authenticated user's current fee tier, rolling 14-day volumes (with spot/perp breakdown), the volume needed to reach the next tier, and the requested pair's six-row fee schedule.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID whose fee schedule to return")})},async({tradingPairId:t})=>{let n=await(await H()).fees.getMyFeeTier({tradingPairId:t});return C(n)})}function H7(e){e.registerTool("simulate_fees",{description:"Simulate the fees for an order before placing it. Returns Monaco protocol fees, application fees, and total amounts.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),side:z(["BUY","SELL"]).describe("Order side"),price:p().describe("Price per unit as a decimal string"),quantity:p().describe("Quantity to trade as a decimal string")})},async({tradingPairId:t,side:r,price:n,quantity:o})=>{let s=await(await H()).fees.simulateFees({tradingPairId:t,side:r,price:n,quantity:o});return C(s)})}function G7(e){H7(e),q7(e)}function V7(e){e.registerTool("get_available_collateral",{description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",inputSchema:y({asset:p().optional().describe("Optional collateral asset symbol or ID to scope the query")})},async({asset:t})=>{let n=await(await H()).marginAccounts.getAvailableCollateral({asset:t});return C(n)})}function Z7(e){e.registerTool("get_margin_accounts",{description:"List your margin accounts with optional filters (state, trading pair). Cursor paged; an empty nextPageToken means the end.",inputSchema:y({pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page"),state:p().optional().describe("Filter by margin account state"),tradingPairId:p().optional().describe("Filter by trading pair UUID")})},async({pageSize:t,pageToken:r,state:n,tradingPairId:o})=>{let s=await(await H()).marginAccounts.listMarginAccounts({pageSize:t,pageToken:r,state:n,tradingPairId:o});return C(s)})}function W7(e){e.registerTool("get_parent_margin_account_movements",{description:"List collateral movements for your parent (cross) margin account. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({movementType:p().optional().describe("Filter by movement type"),pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")})},async({movementType:t,pageSize:r,pageToken:n})=>{let i=await(await H()).marginAccounts.getParentMarginAccountMovements({movementType:t,pageSize:r,pageToken:n});return C(i)})}function K7(e){e.registerTool("get_parent_margin_account_summary",{description:"Get your parent (cross) margin account summary.",inputSchema:y({tradingPairId:p().optional().describe("Optional trading pair UUID to scope the summary")})},async({tradingPairId:t})=>{let n=await(await H()).marginAccounts.getParentMarginAccountSummary({tradingPairId:t});return C(n)})}var Sme=y({applicationId:p().uuid(),enrolled:oe(),payoutAddress:p().nullable().optional(),buildercodesEnabled:oe(),buildercodesBudgetBps:I().int().min(0).max(1e4),builderFeeEnabled:oe(),builderFeeBps:I().int().min(0).max(100),builderFeeCapBps:I().int().min(0).max(100),changesRemaining:I().int().min(0).max(2),nextChangeAllowedAt:p().nullable().optional()}),_me=y({bps:I().int().min(0).max(100)}),Tme=y({builderFeeBps:I().int().min(0).max(100),previousBuilderFeeBps:I().int().min(0).max(100),changesRemaining:I().int().min(0).max(2),nextChangeAllowedAt:p().nullable().optional()}),Y7=z(["BUILDER","ADMIN"]),J7=y({actorType:Y7,actor:p(),oldBps:I().int().min(0).max(100),newBps:I().int().min(0).max(100),createdAt:p()}),vme=y({pageSize:I().int().min(1).max(100).optional(),pageToken:p().optional()}),Eme=y({changes:ie(J7),nextPageToken:p()}),gw=z(["REVENUE_SHARE","BUILDER_FEE"]),Pme=y({page:Qe().optional(),pageSize:I().int().min(1).max(1000).optional(),pageToken:p().optional(),kind:gw.optional()}),Q7=y({tradeId:p().uuid(),payoutAddress:p(),token:p(),amount:p(),appliedBps:I().int(),createdAt:p(),kind:gw.optional()}),Ame=y({payouts:ie(Q7),total:I().int().nonnegative(),pageSize:I().int().positive(),totalPages:I().int().nonnegative(),nextPageToken:p()}),X7=y({token:p(),totalAmount:p(),payoutCount:I().int().nonnegative(),lastCreditedAt:p()}),eH=y({token:p(),kind:gw,totalAmount:p(),payoutCount:I().int().nonnegative(),lastCreditedAt:p()}),Ime=y({totalPayouts:I().int().nonnegative(),lastCreditedAt:p().nullable().optional(),byToken:ie(X7),byTokenAndKind:ie(eH).optional()}),tH=y({token:p(),available:p()}),kme=y({balances:ie(tH)}),Rme=y({token:p().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:p().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),Cme=y({payoutBalance:p(),tradingBalance:p()});function Qo(){return p()}var sk=y({walletAddress:p(),handle:p().nullish(),display:p()}),ak=y({leader:sk,status:Qo(),shareBps:I(),bio:p(),minAllocation:p().nullish(),registeredAt:p()}),ck=y({followerCount:I(),allocated:p(),aumEquity:p().nullish()}),uk=y({window:Qo(),pnl:p(),roiPct:p().nullish(),maxDrawdownPct:p().nullish(),winRatePct:p().nullish(),closedTrades:I()}),Ome=y({profile:ak,followSummary:ck,stats:ie(uk)}),rH=y({profile:ak,followSummary:ck,stats:uk}),Mme=y({leaders:ie(rH),nextPageToken:p(),asOf:p()}),Nme=y({created:oe(),status:Qo(),shareBps:I()}),nH=y({walletAddress:p(),display:p(),status:Qo(),allocation:p(),startedAt:p()}),$me=y({followers:ie(nH),nextPageToken:p()}),oH=y({tradingPairId:p(),positionSide:p(),action:Qo(),size:p().nullish(),exitPrice:p().nullish(),entryPrice:p().nullish(),realizedPnl:p().nullish(),netRealizedPnl:p().nullish(),realizedRoe:p().nullish(),closedAt:p()}),zme=y({closedTrades:ie(oH),nextPageToken:p()}),lk=y({tradingPairId:p(),side:p(),size:p(),entryPrice:p(),markPrice:p().nullish(),unrealizedPnl:p().nullish(),leverage:p().nullish(),marginMode:p()}),Lme=y({positions:ie(lk)}),dk=y({followId:p(),leader:sk,status:Qo(),marginModePolicy:Qo(),sizingMode:Qo(),sizingParam:p().nullish(),leverageMode:Qo(),fixedLeverage:p().nullish(),allocation:p(),slPct:p().nullish(),copyExisting:oe(),tradingPairIds:ie(p()),consecutiveSkips:I(),copyRiskBucketId:p(),startedAt:p(),stoppedAt:p().nullish(),stopReason:Qo().nullish()}),Bme=y({follows:ie(dk),nextPageToken:p()}),iH=y({tradingPairId:p(),reason:Qo(),requestedQuantity:p(),skippedAt:p()}),Dme=y({follow:dk,recentSkips:ie(iH),copyAccountEquity:p().nullish()}),Fme=y({positions:ie(lk)}),Ume=y({followId:p(),copyRiskBucketId:p(),created:oe()}),jme=y({estimatedMargin:p(),estimatedFee:p(),copiedPositions:I(),skippedPositions:I(),truncated:oe()}),qme=y({followId:p()}),sH=y({followId:p(),closeOrdersPlaced:I(),positionsNotClosed:I()}),aH=y({followId:p(),reason:p()}),Hme=y({follows:ie(sH),stoppingFollowIds:ie(p()),failedFollows:ie(aH)}),Gme=y({followId:p(),tradingPairId:p(),riskBucketId:p(),positionId:p(),positionMargin:p(),copyAccountAvailable:p()});var Vme=y({tradingPairId:p().trim().min(1,"Trading pair ID is required and cannot be empty"),side:z(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:p().trim().min(1,"Price is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Price must be a valid number").refine((e)=>Number(e)>0,"Price must be greater than 0"),quantity:p().trim().min(1,"Quantity is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Quantity must be a valid number").refine((e)=>Number(e)>0,"Quantity must be greater than 0"),orderType:z(["LIMIT","MARKET"]).optional(),slippageToleranceBps:I().int().min(0,"Slippage tolerance must be between 0 and 1000 bps").max(1000,"Slippage tolerance must be between 0 and 1000 bps").optional()}).superRefine((e,t)=>{if(e.slippageToleranceBps!==void 0&&e.orderType!=="MARKET")t.addIssue({code:wa.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),Zme=y({applicationName:p().nullable().optional(),applicationTakerFee:p(),applicationTakerFeeBps:I(),buyOrderLockAmount:p().nullable().optional(),makerTotalReceipt:p(),monacoMakerRebate:p(),monacoMakerRebateBps:I(),monacoMakerRebateBpsExact:p(),monacoTakerFee:p(),monacoTakerFeeBps:I(),monacoTakerFeeBpsExact:p(),notional:p(),takerTotalPayment:p(),totalTakerFees:p(),maxQuantity:p().nullable(),maxQuantityRaw:p().nullable(),slippageToleranceBps:I().nullable()}),Wme=y({tradingPairId:p().trim().min(1,"Trading pair ID is required and cannot be empty")}),cH=y({tierLevel:I().int(),minVolumeThreshold:p(),makerFeeBps:p(),takerFeeBps:p()}),Kme=y({currentTierLevel:I().int(),weightedVolume14d:p(),spotVolume14d:p(),perpVolume14d:p(),volumeToNextTier:p().nullable().optional(),nextTierLevel:I().int().nullable().optional(),feeSchedule:ie(cH)});var uH=y({token:p(),available:p()}),Yme=y({balances:ie(uH)}),Jme=y({code:p(),createdAt:p(),customCode:p(),isCustom:oe(),display:p()}),lH=z(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),Qme=y({available:oe(),reason:Ff((e)=>e===""||e===null?void 0:e,lH.optional())}),Xme=y({code:p().trim().min(1,"code is required").regex(/^[A-Za-z][A-Za-z0-9_]{4,19}$/,"code must start with a letter and be 5–20 chars of letters, digits, or underscores")}),ehe=y({code:p()}),the=y({token:p().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:p().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),rhe=y({rewardsBalance:p(),tradingBalance:p()}),dH=y({source:p(),sourceDisplay:p(),level:I(),amount:p(),token:p(),rateApplied:p(),createdAt:p()}),pH=y({wallet:p(),display:p(),level:I()}),nhe=y({referrer:p(),referrerDisplay:p(),totalEarned:p(),rewards:ie(dH),upline:ie(pH)}),fH=y({source:p(),sourceDisplay:p(),level:I(),totalEarned:p(),token:p()}),mH=y({wallet:p(),display:p(),referredAt:p(),totalEarned:p()}),hH=y({level:I(),earned:p()}),gH=y({totalEarned:p(),level1Earned:p(),level2Earned:p(),level3Earned:p(),byLevel:ie(hH)}),ohe=y({pageSize:I().int().min(1).max(500).optional(),pageToken:p().optional()}),ihe=y({earningsBySource:ie(fH),directReferees:ie(mH),summary:gH,nextPageToken:p()}),she=y({parent:p().optional(),pageSize:I().int().min(1).max(200).optional(),pageToken:p().optional()}),yH=y({wallet:p(),display:p(),level:I(),parent:p(),referredAt:p(),refereeCount:I(),totalEarned:p()}),ahe=y({parent:p(),parentLevel:I(),nodes:ie(yH),nextPageToken:p()});var Rp=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var Cp=z(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),Ph=z(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),ww=z(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),Ah=z(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),bH=z(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),pk=z(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),zu=z(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"],{message:'Self-trade prevention mode must be "CANCEL_MAKER", "CANCEL_TAKER", "CANCEL_BOTH", or "SKIP"'}),Op=z(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),Ze=p().trim().min(1,"Value cannot be empty").regex(/^\d+(\.\d+)?$/,"Value must be a positive decimal number (e.g., '1.5', '100')").refine((e)=>Number.parseFloat(e)>0,{message:"Value must be greater than 0"}),xe=U5({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),Qs=wl.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),xH=I().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),Mp=I().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),Np=I().int().min(0,"Slippage tolerance must be at least 0 bps").max(1000,"Slippage tolerance cannot exceed 1000 bps"),che=I().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),yw=y({triggerPrice:Ze,orderType:Op,limitPrice:Ze.optional(),quantity:Ze.optional(),closePosition:oe().optional(),timeInForce:pk.optional(),slippageToleranceBps:Mp.optional(),expiresAt:Qs.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT parent TP/SL",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET parent TP/SL",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),uhe=I().int("trailBps must be an integer number of basis points").min(10,"trailBps must be at least 10 bps").max(2000,"trailBps cannot exceed 2000 bps"),fk=y({trailBps:uhe,activationPrice:Ze.optional(),quantity:Ze.optional(),closePosition:oe().optional(),slippageToleranceBps:Mp.optional(),expiresAt:Qs.optional()}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),wH=fk,bw=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0||e?.trailingStop!==void 0,mk=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),hk=p().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/,"idempotencyKey must contain only letters, digits, or . _ : -"),mBt=y({tradingPairId:xe,side:Cp,quantity:Ze,price:Ze,options:y({idempotencyKey:hk.optional(),tradingMode:Ph.optional(),useMasterBalance:oe().optional(),expirationDate:Qs.optional(),timeInForce:bH.optional(),marginAccountId:xe.optional(),marginMode:ww.optional(),riskBucketId:xe.optional(),riskBucketCollateral:Ze.optional(),strategyKey:p().min(1).max(128).optional(),positionSide:Ah.optional(),leverage:Ze.optional(),reduceOnly:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:zu.optional(),takeProfit:yw.optional(),stopLoss:yw.optional(),trailingStop:wH.optional()}).optional()}).refine((e)=>mk(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!bw(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss/trailingStop are only supported for MARGIN orders",path:["options"]}).refine((e)=>!bw(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss/trailingStop cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}).refine((e)=>e.options?.postOnly!==!0||e.options?.timeInForce===void 0||e.options.timeInForce!=="IOC"&&e.options.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["options","timeInForce"]}),hBt=y({tradingPairId:xe,side:Cp,quantity:Ze,options:y({idempotencyKey:hk.optional(),tradingMode:Ph.optional(),slippageTolerance:xH,marginAccountId:xe.optional(),marginMode:ww.optional(),riskBucketId:xe.optional(),riskBucketCollateral:Ze.optional(),strategyKey:p().min(1).max(128).optional(),positionSide:Ah.optional(),leverage:Ze.optional(),reduceOnly:oe().optional(),selfTradePreventionMode:zu.optional(),takeProfit:yw.optional(),stopLoss:yw.optional(),trailingStop:wH.optional()}).optional()}).refine((e)=>mk(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!bw(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss/trailingStop are only supported for MARGIN orders",path:["options"]}).refine((e)=>!bw(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss/trailingStop cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),gBt=y({orderId:xe,remainingQuantityTarget:Ze.optional()}),yBt=y({orderId:xe,newOrder:y({price:Ze.optional(),quantity:Ze.optional(),useMasterBalance:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:zu.optional()})}),bBt=y({page:Qe().optional(),status:pt([z(Rp),ie(z(Rp)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:xe.optional(),tradingMode:Ph.optional(),marginAccountId:xe.optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),xBt=z(["STOP_LOSS","TAKE_PROFIT","TRAILING_STOP"],{message:'conditionType must be "STOP_LOSS", "TAKE_PROFIT", or "TRAILING_STOP"'}),wBt=z(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),lhe=z(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),SH=z(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),SBt=y({conditionalOrderId:xe}),_Bt=y({page:Qe().optional(),marginAccountId:xe.optional(),tradingPairId:xe.optional(),state:lhe.optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),dhe=z(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),phe=pt([I().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),p().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),fhe=2592000000,TBt=y({tradingPairId:xe,side:Cp,quantity:Ze,options:y({durationSeconds:phe.optional(),startTime:Qs.optional(),endTime:Qs.optional(),limitPrice:Ze.optional(),slippageToleranceBps:che.optional(),randomize:oe().optional(),executionStyle:z(["TAKER","PASSIVE"]).optional(),reduceOnly:oe().optional(),tradingMode:Ph.optional(),marginAccountId:xe.optional(),riskBucketId:xe.optional(),marginMode:ww.optional(),leverage:Ze.optional(),strategyKey:p().min(1).max(128).optional(),useMasterBalance:oe().optional(),clientTwapId:p().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional(),triggerPrice:Ze.optional(),triggerDirection:z(["ABOVE","BELOW"]).optional(),conditionalExpiry:Qs.optional()})}).refine((e)=>e.options.durationSeconds!==void 0!==(e.options.endTime!==void 0),{message:"Exactly one of durationSeconds or endTime must be set",path:["options","durationSeconds"]}).refine((e)=>e.options.startTime===void 0||e.options.endTime!==void 0,{message:"startTime is only valid together with endTime",path:["options","startTime"]}).refine((e)=>e.options.marginMode===void 0||e.options.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode==="MARGIN",{message:"riskBucketId is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}).refine((e)=>e.options.triggerPrice!==void 0===(e.options.triggerDirection!==void 0),{message:"triggerPrice and triggerDirection are both-or-neither",path:["options","triggerDirection"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.durationSeconds!==void 0,{message:"conditional TWAP (triggerPrice) requires durationSeconds — the window floats from the trigger instant",path:["options","durationSeconds"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.startTime===void 0&&e.options.endTime===void 0,{message:"triggerPrice is incompatible with startTime/endTime",path:["options","triggerPrice"]}).refine((e)=>e.options.conditionalExpiry===void 0||e.options.triggerPrice!==void 0,{message:"conditionalExpiry is only valid together with triggerPrice",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r>Date.now()},{message:"conditionalExpiry must be in the future",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r-Date.now()<=fhe},{message:"conditionalExpiry cannot be more than 30 days after creation (the maximum window)",path:["options","conditionalExpiry"]}),vBt=y({twapOrderId:xe}),EBt=y({page:Qe().optional(),state:dhe.optional(),tradingPairId:xe.optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),PBt=y({page:Qe().optional(),twapOrderId:xe,orderBy:z(["ASC","DESC"]).optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),mhe=y({tradingPairId:xe,orderType:Op,side:Cp,price:Ze.optional(),quantity:Ze,idempotencyKey:hk.optional(),tradingMode:Ph.optional(),slippageTolerance:xH,useMasterBalance:oe().optional(),expirationDate:Qs.optional(),timeInForce:bH.optional(),marginAccountId:xe.optional(),marginMode:ww.optional(),riskBucketId:xe.optional(),riskBucketCollateral:Ze.optional(),strategyKey:p().min(1).max(128).optional(),positionSide:Ah.optional(),leverage:Ze.optional(),reduceOnly:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:zu.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).refine((e)=>e.orderType!=="MARKET"||e.postOnly!==!0,{message:"postOnly must not be provided for MARKET orders",path:["postOnly"]}).refine((e)=>e.postOnly!==!0||e.timeInForce===void 0||e.timeInForce!=="IOC"&&e.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["postOnly"]}).refine((e)=>e.riskBucketCollateral===void 0||e.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode!=="CROSS"||e.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine((e)=>e.marginMode!=="CROSS"||e.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine((e)=>e.riskBucketCollateral===void 0||e.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.riskBucketCollateral===void 0||e.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine((e)=>mk(e.side,e.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["positionSide"]}).refine((e)=>e.tradingMode!=="MARGIN"||e.reduceOnly===!0||e.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["leverage"]}),xw=100,ABt=y({orders:ie(mhe).min(1,"At least one order is required").max(xw,`At most ${xw} orders per batch request`)}),hhe=y({orderId:xe,price:Ze.optional(),quantity:Ze.optional(),useMasterBalance:oe().optional(),postOnly:oe().optional(),selfTradePreventionMode:zu.optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),IBt=y({orders:ie(hhe).min(1,"At least one order is required").max(xw,`At most ${xw} orders per batch request`)});var Sw=y({clientId:p().trim().min(1,"Client ID is required"),page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),OBt=Sw.extend({status:p().trim().min(1,"Status cannot be empty").optional(),userId:xe.optional(),tradingPairId:xe.optional(),side:p().trim().min(1,"Side cannot be empty").optional(),orderType:p().trim().min(1,"Order type cannot be empty").optional()}),MBt=Sw.extend({isActive:oe().optional(),accountType:p().trim().min(1,"Account type cannot be empty").optional(),address:p().trim().min(1,"Address filter cannot be empty").optional()}),NBt=Sw.extend({userId:xe.optional(),transactionType:p().trim().min(1,"Transaction type cannot be empty").optional(),entryType:p().trim().min(1,"Entry type cannot be empty").optional(),assetId:xe.optional()}),$Bt=Sw.extend({userId:xe.optional(),assetId:xe.optional()});var _H=p().trim().min(1,"leader handle is required"),ghe=p().trim().regex(/^\d+(\.\d+)?$/,"slPct must be a decimal fraction (e.g. '0.25')").refine((e)=>{let t=Number.parseFloat(e);return t>0&&t<=1},"slPct must be greater than 0 and at most 1");function _w(e){return{pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(e,`Page size cannot exceed ${e}`).optional(),pageToken:p().optional()}}var FBt=y({shareBps:I().int("shareBps must be an integer").min(0,"shareBps cannot be negative").max(1e4,"shareBps cannot exceed 10000").optional(),bio:p().refine((e)=>new TextEncoder().encode(e).length<=2000,"bio cannot exceed 2,000 bytes").optional(),status:z(["ACTIVE","PAUSED"]).optional(),minAllocation:Ze.optional()}).strict(),UBt=y({followId:xe.optional(),leader:_H.optional(),marginModePolicy:z(["FOLLOW","CROSS","ISOLATED"]).optional(),sizingMode:z(["PROPORTIONAL","FIXED_MARGIN"]).optional(),sizingParam:Ze.optional(),leverageMode:z(["FOLLOW","FIXED"]).optional(),fixedLeverage:Ze.optional(),allocation:Ze,slPct:ghe.optional(),tradingPairIds:ie(xe).max(256,"at most 256 markets can be copied").optional(),copyExisting:oe().optional()}).strict().superRefine((e,t)=>{if(e.followId===void 0&&e.leader===void 0)t.addIssue({code:"custom",message:"leader is required when creating a follow",path:["leader"]});if(e.followId!==void 0&&e.copyExisting===!0)t.addIssue({code:"custom",message:"copyExisting applies only when creating a follow",path:["copyExisting"]});TH(e,t)});function TH(e,t){let r=e.sizingMode==="FIXED_MARGIN";if(r&&e.sizingParam===void 0)t.addIssue({code:"custom",message:"sizingParam is required for FIXED_MARGIN sizing",path:["sizingParam"]});if(!r&&e.sizingParam!==void 0)t.addIssue({code:"custom",message:"sizingParam is only accepted with FIXED_MARGIN sizing",path:["sizingParam"]});let n=e.leverageMode==="FIXED";if(n&&e.fixedLeverage===void 0)t.addIssue({code:"custom",message:"fixedLeverage is required for FIXED leverage",path:["fixedLeverage"]});if(!n&&e.fixedLeverage!==void 0)t.addIssue({code:"custom",message:"fixedLeverage is only accepted with FIXED leverage",path:["fixedLeverage"]})}var jBt=y({leader:_H,marginModePolicy:z(["FOLLOW","CROSS","ISOLATED"]).optional(),sizingMode:z(["PROPORTIONAL","FIXED_MARGIN"]).optional(),sizingParam:Ze.optional(),leverageMode:z(["FOLLOW","FIXED"]).optional(),fixedLeverage:Ze.optional(),allocation:Ze,tradingPairIds:ie(xe).max(256,"at most 256 markets can be copied").optional()}).strict().superRefine((e,t)=>TH(e,t)),qBt=y({followId:xe,tradingPairId:xe,amount:Ze}).strict(),HBt=y({sort:z(["roi","pnl","followers","allocated","aum","win_rate"]).optional(),window:z(["7d","30d","90d","all"]).optional(),..._w(100)}).strict(),GBt=y(_w(100)).strict(),VBt=y(_w(1000)).strict(),ZBt=y(_w(1000)).strict();var YBt=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});var gk=y({page:Qe().optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),e8t=gk.extend({state:p().trim().min(1,"State cannot be empty").optional(),tradingPairId:xe.optional()}),t8t=y({marginAccountId:xe,tradingPairId:xe.optional()}),r8t=y({tradingPairId:xe.optional()}).optional(),n8t=y({asset:p().trim().min(1,"Asset cannot be empty").optional()}).optional(),yhe=y({asset:p().trim().min(1,"Asset cannot be empty"),amount:Ze,tradingPairId:xe.optional(),strategyKey:p().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:z(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),Tw=y({asset:p().trim().min(1,"Asset cannot be empty"),amount:Ze}),bhe=y({tradingPairId:xe,strategyKey:p().trim().min(1,"Strategy key cannot be empty").optional()}),EH=bhe.extend({marginMode:Ae("ISOLATED").optional(),marginAccountId:xe.optional(),selectedTradingPairIds:Qe().optional(),applyToPositionMargin:oe().optional()}),xhe=y({marginMode:Ae("CROSS"),marginAccountId:xe.optional(),selectedTradingPairIds:Qe().optional(),strategyKey:Qe().optional()}),whe=y({marginMode:Ae("CROSS"),marginAccountId:xe.optional(),selectedTradingPairIds:Qe().optional(),strategyKey:Qe().optional(),tradingPairId:Qe().optional()}),o8t=y({marginAccountId:xe,request:yhe}),i8t=y({request:Tw}),She=y({marginMode:z(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Nt().optional()}).loose().superRefine((e,t)=>{if(e.selectedTradingPairIds===void 0)return;t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:e.marginMode==="CROSS"?"selectedTradingPairIds is not accepted on a CROSS transfer: cross scope is derived from trading, so a funding call has nothing to declare":"selectedTradingPairIds is not supported for ISOLATED risk buckets"})}),s8t=y({request:She.pipe(pt([Tw.merge(EH).strict(),Tw.merge(whe).strict()]))}),a8t=y({request:Tw}),c8t=gk.extend({marginAccountId:xe,movementType:p().trim().min(1,"Movement type cannot be empty").optional()}),u8t=gk.extend({movementType:p().trim().min(1,"Movement type cannot be empty").optional()}).optional(),yk=y({tradingPairId:xe,side:Cp,positionSide:Ah.optional(),orderType:Op,price:Ze.optional(),quantity:Ze,leverage:Ze.optional(),reduceOnly:oe().optional(),slippageToleranceBps:Np.optional()}),bk=(e,t)=>{if(e.orderType!=="MARKET"&&e.slippageToleranceBps!==void 0)t.addIssue({code:wa.custom,message:"slippageToleranceBps is only supported for MARKET orders",path:["slippageToleranceBps"]});if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:wa.custom,message:"positionSide must match side when provided (BUY=LONG, SELL=SHORT)",path:["positionSide"]})}if(e.reduceOnly!==!0&&e.leverage===void 0)t.addIssue({code:wa.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},PH=yk.strict().superRefine(bk),_he=yk.merge(EH).strict().superRefine(bk),The=yk.merge(xhe).strict().superRefine(bk),vhe=y({marginMode:z(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Nt().optional()}).loose().superRefine((e,t)=>{if(e.selectedTradingPairIds===void 0)return;t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:e.marginMode==="CROSS"?"selectedTradingPairIds is not accepted on a CROSS preview: cross scope is derived from trading, so a preview has nothing to declare":"selectedTradingPairIds is not supported for ISOLATED risk buckets"})}),Ehe=vhe.pipe(pt([_he,The])),l8t=y({marginAccountId:xe,request:PH}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),d8t=y({request:PH}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),p8t=y({request:Ehe}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),f8t=y({request:y({subaccountKey:p().trim().min(1,"subaccountKey is required").max(64,"subaccountKey must be at most 64 characters").regex(/^[A-Za-z0-9_.:-]+$/,"subaccountKey may contain only letters, digits, '_', '-', '.' and ':'").refine((e)=>!e.toLowerCase().startsWith("copy:"),"sub-account keys starting with copy: are reserved").refine((e)=>e!=="default","default names the default margin account"),label:p().optional()}).strict()}),m8t=y({marginAccountId:xe}),h8t=y({marginAccountId:xe,amount:Ze}),g8t=y({marginAccountId:xe}),vH=pt([y({wallet:Ae(!0)}).strict(),y({marginAccountId:xe,riskBucketId:xe.optional()}).strict()]),y8t=y({request:y({asset:p().trim().min(1,"Asset is required"),amount:Ze,from:vH,to:vH}).strict()});var AH=z(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),Phe=31536000000,Ahe=946684800000,vw=I().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(Ahe,{message:"Timestamp must be at least Jan 1, 2000 (946684800000 ms). Did you pass seconds instead of milliseconds?"}).max(Number.MAX_SAFE_INTEGER,{message:"Timestamp must not exceed JavaScript's maximum safe integer"}).refine((e)=>e<=Date.now()+Phe,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),S8t=y({tradingPairId:xe,interval:AH,startTime:vw,endTime:vw}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),_8t=p().min(1,"Trading pair symbol cannot be empty").regex(/^[A-Za-z0-9]{1,10}\/[A-Za-z0-9]{1,10}$/,{message:'Trading pair symbol must be in format "BASE/QUOTE" (e.g., "BTC/USDT", "ETH/USD")'}),Ihe=I().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),T8t=y({tradingPairId:xe,interval:AH,startTime:vw.optional(),endTime:vw.optional(),limit:Ihe,priceType:z(["trade","mark"]).optional()}).refine((e)=>{if(e.startTime!==void 0&&e.endTime!==void 0)return e.startTime<e.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var v8t=y({tradingPairId:xe}),E8t=y({query:p().min(1,"Search query cannot be empty").optional(),pageSize:I().int().min(1).max(100).optional(),page:I().int().min(1).optional()}),P8t=y({tradingPairId:xe}),A8t=y({page:Qe().optional(),startTime:p().optional(),endTime:p().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),orderBy:z(["ASC","DESC"],{message:'orderBy must be "ASC" or "DESC"'}).optional()});var I8t=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});var kH=y({page:Qe().optional(),pageSize:I().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),khe=z(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),Rhe=z(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),xk=y({positionId:xe}),O8t=kH.extend({marginAccountId:xe.optional(),tradingPairId:xe.optional(),status:khe.optional()});var M8t=xk.extend({request:y({closeType:Rhe,limitPrice:Ze.optional(),slippageToleranceBps:Mp.optional(),quantity:Ze.optional()})}).refine((e)=>e.request.closeType==="MARKET"||e.request.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["request","limitPrice"]}).refine((e)=>e.request.closeType!=="MARKET"||e.request.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["request","limitPrice"]}),N8t=y({tradingPairId:xe.optional(),tradingPairIds:ie(xe).min(1,{message:"tradingPairIds must list at least one trading pair; omit it to close every pair"}).max(256,{message:"tradingPairIds accepts at most 256 trading pairs"}).optional(),side:SH.optional(),slippageToleranceBps:Mp.optional()}).strict().refine((e)=>e.tradingPairId===void 0||e.tradingPairIds===void 0,{message:"Pass tradingPairId or tradingPairIds, not both",path:["tradingPairIds"]});var IH=y({triggerPrice:Ze,orderType:Op,limitPrice:Ze.optional(),quantity:Ze.optional(),closePosition:oe().optional(),timeInForce:pk.optional(),slippageToleranceBps:Mp.optional(),expiresAt:Qs.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT TP/SL legs",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET TP/SL legs",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),$8t=xk.extend({request:y({takeProfit:IH.optional(),stopLoss:IH.optional(),trailingStop:fk.optional(),oco:oe().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0||e.trailingStop!==void 0,{message:"At least one of takeProfit, stopLoss, or trailingStop is required"}).refine((e)=>e.oco!==!0||e.takeProfit!==void 0&&e.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),z8t=kH.extend({positionId:xe.optional(),marginAccountId:xe.optional(),tradingPairId:xe.optional(),reductionOnly:oe().optional()}),Che=z(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),L8t=xk.extend({params:y({interval:Che,startTime:I().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:I().int().min(0,"endTime must be a non-negative millisecond timestamp").optional()}).refine((e)=>e.startTime===void 0||e.endTime===void 0||e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["startTime"]})});var Ohe=z(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),Mhe=z(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),U8t=y({mode:zu}),j8t=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),orderBy:z(["ASC","DESC"]).optional(),entryType:Ohe.optional(),transactionType:Mhe.optional(),assetId:xe.optional()}),q8t=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),tradingPairId:xe.optional(),pageToken:p().optional()}),H8t=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()}),G8t=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional(),tradingPairId:xe.optional(),positionId:xe.optional(),marginAccountId:xe.optional()});var K8t=p().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),wk=pt([p().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),q5().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),Y8t=y({assetId:xe,amount:wk,autoWait:oe().optional()}),J8t=y({assetId:xe,amount:wk,autoWait:oe().optional(),target:z(["spot","margin"]).optional(),options:y({asErc20:oe().optional()}).optional()}),Q8t=y({assetId:xe,amount:wk,destination:p().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:oe().optional(),source:z(["spot","margin"]).optional()}),X8t=y({assetId:xe}),e3t=y({page:Qe().optional(),pageSize:I().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:p().optional()});function RH(e){e.registerTool("simulate_parent_margin_order_risk",{description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),side:z(["BUY","SELL"]).describe("Order side (authoritative: BUY=LONG, SELL=SHORT)"),orderType:z(["LIMIT","MARKET"]).describe("Order type"),quantity:p().describe("Order quantity as a decimal string"),price:p().optional().describe("Limit price as a decimal string — required for LIMIT"),leverage:p().optional().describe("Leverage as a decimal string — required unless reduceOnly is true"),reduceOnly:oe().optional().describe("Whether the order can only reduce exposure"),slippageToleranceBps:Np.optional().describe("MARKET only: slippage tolerance in bps (0..1000), tightening the previewed walk to the band placement will use; the response's expectedMatchResult (the engine's simulated fill, in the same shape as a placement's matchResult) and estimatedFee price under it")}).refine((t)=>t.orderType!=="LIMIT"||t.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["price"]}).refine((t)=>t.reduceOnly===!0||t.leverage!==void 0,{message:"leverage is required for normal (non-reduce-only) margin orders",path:["leverage"]}).refine((t)=>t.orderType==="MARKET"||t.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only supported for MARKET orders",path:["slippageToleranceBps"]})},async({tradingPairId:t,side:r,orderType:n,quantity:o,price:i,leverage:s,reduceOnly:a,slippageToleranceBps:c})=>{let d=await(await H()).marginAccounts.simulateParentMarginOrderRisk({tradingPairId:t,side:r,orderType:n,quantity:o,price:i,leverage:s,reduceOnly:a,slippageToleranceBps:c});return C(d)})}function CH(e){e.registerTool("simulate_risk_bucket_order_risk",{description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation). A CROSS preview names no pairs: cross scope is derived from trading (a pair joins the cross risk bucket when a cross order on it succeeds and, once its positions close, stays listed until a later successful cross order on another pair reconciles the bucket), and the response's selectedTradingPairIds reports the derived scope the preview ran against. Unknown input keys are rejected.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),side:z(["BUY","SELL"]).describe("Order side (authoritative: BUY=LONG, SELL=SHORT)"),positionSide:z(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),orderType:z(["LIMIT","MARKET"]).describe("Order type"),quantity:p().describe("Order quantity as a decimal string"),price:p().optional().describe("Limit price as a decimal string — required for LIMIT"),leverage:p().optional().describe("Leverage as a decimal string — required unless reduceOnly is true"),reduceOnly:oe().optional().describe("Whether the order can only reduce exposure"),slippageToleranceBps:Np.optional().describe("MARKET only: slippage tolerance in bps (0..1000), tightening the previewed walk to the band placement will use; the response's expectedMatchResult (the engine's simulated fill, in the same shape as a placement's matchResult) and estimatedFee price under it"),marginMode:z(["ISOLATED","CROSS"]).optional().describe("Risk bucket margin mode (default ISOLATED)"),strategyKey:p().optional().describe("Isolated risk bucket strategy key (ISOLATED only)")}).strict().refine((t)=>t.orderType!=="LIMIT"||t.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["price"]}).refine((t)=>t.reduceOnly===!0||t.leverage!==void 0,{message:"leverage is required for normal (non-reduce-only) margin orders",path:["leverage"]}).refine((t)=>t.orderType==="MARKET"||t.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only supported for MARKET orders",path:["slippageToleranceBps"]}).refine((t)=>t.marginMode!=="CROSS"||t.strategyKey===void 0,{message:"strategyKey is not allowed for CROSS risk buckets",path:["strategyKey"]})},async({tradingPairId:t,side:r,positionSide:n,orderType:o,quantity:i,price:s,leverage:a,reduceOnly:c,slippageToleranceBps:l,marginMode:d,strategyKey:f})=>{let h=await H(),g={tradingPairId:t,side:r,positionSide:n,orderType:o,quantity:i,price:s,leverage:a,reduceOnly:c,slippageToleranceBps:l},x=d==="CROSS"?await h.marginAccounts.simulateRiskBucketOrderRisk({...g,marginMode:d}):await h.marginAccounts.simulateRiskBucketOrderRisk({...g,marginMode:d,strategyKey:f});return C(x)})}function OH(e){e.registerTool("transfer_collateral_from_parent_margin_account",{description:"Move collateral out of your parent (cross) margin account back to spot.",inputSchema:y({asset:p().describe("Collateral asset symbol or ID"),amount:p().describe("Amount to transfer as a decimal string")})},async({asset:t,amount:r})=>{let o=await(await H()).marginAccounts.transferCollateralFromParentMarginAccount({asset:t,amount:r});return C(o)})}function MH(e){e.registerTool("transfer_collateral_from_sub_account",{description:"Move collateral from one of your margin sub-accounts back to your default (parent) margin account.",inputSchema:y({marginAccountId:p().describe("The margin sub-account ID (not the default margin account)"),amount:p().describe("Amount to transfer as a decimal string")})},async({marginAccountId:t,amount:r})=>{let o=await(await H()).marginAccounts.transferCollateralFromSubAccount(t,r);return C(o)})}function NH(e){e.registerTool("transfer_collateral_to_parent_margin_account",{description:"Move collateral from spot into your parent (cross) margin account.",inputSchema:y({asset:p().describe("Collateral asset symbol or ID"),amount:p().describe("Amount to transfer as a decimal string")})},async({asset:t,amount:r})=>{let o=await(await H()).marginAccounts.transferCollateralToParentMarginAccount({asset:t,amount:r});return C(o)})}function $H(e){e.registerTool("transfer_collateral_to_risk_bucket",{description:"Allocate collateral into an isolated or cross risk bucket. A cross transfer names no pairs: cross scope is derived from trading (a pair joins the cross bucket when a cross order on it succeeds and leaves when its positions close).",inputSchema:y({asset:p().describe("Collateral asset symbol or ID"),amount:p().describe("Amount to transfer as a decimal string"),marginMode:z(["ISOLATED","CROSS"]).optional().describe("Risk bucket margin mode (default ISOLATED)"),tradingPairId:p().optional().describe("Trading pair UUID (required for ISOLATED; not allowed for CROSS)"),strategyKey:p().optional().describe("Isolated risk bucket strategy key (ISOLATED only)"),applyToPositionMargin:oe().optional().describe("ISOLATED only. Omitted/true (Adjust Margin, the default): commit the amount to the sole open position's stored margin — leverage drops and stays down, initial margin required rises, free collateral is unchanged. false: plain allocation — free collateral rises and the next order can spend it; funding loops targeting free collateral MUST pass false.")}).strict().refine((t)=>t.marginMode==="CROSS"||t.tradingPairId!==void 0,{message:"tradingPairId is required for ISOLATED risk buckets",path:["tradingPairId"]}).refine((t)=>t.marginMode!=="CROSS"||t.tradingPairId===void 0,{message:"tradingPairId is not allowed for CROSS risk buckets",path:["tradingPairId"]}).refine((t)=>t.marginMode!=="CROSS"||t.strategyKey===void 0,{message:"strategyKey is not allowed for CROSS risk buckets",path:["strategyKey"]}).refine((t)=>t.marginMode!=="CROSS"||t.applyToPositionMargin===void 0,{message:"applyToPositionMargin is only allowed for ISOLATED risk buckets",path:["applyToPositionMargin"]})},async({asset:t,amount:r,marginMode:n,tradingPairId:o,strategyKey:i,applyToPositionMargin:s})=>{let a=await H(),c=n==="CROSS"?await a.marginAccounts.transferCollateralToRiskBucket({asset:t,amount:r,marginMode:n}):await a.marginAccounts.transferCollateralToRiskBucket({asset:t,amount:r,marginMode:n,tradingPairId:o??"",strategyKey:i,applyToPositionMargin:s});return C(c)})}function zH(e){e.registerTool("transfer_collateral_to_sub_account",{description:"Move collateral from your default (parent) margin account into one of your margin sub-accounts.",inputSchema:y({marginAccountId:p().describe("The margin sub-account ID (not the default margin account)"),amount:p().describe("Amount to transfer as a decimal string")})},async({marginAccountId:t,amount:r})=>{let o=await(await H()).marginAccounts.transferCollateralToSubAccount(t,r);return C(o)})}function LH(e){Z7(e),K7(e),V7(e),W7(e),RH(e),CH(e),NH(e),OH(e),$H(e),zH(e),MH(e)}function BH(e){e.registerTool("get_candlesticks",{description:"Get OHLCV candlestick data for a trading pair. Useful for charting and price analysis.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),interval:z(["1m","5m","15m","1h","4h","1d"]).describe("Candlestick interval"),startTime:I().optional().describe("Start time as Unix timestamp (seconds)"),endTime:I().optional().describe("End time as Unix timestamp (seconds)"),limit:I().optional().describe("Max number of candlesticks to return")})},async({tradingPairId:t,interval:r,startTime:n,endTime:o,limit:i})=>{let a=await Ge().market.getCandlesticks(t,r,{startTime:n,endTime:o,limit:i});return C(a)})}function DH(e){e.registerTool("get_market_metadata",{description:"Get metadata for a specific trading pair including tick size, min order size, and trading rules.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ge().market.getMarketMetadata(t);return C(n)})}function FH(e){e.registerTool("get_market_stats",{description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets."},async()=>{let r=await Ge().market.getMarketStats();return C(r)})}function UH(e){e.registerTool("get_screener",{description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",inputSchema:y({page:I().optional().describe("Page number (1-based)"),pageSize:I().optional().describe("Items per page"),marketType:z(["SPOT","MARGIN"]).optional().describe("Filter by market type"),isActive:oe().optional().describe("Filter by active status"),category:p().optional().describe("Filter by category (e.g. crypto, equities, commodities)")})},async({page:t,pageSize:r,marketType:n,isActive:o,category:i})=>{let a=await Ge().market.getScreener({page:t,pageSize:r,marketType:n,isActive:o,category:i});return C(a)})}function jH(e){e.registerTool("get_trading_pair_by_symbol",{description:"Look up a specific trading pair by its symbol (e.g. 'BTC/USDC'). Returns the pair's full details including its UUID.",inputSchema:y({symbol:p().describe("Trading pair symbol (e.g. 'BTC/USDC')")})},async({symbol:t})=>{let n=await Ge().market.getTradingPairBySymbol(t);if(!n)return hw(`Trading pair '${t}' not found.`);return C(n)})}function qH(e){e.registerTool("get_trading_pairs",{description:"Get a paginated list of trading pairs available on Monaco. Returns pair IDs, symbols, base/quote tokens, and status.",inputSchema:y({page:I().optional().describe("Page number (starts from 1)"),pageSize:I().optional().describe("Number of items per page (max 100)"),marketType:z(["SPOT","MARGIN"]).optional().describe("Filter by market type"),baseToken:p().optional().describe("Filter by base token"),quoteToken:p().optional().describe("Filter by quote token"),isActive:oe().optional().describe("Filter by active status"),category:p().optional().describe("Filter by category (e.g. crypto, equities, commodities)")})},async(t)=>{let n=await Ge().market.getPaginatedTradingPairs(t);return C(n)})}function HH(e){qH(e),jH(e),BH(e),DH(e),UH(e),FH(e)}function GH(e){e.registerTool("get_orderbook",{description:"Get the current orderbook snapshot for a trading pair. Shows bids, asks, best bid/ask, and volumes.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),depth:I().optional().describe("Number of price levels to return (max 100, default 10)"),tradingMode:z(["SPOT"]).optional().describe("Trading mode (default: SPOT)"),magnitude:I().optional().describe("Price grouping magnitude (e.g. 0.01, 0.1, 1, 10, 100)"),denomination:z(["BASE","QUOTE"]).optional().describe("Quantity denomination: BASE or QUOTE")})},async({tradingPairId:t,depth:r,tradingMode:n,magnitude:o,denomination:i})=>{let a=await Ge().orderbook.getOrderbook(t,{depth:r,tradingMode:n,magnitude:o,denomination:i});return C(a)})}function VH(e){GH(e)}function ZH(e){e.registerTool("get_all_funding_history",{description:"List historical funding-rate records across all perpetual markets. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({startTime:p().optional().describe('Start time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),endTime:p().optional().describe('End time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 50, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page"),orderBy:z(["ASC","DESC"]).optional().describe("Sort order by time")}).strict()},async({startTime:t,endTime:r,pageSize:n,pageToken:o,orderBy:i})=>{let a=await Ge().market.listAllFundingHistory({startTime:t,endTime:r,pageSize:n,pageToken:o,orderBy:i});return C(a)})}function WH(e){e.registerTool("get_funding_history",{description:"List historical funding-rate records for a perpetual market. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),startTime:p().optional().describe('Start time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),endTime:p().optional().describe('End time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 50, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page"),orderBy:z(["ASC","DESC"]).optional().describe("Sort order by time")}).strict()},async({tradingPairId:t,startTime:r,endTime:n,pageSize:o,pageToken:i,orderBy:s})=>{let c=await Ge().market.listFundingHistory(t,{startTime:r,endTime:n,pageSize:o,pageToken:i,orderBy:s});return C(c)})}function KH(e){e.registerTool("get_funding_state",{description:"Get the current funding rate and next funding time for a perpetual market.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ge().market.getFundingState(t);return C(n)})}function YH(e){e.registerTool("get_index_price",{description:"Get the current index (oracle) price for a perpetual market.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ge().market.getIndexPrice(t);return C(n)})}function JH(e){e.registerTool("get_mark_price",{description:"Get the current mark price for a perpetual market.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ge().market.getMarkPrice(t);return C(n)})}function QH(e){e.registerTool("get_open_interest",{description:"Get the current one-sided LONG open interest (each contract counted once) for a perpetual market.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ge().market.getOpenInterest(t);return C(n)})}function XH(e){e.registerTool("get_perp_market_config",{description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",inputSchema:y({tradingPairId:p().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ge().market.getPerpMarketConfig(t);return C(n)})}function eG(e){e.registerTool("get_perp_market_summary",{description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",inputSchema:y({tradingPairId:p().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ge().market.getPerpMarketSummary(t);return C(n)})}function tG(e){XH(e),eG(e),JH(e),YH(e),KH(e),QH(e),WH(e),ZH(e)}function rG(e){e.registerTool("get_portfolio_assets",{description:"Get your per-asset portfolio allocation and balances over a period.",inputSchema:y({period:z(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await H()).portfolio.getAssets({period:t});return C(n)})}function nG(e){e.registerTool("get_portfolio_margin",{description:"Get your portfolio margin overview (collateral, maintenance margin, health)."},async()=>{let r=await(await H()).portfolio.getMargin();return C(r)})}function oG(e){e.registerTool("get_portfolio_performance",{description:"Get your portfolio performance time series over a period.",inputSchema:y({period:z(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await H()).portfolio.getPerformance({period:t});return C(n)})}function iG(e){e.registerTool("get_portfolio_realized_pnl",{description:"Get your realized PnL breakdown over a period.",inputSchema:y({period:z(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await H()).portfolio.getRealizedPnl({period:t});return C(n)})}function sG(e){e.registerTool("get_portfolio_summary",{description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",inputSchema:y({period:z(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await H()).portfolio.getSummary({period:t});return C(n)})}function aG(e){sG(e),oG(e),iG(e),rG(e),nG(e)}function cG(e){e.registerTool("close_position",{description:"Close a perpetual position with a market, limit, or IOC reduce order.",inputSchema:y({positionId:p().describe("Position UUID"),closeType:z(["MARKET","LIMIT","IOC"]).describe("Close order type"),limitPrice:p().optional().describe("Limit price as a decimal string — required for LIMIT and IOC, not allowed for MARKET"),slippageToleranceBps:I().optional().describe("Slippage tolerance in basis points (MARKET/IOC)"),quantity:p().optional().describe("Quantity to close as a decimal string (defaults to full position)")}).refine((t)=>t.closeType==="MARKET"||t.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["limitPrice"]}).refine((t)=>t.closeType!=="MARKET"||t.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["limitPrice"]})},async({positionId:t,closeType:r,limitPrice:n,slippageToleranceBps:o,quantity:i})=>{let a=await(await H()).positions.closePosition(t,{closeType:r,limitPrice:n,slippageToleranceBps:o,quantity:i});return C(a)})}function uG(e){e.registerTool("get_position",{description:"Get details for a specific perpetual position by ID. lifetimeTotalsStatus says whether the lifetime totals (exitPrice, realizedRoe, feesPaid, fundingPaid, cumFees, netRealizedPnl) are served: COMPLETE means they follow their own rules, PENDING means history is still catching up or the row changed while it was being read, so retry in a few seconds, INCOMPLETE means the lifetime totals are not complete now and a quick retry will not change that: a legacy-history gap (or reductions that do not reconcile) is permanent, while a missing or drifted maintained-totals row is repaired by the background reconcile (at startup and daily); every total that is present comes from the maintained totals, which are cross-checked against each other and repaired by the background reconcile (e.g. exitPrice can be present while cumFees is absent). OPEN and LIQUIDATING positions are checked against realized PnL too: an OPEN or LIQUIDATING row whose reductions do not account for it is INCOMPLETE with no cumFees. Never read an absent total as zero.",inputSchema:y({positionId:p().describe("Position UUID")})},async({positionId:t})=>{let n=await(await H()).positions.getPosition(t);return C(n)})}function lG(e){e.registerTool("get_position_history",{description:"List historical (closed/reduced) perpetual position records with optional filters. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({positionId:p().optional().describe("Filter by position UUID"),marginAccountId:p().optional().describe("Filter by margin account UUID"),tradingPairId:p().optional().describe("Filter by trading pair UUID"),pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page"),reductionOnly:oe().optional().describe("Only include reduction events")})},async({positionId:t,marginAccountId:r,tradingPairId:n,pageSize:o,pageToken:i,reductionOnly:s})=>{let c=await(await H()).positions.listPositionHistory({positionId:t,marginAccountId:r,tradingPairId:n,pageSize:o,pageToken:i,reductionOnly:s});return C(c)})}function dG(e){e.registerTool("get_position_pnl_history",{description:"Get the PnL history time series for a perpetual position over an interval.",inputSchema:y({positionId:p().describe("Position UUID"),interval:z(["1m","5m","15m","1h","4h","1d"]).describe("Sampling interval"),startTime:I().int().min(0).optional().describe("Start time as a Unix timestamp in milliseconds"),endTime:I().int().min(0).optional().describe("End time as a Unix timestamp in milliseconds")}).refine((t)=>t.startTime===void 0||t.endTime===void 0||t.startTime<t.endTime,{message:"startTime must be less than endTime",path:["startTime"]})},async({positionId:t,interval:r,startTime:n,endTime:o})=>{let s=await(await H()).positions.getPositionPnlHistory(t,{interval:r,startTime:n,endTime:o});return C(s)})}function pG(e){e.registerTool("get_position_risk",{description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",inputSchema:y({positionId:p().describe("Position UUID")})},async({positionId:t})=>{let n=await(await H()).positions.getPositionRisk(t);return C(n)})}function fG(e){e.registerTool("get_positions",{description:"List your perpetual positions with optional filters (margin account, trading pair, status). Cursor paged; an empty nextPageToken means the end. Each row's lifetimeTotalsStatus says whether the lifetime totals (exitPrice, realizedRoe, feesPaid, fundingPaid, cumFees, netRealizedPnl) are served: COMPLETE means they follow their own rules, PENDING means history is still catching up or the row changed while it was being read, so retry in a few seconds, INCOMPLETE means the lifetime totals are not complete now and a quick retry will not change that: a legacy-history gap (or reductions that do not reconcile) is permanent, while a missing or drifted maintained-totals row is repaired by the background reconcile (at startup and daily); every total that is present comes from the maintained totals, which are cross-checked against each other and repaired by the background reconcile (e.g. exitPrice can be present while cumFees is absent). OPEN and LIQUIDATING positions are checked against realized PnL too: an OPEN or LIQUIDATING row whose reductions do not account for it is INCOMPLETE with no cumFees. Never read an absent total as zero.",inputSchema:y({marginAccountId:p().optional().describe("Filter by margin account UUID"),tradingPairId:p().optional().describe("Filter by trading pair UUID"),status:z(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"]).optional().describe("Filter by position status"),pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")})},async({marginAccountId:t,tradingPairId:r,status:n,pageSize:o,pageToken:i})=>{let a=await(await H()).positions.listPositions({marginAccountId:t,tradingPairId:r,status:n,pageSize:o,pageToken:i});return C(a)})}function mG(e){fG(e),uG(e),pG(e),lG(e),dG(e),cG(e)}function hG(e){e.registerTool("get_balance_by_asset",{description:"Get the authenticated user's balance for a specific asset by its UUID.",inputSchema:y({assetId:p().describe("The asset UUID")})},async({assetId:t})=>{let n=await(await H()).profile.getUserBalanceByAssetId(t);return C(n)})}function gG(e){e.registerTool("get_balances",{description:"Get the authenticated user's token balances. Cursor paged; an empty nextPageToken means the end.",inputSchema:y({pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")})},async({pageSize:t,pageToken:r})=>{let o=await(await H()).profile.getUserBalances({pageSize:t,pageToken:r});return C(o)})}function yG(e){e.registerTool("get_funding_payments",{description:"List your perpetual funding payments with optional filters (trading pair, position, margin account). Cursor paged; an empty nextPageToken means the end.",inputSchema:y({tradingPairId:p().optional().describe("Filter by trading pair UUID"),positionId:p().optional().describe("Filter by position UUID"),marginAccountId:p().optional().describe("Filter by margin account UUID"),pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page")}).strict()},async({tradingPairId:t,positionId:r,marginAccountId:n,pageSize:o,pageToken:i})=>{let a=await(await H()).profile.listFundingPayments({tradingPairId:t,positionId:r,marginAccountId:n,pageSize:o,pageToken:i});return C(a)})}function bG(e){e.registerTool("get_movements",{description:"Get the authenticated user's ledger movements (transaction history). Cursor paged; an empty nextPageToken means the end.",inputSchema:y({pageSize:I().int().min(1).max(1000).optional().describe("Items per page (default 20, max 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit for the first page"),orderBy:z(["ASC","DESC"]).optional().describe("Sort direction for createdAt (default DESC)"),entryType:z(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"]).optional().describe("Filter by entry type (e.g. CREDIT, DEBIT, LOCK, UNLOCK, FEE)"),transactionType:z(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"]).optional().describe("Filter by transaction type (e.g. DEPOSIT, WITHDRAWAL, TRADE, FEE, FUNDING, LIQUIDATION, INTEREST, REWARD)"),assetId:p().uuid().optional().describe("Filter by asset ID (UUID)")})},async({pageSize:t,pageToken:r,orderBy:n,entryType:o,transactionType:i,assetId:s})=>{let c=await(await H()).profile.getPaginatedUserMovements({pageSize:t,pageToken:r,orderBy:n,entryType:o,transactionType:i,assetId:s});return C(c)})}function xG(e){e.registerTool("get_profile",{description:"Get the authenticated user's profile including address, username, account type, and withdrawal status. Use get_balances, get_movements, and get_orders for detailed account data."},async()=>{let r=await(await H()).profile.getProfile();return C(r)})}function wG(e){e.registerTool("get_user_trades",{description:"List your own trade fills with optional filters and cursor pagination.",inputSchema:y({tradingPairId:p().optional().describe("Filter by trading pair UUID"),pageSize:I().optional().describe("Items per page"),pageToken:p().optional().describe("Cursor for the next page")})},async({tradingPairId:t,pageSize:r,pageToken:n})=>{let i=await(await H()).profile.getUserTrades({tradingPairId:t,pageSize:r,pageToken:n});return C(i)})}function SG(e){xG(e),gG(e),hG(e),bG(e),wG(e),yG(e)}function _G(e){e.registerTool("get_pulse",{description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags."},async()=>{let r=await Ge().pulse.getPulse();return C(r)})}function TG(e){_G(e)}var Nhe="https://docs.0xmonaco.com/mcp",$he="SearchMonacoDocs",Ew=null;async function vG(e,t,r){let n=await fetch(Nhe,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...Ew?{"Mcp-Session-Id":Ew}:{}},body:JSON.stringify({jsonrpc:"2.0",id:r,method:e,params:t})});if(!n.ok)throw Error(`Mintlify MCP error: ${n.status}`);let o=n.headers.get("mcp-session-id");if(o)Ew=o;let s=(await n.text()).split(`
152
152
  `).find((a)=>a.startsWith("data: "));if(!s)throw Error("No data in Mintlify MCP response");return JSON.parse(s.slice(6))}async function zhe(){if(Ew)return;await vG("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"monaco-mcp-server",version:x0.version}},0)}async function Lhe(e){return await zhe(),(await vG("tools/call",{name:$he,arguments:{query:e}},1))?.result}function EG(e){e.registerTool("search_docs",{description:"Search the Monaco documentation for information about the protocol, SDK, trading, and development guides.",inputSchema:y({query:p().describe("The search query")})},async({query:t})=>{try{let r=await Lhe(t);if(r?.content&&Array.isArray(r.content))return{content:r.content};return C(r)}catch(r){return hw(`Search failed: ${r instanceof Error?r.message:String(r)}`)}})}function PG(e){EG(e)}function AG(e){e.registerTool("check_trader_code_availability",{description:"Public advisory check of whether a custom TraderCode handle is available. Returns `available` and, when unavailable, a `reason` (one of taken, too_short, too_long, reserved, invalid_char, looks_like_address). Advisory only — the authoritative gate is the atomic claim in set_trader_code, so a positive result is not a reservation.",inputSchema:y({code:p().describe("The custom handle to check for availability.")})},async({code:t})=>{let n=await Ge().tradercodes.checkTraderCodeAvailability(t);return C(n)})}function IG(e){e.registerTool("clear_trader_code",{description:"Clear the authenticated caller's custom TraderCode handle, reverting to the wallet-derived default. The freed handle enters a cooldown before anyone else can claim it. Returns the caller's TraderCode identity after the revert.",inputSchema:y({})},async()=>{let r=await(await H()).tradercodes.clearTraderCode();return C(r)})}function kG(e){e.registerTool("get_my_trader_code",{description:"Return the authenticated caller's TraderCode — their normalized wallet address. Clients render it as `Monaco - <address>`. Never 404s; ensures the backing row so referrals attributed to this wallet link correctly.",inputSchema:y({})},async()=>{let r=await(await H()).tradercodes.getMyTraderCode();return C(r)})}function RG(e){e.registerTool("get_rewards_balance",{description:"Return the authenticated caller's current TraderCodes rewards-bucket balances across all reward tokens. Returns an empty list when no rewards have been earned yet. Use transfer_rewards to move earned rewards into a tradeable balance.",inputSchema:y({})},async()=>{let r=await(await H()).tradercodes.getRewardsBalance();return C(r)})}function CG(e){e.registerTool("get_trader_code_info",{description:"Public lookup of a TraderCode (wallet address or 'Monaco - <address>' form). Returns the resolved normalized code when it belongs to a known wallet, or a 404 error if not found. Use this to validate a referral code before sign-up.",inputSchema:y({code:p().describe("The TraderCode to look up — a wallet address (0x-prefixed) or the 'Monaco - <address>' display form.")})},async({code:t})=>{let n=await Ge().tradercodes.getTraderCodeInfo(t);return C(n)})}function OG(e){e.registerTool("set_trader_code",{description:"Claim or edit the authenticated caller's custom (vanity) TraderCode handle. Stored exactly as entered (case preserved); uniqueness is case-insensitive. Must start with a letter and be 5–20 characters of letters, digits, or underscores. The server is the authoritative gate: 409 if the handle is taken, 422 on validation failure, 429 when the per-hour edit limit is hit, 403 when the feature is disabled.",inputSchema:y({code:p().describe("The custom handle to claim or edit to — letter-first [A-Za-z0-9_], 5–20 characters. Case is preserved.")})},async({code:t})=>{let n=await(await H()).tradercodes.setTraderCode(t);return C(n)})}function MG(e){e.registerTool("transfer_rewards",{description:"Transfer earned TraderCodes rewards from your rewards bucket into your trading balance, making them immediately tradeable. Ledger-only — no on-chain transaction. Fails if the rewards balance is insufficient.",inputSchema:y({token:p().describe("Reward token contract address (0x-prefixed EVM address) to transfer."),amount:p().describe("Amount to transfer in RAW atomic units of the token (positive integer string).")})},async({token:t,amount:r})=>{let o=await(await H()).tradercodes.transferRewards({token:t,amount:r});return C(o)})}function NG(e){CG(e),AG(e)}function $G(e){kG(e),RG(e),MG(e),OG(e),IG(e)}function zG(e){e.registerTool("get_trades",{description:"Get one page of historical trades for a trading pair, sorted by execution time (newest first). Cursor paged: omit pageToken to start, then pass the previous response's nextPageToken until it comes back empty.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),pageSize:I().optional().describe("Max number of records to return (default: 25, max: 1000)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit to start at the most recent trade")}).strict()},async({tradingPairId:t,pageSize:r,pageToken:n})=>{let i=await Ge().trades.getTrades(t,{pageSize:r,pageToken:n});return C(i)})}function LG(e){zG(e)}function BG(e){e.registerTool("batch_cancel_all_orders",{description:"Cancel EVERY one of your open orders in one call. Destructive and unfiltered by default — with no tradingPairId it cancels your entire open-order book across all pairs; pass a tradingPairId to limit it to that pair.",inputSchema:y({tradingPairId:p().optional().describe("Optional trading pair UUID to limit cancellation to")})},async({tradingPairId:t})=>{let n=await(await H()).trading.batchCancelAll(t);return C(n)})}function DG(e){e.registerTool("batch_cancel_orders",{description:"Cancel multiple orders by their IDs in a single request. Non-atomic and best-effort: each order is cancelled independently, so a failed leg does not stop the others. Inspect the per-order results and reconcile (retry or re-check) any that did not cancel.",inputSchema:y({orderIds:ie(p()).describe("Array of order IDs to cancel")})},async({orderIds:t})=>{let n=await(await H()).trading.batchCancel(t);return C(n)})}function FG(e){e.registerTool("batch_close_all_positions",{description:"Close all open perpetual positions with MARKET reduce-only orders ('panic close'), optionally filtered to one trading pair or a set of them, and to one side. Best-effort: each position closes independently and per-position failures are reported in the result.",inputSchema:y({tradingPairId:p().optional().describe("Optional trading pair UUID to limit the close to; cannot be combined with tradingPairIds"),tradingPairIds:ie(p().uuid()).min(1).max(256).optional().describe("Optional trading pair UUIDs (1 to 256) to limit the close to, in one request; omit to close every pair"),side:z(["LONG","SHORT"]).optional().describe("Optional position side to limit the close to"),slippageToleranceBps:I().int().optional().describe("Optional slippage tolerance (basis points) applied to each close")}).strict().refine((t)=>t.tradingPairId===void 0||t.tradingPairIds===void 0,{message:"Pass tradingPairId or tradingPairIds, not both",path:["tradingPairIds"]})},async({tradingPairId:t,tradingPairIds:r,side:n,slippageToleranceBps:o})=>{let s=await(await H()).positions.batchCloseAllPositions({tradingPairId:t,tradingPairIds:r,side:n,slippageToleranceBps:o});return C(s)})}function UG(e){e.registerTool("cancel_order",{description:"Cancel an open order by its ID.",inputSchema:y({orderId:p().describe("The order ID to cancel")})},async({orderId:t})=>{let n=await(await H()).trading.cancelOrder(t);return C(n)})}function jG(e){e.registerTool("get_order",{description:"Get detailed information about a specific order by its ID.",inputSchema:y({orderId:p().describe("The order ID to look up")})},async({orderId:t})=>{let n=await(await H()).trading.getOrder(t);return C(n)})}function qG(e){e.registerTool("get_orders",{description:"Get a cursor-paginated list of orders with optional filters by status and trading pair. Omit pageToken for the newest orders; pass the previous response's nextPageToken to fetch the next page. A response with zero orders and an empty nextPageToken means the walk is exhausted. Responses carry a bounded item count: total and totalPages are exact up to a server ceiling, then reported as the ceiling with totalCapped=true (a lower bound).",inputSchema:y({status:z(Rp).optional().describe("Filter by order status (e.g. SUBMITTED, FILLED, CANCELLED)"),tradingPairId:p().optional().describe("Filter by trading pair UUID"),pageSize:I().optional().describe("Orders per page (default: 10; up to 1000)"),pageToken:p().optional().describe("Pagination cursor from a previous response's nextPageToken. Omit it to start from the newest orders.")})},async({status:t,tradingPairId:r,pageSize:n,pageToken:o})=>{let s=await(await H()).trading.getPaginatedOrders({status:t,tradingPairId:r,pageSize:n,pageToken:o});return C(s)})}function HG(e){e.registerTool("place_limit_order",{description:"Place a limit order on Monaco. With idempotencyKey, retry the same submission safely within 24 hours of acceptance; different order details conflict. Limit orders execute only when the market reaches the specified price. The SDK generates a key if omitted. Calling this tool again without the original key starts a new submission and is not idempotent: do NOT retry an ambiguous outcome with a new key. Supply and retain your own idempotencyKey to recover across tool calls. get_orders/get_order are replica-backed; a missing row does not prove that an order failed. If the original key is unavailable, report the ambiguity.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),side:z(["BUY","SELL"]).describe("Order side"),quantity:p().describe("Order quantity as a decimal string"),price:p().describe("Limit price as a decimal string"),tradingMode:z(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),timeInForce:z(["GTC","IOC","FOK"]).optional().describe("Time in force (default: GTC)"),expirationDate:p().optional().describe("Expiration date for GTC orders (ISO 8601)"),marginAccountId:p().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:z(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:p().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:p().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:p().optional().describe("Optional client strategy key"),positionSide:z(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:p().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:oe().optional().describe("Whether the order can only reduce existing exposure"),postOnly:oe().optional().describe("Maker-only: rejected with a 400 carrying the structured error code 'POST_ONLY_WOULD_CROSS' if this order would cross the book. GTC time in force only; rejected with IOC/FOK."),selfTradePreventionMode:z(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"]).optional().describe("Per-order self-trade-prevention override for matches against your own resting orders. CANCEL_MAKER cancels your resting orders and keeps matching; CANCEL_TAKER cancels this order's remainder at the first self-touch; CANCEL_BOTH does both; SKIP trades around your orders and cancels a remainder that would cross them. Omitted, your wallet default applies, else the platform default CANCEL_MAKER. Echoed back as selfTradePreventionMode on order reads."),idempotencyKey:p().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/).optional().describe("Stable identity for this submission; the SDK generates a key if omitted. Supply and retain a key for recovery across tool calls. Reuse with the same order details to safely retry a lost response within 24 hours of acceptance, including after a fill. Use a fresh key for each new order. Different details conflict; after 24 hours this key may execute again. Separate from clientOrderId."),clientOrderId:p().optional().describe("Client-assigned correlation handle, echoed back on order reads and order WebSocket events. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: it is claimed only while the order rests, and is released on fill/cancel/expiry/rejection, so a marketable order that fills on arrival never takes it. Never resubmit on a lost response without the original idempotencyKey — a resubmission can execute a second time. Reconciling a lost response needs the order WebSocket stream (it carries the handle even for orders that never rested), which is outside MCP — this server exposes no stream tool, and get_orders is replica-backed and can omit an order that did land.")})},async({tradingPairId:t,side:r,quantity:n,price:o,tradingMode:i,timeInForce:s,expirationDate:a,marginAccountId:c,marginMode:l,riskBucketId:d,riskBucketCollateral:f,strategyKey:h,positionSide:g,leverage:x,reduceOnly:w,postOnly:S,selfTradePreventionMode:_,clientOrderId:A,idempotencyKey:T})=>{let E=await(await H()).trading.placeLimitOrder(t,r,n,o,{tradingMode:i,timeInForce:s,expirationDate:a,marginAccountId:c,marginMode:l,riskBucketId:d,riskBucketCollateral:f,strategyKey:h,positionSide:g,leverage:x,reduceOnly:w,postOnly:S,selfTradePreventionMode:_,clientOrderId:A,idempotencyKey:T});return C(E)})}function GG(e){e.registerTool("place_market_order",{description:"Place a market order on Monaco. With idempotencyKey, retry the same submission safely within 24 hours of acceptance; different order details conflict. It executes immediately against resting liquidity, but only inside a mandatory 1,000 bps (10%) server-side protective price band anchored to the mark/last-trade reference price. Fills stop at the edge of the band, so a market order may partially fill and cancel the remainder, be rejected when no liquidity sits inside the band, or be rejected when the market has no trustworthy price anchor. Optional slippageTolerance is merged tighter-wins with this band: it can only TIGHTEN execution, never widen past the mandatory band; omitting it applies the full 1,000 bps band. The SDK generates a key if omitted. Calling this tool again without the original key starts a new submission and is not idempotent: do NOT retry an ambiguous outcome with a new key. Supply and retain your own idempotencyKey to recover across tool calls. get_orders/get_order are replica-backed; a missing row does not prove that an order failed. If the original key is unavailable, report the ambiguity.",inputSchema:y({tradingPairId:p().describe("Trading pair UUID"),side:z(["BUY","SELL"]).describe("Order side"),quantity:p().describe("Order quantity as a decimal string"),tradingMode:z(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),slippageTolerance:I().optional().describe("Tightens the mandatory 1,000 bps band, as a decimal (e.g. 0.01 for 1%; 0 for best price only). Can only tighten, never widen; omit to apply the full band."),marginAccountId:p().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:z(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:p().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:p().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:p().optional().describe("Optional client strategy key"),positionSide:z(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:p().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:oe().optional().describe("Whether the order can only reduce existing exposure"),idempotencyKey:p().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/).optional().describe("Stable identity for this submission; the SDK generates a key if omitted. Supply and retain a key for recovery across tool calls. Reuse with the same order details to safely retry a lost response within 24 hours of acceptance, including after a fill. Use a fresh key for each new order. Different details conflict; after 24 hours this key may execute again. Separate from clientOrderId."),clientOrderId:p().optional().describe("Client-assigned correlation handle, echoed back on order reads and order WebSocket events. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key. A market order never rests, so it never claims the handle and no duplicate-submission guard can fire for it: Without idempotencyKey, NEVER resubmit a market order on a lost response — it can execute again and increase your exposure (or reject, or fill at a different price; you cannot tell which in advance). Reconciling a lost response needs the order WebSocket stream (it carries the handle even for orders that never rested), which is outside MCP — this server exposes no stream tool, and get_orders is replica-backed and can omit an order that did land.")})},async({tradingPairId:t,side:r,quantity:n,tradingMode:o,slippageTolerance:i,marginAccountId:s,marginMode:a,riskBucketId:c,riskBucketCollateral:l,strategyKey:d,positionSide:f,leverage:h,reduceOnly:g,clientOrderId:x,idempotencyKey:w})=>{let _=await(await H()).trading.placeMarketOrder(t,r,n,{tradingMode:o,slippageTolerance:i,marginAccountId:s,marginMode:a,riskBucketId:c,riskBucketCollateral:l,strategyKey:d,positionSide:f,leverage:h,reduceOnly:g,clientOrderId:x,idempotencyKey:w});return C(_)})}function VG(e){e.registerTool("replace_order",{description:"Replace an existing order with new price and/or quantity. The order must be open. "+"Not idempotent, and MCP has no order-stream tool, so an ambiguous outcome (timeout, network error, or a 5xx with no order returned) CANNOT be resolved from inside MCP: do NOT retry. get_orders/get_order are replica-backed and an order rejected before acceptance is never written to them, so a missing row is not evidence the order failed. Check whether the position or balance moved, and otherwise report the ambiguity to the user rather than resubmitting. A retry here cannot double your exposure — replace names the original order id and a second attempt returns ORDER_NOT_FOUND once the first succeeded — but that code does not distinguish a landed replacement from an original that filled or was cancelled, so retrying still reports the wrong state.",inputSchema:y({orderId:p().describe("The order ID to replace"),price:p().optional().describe("New price as a decimal string"),quantity:p().optional().describe("New quantity as a decimal string"),postOnly:oe().optional().describe("Re-states maker-only intent for the replacement (nothing is inherited from the original order): rejected with a 400 carrying the structured error code 'POST_ONLY_WOULD_CROSS' if it would cross the book."),selfTradePreventionMode:z(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"]).optional().describe("Re-states the per-order self-trade-prevention override for the replacement (nothing is inherited from the original order). Omitted, your wallet default applies, else the platform default CANCEL_MAKER."),clientOrderId:p().optional().describe("Client-assigned correlation handle for the replacement order, echoed back on order reads and order WebSocket events. Nothing is inherited from the original order — re-state it here to keep the handle across a requote. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: it is claimed only while the order rests and is released on fill/cancel/expiry/rejection, so it cannot make a lost-response retry safe. Reconciling a lost response needs the order WebSocket stream, which is outside MCP — this server exposes no stream tool.")})},async({orderId:t,price:r,quantity:n,postOnly:o,selfTradePreventionMode:i,clientOrderId:s})=>{let c=await(await H()).trading.replaceOrder(t,{price:r,quantity:n,postOnly:o,selfTradePreventionMode:i,clientOrderId:s});return C(c)})}function ZG(e){HG(e),GG(e),UG(e),DG(e),BG(e),FG(e),VG(e),qG(e),jG(e)}function WG(e){e.registerTool("vault_get_allowance",{description:"Check the current token allowance granted to the Monaco vault for a specific asset.",inputSchema:y({assetId:p().describe("The asset UUID to check allowance for")})},async({assetId:t})=>{let n=await(await H()).vault.getAllowance(t);return C({assetId:t,allowance:n.toString()})})}function KG(e){e.registerTool("vault_approve",{description:"Approve the Monaco vault contract to spend tokens on your behalf. Required before depositing ERC20 tokens.",inputSchema:y({assetId:p().describe("The asset UUID to approve"),amount:p().regex(/^\d+$/,"Must be a non-negative integer string").describe("Max amount to approve as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)")})},async({assetId:t,amount:r})=>{let o=await(await H()).vault.approve(t,BigInt(r));return C({hash:o.hash,status:o.status})})}function YG(e){e.registerTool("vault_deposit",{description:"Deposit tokens into the Monaco vault. Requires prior approval for ERC20 tokens (use vault_approve first). Set target to 'margin' to route the deposit straight into margin collateral instead of the spot wallet.",inputSchema:y({assetId:p().describe("The asset UUID to deposit"),amount:p().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to deposit as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)"),target:z(["spot","margin"]).optional().describe("Destination ledger: 'spot' (default) or 'margin' to route into margin collateral")})},async({assetId:t,amount:r,target:n})=>{let i=await(await H()).vault.deposit(t,BigInt(r),void 0,n);return C({hash:i.hash,status:i.status})})}function JG(e){e.registerTool("get_pending_withdrawals",{description:"List your pending withdrawals still awaiting on-chain root confirmation.",inputSchema:y({pageSize:I().optional().describe("Items per page (1-1000, default 20)"),pageToken:p().optional().describe("Cursor from a previous response's nextPageToken; omit to start. Walk until nextPageToken is empty.")}).strict()},async({pageSize:t,pageToken:r})=>{let o=await(await H()).withdrawals.listPendingWithdrawals({pageSize:t,pageToken:r});return C(o)})}function QG(e){e.registerTool("vault_needs_approval",{description:"Check if approval is needed before depositing a specific amount of tokens.",inputSchema:y({assetId:p().describe("The asset UUID to check"),amount:p().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to check as a raw integer string")})},async({assetId:t,amount:r})=>{let o=await(await H()).vault.needsApproval(t,BigInt(r));return C({assetId:t,amount:r,needs_approval:o})})}function XG(e){e.registerTool("vault_withdraw",{description:"Withdraw tokens from the Monaco vault back to your wallet.",inputSchema:y({assetId:p().describe("The asset UUID to withdraw"),amount:p().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to withdraw as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)")})},async({assetId:t,amount:r})=>{let o=await(await H()).vault.withdraw(t,BigInt(r));return C({withdrawalIndex:o.withdrawalIndex,status:o.status,hash:o.hash})})}function eV(e){KG(e),YG(e),XG(e),WG(e),QG(e),JG(e)}function Bhe(e){let t=e.length-1,r=e[t];if(typeof r!=="function")return e;let n=S7(r);return[...e.slice(0,t),n]}function Dhe(e,t){let[r,...n]=t;if(!r||typeof r!=="object")return t;let o=h4(e);if(!o)return t;let i=r.annotations;return[{...r,annotations:{...o,...i}},...n]}function tV(e,t,r){return new Proxy(e,{get(n,o,i){if(o==="registerTool")return(a,...c)=>{if(!w4(a,t))return;let l=Dhe(a,c);if(r&&x4(a))l=Bhe(l);return n.registerTool(a,...l)};let s=Reflect.get(n,o,i);return typeof s==="function"?s.bind(n):s}})}function rV(e,t){let r={authenticated:t.authenticated,capability:t.capability,allow:t.allow??[],deny:t.deny??[],network:t.network},n=tV(e,r,!1);if(PG(n),HH(n),tG(n),VH(n),LG(n),NG(n),B7(n),TG(n),t.authenticated){let o=tV(e,r,!0);ZG(o),mG(o),SG(o),aG(o),LH(o),G7(o),eV(o),j7(o,{network:t.network}),$G(o),D7(o)}}if(typeof globalThis.crypto?.getRandomValues!=="function")globalThis.crypto=Fhe;if(!globalThis.fetch)globalThis.fetch=cg,globalThis.Headers=fn,globalThis.Request=rs,globalThis.Response=Wr;if(!globalThis.WebSocket)globalThis.WebSocket=ES.default;async function Uhe(){let e=Jc(),t=e.privateKey!==null,r=new wv({name:"monaco-mcp-server",version:x0.version});rV(r,{authenticated:t,network:e.network,capability:e.capability,allow:e.allow,deny:e.deny});let n=new _v;await r.connect(n),console.error(t?`Monaco MCP server running on stdio (network=${e.network}, capability=${e.capability}). Fund-movement and privilege tools require MONACO_CAPABILITY=full or an explicit MONACO_TOOL_ALLOWLIST entry.`:"Monaco MCP server running on stdio (public read-only mode — set MONACO_PRIVATE_KEY, MONACO_CLIENT_ID and MONACO_NETWORK to enable authenticated tools).")}Uhe().catch((e)=>{console.error("Fatal error:",e),process.exit(1)});