@0xmonaco/mcp-server 1.0.40 → 1.0.41

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 (2) hide show
  1. package/dist/bin.js +10 -10
  2. package/package.json +3 -3
package/dist/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as yX}from"node:module";var cX=Object.create;var{getPrototypeOf:uX,defineProperty:MT,getOwnPropertyNames:lX}=Object;var dX=Object.prototype.hasOwnProperty;function pX(e){return this[e]}var fX,mX,rn=(e,t,r)=>{var o=e!=null&&typeof e==="object";if(o){var n=t?fX??=new WeakMap:mX??=new WeakMap,i=n.get(e);if(i)return i}r=e!=null?cX(uX(e)):{};let s=t||!e||!e.__esModule?MT(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of lX(e))if(!dX.call(s,a))MT(s,a,{get:pX.bind(e,a),enumerable:!0})}if(o)n.set(e,s);return s};var oe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var hX=(e)=>e;function gX(e,t){this[e]=hX.bind(null,t)}var Pn=(e,t)=>{for(var r in t)MT(e,r,{get:t[r],enumerable:!0,configurable:!0,set:gX.bind(t,r)})};var J=(e,t)=>()=>(e&&(t=e(e=0)),t);var Lt=yX(import.meta.url);var Zz=oe(function(lb,Vz){(function(e,t){typeof lb==="object"&&typeof Vz<"u"?t(lb):typeof define==="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.WebStreamsPolyfill={}))})(lb,function(e){function t(){return}function r(l){return typeof l==="object"&&l!==null||typeof l==="function"}let o=t;function n(l,g){try{Object.defineProperty(l,"name",{value:g,configurable:!0})}catch(b){}}let i=Promise,s=Promise.prototype.then,a=Promise.reject.bind(i);function c(l){return new i(l)}function u(l){return c((g)=>g(l))}function d(l){return a(l)}function p(l,g,b){return s.call(l,g,b)}function m(l,g,b){p(p(l,g,b),void 0,o)}function h(l,g){m(l,g)}function y(l,g){m(l,void 0,g)}function x(l,g,b){return p(l,g,b)}function S(l){p(l,void 0,o)}let v=(l)=>{if(typeof queueMicrotask==="function")v=queueMicrotask;else{let g=u(void 0);v=(b)=>p(g,b)}return v(l)};function E(l,g,b){if(typeof l!=="function")throw TypeError("Argument is not a function");return Function.prototype.apply.call(l,g,b)}function w(l,g,b){try{return u(E(l,g,b))}catch(I){return d(I)}}let _=16384;class T{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(l){let g=this._back,b=g;if(g._elements.length===_-1)b={_elements:[],_next:void 0};if(g._elements.push(l),b!==g)this._back=b,g._next=b;++this._size}shift(){let l=this._front,g=l,b=this._cursor,I=b+1,A=l._elements,D=A[b];if(I===_)g=l._next,I=0;if(--this._size,this._cursor=I,l!==g)this._front=g;return A[b]=void 0,D}forEach(l){let g=this._cursor,b=this._front,I=b._elements;while(g!==I.length||b._next!==void 0){if(g===I.length){if(b=b._next,I=b._elements,g=0,I.length===0)break}l(I[g]),++g}}peek(){let l=this._front,g=this._cursor;return l._elements[g]}}let P=Symbol("[[AbortSteps]]"),O=Symbol("[[ErrorSteps]]"),z=Symbol("[[CancelSteps]]"),B=Symbol("[[PullSteps]]"),k=Symbol("[[ReleaseSteps]]");function G(l,g){if(l._ownerReadableStream=g,g._reader=l,g._state==="readable")H(l);else if(g._state==="closed")we(l);else fe(l,g._storedError)}function V(l,g){let b=l._ownerReadableStream;return Io(b,g)}function ue(l){let g=l._ownerReadableStream;if(g._state==="readable")C(l,TypeError("Reader was released and can no longer be used to monitor the stream's closedness"));else U(l,TypeError("Reader was released and can no longer be used to monitor the stream's closedness"));g._readableStreamController[k](),g._reader=void 0,l._ownerReadableStream=void 0}function W(l){return TypeError("Cannot "+l+" a stream using a released reader")}function H(l){l._closedPromise=c((g,b)=>{l._closedPromise_resolve=g,l._closedPromise_reject=b})}function fe(l,g){H(l),C(l,g)}function we(l){H(l),N(l)}function C(l,g){if(l._closedPromise_reject===void 0)return;S(l._closedPromise),l._closedPromise_reject(g),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0}function U(l,g){fe(l,g)}function N(l){if(l._closedPromise_resolve===void 0)return;l._closedPromise_resolve(void 0),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0}let Y=Number.isFinite||function(l){return typeof l==="number"&&isFinite(l)},X=Math.trunc||function(l){return l<0?Math.ceil(l):Math.floor(l)};function ce(l){return typeof l==="object"||typeof l==="function"}function Z(l,g){if(l!==void 0&&!ce(l))throw TypeError(`${g} is not an object.`)}function me(l,g){if(typeof l!=="function")throw TypeError(`${g} is not a function.`)}function Me(l){return typeof l==="object"&&l!==null||typeof l==="function"}function Be(l,g){if(!Me(l))throw TypeError(`${g} is not an object.`)}function Le(l,g,b){if(l===void 0)throw TypeError(`Parameter ${g} is required in '${b}'.`)}function Ut(l,g,b){if(l===void 0)throw TypeError(`${g} is required in '${b}'.`)}function bt(l){return Number(l)}function cr(l){return l===0?0:l}function Zr(l){return cr(X(l))}function tr(l,g){let I=Number.MAX_SAFE_INTEGER,A=Number(l);if(A=cr(A),!Y(A))throw TypeError(`${g} is not a finite number`);if(A=Zr(A),A<0||A>I)throw TypeError(`${g} is outside the accepted range of 0 to ${I}, inclusive`);if(!Y(A)||A===0)return 0;return A}function En(l,g){if(!Xs(l))throw TypeError(`${g} is not a ReadableStream.`)}function Wr(l){return new To(l)}function Ws(l,g){l._reader._readRequests.push(g)}function Cf(l,g,b){let A=l._reader._readRequests.shift();if(b)A._closeSteps();else A._chunkSteps(g)}function sl(l){return l._reader._readRequests.length}function Dy(l){let g=l._reader;if(g===void 0)return!1;if(!Ks(g))return!1;return!0}class To{constructor(l){if(Le(l,1,"ReadableStreamDefaultReader"),En(l,"First parameter"),ea(l))throw TypeError("This stream has already been locked for exclusive reading by another reader");G(this,l),this._readRequests=new T}get closed(){if(!Ks(this))return d(Uy("closed"));return this._closedPromise}cancel(l=void 0){if(!Ks(this))return d(Uy("cancel"));if(this._ownerReadableStream===void 0)return d(W("cancel"));return V(this,l)}read(){if(!Ks(this))return d(Uy("read"));if(this._ownerReadableStream===void 0)return d(W("read from"));let l,g,b=c((A,D)=>{l=A,g=D});return zf(this,{_chunkSteps:(A)=>l({value:A,done:!1}),_closeSteps:()=>l({value:void 0,done:!0}),_errorSteps:(A)=>g(A)}),b}releaseLock(){if(!Ks(this))throw Uy("releaseLock");if(this._ownerReadableStream===void 0)return;TY(this)}}if(Object.defineProperties(To.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(To.prototype.cancel,"cancel"),n(To.prototype.read,"read"),n(To.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(To.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Ks(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_readRequests"))return!1;return l instanceof To}function zf(l,g){let b=l._ownerReadableStream;if(b._disturbed=!0,b._state==="closed")g._closeSteps();else if(b._state==="errored")g._errorSteps(b._storedError);else b._readableStreamController[B](g)}function TY(l){ue(l);let g=TypeError("Reader was released");DC(l,g)}function DC(l,g){let b=l._readRequests;l._readRequests=new T,b.forEach((I)=>{I._errorSteps(g)})}function Uy(l){return TypeError(`ReadableStreamDefaultReader.prototype.${l} can only be used on a ReadableStreamDefaultReader`)}let EY=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class iT{constructor(l,g){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=l,this._preventCancel=g}next(){let l=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?x(this._ongoingPromise,l,l):l(),this._ongoingPromise}return(l){let g=()=>this._returnSteps(l);return this._ongoingPromise?x(this._ongoingPromise,g,g):g()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let l=this._reader,g,b,I=c((D,K)=>{g=D,b=K});return zf(l,{_chunkSteps:(D)=>{this._ongoingPromise=void 0,v(()=>g({value:D,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,ue(l),g({value:void 0,done:!0})},_errorSteps:(D)=>{this._ongoingPromise=void 0,this._isFinished=!0,ue(l),b(D)}}),I}_returnSteps(l){if(this._isFinished)return Promise.resolve({value:l,done:!0});this._isFinished=!0;let g=this._reader;if(!this._preventCancel){let b=V(g,l);return ue(g),x(b,()=>({value:l,done:!0}))}return ue(g),u({value:l,done:!0})}}let UC={next(){if(!LC(this))return d(jC("next"));return this._asyncIteratorImpl.next()},return(l){if(!LC(this))return d(jC("return"));return this._asyncIteratorImpl.return(l)}};Object.setPrototypeOf(UC,EY);function IY(l,g){let b=Wr(l),I=new iT(b,g),A=Object.create(UC);return A._asyncIteratorImpl=I,A}function LC(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_asyncIteratorImpl"))return!1;try{return l._asyncIteratorImpl instanceof iT}catch(g){return!1}}function jC(l){return TypeError(`ReadableStreamAsyncIterator.${l} can only be used on a ReadableSteamAsyncIterator`)}let FC=Number.isNaN||function(l){return l!==l};var sT,aT,cT;function Nf(l){return l.slice()}function qC(l,g,b,I,A){new Uint8Array(l).set(new Uint8Array(b,I,A),g)}let Fi=(l)=>{if(typeof l.transfer==="function")Fi=(g)=>g.transfer();else if(typeof structuredClone==="function")Fi=(g)=>structuredClone(g,{transfer:[g]});else Fi=(g)=>g;return Fi(l)},Js=(l)=>{if(typeof l.detached==="boolean")Js=(g)=>g.detached;else Js=(g)=>g.byteLength===0;return Js(l)};function HC(l,g,b){if(l.slice)return l.slice(g,b);let I=b-g,A=new ArrayBuffer(I);return qC(A,0,l,g,I),A}function Ly(l,g){let b=l[g];if(b===void 0||b===null)return;if(typeof b!=="function")throw TypeError(`${String(g)} is not a function`);return b}function PY(l){let g={[Symbol.iterator]:()=>l.iterator},b=async function*(){return yield*g}(),I=b.next;return{iterator:b,nextMethod:I,done:!1}}let uT=(cT=(sT=Symbol.asyncIterator)!==null&&sT!==void 0?sT:(aT=Symbol.for)===null||aT===void 0?void 0:aT.call(Symbol,"Symbol.asyncIterator"))!==null&&cT!==void 0?cT:"@@asyncIterator";function GC(l,g="sync",b){if(b===void 0)if(g==="async"){if(b=Ly(l,uT),b===void 0){let D=Ly(l,Symbol.iterator),K=GC(l,"sync",D);return PY(K)}}else b=Ly(l,Symbol.iterator);if(b===void 0)throw TypeError("The object is not iterable");let I=E(b,l,[]);if(!r(I))throw TypeError("The iterator method must return an object");let A=I.next;return{iterator:I,nextMethod:A,done:!1}}function kY(l){let g=E(l.nextMethod,l.iterator,[]);if(!r(g))throw TypeError("The iterator.next() method must return an object");return g}function AY(l){return Boolean(l.done)}function $Y(l){return l.value}function RY(l){if(typeof l!=="number")return!1;if(FC(l))return!1;if(l<0)return!1;return!0}function VC(l){let g=HC(l.buffer,l.byteOffset,l.byteOffset+l.byteLength);return new Uint8Array(g)}function lT(l){let g=l._queue.shift();if(l._queueTotalSize-=g.size,l._queueTotalSize<0)l._queueTotalSize=0;return g.value}function dT(l,g,b){if(!RY(b)||b===1/0)throw RangeError("Size must be a finite, non-NaN, non-negative number.");l._queue.push({value:g,size:b}),l._queueTotalSize+=b}function OY(l){return l._queue.peek().value}function Ys(l){l._queue=new T,l._queueTotalSize=0}function ZC(l){return l===DataView}function CY(l){return ZC(l.constructor)}function zY(l){if(ZC(l))return 1;return l.BYTES_PER_ELEMENT}class Qs{constructor(){throw TypeError("Illegal constructor")}get view(){if(!pT(this))throw yT("view");return this._view}respond(l){if(!pT(this))throw yT("respond");if(Le(l,1,"respond"),l=tr(l,"First parameter"),this._associatedReadableByteStreamController===void 0)throw TypeError("This BYOB request has been invalidated");if(Js(this._view.buffer))throw TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Hy(this._associatedReadableByteStreamController,l)}respondWithNewView(l){if(!pT(this))throw yT("respondWithNewView");if(Le(l,1,"respondWithNewView"),!ArrayBuffer.isView(l))throw TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw TypeError("This BYOB request has been invalidated");if(Js(l.buffer))throw TypeError("The given view's buffer has been detached and so cannot be used as a response");Gy(this._associatedReadableByteStreamController,l)}}if(Object.defineProperties(Qs.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),n(Qs.prototype.respond,"respond"),n(Qs.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Qs.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ii{constructor(){throw TypeError("Illegal constructor")}get byobRequest(){if(!wc(this))throw Bf("byobRequest");return gT(this)}get desiredSize(){if(!wc(this))throw Bf("desiredSize");return nz(this)}close(){if(!wc(this))throw Bf("close");if(this._closeRequested)throw TypeError("The stream has already been closed; do not close it again!");let l=this._controlledReadableByteStream._state;if(l!=="readable")throw TypeError(`The stream (in ${l} state) is not in the readable state and cannot be closed`);Mf(this)}enqueue(l){if(!wc(this))throw Bf("enqueue");if(Le(l,1,"enqueue"),!ArrayBuffer.isView(l))throw TypeError("chunk must be an array buffer view");if(l.byteLength===0)throw TypeError("chunk must have non-zero byteLength");if(l.buffer.byteLength===0)throw TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw TypeError("stream is closed or draining");let g=this._controlledReadableByteStream._state;if(g!=="readable")throw TypeError(`The stream (in ${g} state) is not in the readable state and cannot be enqueued to`);qy(this,l)}error(l=void 0){if(!wc(this))throw Bf("error");Xn(this,l)}[z](l){WC(this),Ys(this);let g=this._cancelAlgorithm(l);return Fy(this),g}[B](l){let g=this._controlledReadableByteStream;if(this._queueTotalSize>0){rz(this,l);return}let b=this._autoAllocateChunkSize;if(b!==void 0){let I;try{I=new ArrayBuffer(b)}catch(D){l._errorSteps(D);return}let A={buffer:I,bufferByteLength:b,byteOffset:0,byteLength:b,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(A)}Ws(g,l),Sc(this)}[k](){if(this._pendingPullIntos.length>0){let l=this._pendingPullIntos.peek();l.readerType="none",this._pendingPullIntos=new T,this._pendingPullIntos.push(l)}}}if(Object.defineProperties(ii.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ii.prototype.close,"close"),n(ii.prototype.enqueue,"enqueue"),n(ii.prototype.error,"error"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(ii.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function wc(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_controlledReadableByteStream"))return!1;return l instanceof ii}function pT(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_associatedReadableByteStreamController"))return!1;return l instanceof Qs}function Sc(l){if(!UY(l))return;if(l._pulling){l._pullAgain=!0;return}l._pulling=!0;let b=l._pullAlgorithm();m(b,()=>{if(l._pulling=!1,l._pullAgain)l._pullAgain=!1,Sc(l);return null},(I)=>(Xn(l,I),null))}function WC(l){mT(l),l._pendingPullIntos=new T}function fT(l,g){let b=!1;if(l._state==="closed")b=!0;let I=KC(g);if(g.readerType==="default")Cf(l,I,b);else GY(l,I,b)}function KC(l){let{bytesFilled:g,elementSize:b}=l;return new l.viewConstructor(l.buffer,l.byteOffset,g/b)}function jy(l,g,b,I){l._queue.push({buffer:g,byteOffset:b,byteLength:I}),l._queueTotalSize+=I}function JC(l,g,b,I){let A;try{A=HC(g,b,b+I)}catch(D){throw Xn(l,D),D}jy(l,A,0,I)}function YC(l,g){if(g.bytesFilled>0)JC(l,g.buffer,g.byteOffset,g.bytesFilled);al(l)}function QC(l,g){let b=Math.min(l._queueTotalSize,g.byteLength-g.bytesFilled),I=g.bytesFilled+b,A=b,D=!1,K=I%g.elementSize,ve=I-K;if(ve>=g.minimumFill)A=ve-g.bytesFilled,D=!0;let Pe=l._queue;while(A>0){let De=Pe.peek(),Fe=Math.min(A,De.byteLength),Xe=g.byteOffset+g.bytesFilled;if(qC(g.buffer,Xe,De.buffer,De.byteOffset,Fe),De.byteLength===Fe)Pe.shift();else De.byteOffset+=Fe,De.byteLength-=Fe;l._queueTotalSize-=Fe,XC(l,Fe,g),A-=Fe}return D}function XC(l,g,b){b.bytesFilled+=g}function ez(l){if(l._queueTotalSize===0&&l._closeRequested)Fy(l),qf(l._controlledReadableByteStream);else Sc(l)}function mT(l){if(l._byobRequest===null)return;l._byobRequest._associatedReadableByteStreamController=void 0,l._byobRequest._view=null,l._byobRequest=null}function hT(l){while(l._pendingPullIntos.length>0){if(l._queueTotalSize===0)return;let g=l._pendingPullIntos.peek();if(QC(l,g))al(l),fT(l._controlledReadableByteStream,g)}}function NY(l){let g=l._controlledReadableByteStream._reader;while(g._readRequests.length>0){if(l._queueTotalSize===0)return;let b=g._readRequests.shift();rz(l,b)}}function MY(l,g,b,I){let A=l._controlledReadableByteStream,D=g.constructor,K=zY(D),{byteOffset:ve,byteLength:Pe}=g,De=b*K,Fe;try{Fe=Fi(g.buffer)}catch($t){I._errorSteps($t);return}let Xe={buffer:Fe,bufferByteLength:Fe.byteLength,byteOffset:ve,byteLength:Pe,bytesFilled:0,minimumFill:De,elementSize:K,viewConstructor:D,readerType:"byob"};if(l._pendingPullIntos.length>0){l._pendingPullIntos.push(Xe),sz(A,I);return}if(A._state==="closed"){let $t=new D(Xe.buffer,Xe.byteOffset,0);I._closeSteps($t);return}if(l._queueTotalSize>0){if(QC(l,Xe)){let $t=KC(Xe);ez(l),I._chunkSteps($t);return}if(l._closeRequested){let $t=TypeError("Insufficient bytes to fill elements in the given buffer");Xn(l,$t),I._errorSteps($t);return}}l._pendingPullIntos.push(Xe),sz(A,I),Sc(l)}function BY(l,g){if(g.readerType==="none")al(l);let b=l._controlledReadableByteStream;if(bT(b))while(az(b)>0){let I=al(l);fT(b,I)}}function DY(l,g,b){if(XC(l,g,b),b.readerType==="none"){YC(l,b),hT(l);return}if(b.bytesFilled<b.minimumFill)return;al(l);let I=b.bytesFilled%b.elementSize;if(I>0){let A=b.byteOffset+b.bytesFilled;JC(l,b.buffer,A-I,I)}b.bytesFilled-=I,fT(l._controlledReadableByteStream,b),hT(l)}function tz(l,g){let b=l._pendingPullIntos.peek();if(mT(l),l._controlledReadableByteStream._state==="closed")BY(l,b);else DY(l,g,b);Sc(l)}function al(l){return l._pendingPullIntos.shift()}function UY(l){let g=l._controlledReadableByteStream;if(g._state!=="readable")return!1;if(l._closeRequested)return!1;if(!l._started)return!1;if(Dy(g)&&sl(g)>0)return!0;if(bT(g)&&az(g)>0)return!0;if(nz(l)>0)return!0;return!1}function Fy(l){l._pullAlgorithm=void 0,l._cancelAlgorithm=void 0}function Mf(l){let g=l._controlledReadableByteStream;if(l._closeRequested||g._state!=="readable")return;if(l._queueTotalSize>0){l._closeRequested=!0;return}if(l._pendingPullIntos.length>0){let b=l._pendingPullIntos.peek();if(b.bytesFilled%b.elementSize!==0){let I=TypeError("Insufficient bytes to fill elements in the given buffer");throw Xn(l,I),I}}Fy(l),qf(g)}function qy(l,g){let b=l._controlledReadableByteStream;if(l._closeRequested||b._state!=="readable")return;let{buffer:I,byteOffset:A,byteLength:D}=g;if(Js(I))throw TypeError("chunk's buffer is detached and so cannot be enqueued");let K=Fi(I);if(l._pendingPullIntos.length>0){let ve=l._pendingPullIntos.peek();if(Js(ve.buffer))throw TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");if(mT(l),ve.buffer=Fi(ve.buffer),ve.readerType==="none")YC(l,ve)}if(Dy(b))if(NY(l),sl(b)===0)jy(l,K,A,D);else{if(l._pendingPullIntos.length>0)al(l);let ve=new Uint8Array(K,A,D);Cf(b,ve,!1)}else if(bT(b))jy(l,K,A,D),hT(l);else jy(l,K,A,D);Sc(l)}function Xn(l,g){let b=l._controlledReadableByteStream;if(b._state!=="readable")return;WC(l),Ys(l),Fy(l),Rz(b,g)}function rz(l,g){let b=l._queue.shift();l._queueTotalSize-=b.byteLength,ez(l);let I=new Uint8Array(b.buffer,b.byteOffset,b.byteLength);g._chunkSteps(I)}function gT(l){if(l._byobRequest===null&&l._pendingPullIntos.length>0){let g=l._pendingPullIntos.peek(),b=new Uint8Array(g.buffer,g.byteOffset+g.bytesFilled,g.byteLength-g.bytesFilled),I=Object.create(Qs.prototype);jY(I,l,b),l._byobRequest=I}return l._byobRequest}function nz(l){let g=l._controlledReadableByteStream._state;if(g==="errored")return null;if(g==="closed")return 0;return l._strategyHWM-l._queueTotalSize}function Hy(l,g){let b=l._pendingPullIntos.peek();if(l._controlledReadableByteStream._state==="closed"){if(g!==0)throw TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(g===0)throw TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(b.bytesFilled+g>b.byteLength)throw RangeError("bytesWritten out of range")}b.buffer=Fi(b.buffer),tz(l,g)}function Gy(l,g){let b=l._pendingPullIntos.peek();if(l._controlledReadableByteStream._state==="closed"){if(g.byteLength!==0)throw TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(g.byteLength===0)throw TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(b.byteOffset+b.bytesFilled!==g.byteOffset)throw RangeError("The region specified by view does not match byobRequest");if(b.bufferByteLength!==g.buffer.byteLength)throw RangeError("The buffer of view has different capacity than byobRequest");if(b.bytesFilled+g.byteLength>b.byteLength)throw RangeError("The region specified by view is larger than byobRequest");let A=g.byteLength;b.buffer=Fi(g.buffer),tz(l,A)}function oz(l,g,b,I,A,D,K){g._controlledReadableByteStream=l,g._pullAgain=!1,g._pulling=!1,g._byobRequest=null,g._queue=g._queueTotalSize=void 0,Ys(g),g._closeRequested=!1,g._started=!1,g._strategyHWM=D,g._pullAlgorithm=I,g._cancelAlgorithm=A,g._autoAllocateChunkSize=K,g._pendingPullIntos=new T,l._readableStreamController=g;let ve=b();m(u(ve),()=>(g._started=!0,Sc(g),null),(Pe)=>(Xn(g,Pe),null))}function LY(l,g,b){let I=Object.create(ii.prototype),A,D,K;if(g.start!==void 0)A=()=>g.start(I);else A=()=>{return};if(g.pull!==void 0)D=()=>g.pull(I);else D=()=>u(void 0);if(g.cancel!==void 0)K=(Pe)=>g.cancel(Pe);else K=()=>u(void 0);let ve=g.autoAllocateChunkSize;if(ve===0)throw TypeError("autoAllocateChunkSize must be greater than 0");oz(l,I,A,D,K,b,ve)}function jY(l,g,b){l._associatedReadableByteStreamController=g,l._view=b}function yT(l){return TypeError(`ReadableStreamBYOBRequest.prototype.${l} can only be used on a ReadableStreamBYOBRequest`)}function Bf(l){return TypeError(`ReadableByteStreamController.prototype.${l} can only be used on a ReadableByteStreamController`)}function FY(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.mode;return{mode:b===void 0?void 0:qY(b,`${g} has member 'mode' that`)}}function qY(l,g){if(l=`${l}`,l!=="byob")throw TypeError(`${g} '${l}' is not a valid enumeration value for ReadableStreamReaderMode`);return l}function HY(l,g){var b;Z(l,g);let I=(b=l===null||l===void 0?void 0:l.min)!==null&&b!==void 0?b:1;return{min:tr(I,`${g} has member 'min' that`)}}function iz(l){return new qi(l)}function sz(l,g){l._reader._readIntoRequests.push(g)}function GY(l,g,b){let A=l._reader._readIntoRequests.shift();if(b)A._closeSteps(g);else A._chunkSteps(g)}function az(l){return l._reader._readIntoRequests.length}function bT(l){let g=l._reader;if(g===void 0)return!1;if(!Tc(g))return!1;return!0}class qi{constructor(l){if(Le(l,1,"ReadableStreamBYOBReader"),En(l,"First parameter"),ea(l))throw TypeError("This stream has already been locked for exclusive reading by another reader");if(!wc(l._readableStreamController))throw TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");G(this,l),this._readIntoRequests=new T}get closed(){if(!Tc(this))return d(Vy("closed"));return this._closedPromise}cancel(l=void 0){if(!Tc(this))return d(Vy("cancel"));if(this._ownerReadableStream===void 0)return d(W("cancel"));return V(this,l)}read(l,g={}){if(!Tc(this))return d(Vy("read"));if(!ArrayBuffer.isView(l))return d(TypeError("view must be an array buffer view"));if(l.byteLength===0)return d(TypeError("view must have non-zero byteLength"));if(l.buffer.byteLength===0)return d(TypeError("view's buffer must have non-zero byteLength"));if(Js(l.buffer))return d(TypeError("view's buffer has been detached"));let b;try{b=HY(g,"options")}catch(Pe){return d(Pe)}let I=b.min;if(I===0)return d(TypeError("options.min must be greater than 0"));if(!CY(l)){if(I>l.length)return d(RangeError("options.min must be less than or equal to view's length"))}else if(I>l.byteLength)return d(RangeError("options.min must be less than or equal to view's byteLength"));if(this._ownerReadableStream===void 0)return d(W("read from"));let A,D,K=c((Pe,De)=>{A=Pe,D=De});return cz(this,l,I,{_chunkSteps:(Pe)=>A({value:Pe,done:!1}),_closeSteps:(Pe)=>A({value:Pe,done:!0}),_errorSteps:(Pe)=>D(Pe)}),K}releaseLock(){if(!Tc(this))throw Vy("releaseLock");if(this._ownerReadableStream===void 0)return;VY(this)}}if(Object.defineProperties(qi.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(qi.prototype.cancel,"cancel"),n(qi.prototype.read,"read"),n(qi.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(qi.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Tc(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_readIntoRequests"))return!1;return l instanceof qi}function cz(l,g,b,I){let A=l._ownerReadableStream;if(A._disturbed=!0,A._state==="errored")I._errorSteps(A._storedError);else MY(A._readableStreamController,g,b,I)}function VY(l){ue(l);let g=TypeError("Reader was released");uz(l,g)}function uz(l,g){let b=l._readIntoRequests;l._readIntoRequests=new T,b.forEach((I)=>{I._errorSteps(g)})}function Vy(l){return TypeError(`ReadableStreamBYOBReader.prototype.${l} can only be used on a ReadableStreamBYOBReader`)}function Df(l,g){let{highWaterMark:b}=l;if(b===void 0)return g;if(FC(b)||b<0)throw RangeError("Invalid highWaterMark");return b}function Zy(l){let{size:g}=l;if(!g)return()=>1;return g}function Wy(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.highWaterMark,I=l===null||l===void 0?void 0:l.size;return{highWaterMark:b===void 0?void 0:bt(b),size:I===void 0?void 0:ZY(I,`${g} has member 'size' that`)}}function ZY(l,g){return me(l,g),(b)=>bt(l(b))}function WY(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.abort,I=l===null||l===void 0?void 0:l.close,A=l===null||l===void 0?void 0:l.start,D=l===null||l===void 0?void 0:l.type,K=l===null||l===void 0?void 0:l.write;return{abort:b===void 0?void 0:KY(b,l,`${g} has member 'abort' that`),close:I===void 0?void 0:JY(I,l,`${g} has member 'close' that`),start:A===void 0?void 0:YY(A,l,`${g} has member 'start' that`),write:K===void 0?void 0:QY(K,l,`${g} has member 'write' that`),type:D}}function KY(l,g,b){return me(l,b),(I)=>w(l,g,[I])}function JY(l,g,b){return me(l,b),()=>w(l,g,[])}function YY(l,g,b){return me(l,b),(I)=>E(l,g,[I])}function QY(l,g,b){return me(l,b),(I,A)=>w(l,g,[I,A])}function lz(l,g){if(!cl(l))throw TypeError(`${g} is not a WritableStream.`)}function XY(l){if(typeof l!=="object"||l===null)return!1;try{return typeof l.aborted==="boolean"}catch(g){return!1}}let eQ=typeof AbortController==="function";function tQ(){if(eQ)return new AbortController;return}class Hi{constructor(l={},g={}){if(l===void 0)l=null;else Be(l,"First parameter");let b=Wy(g,"Second parameter"),I=WY(l,"First parameter");if(pz(this),I.type!==void 0)throw RangeError("Invalid type is specified");let D=Zy(b),K=Df(b,1);hQ(this,I,K,D)}get locked(){if(!cl(this))throw Xy("locked");return ul(this)}abort(l=void 0){if(!cl(this))return d(Xy("abort"));if(ul(this))return d(TypeError("Cannot abort a stream that already has a writer"));return Ky(this,l)}close(){if(!cl(this))return d(Xy("close"));if(ul(this))return d(TypeError("Cannot close a stream that already has a writer"));if(si(this))return d(TypeError("Cannot close an already-closing stream"));return fz(this)}getWriter(){if(!cl(this))throw Xy("getWriter");return dz(this)}}if(Object.defineProperties(Hi.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),n(Hi.prototype.abort,"abort"),n(Hi.prototype.close,"close"),n(Hi.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Hi.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function dz(l){return new ai(l)}function rQ(l,g,b,I,A=1,D=()=>1){let K=Object.create(Hi.prototype);pz(K);let ve=Object.create(Ic.prototype);return xz(K,ve,l,g,b,I,A,D),K}function pz(l){l._state="writable",l._storedError=void 0,l._writer=void 0,l._writableStreamController=void 0,l._writeRequests=new T,l._inFlightWriteRequest=void 0,l._closeRequest=void 0,l._inFlightCloseRequest=void 0,l._pendingAbortRequest=void 0,l._backpressure=!1}function cl(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_writableStreamController"))return!1;return l instanceof Hi}function ul(l){if(l._writer===void 0)return!1;return!0}function Ky(l,g){var b;if(l._state==="closed"||l._state==="errored")return u(void 0);l._writableStreamController._abortReason=g,(b=l._writableStreamController._abortController)===null||b===void 0||b.abort(g);let I=l._state;if(I==="closed"||I==="errored")return u(void 0);if(l._pendingAbortRequest!==void 0)return l._pendingAbortRequest._promise;let A=!1;if(I==="erroring")A=!0,g=void 0;let D=c((K,ve)=>{l._pendingAbortRequest={_promise:void 0,_resolve:K,_reject:ve,_reason:g,_wasAlreadyErroring:A}});if(l._pendingAbortRequest._promise=D,!A)vT(l,g);return D}function fz(l){let g=l._state;if(g==="closed"||g==="errored")return d(TypeError(`The stream (in ${g} state) is not in the writable state and cannot be closed`));let b=c((A,D)=>{let K={_resolve:A,_reject:D};l._closeRequest=K}),I=l._writer;if(I!==void 0&&l._backpressure&&g==="writable")kT(I);return gQ(l._writableStreamController),b}function nQ(l){return c((b,I)=>{let A={_resolve:b,_reject:I};l._writeRequests.push(A)})}function xT(l,g){if(l._state==="writable"){vT(l,g);return}_T(l)}function vT(l,g){let b=l._writableStreamController;l._state="erroring",l._storedError=g;let I=l._writer;if(I!==void 0)hz(I,g);if(!cQ(l)&&b._started)_T(l)}function _T(l){l._state="errored",l._writableStreamController[O]();let g=l._storedError;if(l._writeRequests.forEach((A)=>{A._reject(g)}),l._writeRequests=new T,l._pendingAbortRequest===void 0){Jy(l);return}let b=l._pendingAbortRequest;if(l._pendingAbortRequest=void 0,b._wasAlreadyErroring){b._reject(g),Jy(l);return}let I=l._writableStreamController[P](b._reason);m(I,()=>(b._resolve(),Jy(l),null),(A)=>(b._reject(A),Jy(l),null))}function oQ(l){l._inFlightWriteRequest._resolve(void 0),l._inFlightWriteRequest=void 0}function iQ(l,g){l._inFlightWriteRequest._reject(g),l._inFlightWriteRequest=void 0,xT(l,g)}function sQ(l){if(l._inFlightCloseRequest._resolve(void 0),l._inFlightCloseRequest=void 0,l._state==="erroring"){if(l._storedError=void 0,l._pendingAbortRequest!==void 0)l._pendingAbortRequest._resolve(),l._pendingAbortRequest=void 0}l._state="closed";let b=l._writer;if(b!==void 0)Sz(b)}function aQ(l,g){if(l._inFlightCloseRequest._reject(g),l._inFlightCloseRequest=void 0,l._pendingAbortRequest!==void 0)l._pendingAbortRequest._reject(g),l._pendingAbortRequest=void 0;xT(l,g)}function si(l){if(l._closeRequest===void 0&&l._inFlightCloseRequest===void 0)return!1;return!0}function cQ(l){if(l._inFlightWriteRequest===void 0&&l._inFlightCloseRequest===void 0)return!1;return!0}function uQ(l){l._inFlightCloseRequest=l._closeRequest,l._closeRequest=void 0}function lQ(l){l._inFlightWriteRequest=l._writeRequests.shift()}function Jy(l){if(l._closeRequest!==void 0)l._closeRequest._reject(l._storedError),l._closeRequest=void 0;let g=l._writer;if(g!==void 0)IT(g,l._storedError)}function wT(l,g){let b=l._writer;if(b!==void 0&&g!==l._backpressure)if(g)SQ(b);else kT(b);l._backpressure=g}class ai{constructor(l){if(Le(l,1,"WritableStreamDefaultWriter"),lz(l,"First parameter"),ul(l))throw TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=l,l._writer=this;let g=l._state;if(g==="writable"){if(!si(l)&&l._backpressure)tb(this);else Tz(this);eb(this)}else if(g==="erroring")PT(this,l._storedError),eb(this);else if(g==="closed")Tz(this),_Q(this);else{let b=l._storedError;PT(this,b),wz(this,b)}}get closed(){if(!Ec(this))return d(Pc("closed"));return this._closedPromise}get desiredSize(){if(!Ec(this))throw Pc("desiredSize");if(this._ownerWritableStream===void 0)throw Lf("desiredSize");return mQ(this)}get ready(){if(!Ec(this))return d(Pc("ready"));return this._readyPromise}abort(l=void 0){if(!Ec(this))return d(Pc("abort"));if(this._ownerWritableStream===void 0)return d(Lf("abort"));return dQ(this,l)}close(){if(!Ec(this))return d(Pc("close"));let l=this._ownerWritableStream;if(l===void 0)return d(Lf("close"));if(si(l))return d(TypeError("Cannot close an already-closing stream"));return mz(this)}releaseLock(){if(!Ec(this))throw Pc("releaseLock");if(this._ownerWritableStream===void 0)return;gz(this)}write(l=void 0){if(!Ec(this))return d(Pc("write"));if(this._ownerWritableStream===void 0)return d(Lf("write to"));return yz(this,l)}}if(Object.defineProperties(ai.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),n(ai.prototype.abort,"abort"),n(ai.prototype.close,"close"),n(ai.prototype.releaseLock,"releaseLock"),n(ai.prototype.write,"write"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(ai.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Ec(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_ownerWritableStream"))return!1;return l instanceof ai}function dQ(l,g){let b=l._ownerWritableStream;return Ky(b,g)}function mz(l){let g=l._ownerWritableStream;return fz(g)}function pQ(l){let g=l._ownerWritableStream,b=g._state;if(si(g)||b==="closed")return u(void 0);if(b==="errored")return d(g._storedError);return mz(l)}function fQ(l,g){if(l._closedPromiseState==="pending")IT(l,g);else wQ(l,g)}function hz(l,g){if(l._readyPromiseState==="pending")Ez(l,g);else TQ(l,g)}function mQ(l){let g=l._ownerWritableStream,b=g._state;if(b==="errored"||b==="erroring")return null;if(b==="closed")return 0;return vz(g._writableStreamController)}function gz(l){let g=l._ownerWritableStream,b=TypeError("Writer was released and can no longer be used to monitor the stream's closedness");hz(l,b),fQ(l,b),g._writer=void 0,l._ownerWritableStream=void 0}function yz(l,g){let b=l._ownerWritableStream,I=b._writableStreamController,A=yQ(I,g);if(b!==l._ownerWritableStream)return d(Lf("write to"));let D=b._state;if(D==="errored")return d(b._storedError);if(si(b)||D==="closed")return d(TypeError("The stream is closing or closed and cannot be written to"));if(D==="erroring")return d(b._storedError);let K=nQ(b);return bQ(I,g,A),K}let bz={};class Ic{constructor(){throw TypeError("Illegal constructor")}get abortReason(){if(!ST(this))throw ET("abortReason");return this._abortReason}get signal(){if(!ST(this))throw ET("signal");if(this._abortController===void 0)throw TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(l=void 0){if(!ST(this))throw ET("error");if(this._controlledWritableStream._state!=="writable")return;_z(this,l)}[P](l){let g=this._abortAlgorithm(l);return Yy(this),g}[O](){Ys(this)}}if(Object.defineProperties(Ic.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Ic.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function ST(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_controlledWritableStream"))return!1;return l instanceof Ic}function xz(l,g,b,I,A,D,K,ve){g._controlledWritableStream=l,l._writableStreamController=g,g._queue=void 0,g._queueTotalSize=void 0,Ys(g),g._abortReason=void 0,g._abortController=tQ(),g._started=!1,g._strategySizeAlgorithm=ve,g._strategyHWM=K,g._writeAlgorithm=I,g._closeAlgorithm=A,g._abortAlgorithm=D;let Pe=TT(g);wT(l,Pe);let De=b(),Fe=u(De);m(Fe,()=>(g._started=!0,Qy(g),null),(Xe)=>(g._started=!0,xT(l,Xe),null))}function hQ(l,g,b,I){let A=Object.create(Ic.prototype),D,K,ve,Pe;if(g.start!==void 0)D=()=>g.start(A);else D=()=>{return};if(g.write!==void 0)K=(De)=>g.write(De,A);else K=()=>u(void 0);if(g.close!==void 0)ve=()=>g.close();else ve=()=>u(void 0);if(g.abort!==void 0)Pe=(De)=>g.abort(De);else Pe=()=>u(void 0);xz(l,A,D,K,ve,Pe,b,I)}function Yy(l){l._writeAlgorithm=void 0,l._closeAlgorithm=void 0,l._abortAlgorithm=void 0,l._strategySizeAlgorithm=void 0}function gQ(l){dT(l,bz,0),Qy(l)}function yQ(l,g){try{return l._strategySizeAlgorithm(g)}catch(b){return Uf(l,b),1}}function vz(l){return l._strategyHWM-l._queueTotalSize}function bQ(l,g,b){try{dT(l,g,b)}catch(A){Uf(l,A);return}let I=l._controlledWritableStream;if(!si(I)&&I._state==="writable"){let A=TT(l);wT(I,A)}Qy(l)}function Qy(l){let g=l._controlledWritableStream;if(!l._started)return;if(g._inFlightWriteRequest!==void 0)return;if(g._state==="erroring"){_T(g);return}if(l._queue.length===0)return;let I=OY(l);if(I===bz)xQ(l);else vQ(l,I)}function Uf(l,g){if(l._controlledWritableStream._state==="writable")_z(l,g)}function xQ(l){let g=l._controlledWritableStream;uQ(g),lT(l);let b=l._closeAlgorithm();Yy(l),m(b,()=>(sQ(g),null),(I)=>(aQ(g,I),null))}function vQ(l,g){let b=l._controlledWritableStream;lQ(b);let I=l._writeAlgorithm(g);m(I,()=>{oQ(b);let A=b._state;if(lT(l),!si(b)&&A==="writable"){let D=TT(l);wT(b,D)}return Qy(l),null},(A)=>{if(b._state==="writable")Yy(l);return iQ(b,A),null})}function TT(l){return vz(l)<=0}function _z(l,g){let b=l._controlledWritableStream;Yy(l),vT(b,g)}function Xy(l){return TypeError(`WritableStream.prototype.${l} can only be used on a WritableStream`)}function ET(l){return TypeError(`WritableStreamDefaultController.prototype.${l} can only be used on a WritableStreamDefaultController`)}function Pc(l){return TypeError(`WritableStreamDefaultWriter.prototype.${l} can only be used on a WritableStreamDefaultWriter`)}function Lf(l){return TypeError("Cannot "+l+" a stream using a released writer")}function eb(l){l._closedPromise=c((g,b)=>{l._closedPromise_resolve=g,l._closedPromise_reject=b,l._closedPromiseState="pending"})}function wz(l,g){eb(l),IT(l,g)}function _Q(l){eb(l),Sz(l)}function IT(l,g){if(l._closedPromise_reject===void 0)return;S(l._closedPromise),l._closedPromise_reject(g),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0,l._closedPromiseState="rejected"}function wQ(l,g){wz(l,g)}function Sz(l){if(l._closedPromise_resolve===void 0)return;l._closedPromise_resolve(void 0),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0,l._closedPromiseState="resolved"}function tb(l){l._readyPromise=c((g,b)=>{l._readyPromise_resolve=g,l._readyPromise_reject=b}),l._readyPromiseState="pending"}function PT(l,g){tb(l),Ez(l,g)}function Tz(l){tb(l),kT(l)}function Ez(l,g){if(l._readyPromise_reject===void 0)return;S(l._readyPromise),l._readyPromise_reject(g),l._readyPromise_resolve=void 0,l._readyPromise_reject=void 0,l._readyPromiseState="rejected"}function SQ(l){tb(l)}function TQ(l,g){PT(l,g)}function kT(l){if(l._readyPromise_resolve===void 0)return;l._readyPromise_resolve(void 0),l._readyPromise_resolve=void 0,l._readyPromise_reject=void 0,l._readyPromiseState="fulfilled"}function EQ(){if(typeof globalThis<"u")return globalThis;else if(typeof self<"u")return self;else if(typeof global<"u")return global;return}let AT=EQ();function IQ(l){if(!(typeof l==="function"||typeof l==="object"))return!1;if(l.name!=="DOMException")return!1;try{return new l,!0}catch(g){return!1}}function PQ(){let l=AT===null||AT===void 0?void 0:AT.DOMException;return IQ(l)?l:void 0}function kQ(){let l=function(b,I){if(this.message=b||"",this.name=I||"Error",Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)};return n(l,"DOMException"),l.prototype=Object.create(Error.prototype),Object.defineProperty(l.prototype,"constructor",{value:l,writable:!0,configurable:!0}),l}let AQ=PQ()||kQ();function Iz(l,g,b,I,A,D){let K=Wr(l),ve=dz(g);l._disturbed=!0;let Pe=!1,De=u(void 0);return c((Fe,Xe)=>{let $t;if(D!==void 0){if($t=()=>{let Re=D.reason!==void 0?D.reason:new AQ("Aborted","AbortError"),et=[];if(!I)et.push(()=>{if(g._state==="writable")return Ky(g,Re);return u(void 0)});if(!A)et.push(()=>{if(l._state==="readable")return Io(l,Re);return u(void 0)});In(()=>Promise.all(et.map((Nt)=>Nt())),!0,Re)},D.aborted){$t();return}D.addEventListener("abort",$t)}function Vi(){return c((Re,et)=>{function Nt(qn){if(qn)Re();else p(fl(),Nt,et)}Nt(!1)})}function fl(){if(Pe)return u(!0);return p(ve._readyPromise,()=>c((Re,et)=>{zf(K,{_chunkSteps:(Nt)=>{De=p(yz(ve,Nt),void 0,t),Re(!1)},_closeSteps:()=>Re(!0),_errorSteps:et})}))}if(Zi(l,K._closedPromise,(Re)=>{if(!I)In(()=>Ky(g,Re),!0,Re);else eo(!0,Re);return null}),Zi(g,ve._closedPromise,(Re)=>{if(!A)In(()=>Io(l,Re),!0,Re);else eo(!0,Re);return null}),tn(l,K._closedPromise,()=>{if(!b)In(()=>pQ(ve));else eo();return null}),si(g)||g._state==="closed"){let Re=TypeError("the destination writable stream closed before all data could be piped to it");if(!A)In(()=>Io(l,Re),!0,Re);else eo(!0,Re)}S(Vi());function ta(){let Re=De;return p(De,()=>Re!==De?ta():void 0)}function Zi(Re,et,Nt){if(Re._state==="errored")Nt(Re._storedError);else y(et,Nt)}function tn(Re,et,Nt){if(Re._state==="closed")Nt();else h(et,Nt)}function In(Re,et,Nt){if(Pe)return;if(Pe=!0,g._state==="writable"&&!si(g))h(ta(),qn);else qn();function qn(){return m(Re(),()=>Wi(et,Nt),(ml)=>Wi(!0,ml)),null}}function eo(Re,et){if(Pe)return;if(Pe=!0,g._state==="writable"&&!si(g))h(ta(),()=>Wi(Re,et));else Wi(Re,et)}function Wi(Re,et){if(gz(ve),ue(K),D!==void 0)D.removeEventListener("abort",$t);if(Re)Xe(et);else Fe(void 0);return null}})}class ci{constructor(){throw TypeError("Illegal constructor")}get desiredSize(){if(!rb(this))throw ob("desiredSize");return $T(this)}close(){if(!rb(this))throw ob("close");if(!dl(this))throw TypeError("The stream is not in a state that permits close");kc(this)}enqueue(l=void 0){if(!rb(this))throw ob("enqueue");if(!dl(this))throw TypeError("The stream is not in a state that permits enqueue");return ll(this,l)}error(l=void 0){if(!rb(this))throw ob("error");Eo(this,l)}[z](l){Ys(this);let g=this._cancelAlgorithm(l);return nb(this),g}[B](l){let g=this._controlledReadableStream;if(this._queue.length>0){let b=lT(this);if(this._closeRequested&&this._queue.length===0)nb(this),qf(g);else jf(this);l._chunkSteps(b)}else Ws(g,l),jf(this)}[k](){}}if(Object.defineProperties(ci.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ci.prototype.close,"close"),n(ci.prototype.enqueue,"enqueue"),n(ci.prototype.error,"error"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(ci.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function rb(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_controlledReadableStream"))return!1;return l instanceof ci}function jf(l){if(!Pz(l))return;if(l._pulling){l._pullAgain=!0;return}l._pulling=!0;let b=l._pullAlgorithm();m(b,()=>{if(l._pulling=!1,l._pullAgain)l._pullAgain=!1,jf(l);return null},(I)=>(Eo(l,I),null))}function Pz(l){let g=l._controlledReadableStream;if(!dl(l))return!1;if(!l._started)return!1;if(ea(g)&&sl(g)>0)return!0;if($T(l)>0)return!0;return!1}function nb(l){l._pullAlgorithm=void 0,l._cancelAlgorithm=void 0,l._strategySizeAlgorithm=void 0}function kc(l){if(!dl(l))return;let g=l._controlledReadableStream;if(l._closeRequested=!0,l._queue.length===0)nb(l),qf(g)}function ll(l,g){if(!dl(l))return;let b=l._controlledReadableStream;if(ea(b)&&sl(b)>0)Cf(b,g,!1);else{let I;try{I=l._strategySizeAlgorithm(g)}catch(A){throw Eo(l,A),A}try{dT(l,g,I)}catch(A){throw Eo(l,A),A}}jf(l)}function Eo(l,g){let b=l._controlledReadableStream;if(b._state!=="readable")return;Ys(l),nb(l),Rz(b,g)}function $T(l){let g=l._controlledReadableStream._state;if(g==="errored")return null;if(g==="closed")return 0;return l._strategyHWM-l._queueTotalSize}function $Q(l){if(Pz(l))return!1;return!0}function dl(l){let g=l._controlledReadableStream._state;if(!l._closeRequested&&g==="readable")return!0;return!1}function kz(l,g,b,I,A,D,K){g._controlledReadableStream=l,g._queue=void 0,g._queueTotalSize=void 0,Ys(g),g._started=!1,g._closeRequested=!1,g._pullAgain=!1,g._pulling=!1,g._strategySizeAlgorithm=K,g._strategyHWM=D,g._pullAlgorithm=I,g._cancelAlgorithm=A,l._readableStreamController=g;let ve=b();m(u(ve),()=>(g._started=!0,jf(g),null),(Pe)=>(Eo(g,Pe),null))}function RQ(l,g,b,I){let A=Object.create(ci.prototype),D,K,ve;if(g.start!==void 0)D=()=>g.start(A);else D=()=>{return};if(g.pull!==void 0)K=()=>g.pull(A);else K=()=>u(void 0);if(g.cancel!==void 0)ve=(Pe)=>g.cancel(Pe);else ve=()=>u(void 0);kz(l,A,D,K,ve,b,I)}function ob(l){return TypeError(`ReadableStreamDefaultController.prototype.${l} can only be used on a ReadableStreamDefaultController`)}function OQ(l,g){if(wc(l._readableStreamController))return zQ(l);return CQ(l)}function CQ(l,g){let b=Wr(l),I=!1,A=!1,D=!1,K=!1,ve,Pe,De,Fe,Xe,$t=c((tn)=>{Xe=tn});function Vi(){if(I)return A=!0,u(void 0);return I=!0,zf(b,{_chunkSteps:(In)=>{v(()=>{A=!1;let eo=In,Wi=In;if(!D)ll(De._readableStreamController,eo);if(!K)ll(Fe._readableStreamController,Wi);if(I=!1,A)Vi()})},_closeSteps:()=>{if(I=!1,!D)kc(De._readableStreamController);if(!K)kc(Fe._readableStreamController);if(!D||!K)Xe(void 0)},_errorSteps:()=>{I=!1}}),u(void 0)}function fl(tn){if(D=!0,ve=tn,K){let In=Nf([ve,Pe]),eo=Io(l,In);Xe(eo)}return $t}function ta(tn){if(K=!0,Pe=tn,D){let In=Nf([ve,Pe]),eo=Io(l,In);Xe(eo)}return $t}function Zi(){}return De=Ff(Zi,Vi,fl),Fe=Ff(Zi,Vi,ta),y(b._closedPromise,(tn)=>{if(Eo(De._readableStreamController,tn),Eo(Fe._readableStreamController,tn),!D||!K)Xe(void 0);return null}),[De,Fe]}function zQ(l){let g=Wr(l),b=!1,I=!1,A=!1,D=!1,K=!1,ve,Pe,De,Fe,Xe,$t=c((Re)=>{Xe=Re});function Vi(Re){y(Re._closedPromise,(et)=>{if(Re!==g)return null;if(Xn(De._readableStreamController,et),Xn(Fe._readableStreamController,et),!D||!K)Xe(void 0);return null})}function fl(){if(Tc(g))ue(g),g=Wr(l),Vi(g);zf(g,{_chunkSteps:(et)=>{v(()=>{I=!1,A=!1;let Nt=et,qn=et;if(!D&&!K)try{qn=VC(et)}catch(ml){Xn(De._readableStreamController,ml),Xn(Fe._readableStreamController,ml),Xe(Io(l,ml));return}if(!D)qy(De._readableStreamController,Nt);if(!K)qy(Fe._readableStreamController,qn);if(b=!1,I)Zi();else if(A)tn()})},_closeSteps:()=>{if(b=!1,!D)Mf(De._readableStreamController);if(!K)Mf(Fe._readableStreamController);if(De._readableStreamController._pendingPullIntos.length>0)Hy(De._readableStreamController,0);if(Fe._readableStreamController._pendingPullIntos.length>0)Hy(Fe._readableStreamController,0);if(!D||!K)Xe(void 0)},_errorSteps:()=>{b=!1}})}function ta(Re,et){if(Ks(g))ue(g),g=iz(l),Vi(g);let Nt=et?Fe:De,qn=et?De:Fe;cz(g,Re,1,{_chunkSteps:(hl)=>{v(()=>{I=!1,A=!1;let gl=et?K:D;if(!(et?D:K)){let Hz;try{Hz=VC(hl)}catch(NT){Xn(Nt._readableStreamController,NT),Xn(qn._readableStreamController,NT),Xe(Io(l,NT));return}if(!gl)Gy(Nt._readableStreamController,hl);qy(qn._readableStreamController,Hz)}else if(!gl)Gy(Nt._readableStreamController,hl);if(b=!1,I)Zi();else if(A)tn()})},_closeSteps:(hl)=>{b=!1;let gl=et?K:D,ub=et?D:K;if(!gl)Mf(Nt._readableStreamController);if(!ub)Mf(qn._readableStreamController);if(hl!==void 0){if(!gl)Gy(Nt._readableStreamController,hl);if(!ub&&qn._readableStreamController._pendingPullIntos.length>0)Hy(qn._readableStreamController,0)}if(!gl||!ub)Xe(void 0)},_errorSteps:()=>{b=!1}})}function Zi(){if(b)return I=!0,u(void 0);b=!0;let Re=gT(De._readableStreamController);if(Re===null)fl();else ta(Re._view,!1);return u(void 0)}function tn(){if(b)return A=!0,u(void 0);b=!0;let Re=gT(Fe._readableStreamController);if(Re===null)fl();else ta(Re._view,!0);return u(void 0)}function In(Re){if(D=!0,ve=Re,K){let et=Nf([ve,Pe]),Nt=Io(l,et);Xe(Nt)}return $t}function eo(Re){if(K=!0,Pe=Re,D){let et=Nf([ve,Pe]),Nt=Io(l,et);Xe(Nt)}return $t}function Wi(){return}return De=$z(Wi,Zi,In),Fe=$z(Wi,tn,eo),Vi(g),[De,Fe]}function NQ(l){return r(l)&&typeof l.getReader<"u"}function MQ(l){if(NQ(l))return DQ(l.getReader());return BQ(l)}function BQ(l){let g,b=GC(l,"async"),I=t;function A(){let K;try{K=kY(b)}catch(Pe){return d(Pe)}let ve=u(K);return x(ve,(Pe)=>{if(!r(Pe))throw TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(AY(Pe))kc(g._readableStreamController);else{let Fe=$Y(Pe);ll(g._readableStreamController,Fe)}})}function D(K){let ve=b.iterator,Pe;try{Pe=Ly(ve,"return")}catch(Xe){return d(Xe)}if(Pe===void 0)return u(void 0);let De;try{De=E(Pe,ve,[K])}catch(Xe){return d(Xe)}let Fe=u(De);return x(Fe,(Xe)=>{if(!r(Xe))throw TypeError("The promise returned by the iterator.return() method must fulfill with an object");return})}return g=Ff(I,A,D,0),g}function DQ(l){let g,b=t;function I(){let D;try{D=l.read()}catch(K){return d(K)}return x(D,(K)=>{if(!r(K))throw TypeError("The promise returned by the reader.read() method must fulfill with an object");if(K.done)kc(g._readableStreamController);else{let ve=K.value;ll(g._readableStreamController,ve)}})}function A(D){try{return u(l.cancel(D))}catch(K){return d(K)}}return g=Ff(b,I,A,0),g}function UQ(l,g){Z(l,g);let b=l,I=b===null||b===void 0?void 0:b.autoAllocateChunkSize,A=b===null||b===void 0?void 0:b.cancel,D=b===null||b===void 0?void 0:b.pull,K=b===null||b===void 0?void 0:b.start,ve=b===null||b===void 0?void 0:b.type;return{autoAllocateChunkSize:I===void 0?void 0:tr(I,`${g} has member 'autoAllocateChunkSize' that`),cancel:A===void 0?void 0:LQ(A,b,`${g} has member 'cancel' that`),pull:D===void 0?void 0:jQ(D,b,`${g} has member 'pull' that`),start:K===void 0?void 0:FQ(K,b,`${g} has member 'start' that`),type:ve===void 0?void 0:qQ(ve,`${g} has member 'type' that`)}}function LQ(l,g,b){return me(l,b),(I)=>w(l,g,[I])}function jQ(l,g,b){return me(l,b),(I)=>w(l,g,[I])}function FQ(l,g,b){return me(l,b),(I)=>E(l,g,[I])}function qQ(l,g){if(l=`${l}`,l!=="bytes")throw TypeError(`${g} '${l}' is not a valid enumeration value for ReadableStreamType`);return l}function HQ(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.preventCancel;return{preventCancel:Boolean(b)}}function Az(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.preventAbort,I=l===null||l===void 0?void 0:l.preventCancel,A=l===null||l===void 0?void 0:l.preventClose,D=l===null||l===void 0?void 0:l.signal;if(D!==void 0)GQ(D,`${g} has member 'signal' that`);return{preventAbort:Boolean(b),preventCancel:Boolean(I),preventClose:Boolean(A),signal:D}}function GQ(l,g){if(!XY(l))throw TypeError(`${g} is not an AbortSignal.`)}function VQ(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.readable;Ut(b,"readable","ReadableWritablePair"),En(b,`${g} has member 'readable' that`);let I=l===null||l===void 0?void 0:l.writable;return Ut(I,"writable","ReadableWritablePair"),lz(I,`${g} has member 'writable' that`),{readable:b,writable:I}}class kr{constructor(l={},g={}){if(l===void 0)l=null;else Be(l,"First parameter");let b=Wy(g,"Second parameter"),I=UQ(l,"First parameter");if(RT(this),I.type==="bytes"){if(b.size!==void 0)throw RangeError("The strategy for a byte stream cannot have a size function");let A=Df(b,0);LY(this,I,A)}else{let A=Zy(b),D=Df(b,1);RQ(this,I,D,A)}}get locked(){if(!Xs(this))throw Ac("locked");return ea(this)}cancel(l=void 0){if(!Xs(this))return d(Ac("cancel"));if(ea(this))return d(TypeError("Cannot cancel a stream that already has a reader"));return Io(this,l)}getReader(l=void 0){if(!Xs(this))throw Ac("getReader");if(FY(l,"First parameter").mode===void 0)return Wr(this);return iz(this)}pipeThrough(l,g={}){if(!Xs(this))throw Ac("pipeThrough");Le(l,1,"pipeThrough");let b=VQ(l,"First parameter"),I=Az(g,"Second parameter");if(ea(this))throw TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(ul(b.writable))throw TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let A=Iz(this,b.writable,I.preventClose,I.preventAbort,I.preventCancel,I.signal);return S(A),b.readable}pipeTo(l,g={}){if(!Xs(this))return d(Ac("pipeTo"));if(l===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!cl(l))return d(TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let b;try{b=Az(g,"Second parameter")}catch(I){return d(I)}if(ea(this))return d(TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));if(ul(l))return d(TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));return Iz(this,l,b.preventClose,b.preventAbort,b.preventCancel,b.signal)}tee(){if(!Xs(this))throw Ac("tee");let l=OQ(this);return Nf(l)}values(l=void 0){if(!Xs(this))throw Ac("values");let g=HQ(l,"First parameter");return IY(this,g.preventCancel)}[uT](l){return this.values(l)}static from(l){return MQ(l)}}if(Object.defineProperties(kr,{from:{enumerable:!0}}),Object.defineProperties(kr.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),n(kr.from,"from"),n(kr.prototype.cancel,"cancel"),n(kr.prototype.getReader,"getReader"),n(kr.prototype.pipeThrough,"pipeThrough"),n(kr.prototype.pipeTo,"pipeTo"),n(kr.prototype.tee,"tee"),n(kr.prototype.values,"values"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(kr.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0});Object.defineProperty(kr.prototype,uT,{value:kr.prototype.values,writable:!0,configurable:!0});function Ff(l,g,b,I=1,A=()=>1){let D=Object.create(kr.prototype);RT(D);let K=Object.create(ci.prototype);return kz(D,K,l,g,b,I,A),D}function $z(l,g,b){let I=Object.create(kr.prototype);RT(I);let A=Object.create(ii.prototype);return oz(I,A,l,g,b,0,void 0),I}function RT(l){l._state="readable",l._reader=void 0,l._storedError=void 0,l._disturbed=!1}function Xs(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_readableStreamController"))return!1;return l instanceof kr}function ea(l){if(l._reader===void 0)return!1;return!0}function Io(l,g){if(l._disturbed=!0,l._state==="closed")return u(void 0);if(l._state==="errored")return d(l._storedError);qf(l);let b=l._reader;if(b!==void 0&&Tc(b)){let A=b._readIntoRequests;b._readIntoRequests=new T,A.forEach((D)=>{D._closeSteps(void 0)})}let I=l._readableStreamController[z](g);return x(I,t)}function qf(l){l._state="closed";let g=l._reader;if(g===void 0)return;if(N(g),Ks(g)){let b=g._readRequests;g._readRequests=new T,b.forEach((I)=>{I._closeSteps()})}}function Rz(l,g){l._state="errored",l._storedError=g;let b=l._reader;if(b===void 0)return;if(C(b,g),Ks(b))DC(b,g);else uz(b,g)}function Ac(l){return TypeError(`ReadableStream.prototype.${l} can only be used on a ReadableStream`)}function Oz(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.highWaterMark;return Ut(b,"highWaterMark","QueuingStrategyInit"),{highWaterMark:bt(b)}}let Cz=(l)=>l.byteLength;n(Cz,"size");class Hf{constructor(l){Le(l,1,"ByteLengthQueuingStrategy"),l=Oz(l,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!Nz(this))throw zz("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Nz(this))throw zz("size");return Cz}}if(Object.defineProperties(Hf.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Hf.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function zz(l){return TypeError(`ByteLengthQueuingStrategy.prototype.${l} can only be used on a ByteLengthQueuingStrategy`)}function Nz(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_byteLengthQueuingStrategyHighWaterMark"))return!1;return l instanceof Hf}let Mz=()=>1;n(Mz,"size");class Gf{constructor(l){Le(l,1,"CountQueuingStrategy"),l=Oz(l,"First parameter"),this._countQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!Dz(this))throw Bz("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Dz(this))throw Bz("size");return Mz}}if(Object.defineProperties(Gf.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Gf.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Bz(l){return TypeError(`CountQueuingStrategy.prototype.${l} can only be used on a CountQueuingStrategy`)}function Dz(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_countQueuingStrategyHighWaterMark"))return!1;return l instanceof Gf}function ZQ(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.cancel,I=l===null||l===void 0?void 0:l.flush,A=l===null||l===void 0?void 0:l.readableType,D=l===null||l===void 0?void 0:l.start,K=l===null||l===void 0?void 0:l.transform,ve=l===null||l===void 0?void 0:l.writableType;return{cancel:b===void 0?void 0:YQ(b,l,`${g} has member 'cancel' that`),flush:I===void 0?void 0:WQ(I,l,`${g} has member 'flush' that`),readableType:A,start:D===void 0?void 0:KQ(D,l,`${g} has member 'start' that`),transform:K===void 0?void 0:JQ(K,l,`${g} has member 'transform' that`),writableType:ve}}function WQ(l,g,b){return me(l,b),(I)=>w(l,g,[I])}function KQ(l,g,b){return me(l,b),(I)=>E(l,g,[I])}function JQ(l,g,b){return me(l,b),(I,A)=>w(l,g,[I,A])}function YQ(l,g,b){return me(l,b),(I)=>w(l,g,[I])}class Vf{constructor(l={},g={},b={}){if(l===void 0)l=null;let I=Wy(g,"Second parameter"),A=Wy(b,"Third parameter"),D=ZQ(l,"First parameter");if(D.readableType!==void 0)throw RangeError("Invalid readableType specified");if(D.writableType!==void 0)throw RangeError("Invalid writableType specified");let K=Df(A,0),ve=Zy(A),Pe=Df(I,1),De=Zy(I),Fe,Xe=c(($t)=>{Fe=$t});if(QQ(this,Xe,Pe,De,K,ve),eX(this,D),D.start!==void 0)Fe(D.start(this._transformStreamController));else Fe(void 0)}get readable(){if(!Uz(this))throw qz("readable");return this._readable}get writable(){if(!Uz(this))throw qz("writable");return this._writable}}if(Object.defineProperties(Vf.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Vf.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function QQ(l,g,b,I,A,D){function K(){return g}function ve($t){return nX(l,$t)}function Pe($t){return oX(l,$t)}function De(){return iX(l)}l._writable=rQ(K,ve,De,Pe,b,I);function Fe(){return sX(l)}function Xe($t){return aX(l,$t)}l._readable=Ff(K,Fe,Xe,A,D),l._backpressure=void 0,l._backpressureChangePromise=void 0,l._backpressureChangePromise_resolve=void 0,ib(l,!0),l._transformStreamController=void 0}function Uz(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_transformStreamController"))return!1;return l instanceof Vf}function Lz(l,g){Eo(l._readable._readableStreamController,g),OT(l,g)}function OT(l,g){ab(l._transformStreamController),Uf(l._writable._writableStreamController,g),CT(l)}function CT(l){if(l._backpressure)ib(l,!1)}function ib(l,g){if(l._backpressureChangePromise!==void 0)l._backpressureChangePromise_resolve();l._backpressureChangePromise=c((b)=>{l._backpressureChangePromise_resolve=b}),l._backpressure=g}class Gi{constructor(){throw TypeError("Illegal constructor")}get desiredSize(){if(!sb(this))throw cb("desiredSize");let l=this._controlledTransformStream._readable._readableStreamController;return $T(l)}enqueue(l=void 0){if(!sb(this))throw cb("enqueue");jz(this,l)}error(l=void 0){if(!sb(this))throw cb("error");tX(this,l)}terminate(){if(!sb(this))throw cb("terminate");rX(this)}}if(Object.defineProperties(Gi.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),n(Gi.prototype.enqueue,"enqueue"),n(Gi.prototype.error,"error"),n(Gi.prototype.terminate,"terminate"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Gi.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function sb(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_controlledTransformStream"))return!1;return l instanceof Gi}function XQ(l,g,b,I,A){g._controlledTransformStream=l,l._transformStreamController=g,g._transformAlgorithm=b,g._flushAlgorithm=I,g._cancelAlgorithm=A,g._finishPromise=void 0,g._finishPromise_resolve=void 0,g._finishPromise_reject=void 0}function eX(l,g){let b=Object.create(Gi.prototype),I,A,D;if(g.transform!==void 0)I=(K)=>g.transform(K,b);else I=(K)=>{try{return jz(b,K),u(void 0)}catch(ve){return d(ve)}};if(g.flush!==void 0)A=()=>g.flush(b);else A=()=>u(void 0);if(g.cancel!==void 0)D=(K)=>g.cancel(K);else D=()=>u(void 0);XQ(l,b,I,A,D)}function ab(l){l._transformAlgorithm=void 0,l._flushAlgorithm=void 0,l._cancelAlgorithm=void 0}function jz(l,g){let b=l._controlledTransformStream,I=b._readable._readableStreamController;if(!dl(I))throw TypeError("Readable side is not in a state that permits enqueue");try{ll(I,g)}catch(D){throw OT(b,D),b._readable._storedError}if($Q(I)!==b._backpressure)ib(b,!0)}function tX(l,g){Lz(l._controlledTransformStream,g)}function Fz(l,g){let b=l._transformAlgorithm(g);return x(b,void 0,(I)=>{throw Lz(l._controlledTransformStream,I),I})}function rX(l){let g=l._controlledTransformStream,b=g._readable._readableStreamController;kc(b);let I=TypeError("TransformStream terminated");OT(g,I)}function nX(l,g){let b=l._transformStreamController;if(l._backpressure){let I=l._backpressureChangePromise;return x(I,()=>{let A=l._writable;if(A._state==="erroring")throw A._storedError;return Fz(b,g)})}return Fz(b,g)}function oX(l,g){let b=l._transformStreamController;if(b._finishPromise!==void 0)return b._finishPromise;let I=l._readable;b._finishPromise=c((D,K)=>{b._finishPromise_resolve=D,b._finishPromise_reject=K});let A=b._cancelAlgorithm(g);return ab(b),m(A,()=>{if(I._state==="errored")pl(b,I._storedError);else Eo(I._readableStreamController,g),zT(b);return null},(D)=>(Eo(I._readableStreamController,D),pl(b,D),null)),b._finishPromise}function iX(l){let g=l._transformStreamController;if(g._finishPromise!==void 0)return g._finishPromise;let b=l._readable;g._finishPromise=c((A,D)=>{g._finishPromise_resolve=A,g._finishPromise_reject=D});let I=g._flushAlgorithm();return ab(g),m(I,()=>{if(b._state==="errored")pl(g,b._storedError);else kc(b._readableStreamController),zT(g);return null},(A)=>(Eo(b._readableStreamController,A),pl(g,A),null)),g._finishPromise}function sX(l){return ib(l,!1),l._backpressureChangePromise}function aX(l,g){let b=l._transformStreamController;if(b._finishPromise!==void 0)return b._finishPromise;let I=l._writable;b._finishPromise=c((D,K)=>{b._finishPromise_resolve=D,b._finishPromise_reject=K});let A=b._cancelAlgorithm(g);return ab(b),m(A,()=>{if(I._state==="errored")pl(b,I._storedError);else Uf(I._writableStreamController,g),CT(l),zT(b);return null},(D)=>(Uf(I._writableStreamController,D),CT(l),pl(b,D),null)),b._finishPromise}function cb(l){return TypeError(`TransformStreamDefaultController.prototype.${l} can only be used on a TransformStreamDefaultController`)}function zT(l){if(l._finishPromise_resolve===void 0)return;l._finishPromise_resolve(),l._finishPromise_resolve=void 0,l._finishPromise_reject=void 0}function pl(l,g){if(l._finishPromise_reject===void 0)return;S(l._finishPromise),l._finishPromise_reject(g),l._finishPromise_resolve=void 0,l._finishPromise_reject=void 0}function qz(l){return TypeError(`TransformStream.prototype.${l} can only be used on a TransformStream`)}e.ByteLengthQueuingStrategy=Hf,e.CountQueuingStrategy=Gf,e.ReadableByteStreamController=ii,e.ReadableStream=kr,e.ReadableStreamBYOBReader=qi,e.ReadableStreamBYOBRequest=Qs,e.ReadableStreamDefaultController=ci,e.ReadableStreamDefaultReader=To,e.TransformStream=Vf,e.TransformStreamDefaultController=Gi,e.WritableStream=Hi,e.WritableStreamDefaultController=Ic,e.WritableStreamDefaultWriter=ai})});var Wz=oe(function(){if(!globalThis.ReadableStream)try{let e=Lt("node:process"),{emitWarning:t}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,Lt("node:stream/web")),e.emitWarning=t}catch(r){throw e.emitWarning=t,r}}catch(e){Object.assign(globalThis,Zz())}try{let{Blob:e}=Lt("buffer");if(e&&!e.prototype.stream)e.prototype.stream=function(r){let o=0,n=this;return new ReadableStream({type:"bytes",async pull(i){let a=await n.slice(o,Math.min(n.size,o+65536)).arrayBuffer();if(o+=a.byteLength,i.enqueue(new Uint8Array(a)),o===n.size)i.close()}})}}catch(e){}});async function*BT(e,t=!0){for(let r of e)if("stream"in r)yield*r.stream();else if(ArrayBuffer.isView(r))if(t){let o=r.byteOffset,n=r.byteOffset+r.byteLength;while(o!==n){let i=Math.min(n-o,Kz),s=r.buffer.slice(o,o+i);o+=s.byteLength,yield new Uint8Array(s)}}else yield r;else{let o=0,n=r;while(o!==n.size){let s=await n.slice(o,Math.min(n.size,o+Kz)).arrayBuffer();o+=s.byteLength,yield new Uint8Array(s)}}}var Rve,Kz=65536,Jz,xX,Ki;var Zf=J(()=>{Rve=rn(Wz(),1);/*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */Jz=class e{#e=[];#t="";#r=0;#n="transparent";constructor(t=[],r={}){if(typeof t!=="object"||t===null)throw TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof t[Symbol.iterator]!=="function")throw TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof r!=="object"&&typeof r!=="function")throw TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");if(r===null)r={};let o=new TextEncoder;for(let i of t){let s;if(ArrayBuffer.isView(i))s=new Uint8Array(i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength));else if(i instanceof ArrayBuffer)s=new Uint8Array(i.slice(0));else if(i instanceof e)s=i;else s=o.encode(`${i}`);this.#r+=ArrayBuffer.isView(s)?s.byteLength:s.size,this.#e.push(s)}this.#n=`${r.endings===void 0?"transparent":r.endings}`;let n=r.type===void 0?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(n)?n:""}get size(){return this.#r}get type(){return this.#t}async text(){let t=new TextDecoder,r="";for await(let o of BT(this.#e,!1))r+=t.decode(o,{stream:!0});return r+=t.decode(),r}async arrayBuffer(){let t=new Uint8Array(this.size),r=0;for await(let o of BT(this.#e,!1))t.set(o,r),r+=o.length;return t.buffer}stream(){let t=BT(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(r){let o=await t.next();o.done?r.close():r.enqueue(o.value)},async cancel(){await t.return()}})}slice(t=0,r=this.size,o=""){let{size:n}=this,i=t<0?Math.max(n+t,0):Math.min(t,n),s=r<0?Math.max(n+r,0):Math.min(r,n),a=Math.max(s-i,0),c=this.#e,u=[],d=0;for(let m of c){if(d>=a)break;let h=ArrayBuffer.isView(m)?m.byteLength:m.size;if(i&&h<=i)i-=h,s-=h;else{let y;if(ArrayBuffer.isView(m))y=m.subarray(i,Math.min(h,s)),d+=y.byteLength;else y=m.slice(i,Math.min(h,s)),d+=y.size;s-=h,u.push(y),i=0}}let p=new e([],{type:String(o).toLowerCase()});return p.#r=a,p.#e=u,p}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](t){return t&&typeof t==="object"&&typeof t.constructor==="function"&&(typeof t.stream==="function"||typeof t.arrayBuffer==="function")&&/^(Blob|File)$/.test(t[Symbol.toStringTag])}};Object.defineProperties(Jz.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});xX=Jz,Ki=xX});var vX,_X,yl;var DT=J(()=>{Zf();vX=class extends Ki{#e=0;#t="";constructor(t,r,o={}){if(arguments.length<2)throw TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(t,o);if(o===null)o={};let n=o.lastModified===void 0?Date.now():Number(o.lastModified);if(!Number.isNaN(n))this.#e=n;this.#t=String(r)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](t){return!!t&&t instanceof Ki&&/^(File)$/.test(t[Symbol.toStringTag])}},_X=vX,yl=_X});function Xz(e,t=Ki){var r=`${Yz()}${Yz()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),o=[],n=`--${r}\r
2
+ import{createRequire as yX}from"node:module";var cX=Object.create;var{getPrototypeOf:uX,defineProperty:MT,getOwnPropertyNames:lX}=Object;var dX=Object.prototype.hasOwnProperty;function pX(e){return this[e]}var fX,mX,rn=(e,t,r)=>{var o=e!=null&&typeof e==="object";if(o){var n=t?fX??=new WeakMap:mX??=new WeakMap,i=n.get(e);if(i)return i}r=e!=null?cX(uX(e)):{};let s=t||!e||!e.__esModule?MT(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of lX(e))if(!dX.call(s,a))MT(s,a,{get:pX.bind(e,a),enumerable:!0})}if(o)n.set(e,s);return s};var oe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var hX=(e)=>e;function gX(e,t){this[e]=hX.bind(null,t)}var Pn=(e,t)=>{for(var r in t)MT(e,r,{get:t[r],enumerable:!0,configurable:!0,set:gX.bind(t,r)})};var J=(e,t)=>()=>(e&&(t=e(e=0)),t);var Lt=yX(import.meta.url);var Zz=oe(function(lb,Vz){(function(e,t){typeof lb==="object"&&typeof Vz<"u"?t(lb):typeof define==="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.WebStreamsPolyfill={}))})(lb,function(e){function t(){return}function r(l){return typeof l==="object"&&l!==null||typeof l==="function"}let o=t;function n(l,g){try{Object.defineProperty(l,"name",{value:g,configurable:!0})}catch(b){}}let i=Promise,s=Promise.prototype.then,a=Promise.reject.bind(i);function c(l){return new i(l)}function u(l){return c((g)=>g(l))}function d(l){return a(l)}function p(l,g,b){return s.call(l,g,b)}function m(l,g,b){p(p(l,g,b),void 0,o)}function h(l,g){m(l,g)}function y(l,g){m(l,void 0,g)}function x(l,g,b){return p(l,g,b)}function S(l){p(l,void 0,o)}let v=(l)=>{if(typeof queueMicrotask==="function")v=queueMicrotask;else{let g=u(void 0);v=(b)=>p(g,b)}return v(l)};function E(l,g,b){if(typeof l!=="function")throw TypeError("Argument is not a function");return Function.prototype.apply.call(l,g,b)}function w(l,g,b){try{return u(E(l,g,b))}catch(I){return d(I)}}let _=16384;class T{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(l){let g=this._back,b=g;if(g._elements.length===_-1)b={_elements:[],_next:void 0};if(g._elements.push(l),b!==g)this._back=b,g._next=b;++this._size}shift(){let l=this._front,g=l,b=this._cursor,I=b+1,A=l._elements,D=A[b];if(I===_)g=l._next,I=0;if(--this._size,this._cursor=I,l!==g)this._front=g;return A[b]=void 0,D}forEach(l){let g=this._cursor,b=this._front,I=b._elements;while(g!==I.length||b._next!==void 0){if(g===I.length){if(b=b._next,I=b._elements,g=0,I.length===0)break}l(I[g]),++g}}peek(){let l=this._front,g=this._cursor;return l._elements[g]}}let P=Symbol("[[AbortSteps]]"),O=Symbol("[[ErrorSteps]]"),z=Symbol("[[CancelSteps]]"),B=Symbol("[[PullSteps]]"),k=Symbol("[[ReleaseSteps]]");function G(l,g){if(l._ownerReadableStream=g,g._reader=l,g._state==="readable")H(l);else if(g._state==="closed")we(l);else fe(l,g._storedError)}function V(l,g){let b=l._ownerReadableStream;return Io(b,g)}function ue(l){let g=l._ownerReadableStream;if(g._state==="readable")C(l,TypeError("Reader was released and can no longer be used to monitor the stream's closedness"));else U(l,TypeError("Reader was released and can no longer be used to monitor the stream's closedness"));g._readableStreamController[k](),g._reader=void 0,l._ownerReadableStream=void 0}function W(l){return TypeError("Cannot "+l+" a stream using a released reader")}function H(l){l._closedPromise=c((g,b)=>{l._closedPromise_resolve=g,l._closedPromise_reject=b})}function fe(l,g){H(l),C(l,g)}function we(l){H(l),N(l)}function C(l,g){if(l._closedPromise_reject===void 0)return;S(l._closedPromise),l._closedPromise_reject(g),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0}function U(l,g){fe(l,g)}function N(l){if(l._closedPromise_resolve===void 0)return;l._closedPromise_resolve(void 0),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0}let Y=Number.isFinite||function(l){return typeof l==="number"&&isFinite(l)},X=Math.trunc||function(l){return l<0?Math.ceil(l):Math.floor(l)};function ce(l){return typeof l==="object"||typeof l==="function"}function Z(l,g){if(l!==void 0&&!ce(l))throw TypeError(`${g} is not an object.`)}function me(l,g){if(typeof l!=="function")throw TypeError(`${g} is not a function.`)}function Me(l){return typeof l==="object"&&l!==null||typeof l==="function"}function Be(l,g){if(!Me(l))throw TypeError(`${g} is not an object.`)}function Le(l,g,b){if(l===void 0)throw TypeError(`Parameter ${g} is required in '${b}'.`)}function Ut(l,g,b){if(l===void 0)throw TypeError(`${g} is required in '${b}'.`)}function vt(l){return Number(l)}function cr(l){return l===0?0:l}function Zr(l){return cr(X(l))}function tr(l,g){let I=Number.MAX_SAFE_INTEGER,A=Number(l);if(A=cr(A),!Y(A))throw TypeError(`${g} is not a finite number`);if(A=Zr(A),A<0||A>I)throw TypeError(`${g} is outside the accepted range of 0 to ${I}, inclusive`);if(!Y(A)||A===0)return 0;return A}function En(l,g){if(!Xs(l))throw TypeError(`${g} is not a ReadableStream.`)}function Wr(l){return new To(l)}function Ws(l,g){l._reader._readRequests.push(g)}function Cf(l,g,b){let A=l._reader._readRequests.shift();if(b)A._closeSteps();else A._chunkSteps(g)}function sl(l){return l._reader._readRequests.length}function Dy(l){let g=l._reader;if(g===void 0)return!1;if(!Ks(g))return!1;return!0}class To{constructor(l){if(Le(l,1,"ReadableStreamDefaultReader"),En(l,"First parameter"),ea(l))throw TypeError("This stream has already been locked for exclusive reading by another reader");G(this,l),this._readRequests=new T}get closed(){if(!Ks(this))return d(Uy("closed"));return this._closedPromise}cancel(l=void 0){if(!Ks(this))return d(Uy("cancel"));if(this._ownerReadableStream===void 0)return d(W("cancel"));return V(this,l)}read(){if(!Ks(this))return d(Uy("read"));if(this._ownerReadableStream===void 0)return d(W("read from"));let l,g,b=c((A,D)=>{l=A,g=D});return zf(this,{_chunkSteps:(A)=>l({value:A,done:!1}),_closeSteps:()=>l({value:void 0,done:!0}),_errorSteps:(A)=>g(A)}),b}releaseLock(){if(!Ks(this))throw Uy("releaseLock");if(this._ownerReadableStream===void 0)return;TY(this)}}if(Object.defineProperties(To.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(To.prototype.cancel,"cancel"),n(To.prototype.read,"read"),n(To.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(To.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Ks(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_readRequests"))return!1;return l instanceof To}function zf(l,g){let b=l._ownerReadableStream;if(b._disturbed=!0,b._state==="closed")g._closeSteps();else if(b._state==="errored")g._errorSteps(b._storedError);else b._readableStreamController[B](g)}function TY(l){ue(l);let g=TypeError("Reader was released");DC(l,g)}function DC(l,g){let b=l._readRequests;l._readRequests=new T,b.forEach((I)=>{I._errorSteps(g)})}function Uy(l){return TypeError(`ReadableStreamDefaultReader.prototype.${l} can only be used on a ReadableStreamDefaultReader`)}let EY=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class iT{constructor(l,g){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=l,this._preventCancel=g}next(){let l=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?x(this._ongoingPromise,l,l):l(),this._ongoingPromise}return(l){let g=()=>this._returnSteps(l);return this._ongoingPromise?x(this._ongoingPromise,g,g):g()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let l=this._reader,g,b,I=c((D,K)=>{g=D,b=K});return zf(l,{_chunkSteps:(D)=>{this._ongoingPromise=void 0,v(()=>g({value:D,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,ue(l),g({value:void 0,done:!0})},_errorSteps:(D)=>{this._ongoingPromise=void 0,this._isFinished=!0,ue(l),b(D)}}),I}_returnSteps(l){if(this._isFinished)return Promise.resolve({value:l,done:!0});this._isFinished=!0;let g=this._reader;if(!this._preventCancel){let b=V(g,l);return ue(g),x(b,()=>({value:l,done:!0}))}return ue(g),u({value:l,done:!0})}}let UC={next(){if(!LC(this))return d(jC("next"));return this._asyncIteratorImpl.next()},return(l){if(!LC(this))return d(jC("return"));return this._asyncIteratorImpl.return(l)}};Object.setPrototypeOf(UC,EY);function IY(l,g){let b=Wr(l),I=new iT(b,g),A=Object.create(UC);return A._asyncIteratorImpl=I,A}function LC(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_asyncIteratorImpl"))return!1;try{return l._asyncIteratorImpl instanceof iT}catch(g){return!1}}function jC(l){return TypeError(`ReadableStreamAsyncIterator.${l} can only be used on a ReadableSteamAsyncIterator`)}let FC=Number.isNaN||function(l){return l!==l};var sT,aT,cT;function Nf(l){return l.slice()}function qC(l,g,b,I,A){new Uint8Array(l).set(new Uint8Array(b,I,A),g)}let Fi=(l)=>{if(typeof l.transfer==="function")Fi=(g)=>g.transfer();else if(typeof structuredClone==="function")Fi=(g)=>structuredClone(g,{transfer:[g]});else Fi=(g)=>g;return Fi(l)},Js=(l)=>{if(typeof l.detached==="boolean")Js=(g)=>g.detached;else Js=(g)=>g.byteLength===0;return Js(l)};function HC(l,g,b){if(l.slice)return l.slice(g,b);let I=b-g,A=new ArrayBuffer(I);return qC(A,0,l,g,I),A}function Ly(l,g){let b=l[g];if(b===void 0||b===null)return;if(typeof b!=="function")throw TypeError(`${String(g)} is not a function`);return b}function PY(l){let g={[Symbol.iterator]:()=>l.iterator},b=async function*(){return yield*g}(),I=b.next;return{iterator:b,nextMethod:I,done:!1}}let uT=(cT=(sT=Symbol.asyncIterator)!==null&&sT!==void 0?sT:(aT=Symbol.for)===null||aT===void 0?void 0:aT.call(Symbol,"Symbol.asyncIterator"))!==null&&cT!==void 0?cT:"@@asyncIterator";function GC(l,g="sync",b){if(b===void 0)if(g==="async"){if(b=Ly(l,uT),b===void 0){let D=Ly(l,Symbol.iterator),K=GC(l,"sync",D);return PY(K)}}else b=Ly(l,Symbol.iterator);if(b===void 0)throw TypeError("The object is not iterable");let I=E(b,l,[]);if(!r(I))throw TypeError("The iterator method must return an object");let A=I.next;return{iterator:I,nextMethod:A,done:!1}}function kY(l){let g=E(l.nextMethod,l.iterator,[]);if(!r(g))throw TypeError("The iterator.next() method must return an object");return g}function AY(l){return Boolean(l.done)}function $Y(l){return l.value}function RY(l){if(typeof l!=="number")return!1;if(FC(l))return!1;if(l<0)return!1;return!0}function VC(l){let g=HC(l.buffer,l.byteOffset,l.byteOffset+l.byteLength);return new Uint8Array(g)}function lT(l){let g=l._queue.shift();if(l._queueTotalSize-=g.size,l._queueTotalSize<0)l._queueTotalSize=0;return g.value}function dT(l,g,b){if(!RY(b)||b===1/0)throw RangeError("Size must be a finite, non-NaN, non-negative number.");l._queue.push({value:g,size:b}),l._queueTotalSize+=b}function OY(l){return l._queue.peek().value}function Ys(l){l._queue=new T,l._queueTotalSize=0}function ZC(l){return l===DataView}function CY(l){return ZC(l.constructor)}function zY(l){if(ZC(l))return 1;return l.BYTES_PER_ELEMENT}class Qs{constructor(){throw TypeError("Illegal constructor")}get view(){if(!pT(this))throw yT("view");return this._view}respond(l){if(!pT(this))throw yT("respond");if(Le(l,1,"respond"),l=tr(l,"First parameter"),this._associatedReadableByteStreamController===void 0)throw TypeError("This BYOB request has been invalidated");if(Js(this._view.buffer))throw TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Hy(this._associatedReadableByteStreamController,l)}respondWithNewView(l){if(!pT(this))throw yT("respondWithNewView");if(Le(l,1,"respondWithNewView"),!ArrayBuffer.isView(l))throw TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw TypeError("This BYOB request has been invalidated");if(Js(l.buffer))throw TypeError("The given view's buffer has been detached and so cannot be used as a response");Gy(this._associatedReadableByteStreamController,l)}}if(Object.defineProperties(Qs.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),n(Qs.prototype.respond,"respond"),n(Qs.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Qs.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ii{constructor(){throw TypeError("Illegal constructor")}get byobRequest(){if(!wc(this))throw Bf("byobRequest");return gT(this)}get desiredSize(){if(!wc(this))throw Bf("desiredSize");return nz(this)}close(){if(!wc(this))throw Bf("close");if(this._closeRequested)throw TypeError("The stream has already been closed; do not close it again!");let l=this._controlledReadableByteStream._state;if(l!=="readable")throw TypeError(`The stream (in ${l} state) is not in the readable state and cannot be closed`);Mf(this)}enqueue(l){if(!wc(this))throw Bf("enqueue");if(Le(l,1,"enqueue"),!ArrayBuffer.isView(l))throw TypeError("chunk must be an array buffer view");if(l.byteLength===0)throw TypeError("chunk must have non-zero byteLength");if(l.buffer.byteLength===0)throw TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw TypeError("stream is closed or draining");let g=this._controlledReadableByteStream._state;if(g!=="readable")throw TypeError(`The stream (in ${g} state) is not in the readable state and cannot be enqueued to`);qy(this,l)}error(l=void 0){if(!wc(this))throw Bf("error");Xn(this,l)}[z](l){WC(this),Ys(this);let g=this._cancelAlgorithm(l);return Fy(this),g}[B](l){let g=this._controlledReadableByteStream;if(this._queueTotalSize>0){rz(this,l);return}let b=this._autoAllocateChunkSize;if(b!==void 0){let I;try{I=new ArrayBuffer(b)}catch(D){l._errorSteps(D);return}let A={buffer:I,bufferByteLength:b,byteOffset:0,byteLength:b,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(A)}Ws(g,l),Sc(this)}[k](){if(this._pendingPullIntos.length>0){let l=this._pendingPullIntos.peek();l.readerType="none",this._pendingPullIntos=new T,this._pendingPullIntos.push(l)}}}if(Object.defineProperties(ii.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ii.prototype.close,"close"),n(ii.prototype.enqueue,"enqueue"),n(ii.prototype.error,"error"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(ii.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function wc(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_controlledReadableByteStream"))return!1;return l instanceof ii}function pT(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_associatedReadableByteStreamController"))return!1;return l instanceof Qs}function Sc(l){if(!UY(l))return;if(l._pulling){l._pullAgain=!0;return}l._pulling=!0;let b=l._pullAlgorithm();m(b,()=>{if(l._pulling=!1,l._pullAgain)l._pullAgain=!1,Sc(l);return null},(I)=>(Xn(l,I),null))}function WC(l){mT(l),l._pendingPullIntos=new T}function fT(l,g){let b=!1;if(l._state==="closed")b=!0;let I=KC(g);if(g.readerType==="default")Cf(l,I,b);else GY(l,I,b)}function KC(l){let{bytesFilled:g,elementSize:b}=l;return new l.viewConstructor(l.buffer,l.byteOffset,g/b)}function jy(l,g,b,I){l._queue.push({buffer:g,byteOffset:b,byteLength:I}),l._queueTotalSize+=I}function JC(l,g,b,I){let A;try{A=HC(g,b,b+I)}catch(D){throw Xn(l,D),D}jy(l,A,0,I)}function YC(l,g){if(g.bytesFilled>0)JC(l,g.buffer,g.byteOffset,g.bytesFilled);al(l)}function QC(l,g){let b=Math.min(l._queueTotalSize,g.byteLength-g.bytesFilled),I=g.bytesFilled+b,A=b,D=!1,K=I%g.elementSize,ve=I-K;if(ve>=g.minimumFill)A=ve-g.bytesFilled,D=!0;let Pe=l._queue;while(A>0){let De=Pe.peek(),Fe=Math.min(A,De.byteLength),Xe=g.byteOffset+g.bytesFilled;if(qC(g.buffer,Xe,De.buffer,De.byteOffset,Fe),De.byteLength===Fe)Pe.shift();else De.byteOffset+=Fe,De.byteLength-=Fe;l._queueTotalSize-=Fe,XC(l,Fe,g),A-=Fe}return D}function XC(l,g,b){b.bytesFilled+=g}function ez(l){if(l._queueTotalSize===0&&l._closeRequested)Fy(l),qf(l._controlledReadableByteStream);else Sc(l)}function mT(l){if(l._byobRequest===null)return;l._byobRequest._associatedReadableByteStreamController=void 0,l._byobRequest._view=null,l._byobRequest=null}function hT(l){while(l._pendingPullIntos.length>0){if(l._queueTotalSize===0)return;let g=l._pendingPullIntos.peek();if(QC(l,g))al(l),fT(l._controlledReadableByteStream,g)}}function NY(l){let g=l._controlledReadableByteStream._reader;while(g._readRequests.length>0){if(l._queueTotalSize===0)return;let b=g._readRequests.shift();rz(l,b)}}function MY(l,g,b,I){let A=l._controlledReadableByteStream,D=g.constructor,K=zY(D),{byteOffset:ve,byteLength:Pe}=g,De=b*K,Fe;try{Fe=Fi(g.buffer)}catch($t){I._errorSteps($t);return}let Xe={buffer:Fe,bufferByteLength:Fe.byteLength,byteOffset:ve,byteLength:Pe,bytesFilled:0,minimumFill:De,elementSize:K,viewConstructor:D,readerType:"byob"};if(l._pendingPullIntos.length>0){l._pendingPullIntos.push(Xe),sz(A,I);return}if(A._state==="closed"){let $t=new D(Xe.buffer,Xe.byteOffset,0);I._closeSteps($t);return}if(l._queueTotalSize>0){if(QC(l,Xe)){let $t=KC(Xe);ez(l),I._chunkSteps($t);return}if(l._closeRequested){let $t=TypeError("Insufficient bytes to fill elements in the given buffer");Xn(l,$t),I._errorSteps($t);return}}l._pendingPullIntos.push(Xe),sz(A,I),Sc(l)}function BY(l,g){if(g.readerType==="none")al(l);let b=l._controlledReadableByteStream;if(bT(b))while(az(b)>0){let I=al(l);fT(b,I)}}function DY(l,g,b){if(XC(l,g,b),b.readerType==="none"){YC(l,b),hT(l);return}if(b.bytesFilled<b.minimumFill)return;al(l);let I=b.bytesFilled%b.elementSize;if(I>0){let A=b.byteOffset+b.bytesFilled;JC(l,b.buffer,A-I,I)}b.bytesFilled-=I,fT(l._controlledReadableByteStream,b),hT(l)}function tz(l,g){let b=l._pendingPullIntos.peek();if(mT(l),l._controlledReadableByteStream._state==="closed")BY(l,b);else DY(l,g,b);Sc(l)}function al(l){return l._pendingPullIntos.shift()}function UY(l){let g=l._controlledReadableByteStream;if(g._state!=="readable")return!1;if(l._closeRequested)return!1;if(!l._started)return!1;if(Dy(g)&&sl(g)>0)return!0;if(bT(g)&&az(g)>0)return!0;if(nz(l)>0)return!0;return!1}function Fy(l){l._pullAlgorithm=void 0,l._cancelAlgorithm=void 0}function Mf(l){let g=l._controlledReadableByteStream;if(l._closeRequested||g._state!=="readable")return;if(l._queueTotalSize>0){l._closeRequested=!0;return}if(l._pendingPullIntos.length>0){let b=l._pendingPullIntos.peek();if(b.bytesFilled%b.elementSize!==0){let I=TypeError("Insufficient bytes to fill elements in the given buffer");throw Xn(l,I),I}}Fy(l),qf(g)}function qy(l,g){let b=l._controlledReadableByteStream;if(l._closeRequested||b._state!=="readable")return;let{buffer:I,byteOffset:A,byteLength:D}=g;if(Js(I))throw TypeError("chunk's buffer is detached and so cannot be enqueued");let K=Fi(I);if(l._pendingPullIntos.length>0){let ve=l._pendingPullIntos.peek();if(Js(ve.buffer))throw TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");if(mT(l),ve.buffer=Fi(ve.buffer),ve.readerType==="none")YC(l,ve)}if(Dy(b))if(NY(l),sl(b)===0)jy(l,K,A,D);else{if(l._pendingPullIntos.length>0)al(l);let ve=new Uint8Array(K,A,D);Cf(b,ve,!1)}else if(bT(b))jy(l,K,A,D),hT(l);else jy(l,K,A,D);Sc(l)}function Xn(l,g){let b=l._controlledReadableByteStream;if(b._state!=="readable")return;WC(l),Ys(l),Fy(l),Rz(b,g)}function rz(l,g){let b=l._queue.shift();l._queueTotalSize-=b.byteLength,ez(l);let I=new Uint8Array(b.buffer,b.byteOffset,b.byteLength);g._chunkSteps(I)}function gT(l){if(l._byobRequest===null&&l._pendingPullIntos.length>0){let g=l._pendingPullIntos.peek(),b=new Uint8Array(g.buffer,g.byteOffset+g.bytesFilled,g.byteLength-g.bytesFilled),I=Object.create(Qs.prototype);jY(I,l,b),l._byobRequest=I}return l._byobRequest}function nz(l){let g=l._controlledReadableByteStream._state;if(g==="errored")return null;if(g==="closed")return 0;return l._strategyHWM-l._queueTotalSize}function Hy(l,g){let b=l._pendingPullIntos.peek();if(l._controlledReadableByteStream._state==="closed"){if(g!==0)throw TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(g===0)throw TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(b.bytesFilled+g>b.byteLength)throw RangeError("bytesWritten out of range")}b.buffer=Fi(b.buffer),tz(l,g)}function Gy(l,g){let b=l._pendingPullIntos.peek();if(l._controlledReadableByteStream._state==="closed"){if(g.byteLength!==0)throw TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(g.byteLength===0)throw TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(b.byteOffset+b.bytesFilled!==g.byteOffset)throw RangeError("The region specified by view does not match byobRequest");if(b.bufferByteLength!==g.buffer.byteLength)throw RangeError("The buffer of view has different capacity than byobRequest");if(b.bytesFilled+g.byteLength>b.byteLength)throw RangeError("The region specified by view is larger than byobRequest");let A=g.byteLength;b.buffer=Fi(g.buffer),tz(l,A)}function oz(l,g,b,I,A,D,K){g._controlledReadableByteStream=l,g._pullAgain=!1,g._pulling=!1,g._byobRequest=null,g._queue=g._queueTotalSize=void 0,Ys(g),g._closeRequested=!1,g._started=!1,g._strategyHWM=D,g._pullAlgorithm=I,g._cancelAlgorithm=A,g._autoAllocateChunkSize=K,g._pendingPullIntos=new T,l._readableStreamController=g;let ve=b();m(u(ve),()=>(g._started=!0,Sc(g),null),(Pe)=>(Xn(g,Pe),null))}function LY(l,g,b){let I=Object.create(ii.prototype),A,D,K;if(g.start!==void 0)A=()=>g.start(I);else A=()=>{return};if(g.pull!==void 0)D=()=>g.pull(I);else D=()=>u(void 0);if(g.cancel!==void 0)K=(Pe)=>g.cancel(Pe);else K=()=>u(void 0);let ve=g.autoAllocateChunkSize;if(ve===0)throw TypeError("autoAllocateChunkSize must be greater than 0");oz(l,I,A,D,K,b,ve)}function jY(l,g,b){l._associatedReadableByteStreamController=g,l._view=b}function yT(l){return TypeError(`ReadableStreamBYOBRequest.prototype.${l} can only be used on a ReadableStreamBYOBRequest`)}function Bf(l){return TypeError(`ReadableByteStreamController.prototype.${l} can only be used on a ReadableByteStreamController`)}function FY(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.mode;return{mode:b===void 0?void 0:qY(b,`${g} has member 'mode' that`)}}function qY(l,g){if(l=`${l}`,l!=="byob")throw TypeError(`${g} '${l}' is not a valid enumeration value for ReadableStreamReaderMode`);return l}function HY(l,g){var b;Z(l,g);let I=(b=l===null||l===void 0?void 0:l.min)!==null&&b!==void 0?b:1;return{min:tr(I,`${g} has member 'min' that`)}}function iz(l){return new qi(l)}function sz(l,g){l._reader._readIntoRequests.push(g)}function GY(l,g,b){let A=l._reader._readIntoRequests.shift();if(b)A._closeSteps(g);else A._chunkSteps(g)}function az(l){return l._reader._readIntoRequests.length}function bT(l){let g=l._reader;if(g===void 0)return!1;if(!Tc(g))return!1;return!0}class qi{constructor(l){if(Le(l,1,"ReadableStreamBYOBReader"),En(l,"First parameter"),ea(l))throw TypeError("This stream has already been locked for exclusive reading by another reader");if(!wc(l._readableStreamController))throw TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");G(this,l),this._readIntoRequests=new T}get closed(){if(!Tc(this))return d(Vy("closed"));return this._closedPromise}cancel(l=void 0){if(!Tc(this))return d(Vy("cancel"));if(this._ownerReadableStream===void 0)return d(W("cancel"));return V(this,l)}read(l,g={}){if(!Tc(this))return d(Vy("read"));if(!ArrayBuffer.isView(l))return d(TypeError("view must be an array buffer view"));if(l.byteLength===0)return d(TypeError("view must have non-zero byteLength"));if(l.buffer.byteLength===0)return d(TypeError("view's buffer must have non-zero byteLength"));if(Js(l.buffer))return d(TypeError("view's buffer has been detached"));let b;try{b=HY(g,"options")}catch(Pe){return d(Pe)}let I=b.min;if(I===0)return d(TypeError("options.min must be greater than 0"));if(!CY(l)){if(I>l.length)return d(RangeError("options.min must be less than or equal to view's length"))}else if(I>l.byteLength)return d(RangeError("options.min must be less than or equal to view's byteLength"));if(this._ownerReadableStream===void 0)return d(W("read from"));let A,D,K=c((Pe,De)=>{A=Pe,D=De});return cz(this,l,I,{_chunkSteps:(Pe)=>A({value:Pe,done:!1}),_closeSteps:(Pe)=>A({value:Pe,done:!0}),_errorSteps:(Pe)=>D(Pe)}),K}releaseLock(){if(!Tc(this))throw Vy("releaseLock");if(this._ownerReadableStream===void 0)return;VY(this)}}if(Object.defineProperties(qi.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(qi.prototype.cancel,"cancel"),n(qi.prototype.read,"read"),n(qi.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(qi.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Tc(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_readIntoRequests"))return!1;return l instanceof qi}function cz(l,g,b,I){let A=l._ownerReadableStream;if(A._disturbed=!0,A._state==="errored")I._errorSteps(A._storedError);else MY(A._readableStreamController,g,b,I)}function VY(l){ue(l);let g=TypeError("Reader was released");uz(l,g)}function uz(l,g){let b=l._readIntoRequests;l._readIntoRequests=new T,b.forEach((I)=>{I._errorSteps(g)})}function Vy(l){return TypeError(`ReadableStreamBYOBReader.prototype.${l} can only be used on a ReadableStreamBYOBReader`)}function Df(l,g){let{highWaterMark:b}=l;if(b===void 0)return g;if(FC(b)||b<0)throw RangeError("Invalid highWaterMark");return b}function Zy(l){let{size:g}=l;if(!g)return()=>1;return g}function Wy(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.highWaterMark,I=l===null||l===void 0?void 0:l.size;return{highWaterMark:b===void 0?void 0:vt(b),size:I===void 0?void 0:ZY(I,`${g} has member 'size' that`)}}function ZY(l,g){return me(l,g),(b)=>vt(l(b))}function WY(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.abort,I=l===null||l===void 0?void 0:l.close,A=l===null||l===void 0?void 0:l.start,D=l===null||l===void 0?void 0:l.type,K=l===null||l===void 0?void 0:l.write;return{abort:b===void 0?void 0:KY(b,l,`${g} has member 'abort' that`),close:I===void 0?void 0:JY(I,l,`${g} has member 'close' that`),start:A===void 0?void 0:YY(A,l,`${g} has member 'start' that`),write:K===void 0?void 0:QY(K,l,`${g} has member 'write' that`),type:D}}function KY(l,g,b){return me(l,b),(I)=>w(l,g,[I])}function JY(l,g,b){return me(l,b),()=>w(l,g,[])}function YY(l,g,b){return me(l,b),(I)=>E(l,g,[I])}function QY(l,g,b){return me(l,b),(I,A)=>w(l,g,[I,A])}function lz(l,g){if(!cl(l))throw TypeError(`${g} is not a WritableStream.`)}function XY(l){if(typeof l!=="object"||l===null)return!1;try{return typeof l.aborted==="boolean"}catch(g){return!1}}let eQ=typeof AbortController==="function";function tQ(){if(eQ)return new AbortController;return}class Hi{constructor(l={},g={}){if(l===void 0)l=null;else Be(l,"First parameter");let b=Wy(g,"Second parameter"),I=WY(l,"First parameter");if(pz(this),I.type!==void 0)throw RangeError("Invalid type is specified");let D=Zy(b),K=Df(b,1);hQ(this,I,K,D)}get locked(){if(!cl(this))throw Xy("locked");return ul(this)}abort(l=void 0){if(!cl(this))return d(Xy("abort"));if(ul(this))return d(TypeError("Cannot abort a stream that already has a writer"));return Ky(this,l)}close(){if(!cl(this))return d(Xy("close"));if(ul(this))return d(TypeError("Cannot close a stream that already has a writer"));if(si(this))return d(TypeError("Cannot close an already-closing stream"));return fz(this)}getWriter(){if(!cl(this))throw Xy("getWriter");return dz(this)}}if(Object.defineProperties(Hi.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),n(Hi.prototype.abort,"abort"),n(Hi.prototype.close,"close"),n(Hi.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Hi.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function dz(l){return new ai(l)}function rQ(l,g,b,I,A=1,D=()=>1){let K=Object.create(Hi.prototype);pz(K);let ve=Object.create(Ic.prototype);return xz(K,ve,l,g,b,I,A,D),K}function pz(l){l._state="writable",l._storedError=void 0,l._writer=void 0,l._writableStreamController=void 0,l._writeRequests=new T,l._inFlightWriteRequest=void 0,l._closeRequest=void 0,l._inFlightCloseRequest=void 0,l._pendingAbortRequest=void 0,l._backpressure=!1}function cl(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_writableStreamController"))return!1;return l instanceof Hi}function ul(l){if(l._writer===void 0)return!1;return!0}function Ky(l,g){var b;if(l._state==="closed"||l._state==="errored")return u(void 0);l._writableStreamController._abortReason=g,(b=l._writableStreamController._abortController)===null||b===void 0||b.abort(g);let I=l._state;if(I==="closed"||I==="errored")return u(void 0);if(l._pendingAbortRequest!==void 0)return l._pendingAbortRequest._promise;let A=!1;if(I==="erroring")A=!0,g=void 0;let D=c((K,ve)=>{l._pendingAbortRequest={_promise:void 0,_resolve:K,_reject:ve,_reason:g,_wasAlreadyErroring:A}});if(l._pendingAbortRequest._promise=D,!A)vT(l,g);return D}function fz(l){let g=l._state;if(g==="closed"||g==="errored")return d(TypeError(`The stream (in ${g} state) is not in the writable state and cannot be closed`));let b=c((A,D)=>{let K={_resolve:A,_reject:D};l._closeRequest=K}),I=l._writer;if(I!==void 0&&l._backpressure&&g==="writable")kT(I);return gQ(l._writableStreamController),b}function nQ(l){return c((b,I)=>{let A={_resolve:b,_reject:I};l._writeRequests.push(A)})}function xT(l,g){if(l._state==="writable"){vT(l,g);return}_T(l)}function vT(l,g){let b=l._writableStreamController;l._state="erroring",l._storedError=g;let I=l._writer;if(I!==void 0)hz(I,g);if(!cQ(l)&&b._started)_T(l)}function _T(l){l._state="errored",l._writableStreamController[O]();let g=l._storedError;if(l._writeRequests.forEach((A)=>{A._reject(g)}),l._writeRequests=new T,l._pendingAbortRequest===void 0){Jy(l);return}let b=l._pendingAbortRequest;if(l._pendingAbortRequest=void 0,b._wasAlreadyErroring){b._reject(g),Jy(l);return}let I=l._writableStreamController[P](b._reason);m(I,()=>(b._resolve(),Jy(l),null),(A)=>(b._reject(A),Jy(l),null))}function oQ(l){l._inFlightWriteRequest._resolve(void 0),l._inFlightWriteRequest=void 0}function iQ(l,g){l._inFlightWriteRequest._reject(g),l._inFlightWriteRequest=void 0,xT(l,g)}function sQ(l){if(l._inFlightCloseRequest._resolve(void 0),l._inFlightCloseRequest=void 0,l._state==="erroring"){if(l._storedError=void 0,l._pendingAbortRequest!==void 0)l._pendingAbortRequest._resolve(),l._pendingAbortRequest=void 0}l._state="closed";let b=l._writer;if(b!==void 0)Sz(b)}function aQ(l,g){if(l._inFlightCloseRequest._reject(g),l._inFlightCloseRequest=void 0,l._pendingAbortRequest!==void 0)l._pendingAbortRequest._reject(g),l._pendingAbortRequest=void 0;xT(l,g)}function si(l){if(l._closeRequest===void 0&&l._inFlightCloseRequest===void 0)return!1;return!0}function cQ(l){if(l._inFlightWriteRequest===void 0&&l._inFlightCloseRequest===void 0)return!1;return!0}function uQ(l){l._inFlightCloseRequest=l._closeRequest,l._closeRequest=void 0}function lQ(l){l._inFlightWriteRequest=l._writeRequests.shift()}function Jy(l){if(l._closeRequest!==void 0)l._closeRequest._reject(l._storedError),l._closeRequest=void 0;let g=l._writer;if(g!==void 0)IT(g,l._storedError)}function wT(l,g){let b=l._writer;if(b!==void 0&&g!==l._backpressure)if(g)SQ(b);else kT(b);l._backpressure=g}class ai{constructor(l){if(Le(l,1,"WritableStreamDefaultWriter"),lz(l,"First parameter"),ul(l))throw TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=l,l._writer=this;let g=l._state;if(g==="writable"){if(!si(l)&&l._backpressure)tb(this);else Tz(this);eb(this)}else if(g==="erroring")PT(this,l._storedError),eb(this);else if(g==="closed")Tz(this),_Q(this);else{let b=l._storedError;PT(this,b),wz(this,b)}}get closed(){if(!Ec(this))return d(Pc("closed"));return this._closedPromise}get desiredSize(){if(!Ec(this))throw Pc("desiredSize");if(this._ownerWritableStream===void 0)throw Lf("desiredSize");return mQ(this)}get ready(){if(!Ec(this))return d(Pc("ready"));return this._readyPromise}abort(l=void 0){if(!Ec(this))return d(Pc("abort"));if(this._ownerWritableStream===void 0)return d(Lf("abort"));return dQ(this,l)}close(){if(!Ec(this))return d(Pc("close"));let l=this._ownerWritableStream;if(l===void 0)return d(Lf("close"));if(si(l))return d(TypeError("Cannot close an already-closing stream"));return mz(this)}releaseLock(){if(!Ec(this))throw Pc("releaseLock");if(this._ownerWritableStream===void 0)return;gz(this)}write(l=void 0){if(!Ec(this))return d(Pc("write"));if(this._ownerWritableStream===void 0)return d(Lf("write to"));return yz(this,l)}}if(Object.defineProperties(ai.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),n(ai.prototype.abort,"abort"),n(ai.prototype.close,"close"),n(ai.prototype.releaseLock,"releaseLock"),n(ai.prototype.write,"write"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(ai.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Ec(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_ownerWritableStream"))return!1;return l instanceof ai}function dQ(l,g){let b=l._ownerWritableStream;return Ky(b,g)}function mz(l){let g=l._ownerWritableStream;return fz(g)}function pQ(l){let g=l._ownerWritableStream,b=g._state;if(si(g)||b==="closed")return u(void 0);if(b==="errored")return d(g._storedError);return mz(l)}function fQ(l,g){if(l._closedPromiseState==="pending")IT(l,g);else wQ(l,g)}function hz(l,g){if(l._readyPromiseState==="pending")Ez(l,g);else TQ(l,g)}function mQ(l){let g=l._ownerWritableStream,b=g._state;if(b==="errored"||b==="erroring")return null;if(b==="closed")return 0;return vz(g._writableStreamController)}function gz(l){let g=l._ownerWritableStream,b=TypeError("Writer was released and can no longer be used to monitor the stream's closedness");hz(l,b),fQ(l,b),g._writer=void 0,l._ownerWritableStream=void 0}function yz(l,g){let b=l._ownerWritableStream,I=b._writableStreamController,A=yQ(I,g);if(b!==l._ownerWritableStream)return d(Lf("write to"));let D=b._state;if(D==="errored")return d(b._storedError);if(si(b)||D==="closed")return d(TypeError("The stream is closing or closed and cannot be written to"));if(D==="erroring")return d(b._storedError);let K=nQ(b);return bQ(I,g,A),K}let bz={};class Ic{constructor(){throw TypeError("Illegal constructor")}get abortReason(){if(!ST(this))throw ET("abortReason");return this._abortReason}get signal(){if(!ST(this))throw ET("signal");if(this._abortController===void 0)throw TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(l=void 0){if(!ST(this))throw ET("error");if(this._controlledWritableStream._state!=="writable")return;_z(this,l)}[P](l){let g=this._abortAlgorithm(l);return Yy(this),g}[O](){Ys(this)}}if(Object.defineProperties(Ic.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Ic.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function ST(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_controlledWritableStream"))return!1;return l instanceof Ic}function xz(l,g,b,I,A,D,K,ve){g._controlledWritableStream=l,l._writableStreamController=g,g._queue=void 0,g._queueTotalSize=void 0,Ys(g),g._abortReason=void 0,g._abortController=tQ(),g._started=!1,g._strategySizeAlgorithm=ve,g._strategyHWM=K,g._writeAlgorithm=I,g._closeAlgorithm=A,g._abortAlgorithm=D;let Pe=TT(g);wT(l,Pe);let De=b(),Fe=u(De);m(Fe,()=>(g._started=!0,Qy(g),null),(Xe)=>(g._started=!0,xT(l,Xe),null))}function hQ(l,g,b,I){let A=Object.create(Ic.prototype),D,K,ve,Pe;if(g.start!==void 0)D=()=>g.start(A);else D=()=>{return};if(g.write!==void 0)K=(De)=>g.write(De,A);else K=()=>u(void 0);if(g.close!==void 0)ve=()=>g.close();else ve=()=>u(void 0);if(g.abort!==void 0)Pe=(De)=>g.abort(De);else Pe=()=>u(void 0);xz(l,A,D,K,ve,Pe,b,I)}function Yy(l){l._writeAlgorithm=void 0,l._closeAlgorithm=void 0,l._abortAlgorithm=void 0,l._strategySizeAlgorithm=void 0}function gQ(l){dT(l,bz,0),Qy(l)}function yQ(l,g){try{return l._strategySizeAlgorithm(g)}catch(b){return Uf(l,b),1}}function vz(l){return l._strategyHWM-l._queueTotalSize}function bQ(l,g,b){try{dT(l,g,b)}catch(A){Uf(l,A);return}let I=l._controlledWritableStream;if(!si(I)&&I._state==="writable"){let A=TT(l);wT(I,A)}Qy(l)}function Qy(l){let g=l._controlledWritableStream;if(!l._started)return;if(g._inFlightWriteRequest!==void 0)return;if(g._state==="erroring"){_T(g);return}if(l._queue.length===0)return;let I=OY(l);if(I===bz)xQ(l);else vQ(l,I)}function Uf(l,g){if(l._controlledWritableStream._state==="writable")_z(l,g)}function xQ(l){let g=l._controlledWritableStream;uQ(g),lT(l);let b=l._closeAlgorithm();Yy(l),m(b,()=>(sQ(g),null),(I)=>(aQ(g,I),null))}function vQ(l,g){let b=l._controlledWritableStream;lQ(b);let I=l._writeAlgorithm(g);m(I,()=>{oQ(b);let A=b._state;if(lT(l),!si(b)&&A==="writable"){let D=TT(l);wT(b,D)}return Qy(l),null},(A)=>{if(b._state==="writable")Yy(l);return iQ(b,A),null})}function TT(l){return vz(l)<=0}function _z(l,g){let b=l._controlledWritableStream;Yy(l),vT(b,g)}function Xy(l){return TypeError(`WritableStream.prototype.${l} can only be used on a WritableStream`)}function ET(l){return TypeError(`WritableStreamDefaultController.prototype.${l} can only be used on a WritableStreamDefaultController`)}function Pc(l){return TypeError(`WritableStreamDefaultWriter.prototype.${l} can only be used on a WritableStreamDefaultWriter`)}function Lf(l){return TypeError("Cannot "+l+" a stream using a released writer")}function eb(l){l._closedPromise=c((g,b)=>{l._closedPromise_resolve=g,l._closedPromise_reject=b,l._closedPromiseState="pending"})}function wz(l,g){eb(l),IT(l,g)}function _Q(l){eb(l),Sz(l)}function IT(l,g){if(l._closedPromise_reject===void 0)return;S(l._closedPromise),l._closedPromise_reject(g),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0,l._closedPromiseState="rejected"}function wQ(l,g){wz(l,g)}function Sz(l){if(l._closedPromise_resolve===void 0)return;l._closedPromise_resolve(void 0),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0,l._closedPromiseState="resolved"}function tb(l){l._readyPromise=c((g,b)=>{l._readyPromise_resolve=g,l._readyPromise_reject=b}),l._readyPromiseState="pending"}function PT(l,g){tb(l),Ez(l,g)}function Tz(l){tb(l),kT(l)}function Ez(l,g){if(l._readyPromise_reject===void 0)return;S(l._readyPromise),l._readyPromise_reject(g),l._readyPromise_resolve=void 0,l._readyPromise_reject=void 0,l._readyPromiseState="rejected"}function SQ(l){tb(l)}function TQ(l,g){PT(l,g)}function kT(l){if(l._readyPromise_resolve===void 0)return;l._readyPromise_resolve(void 0),l._readyPromise_resolve=void 0,l._readyPromise_reject=void 0,l._readyPromiseState="fulfilled"}function EQ(){if(typeof globalThis<"u")return globalThis;else if(typeof self<"u")return self;else if(typeof global<"u")return global;return}let AT=EQ();function IQ(l){if(!(typeof l==="function"||typeof l==="object"))return!1;if(l.name!=="DOMException")return!1;try{return new l,!0}catch(g){return!1}}function PQ(){let l=AT===null||AT===void 0?void 0:AT.DOMException;return IQ(l)?l:void 0}function kQ(){let l=function(b,I){if(this.message=b||"",this.name=I||"Error",Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)};return n(l,"DOMException"),l.prototype=Object.create(Error.prototype),Object.defineProperty(l.prototype,"constructor",{value:l,writable:!0,configurable:!0}),l}let AQ=PQ()||kQ();function Iz(l,g,b,I,A,D){let K=Wr(l),ve=dz(g);l._disturbed=!0;let Pe=!1,De=u(void 0);return c((Fe,Xe)=>{let $t;if(D!==void 0){if($t=()=>{let Re=D.reason!==void 0?D.reason:new AQ("Aborted","AbortError"),et=[];if(!I)et.push(()=>{if(g._state==="writable")return Ky(g,Re);return u(void 0)});if(!A)et.push(()=>{if(l._state==="readable")return Io(l,Re);return u(void 0)});In(()=>Promise.all(et.map((Nt)=>Nt())),!0,Re)},D.aborted){$t();return}D.addEventListener("abort",$t)}function Vi(){return c((Re,et)=>{function Nt(qn){if(qn)Re();else p(fl(),Nt,et)}Nt(!1)})}function fl(){if(Pe)return u(!0);return p(ve._readyPromise,()=>c((Re,et)=>{zf(K,{_chunkSteps:(Nt)=>{De=p(yz(ve,Nt),void 0,t),Re(!1)},_closeSteps:()=>Re(!0),_errorSteps:et})}))}if(Zi(l,K._closedPromise,(Re)=>{if(!I)In(()=>Ky(g,Re),!0,Re);else eo(!0,Re);return null}),Zi(g,ve._closedPromise,(Re)=>{if(!A)In(()=>Io(l,Re),!0,Re);else eo(!0,Re);return null}),tn(l,K._closedPromise,()=>{if(!b)In(()=>pQ(ve));else eo();return null}),si(g)||g._state==="closed"){let Re=TypeError("the destination writable stream closed before all data could be piped to it");if(!A)In(()=>Io(l,Re),!0,Re);else eo(!0,Re)}S(Vi());function ta(){let Re=De;return p(De,()=>Re!==De?ta():void 0)}function Zi(Re,et,Nt){if(Re._state==="errored")Nt(Re._storedError);else y(et,Nt)}function tn(Re,et,Nt){if(Re._state==="closed")Nt();else h(et,Nt)}function In(Re,et,Nt){if(Pe)return;if(Pe=!0,g._state==="writable"&&!si(g))h(ta(),qn);else qn();function qn(){return m(Re(),()=>Wi(et,Nt),(ml)=>Wi(!0,ml)),null}}function eo(Re,et){if(Pe)return;if(Pe=!0,g._state==="writable"&&!si(g))h(ta(),()=>Wi(Re,et));else Wi(Re,et)}function Wi(Re,et){if(gz(ve),ue(K),D!==void 0)D.removeEventListener("abort",$t);if(Re)Xe(et);else Fe(void 0);return null}})}class ci{constructor(){throw TypeError("Illegal constructor")}get desiredSize(){if(!rb(this))throw ob("desiredSize");return $T(this)}close(){if(!rb(this))throw ob("close");if(!dl(this))throw TypeError("The stream is not in a state that permits close");kc(this)}enqueue(l=void 0){if(!rb(this))throw ob("enqueue");if(!dl(this))throw TypeError("The stream is not in a state that permits enqueue");return ll(this,l)}error(l=void 0){if(!rb(this))throw ob("error");Eo(this,l)}[z](l){Ys(this);let g=this._cancelAlgorithm(l);return nb(this),g}[B](l){let g=this._controlledReadableStream;if(this._queue.length>0){let b=lT(this);if(this._closeRequested&&this._queue.length===0)nb(this),qf(g);else jf(this);l._chunkSteps(b)}else Ws(g,l),jf(this)}[k](){}}if(Object.defineProperties(ci.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ci.prototype.close,"close"),n(ci.prototype.enqueue,"enqueue"),n(ci.prototype.error,"error"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(ci.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function rb(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_controlledReadableStream"))return!1;return l instanceof ci}function jf(l){if(!Pz(l))return;if(l._pulling){l._pullAgain=!0;return}l._pulling=!0;let b=l._pullAlgorithm();m(b,()=>{if(l._pulling=!1,l._pullAgain)l._pullAgain=!1,jf(l);return null},(I)=>(Eo(l,I),null))}function Pz(l){let g=l._controlledReadableStream;if(!dl(l))return!1;if(!l._started)return!1;if(ea(g)&&sl(g)>0)return!0;if($T(l)>0)return!0;return!1}function nb(l){l._pullAlgorithm=void 0,l._cancelAlgorithm=void 0,l._strategySizeAlgorithm=void 0}function kc(l){if(!dl(l))return;let g=l._controlledReadableStream;if(l._closeRequested=!0,l._queue.length===0)nb(l),qf(g)}function ll(l,g){if(!dl(l))return;let b=l._controlledReadableStream;if(ea(b)&&sl(b)>0)Cf(b,g,!1);else{let I;try{I=l._strategySizeAlgorithm(g)}catch(A){throw Eo(l,A),A}try{dT(l,g,I)}catch(A){throw Eo(l,A),A}}jf(l)}function Eo(l,g){let b=l._controlledReadableStream;if(b._state!=="readable")return;Ys(l),nb(l),Rz(b,g)}function $T(l){let g=l._controlledReadableStream._state;if(g==="errored")return null;if(g==="closed")return 0;return l._strategyHWM-l._queueTotalSize}function $Q(l){if(Pz(l))return!1;return!0}function dl(l){let g=l._controlledReadableStream._state;if(!l._closeRequested&&g==="readable")return!0;return!1}function kz(l,g,b,I,A,D,K){g._controlledReadableStream=l,g._queue=void 0,g._queueTotalSize=void 0,Ys(g),g._started=!1,g._closeRequested=!1,g._pullAgain=!1,g._pulling=!1,g._strategySizeAlgorithm=K,g._strategyHWM=D,g._pullAlgorithm=I,g._cancelAlgorithm=A,l._readableStreamController=g;let ve=b();m(u(ve),()=>(g._started=!0,jf(g),null),(Pe)=>(Eo(g,Pe),null))}function RQ(l,g,b,I){let A=Object.create(ci.prototype),D,K,ve;if(g.start!==void 0)D=()=>g.start(A);else D=()=>{return};if(g.pull!==void 0)K=()=>g.pull(A);else K=()=>u(void 0);if(g.cancel!==void 0)ve=(Pe)=>g.cancel(Pe);else ve=()=>u(void 0);kz(l,A,D,K,ve,b,I)}function ob(l){return TypeError(`ReadableStreamDefaultController.prototype.${l} can only be used on a ReadableStreamDefaultController`)}function OQ(l,g){if(wc(l._readableStreamController))return zQ(l);return CQ(l)}function CQ(l,g){let b=Wr(l),I=!1,A=!1,D=!1,K=!1,ve,Pe,De,Fe,Xe,$t=c((tn)=>{Xe=tn});function Vi(){if(I)return A=!0,u(void 0);return I=!0,zf(b,{_chunkSteps:(In)=>{v(()=>{A=!1;let eo=In,Wi=In;if(!D)ll(De._readableStreamController,eo);if(!K)ll(Fe._readableStreamController,Wi);if(I=!1,A)Vi()})},_closeSteps:()=>{if(I=!1,!D)kc(De._readableStreamController);if(!K)kc(Fe._readableStreamController);if(!D||!K)Xe(void 0)},_errorSteps:()=>{I=!1}}),u(void 0)}function fl(tn){if(D=!0,ve=tn,K){let In=Nf([ve,Pe]),eo=Io(l,In);Xe(eo)}return $t}function ta(tn){if(K=!0,Pe=tn,D){let In=Nf([ve,Pe]),eo=Io(l,In);Xe(eo)}return $t}function Zi(){}return De=Ff(Zi,Vi,fl),Fe=Ff(Zi,Vi,ta),y(b._closedPromise,(tn)=>{if(Eo(De._readableStreamController,tn),Eo(Fe._readableStreamController,tn),!D||!K)Xe(void 0);return null}),[De,Fe]}function zQ(l){let g=Wr(l),b=!1,I=!1,A=!1,D=!1,K=!1,ve,Pe,De,Fe,Xe,$t=c((Re)=>{Xe=Re});function Vi(Re){y(Re._closedPromise,(et)=>{if(Re!==g)return null;if(Xn(De._readableStreamController,et),Xn(Fe._readableStreamController,et),!D||!K)Xe(void 0);return null})}function fl(){if(Tc(g))ue(g),g=Wr(l),Vi(g);zf(g,{_chunkSteps:(et)=>{v(()=>{I=!1,A=!1;let Nt=et,qn=et;if(!D&&!K)try{qn=VC(et)}catch(ml){Xn(De._readableStreamController,ml),Xn(Fe._readableStreamController,ml),Xe(Io(l,ml));return}if(!D)qy(De._readableStreamController,Nt);if(!K)qy(Fe._readableStreamController,qn);if(b=!1,I)Zi();else if(A)tn()})},_closeSteps:()=>{if(b=!1,!D)Mf(De._readableStreamController);if(!K)Mf(Fe._readableStreamController);if(De._readableStreamController._pendingPullIntos.length>0)Hy(De._readableStreamController,0);if(Fe._readableStreamController._pendingPullIntos.length>0)Hy(Fe._readableStreamController,0);if(!D||!K)Xe(void 0)},_errorSteps:()=>{b=!1}})}function ta(Re,et){if(Ks(g))ue(g),g=iz(l),Vi(g);let Nt=et?Fe:De,qn=et?De:Fe;cz(g,Re,1,{_chunkSteps:(hl)=>{v(()=>{I=!1,A=!1;let gl=et?K:D;if(!(et?D:K)){let Hz;try{Hz=VC(hl)}catch(NT){Xn(Nt._readableStreamController,NT),Xn(qn._readableStreamController,NT),Xe(Io(l,NT));return}if(!gl)Gy(Nt._readableStreamController,hl);qy(qn._readableStreamController,Hz)}else if(!gl)Gy(Nt._readableStreamController,hl);if(b=!1,I)Zi();else if(A)tn()})},_closeSteps:(hl)=>{b=!1;let gl=et?K:D,ub=et?D:K;if(!gl)Mf(Nt._readableStreamController);if(!ub)Mf(qn._readableStreamController);if(hl!==void 0){if(!gl)Gy(Nt._readableStreamController,hl);if(!ub&&qn._readableStreamController._pendingPullIntos.length>0)Hy(qn._readableStreamController,0)}if(!gl||!ub)Xe(void 0)},_errorSteps:()=>{b=!1}})}function Zi(){if(b)return I=!0,u(void 0);b=!0;let Re=gT(De._readableStreamController);if(Re===null)fl();else ta(Re._view,!1);return u(void 0)}function tn(){if(b)return A=!0,u(void 0);b=!0;let Re=gT(Fe._readableStreamController);if(Re===null)fl();else ta(Re._view,!0);return u(void 0)}function In(Re){if(D=!0,ve=Re,K){let et=Nf([ve,Pe]),Nt=Io(l,et);Xe(Nt)}return $t}function eo(Re){if(K=!0,Pe=Re,D){let et=Nf([ve,Pe]),Nt=Io(l,et);Xe(Nt)}return $t}function Wi(){return}return De=$z(Wi,Zi,In),Fe=$z(Wi,tn,eo),Vi(g),[De,Fe]}function NQ(l){return r(l)&&typeof l.getReader<"u"}function MQ(l){if(NQ(l))return DQ(l.getReader());return BQ(l)}function BQ(l){let g,b=GC(l,"async"),I=t;function A(){let K;try{K=kY(b)}catch(Pe){return d(Pe)}let ve=u(K);return x(ve,(Pe)=>{if(!r(Pe))throw TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(AY(Pe))kc(g._readableStreamController);else{let Fe=$Y(Pe);ll(g._readableStreamController,Fe)}})}function D(K){let ve=b.iterator,Pe;try{Pe=Ly(ve,"return")}catch(Xe){return d(Xe)}if(Pe===void 0)return u(void 0);let De;try{De=E(Pe,ve,[K])}catch(Xe){return d(Xe)}let Fe=u(De);return x(Fe,(Xe)=>{if(!r(Xe))throw TypeError("The promise returned by the iterator.return() method must fulfill with an object");return})}return g=Ff(I,A,D,0),g}function DQ(l){let g,b=t;function I(){let D;try{D=l.read()}catch(K){return d(K)}return x(D,(K)=>{if(!r(K))throw TypeError("The promise returned by the reader.read() method must fulfill with an object");if(K.done)kc(g._readableStreamController);else{let ve=K.value;ll(g._readableStreamController,ve)}})}function A(D){try{return u(l.cancel(D))}catch(K){return d(K)}}return g=Ff(b,I,A,0),g}function UQ(l,g){Z(l,g);let b=l,I=b===null||b===void 0?void 0:b.autoAllocateChunkSize,A=b===null||b===void 0?void 0:b.cancel,D=b===null||b===void 0?void 0:b.pull,K=b===null||b===void 0?void 0:b.start,ve=b===null||b===void 0?void 0:b.type;return{autoAllocateChunkSize:I===void 0?void 0:tr(I,`${g} has member 'autoAllocateChunkSize' that`),cancel:A===void 0?void 0:LQ(A,b,`${g} has member 'cancel' that`),pull:D===void 0?void 0:jQ(D,b,`${g} has member 'pull' that`),start:K===void 0?void 0:FQ(K,b,`${g} has member 'start' that`),type:ve===void 0?void 0:qQ(ve,`${g} has member 'type' that`)}}function LQ(l,g,b){return me(l,b),(I)=>w(l,g,[I])}function jQ(l,g,b){return me(l,b),(I)=>w(l,g,[I])}function FQ(l,g,b){return me(l,b),(I)=>E(l,g,[I])}function qQ(l,g){if(l=`${l}`,l!=="bytes")throw TypeError(`${g} '${l}' is not a valid enumeration value for ReadableStreamType`);return l}function HQ(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.preventCancel;return{preventCancel:Boolean(b)}}function Az(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.preventAbort,I=l===null||l===void 0?void 0:l.preventCancel,A=l===null||l===void 0?void 0:l.preventClose,D=l===null||l===void 0?void 0:l.signal;if(D!==void 0)GQ(D,`${g} has member 'signal' that`);return{preventAbort:Boolean(b),preventCancel:Boolean(I),preventClose:Boolean(A),signal:D}}function GQ(l,g){if(!XY(l))throw TypeError(`${g} is not an AbortSignal.`)}function VQ(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.readable;Ut(b,"readable","ReadableWritablePair"),En(b,`${g} has member 'readable' that`);let I=l===null||l===void 0?void 0:l.writable;return Ut(I,"writable","ReadableWritablePair"),lz(I,`${g} has member 'writable' that`),{readable:b,writable:I}}class kr{constructor(l={},g={}){if(l===void 0)l=null;else Be(l,"First parameter");let b=Wy(g,"Second parameter"),I=UQ(l,"First parameter");if(RT(this),I.type==="bytes"){if(b.size!==void 0)throw RangeError("The strategy for a byte stream cannot have a size function");let A=Df(b,0);LY(this,I,A)}else{let A=Zy(b),D=Df(b,1);RQ(this,I,D,A)}}get locked(){if(!Xs(this))throw Ac("locked");return ea(this)}cancel(l=void 0){if(!Xs(this))return d(Ac("cancel"));if(ea(this))return d(TypeError("Cannot cancel a stream that already has a reader"));return Io(this,l)}getReader(l=void 0){if(!Xs(this))throw Ac("getReader");if(FY(l,"First parameter").mode===void 0)return Wr(this);return iz(this)}pipeThrough(l,g={}){if(!Xs(this))throw Ac("pipeThrough");Le(l,1,"pipeThrough");let b=VQ(l,"First parameter"),I=Az(g,"Second parameter");if(ea(this))throw TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(ul(b.writable))throw TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let A=Iz(this,b.writable,I.preventClose,I.preventAbort,I.preventCancel,I.signal);return S(A),b.readable}pipeTo(l,g={}){if(!Xs(this))return d(Ac("pipeTo"));if(l===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!cl(l))return d(TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let b;try{b=Az(g,"Second parameter")}catch(I){return d(I)}if(ea(this))return d(TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));if(ul(l))return d(TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));return Iz(this,l,b.preventClose,b.preventAbort,b.preventCancel,b.signal)}tee(){if(!Xs(this))throw Ac("tee");let l=OQ(this);return Nf(l)}values(l=void 0){if(!Xs(this))throw Ac("values");let g=HQ(l,"First parameter");return IY(this,g.preventCancel)}[uT](l){return this.values(l)}static from(l){return MQ(l)}}if(Object.defineProperties(kr,{from:{enumerable:!0}}),Object.defineProperties(kr.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),n(kr.from,"from"),n(kr.prototype.cancel,"cancel"),n(kr.prototype.getReader,"getReader"),n(kr.prototype.pipeThrough,"pipeThrough"),n(kr.prototype.pipeTo,"pipeTo"),n(kr.prototype.tee,"tee"),n(kr.prototype.values,"values"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(kr.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0});Object.defineProperty(kr.prototype,uT,{value:kr.prototype.values,writable:!0,configurable:!0});function Ff(l,g,b,I=1,A=()=>1){let D=Object.create(kr.prototype);RT(D);let K=Object.create(ci.prototype);return kz(D,K,l,g,b,I,A),D}function $z(l,g,b){let I=Object.create(kr.prototype);RT(I);let A=Object.create(ii.prototype);return oz(I,A,l,g,b,0,void 0),I}function RT(l){l._state="readable",l._reader=void 0,l._storedError=void 0,l._disturbed=!1}function Xs(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_readableStreamController"))return!1;return l instanceof kr}function ea(l){if(l._reader===void 0)return!1;return!0}function Io(l,g){if(l._disturbed=!0,l._state==="closed")return u(void 0);if(l._state==="errored")return d(l._storedError);qf(l);let b=l._reader;if(b!==void 0&&Tc(b)){let A=b._readIntoRequests;b._readIntoRequests=new T,A.forEach((D)=>{D._closeSteps(void 0)})}let I=l._readableStreamController[z](g);return x(I,t)}function qf(l){l._state="closed";let g=l._reader;if(g===void 0)return;if(N(g),Ks(g)){let b=g._readRequests;g._readRequests=new T,b.forEach((I)=>{I._closeSteps()})}}function Rz(l,g){l._state="errored",l._storedError=g;let b=l._reader;if(b===void 0)return;if(C(b,g),Ks(b))DC(b,g);else uz(b,g)}function Ac(l){return TypeError(`ReadableStream.prototype.${l} can only be used on a ReadableStream`)}function Oz(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.highWaterMark;return Ut(b,"highWaterMark","QueuingStrategyInit"),{highWaterMark:vt(b)}}let Cz=(l)=>l.byteLength;n(Cz,"size");class Hf{constructor(l){Le(l,1,"ByteLengthQueuingStrategy"),l=Oz(l,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!Nz(this))throw zz("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Nz(this))throw zz("size");return Cz}}if(Object.defineProperties(Hf.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Hf.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function zz(l){return TypeError(`ByteLengthQueuingStrategy.prototype.${l} can only be used on a ByteLengthQueuingStrategy`)}function Nz(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_byteLengthQueuingStrategyHighWaterMark"))return!1;return l instanceof Hf}let Mz=()=>1;n(Mz,"size");class Gf{constructor(l){Le(l,1,"CountQueuingStrategy"),l=Oz(l,"First parameter"),this._countQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!Dz(this))throw Bz("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Dz(this))throw Bz("size");return Mz}}if(Object.defineProperties(Gf.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Gf.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Bz(l){return TypeError(`CountQueuingStrategy.prototype.${l} can only be used on a CountQueuingStrategy`)}function Dz(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_countQueuingStrategyHighWaterMark"))return!1;return l instanceof Gf}function ZQ(l,g){Z(l,g);let b=l===null||l===void 0?void 0:l.cancel,I=l===null||l===void 0?void 0:l.flush,A=l===null||l===void 0?void 0:l.readableType,D=l===null||l===void 0?void 0:l.start,K=l===null||l===void 0?void 0:l.transform,ve=l===null||l===void 0?void 0:l.writableType;return{cancel:b===void 0?void 0:YQ(b,l,`${g} has member 'cancel' that`),flush:I===void 0?void 0:WQ(I,l,`${g} has member 'flush' that`),readableType:A,start:D===void 0?void 0:KQ(D,l,`${g} has member 'start' that`),transform:K===void 0?void 0:JQ(K,l,`${g} has member 'transform' that`),writableType:ve}}function WQ(l,g,b){return me(l,b),(I)=>w(l,g,[I])}function KQ(l,g,b){return me(l,b),(I)=>E(l,g,[I])}function JQ(l,g,b){return me(l,b),(I,A)=>w(l,g,[I,A])}function YQ(l,g,b){return me(l,b),(I)=>w(l,g,[I])}class Vf{constructor(l={},g={},b={}){if(l===void 0)l=null;let I=Wy(g,"Second parameter"),A=Wy(b,"Third parameter"),D=ZQ(l,"First parameter");if(D.readableType!==void 0)throw RangeError("Invalid readableType specified");if(D.writableType!==void 0)throw RangeError("Invalid writableType specified");let K=Df(A,0),ve=Zy(A),Pe=Df(I,1),De=Zy(I),Fe,Xe=c(($t)=>{Fe=$t});if(QQ(this,Xe,Pe,De,K,ve),eX(this,D),D.start!==void 0)Fe(D.start(this._transformStreamController));else Fe(void 0)}get readable(){if(!Uz(this))throw qz("readable");return this._readable}get writable(){if(!Uz(this))throw qz("writable");return this._writable}}if(Object.defineProperties(Vf.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Vf.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function QQ(l,g,b,I,A,D){function K(){return g}function ve($t){return nX(l,$t)}function Pe($t){return oX(l,$t)}function De(){return iX(l)}l._writable=rQ(K,ve,De,Pe,b,I);function Fe(){return sX(l)}function Xe($t){return aX(l,$t)}l._readable=Ff(K,Fe,Xe,A,D),l._backpressure=void 0,l._backpressureChangePromise=void 0,l._backpressureChangePromise_resolve=void 0,ib(l,!0),l._transformStreamController=void 0}function Uz(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_transformStreamController"))return!1;return l instanceof Vf}function Lz(l,g){Eo(l._readable._readableStreamController,g),OT(l,g)}function OT(l,g){ab(l._transformStreamController),Uf(l._writable._writableStreamController,g),CT(l)}function CT(l){if(l._backpressure)ib(l,!1)}function ib(l,g){if(l._backpressureChangePromise!==void 0)l._backpressureChangePromise_resolve();l._backpressureChangePromise=c((b)=>{l._backpressureChangePromise_resolve=b}),l._backpressure=g}class Gi{constructor(){throw TypeError("Illegal constructor")}get desiredSize(){if(!sb(this))throw cb("desiredSize");let l=this._controlledTransformStream._readable._readableStreamController;return $T(l)}enqueue(l=void 0){if(!sb(this))throw cb("enqueue");jz(this,l)}error(l=void 0){if(!sb(this))throw cb("error");tX(this,l)}terminate(){if(!sb(this))throw cb("terminate");rX(this)}}if(Object.defineProperties(Gi.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),n(Gi.prototype.enqueue,"enqueue"),n(Gi.prototype.error,"error"),n(Gi.prototype.terminate,"terminate"),typeof Symbol.toStringTag==="symbol")Object.defineProperty(Gi.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function sb(l){if(!r(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_controlledTransformStream"))return!1;return l instanceof Gi}function XQ(l,g,b,I,A){g._controlledTransformStream=l,l._transformStreamController=g,g._transformAlgorithm=b,g._flushAlgorithm=I,g._cancelAlgorithm=A,g._finishPromise=void 0,g._finishPromise_resolve=void 0,g._finishPromise_reject=void 0}function eX(l,g){let b=Object.create(Gi.prototype),I,A,D;if(g.transform!==void 0)I=(K)=>g.transform(K,b);else I=(K)=>{try{return jz(b,K),u(void 0)}catch(ve){return d(ve)}};if(g.flush!==void 0)A=()=>g.flush(b);else A=()=>u(void 0);if(g.cancel!==void 0)D=(K)=>g.cancel(K);else D=()=>u(void 0);XQ(l,b,I,A,D)}function ab(l){l._transformAlgorithm=void 0,l._flushAlgorithm=void 0,l._cancelAlgorithm=void 0}function jz(l,g){let b=l._controlledTransformStream,I=b._readable._readableStreamController;if(!dl(I))throw TypeError("Readable side is not in a state that permits enqueue");try{ll(I,g)}catch(D){throw OT(b,D),b._readable._storedError}if($Q(I)!==b._backpressure)ib(b,!0)}function tX(l,g){Lz(l._controlledTransformStream,g)}function Fz(l,g){let b=l._transformAlgorithm(g);return x(b,void 0,(I)=>{throw Lz(l._controlledTransformStream,I),I})}function rX(l){let g=l._controlledTransformStream,b=g._readable._readableStreamController;kc(b);let I=TypeError("TransformStream terminated");OT(g,I)}function nX(l,g){let b=l._transformStreamController;if(l._backpressure){let I=l._backpressureChangePromise;return x(I,()=>{let A=l._writable;if(A._state==="erroring")throw A._storedError;return Fz(b,g)})}return Fz(b,g)}function oX(l,g){let b=l._transformStreamController;if(b._finishPromise!==void 0)return b._finishPromise;let I=l._readable;b._finishPromise=c((D,K)=>{b._finishPromise_resolve=D,b._finishPromise_reject=K});let A=b._cancelAlgorithm(g);return ab(b),m(A,()=>{if(I._state==="errored")pl(b,I._storedError);else Eo(I._readableStreamController,g),zT(b);return null},(D)=>(Eo(I._readableStreamController,D),pl(b,D),null)),b._finishPromise}function iX(l){let g=l._transformStreamController;if(g._finishPromise!==void 0)return g._finishPromise;let b=l._readable;g._finishPromise=c((A,D)=>{g._finishPromise_resolve=A,g._finishPromise_reject=D});let I=g._flushAlgorithm();return ab(g),m(I,()=>{if(b._state==="errored")pl(g,b._storedError);else kc(b._readableStreamController),zT(g);return null},(A)=>(Eo(b._readableStreamController,A),pl(g,A),null)),g._finishPromise}function sX(l){return ib(l,!1),l._backpressureChangePromise}function aX(l,g){let b=l._transformStreamController;if(b._finishPromise!==void 0)return b._finishPromise;let I=l._writable;b._finishPromise=c((D,K)=>{b._finishPromise_resolve=D,b._finishPromise_reject=K});let A=b._cancelAlgorithm(g);return ab(b),m(A,()=>{if(I._state==="errored")pl(b,I._storedError);else Uf(I._writableStreamController,g),CT(l),zT(b);return null},(D)=>(Uf(I._writableStreamController,D),CT(l),pl(b,D),null)),b._finishPromise}function cb(l){return TypeError(`TransformStreamDefaultController.prototype.${l} can only be used on a TransformStreamDefaultController`)}function zT(l){if(l._finishPromise_resolve===void 0)return;l._finishPromise_resolve(),l._finishPromise_resolve=void 0,l._finishPromise_reject=void 0}function pl(l,g){if(l._finishPromise_reject===void 0)return;S(l._finishPromise),l._finishPromise_reject(g),l._finishPromise_resolve=void 0,l._finishPromise_reject=void 0}function qz(l){return TypeError(`TransformStream.prototype.${l} can only be used on a TransformStream`)}e.ByteLengthQueuingStrategy=Hf,e.CountQueuingStrategy=Gf,e.ReadableByteStreamController=ii,e.ReadableStream=kr,e.ReadableStreamBYOBReader=qi,e.ReadableStreamBYOBRequest=Qs,e.ReadableStreamDefaultController=ci,e.ReadableStreamDefaultReader=To,e.TransformStream=Vf,e.TransformStreamDefaultController=Gi,e.WritableStream=Hi,e.WritableStreamDefaultController=Ic,e.WritableStreamDefaultWriter=ai})});var Wz=oe(function(){if(!globalThis.ReadableStream)try{let e=Lt("node:process"),{emitWarning:t}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,Lt("node:stream/web")),e.emitWarning=t}catch(r){throw e.emitWarning=t,r}}catch(e){Object.assign(globalThis,Zz())}try{let{Blob:e}=Lt("buffer");if(e&&!e.prototype.stream)e.prototype.stream=function(r){let o=0,n=this;return new ReadableStream({type:"bytes",async pull(i){let a=await n.slice(o,Math.min(n.size,o+65536)).arrayBuffer();if(o+=a.byteLength,i.enqueue(new Uint8Array(a)),o===n.size)i.close()}})}}catch(e){}});async function*BT(e,t=!0){for(let r of e)if("stream"in r)yield*r.stream();else if(ArrayBuffer.isView(r))if(t){let o=r.byteOffset,n=r.byteOffset+r.byteLength;while(o!==n){let i=Math.min(n-o,Kz),s=r.buffer.slice(o,o+i);o+=s.byteLength,yield new Uint8Array(s)}}else yield r;else{let o=0,n=r;while(o!==n.size){let s=await n.slice(o,Math.min(n.size,o+Kz)).arrayBuffer();o+=s.byteLength,yield new Uint8Array(s)}}}var Rve,Kz=65536,Jz,xX,Ki;var Zf=J(()=>{Rve=rn(Wz(),1);/*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */Jz=class e{#e=[];#t="";#r=0;#n="transparent";constructor(t=[],r={}){if(typeof t!=="object"||t===null)throw TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof t[Symbol.iterator]!=="function")throw TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof r!=="object"&&typeof r!=="function")throw TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");if(r===null)r={};let o=new TextEncoder;for(let i of t){let s;if(ArrayBuffer.isView(i))s=new Uint8Array(i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength));else if(i instanceof ArrayBuffer)s=new Uint8Array(i.slice(0));else if(i instanceof e)s=i;else s=o.encode(`${i}`);this.#r+=ArrayBuffer.isView(s)?s.byteLength:s.size,this.#e.push(s)}this.#n=`${r.endings===void 0?"transparent":r.endings}`;let n=r.type===void 0?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(n)?n:""}get size(){return this.#r}get type(){return this.#t}async text(){let t=new TextDecoder,r="";for await(let o of BT(this.#e,!1))r+=t.decode(o,{stream:!0});return r+=t.decode(),r}async arrayBuffer(){let t=new Uint8Array(this.size),r=0;for await(let o of BT(this.#e,!1))t.set(o,r),r+=o.length;return t.buffer}stream(){let t=BT(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(r){let o=await t.next();o.done?r.close():r.enqueue(o.value)},async cancel(){await t.return()}})}slice(t=0,r=this.size,o=""){let{size:n}=this,i=t<0?Math.max(n+t,0):Math.min(t,n),s=r<0?Math.max(n+r,0):Math.min(r,n),a=Math.max(s-i,0),c=this.#e,u=[],d=0;for(let m of c){if(d>=a)break;let h=ArrayBuffer.isView(m)?m.byteLength:m.size;if(i&&h<=i)i-=h,s-=h;else{let y;if(ArrayBuffer.isView(m))y=m.subarray(i,Math.min(h,s)),d+=y.byteLength;else y=m.slice(i,Math.min(h,s)),d+=y.size;s-=h,u.push(y),i=0}}let p=new e([],{type:String(o).toLowerCase()});return p.#r=a,p.#e=u,p}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](t){return t&&typeof t==="object"&&typeof t.constructor==="function"&&(typeof t.stream==="function"||typeof t.arrayBuffer==="function")&&/^(Blob|File)$/.test(t[Symbol.toStringTag])}};Object.defineProperties(Jz.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});xX=Jz,Ki=xX});var vX,_X,yl;var DT=J(()=>{Zf();vX=class extends Ki{#e=0;#t="";constructor(t,r,o={}){if(arguments.length<2)throw TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(t,o);if(o===null)o={};let n=o.lastModified===void 0?Date.now():Number(o.lastModified);if(!Number.isNaN(n))this.#e=n;this.#t=String(r)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](t){return!!t&&t instanceof Ki&&/^(File)$/.test(t[Symbol.toStringTag])}},_X=vX,yl=_X});function Xz(e,t=Ki){var r=`${Yz()}${Yz()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),o=[],n=`--${r}\r
3
3
  Content-Disposition: form-data; name="`;return e.forEach((i,s)=>typeof i=="string"?o.push(n+UT(s)+`"\r
4
4
  \r
5
5
  ${i.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
@@ -61,12 +61,12 @@ ${vH(m)}`;super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessag
61
61
  `);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=n,this.docsPath=o,this.shortMessage=e,this.showVersion=s,this.version=a}walk(e){return OH(this,e)}};Object.defineProperty(xe,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${$H()}`}});(()=>{xe.setStaticOptions(xe.defaultStaticOptions)})()});function Ap(e,t){if(bo(e)>t)throw new l2({givenSize:bo(e),maxSize:t})}function CH(e,t){if(typeof t==="number"&&t>0&&t>bo(e)-1)throw new Mw({offset:t,position:"start",size:bo(e)})}function zH(e,t,r){if(typeof t==="number"&&typeof r==="number"&&bo(e)!==r-t)throw new Mw({offset:r,position:"end",size:bo(e)})}function c2(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 NH(e,t={}){let{dir:r,size:o=32}=t;if(o===0)return e;if(e.length>o)throw new d2({size:e.length,targetSize:o,type:"Bytes"});let n=new Uint8Array(o);for(let i=0;i<o;i++){let s=r==="right";n[s?i:o-i-1]=e[s?i:e.length-i-1]}return n}function u2(e,t={}){let{dir:r="left"}=t,o=e,n=0;for(let i=0;i<o.length-1;i++)if(o[r==="left"?i:o.length-i-1].toString()==="0")n++;else break;return o=r==="left"?o.slice(n):o.slice(0,o.length-n),o}var Bs;var MH=J(()=>{Ja();Bs={zero:48,nine:57,A:65,F:70,a:97,f:102}});function $p(e,t){if(Zt(e)>t)throw new m2({givenSize:Zt(e),maxSize:t})}function BH(e,t){if(typeof t==="number"&&t>0&&t>Zt(e)-1)throw new Bw({offset:t,position:"start",size:Zt(e)})}function DH(e,t,r){if(typeof t==="number"&&typeof r==="number"&&Zt(e)!==r-t)throw new Bw({offset:r,position:"end",size:Zt(e)})}function p2(e,t={}){let{dir:r,size:o=32}=t;if(o===0)return e;let n=e.replace("0x","");if(n.length>o*2)throw new h2({size:Math.ceil(n.length/2),targetSize:o,type:"Hex"});return`0x${n[r==="right"?"padEnd":"padStart"](o*2,"0")}`}function UH(e,t={}){let{dir:r="left"}=t,o=e.replace("0x",""),n=0;for(let i=0;i<o.length-1;i++)if(o[r==="left"?i:o.length-i-1].toString()==="0")n++;else break;if(o=r==="left"?o.slice(n):o.slice(0,o.length-n),o==="0")return"0x";if(r==="right"&&o.length%2===1)return`0x${o}0`;return`0x${o}`}var f2=J(()=>{Sr()});function Ya(e,t,r){return JSON.stringify(e,(o,n)=>{if(typeof t==="function")return t(o,n);if(typeof n==="bigint")return n.toString()+"#__bigint";return n},r)}function eye(e){if(e instanceof Uint8Array)return;if(!e)throw new zg(e);if(typeof e!=="object")throw new zg(e);if(!("BYTES_PER_ELEMENT"in e))throw new zg(e);if(e.BYTES_PER_ELEMENT!==1||e.constructor.name!=="Uint8Array")throw new zg(e)}function jH(e){if(e instanceof Uint8Array)return e;if(typeof e==="string")return Rp(e);return tye(e)}function tye(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Rp(e,t={}){let{size:r}=t,o=e;if(r)$p(e,r),o=Oi(e,r);let n=o.slice(2);if(n.length%2)n=`0${n}`;let i=n.length/2,s=new Uint8Array(i);for(let a=0,c=0;a<i;a++){let u=c2(n.charCodeAt(c++)),d=c2(n.charCodeAt(c++));if(u===void 0||d===void 0)throw new xe(`Invalid byte sequence ("${n[c-2]}${n[c-1]}" in "${n}").`);s[a]=u<<4|d}return s}function FH(e,t={}){let{size:r}=t,o=Xge.encode(e);if(typeof r==="number")return Ap(o,r),rye(o,r);return o}function rye(e,t){return NH(e,{dir:"right",size:t})}function bo(e){return e.length}function qH(e,t,r,o={}){let{strict:n}=o;CH(e,t);let i=e.slice(t,r);if(n)zH(i,t,r);return i}function HH(e,t={}){let{size:r}=t;if(typeof r<"u")Ap(e,r);let o=ar(e,t);return y2(o,t)}function GH(e,t={}){let{size:r}=t,o=e;if(typeof r<"u")Ap(o,r),o=g2(o);if(o.length>1||o[0]>1)throw new WH(o);return Boolean(o[0])}function Ri(e,t={}){let{size:r}=t;if(typeof r<"u")Ap(e,r);let o=ar(e,t);return Uw(o,t)}function VH(e,t={}){let{size:r}=t,o=e;if(typeof r<"u")Ap(o,r),o=nye(o);return Qge.decode(o)}function g2(e){return u2(e,{dir:"left"})}function nye(e){return u2(e,{dir:"right"})}function ZH(e){try{return eye(e),!0}catch{return!1}}var Qge,Xge,WH,zg,l2,Mw,d2;var Ja=J(()=>{jn();Sr();MH();f2();Qge=new TextDecoder,Xge=new TextEncoder;WH=class WH extends xe{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"})}};zg=class zg extends xe{constructor(e){super(`Value \`${typeof e==="object"?Ya(e):e}\` of type \`${typeof e}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}};l2=class l2 extends xe{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"})}};Mw=class Mw extends xe{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"})}};d2=class d2 extends xe{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 sye(e,t={}){let{strict:r=!1}=t;if(!e)throw new b2(e);if(typeof e!=="string")throw new b2(e);if(r){if(!/^0x[0-9a-fA-F]*$/.test(e))throw new x2(e)}if(!e.startsWith("0x"))throw new x2(e)}function Jt(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Op(e){if(e instanceof Uint8Array)return ar(e);if(Array.isArray(e))return ar(new Uint8Array(e));return e}function Lw(e,t={}){let r=`0x${Number(e)}`;if(typeof t.size==="number")return $p(r,t.size),Ds(r,t.size);return r}function ar(e,t={}){let r="";for(let n=0;n<e.length;n++)r+=iye[e[n]];let o=`0x${r}`;if(typeof t.size==="number")return $p(o,t.size),Oi(o,t.size);return o}function pt(e,t={}){let{signed:r,size:o}=t,n=BigInt(e),i;if(o)if(r)i=(1n<<BigInt(o)*8n-1n)-1n;else i=2n**(BigInt(o)*8n)-1n;else if(typeof e==="number")i=BigInt(Number.MAX_SAFE_INTEGER);let s=typeof i==="bigint"&&r?-i-1n:0;if(i&&n>i||n<s){let u=typeof e==="bigint"?"n":"";throw new jw({max:i?`${i}${u}`:void 0,min:`${s}${u}`,signed:r,size:o,value:`${e}${u}`})}let c=`0x${(r&&n<0?BigInt.asUintN(o*8,BigInt(n)):n).toString(16)}`;if(o)return Ds(c,o);return c}function Cp(e,t={}){return ar(oye.encode(e),t)}function Ds(e,t){return p2(e,{dir:"left",size:t})}function Oi(e,t){return p2(e,{dir:"right",size:t})}function Wt(e,t,r,o={}){let{strict:n}=o;BH(e,t);let i=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;if(n)DH(i,t,r);return i}function Zt(e){return Math.ceil((e.length-2)/2)}function v2(e){return UH(e,{dir:"left"})}function y2(e,t={}){let{signed:r}=t;if(t.size)$p(e,t.size);let o=BigInt(e);if(!r)return o;let n=(e.length-2)/2,i=(1n<<BigInt(n)*8n)-1n,s=i>>1n;if(o<=s)return o;return o-i-1n}function Uw(e,t={}){let{signed:r,size:o}=t;if(!r&&!o)return Number(e);return Number(y2(e,t))}function Ng(e,t={}){let{strict:r=!1}=t;try{return sye(e,{strict:r}),!0}catch{return!1}}var oye,iye,jw,b2,x2,m2,Bw,h2;var Sr=J(()=>{jn();f2();oye=new TextEncoder,iye=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));jw=class jw extends xe{constructor({max:e,min:t,signed:r,size:o,value:n}){super(`Number \`${n}\` is not in safe${o?` ${o*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"})}};b2=class b2 extends xe{constructor(e){super(`Value \`${typeof e==="object"?Ya(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"})}};x2=class x2 extends xe{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"})}};m2=class m2 extends xe{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"})}};Bw=class Bw extends xe{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"})}};h2=class h2 extends xe{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 KH(e){return{address:e.address,amount:pt(e.amount),index:pt(e.index),validatorIndex:pt(e.validatorIndex)}}var JH=J(()=>{Sr()});function Fw(e){return{...typeof e.baseFeePerGas==="bigint"&&{baseFeePerGas:pt(e.baseFeePerGas)},...typeof e.blobBaseFee==="bigint"&&{blobBaseFee:pt(e.blobBaseFee)},...typeof e.feeRecipient==="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit==="bigint"&&{gasLimit:pt(e.gasLimit)},...typeof e.number==="bigint"&&{number:pt(e.number)},...typeof e.prevRandao==="bigint"&&{prevRandao:pt(e.prevRandao)},...typeof e.time==="bigint"&&{time:pt(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(KH)}}}var _2=J(()=>{Sr();JH()});var QH="0x82ad56cb";var qw="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",XH="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",eG="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",zp="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033";function Mg(e){let{abi:t,args:r,bytecode:o}=e;if(!r||r.length===0)return o;let n=t.find((s)=>("type"in s)&&s.type==="constructor");if(!n)throw new K$({docsPath:w2});if(!("inputs"in n))throw new ow({docsPath:w2});if(!n.inputs||n.inputs.length===0)throw new ow({docsPath:w2});let i=yn(n.inputs,r);return Wo([o,i])}var w2="/docs/contract/encodeDeployData";var S2=J(()=>{ir();Ps()});var Qa,Nu,Bg,Dg,Ug,Lg,jg,Fg,qg,Hg,Mu,Qo;var Bu=J(()=>{op();ot();Qa=class Qa extends F{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(Qa,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(Qa,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});Nu=class Nu extends F{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${gr(t)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}};Object.defineProperty(Nu,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});Bg=class Bg extends F{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${gr(t)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}};Object.defineProperty(Bg,"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/});Dg=class Dg extends F{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(Dg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});Ug=class Ug extends F{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(`
62
62
  `),{cause:e,name:"NonceTooLowError"})}};Object.defineProperty(Ug,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});Lg=class Lg extends F{constructor({cause:e,nonce:t}={}){super(`Nonce provided for the transaction ${t?`(${t}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}};Object.defineProperty(Lg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});jg=class jg extends F{constructor({cause:e}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
63
63
  `),{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(jg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});Fg=class Fg extends F{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(Fg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});qg=class qg extends F{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(qg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});Hg=class Hg extends F{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}};Object.defineProperty(Hg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});Mu=class Mu extends F{constructor({cause:e,maxPriorityFeePerGas:t,maxFeePerGas:r}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${t?` = ${gr(t)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${r?` = ${gr(r)} gwei`:""}).`].join(`
64
- `),{cause:e,name:"TipAboveFeeCapError"})}};Object.defineProperty(Mu,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});Qo=class Qo extends F{constructor({cause:e}){super(`An error occurred while executing: ${e?.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}});function Xa(e,t){let r=(e.details||"").toLowerCase(),o=e instanceof F?e.walk((n)=>n?.code===Qa.code):e;if(o instanceof F)return new Qa({cause:e,message:o.details});if(Qa.nodeMessage.test(r))return new Qa({cause:e,message:e.details});if(Nu.nodeMessage.test(r))return new Nu({cause:e,maxFeePerGas:t?.maxFeePerGas});if(Bg.nodeMessage.test(r))return new Bg({cause:e,maxFeePerGas:t?.maxFeePerGas});if(Dg.nodeMessage.test(r))return new Dg({cause:e,nonce:t?.nonce});if(Ug.nodeMessage.test(r))return new Ug({cause:e,nonce:t?.nonce});if(Lg.nodeMessage.test(r))return new Lg({cause:e,nonce:t?.nonce});if(jg.nodeMessage.test(r))return new jg({cause:e});if(Fg.nodeMessage.test(r))return new Fg({cause:e,gas:t?.gas});if(qg.nodeMessage.test(r))return new qg({cause:e,gas:t?.gas});if(Hg.nodeMessage.test(r))return new Hg({cause:e});if(Mu.nodeMessage.test(r))return new Mu({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas});return new Qo({cause:e})}var Gg=J(()=>{ot();Bu()});function Hw(e,{docsPath:t,...r}){let o=(()=>{let n=Xa(e,r);if(n instanceof Qo)return e;return n})();return new Ag(o,{docsPath:t,...r})}var T2=J(()=>{Wa();Bu();Gg()});function ec(e,{format:t}){if(!t)return{};let r={};function o(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]))o(i[a])}}let n=t(e||{});return o(n),r}function Ci(e,t){let r={};if(typeof e.authorizationList<"u")r.authorizationList=uye(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((o)=>ht(o));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=ye(e.gas);if(typeof e.gasPrice<"u")r.gasPrice=ye(e.gasPrice);if(typeof e.maxFeePerBlobGas<"u")r.maxFeePerBlobGas=ye(e.maxFeePerBlobGas);if(typeof e.maxFeePerGas<"u")r.maxFeePerGas=ye(e.maxFeePerGas);if(typeof e.maxPriorityFeePerGas<"u")r.maxPriorityFeePerGas=ye(e.maxPriorityFeePerGas);if(typeof e.nonce<"u")r.nonce=ye(e.nonce);if(typeof e.to<"u")r.to=e.to;if(typeof e.type<"u")r.type=cye[e.type];if(typeof e.value<"u")r.value=ye(e.value);return r}function uye(e){return e.map((t)=>({address:t.address,r:t.r?ye(BigInt(t.r)):t.r,s:t.s?ye(BigInt(t.s)):t.s,chainId:ye(t.chainId),nonce:ye(t.nonce),...typeof t.yParity<"u"?{yParity:ye(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:ye(t.v)}:{}}))}var cye;var Np=J(()=>{We();cye={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"}});function Gw(){let e=()=>{return},t=()=>{return};return{promise:new Promise((o,n)=>{e=o,t=n}),resolve:e,reject:t}}function Vw({fn:e,id:t,shouldSplitBatch:r,wait:o=0,sort:n}){let i=async()=>{let d=c();s();let p=d.map(({args:m})=>m);if(p.length===0)return;e(p).then((m)=>{if(n&&Array.isArray(m))m.sort(n);for(let h=0;h<d.length;h++){let{resolve:y}=d[h];y?.([m[h],m])}}).catch((m)=>{for(let h=0;h<d.length;h++){let{reject:y}=d[h];y?.(m)}})},s=()=>E2.delete(t),a=()=>c().map(({args:d})=>d),c=()=>E2.get(t)||[],u=(d)=>E2.set(t,[...c(),d]);return{flush:s,async schedule(d){let{promise:p,resolve:m,reject:h}=Gw();if(r?.([...a(),d]))i();if(c().length>0)return u({args:d,resolve:m,reject:h}),p;return u({args:d,resolve:m,reject:h}),setTimeout(i,o),p}}}var E2;var I2=J(()=>{E2=new Map});function tG(e){if(!e||e.length===0)return;return e.reduce((t,{slot:r,value:o})=>{if(r.length!==66)throw new uw({size:r.length,targetSize:66,type:"hex"});if(o.length!==66)throw new uw({size:o.length,targetSize:66,type:"hex"});return t[r]=o,t},{})}function lye(e){let{balance:t,nonce:r,state:o,stateDiff:n,code:i}=e,s={};if(i!==void 0)s.code=i;if(t!==void 0)s.balance=ye(t);if(r!==void 0)s.nonce=ye(r);if(o!==void 0)s.state=tG(o);if(n!==void 0){if(s.state)throw new KR;s.stateDiff=tG(n)}return s}function Mp(e){if(!e)return;let t={};for(let{address:r,...o}of e){if(!lr(r,{strict:!1}))throw new hn({address:r});if(t[r])throw new WR({address:r});t[r]=lye(o)}return t}var Zw=J(()=>{_u();lw();JR();Is();We()});var xNe,vNe,_Ne,wNe,SNe,TNe,ENe,INe,PNe,kNe,ANe,$Ne,RNe,ONe,CNe,zNe,NNe,MNe,BNe,DNe,UNe,LNe,jNe,FNe,qNe,HNe,GNe,VNe,ZNe,WNe,KNe,JNe,YNe,QNe,XNe,eMe,tMe,rMe,nMe,oMe,iMe,sMe,aMe,cMe,uMe,lMe,dMe,pMe,fMe,mMe,hMe,gMe,yMe,bMe,xMe,vMe,_Me,wMe,SMe,TMe,EMe,IMe,PMe,kMe,AMe,$Me,RMe,OMe,CMe,zMe,NMe,MMe,BMe,DMe,UMe,LMe,jMe,FMe,qMe,HMe,GMe,VMe,ZMe,WMe,KMe,JMe,YMe,QMe,XMe,e4e,t4e,r4e,n4e,o4e,i4e,rG;var nG=J(()=>{xNe=2n**(8n-1n)-1n,vNe=2n**(16n-1n)-1n,_Ne=2n**(24n-1n)-1n,wNe=2n**(32n-1n)-1n,SNe=2n**(40n-1n)-1n,TNe=2n**(48n-1n)-1n,ENe=2n**(56n-1n)-1n,INe=2n**(64n-1n)-1n,PNe=2n**(72n-1n)-1n,kNe=2n**(80n-1n)-1n,ANe=2n**(88n-1n)-1n,$Ne=2n**(96n-1n)-1n,RNe=2n**(104n-1n)-1n,ONe=2n**(112n-1n)-1n,CNe=2n**(120n-1n)-1n,zNe=2n**(128n-1n)-1n,NNe=2n**(136n-1n)-1n,MNe=2n**(144n-1n)-1n,BNe=2n**(152n-1n)-1n,DNe=2n**(160n-1n)-1n,UNe=2n**(168n-1n)-1n,LNe=2n**(176n-1n)-1n,jNe=2n**(184n-1n)-1n,FNe=2n**(192n-1n)-1n,qNe=2n**(200n-1n)-1n,HNe=2n**(208n-1n)-1n,GNe=2n**(216n-1n)-1n,VNe=2n**(224n-1n)-1n,ZNe=2n**(232n-1n)-1n,WNe=2n**(240n-1n)-1n,KNe=2n**(248n-1n)-1n,JNe=2n**(256n-1n)-1n,YNe=-(2n**(8n-1n)),QNe=-(2n**(16n-1n)),XNe=-(2n**(24n-1n)),eMe=-(2n**(32n-1n)),tMe=-(2n**(40n-1n)),rMe=-(2n**(48n-1n)),nMe=-(2n**(56n-1n)),oMe=-(2n**(64n-1n)),iMe=-(2n**(72n-1n)),sMe=-(2n**(80n-1n)),aMe=-(2n**(88n-1n)),cMe=-(2n**(96n-1n)),uMe=-(2n**(104n-1n)),lMe=-(2n**(112n-1n)),dMe=-(2n**(120n-1n)),pMe=-(2n**(128n-1n)),fMe=-(2n**(136n-1n)),mMe=-(2n**(144n-1n)),hMe=-(2n**(152n-1n)),gMe=-(2n**(160n-1n)),yMe=-(2n**(168n-1n)),bMe=-(2n**(176n-1n)),xMe=-(2n**(184n-1n)),vMe=-(2n**(192n-1n)),_Me=-(2n**(200n-1n)),wMe=-(2n**(208n-1n)),SMe=-(2n**(216n-1n)),TMe=-(2n**(224n-1n)),EMe=-(2n**(232n-1n)),IMe=-(2n**(240n-1n)),PMe=-(2n**(248n-1n)),kMe=-(2n**(256n-1n)),AMe=2n**8n-1n,$Me=2n**16n-1n,RMe=2n**24n-1n,OMe=2n**32n-1n,CMe=2n**40n-1n,zMe=2n**48n-1n,NMe=2n**56n-1n,MMe=2n**64n-1n,BMe=2n**72n-1n,DMe=2n**80n-1n,UMe=2n**88n-1n,LMe=2n**96n-1n,jMe=2n**104n-1n,FMe=2n**112n-1n,qMe=2n**120n-1n,HMe=2n**128n-1n,GMe=2n**136n-1n,VMe=2n**144n-1n,ZMe=2n**152n-1n,WMe=2n**160n-1n,KMe=2n**168n-1n,JMe=2n**176n-1n,YMe=2n**184n-1n,QMe=2n**192n-1n,XMe=2n**200n-1n,e4e=2n**208n-1n,t4e=2n**216n-1n,r4e=2n**224n-1n,n4e=2n**232n-1n,o4e=2n**240n-1n,i4e=2n**248n-1n,rG=2n**256n-1n});function xo(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:o,to:n}=e,i=t?Ft(t):void 0;if(i&&!lr(i.address))throw new hn({address:i.address});if(n&&!lr(n))throw new hn({address:n});if(r&&r>rG)throw new Nu({maxFeePerGas:r});if(o&&r&&o>r)throw new Mu({maxFeePerGas:r,maxPriorityFeePerGas:o})}var Du=J(()=>{nG();_u();Bu();Is()});var P2,k2,A2;var oG=J(()=>{ot();P2=class P2 extends F{constructor({callbackSelector:e,cause:t,data:r,extraData:o,sender:n,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)=>` ${Au(s)}`)],` Sender: ${n}`,` Data: ${r}`,` Callback selector: ${e}`,` Extra data: ${o}`].flat(),name:"OffchainLookupError"})}};k2=class k2 extends F{constructor({result:e,url:t}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${Au(t)}`,`Response: ${dt(e)}`],name:"OffchainLookupResponseMalformedError"})}};A2=class A2 extends F{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"})}}});function Xo(e,t){if(!lr(e,{strict:!1}))throw new hn({address:e});if(!lr(t,{strict:!1}))throw new hn({address:t});return e.toLowerCase()===t.toLowerCase()}var Bp=J(()=>{_u();Is()});var aG={};Pn(aG,{ccipRequest:()=>sG,offchainLookup:()=>pye,offchainLookupAbiItem:()=>iG,offchainLookupSignature:()=>dye});async function pye(e,{blockNumber:t,blockTag:r,data:o,to:n}){let{args:i}=Rw({data:o,abi:[iG]}),[s,a,c,u,d]=i,{ccipRead:p}=e,m=p&&typeof p?.request==="function"?p.request:sG;try{if(!Xo(n,s))throw new A2({sender:s,to:n});let h=a.includes(Ns)?await s2({data:c,ccipRequest:m}):await m({data:c,sender:s,urls:a}),{data:y}=await vo(e,{blockNumber:t,blockTag:r,data:Fr([u,yn([{type:"bytes"},{type:"bytes"}],[h,d])]),to:n});return y}catch(h){throw new P2({callbackSelector:u,cause:h,data:o,extraData:d,sender:s,urls:a})}}async function sG({data:e,sender:t,urls:r}){let o=Error("An unknown error occurred.");for(let n=0;n<r.length;n++){let i=r[n],s=i.includes("{data}")?"GET":"POST",a=s==="POST"?{data:e,sender:t}:void 0,c=s==="POST"?{"Content-Type":"application/json"}:{};try{let u=await fetch(i.replace("{sender}",t.toLowerCase()).replace("{data}",e),{body:JSON.stringify(a),headers:c,method:s}),d;if(u.headers.get("Content-Type")?.startsWith("application/json"))d=(await u.json()).data;else d=await u.text();if(!u.ok){o=new Jo({body:a,details:d?.error?dt(d.error):u.statusText,headers:u.headers,status:u.status,url:i});continue}if(!sr(d)){o=new k2({result:d,url:i});continue}return d}catch(u){o=new Jo({body:a,details:u.message,url:i})}}throw o}var dye="0x556f1830",iG;var cG=J(()=>{Uu();oG();Ru();GR();Ps();Bp();Rg();iG={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 vo(e,t){let{account:r=e.account,authorizationList:o,batch:n=Boolean(e.batch?.multicall),blockNumber:i,blockTag:s=e.experimental_blockTag??"latest",accessList:a,blobs:c,blockOverrides:u,code:d,data:p,factory:m,factoryData:h,gas:y,gasPrice:x,maxFeePerBlobGas:S,maxFeePerGas:v,maxPriorityFeePerGas:E,nonce:w,to:_,value:T,stateOverride:P,...O}=t,z=r?Ft(r):void 0;if(d&&(m||h))throw new F("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(d&&_)throw new F("Cannot provide both `code` & `to` as parameters.");let B=d&&p,k=m&&h&&_&&p,G=B||k,V=(()=>{if(B)return uG({code:d,data:p});if(k)return hye({data:p,factory:m,factoryData:h,to:_});return p})();try{xo(t);let W=(typeof i==="bigint"?ye(i):void 0)||s,H=u?Fw(u):void 0,fe=Mp(P),we=e.chain?.formatters?.transactionRequest?.format,U=(we||Ci)({...ec(O,{format:we}),accessList:a,account:z,authorizationList:o,blobs:c,data:V,gas:y,gasPrice:x,maxFeePerBlobGas:S,maxFeePerGas:v,maxPriorityFeePerGas:E,nonce:w,to:G?void 0:_,value:T},"call");if(n&&fye({request:U})&&!fe&&!H)try{return await mye(e,{...U,blockNumber:i,blockTag:s})}catch(X){if(!(X instanceof kw)&&!(X instanceof rp))throw X}let N=(()=>{let X=[U,W];if(fe&&H)return[...X,fe,H];if(fe)return[...X,fe];if(H)return[...X,{},H];return X})(),Y=await e.request({method:"eth_call",params:N});if(Y==="0x")return{data:void 0};return{data:Y}}catch(ue){let W=gye(ue),{offchainLookup:H,offchainLookupSignature:fe}=await Promise.resolve().then(() => (cG(),aG));if(e.ccipRead!==!1&&W?.slice(0,10)===fe&&_)return{data:await H(e,{data:W,to:_})};if(G&&W?.slice(0,10)==="0x101bb98d")throw new r2({factory:m});throw Hw(ue,{...t,account:z,chain:e.chain})}}function fye({request:e}){let{data:t,to:r,...o}=e;if(!t)return!1;if(t.startsWith(QH))return!1;if(!r)return!1;if(Object.values(o).filter((n)=>typeof n<"u").length>0)return!1;return!0}async function mye(e,t){let{batchSize:r=1024,deployless:o=!1,wait:n=0}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},{blockNumber:i,blockTag:s=e.experimental_blockTag??"latest",data:a,to:c}=t,u=(()=>{if(o)return null;if(t.multicallAddress)return t.multicallAddress;if(e.chain)return go({blockNumber:i,chain:e.chain,contract:"multicall3"});throw new kw})(),p=(typeof i==="bigint"?ye(i):void 0)||s,{schedule:m}=Vw({id:`${e.uid}.${p}`,wait:n,shouldSplitBatch(x){return x.reduce((v,{data:E})=>v+(E.length-2),0)>r*2},fn:async(x)=>{let S=x.map((w)=>({allowFailure:!0,callData:w.data,target:w.to})),v=Kt({abi:qo,args:[S],functionName:"aggregate3"}),E=await e.request({method:"eth_call",params:[{...u===null?{data:uG({code:zp,data:v})}:{to:u,data:v}},p]});return Xr({abi:qo,args:[S],functionName:"aggregate3",data:E||"0x"})}}),[{returnData:h,success:y}]=await m({data:a,to:c});if(!y)throw new zs({data:h});if(h==="0x")return{data:void 0};return{data:h}}function uG(e){let{code:t,data:r}=e;return Mg({abi:Tw(["constructor(bytes, bytes)"]),bytecode:qw,args:[t,r]})}function hye(e){let{data:t,factory:r,factoryData:o,to:n}=e;return Mg({abi:Tw(["constructor(address, bytes, address, bytes)"]),bytecode:XH,args:[n,t,r,o]})}function gye(e){if(!(e instanceof F))return;let t=e.walk();return typeof t?.data==="object"?t.data?.data:t.data}var Uu=J(()=>{ep();_2();Pi();ot();HR();Wa();Os();S2();ho();Pu();We();T2();Np();I2();Zw();Du()});var N2,M2=(e,t,r)=>new N2(e,t).update(r).digest();var SG=J(()=>{lo();N2=class N2 extends du{constructor(e,t){super();this.finished=!1,this.destroyed=!1,Y3(e);let r=lu(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 o=this.blockLen,n=new Uint8Array(o);n.set(r.length>o?e.create().update(r).digest():r);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),uo(n)}update(e){return ms(this),this.iHash.update(e),this}digestInto(e){ms(this),Lo(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:o,destroyed:n,blockLen:i,outputLen:s}=this;return e=e,e.finished=o,e.destroyed=n,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()}};M2.create=(e,t)=>new N2(e,t)});function TG(e){if(e.lowS!==void 0)Si("lowS",e.lowS);if(e.prehash!==void 0)Si("prehash",e.prehash)}function Sye(e){let t=cg(e);Fo(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:o,a:n}=t;if(r){if(!o.eql(n,o.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 B2(e,t){return La(Ti(e,t))}function Tye(e){let t=Sye(e),{Fp:r}=t,o=vs(t.n,t.nBitLength),n=t.toBytes||((w,_,T)=>{let P=_.toAffine();return vr(Uint8Array.from([4]),r.toBytes(P.x),r.toBytes(P.y))}),i=t.fromBytes||((w)=>{let _=w.subarray(1),T=r.fromBytes(_.subarray(0,r.BYTES)),P=r.fromBytes(_.subarray(r.BYTES,2*r.BYTES));return{x:T,y:P}});function s(w){let{a:_,b:T}=t,P=r.sqr(w),O=r.mul(P,w);return r.add(r.add(O,r.mul(w,_)),T)}function a(w,_){let T=r.sqr(_),P=s(w);return r.eql(T,P)}if(!a(t.Gx,t.Gy))throw Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,Zg),D2),u=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,u)))throw Error("bad curve params: a or b");function d(w){return hu(w,kt,t.n)}function p(w){let{allowedPrivateKeyLengths:_,nByteLength:T,wrapPrivateKey:P,n:O}=t;if(_&&typeof w!=="bigint"){if(Ld(w))w=La(w);if(typeof w!=="string"||!_.includes(w.length))throw Error("invalid private key");w=w.padStart(T*2,"0")}let z;try{z=typeof w==="bigint"?w:Bn(yt("private key",w,T))}catch(B){throw Error("invalid private key, expected hex or "+T+" bytes, got "+typeof w)}if(P)z=lt(z,O);return pn("private key",z,kt,O),z}function m(w){if(!(w instanceof x))throw Error("ProjectivePoint expected")}let h=Fd((w,_)=>{let{px:T,py:P,pz:O}=w;if(r.eql(O,r.ONE))return{x:T,y:P};let z=w.is0();if(_==null)_=z?r.ONE:r.inv(O);let B=r.mul(T,_),k=r.mul(P,_),G=r.mul(O,_);if(z)return{x:r.ZERO,y:r.ZERO};if(!r.eql(G,r.ONE))throw Error("invZ was invalid");return{x:B,y:k}}),y=Fd((w)=>{if(w.is0()){if(t.allowInfinityPoint&&!r.is0(w.py))return;throw Error("bad point: ZERO")}let{x:_,y:T}=w.toAffine();if(!r.isValid(_)||!r.isValid(T))throw Error("bad point: x or y not FE");if(!a(_,T))throw Error("bad point: equation left != right");if(!w.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class x{constructor(w,_,T){if(w==null||!r.isValid(w))throw Error("x required");if(_==null||!r.isValid(_)||r.is0(_))throw Error("y required");if(T==null||!r.isValid(T))throw Error("z required");this.px=w,this.py=_,this.pz=T,Object.freeze(this)}static fromAffine(w){let{x:_,y:T}=w||{};if(!w||!r.isValid(_)||!r.isValid(T))throw Error("invalid affine point");if(w instanceof x)throw Error("projective point not allowed");let P=(O)=>r.eql(O,r.ZERO);if(P(_)&&P(T))return x.ZERO;return new x(_,T,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){let _=xs(r,w.map((T)=>T.pz));return w.map((T,P)=>T.toAffine(_[P])).map(x.fromAffine)}static fromHex(w){let _=x.fromAffine(i(yt("pointHex",w)));return _.assertValidity(),_}static fromPrivateKey(w){return x.BASE.multiply(p(w))}static msm(w,_){return H_(x,o,w,_)}_setWindowSize(w){E.setWindowSize(this,w)}assertValidity(){y(this)}hasEvenY(){let{y:w}=this.toAffine();if(r.isOdd)return!r.isOdd(w);throw Error("Field doesn't support isOdd")}equals(w){m(w);let{px:_,py:T,pz:P}=this,{px:O,py:z,pz:B}=w,k=r.eql(r.mul(_,B),r.mul(O,P)),G=r.eql(r.mul(T,B),r.mul(z,P));return k&&G}negate(){return new x(this.px,r.neg(this.py),this.pz)}double(){let{a:w,b:_}=t,T=r.mul(_,Zg),{px:P,py:O,pz:z}=this,B=r.ZERO,k=r.ZERO,G=r.ZERO,V=r.mul(P,P),ue=r.mul(O,O),W=r.mul(z,z),H=r.mul(P,O);return H=r.add(H,H),G=r.mul(P,z),G=r.add(G,G),B=r.mul(w,G),k=r.mul(T,W),k=r.add(B,k),B=r.sub(ue,k),k=r.add(ue,k),k=r.mul(B,k),B=r.mul(H,B),G=r.mul(T,G),W=r.mul(w,W),H=r.sub(V,W),H=r.mul(w,H),H=r.add(H,G),G=r.add(V,V),V=r.add(G,V),V=r.add(V,W),V=r.mul(V,H),k=r.add(k,V),W=r.mul(O,z),W=r.add(W,W),V=r.mul(W,H),B=r.sub(B,V),G=r.mul(W,ue),G=r.add(G,G),G=r.add(G,G),new x(B,k,G)}add(w){m(w);let{px:_,py:T,pz:P}=this,{px:O,py:z,pz:B}=w,k=r.ZERO,G=r.ZERO,V=r.ZERO,ue=t.a,W=r.mul(t.b,Zg),H=r.mul(_,O),fe=r.mul(T,z),we=r.mul(P,B),C=r.add(_,T),U=r.add(O,z);C=r.mul(C,U),U=r.add(H,fe),C=r.sub(C,U),U=r.add(_,P);let N=r.add(O,B);return U=r.mul(U,N),N=r.add(H,we),U=r.sub(U,N),N=r.add(T,P),k=r.add(z,B),N=r.mul(N,k),k=r.add(fe,we),N=r.sub(N,k),V=r.mul(ue,U),k=r.mul(W,we),V=r.add(k,V),k=r.sub(fe,V),V=r.add(fe,V),G=r.mul(k,V),fe=r.add(H,H),fe=r.add(fe,H),we=r.mul(ue,we),U=r.mul(W,U),fe=r.add(fe,we),we=r.sub(H,we),we=r.mul(ue,we),U=r.add(U,we),H=r.mul(fe,U),G=r.add(G,H),H=r.mul(N,U),k=r.mul(C,k),k=r.sub(k,H),H=r.mul(C,fe),V=r.mul(N,V),V=r.add(V,H),new x(k,G,V)}subtract(w){return this.add(w.negate())}is0(){return this.equals(x.ZERO)}wNAF(w){return E.wNAFCached(this,w,x.normalizeZ)}multiplyUnsafe(w){let{endo:_,n:T}=t;pn("scalar",w,ei,T);let P=x.ZERO;if(w===ei)return P;if(this.is0()||w===kt)return this;if(!_||E.hasPrecomputes(this))return E.wNAFCachedUnsafe(this,w,x.normalizeZ);let{k1neg:O,k1:z,k2neg:B,k2:k}=_.splitScalar(w),G=P,V=P,ue=this;while(z>ei||k>ei){if(z&kt)G=G.add(ue);if(k&kt)V=V.add(ue);ue=ue.double(),z>>=kt,k>>=kt}if(O)G=G.negate();if(B)V=V.negate();return V=new x(r.mul(V.px,_.beta),V.py,V.pz),G.add(V)}multiply(w){let{endo:_,n:T}=t;pn("scalar",w,kt,T);let P,O;if(_){let{k1neg:z,k1:B,k2neg:k,k2:G}=_.splitScalar(w),{p:V,f:ue}=this.wNAF(B),{p:W,f:H}=this.wNAF(G);V=E.constTimeNegate(z,V),W=E.constTimeNegate(k,W),W=new x(r.mul(W.px,_.beta),W.py,W.pz),P=V.add(W),O=ue.add(H)}else{let{p:z,f:B}=this.wNAF(w);P=z,O=B}return x.normalizeZ([P,O])[0]}multiplyAndAddUnsafe(w,_,T){let P=x.BASE,O=(B,k)=>k===ei||k===kt||!B.equals(P)?B.multiplyUnsafe(k):B.multiply(k),z=O(this,_).add(O(w,T));return z.is0()?void 0:z}toAffine(w){return h(this,w)}isTorsionFree(){let{h:w,isTorsionFree:_}=t;if(w===kt)return!0;if(_)return _(x,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:w,clearCofactor:_}=t;if(w===kt)return this;if(_)return _(x,this);return this.multiplyUnsafe(t.h)}toRawBytes(w=!0){return Si("isCompressed",w),this.assertValidity(),n(x,this,w)}toHex(w=!0){return Si("isCompressed",w),La(this.toRawBytes(w))}}x.BASE=new x(t.Gx,t.Gy,r.ONE),x.ZERO=new x(r.ZERO,r.ONE,r.ZERO);let{endo:S,nBitLength:v}=t,E=q_(x,S?Math.ceil(v/2):v);return{CURVE:t,ProjectivePoint:x,normPrivateKeyToScalar:p,weierstrassEquation:s,isWithinCurveOrder:d}}function Eye(e){let t=cg(e);return Fo(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function IG(e){let t=Eye(e),{Fp:r,n:o,nByteLength:n,nBitLength:i}=t,s=r.BYTES+1,a=2*r.BYTES+1;function c(H){return lt(H,o)}function u(H){return j_(H,o)}let{ProjectivePoint:d,normPrivateKeyToScalar:p,weierstrassEquation:m,isWithinCurveOrder:h}=Tye({...t,toBytes(H,fe,we){let C=fe.toAffine(),U=r.toBytes(C.x),N=vr;if(Si("isCompressed",we),we)return N(Uint8Array.from([fe.hasEvenY()?2:3]),U);else return N(Uint8Array.from([4]),U,r.toBytes(C.y))},fromBytes(H){let fe=H.length,we=H[0],C=H.subarray(1);if(fe===s&&(we===2||we===3)){let U=Bn(C);if(!hu(U,kt,r.ORDER))throw Error("Point is not on curve");let N=m(U),Y;try{Y=r.sqrt(N)}catch(Z){let me=Z instanceof Error?": "+Z.message:"";throw Error("Point is not on curve"+me)}let X=(Y&kt)===kt;if((we&1)===1!==X)Y=r.neg(Y);return{x:U,y:Y}}else if(fe===a&&we===4){let U=r.fromBytes(C.subarray(0,r.BYTES)),N=r.fromBytes(C.subarray(r.BYTES,2*r.BYTES));return{x:U,y:N}}else{let U=s,N=a;throw Error("invalid Point, expected length of "+U+", or uncompressed "+N+", got "+fe)}}});function y(H){let fe=o>>kt;return H>fe}function x(H){return y(H)?c(-H):H}let S=(H,fe,we)=>Bn(H.slice(fe,we));class v{constructor(H,fe,we){if(pn("r",H,kt,o),pn("s",fe,kt,o),this.r=H,this.s=fe,we!=null)this.recovery=we;Object.freeze(this)}static fromCompact(H){let fe=n;return H=yt("compactSignature",H,fe*2),new v(S(H,0,fe),S(H,fe,2*fe))}static fromDER(H){let{r:fe,s:we}=Us.toSig(yt("DER",H));return new v(fe,we)}assertValidity(){}addRecoveryBit(H){return new v(this.r,this.s,H)}recoverPublicKey(H){let{r:fe,s:we,recovery:C}=this,U=O(yt("msgHash",H));if(C==null||![0,1,2,3].includes(C))throw Error("recovery id invalid");let N=C===2||C===3?fe+t.n:fe;if(N>=r.ORDER)throw Error("recovery id 2 or 3 invalid");let Y=(C&1)===0?"02":"03",X=d.fromHex(Y+B2(N,r.BYTES)),ce=u(N),Z=c(-U*ce),me=c(we*ce),Me=d.BASE.multiplyAndAddUnsafe(X,Z,me);if(!Me)throw Error("point at infinify");return Me.assertValidity(),Me}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ag(this.toDERHex())}toDERHex(){return Us.hexFromSig(this)}toCompactRawBytes(){return ag(this.toCompactHex())}toCompactHex(){let H=n;return B2(this.r,H)+B2(this.s,H)}}let E={isValidPrivateKey(H){try{return p(H),!0}catch(fe){return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{let H=I$(t.n);return $F(t.randomBytes(H),t.n)},precompute(H=8,fe=d.BASE){return fe._setWindowSize(H),fe.multiply(BigInt(3)),fe}};function w(H,fe=!0){return d.fromPrivateKey(H).toRawBytes(fe)}function _(H){if(typeof H==="bigint")return!1;if(H instanceof d)return!0;let we=yt("key",H).length,C=r.BYTES,U=C+1,N=2*C+1;if(t.allowedPrivateKeyLengths||n===U)return;else return we===U||we===N}function T(H,fe,we=!0){if(_(H)===!0)throw Error("first arg must be private key");if(_(fe)===!1)throw Error("second arg must be public key");return d.fromHex(fe).multiply(p(H)).toRawBytes(we)}let P=t.bits2int||function(H){if(H.length>8192)throw Error("input is too large");let fe=Bn(H),we=H.length*8-i;return we>0?fe>>BigInt(we):fe},O=t.bits2int_modN||function(H){return c(P(H))},z=gu(i);function B(H){return pn("num < 2^"+i,H,ei,z),Ti(H,n)}function k(H,fe,we=G){if(["recovered","canonical"].some((Ut)=>(Ut in we)))throw Error("sign() legacy options not supported");let{hash:C,randomBytes:U}=t,{lowS:N,prehash:Y,extraEntropy:X}=we;if(N==null)N=!0;if(H=yt("msgHash",H),TG(we),Y)H=yt("prehashed msgHash",C(H));let ce=O(H),Z=p(fe),me=[B(Z),B(ce)];if(X!=null&&X!==!1){let Ut=X===!0?U(r.BYTES):X;me.push(yt("extraEntropy",Ut))}let Me=vr(...me),Be=ce;function Le(Ut){let bt=P(Ut);if(!h(bt))return;let cr=u(bt),Zr=d.BASE.multiply(bt).toAffine(),tr=c(Zr.x);if(tr===ei)return;let En=c(cr*c(Be+tr*Z));if(En===ei)return;let Wr=(Zr.x===tr?0:2)|Number(Zr.y&kt),Ws=En;if(N&&y(En))Ws=x(En),Wr^=1;return new v(tr,Ws,Wr)}return{seed:Me,k2sig:Le}}let G={lowS:t.lowS,prehash:!1},V={lowS:t.lowS,prehash:!1};function ue(H,fe,we=G){let{seed:C,k2sig:U}=k(H,fe,we),N=t;return wF(N.hash.outputLen,N.nByteLength,N.hmac)(C,U)}d.BASE._setWindowSize(8);function W(H,fe,we,C=V){let U=H;fe=yt("msgHash",fe),we=yt("publicKey",we);let{lowS:N,prehash:Y,format:X}=C;if(TG(C),"strict"in C)throw Error("options.strict was renamed to lowS");if(X!==void 0&&X!=="compact"&&X!=="der")throw Error("format must be compact or der");let ce=typeof U==="string"||Ld(U),Z=!ce&&!X&&typeof U==="object"&&U!==null&&typeof U.r==="bigint"&&typeof U.s==="bigint";if(!ce&&!Z)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");let me=void 0,Me;try{if(Z)me=new v(U.r,U.s);if(ce){try{if(X!=="compact")me=v.fromDER(U)}catch(Wr){if(!(Wr instanceof Us.Err))throw Wr}if(!me&&X!=="der")me=v.fromCompact(U)}Me=d.fromHex(we)}catch(Wr){return!1}if(!me)return!1;if(N&&me.hasHighS())return!1;if(Y)fe=t.hash(fe);let{r:Be,s:Le}=me,Ut=O(fe),bt=u(Le),cr=c(Ut*bt),Zr=c(Be*bt),tr=d.BASE.multiplyAndAddUnsafe(Me,cr,Zr)?.toAffine();if(!tr)return!1;return c(tr.x)===Be}return{CURVE:t,getPublicKey:w,getSharedSecret:T,sign:ue,verify:W,ProjectivePoint:d,Signature:v,utils:E}}function Iye(e,t){let r=e.ORDER,o=ei;for(let y=r-kt;y%rc===ei;y/=rc)o+=kt;let n=o,i=rc<<n-kt-kt,s=i*rc,a=(r-kt)/s,c=(a-kt)/rc,u=s-kt,d=i,p=e.pow(t,a),m=e.pow(t,(a+kt)/rc),h=(y,x)=>{let S=p,v=e.pow(x,u),E=e.sqr(v);E=e.mul(E,x);let w=e.mul(y,E);w=e.pow(w,c),w=e.mul(w,v),v=e.mul(w,x),E=e.mul(w,y);let _=e.mul(E,v);w=e.pow(_,d);let T=e.eql(w,e.ONE);v=e.mul(E,m),w=e.mul(_,S),E=e.cmov(v,E,T),_=e.cmov(w,_,T);for(let P=n;P>kt;P--){let O=P-rc;O=rc<<O-kt;let z=e.pow(_,O),B=e.eql(z,e.ONE);v=e.mul(E,S),S=e.mul(S,S),z=e.mul(_,S),E=e.cmov(v,E,B),_=e.cmov(z,_,B)}return{isValid:T,value:E}};if(e.ORDER%D2===Zg){let y=(e.ORDER-Zg)/D2,x=e.sqrt(e.neg(t));h=(S,v)=>{let E=e.sqr(v),w=e.mul(S,v);E=e.mul(E,w);let _=e.pow(E,y);_=e.mul(_,w);let T=e.mul(_,x),P=e.mul(e.sqr(_),v),O=e.eql(P,S),z=e.cmov(T,_,O);return{isValid:O,value:z}}}return h}function PG(e,t){if(F_(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw Error("mapToCurveSimpleSWU: invalid opts");let r=Iye(e,t.Z);if(!e.isOdd)throw Error("Fp.isOdd is not implemented!");return(o)=>{let n,i,s,a,c,u,d,p;n=e.sqr(o),n=e.mul(n,t.Z),i=e.sqr(n),i=e.add(i,n),s=e.add(i,e.ONE),s=e.mul(s,t.B),a=e.cmov(t.Z,e.neg(i),!e.eql(i,e.ZERO)),a=e.mul(a,t.A),i=e.sqr(s),u=e.sqr(a),c=e.mul(u,t.A),i=e.add(i,c),i=e.mul(i,s),u=e.mul(u,a),c=e.mul(u,t.B),i=e.add(i,c),d=e.mul(n,s);let{isValid:m,value:h}=r(i,u);p=e.mul(n,o),p=e.mul(p,h),d=e.cmov(d,s,m),p=e.cmov(p,h,m);let y=e.isOdd(o)===e.isOdd(p);p=e.cmov(e.neg(p),p,y);let x=xs(e,[a],!0)[0];return d=e.mul(d,x),{x:d,y:p}}}var EG,Us,ei,kt,rc,Zg,D2;var U2=J(()=>{O$();xu();yu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */EG=class EG extends Error{constructor(e=""){super(e)}};Us={Err:EG,_tlv:{encode:(e,t)=>{let{Err:r}=Us;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let o=t.length/2,n=sg(o);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=o>127?sg(n.length/2|128):"";return sg(e)+i+n+t},decode(e,t){let{Err:r}=Us,o=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[o++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[o++],i=!!(n&128),s=0;if(!i)s=n;else{let c=n&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 u=t.subarray(o,o+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(o+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(o,o+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(o+s)}}},_int:{encode(e){let{Err:t}=Us;if(e<ei)throw new t("integer: negative integers are not allowed");let r=sg(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}=Us;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 Bn(e)}},toSig(e){let{Err:t,_int:r,_tlv:o}=Us,n=yt("signature",e),{v:i,l:s}=o.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=o.decode(2,i),{v:u,l:d}=o.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=Us,o=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),i=o+n;return t.encode(48,i)}};ei=BigInt(0),kt=BigInt(1),rc=BigInt(2),Zg=BigInt(3),D2=BigInt(4)});function Pye(e){return{hash:e,hmac:(t,...r)=>M2(e,t,g$(...r)),randomBytes:Ud}}function kG(e,t){let r=(o)=>IG({...e,...Pye(o)});return{...r(t),create:r}}var AG=J(()=>{SG();lo();U2();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */});var Z2={};Pn(Z2,{encodeToCurve:()=>Nye,hashToCurve:()=>zye,schnorr:()=>Rye,secp256k1:()=>vn,secp256k1_hasher:()=>V2});function OG(e){let t=Jg,r=BigInt(3),o=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,d=u*u*e%t,p=Vt(d,r,t)*d%t,m=Vt(p,r,t)*d%t,h=Vt(m,t1,t)*u%t,y=Vt(h,n,t)*h%t,x=Vt(y,i,t)*y%t,S=Vt(x,a,t)*x%t,v=Vt(S,c,t)*S%t,E=Vt(v,a,t)*x%t,w=Vt(E,r,t)*d%t,_=Vt(w,s,t)*y%t,T=Vt(_,o,t)*u%t,P=Vt(T,t1,t);if(!nc.eql(nc.sqr(P),e))throw Error("Cannot find square root");return P}function r1(e,...t){let r=RG[e];if(r===void 0){let o=gs(Uint8Array.from(e,(n)=>n.charCodeAt(0)));r=vr(o,o),RG[e]=r}return gs(vr(r,...t))}function F2(e){let t=vn.utils.normPrivateKeyToScalar(e),r=G2.fromPrivateKey(t);return{scalar:r.hasEvenY()?t:Kg(-t),bytes:H2(r)}}function CG(e){pn("x",e,Wg,Jg);let t=L2(e*e),r=L2(t*e+BigInt(7)),o=OG(r);if(o%t1!==q2)o=L2(-o);let n=new G2(e,o,Wg);return n.assertValidity(),n}function zG(...e){return Kg(Dp(r1("BIP0340/challenge",...e)))}function Aye(e){return F2(e).bytes}function $ye(e,t,r=Ud(32)){let o=yt("message",e),{bytes:n,scalar:i}=F2(t),s=yt("auxRand",r,32),a=j2(i^Dp(r1("BIP0340/aux",s))),c=r1("BIP0340/nonce",a,n,o),u=Kg(Dp(c));if(u===q2)throw Error("sign failed: k is zero");let{bytes:d,scalar:p}=F2(u),m=zG(d,n,o),h=new Uint8Array(64);if(h.set(d,0),h.set(j2(Kg(p+m*i)),32),!NG(h,o,n))throw Error("sign: Invalid signature produced");return h}function NG(e,t,r){let o=yt("signature",e,64),n=yt("message",t),i=yt("publicKey",r,32);try{let s=CG(Dp(i)),a=Dp(o.subarray(0,32));if(!hu(a,Wg,Jg))return!1;let c=Dp(o.subarray(32,64));if(!hu(c,Wg,e1))return!1;let u=zG(j2(a),H2(s),n),d=kye(s,c,Kg(-u));if(!d||!d.hasEvenY()||d.toAffine().x!==a)return!1;return!0}catch(s){return!1}}var Jg,e1,q2,Wg,t1,$G=(e,t)=>(e+t/t1)/t,nc,vn,RG,H2=(e)=>e.toRawBytes(!0).slice(1),j2=(e)=>Ti(e,32),L2=(e)=>lt(e,Jg),Kg=(e)=>lt(e,e1),G2,kye=(e,t,r)=>G2.BASE.multiplyAndAddUnsafe(e,t,r),Dp,Rye,Oye,Cye,V2,zye,Nye;var oc=J(()=>{ig();lo();AG();LF();xu();yu();U2();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Jg=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),e1=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),q2=BigInt(0),Wg=BigInt(1),t1=BigInt(2);nc=vs(Jg,void 0,void 0,{sqrt:OG}),vn=kG({a:q2,b:BigInt(7),Fp:nc,n:e1,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:(e)=>{let t=e1,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),o=-Wg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),n=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,s=BigInt("0x100000000000000000000000000000000"),a=$G(i*e,t),c=$G(-o*e,t),u=lt(e-a*r-c*n,t),d=lt(-a*o-c*i,t),p=u>s,m=d>s;if(p)u=t-u;if(m)d=t-d;if(u>s||d>s)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:p,k1:u,k2neg:m,k2:d}}}},gs),RG={};G2=(()=>vn.ProjectivePoint)();Dp=Bn;Rye=(()=>({getPublicKey:Aye,sign:$ye,verify:NG,utils:{randomPrivateKey:vn.utils.randomPrivateKey,lift_x:CG,pointToBytes:H2,numberToBytesBE:Ti,bytesToNumberBE:Bn,taggedHash:r1,mod:lt}}))(),Oye=(()=>DF(nc,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map((e)=>e.map((t)=>BigInt(t)))))(),Cye=(()=>PG(nc,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:nc.create(BigInt("-11"))}))(),V2=(()=>UF(vn.ProjectivePoint,(e)=>{let{x:t,y:r}=Cye(nc.create(e[0]));return Oye(t,r)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:nc.ORDER,m:1,k:128,expand:"xmd",hash:gs}))(),zye=(()=>V2.hashToCurve)(),Nye=(()=>V2.encodeToCurve)()});import{webcrypto as Tve}from"node:crypto";import HX from"node:http";import GX from"node:https";import vl from"node:zlib";import EN,{PassThrough as IN,pipeline as _l}from"node:stream";import{Buffer as xb}from"node:buffer";function bX(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(";"),o="",n=!1,i=r[0]||"text/plain",s=i;for(let d=1;d<r.length;d++)if(r[d]==="base64")n=!0;else if(r[d]){if(s+=`;${r[d]}`,r[d].indexOf("charset=")===0)o=r[d].substring(8)}if(!r[0]&&!o.length)s+=";charset=US-ASCII",o="US-ASCII";let a=n?"base64":"ascii",c=unescape(e.substring(t+1)),u=Buffer.from(c,a);return u.type=i,u.typeFull=s,u.charset=o,u}var Gz=bX;Zf();db();import oa,{PassThrough as dN}from"node:stream";import{types as pN,deprecate as qT,promisify as NX}from"node:util";import{Buffer as to}from"node:buffer";class ra 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 Hn extends ra{constructor(e,t,r){super(e,t);if(r)this.code=this.errno=r.code,this.erroredSysCall=r.syscall}}var pb=Symbol.toStringTag,LT=(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[pb]==="URLSearchParams",Kf=(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[pb]),eN=(e)=>typeof e==="object"&&(e[pb]==="AbortSignal"||e[pb]==="EventTarget"),tN=(e,t)=>{let r=new URL(t).hostname,o=new URL(e).hostname;return r===o||r.endsWith(`.${o}`)},rN=(e,t)=>{let r=new URL(t).protocol,o=new URL(e).protocol;return r===o};var MX=NX(oa.pipeline),kn=Symbol("Body internals");class Ji{constructor(e,{size:t=0}={}){let r=null;if(e===null)e=null;else if(LT(e))e=to.from(e.toString());else if(Kf(e));else if(to.isBuffer(e));else if(pN.isAnyArrayBuffer(e))e=to.from(e);else if(ArrayBuffer.isView(e))e=to.from(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof oa);else if(e instanceof Rc)e=Xz(e),r=e.type.split("=")[1];else e=to.from(String(e));let o=e;if(to.isBuffer(e))o=oa.Readable.from(e);else if(Kf(e))o=oa.Readable.from(e.stream());if(this[kn]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=t,e instanceof oa)e.on("error",(n)=>{let i=n instanceof ra?n:new Hn(`Invalid response body while trying to fetch ${this.url}: ${n.message}`,"system",n);this[kn].error=i})}get body(){return this[kn].stream}get bodyUsed(){return this[kn].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:r}=await FT(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 Rc,o=new URLSearchParams(await this.text());for(let[n,i]of o)r.append(n,i);return r}let{toFormData:t}=await Promise.resolve().then(() => (lN(),uN));return t(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[kn].body&&this[kn].body.type||"",t=await this.arrayBuffer();return new Ki([t],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await FT(this);return new TextDecoder().decode(e)}buffer(){return FT(this)}}Ji.prototype.buffer=qT(Ji.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Ji.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:qT(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});async function FT(e){if(e[kn].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[kn].disturbed=!0,e[kn].error)throw e[kn].error;let{body:t}=e;if(t===null)return to.alloc(0);if(!(t instanceof oa))return to.alloc(0);let r=[],o=0;try{for await(let n of t){if(e.size>0&&o+n.length>e.size){let i=new Hn(`content size at ${e.url} over limit: ${e.size}`,"max-size");throw t.destroy(i),i}o+=n.length,r.push(n)}}catch(n){throw n instanceof ra?n:new Hn(`Invalid response body while trying to fetch ${e.url}: ${n.message}`,"system",n)}if(t.readableEnded===!0||t._readableState.ended===!0)try{if(r.every((n)=>typeof n==="string"))return to.from(r.join(""));return to.concat(r,o)}catch(n){throw new Hn(`Could not create Buffer from response body for ${e.url}: ${n.message}`,"system",n)}else throw new Hn(`Premature close of server response while trying to fetch ${e.url}`)}var bl=(e,t)=>{let r,o,{body:n}=e[kn];if(e.bodyUsed)throw Error("cannot clone body after it is used");if(n instanceof oa&&typeof n.getBoundary!=="function")r=new dN({highWaterMark:t}),o=new dN({highWaterMark:t}),n.pipe(r),n.pipe(o),e[kn].stream=r,n=o;return n},BX=qT((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"),hb=(e,t)=>{if(e===null)return null;if(typeof e==="string")return"text/plain;charset=UTF-8";if(LT(e))return"application/x-www-form-urlencoded;charset=UTF-8";if(Kf(e))return e.type||null;if(to.isBuffer(e)||pN.isAnyArrayBuffer(e)||ArrayBuffer.isView(e))return null;if(e instanceof Rc)return`multipart/form-data; boundary=${t[kn].boundary}`;if(e&&typeof e.getBoundary==="function")return`multipart/form-data;boundary=${BX(e)}`;if(e instanceof oa)return null;return"text/plain;charset=UTF-8"},fN=(e)=>{let{body:t}=e[kn];if(t===null)return 0;if(Kf(t))return t.size;if(to.isBuffer(t))return t.length;if(t&&typeof t.getLengthSync==="function")return t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null;return null},mN=async(e,{body:t})=>{if(t===null)e.end();else await MX(t,e)};import{types as hN}from"node:util";import yb from"node:http";var gb=typeof yb.validateHeaderName==="function"?yb.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}},HT=typeof yb.validateHeaderValue==="function"?yb.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 nn extends URLSearchParams{constructor(e){let t=[];if(e instanceof nn){let r=e.raw();for(let[o,n]of Object.entries(r))t.push(...n.map((i)=>[o,i]))}else if(e==null);else if(typeof e==="object"&&!hN.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((o)=>{if(typeof o!=="object"||hN.isBoxedPrimitive(o))throw TypeError("Each header pair must be an iterable object");return[...o]}).map((o)=>{if(o.length!==2)throw TypeError("Each header pair must be a name/value tuple");return[...o]})}}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,o])=>(gb(r),HT(r,String(o)),[String(r).toLowerCase(),String(o)])):void 0;super(t);return new Proxy(this,{get(r,o,n){switch(o){case"append":case"set":return(i,s)=>(gb(i),HT(i,String(s)),URLSearchParams.prototype[o].call(r,String(i).toLowerCase(),String(s)));case"delete":case"has":case"getAll":return(i)=>(gb(i),URLSearchParams.prototype[o].call(r,String(i).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,o,n)}}})}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(nn.prototype,["get","entries","forEach","values"].reduce((e,t)=>(e[t]={enumerable:!0},e),{}));function gN(e=[]){return new nn(e.reduce((t,r,o,n)=>{if(o%2===0)t.push(n.slice(o,o+2));return t},[]).filter(([t,r])=>{try{return gb(t),HT(t,String(r)),!0}catch{return!1}}))}var DX=new Set([301,302,303,307,308]),bb=(e)=>DX.has(e);var Po=Symbol("Response internals");class Ar extends Ji{constructor(e=null,t={}){super(e,t);let r=t.status!=null?t.status:200,o=new nn(t.headers);if(e!==null&&!o.has("Content-Type")){let n=hb(e,this);if(n)o.append("Content-Type",n)}this[Po]={type:"default",url:t.url,status:r,statusText:t.statusText||"",headers:o,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[Po].type}get url(){return this[Po].url||""}get status(){return this[Po].status}get ok(){return this[Po].status>=200&&this[Po].status<300}get redirected(){return this[Po].counter>0}get statusText(){return this[Po].statusText}get headers(){return this[Po].headers}get highWaterMark(){return this[Po].highWaterMark}clone(){return new Ar(bl(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(!bb(t))throw RangeError('Failed to execute "redirect" on "response": Invalid status code');return new Ar(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new Ar(null,{status:0,statusText:""});return e[Po].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 o=new nn(t&&t.headers);if(!o.has("content-type"))o.set("content-type","application/json");return new Ar(r,{...t,headers:o})}get[Symbol.toStringTag](){return"Response"}}Object.defineProperties(Ar.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 jX}from"node:url";import{deprecate as FX}from"node:util";var yN=(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 UX}from"node:net";function bN(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 xN=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),vN="strict-origin-when-cross-origin";function _N(e){if(!xN.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function LX(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let t=e.host.replace(/(^\[)|(]$)/g,""),r=UX(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 xl(e){if(/^about:(blank|srcdoc)$/.test(e))return!0;if(e.protocol==="data:")return!0;if(/^(blob|filesystem):$/.test(e.protocol))return!0;return LX(e)}function wN(e,{referrerURLCallback:t,referrerOriginCallback:r}={}){if(e.referrer==="no-referrer"||e.referrerPolicy==="")return null;let o=e.referrerPolicy;if(e.referrer==="about:client")return"no-referrer";let n=e.referrer,i=bN(n),s=bN(n,!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(o){case"no-referrer":return"no-referrer";case"origin":return s;case"unsafe-url":return i;case"strict-origin":if(xl(i)&&!xl(a))return"no-referrer";return s.toString();case"strict-origin-when-cross-origin":if(i.origin===a.origin)return i;if(xl(i)&&!xl(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(xl(i)&&!xl(a))return"no-referrer";return i;default:throw TypeError(`Invalid referrerPolicy: ${o}`)}}function SN(e){let t=(e.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let o of t)if(o&&xN.has(o))r=o;return r}var br=Symbol("Request internals"),Yf=(e)=>typeof e==="object"&&typeof e[br]==="object",qX=FX(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)");class Yi extends Ji{constructor(e,t={}){let r;if(Yf(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 o=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o))o=o.toUpperCase();if(!Yf(t)&&"data"in t)qX();if((t.body!=null||Yf(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw TypeError("Request with GET/HEAD method cannot have body");let n=t.body?t.body:Yf(e)&&e.body!==null?bl(e):null;super(n,{size:t.size||e.size||0});let i=new nn(t.headers||e.headers||{});if(n!==null&&!i.has("Content-Type")){let c=hb(n,this);if(c)i.set("Content-Type",c)}let s=Yf(e)?e.signal:null;if("signal"in t)s=t.signal;if(s!=null&&!eN(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[br]={method:o,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[br].method}get url(){return jX(this[br].parsedURL)}get headers(){return this[br].headers}get redirect(){return this[br].redirect}get signal(){return this[br].signal}get referrer(){if(this[br].referrer==="no-referrer")return"";if(this[br].referrer==="client")return"about:client";if(this[br].referrer)return this[br].referrer.toString();return}get referrerPolicy(){return this[br].referrerPolicy}set referrerPolicy(e){this[br].referrerPolicy=_N(e)}clone(){return new Yi(this)}get[Symbol.toStringTag](){return"Request"}}Object.defineProperties(Yi.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 TN=(e)=>{let{parsedURL:t}=e[br],r=new nn(e[br].headers);if(!r.has("Accept"))r.set("Accept","*/*");let o=null;if(e.body===null&&/^(post|put)$/i.test(e.method))o="0";if(e.body!==null){let a=fN(e);if(typeof a==="number"&&!Number.isNaN(a))o=String(a)}if(o)r.set("Content-Length",o);if(e.referrerPolicy==="")e.referrerPolicy=vN;if(e.referrer&&e.referrer!=="no-referrer")e[br].referrer=wN(e);else e[br].referrer="no-referrer";if(e[br].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:n}=e;if(typeof n==="function")n=n(t);let i=yN(t),s={path:t.pathname+i,method:e.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:e.insecureHTTPParser,agent:n};return{parsedURL:t,options:s}};class GT extends ra{constructor(e,t="aborted"){super(e,t)}}db();jT();var VX=new Set(["data:","http:","https:"]);async function vb(e,t){return new Promise((r,o)=>{let n=new Yi(e,t),{parsedURL:i,options:s}=TN(n);if(!VX.has(i.protocol))throw TypeError(`node-fetch cannot load ${e}. URL scheme "${i.protocol.replace(/:$/,"")}" is not supported.`);if(i.protocol==="data:"){let y=Gz(n.url),x=new Ar(y,{headers:{"Content-Type":y.typeFull}});r(x);return}let a=(i.protocol==="https:"?GX:HX).request,{signal:c}=n,u=null,d=()=>{let y=new GT("The operation was aborted.");if(o(y),n.body&&n.body instanceof EN.Readable)n.body.destroy(y);if(!u||!u.body)return;u.body.emit("error",y)};if(c&&c.aborted){d();return}let p=()=>{d(),h()},m=a(i.toString(),s);if(c)c.addEventListener("abort",p);let h=()=>{if(m.abort(),c)c.removeEventListener("abort",p)};if(m.on("error",(y)=>{o(new Hn(`request to ${n.url} failed, reason: ${y.message}`,"system",y)),h()}),ZX(m,(y)=>{if(u&&u.body)u.body.destroy(y)}),process.version<"v14")m.on("socket",(y)=>{let x;y.prependListener("end",()=>{x=y._eventsCount}),y.prependListener("close",(S)=>{if(u&&x<y._eventsCount&&!S){let v=Error("Premature close");v.code="ERR_STREAM_PREMATURE_CLOSE",u.body.emit("error",v)}})});m.on("response",(y)=>{m.setTimeout(0);let x=gN(y.rawHeaders);if(bb(y.statusCode)){let _=x.get("Location"),T=null;try{T=_===null?null:new URL(_,n.url)}catch{if(n.redirect!=="manual"){o(new Hn(`uri requested responds with an invalid redirect URL: ${_}`,"invalid-redirect")),h();return}}switch(n.redirect){case"error":o(new Hn(`uri requested responds with a redirect, redirect mode is set to error: ${n.url}`,"no-redirect")),h();return;case"manual":break;case"follow":{if(T===null)break;if(n.counter>=n.follow){o(new Hn(`maximum redirect reached at: ${n.url}`,"max-redirect")),h();return}let P={headers:new nn(n.headers),follow:n.follow,counter:n.counter+1,agent:n.agent,compress:n.compress,method:n.method,body:bl(n),signal:n.signal,size:n.size,referrer:n.referrer,referrerPolicy:n.referrerPolicy};if(!tN(n.url,T)||!rN(n.url,T))for(let z of["authorization","www-authenticate","cookie","cookie2"])P.headers.delete(z);if(y.statusCode!==303&&n.body&&t.body instanceof EN.Readable){o(new Hn("Cannot follow redirect with body being a readable stream","unsupported-redirect")),h();return}if(y.statusCode===303||(y.statusCode===301||y.statusCode===302)&&n.method==="POST")P.method="GET",P.body=void 0,P.headers.delete("content-length");let O=SN(x);if(O)P.referrerPolicy=O;r(vb(new Yi(T,P))),h();return}default:return o(TypeError(`Redirect option '${n.redirect}' is not a valid value of RequestRedirect`))}}if(c)y.once("end",()=>{c.removeEventListener("abort",p)});let S=_l(y,new IN,(_)=>{if(_)o(_)});if(process.version<"v12.10")y.on("aborted",p);let v={url:n.url,status:y.statusCode,statusText:y.statusMessage,headers:x,size:n.size,counter:n.counter,highWaterMark:n.highWaterMark},E=x.get("Content-Encoding");if(!n.compress||n.method==="HEAD"||E===null||y.statusCode===204||y.statusCode===304){u=new Ar(S,v),r(u);return}let w={flush:vl.Z_SYNC_FLUSH,finishFlush:vl.Z_SYNC_FLUSH};if(E==="gzip"||E==="x-gzip"){S=_l(S,vl.createGunzip(w),(_)=>{if(_)o(_)}),u=new Ar(S,v),r(u);return}if(E==="deflate"||E==="x-deflate"){let _=_l(y,new IN,(T)=>{if(T)o(T)});_.once("data",(T)=>{if((T[0]&15)===8)S=_l(S,vl.createInflate(),(P)=>{if(P)o(P)});else S=_l(S,vl.createInflateRaw(),(P)=>{if(P)o(P)});u=new Ar(S,v),r(u)}),_.once("end",()=>{if(!u)u=new Ar(S,v),r(u)});return}if(E==="br"){S=_l(S,vl.createBrotliDecompress(),(_)=>{if(_)o(_)}),u=new Ar(S,v),r(u);return}u=new Ar(S,v),r(u)}),mN(m,n).catch(o)})}function ZX(e,t){let r=xb.from(`0\r
64
+ `),{cause:e,name:"TipAboveFeeCapError"})}};Object.defineProperty(Mu,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});Qo=class Qo extends F{constructor({cause:e}){super(`An error occurred while executing: ${e?.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}});function Xa(e,t){let r=(e.details||"").toLowerCase(),o=e instanceof F?e.walk((n)=>n?.code===Qa.code):e;if(o instanceof F)return new Qa({cause:e,message:o.details});if(Qa.nodeMessage.test(r))return new Qa({cause:e,message:e.details});if(Nu.nodeMessage.test(r))return new Nu({cause:e,maxFeePerGas:t?.maxFeePerGas});if(Bg.nodeMessage.test(r))return new Bg({cause:e,maxFeePerGas:t?.maxFeePerGas});if(Dg.nodeMessage.test(r))return new Dg({cause:e,nonce:t?.nonce});if(Ug.nodeMessage.test(r))return new Ug({cause:e,nonce:t?.nonce});if(Lg.nodeMessage.test(r))return new Lg({cause:e,nonce:t?.nonce});if(jg.nodeMessage.test(r))return new jg({cause:e});if(Fg.nodeMessage.test(r))return new Fg({cause:e,gas:t?.gas});if(qg.nodeMessage.test(r))return new qg({cause:e,gas:t?.gas});if(Hg.nodeMessage.test(r))return new Hg({cause:e});if(Mu.nodeMessage.test(r))return new Mu({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas});return new Qo({cause:e})}var Gg=J(()=>{ot();Bu()});function Hw(e,{docsPath:t,...r}){let o=(()=>{let n=Xa(e,r);if(n instanceof Qo)return e;return n})();return new Ag(o,{docsPath:t,...r})}var T2=J(()=>{Wa();Bu();Gg()});function ec(e,{format:t}){if(!t)return{};let r={};function o(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]))o(i[a])}}let n=t(e||{});return o(n),r}function Ci(e,t){let r={};if(typeof e.authorizationList<"u")r.authorizationList=uye(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((o)=>ht(o));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=ye(e.gas);if(typeof e.gasPrice<"u")r.gasPrice=ye(e.gasPrice);if(typeof e.maxFeePerBlobGas<"u")r.maxFeePerBlobGas=ye(e.maxFeePerBlobGas);if(typeof e.maxFeePerGas<"u")r.maxFeePerGas=ye(e.maxFeePerGas);if(typeof e.maxPriorityFeePerGas<"u")r.maxPriorityFeePerGas=ye(e.maxPriorityFeePerGas);if(typeof e.nonce<"u")r.nonce=ye(e.nonce);if(typeof e.to<"u")r.to=e.to;if(typeof e.type<"u")r.type=cye[e.type];if(typeof e.value<"u")r.value=ye(e.value);return r}function uye(e){return e.map((t)=>({address:t.address,r:t.r?ye(BigInt(t.r)):t.r,s:t.s?ye(BigInt(t.s)):t.s,chainId:ye(t.chainId),nonce:ye(t.nonce),...typeof t.yParity<"u"?{yParity:ye(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:ye(t.v)}:{}}))}var cye;var Np=J(()=>{We();cye={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"}});function Gw(){let e=()=>{return},t=()=>{return};return{promise:new Promise((o,n)=>{e=o,t=n}),resolve:e,reject:t}}function Vw({fn:e,id:t,shouldSplitBatch:r,wait:o=0,sort:n}){let i=async()=>{let d=c();s();let p=d.map(({args:m})=>m);if(p.length===0)return;e(p).then((m)=>{if(n&&Array.isArray(m))m.sort(n);for(let h=0;h<d.length;h++){let{resolve:y}=d[h];y?.([m[h],m])}}).catch((m)=>{for(let h=0;h<d.length;h++){let{reject:y}=d[h];y?.(m)}})},s=()=>E2.delete(t),a=()=>c().map(({args:d})=>d),c=()=>E2.get(t)||[],u=(d)=>E2.set(t,[...c(),d]);return{flush:s,async schedule(d){let{promise:p,resolve:m,reject:h}=Gw();if(r?.([...a(),d]))i();if(c().length>0)return u({args:d,resolve:m,reject:h}),p;return u({args:d,resolve:m,reject:h}),setTimeout(i,o),p}}}var E2;var I2=J(()=>{E2=new Map});function tG(e){if(!e||e.length===0)return;return e.reduce((t,{slot:r,value:o})=>{if(r.length!==66)throw new uw({size:r.length,targetSize:66,type:"hex"});if(o.length!==66)throw new uw({size:o.length,targetSize:66,type:"hex"});return t[r]=o,t},{})}function lye(e){let{balance:t,nonce:r,state:o,stateDiff:n,code:i}=e,s={};if(i!==void 0)s.code=i;if(t!==void 0)s.balance=ye(t);if(r!==void 0)s.nonce=ye(r);if(o!==void 0)s.state=tG(o);if(n!==void 0){if(s.state)throw new KR;s.stateDiff=tG(n)}return s}function Mp(e){if(!e)return;let t={};for(let{address:r,...o}of e){if(!lr(r,{strict:!1}))throw new hn({address:r});if(t[r])throw new WR({address:r});t[r]=lye(o)}return t}var Zw=J(()=>{_u();lw();JR();Is();We()});var xNe,vNe,_Ne,wNe,SNe,TNe,ENe,INe,PNe,kNe,ANe,$Ne,RNe,ONe,CNe,zNe,NNe,MNe,BNe,DNe,UNe,LNe,jNe,FNe,qNe,HNe,GNe,VNe,ZNe,WNe,KNe,JNe,YNe,QNe,XNe,eMe,tMe,rMe,nMe,oMe,iMe,sMe,aMe,cMe,uMe,lMe,dMe,pMe,fMe,mMe,hMe,gMe,yMe,bMe,xMe,vMe,_Me,wMe,SMe,TMe,EMe,IMe,PMe,kMe,AMe,$Me,RMe,OMe,CMe,zMe,NMe,MMe,BMe,DMe,UMe,LMe,jMe,FMe,qMe,HMe,GMe,VMe,ZMe,WMe,KMe,JMe,YMe,QMe,XMe,e4e,t4e,r4e,n4e,o4e,i4e,rG;var nG=J(()=>{xNe=2n**(8n-1n)-1n,vNe=2n**(16n-1n)-1n,_Ne=2n**(24n-1n)-1n,wNe=2n**(32n-1n)-1n,SNe=2n**(40n-1n)-1n,TNe=2n**(48n-1n)-1n,ENe=2n**(56n-1n)-1n,INe=2n**(64n-1n)-1n,PNe=2n**(72n-1n)-1n,kNe=2n**(80n-1n)-1n,ANe=2n**(88n-1n)-1n,$Ne=2n**(96n-1n)-1n,RNe=2n**(104n-1n)-1n,ONe=2n**(112n-1n)-1n,CNe=2n**(120n-1n)-1n,zNe=2n**(128n-1n)-1n,NNe=2n**(136n-1n)-1n,MNe=2n**(144n-1n)-1n,BNe=2n**(152n-1n)-1n,DNe=2n**(160n-1n)-1n,UNe=2n**(168n-1n)-1n,LNe=2n**(176n-1n)-1n,jNe=2n**(184n-1n)-1n,FNe=2n**(192n-1n)-1n,qNe=2n**(200n-1n)-1n,HNe=2n**(208n-1n)-1n,GNe=2n**(216n-1n)-1n,VNe=2n**(224n-1n)-1n,ZNe=2n**(232n-1n)-1n,WNe=2n**(240n-1n)-1n,KNe=2n**(248n-1n)-1n,JNe=2n**(256n-1n)-1n,YNe=-(2n**(8n-1n)),QNe=-(2n**(16n-1n)),XNe=-(2n**(24n-1n)),eMe=-(2n**(32n-1n)),tMe=-(2n**(40n-1n)),rMe=-(2n**(48n-1n)),nMe=-(2n**(56n-1n)),oMe=-(2n**(64n-1n)),iMe=-(2n**(72n-1n)),sMe=-(2n**(80n-1n)),aMe=-(2n**(88n-1n)),cMe=-(2n**(96n-1n)),uMe=-(2n**(104n-1n)),lMe=-(2n**(112n-1n)),dMe=-(2n**(120n-1n)),pMe=-(2n**(128n-1n)),fMe=-(2n**(136n-1n)),mMe=-(2n**(144n-1n)),hMe=-(2n**(152n-1n)),gMe=-(2n**(160n-1n)),yMe=-(2n**(168n-1n)),bMe=-(2n**(176n-1n)),xMe=-(2n**(184n-1n)),vMe=-(2n**(192n-1n)),_Me=-(2n**(200n-1n)),wMe=-(2n**(208n-1n)),SMe=-(2n**(216n-1n)),TMe=-(2n**(224n-1n)),EMe=-(2n**(232n-1n)),IMe=-(2n**(240n-1n)),PMe=-(2n**(248n-1n)),kMe=-(2n**(256n-1n)),AMe=2n**8n-1n,$Me=2n**16n-1n,RMe=2n**24n-1n,OMe=2n**32n-1n,CMe=2n**40n-1n,zMe=2n**48n-1n,NMe=2n**56n-1n,MMe=2n**64n-1n,BMe=2n**72n-1n,DMe=2n**80n-1n,UMe=2n**88n-1n,LMe=2n**96n-1n,jMe=2n**104n-1n,FMe=2n**112n-1n,qMe=2n**120n-1n,HMe=2n**128n-1n,GMe=2n**136n-1n,VMe=2n**144n-1n,ZMe=2n**152n-1n,WMe=2n**160n-1n,KMe=2n**168n-1n,JMe=2n**176n-1n,YMe=2n**184n-1n,QMe=2n**192n-1n,XMe=2n**200n-1n,e4e=2n**208n-1n,t4e=2n**216n-1n,r4e=2n**224n-1n,n4e=2n**232n-1n,o4e=2n**240n-1n,i4e=2n**248n-1n,rG=2n**256n-1n});function xo(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:o,to:n}=e,i=t?Ft(t):void 0;if(i&&!lr(i.address))throw new hn({address:i.address});if(n&&!lr(n))throw new hn({address:n});if(r&&r>rG)throw new Nu({maxFeePerGas:r});if(o&&r&&o>r)throw new Mu({maxFeePerGas:r,maxPriorityFeePerGas:o})}var Du=J(()=>{nG();_u();Bu();Is()});var P2,k2,A2;var oG=J(()=>{ot();P2=class P2 extends F{constructor({callbackSelector:e,cause:t,data:r,extraData:o,sender:n,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)=>` ${Au(s)}`)],` Sender: ${n}`,` Data: ${r}`,` Callback selector: ${e}`,` Extra data: ${o}`].flat(),name:"OffchainLookupError"})}};k2=class k2 extends F{constructor({result:e,url:t}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${Au(t)}`,`Response: ${dt(e)}`],name:"OffchainLookupResponseMalformedError"})}};A2=class A2 extends F{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"})}}});function Xo(e,t){if(!lr(e,{strict:!1}))throw new hn({address:e});if(!lr(t,{strict:!1}))throw new hn({address:t});return e.toLowerCase()===t.toLowerCase()}var Bp=J(()=>{_u();Is()});var aG={};Pn(aG,{ccipRequest:()=>sG,offchainLookup:()=>pye,offchainLookupAbiItem:()=>iG,offchainLookupSignature:()=>dye});async function pye(e,{blockNumber:t,blockTag:r,data:o,to:n}){let{args:i}=Rw({data:o,abi:[iG]}),[s,a,c,u,d]=i,{ccipRead:p}=e,m=p&&typeof p?.request==="function"?p.request:sG;try{if(!Xo(n,s))throw new A2({sender:s,to:n});let h=a.includes(Ns)?await s2({data:c,ccipRequest:m}):await m({data:c,sender:s,urls:a}),{data:y}=await vo(e,{blockNumber:t,blockTag:r,data:Fr([u,yn([{type:"bytes"},{type:"bytes"}],[h,d])]),to:n});return y}catch(h){throw new P2({callbackSelector:u,cause:h,data:o,extraData:d,sender:s,urls:a})}}async function sG({data:e,sender:t,urls:r}){let o=Error("An unknown error occurred.");for(let n=0;n<r.length;n++){let i=r[n],s=i.includes("{data}")?"GET":"POST",a=s==="POST"?{data:e,sender:t}:void 0,c=s==="POST"?{"Content-Type":"application/json"}:{};try{let u=await fetch(i.replace("{sender}",t.toLowerCase()).replace("{data}",e),{body:JSON.stringify(a),headers:c,method:s}),d;if(u.headers.get("Content-Type")?.startsWith("application/json"))d=(await u.json()).data;else d=await u.text();if(!u.ok){o=new Jo({body:a,details:d?.error?dt(d.error):u.statusText,headers:u.headers,status:u.status,url:i});continue}if(!sr(d)){o=new k2({result:d,url:i});continue}return d}catch(u){o=new Jo({body:a,details:u.message,url:i})}}throw o}var dye="0x556f1830",iG;var cG=J(()=>{Uu();oG();Ru();GR();Ps();Bp();Rg();iG={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 vo(e,t){let{account:r=e.account,authorizationList:o,batch:n=Boolean(e.batch?.multicall),blockNumber:i,blockTag:s=e.experimental_blockTag??"latest",accessList:a,blobs:c,blockOverrides:u,code:d,data:p,factory:m,factoryData:h,gas:y,gasPrice:x,maxFeePerBlobGas:S,maxFeePerGas:v,maxPriorityFeePerGas:E,nonce:w,to:_,value:T,stateOverride:P,...O}=t,z=r?Ft(r):void 0;if(d&&(m||h))throw new F("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(d&&_)throw new F("Cannot provide both `code` & `to` as parameters.");let B=d&&p,k=m&&h&&_&&p,G=B||k,V=(()=>{if(B)return uG({code:d,data:p});if(k)return hye({data:p,factory:m,factoryData:h,to:_});return p})();try{xo(t);let W=(typeof i==="bigint"?ye(i):void 0)||s,H=u?Fw(u):void 0,fe=Mp(P),we=e.chain?.formatters?.transactionRequest?.format,U=(we||Ci)({...ec(O,{format:we}),accessList:a,account:z,authorizationList:o,blobs:c,data:V,gas:y,gasPrice:x,maxFeePerBlobGas:S,maxFeePerGas:v,maxPriorityFeePerGas:E,nonce:w,to:G?void 0:_,value:T},"call");if(n&&fye({request:U})&&!fe&&!H)try{return await mye(e,{...U,blockNumber:i,blockTag:s})}catch(X){if(!(X instanceof kw)&&!(X instanceof rp))throw X}let N=(()=>{let X=[U,W];if(fe&&H)return[...X,fe,H];if(fe)return[...X,fe];if(H)return[...X,{},H];return X})(),Y=await e.request({method:"eth_call",params:N});if(Y==="0x")return{data:void 0};return{data:Y}}catch(ue){let W=gye(ue),{offchainLookup:H,offchainLookupSignature:fe}=await Promise.resolve().then(() => (cG(),aG));if(e.ccipRead!==!1&&W?.slice(0,10)===fe&&_)return{data:await H(e,{data:W,to:_})};if(G&&W?.slice(0,10)==="0x101bb98d")throw new r2({factory:m});throw Hw(ue,{...t,account:z,chain:e.chain})}}function fye({request:e}){let{data:t,to:r,...o}=e;if(!t)return!1;if(t.startsWith(QH))return!1;if(!r)return!1;if(Object.values(o).filter((n)=>typeof n<"u").length>0)return!1;return!0}async function mye(e,t){let{batchSize:r=1024,deployless:o=!1,wait:n=0}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},{blockNumber:i,blockTag:s=e.experimental_blockTag??"latest",data:a,to:c}=t,u=(()=>{if(o)return null;if(t.multicallAddress)return t.multicallAddress;if(e.chain)return go({blockNumber:i,chain:e.chain,contract:"multicall3"});throw new kw})(),p=(typeof i==="bigint"?ye(i):void 0)||s,{schedule:m}=Vw({id:`${e.uid}.${p}`,wait:n,shouldSplitBatch(x){return x.reduce((v,{data:E})=>v+(E.length-2),0)>r*2},fn:async(x)=>{let S=x.map((w)=>({allowFailure:!0,callData:w.data,target:w.to})),v=Kt({abi:qo,args:[S],functionName:"aggregate3"}),E=await e.request({method:"eth_call",params:[{...u===null?{data:uG({code:zp,data:v})}:{to:u,data:v}},p]});return Xr({abi:qo,args:[S],functionName:"aggregate3",data:E||"0x"})}}),[{returnData:h,success:y}]=await m({data:a,to:c});if(!y)throw new zs({data:h});if(h==="0x")return{data:void 0};return{data:h}}function uG(e){let{code:t,data:r}=e;return Mg({abi:Tw(["constructor(bytes, bytes)"]),bytecode:qw,args:[t,r]})}function hye(e){let{data:t,factory:r,factoryData:o,to:n}=e;return Mg({abi:Tw(["constructor(address, bytes, address, bytes)"]),bytecode:XH,args:[n,t,r,o]})}function gye(e){if(!(e instanceof F))return;let t=e.walk();return typeof t?.data==="object"?t.data?.data:t.data}var Uu=J(()=>{ep();_2();Pi();ot();HR();Wa();Os();S2();ho();Pu();We();T2();Np();I2();Zw();Du()});var N2,M2=(e,t,r)=>new N2(e,t).update(r).digest();var SG=J(()=>{lo();N2=class N2 extends du{constructor(e,t){super();this.finished=!1,this.destroyed=!1,Y3(e);let r=lu(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 o=this.blockLen,n=new Uint8Array(o);n.set(r.length>o?e.create().update(r).digest():r);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),uo(n)}update(e){return ms(this),this.iHash.update(e),this}digestInto(e){ms(this),Lo(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:o,destroyed:n,blockLen:i,outputLen:s}=this;return e=e,e.finished=o,e.destroyed=n,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()}};M2.create=(e,t)=>new N2(e,t)});function TG(e){if(e.lowS!==void 0)Si("lowS",e.lowS);if(e.prehash!==void 0)Si("prehash",e.prehash)}function Sye(e){let t=cg(e);Fo(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:o,a:n}=t;if(r){if(!o.eql(n,o.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 B2(e,t){return La(Ti(e,t))}function Tye(e){let t=Sye(e),{Fp:r}=t,o=vs(t.n,t.nBitLength),n=t.toBytes||((w,_,T)=>{let P=_.toAffine();return vr(Uint8Array.from([4]),r.toBytes(P.x),r.toBytes(P.y))}),i=t.fromBytes||((w)=>{let _=w.subarray(1),T=r.fromBytes(_.subarray(0,r.BYTES)),P=r.fromBytes(_.subarray(r.BYTES,2*r.BYTES));return{x:T,y:P}});function s(w){let{a:_,b:T}=t,P=r.sqr(w),O=r.mul(P,w);return r.add(r.add(O,r.mul(w,_)),T)}function a(w,_){let T=r.sqr(_),P=s(w);return r.eql(T,P)}if(!a(t.Gx,t.Gy))throw Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,Zg),D2),u=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,u)))throw Error("bad curve params: a or b");function d(w){return hu(w,kt,t.n)}function p(w){let{allowedPrivateKeyLengths:_,nByteLength:T,wrapPrivateKey:P,n:O}=t;if(_&&typeof w!=="bigint"){if(Ld(w))w=La(w);if(typeof w!=="string"||!_.includes(w.length))throw Error("invalid private key");w=w.padStart(T*2,"0")}let z;try{z=typeof w==="bigint"?w:Bn(yt("private key",w,T))}catch(B){throw Error("invalid private key, expected hex or "+T+" bytes, got "+typeof w)}if(P)z=lt(z,O);return pn("private key",z,kt,O),z}function m(w){if(!(w instanceof x))throw Error("ProjectivePoint expected")}let h=Fd((w,_)=>{let{px:T,py:P,pz:O}=w;if(r.eql(O,r.ONE))return{x:T,y:P};let z=w.is0();if(_==null)_=z?r.ONE:r.inv(O);let B=r.mul(T,_),k=r.mul(P,_),G=r.mul(O,_);if(z)return{x:r.ZERO,y:r.ZERO};if(!r.eql(G,r.ONE))throw Error("invZ was invalid");return{x:B,y:k}}),y=Fd((w)=>{if(w.is0()){if(t.allowInfinityPoint&&!r.is0(w.py))return;throw Error("bad point: ZERO")}let{x:_,y:T}=w.toAffine();if(!r.isValid(_)||!r.isValid(T))throw Error("bad point: x or y not FE");if(!a(_,T))throw Error("bad point: equation left != right");if(!w.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class x{constructor(w,_,T){if(w==null||!r.isValid(w))throw Error("x required");if(_==null||!r.isValid(_)||r.is0(_))throw Error("y required");if(T==null||!r.isValid(T))throw Error("z required");this.px=w,this.py=_,this.pz=T,Object.freeze(this)}static fromAffine(w){let{x:_,y:T}=w||{};if(!w||!r.isValid(_)||!r.isValid(T))throw Error("invalid affine point");if(w instanceof x)throw Error("projective point not allowed");let P=(O)=>r.eql(O,r.ZERO);if(P(_)&&P(T))return x.ZERO;return new x(_,T,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){let _=xs(r,w.map((T)=>T.pz));return w.map((T,P)=>T.toAffine(_[P])).map(x.fromAffine)}static fromHex(w){let _=x.fromAffine(i(yt("pointHex",w)));return _.assertValidity(),_}static fromPrivateKey(w){return x.BASE.multiply(p(w))}static msm(w,_){return H_(x,o,w,_)}_setWindowSize(w){E.setWindowSize(this,w)}assertValidity(){y(this)}hasEvenY(){let{y:w}=this.toAffine();if(r.isOdd)return!r.isOdd(w);throw Error("Field doesn't support isOdd")}equals(w){m(w);let{px:_,py:T,pz:P}=this,{px:O,py:z,pz:B}=w,k=r.eql(r.mul(_,B),r.mul(O,P)),G=r.eql(r.mul(T,B),r.mul(z,P));return k&&G}negate(){return new x(this.px,r.neg(this.py),this.pz)}double(){let{a:w,b:_}=t,T=r.mul(_,Zg),{px:P,py:O,pz:z}=this,B=r.ZERO,k=r.ZERO,G=r.ZERO,V=r.mul(P,P),ue=r.mul(O,O),W=r.mul(z,z),H=r.mul(P,O);return H=r.add(H,H),G=r.mul(P,z),G=r.add(G,G),B=r.mul(w,G),k=r.mul(T,W),k=r.add(B,k),B=r.sub(ue,k),k=r.add(ue,k),k=r.mul(B,k),B=r.mul(H,B),G=r.mul(T,G),W=r.mul(w,W),H=r.sub(V,W),H=r.mul(w,H),H=r.add(H,G),G=r.add(V,V),V=r.add(G,V),V=r.add(V,W),V=r.mul(V,H),k=r.add(k,V),W=r.mul(O,z),W=r.add(W,W),V=r.mul(W,H),B=r.sub(B,V),G=r.mul(W,ue),G=r.add(G,G),G=r.add(G,G),new x(B,k,G)}add(w){m(w);let{px:_,py:T,pz:P}=this,{px:O,py:z,pz:B}=w,k=r.ZERO,G=r.ZERO,V=r.ZERO,ue=t.a,W=r.mul(t.b,Zg),H=r.mul(_,O),fe=r.mul(T,z),we=r.mul(P,B),C=r.add(_,T),U=r.add(O,z);C=r.mul(C,U),U=r.add(H,fe),C=r.sub(C,U),U=r.add(_,P);let N=r.add(O,B);return U=r.mul(U,N),N=r.add(H,we),U=r.sub(U,N),N=r.add(T,P),k=r.add(z,B),N=r.mul(N,k),k=r.add(fe,we),N=r.sub(N,k),V=r.mul(ue,U),k=r.mul(W,we),V=r.add(k,V),k=r.sub(fe,V),V=r.add(fe,V),G=r.mul(k,V),fe=r.add(H,H),fe=r.add(fe,H),we=r.mul(ue,we),U=r.mul(W,U),fe=r.add(fe,we),we=r.sub(H,we),we=r.mul(ue,we),U=r.add(U,we),H=r.mul(fe,U),G=r.add(G,H),H=r.mul(N,U),k=r.mul(C,k),k=r.sub(k,H),H=r.mul(C,fe),V=r.mul(N,V),V=r.add(V,H),new x(k,G,V)}subtract(w){return this.add(w.negate())}is0(){return this.equals(x.ZERO)}wNAF(w){return E.wNAFCached(this,w,x.normalizeZ)}multiplyUnsafe(w){let{endo:_,n:T}=t;pn("scalar",w,ei,T);let P=x.ZERO;if(w===ei)return P;if(this.is0()||w===kt)return this;if(!_||E.hasPrecomputes(this))return E.wNAFCachedUnsafe(this,w,x.normalizeZ);let{k1neg:O,k1:z,k2neg:B,k2:k}=_.splitScalar(w),G=P,V=P,ue=this;while(z>ei||k>ei){if(z&kt)G=G.add(ue);if(k&kt)V=V.add(ue);ue=ue.double(),z>>=kt,k>>=kt}if(O)G=G.negate();if(B)V=V.negate();return V=new x(r.mul(V.px,_.beta),V.py,V.pz),G.add(V)}multiply(w){let{endo:_,n:T}=t;pn("scalar",w,kt,T);let P,O;if(_){let{k1neg:z,k1:B,k2neg:k,k2:G}=_.splitScalar(w),{p:V,f:ue}=this.wNAF(B),{p:W,f:H}=this.wNAF(G);V=E.constTimeNegate(z,V),W=E.constTimeNegate(k,W),W=new x(r.mul(W.px,_.beta),W.py,W.pz),P=V.add(W),O=ue.add(H)}else{let{p:z,f:B}=this.wNAF(w);P=z,O=B}return x.normalizeZ([P,O])[0]}multiplyAndAddUnsafe(w,_,T){let P=x.BASE,O=(B,k)=>k===ei||k===kt||!B.equals(P)?B.multiplyUnsafe(k):B.multiply(k),z=O(this,_).add(O(w,T));return z.is0()?void 0:z}toAffine(w){return h(this,w)}isTorsionFree(){let{h:w,isTorsionFree:_}=t;if(w===kt)return!0;if(_)return _(x,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:w,clearCofactor:_}=t;if(w===kt)return this;if(_)return _(x,this);return this.multiplyUnsafe(t.h)}toRawBytes(w=!0){return Si("isCompressed",w),this.assertValidity(),n(x,this,w)}toHex(w=!0){return Si("isCompressed",w),La(this.toRawBytes(w))}}x.BASE=new x(t.Gx,t.Gy,r.ONE),x.ZERO=new x(r.ZERO,r.ONE,r.ZERO);let{endo:S,nBitLength:v}=t,E=q_(x,S?Math.ceil(v/2):v);return{CURVE:t,ProjectivePoint:x,normPrivateKeyToScalar:p,weierstrassEquation:s,isWithinCurveOrder:d}}function Eye(e){let t=cg(e);return Fo(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function IG(e){let t=Eye(e),{Fp:r,n:o,nByteLength:n,nBitLength:i}=t,s=r.BYTES+1,a=2*r.BYTES+1;function c(H){return lt(H,o)}function u(H){return j_(H,o)}let{ProjectivePoint:d,normPrivateKeyToScalar:p,weierstrassEquation:m,isWithinCurveOrder:h}=Tye({...t,toBytes(H,fe,we){let C=fe.toAffine(),U=r.toBytes(C.x),N=vr;if(Si("isCompressed",we),we)return N(Uint8Array.from([fe.hasEvenY()?2:3]),U);else return N(Uint8Array.from([4]),U,r.toBytes(C.y))},fromBytes(H){let fe=H.length,we=H[0],C=H.subarray(1);if(fe===s&&(we===2||we===3)){let U=Bn(C);if(!hu(U,kt,r.ORDER))throw Error("Point is not on curve");let N=m(U),Y;try{Y=r.sqrt(N)}catch(Z){let me=Z instanceof Error?": "+Z.message:"";throw Error("Point is not on curve"+me)}let X=(Y&kt)===kt;if((we&1)===1!==X)Y=r.neg(Y);return{x:U,y:Y}}else if(fe===a&&we===4){let U=r.fromBytes(C.subarray(0,r.BYTES)),N=r.fromBytes(C.subarray(r.BYTES,2*r.BYTES));return{x:U,y:N}}else{let U=s,N=a;throw Error("invalid Point, expected length of "+U+", or uncompressed "+N+", got "+fe)}}});function y(H){let fe=o>>kt;return H>fe}function x(H){return y(H)?c(-H):H}let S=(H,fe,we)=>Bn(H.slice(fe,we));class v{constructor(H,fe,we){if(pn("r",H,kt,o),pn("s",fe,kt,o),this.r=H,this.s=fe,we!=null)this.recovery=we;Object.freeze(this)}static fromCompact(H){let fe=n;return H=yt("compactSignature",H,fe*2),new v(S(H,0,fe),S(H,fe,2*fe))}static fromDER(H){let{r:fe,s:we}=Us.toSig(yt("DER",H));return new v(fe,we)}assertValidity(){}addRecoveryBit(H){return new v(this.r,this.s,H)}recoverPublicKey(H){let{r:fe,s:we,recovery:C}=this,U=O(yt("msgHash",H));if(C==null||![0,1,2,3].includes(C))throw Error("recovery id invalid");let N=C===2||C===3?fe+t.n:fe;if(N>=r.ORDER)throw Error("recovery id 2 or 3 invalid");let Y=(C&1)===0?"02":"03",X=d.fromHex(Y+B2(N,r.BYTES)),ce=u(N),Z=c(-U*ce),me=c(we*ce),Me=d.BASE.multiplyAndAddUnsafe(X,Z,me);if(!Me)throw Error("point at infinify");return Me.assertValidity(),Me}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ag(this.toDERHex())}toDERHex(){return Us.hexFromSig(this)}toCompactRawBytes(){return ag(this.toCompactHex())}toCompactHex(){let H=n;return B2(this.r,H)+B2(this.s,H)}}let E={isValidPrivateKey(H){try{return p(H),!0}catch(fe){return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{let H=I$(t.n);return $F(t.randomBytes(H),t.n)},precompute(H=8,fe=d.BASE){return fe._setWindowSize(H),fe.multiply(BigInt(3)),fe}};function w(H,fe=!0){return d.fromPrivateKey(H).toRawBytes(fe)}function _(H){if(typeof H==="bigint")return!1;if(H instanceof d)return!0;let we=yt("key",H).length,C=r.BYTES,U=C+1,N=2*C+1;if(t.allowedPrivateKeyLengths||n===U)return;else return we===U||we===N}function T(H,fe,we=!0){if(_(H)===!0)throw Error("first arg must be private key");if(_(fe)===!1)throw Error("second arg must be public key");return d.fromHex(fe).multiply(p(H)).toRawBytes(we)}let P=t.bits2int||function(H){if(H.length>8192)throw Error("input is too large");let fe=Bn(H),we=H.length*8-i;return we>0?fe>>BigInt(we):fe},O=t.bits2int_modN||function(H){return c(P(H))},z=gu(i);function B(H){return pn("num < 2^"+i,H,ei,z),Ti(H,n)}function k(H,fe,we=G){if(["recovered","canonical"].some((Ut)=>(Ut in we)))throw Error("sign() legacy options not supported");let{hash:C,randomBytes:U}=t,{lowS:N,prehash:Y,extraEntropy:X}=we;if(N==null)N=!0;if(H=yt("msgHash",H),TG(we),Y)H=yt("prehashed msgHash",C(H));let ce=O(H),Z=p(fe),me=[B(Z),B(ce)];if(X!=null&&X!==!1){let Ut=X===!0?U(r.BYTES):X;me.push(yt("extraEntropy",Ut))}let Me=vr(...me),Be=ce;function Le(Ut){let vt=P(Ut);if(!h(vt))return;let cr=u(vt),Zr=d.BASE.multiply(vt).toAffine(),tr=c(Zr.x);if(tr===ei)return;let En=c(cr*c(Be+tr*Z));if(En===ei)return;let Wr=(Zr.x===tr?0:2)|Number(Zr.y&kt),Ws=En;if(N&&y(En))Ws=x(En),Wr^=1;return new v(tr,Ws,Wr)}return{seed:Me,k2sig:Le}}let G={lowS:t.lowS,prehash:!1},V={lowS:t.lowS,prehash:!1};function ue(H,fe,we=G){let{seed:C,k2sig:U}=k(H,fe,we),N=t;return wF(N.hash.outputLen,N.nByteLength,N.hmac)(C,U)}d.BASE._setWindowSize(8);function W(H,fe,we,C=V){let U=H;fe=yt("msgHash",fe),we=yt("publicKey",we);let{lowS:N,prehash:Y,format:X}=C;if(TG(C),"strict"in C)throw Error("options.strict was renamed to lowS");if(X!==void 0&&X!=="compact"&&X!=="der")throw Error("format must be compact or der");let ce=typeof U==="string"||Ld(U),Z=!ce&&!X&&typeof U==="object"&&U!==null&&typeof U.r==="bigint"&&typeof U.s==="bigint";if(!ce&&!Z)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");let me=void 0,Me;try{if(Z)me=new v(U.r,U.s);if(ce){try{if(X!=="compact")me=v.fromDER(U)}catch(Wr){if(!(Wr instanceof Us.Err))throw Wr}if(!me&&X!=="der")me=v.fromCompact(U)}Me=d.fromHex(we)}catch(Wr){return!1}if(!me)return!1;if(N&&me.hasHighS())return!1;if(Y)fe=t.hash(fe);let{r:Be,s:Le}=me,Ut=O(fe),vt=u(Le),cr=c(Ut*vt),Zr=c(Be*vt),tr=d.BASE.multiplyAndAddUnsafe(Me,cr,Zr)?.toAffine();if(!tr)return!1;return c(tr.x)===Be}return{CURVE:t,getPublicKey:w,getSharedSecret:T,sign:ue,verify:W,ProjectivePoint:d,Signature:v,utils:E}}function Iye(e,t){let r=e.ORDER,o=ei;for(let y=r-kt;y%rc===ei;y/=rc)o+=kt;let n=o,i=rc<<n-kt-kt,s=i*rc,a=(r-kt)/s,c=(a-kt)/rc,u=s-kt,d=i,p=e.pow(t,a),m=e.pow(t,(a+kt)/rc),h=(y,x)=>{let S=p,v=e.pow(x,u),E=e.sqr(v);E=e.mul(E,x);let w=e.mul(y,E);w=e.pow(w,c),w=e.mul(w,v),v=e.mul(w,x),E=e.mul(w,y);let _=e.mul(E,v);w=e.pow(_,d);let T=e.eql(w,e.ONE);v=e.mul(E,m),w=e.mul(_,S),E=e.cmov(v,E,T),_=e.cmov(w,_,T);for(let P=n;P>kt;P--){let O=P-rc;O=rc<<O-kt;let z=e.pow(_,O),B=e.eql(z,e.ONE);v=e.mul(E,S),S=e.mul(S,S),z=e.mul(_,S),E=e.cmov(v,E,B),_=e.cmov(z,_,B)}return{isValid:T,value:E}};if(e.ORDER%D2===Zg){let y=(e.ORDER-Zg)/D2,x=e.sqrt(e.neg(t));h=(S,v)=>{let E=e.sqr(v),w=e.mul(S,v);E=e.mul(E,w);let _=e.pow(E,y);_=e.mul(_,w);let T=e.mul(_,x),P=e.mul(e.sqr(_),v),O=e.eql(P,S),z=e.cmov(T,_,O);return{isValid:O,value:z}}}return h}function PG(e,t){if(F_(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw Error("mapToCurveSimpleSWU: invalid opts");let r=Iye(e,t.Z);if(!e.isOdd)throw Error("Fp.isOdd is not implemented!");return(o)=>{let n,i,s,a,c,u,d,p;n=e.sqr(o),n=e.mul(n,t.Z),i=e.sqr(n),i=e.add(i,n),s=e.add(i,e.ONE),s=e.mul(s,t.B),a=e.cmov(t.Z,e.neg(i),!e.eql(i,e.ZERO)),a=e.mul(a,t.A),i=e.sqr(s),u=e.sqr(a),c=e.mul(u,t.A),i=e.add(i,c),i=e.mul(i,s),u=e.mul(u,a),c=e.mul(u,t.B),i=e.add(i,c),d=e.mul(n,s);let{isValid:m,value:h}=r(i,u);p=e.mul(n,o),p=e.mul(p,h),d=e.cmov(d,s,m),p=e.cmov(p,h,m);let y=e.isOdd(o)===e.isOdd(p);p=e.cmov(e.neg(p),p,y);let x=xs(e,[a],!0)[0];return d=e.mul(d,x),{x:d,y:p}}}var EG,Us,ei,kt,rc,Zg,D2;var U2=J(()=>{O$();xu();yu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */EG=class EG extends Error{constructor(e=""){super(e)}};Us={Err:EG,_tlv:{encode:(e,t)=>{let{Err:r}=Us;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let o=t.length/2,n=sg(o);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=o>127?sg(n.length/2|128):"";return sg(e)+i+n+t},decode(e,t){let{Err:r}=Us,o=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[o++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[o++],i=!!(n&128),s=0;if(!i)s=n;else{let c=n&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 u=t.subarray(o,o+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(o+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(o,o+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(o+s)}}},_int:{encode(e){let{Err:t}=Us;if(e<ei)throw new t("integer: negative integers are not allowed");let r=sg(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}=Us;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 Bn(e)}},toSig(e){let{Err:t,_int:r,_tlv:o}=Us,n=yt("signature",e),{v:i,l:s}=o.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=o.decode(2,i),{v:u,l:d}=o.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=Us,o=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),i=o+n;return t.encode(48,i)}};ei=BigInt(0),kt=BigInt(1),rc=BigInt(2),Zg=BigInt(3),D2=BigInt(4)});function Pye(e){return{hash:e,hmac:(t,...r)=>M2(e,t,g$(...r)),randomBytes:Ud}}function kG(e,t){let r=(o)=>IG({...e,...Pye(o)});return{...r(t),create:r}}var AG=J(()=>{SG();lo();U2();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */});var Z2={};Pn(Z2,{encodeToCurve:()=>Nye,hashToCurve:()=>zye,schnorr:()=>Rye,secp256k1:()=>vn,secp256k1_hasher:()=>V2});function OG(e){let t=Jg,r=BigInt(3),o=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,d=u*u*e%t,p=Vt(d,r,t)*d%t,m=Vt(p,r,t)*d%t,h=Vt(m,t1,t)*u%t,y=Vt(h,n,t)*h%t,x=Vt(y,i,t)*y%t,S=Vt(x,a,t)*x%t,v=Vt(S,c,t)*S%t,E=Vt(v,a,t)*x%t,w=Vt(E,r,t)*d%t,_=Vt(w,s,t)*y%t,T=Vt(_,o,t)*u%t,P=Vt(T,t1,t);if(!nc.eql(nc.sqr(P),e))throw Error("Cannot find square root");return P}function r1(e,...t){let r=RG[e];if(r===void 0){let o=gs(Uint8Array.from(e,(n)=>n.charCodeAt(0)));r=vr(o,o),RG[e]=r}return gs(vr(r,...t))}function F2(e){let t=vn.utils.normPrivateKeyToScalar(e),r=G2.fromPrivateKey(t);return{scalar:r.hasEvenY()?t:Kg(-t),bytes:H2(r)}}function CG(e){pn("x",e,Wg,Jg);let t=L2(e*e),r=L2(t*e+BigInt(7)),o=OG(r);if(o%t1!==q2)o=L2(-o);let n=new G2(e,o,Wg);return n.assertValidity(),n}function zG(...e){return Kg(Dp(r1("BIP0340/challenge",...e)))}function Aye(e){return F2(e).bytes}function $ye(e,t,r=Ud(32)){let o=yt("message",e),{bytes:n,scalar:i}=F2(t),s=yt("auxRand",r,32),a=j2(i^Dp(r1("BIP0340/aux",s))),c=r1("BIP0340/nonce",a,n,o),u=Kg(Dp(c));if(u===q2)throw Error("sign failed: k is zero");let{bytes:d,scalar:p}=F2(u),m=zG(d,n,o),h=new Uint8Array(64);if(h.set(d,0),h.set(j2(Kg(p+m*i)),32),!NG(h,o,n))throw Error("sign: Invalid signature produced");return h}function NG(e,t,r){let o=yt("signature",e,64),n=yt("message",t),i=yt("publicKey",r,32);try{let s=CG(Dp(i)),a=Dp(o.subarray(0,32));if(!hu(a,Wg,Jg))return!1;let c=Dp(o.subarray(32,64));if(!hu(c,Wg,e1))return!1;let u=zG(j2(a),H2(s),n),d=kye(s,c,Kg(-u));if(!d||!d.hasEvenY()||d.toAffine().x!==a)return!1;return!0}catch(s){return!1}}var Jg,e1,q2,Wg,t1,$G=(e,t)=>(e+t/t1)/t,nc,vn,RG,H2=(e)=>e.toRawBytes(!0).slice(1),j2=(e)=>Ti(e,32),L2=(e)=>lt(e,Jg),Kg=(e)=>lt(e,e1),G2,kye=(e,t,r)=>G2.BASE.multiplyAndAddUnsafe(e,t,r),Dp,Rye,Oye,Cye,V2,zye,Nye;var oc=J(()=>{ig();lo();AG();LF();xu();yu();U2();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Jg=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),e1=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),q2=BigInt(0),Wg=BigInt(1),t1=BigInt(2);nc=vs(Jg,void 0,void 0,{sqrt:OG}),vn=kG({a:q2,b:BigInt(7),Fp:nc,n:e1,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:(e)=>{let t=e1,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),o=-Wg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),n=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,s=BigInt("0x100000000000000000000000000000000"),a=$G(i*e,t),c=$G(-o*e,t),u=lt(e-a*r-c*n,t),d=lt(-a*o-c*i,t),p=u>s,m=d>s;if(p)u=t-u;if(m)d=t-d;if(u>s||d>s)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:p,k1:u,k2neg:m,k2:d}}}},gs),RG={};G2=(()=>vn.ProjectivePoint)();Dp=Bn;Rye=(()=>({getPublicKey:Aye,sign:$ye,verify:NG,utils:{randomPrivateKey:vn.utils.randomPrivateKey,lift_x:CG,pointToBytes:H2,numberToBytesBE:Ti,bytesToNumberBE:Bn,taggedHash:r1,mod:lt}}))(),Oye=(()=>DF(nc,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map((e)=>e.map((t)=>BigInt(t)))))(),Cye=(()=>PG(nc,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:nc.create(BigInt("-11"))}))(),V2=(()=>UF(vn.ProjectivePoint,(e)=>{let{x:t,y:r}=Cye(nc.create(e[0]));return Oye(t,r)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:nc.ORDER,m:1,k:128,expand:"xmd",hash:gs}))(),zye=(()=>V2.hashToCurve)(),Nye=(()=>V2.encodeToCurve)()});import{webcrypto as Tve}from"node:crypto";import HX from"node:http";import GX from"node:https";import vl from"node:zlib";import EN,{PassThrough as IN,pipeline as _l}from"node:stream";import{Buffer as xb}from"node:buffer";function bX(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(";"),o="",n=!1,i=r[0]||"text/plain",s=i;for(let d=1;d<r.length;d++)if(r[d]==="base64")n=!0;else if(r[d]){if(s+=`;${r[d]}`,r[d].indexOf("charset=")===0)o=r[d].substring(8)}if(!r[0]&&!o.length)s+=";charset=US-ASCII",o="US-ASCII";let a=n?"base64":"ascii",c=unescape(e.substring(t+1)),u=Buffer.from(c,a);return u.type=i,u.typeFull=s,u.charset=o,u}var Gz=bX;Zf();db();import oa,{PassThrough as dN}from"node:stream";import{types as pN,deprecate as qT,promisify as NX}from"node:util";import{Buffer as to}from"node:buffer";class ra 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 Hn extends ra{constructor(e,t,r){super(e,t);if(r)this.code=this.errno=r.code,this.erroredSysCall=r.syscall}}var pb=Symbol.toStringTag,LT=(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[pb]==="URLSearchParams",Kf=(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[pb]),eN=(e)=>typeof e==="object"&&(e[pb]==="AbortSignal"||e[pb]==="EventTarget"),tN=(e,t)=>{let r=new URL(t).hostname,o=new URL(e).hostname;return r===o||r.endsWith(`.${o}`)},rN=(e,t)=>{let r=new URL(t).protocol,o=new URL(e).protocol;return r===o};var MX=NX(oa.pipeline),kn=Symbol("Body internals");class Ji{constructor(e,{size:t=0}={}){let r=null;if(e===null)e=null;else if(LT(e))e=to.from(e.toString());else if(Kf(e));else if(to.isBuffer(e));else if(pN.isAnyArrayBuffer(e))e=to.from(e);else if(ArrayBuffer.isView(e))e=to.from(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof oa);else if(e instanceof Rc)e=Xz(e),r=e.type.split("=")[1];else e=to.from(String(e));let o=e;if(to.isBuffer(e))o=oa.Readable.from(e);else if(Kf(e))o=oa.Readable.from(e.stream());if(this[kn]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=t,e instanceof oa)e.on("error",(n)=>{let i=n instanceof ra?n:new Hn(`Invalid response body while trying to fetch ${this.url}: ${n.message}`,"system",n);this[kn].error=i})}get body(){return this[kn].stream}get bodyUsed(){return this[kn].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:r}=await FT(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 Rc,o=new URLSearchParams(await this.text());for(let[n,i]of o)r.append(n,i);return r}let{toFormData:t}=await Promise.resolve().then(() => (lN(),uN));return t(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[kn].body&&this[kn].body.type||"",t=await this.arrayBuffer();return new Ki([t],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await FT(this);return new TextDecoder().decode(e)}buffer(){return FT(this)}}Ji.prototype.buffer=qT(Ji.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Ji.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:qT(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});async function FT(e){if(e[kn].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[kn].disturbed=!0,e[kn].error)throw e[kn].error;let{body:t}=e;if(t===null)return to.alloc(0);if(!(t instanceof oa))return to.alloc(0);let r=[],o=0;try{for await(let n of t){if(e.size>0&&o+n.length>e.size){let i=new Hn(`content size at ${e.url} over limit: ${e.size}`,"max-size");throw t.destroy(i),i}o+=n.length,r.push(n)}}catch(n){throw n instanceof ra?n:new Hn(`Invalid response body while trying to fetch ${e.url}: ${n.message}`,"system",n)}if(t.readableEnded===!0||t._readableState.ended===!0)try{if(r.every((n)=>typeof n==="string"))return to.from(r.join(""));return to.concat(r,o)}catch(n){throw new Hn(`Could not create Buffer from response body for ${e.url}: ${n.message}`,"system",n)}else throw new Hn(`Premature close of server response while trying to fetch ${e.url}`)}var bl=(e,t)=>{let r,o,{body:n}=e[kn];if(e.bodyUsed)throw Error("cannot clone body after it is used");if(n instanceof oa&&typeof n.getBoundary!=="function")r=new dN({highWaterMark:t}),o=new dN({highWaterMark:t}),n.pipe(r),n.pipe(o),e[kn].stream=r,n=o;return n},BX=qT((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"),hb=(e,t)=>{if(e===null)return null;if(typeof e==="string")return"text/plain;charset=UTF-8";if(LT(e))return"application/x-www-form-urlencoded;charset=UTF-8";if(Kf(e))return e.type||null;if(to.isBuffer(e)||pN.isAnyArrayBuffer(e)||ArrayBuffer.isView(e))return null;if(e instanceof Rc)return`multipart/form-data; boundary=${t[kn].boundary}`;if(e&&typeof e.getBoundary==="function")return`multipart/form-data;boundary=${BX(e)}`;if(e instanceof oa)return null;return"text/plain;charset=UTF-8"},fN=(e)=>{let{body:t}=e[kn];if(t===null)return 0;if(Kf(t))return t.size;if(to.isBuffer(t))return t.length;if(t&&typeof t.getLengthSync==="function")return t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null;return null},mN=async(e,{body:t})=>{if(t===null)e.end();else await MX(t,e)};import{types as hN}from"node:util";import yb from"node:http";var gb=typeof yb.validateHeaderName==="function"?yb.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}},HT=typeof yb.validateHeaderValue==="function"?yb.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 nn extends URLSearchParams{constructor(e){let t=[];if(e instanceof nn){let r=e.raw();for(let[o,n]of Object.entries(r))t.push(...n.map((i)=>[o,i]))}else if(e==null);else if(typeof e==="object"&&!hN.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((o)=>{if(typeof o!=="object"||hN.isBoxedPrimitive(o))throw TypeError("Each header pair must be an iterable object");return[...o]}).map((o)=>{if(o.length!==2)throw TypeError("Each header pair must be a name/value tuple");return[...o]})}}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,o])=>(gb(r),HT(r,String(o)),[String(r).toLowerCase(),String(o)])):void 0;super(t);return new Proxy(this,{get(r,o,n){switch(o){case"append":case"set":return(i,s)=>(gb(i),HT(i,String(s)),URLSearchParams.prototype[o].call(r,String(i).toLowerCase(),String(s)));case"delete":case"has":case"getAll":return(i)=>(gb(i),URLSearchParams.prototype[o].call(r,String(i).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,o,n)}}})}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(nn.prototype,["get","entries","forEach","values"].reduce((e,t)=>(e[t]={enumerable:!0},e),{}));function gN(e=[]){return new nn(e.reduce((t,r,o,n)=>{if(o%2===0)t.push(n.slice(o,o+2));return t},[]).filter(([t,r])=>{try{return gb(t),HT(t,String(r)),!0}catch{return!1}}))}var DX=new Set([301,302,303,307,308]),bb=(e)=>DX.has(e);var Po=Symbol("Response internals");class Ar extends Ji{constructor(e=null,t={}){super(e,t);let r=t.status!=null?t.status:200,o=new nn(t.headers);if(e!==null&&!o.has("Content-Type")){let n=hb(e,this);if(n)o.append("Content-Type",n)}this[Po]={type:"default",url:t.url,status:r,statusText:t.statusText||"",headers:o,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[Po].type}get url(){return this[Po].url||""}get status(){return this[Po].status}get ok(){return this[Po].status>=200&&this[Po].status<300}get redirected(){return this[Po].counter>0}get statusText(){return this[Po].statusText}get headers(){return this[Po].headers}get highWaterMark(){return this[Po].highWaterMark}clone(){return new Ar(bl(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(!bb(t))throw RangeError('Failed to execute "redirect" on "response": Invalid status code');return new Ar(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new Ar(null,{status:0,statusText:""});return e[Po].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 o=new nn(t&&t.headers);if(!o.has("content-type"))o.set("content-type","application/json");return new Ar(r,{...t,headers:o})}get[Symbol.toStringTag](){return"Response"}}Object.defineProperties(Ar.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 jX}from"node:url";import{deprecate as FX}from"node:util";var yN=(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 UX}from"node:net";function bN(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 xN=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),vN="strict-origin-when-cross-origin";function _N(e){if(!xN.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function LX(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let t=e.host.replace(/(^\[)|(]$)/g,""),r=UX(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 xl(e){if(/^about:(blank|srcdoc)$/.test(e))return!0;if(e.protocol==="data:")return!0;if(/^(blob|filesystem):$/.test(e.protocol))return!0;return LX(e)}function wN(e,{referrerURLCallback:t,referrerOriginCallback:r}={}){if(e.referrer==="no-referrer"||e.referrerPolicy==="")return null;let o=e.referrerPolicy;if(e.referrer==="about:client")return"no-referrer";let n=e.referrer,i=bN(n),s=bN(n,!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(o){case"no-referrer":return"no-referrer";case"origin":return s;case"unsafe-url":return i;case"strict-origin":if(xl(i)&&!xl(a))return"no-referrer";return s.toString();case"strict-origin-when-cross-origin":if(i.origin===a.origin)return i;if(xl(i)&&!xl(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(xl(i)&&!xl(a))return"no-referrer";return i;default:throw TypeError(`Invalid referrerPolicy: ${o}`)}}function SN(e){let t=(e.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let o of t)if(o&&xN.has(o))r=o;return r}var br=Symbol("Request internals"),Yf=(e)=>typeof e==="object"&&typeof e[br]==="object",qX=FX(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)");class Yi extends Ji{constructor(e,t={}){let r;if(Yf(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 o=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o))o=o.toUpperCase();if(!Yf(t)&&"data"in t)qX();if((t.body!=null||Yf(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw TypeError("Request with GET/HEAD method cannot have body");let n=t.body?t.body:Yf(e)&&e.body!==null?bl(e):null;super(n,{size:t.size||e.size||0});let i=new nn(t.headers||e.headers||{});if(n!==null&&!i.has("Content-Type")){let c=hb(n,this);if(c)i.set("Content-Type",c)}let s=Yf(e)?e.signal:null;if("signal"in t)s=t.signal;if(s!=null&&!eN(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[br]={method:o,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[br].method}get url(){return jX(this[br].parsedURL)}get headers(){return this[br].headers}get redirect(){return this[br].redirect}get signal(){return this[br].signal}get referrer(){if(this[br].referrer==="no-referrer")return"";if(this[br].referrer==="client")return"about:client";if(this[br].referrer)return this[br].referrer.toString();return}get referrerPolicy(){return this[br].referrerPolicy}set referrerPolicy(e){this[br].referrerPolicy=_N(e)}clone(){return new Yi(this)}get[Symbol.toStringTag](){return"Request"}}Object.defineProperties(Yi.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 TN=(e)=>{let{parsedURL:t}=e[br],r=new nn(e[br].headers);if(!r.has("Accept"))r.set("Accept","*/*");let o=null;if(e.body===null&&/^(post|put)$/i.test(e.method))o="0";if(e.body!==null){let a=fN(e);if(typeof a==="number"&&!Number.isNaN(a))o=String(a)}if(o)r.set("Content-Length",o);if(e.referrerPolicy==="")e.referrerPolicy=vN;if(e.referrer&&e.referrer!=="no-referrer")e[br].referrer=wN(e);else e[br].referrer="no-referrer";if(e[br].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:n}=e;if(typeof n==="function")n=n(t);let i=yN(t),s={path:t.pathname+i,method:e.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:e.insecureHTTPParser,agent:n};return{parsedURL:t,options:s}};class GT extends ra{constructor(e,t="aborted"){super(e,t)}}db();jT();var VX=new Set(["data:","http:","https:"]);async function vb(e,t){return new Promise((r,o)=>{let n=new Yi(e,t),{parsedURL:i,options:s}=TN(n);if(!VX.has(i.protocol))throw TypeError(`node-fetch cannot load ${e}. URL scheme "${i.protocol.replace(/:$/,"")}" is not supported.`);if(i.protocol==="data:"){let y=Gz(n.url),x=new Ar(y,{headers:{"Content-Type":y.typeFull}});r(x);return}let a=(i.protocol==="https:"?GX:HX).request,{signal:c}=n,u=null,d=()=>{let y=new GT("The operation was aborted.");if(o(y),n.body&&n.body instanceof EN.Readable)n.body.destroy(y);if(!u||!u.body)return;u.body.emit("error",y)};if(c&&c.aborted){d();return}let p=()=>{d(),h()},m=a(i.toString(),s);if(c)c.addEventListener("abort",p);let h=()=>{if(m.abort(),c)c.removeEventListener("abort",p)};if(m.on("error",(y)=>{o(new Hn(`request to ${n.url} failed, reason: ${y.message}`,"system",y)),h()}),ZX(m,(y)=>{if(u&&u.body)u.body.destroy(y)}),process.version<"v14")m.on("socket",(y)=>{let x;y.prependListener("end",()=>{x=y._eventsCount}),y.prependListener("close",(S)=>{if(u&&x<y._eventsCount&&!S){let v=Error("Premature close");v.code="ERR_STREAM_PREMATURE_CLOSE",u.body.emit("error",v)}})});m.on("response",(y)=>{m.setTimeout(0);let x=gN(y.rawHeaders);if(bb(y.statusCode)){let _=x.get("Location"),T=null;try{T=_===null?null:new URL(_,n.url)}catch{if(n.redirect!=="manual"){o(new Hn(`uri requested responds with an invalid redirect URL: ${_}`,"invalid-redirect")),h();return}}switch(n.redirect){case"error":o(new Hn(`uri requested responds with a redirect, redirect mode is set to error: ${n.url}`,"no-redirect")),h();return;case"manual":break;case"follow":{if(T===null)break;if(n.counter>=n.follow){o(new Hn(`maximum redirect reached at: ${n.url}`,"max-redirect")),h();return}let P={headers:new nn(n.headers),follow:n.follow,counter:n.counter+1,agent:n.agent,compress:n.compress,method:n.method,body:bl(n),signal:n.signal,size:n.size,referrer:n.referrer,referrerPolicy:n.referrerPolicy};if(!tN(n.url,T)||!rN(n.url,T))for(let z of["authorization","www-authenticate","cookie","cookie2"])P.headers.delete(z);if(y.statusCode!==303&&n.body&&t.body instanceof EN.Readable){o(new Hn("Cannot follow redirect with body being a readable stream","unsupported-redirect")),h();return}if(y.statusCode===303||(y.statusCode===301||y.statusCode===302)&&n.method==="POST")P.method="GET",P.body=void 0,P.headers.delete("content-length");let O=SN(x);if(O)P.referrerPolicy=O;r(vb(new Yi(T,P))),h();return}default:return o(TypeError(`Redirect option '${n.redirect}' is not a valid value of RequestRedirect`))}}if(c)y.once("end",()=>{c.removeEventListener("abort",p)});let S=_l(y,new IN,(_)=>{if(_)o(_)});if(process.version<"v12.10")y.on("aborted",p);let v={url:n.url,status:y.statusCode,statusText:y.statusMessage,headers:x,size:n.size,counter:n.counter,highWaterMark:n.highWaterMark},E=x.get("Content-Encoding");if(!n.compress||n.method==="HEAD"||E===null||y.statusCode===204||y.statusCode===304){u=new Ar(S,v),r(u);return}let w={flush:vl.Z_SYNC_FLUSH,finishFlush:vl.Z_SYNC_FLUSH};if(E==="gzip"||E==="x-gzip"){S=_l(S,vl.createGunzip(w),(_)=>{if(_)o(_)}),u=new Ar(S,v),r(u);return}if(E==="deflate"||E==="x-deflate"){let _=_l(y,new IN,(T)=>{if(T)o(T)});_.once("data",(T)=>{if((T[0]&15)===8)S=_l(S,vl.createInflate(),(P)=>{if(P)o(P)});else S=_l(S,vl.createInflateRaw(),(P)=>{if(P)o(P)});u=new Ar(S,v),r(u)}),_.once("end",()=>{if(!u)u=new Ar(S,v),r(u)});return}if(E==="br"){S=_l(S,vl.createBrotliDecompress(),(_)=>{if(_)o(_)}),u=new Ar(S,v),r(u);return}u=new Ar(S,v),r(u)}),mN(m,n).catch(o)})}function ZX(e,t){let r=xb.from(`0\r
65
65
  \r
66
- `),o=!1,n=!1,i;e.on("response",(s)=>{let{headers:a}=s;o=a["transfer-encoding"]==="chunked"&&!a["content-length"]}),e.on("socket",(s)=>{let a=()=>{if(o&&!n){let u=Error("Premature close");u.code="ERR_STREAM_PREMATURE_CLOSE",t(u)}},c=(u)=>{if(n=xb.compare(u.slice(-5),r)===0,!n&&i)n=xb.compare(i.slice(-3),r.slice(0,3))===0&&xb.compare(u.slice(-2),r.slice(3))===0;i=u};s.prependListener("close",a),s.on("data",c),e.on("close",()=>{s.removeListener("close",a),s.removeListener("data",c)})})}var mte=rn(_M(),1),hte=rn(kb(),1),gte=rn(Tl(),1),yte=rn(YT(),1),bte=rn(XT(),1),xte=rn(iE(),1),sE=rn(Ob(),1),vte=rn(PM(),1);var tt;(function(e){e.assertEqual=(n)=>{};function t(n){}e.assertIs=t;function r(n){throw Error()}e.assertNever=r,e.arrayToEnum=(n)=>{let i={};for(let s of n)i[s]=s;return i},e.getValidEnumValues=(n)=>{let i=e.objectKeys(n).filter((a)=>typeof n[n[a]]!=="number"),s={};for(let a of i)s[a]=n[a];return e.objectValues(s)},e.objectValues=(n)=>e.objectKeys(n).map(function(i){return n[i]}),e.objectKeys=typeof Object.keys==="function"?(n)=>Object.keys(n):(n)=>{let i=[];for(let s in n)if(Object.prototype.hasOwnProperty.call(n,s))i.push(s);return i},e.find=(n,i)=>{for(let s of n)if(i(s))return s;return},e.isInteger=typeof Number.isInteger==="function"?(n)=>Number.isInteger(n):(n)=>typeof n==="number"&&Number.isFinite(n)&&Math.floor(n)===n;function o(n,i=" | "){return n.map((s)=>typeof s==="string"?`'${s}'`:s).join(i)}e.joinValues=o,e.jsonStringifyReplacer=(n,i)=>{if(typeof i==="bigint")return i.toString();return i}})(tt||(tt={}));var kM;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(kM||(kM={}));var le=tt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ts=(e)=>{switch(typeof e){case"undefined":return le.undefined;case"string":return le.string;case"number":return Number.isNaN(e)?le.nan:le.number;case"boolean":return le.boolean;case"function":return le.function;case"bigint":return le.bigint;case"symbol":return le.symbol;case"object":if(Array.isArray(e))return le.array;if(e===null)return le.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return le.promise;if(typeof Map<"u"&&e instanceof Map)return le.map;if(typeof Set<"u"&&e instanceof Set)return le.set;if(typeof Date<"u"&&e instanceof Date)return le.date;return le.object;default:return le.unknown}};var ne=tt.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(n){return n.message},r={_errors:[]},o=(n)=>{for(let i of n.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(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 o(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,tt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t=Object.create(null),r=[];for(let o of this.issues)if(o.path.length>0){let n=o.path[0];t[n]=t[n]||[],t[n].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Vn.create=(e)=>new Vn(e);var _te=(e,t)=>{let r;switch(e.code){case ne.invalid_type:if(e.received===le.undefined)r="Required";else r=`Expected ${e.expected}, received ${e.received}`;break;case ne.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,tt.jsonStringifyReplacer)}`;break;case ne.unrecognized_keys:r=`Unrecognized key(s) in object: ${tt.joinValues(e.keys,", ")}`;break;case ne.invalid_union:r="Invalid input";break;case ne.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${tt.joinValues(e.options)}`;break;case ne.invalid_enum_value:r=`Invalid enum value. Expected ${tt.joinValues(e.options)}, received '${e.received}'`;break;case ne.invalid_arguments:r="Invalid function arguments";break;case ne.invalid_return_type:r="Invalid function return type";break;case ne.invalid_date:r="Invalid date";break;case ne.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 tt.assertNever(e.validation);else if(e.validation!=="regex")r=`Invalid ${e.validation}`;else r="Invalid";break;case ne.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 ne.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 ne.custom:r="Invalid input";break;case ne.invalid_intersection_types:r="Intersection results could not be merged";break;case ne.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ne.not_finite:r="Number must be finite";break;default:r=t.defaultError,tt.assertNever(e)}return{message:r}},ua=_te;var wte=ua;function im(){return wte}var zb=(e)=>{let{data:t,path:r,errorMaps:o,issueData:n}=e,i=[...r,...n.path||[]],s={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let a="",c=o.filter((u)=>!!u).slice().reverse();for(let u of c)a=u(s,{data:t,defaultError:a}).message;return{...n,path:i,message:a}};function he(e,t){let r=im(),o=zb({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===ua?void 0:ua].filter((n)=>!!n)});e.common.issues.push(o)}class Kr{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 o of t){if(o.status==="aborted")return Oe;if(o.status==="dirty")e.dirty();r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let o of t){let n=await o.key,i=await o.value;r.push({key:n,value:i})}return Kr.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let o of t){let{key:n,value:i}=o;if(n.status==="aborted")return Oe;if(i.status==="aborted")return Oe;if(n.status==="dirty")e.dirty();if(i.status==="dirty")e.dirty();if(n.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet))r[n.value]=i.value}return{status:e.value,value:r}}}var Oe=Object.freeze({status:"aborted"}),$l=(e)=>({status:"dirty",value:e}),on=(e)=>({status:"valid",value:e}),aE=(e)=>e.status==="aborted",cE=(e)=>e.status==="dirty",Bc=(e)=>e.status==="valid",sm=(e)=>typeof Promise<"u"&&e instanceof Promise;var _e;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(_e||(_e={}));class Ao{constructor(e,t,r,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=o}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 AM=(e,t)=>{if(Bc(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 He(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:o,description:n}=e;if(t&&(r||o))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:n};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??o??a.defaultError};if(s.code!=="invalid_type")return{message:a.defaultError};return{message:c??r??a.defaultError}},description:n}}class Qe{get description(){return this._def.description}_getType(e){return ts(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ts(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Kr,ctx:{common:e.parent.common,data:e.data,parsedType:ts(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(sm(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:ts(e)},o=this._parseSync({data:e,path:r.path,parent:r});return AM(r,o)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ts(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Bc(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)=>Bc(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:ts(e)},o=this._parse({data:e,path:r.path,parent:r}),n=await(sm(o)?o:Promise.resolve(o));return AM(r,n)}refine(e,t){let r=(o)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(o);else return t};return this._refinement((o,n)=>{let i=e(o),s=()=>n.addIssue({code:ne.custom,...r(o)});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,o)=>{if(!e(r))return o.addIssue(typeof t==="function"?t(r,o):t),!1;else return!0})}_refinement(e){return new fi({schema:this,typeName:ie.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 pi.create(this,this._def)}nullable(){return la.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return di.create(this)}promise(){return Nl.create(this,this._def)}or(e){return dm.create([this,e],this._def)}and(e){return pm.create(this,e,this._def)}transform(e){return new fi({...He(this._def),schema:this,typeName:ie.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new gm({...He(this._def),innerType:this,defaultValue:t,typeName:ie.ZodDefault})}brand(){return new pE({typeName:ie.ZodBranded,type:this,...He(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new ym({...He(this._def),innerType:this,catchValue:t,typeName:ie.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return Fb.create(this,e)}readonly(){return bm.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Ste=/^c[^\s-]{8,}$/i,Tte=/^[0-9a-z]+$/,Ete=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ite=/^[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,Pte=/^[a-z0-9_-]{21}$/i,kte=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ate=/^[-+]?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)?)??$/,$te=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Rte="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",uE,Ote=/^(?:(?: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])$/,Cte=/^(?:(?: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])$/,zte=/^(([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]))$/,Nte=/^(([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])$/,Mte=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Bte=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$M="((\\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])))",Dte=new RegExp(`^${$M}$`);function RM(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 Ute(e){return new RegExp(`^${RM(e)}$`)}function Lte(e){let t=`${$M}T${RM(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 jte(e,t){if((t==="v4"||!t)&&Ote.test(e))return!0;if((t==="v6"||!t)&&zte.test(e))return!0;return!1}function Fte(e,t){if(!kte.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let o=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(o));if(typeof n!=="object"||n===null)return!1;if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(t&&n.alg!==t)return!1;return!0}catch{return!1}}function qte(e,t){if((t==="v4"||!t)&&Cte.test(e))return!0;if((t==="v6"||!t)&&Nte.test(e))return!0;return!1}class ns extends Qe{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==le.string){let n=this._getOrReturnCtx(e);return he(n,{code:ne.invalid_type,expected:le.string,received:n.parsedType}),Oe}let r=new Kr,o=void 0;for(let n of this._def.checks)if(n.kind==="min"){if(e.data.length<n.value)o=this._getOrReturnCtx(e,o),he(o,{code:ne.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),r.dirty()}else if(n.kind==="max"){if(e.data.length>n.value)o=this._getOrReturnCtx(e,o),he(o,{code:ne.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),r.dirty()}else if(n.kind==="length"){let i=e.data.length>n.value,s=e.data.length<n.value;if(i||s){if(o=this._getOrReturnCtx(e,o),i)he(o,{code:ne.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message});else if(s)he(o,{code:ne.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message});r.dirty()}}else if(n.kind==="email"){if(!$te.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"email",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="emoji"){if(!uE)uE=new RegExp(Rte,"u");if(!uE.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"emoji",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="uuid"){if(!Ite.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"uuid",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="nanoid"){if(!Pte.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"nanoid",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="cuid"){if(!Ste.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"cuid",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="cuid2"){if(!Tte.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"cuid2",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="ulid"){if(!Ete.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"ulid",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),he(o,{validation:"url",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="regex"){if(n.regex.lastIndex=0,!n.regex.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"regex",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="trim")e.data=e.data.trim();else if(n.kind==="includes"){if(!e.data.includes(n.value,n.position))o=this._getOrReturnCtx(e,o),he(o,{code:ne.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),r.dirty()}else if(n.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(n.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(n.kind==="startsWith"){if(!e.data.startsWith(n.value))o=this._getOrReturnCtx(e,o),he(o,{code:ne.invalid_string,validation:{startsWith:n.value},message:n.message}),r.dirty()}else if(n.kind==="endsWith"){if(!e.data.endsWith(n.value))o=this._getOrReturnCtx(e,o),he(o,{code:ne.invalid_string,validation:{endsWith:n.value},message:n.message}),r.dirty()}else if(n.kind==="datetime"){if(!Lte(n).test(e.data))o=this._getOrReturnCtx(e,o),he(o,{code:ne.invalid_string,validation:"datetime",message:n.message}),r.dirty()}else if(n.kind==="date"){if(!Dte.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{code:ne.invalid_string,validation:"date",message:n.message}),r.dirty()}else if(n.kind==="time"){if(!Ute(n).test(e.data))o=this._getOrReturnCtx(e,o),he(o,{code:ne.invalid_string,validation:"time",message:n.message}),r.dirty()}else if(n.kind==="duration"){if(!Ate.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"duration",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="ip"){if(!jte(e.data,n.version))o=this._getOrReturnCtx(e,o),he(o,{validation:"ip",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="jwt"){if(!Fte(e.data,n.alg))o=this._getOrReturnCtx(e,o),he(o,{validation:"jwt",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="cidr"){if(!qte(e.data,n.version))o=this._getOrReturnCtx(e,o),he(o,{validation:"cidr",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="base64"){if(!Mte.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"base64",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="base64url"){if(!Bte.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"base64url",code:ne.invalid_string,message:n.message}),r.dirty()}else tt.assertNever(n);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement((o)=>e.test(o),{validation:t,code:ne.invalid_string,..._e.errToObj(r)})}_addCheck(e){return new ns({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",..._e.errToObj(e)})}url(e){return this._addCheck({kind:"url",..._e.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",..._e.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",..._e.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",..._e.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",..._e.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",..._e.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",..._e.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",..._e.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",..._e.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",..._e.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",..._e.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",..._e.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,..._e.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,..._e.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",..._e.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,..._e.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,..._e.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,..._e.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,..._e.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,..._e.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,..._e.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,..._e.errToObj(t)})}nonempty(e){return this.min(1,_e.errToObj(e))}trim(){return new ns({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ns({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ns({...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}}ns.create=(e)=>new ns({checks:[],typeName:ie.ZodString,coerce:e?.coerce??!1,...He(e)});function Hte(e,t){let r=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,n=r>o?r:o,i=Number.parseInt(e.toFixed(n).replace(".","")),s=Number.parseInt(t.toFixed(n).replace(".",""));return i%s/10**n}class Ol extends Qe{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)!==le.number){let n=this._getOrReturnCtx(e);return he(n,{code:ne.invalid_type,expected:le.number,received:n.parsedType}),Oe}let r=void 0,o=new Kr;for(let n of this._def.checks)if(n.kind==="int"){if(!tt.isInteger(e.data))r=this._getOrReturnCtx(e,r),he(r,{code:ne.invalid_type,expected:"integer",received:"float",message:n.message}),o.dirty()}else if(n.kind==="min"){if(n.inclusive?e.data<n.value:e.data<=n.value)r=this._getOrReturnCtx(e,r),he(r,{code:ne.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),o.dirty()}else if(n.kind==="max"){if(n.inclusive?e.data>n.value:e.data>=n.value)r=this._getOrReturnCtx(e,r),he(r,{code:ne.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),o.dirty()}else if(n.kind==="multipleOf"){if(Hte(e.data,n.value)!==0)r=this._getOrReturnCtx(e,r),he(r,{code:ne.not_multiple_of,multipleOf:n.value,message:n.message}),o.dirty()}else if(n.kind==="finite"){if(!Number.isFinite(e.data))r=this._getOrReturnCtx(e,r),he(r,{code:ne.not_finite,message:n.message}),o.dirty()}else tt.assertNever(n);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,_e.toString(t))}gt(e,t){return this.setLimit("min",e,!1,_e.toString(t))}lte(e,t){return this.setLimit("max",e,!0,_e.toString(t))}lt(e,t){return this.setLimit("max",e,!1,_e.toString(t))}setLimit(e,t,r,o){return new Ol({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:_e.toString(o)}]})}_addCheck(e){return new Ol({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:_e.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_e.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_e.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_e.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_e.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:_e.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:_e.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_e.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_e.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"&&tt.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)}}Ol.create=(e)=>new Ol({checks:[],typeName:ie.ZodNumber,coerce:e?.coerce||!1,...He(e)});class Cl extends Qe{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)!==le.bigint)return this._getInvalidInput(e);let r=void 0,o=new Kr;for(let n of this._def.checks)if(n.kind==="min"){if(n.inclusive?e.data<n.value:e.data<=n.value)r=this._getOrReturnCtx(e,r),he(r,{code:ne.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),o.dirty()}else if(n.kind==="max"){if(n.inclusive?e.data>n.value:e.data>=n.value)r=this._getOrReturnCtx(e,r),he(r,{code:ne.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),o.dirty()}else if(n.kind==="multipleOf"){if(e.data%n.value!==BigInt(0))r=this._getOrReturnCtx(e,r),he(r,{code:ne.not_multiple_of,multipleOf:n.value,message:n.message}),o.dirty()}else tt.assertNever(n);return{status:o.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return he(t,{code:ne.invalid_type,expected:le.bigint,received:t.parsedType}),Oe}gte(e,t){return this.setLimit("min",e,!0,_e.toString(t))}gt(e,t){return this.setLimit("min",e,!1,_e.toString(t))}lte(e,t){return this.setLimit("max",e,!0,_e.toString(t))}lt(e,t){return this.setLimit("max",e,!1,_e.toString(t))}setLimit(e,t,r,o){return new Cl({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:_e.toString(o)}]})}_addCheck(e){return new Cl({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:_e.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_e.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_e.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_e.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:_e.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}}Cl.create=(e)=>new Cl({checks:[],typeName:ie.ZodBigInt,coerce:e?.coerce??!1,...He(e)});class Nb extends Qe{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==le.boolean){let r=this._getOrReturnCtx(e);return he(r,{code:ne.invalid_type,expected:le.boolean,received:r.parsedType}),Oe}return on(e.data)}}Nb.create=(e)=>new Nb({typeName:ie.ZodBoolean,coerce:e?.coerce||!1,...He(e)});class cm extends Qe{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==le.date){let n=this._getOrReturnCtx(e);return he(n,{code:ne.invalid_type,expected:le.date,received:n.parsedType}),Oe}if(Number.isNaN(e.data.getTime())){let n=this._getOrReturnCtx(e);return he(n,{code:ne.invalid_date}),Oe}let r=new Kr,o=void 0;for(let n of this._def.checks)if(n.kind==="min"){if(e.data.getTime()<n.value)o=this._getOrReturnCtx(e,o),he(o,{code:ne.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),r.dirty()}else if(n.kind==="max"){if(e.data.getTime()>n.value)o=this._getOrReturnCtx(e,o),he(o,{code:ne.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),r.dirty()}else tt.assertNever(n);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new cm({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:_e.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:_e.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}}cm.create=(e)=>new cm({checks:[],coerce:e?.coerce||!1,typeName:ie.ZodDate,...He(e)});class Mb extends Qe{_parse(e){if(this._getType(e)!==le.symbol){let r=this._getOrReturnCtx(e);return he(r,{code:ne.invalid_type,expected:le.symbol,received:r.parsedType}),Oe}return on(e.data)}}Mb.create=(e)=>new Mb({typeName:ie.ZodSymbol,...He(e)});class um extends Qe{_parse(e){if(this._getType(e)!==le.undefined){let r=this._getOrReturnCtx(e);return he(r,{code:ne.invalid_type,expected:le.undefined,received:r.parsedType}),Oe}return on(e.data)}}um.create=(e)=>new um({typeName:ie.ZodUndefined,...He(e)});class lm extends Qe{_parse(e){if(this._getType(e)!==le.null){let r=this._getOrReturnCtx(e);return he(r,{code:ne.invalid_type,expected:le.null,received:r.parsedType}),Oe}return on(e.data)}}lm.create=(e)=>new lm({typeName:ie.ZodNull,...He(e)});class Bb extends Qe{constructor(){super(...arguments);this._any=!0}_parse(e){return on(e.data)}}Bb.create=(e)=>new Bb({typeName:ie.ZodAny,...He(e)});class Dc extends Qe{constructor(){super(...arguments);this._unknown=!0}_parse(e){return on(e.data)}}Dc.create=(e)=>new Dc({typeName:ie.ZodUnknown,...He(e)});class os extends Qe{_parse(e){let t=this._getOrReturnCtx(e);return he(t,{code:ne.invalid_type,expected:le.never,received:t.parsedType}),Oe}}os.create=(e)=>new os({typeName:ie.ZodNever,...He(e)});class Db extends Qe{_parse(e){if(this._getType(e)!==le.undefined){let r=this._getOrReturnCtx(e);return he(r,{code:ne.invalid_type,expected:le.void,received:r.parsedType}),Oe}return on(e.data)}}Db.create=(e)=>new Db({typeName:ie.ZodVoid,...He(e)});class di extends Qe{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),o=this._def;if(t.parsedType!==le.array)return he(t,{code:ne.invalid_type,expected:le.array,received:t.parsedType}),Oe;if(o.exactLength!==null){let i=t.data.length>o.exactLength.value,s=t.data.length<o.exactLength.value;if(i||s)he(t,{code:i?ne.too_big:ne.too_small,minimum:s?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty()}if(o.minLength!==null){if(t.data.length<o.minLength.value)he(t,{code:ne.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()}if(o.maxLength!==null){if(t.data.length>o.maxLength.value)he(t,{code:ne.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()}if(t.common.async)return Promise.all([...t.data].map((i,s)=>o.type._parseAsync(new Ao(t,i,t.path,s)))).then((i)=>Kr.mergeArray(r,i));let n=[...t.data].map((i,s)=>o.type._parseSync(new Ao(t,i,t.path,s)));return Kr.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new di({...this._def,minLength:{value:e,message:_e.toString(t)}})}max(e,t){return new di({...this._def,maxLength:{value:e,message:_e.toString(t)}})}length(e,t){return new di({...this._def,exactLength:{value:e,message:_e.toString(t)}})}nonempty(e){return this.min(1,e)}}di.create=(e,t)=>new di({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ie.ZodArray,...He(t)});function Rl(e){if(e instanceof Qt){let t={};for(let r in e.shape){let o=e.shape[r];t[r]=pi.create(Rl(o))}return new Qt({...e._def,shape:()=>t})}else if(e instanceof di)return new di({...e._def,type:Rl(e.element)});else if(e instanceof pi)return pi.create(Rl(e.unwrap()));else if(e instanceof la)return la.create(Rl(e.unwrap()));else if(e instanceof is)return is.create(e.items.map((t)=>Rl(t)));else return e}class Qt extends Qe{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=tt.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==le.object){let c=this._getOrReturnCtx(e);return he(c,{code:ne.invalid_type,expected:le.object,received:c.parsedType}),Oe}let{status:r,ctx:o}=this._processInputParams(e),{shape:n,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof os&&this._def.unknownKeys==="strip")){for(let c in o.data)if(!i.includes(c))s.push(c)}let a=[];for(let c of i){let u=n[c],d=o.data[c];a.push({key:{status:"valid",value:c},value:u._parse(new Ao(o,d,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof os){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of s)a.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict"){if(s.length>0)he(o,{code:ne.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 u of s){let d=o.data[u];a.push({key:{status:"valid",value:u},value:c._parse(new Ao(o,d,o.path,u)),alwaysSet:u in o.data})}}if(o.common.async)return Promise.resolve().then(async()=>{let c=[];for(let u of a){let d=await u.key,p=await u.value;c.push({key:d,value:p,alwaysSet:u.alwaysSet})}return c}).then((c)=>Kr.mergeObjectSync(r,c));else return Kr.mergeObjectSync(r,a)}get shape(){return this._def.shape()}strict(e){return _e.errToObj,new Qt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let o=this._def.errorMap?.(t,r).message??r.defaultError;if(t.code==="unrecognized_keys")return{message:_e.errToObj(e).message??o};return{message:o}}}:{}})}strip(){return new Qt({...this._def,unknownKeys:"strip"})}passthrough(){return new Qt({...this._def,unknownKeys:"passthrough"})}extend(e){return new Qt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Qt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ie.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Qt({...this._def,catchall:e})}pick(e){let t={};for(let r of tt.objectKeys(e))if(e[r]&&this.shape[r])t[r]=this.shape[r];return new Qt({...this._def,shape:()=>t})}omit(e){let t={};for(let r of tt.objectKeys(this.shape))if(!e[r])t[r]=this.shape[r];return new Qt({...this._def,shape:()=>t})}deepPartial(){return Rl(this)}partial(e){let t={};for(let r of tt.objectKeys(this.shape)){let o=this.shape[r];if(e&&!e[r])t[r]=o;else t[r]=o.optional()}return new Qt({...this._def,shape:()=>t})}required(e){let t={};for(let r of tt.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let n=this.shape[r];while(n instanceof pi)n=n._def.innerType;t[r]=n}return new Qt({...this._def,shape:()=>t})}keyof(){return OM(tt.objectKeys(this.shape))}}Qt.create=(e,t)=>new Qt({shape:()=>e,unknownKeys:"strip",catchall:os.create(),typeName:ie.ZodObject,...He(t)});Qt.strictCreate=(e,t)=>new Qt({shape:()=>e,unknownKeys:"strict",catchall:os.create(),typeName:ie.ZodObject,...He(t)});Qt.lazycreate=(e,t)=>new Qt({shape:e,unknownKeys:"strip",catchall:os.create(),typeName:ie.ZodObject,...He(t)});class dm extends Qe{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function o(n){for(let s of n)if(s.result.status==="valid")return s.result;for(let s of n)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;let i=n.map((s)=>new Vn(s.ctx.common.issues));return he(t,{code:ne.invalid_union,unionErrors:i}),Oe}if(t.common.async)return Promise.all(r.map(async(n)=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await n._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(o);else{let n=void 0,i=[];for(let a of r){let c={...t,common:{...t.common,issues:[]},parent:null},u=a._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;else if(u.status==="dirty"&&!n)n={result:u,ctx:c};if(c.common.issues.length)i.push(c.common.issues)}if(n)return t.common.issues.push(...n.ctx.common.issues),n.result;let s=i.map((a)=>new Vn(a));return he(t,{code:ne.invalid_union,unionErrors:s}),Oe}}get options(){return this._def.options}}dm.create=(e,t)=>new dm({options:e,typeName:ie.ZodUnion,...He(t)});var rs=(e)=>{if(e instanceof fm)return rs(e.schema);else if(e instanceof fi)return rs(e.innerType());else if(e instanceof mm)return[e.value];else if(e instanceof Uc)return e.options;else if(e instanceof hm)return tt.objectValues(e.enum);else if(e instanceof gm)return rs(e._def.innerType);else if(e instanceof um)return[void 0];else if(e instanceof lm)return[null];else if(e instanceof pi)return[void 0,...rs(e.unwrap())];else if(e instanceof la)return[null,...rs(e.unwrap())];else if(e instanceof pE)return rs(e.unwrap());else if(e instanceof bm)return rs(e.unwrap());else if(e instanceof ym)return rs(e._def.innerType);else return[]};class dE extends Qe{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==le.object)return he(t,{code:ne.invalid_type,expected:le.object,received:t.parsedType}),Oe;let r=this.discriminator,o=t.data[r],n=this.optionsMap.get(o);if(!n)return he(t,{code:ne.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Oe;if(t.common.async)return n._parseAsync({data:t.data,path:t.path,parent:t});else return n._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 o=new Map;for(let n of t){let i=rs(n.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(o.has(s))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);o.set(s,n)}}return new dE({typeName:ie.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...He(r)})}}function lE(e,t){let r=ts(e),o=ts(t);if(e===t)return{valid:!0,data:e};else if(r===le.object&&o===le.object){let n=tt.objectKeys(t),i=tt.objectKeys(e).filter((a)=>n.indexOf(a)!==-1),s={...e,...t};for(let a of i){let c=lE(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===le.array&&o===le.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let i=0;i<e.length;i++){let s=e[i],a=t[i],c=lE(s,a);if(!c.valid)return{valid:!1};n.push(c.data)}return{valid:!0,data:n}}else if(r===le.date&&o===le.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class pm extends Qe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),o=(n,i)=>{if(aE(n)||aE(i))return Oe;let s=lE(n.value,i.value);if(!s.valid)return he(r,{code:ne.invalid_intersection_types}),Oe;if(cE(n)||cE(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(([n,i])=>o(n,i));else return o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}pm.create=(e,t,r)=>new pm({left:e,right:t,typeName:ie.ZodIntersection,...He(r)});class is extends Qe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==le.array)return he(r,{code:ne.invalid_type,expected:le.array,received:r.parsedType}),Oe;if(r.data.length<this._def.items.length)return he(r,{code:ne.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Oe;if(!this._def.rest&&r.data.length>this._def.items.length)he(r,{code:ne.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let n=[...r.data].map((i,s)=>{let a=this._def.items[s]||this._def.rest;if(!a)return null;return a._parse(new Ao(r,i,r.path,s))}).filter((i)=>!!i);if(r.common.async)return Promise.all(n).then((i)=>Kr.mergeArray(t,i));else return Kr.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new is({...this._def,rest:e})}}is.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new is({items:e,typeName:ie.ZodTuple,rest:null,...He(t)})};class Ub extends Qe{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!==le.object)return he(r,{code:ne.invalid_type,expected:le.object,received:r.parsedType}),Oe;let o=[],n=this._def.keyType,i=this._def.valueType;for(let s in r.data)o.push({key:n._parse(new Ao(r,s,r.path,s)),value:i._parse(new Ao(r,r.data[s],r.path,s)),alwaysSet:s in r.data});if(r.common.async)return Kr.mergeObjectAsync(t,o);else return Kr.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,r){if(t instanceof Qe)return new Ub({keyType:e,valueType:t,typeName:ie.ZodRecord,...He(r)});return new Ub({keyType:ns.create(),valueType:e,typeName:ie.ZodRecord,...He(t)})}}class Lb extends Qe{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!==le.map)return he(r,{code:ne.invalid_type,expected:le.map,received:r.parsedType}),Oe;let o=this._def.keyType,n=this._def.valueType,i=[...r.data.entries()].map(([s,a],c)=>({key:o._parse(new Ao(r,s,r.path,[c,"key"])),value:n._parse(new Ao(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,u=await a.value;if(c.status==="aborted"||u.status==="aborted")return Oe;if(c.status==="dirty"||u.status==="dirty")t.dirty();s.set(c.value,u.value)}return{status:t.value,value:s}})}else{let s=new Map;for(let a of i){let{key:c,value:u}=a;if(c.status==="aborted"||u.status==="aborted")return Oe;if(c.status==="dirty"||u.status==="dirty")t.dirty();s.set(c.value,u.value)}return{status:t.value,value:s}}}}Lb.create=(e,t,r)=>new Lb({valueType:t,keyType:e,typeName:ie.ZodMap,...He(r)});class zl extends Qe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==le.set)return he(r,{code:ne.invalid_type,expected:le.set,received:r.parsedType}),Oe;let o=this._def;if(o.minSize!==null){if(r.data.size<o.minSize.value)he(r,{code:ne.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()}if(o.maxSize!==null){if(r.data.size>o.maxSize.value)he(r,{code:ne.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty()}let n=this._def.valueType;function i(a){let c=new Set;for(let u of a){if(u.status==="aborted")return Oe;if(u.status==="dirty")t.dirty();c.add(u.value)}return{status:t.value,value:c}}let s=[...r.data.values()].map((a,c)=>n._parse(new Ao(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 zl({...this._def,minSize:{value:e,message:_e.toString(t)}})}max(e,t){return new zl({...this._def,maxSize:{value:e,message:_e.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}zl.create=(e,t)=>new zl({valueType:e,minSize:null,maxSize:null,typeName:ie.ZodSet,...He(t)});class am extends Qe{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==le.function)return he(t,{code:ne.invalid_type,expected:le.function,received:t.parsedType}),Oe;function r(s,a){return zb({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,im(),ua].filter((c)=>!!c),issueData:{code:ne.invalid_arguments,argumentsError:a}})}function o(s,a){return zb({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,im(),ua].filter((c)=>!!c),issueData:{code:ne.invalid_return_type,returnTypeError:a}})}let n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Nl){let s=this;return on(async function(...a){let c=new Vn([]),u=await s._def.args.parseAsync(a,n).catch((m)=>{throw c.addIssue(r(a,m)),c}),d=await Reflect.apply(i,this,u);return await s._def.returns._def.type.parseAsync(d,n).catch((m)=>{throw c.addIssue(o(d,m)),c})})}else{let s=this;return on(function(...a){let c=s._def.args.safeParse(a,n);if(!c.success)throw new Vn([r(a,c.error)]);let u=Reflect.apply(i,this,c.data),d=s._def.returns.safeParse(u,n);if(!d.success)throw new Vn([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new am({...this._def,args:is.create(e).rest(Dc.create())})}returns(e){return new am({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new am({args:e?e:is.create([]).rest(Dc.create()),returns:t||Dc.create(),typeName:ie.ZodFunction,...He(r)})}}class fm extends Qe{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})}}fm.create=(e,t)=>new fm({getter:e,typeName:ie.ZodLazy,...He(t)});class mm extends Qe{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return he(t,{received:t.data,code:ne.invalid_literal,expected:this._def.value}),Oe}return{status:"valid",value:e.data}}get value(){return this._def.value}}mm.create=(e,t)=>new mm({value:e,typeName:ie.ZodLiteral,...He(t)});function OM(e,t){return new Uc({values:e,typeName:ie.ZodEnum,...He(t)})}class Uc extends Qe{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return he(t,{expected:tt.joinValues(r),received:t.parsedType,code:ne.invalid_type}),Oe}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 he(t,{received:t.data,code:ne.invalid_enum_value,options:r}),Oe}return on(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 Uc.create(e,{...this._def,...t})}exclude(e,t=this._def){return Uc.create(this.options.filter((r)=>!e.includes(r)),{...this._def,...t})}}Uc.create=OM;class hm extends Qe{_parse(e){let t=tt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==le.string&&r.parsedType!==le.number){let o=tt.objectValues(t);return he(r,{expected:tt.joinValues(o),received:r.parsedType,code:ne.invalid_type}),Oe}if(!this._cache)this._cache=new Set(tt.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let o=tt.objectValues(t);return he(r,{received:r.data,code:ne.invalid_enum_value,options:o}),Oe}return on(e.data)}get enum(){return this._def.values}}hm.create=(e,t)=>new hm({values:e,typeName:ie.ZodNativeEnum,...He(t)});class Nl extends Qe{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==le.promise&&t.common.async===!1)return he(t,{code:ne.invalid_type,expected:le.promise,received:t.parsedType}),Oe;let r=t.parsedType===le.promise?t.data:Promise.resolve(t.data);return on(r.then((o)=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Nl.create=(e,t)=>new Nl({type:e,typeName:ie.ZodPromise,...He(t)});class fi extends Qe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ie.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),o=this._def.effect||null,n={addIssue:(i)=>{if(he(r,i),i.fatal)t.abort();else t.dirty()},get path(){return r.path}};if(n.addIssue=n.addIssue.bind(n),o.type==="preprocess"){let i=o.transform(r.data,n);if(r.common.async)return Promise.resolve(i).then(async(s)=>{if(t.value==="aborted")return Oe;let a=await this._def.schema._parseAsync({data:s,path:r.path,parent:r});if(a.status==="aborted")return Oe;if(a.status==="dirty")return $l(a.value);if(t.value==="dirty")return $l(a.value);return a});else{if(t.value==="aborted")return Oe;let s=this._def.schema._parseSync({data:i,path:r.path,parent:r});if(s.status==="aborted")return Oe;if(s.status==="dirty")return $l(s.value);if(t.value==="dirty")return $l(s.value);return s}}if(o.type==="refinement"){let i=(s)=>{let a=o.refinement(s,n);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 Oe;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 Oe;if(s.status==="dirty")t.dirty();return i(s.value).then(()=>({status:t.value,value:s.value}))})}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Bc(i))return Oe;let s=o.transform(i.value,n);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(!Bc(i))return Oe;return Promise.resolve(o.transform(i.value,n)).then((s)=>({status:t.value,value:s}))});tt.assertNever(o)}}fi.create=(e,t,r)=>new fi({schema:e,typeName:ie.ZodEffects,effect:t,...He(r)});fi.createWithPreprocess=(e,t,r)=>new fi({schema:t,effect:{type:"preprocess",transform:e},typeName:ie.ZodEffects,...He(r)});class pi extends Qe{_parse(e){if(this._getType(e)===le.undefined)return on(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pi.create=(e,t)=>new pi({innerType:e,typeName:ie.ZodOptional,...He(t)});class la extends Qe{_parse(e){if(this._getType(e)===le.null)return on(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}la.create=(e,t)=>new la({innerType:e,typeName:ie.ZodNullable,...He(t)});class gm extends Qe{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;if(t.parsedType===le.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}gm.create=(e,t)=>new gm({innerType:e,typeName:ie.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...He(t)});class ym extends Qe{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if(sm(o))return o.then((n)=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Vn(r.common.issues)},input:r.data})}));else return{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Vn(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ym.create=(e,t)=>new ym({innerType:e,typeName:ie.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...He(t)});class jb extends Qe{_parse(e){if(this._getType(e)!==le.nan){let r=this._getOrReturnCtx(e);return he(r,{code:ne.invalid_type,expected:le.nan,received:r.parsedType}),Oe}return{status:"valid",value:e.data}}}jb.create=(e)=>new jb({typeName:ie.ZodNaN,...He(e)});var $we=Symbol("zod_brand");class pE extends Qe{_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 Fb extends Qe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let n=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(n.status==="aborted")return Oe;if(n.status==="dirty")return t.dirty(),$l(n.value);else return this._def.out._parseAsync({data:n.value,path:r.path,parent:r})})();else{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(o.status==="aborted")return Oe;if(o.status==="dirty")return t.dirty(),{status:"dirty",value:o.value};else return this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,t){return new Fb({in:e,out:t,typeName:ie.ZodPipeline})}}class bm extends Qe{_parse(e){let t=this._def.innerType._parse(e),r=(o)=>{if(Bc(o))o.value=Object.freeze(o.value);return o};return sm(t)?t.then((o)=>r(o)):r(t)}unwrap(){return this._def.innerType}}bm.create=(e,t)=>new bm({innerType:e,typeName:ie.ZodReadonly,...He(t)});var Rwe={object:Qt.lazycreate},ie;(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"})(ie||(ie={}));var Owe=ns.create,Cwe=Ol.create,zwe=jb.create,Nwe=Cl.create,Mwe=Nb.create,Bwe=cm.create,Dwe=Mb.create,Uwe=um.create,Lwe=lm.create,jwe=Bb.create,Fwe=Dc.create,qwe=os.create,Hwe=Db.create,Gwe=di.create,CM=Qt.create,Vwe=Qt.strictCreate,Zwe=dm.create,Wwe=dE.create,Kwe=pm.create,Jwe=is.create,Ywe=Ub.create,Qwe=Lb.create,Xwe=zl.create,e1e=am.create,t1e=fm.create,r1e=mm.create,n1e=Uc.create,o1e=hm.create,i1e=Nl.create,s1e=fi.create,a1e=pi.create,c1e=la.create,u1e=fi.createWithPreprocess,l1e=Fb.create;var Ro={};Pn(Ro,{$ZodAny:()=>z0,$ZodArray:()=>U0,$ZodAsyncError:()=>mi,$ZodBase64:()=>T0,$ZodBase64URL:()=>E0,$ZodBigInt:()=>Om,$ZodBigIntFormat:()=>$0,$ZodBoolean:()=>Hl,$ZodCIDRv4:()=>w0,$ZodCIDRv6:()=>S0,$ZodCUID:()=>m0,$ZodCUID2:()=>h0,$ZodCatch:()=>nx,$ZodCheck:()=>Tt,$ZodCheckBigIntFormat:()=>nI,$ZodCheckEndsWith:()=>hI,$ZodCheckGreaterThan:()=>r0,$ZodCheckIncludes:()=>fI,$ZodCheckLengthEquals:()=>uI,$ZodCheckLessThan:()=>t0,$ZodCheckLowerCase:()=>dI,$ZodCheckMaxLength:()=>aI,$ZodCheckMaxSize:()=>oI,$ZodCheckMimeType:()=>yI,$ZodCheckMinLength:()=>cI,$ZodCheckMinSize:()=>iI,$ZodCheckMultipleOf:()=>tI,$ZodCheckNumberFormat:()=>rI,$ZodCheckOverwrite:()=>bI,$ZodCheckProperty:()=>gI,$ZodCheckRegex:()=>lI,$ZodCheckSizeEquals:()=>sI,$ZodCheckStartsWith:()=>mI,$ZodCheckStringFormat:()=>ql,$ZodCheckUpperCase:()=>pI,$ZodCodec:()=>Vl,$ZodCustom:()=>lx,$ZodCustomStringFormat:()=>k0,$ZodDate:()=>D0,$ZodDefault:()=>X0,$ZodDiscriminatedUnion:()=>F0,$ZodE164:()=>I0,$ZodEmail:()=>l0,$ZodEmoji:()=>p0,$ZodEncodeError:()=>jc,$ZodEnum:()=>Z0,$ZodError:()=>Em,$ZodExactOptional:()=>Y0,$ZodFile:()=>K0,$ZodFunction:()=>ax,$ZodGUID:()=>c0,$ZodIPv4:()=>x0,$ZodIPv6:()=>v0,$ZodISODate:()=>wI,$ZodISODateTime:()=>_I,$ZodISODuration:()=>TI,$ZodISOTime:()=>SI,$ZodIntersection:()=>q0,$ZodJWT:()=>P0,$ZodKSUID:()=>b0,$ZodLazy:()=>ux,$ZodLiteral:()=>W0,$ZodMAC:()=>_0,$ZodMap:()=>G0,$ZodNaN:()=>ox,$ZodNanoID:()=>f0,$ZodNever:()=>M0,$ZodNonOptional:()=>tx,$ZodNull:()=>C0,$ZodNullable:()=>Q0,$ZodNumber:()=>Rm,$ZodNumberFormat:()=>A0,$ZodObject:()=>L0,$ZodObjectJIT:()=>II,$ZodOptional:()=>zm,$ZodPipe:()=>Nm,$ZodPrefault:()=>ex,$ZodPreprocess:()=>PI,$ZodPromise:()=>cx,$ZodReadonly:()=>ix,$ZodRealError:()=>$n,$ZodRecord:()=>H0,$ZodRegistry:()=>EP,$ZodSet:()=>V0,$ZodString:()=>ya,$ZodStringFormat:()=>xt,$ZodSuccess:()=>rx,$ZodSymbol:()=>R0,$ZodTemplateLiteral:()=>sx,$ZodTransform:()=>J0,$ZodTuple:()=>Cm,$ZodType:()=>ze,$ZodULID:()=>g0,$ZodURL:()=>d0,$ZodUUID:()=>u0,$ZodUndefined:()=>O0,$ZodUnion:()=>Gl,$ZodUnknown:()=>N0,$ZodVoid:()=>B0,$ZodXID:()=>y0,$ZodXor:()=>j0,$brand:()=>mE,$constructor:()=>R,$input:()=>TP,$output:()=>SP,Doc:()=>n0,JSONSchema:()=>R4,JSONSchemaGenerator:()=>_k,NEVER:()=>fE,TimePrecision:()=>PP,_any:()=>Px,_array:()=>MP,_base64:()=>rh,_base64url:()=>nh,_bigint:()=>_x,_boolean:()=>vx,_catch:()=>Xne,_check:()=>$4,_cidrv4:()=>eh,_cidrv6:()=>th,_coercedBigint:()=>zP,_coercedBoolean:()=>CP,_coercedDate:()=>NP,_coercedNumber:()=>OP,_coercedString:()=>IP,_cuid:()=>Zm,_cuid2:()=>Wm,_custom:()=>Ux,_date:()=>Rx,_decode:()=>Zb,_decodeAsync:()=>Kb,_default:()=>Jne,_discriminatedUnion:()=>Dne,_e164:()=>oh,_email:()=>Lm,_emoji:()=>Gm,_encode:()=>Vb,_encodeAsync:()=>Wb,_endsWith:()=>rd,_enum:()=>Hne,_file:()=>Dx,_float32:()=>gx,_float64:()=>yx,_gt:()=>gi,_gte:()=>an,_guid:()=>Kl,_includes:()=>ed,_int:()=>hx,_int32:()=>bx,_int64:()=>wx,_intersection:()=>Une,_ipv4:()=>Qm,_ipv6:()=>Xm,_isoDate:()=>AP,_isoDateTime:()=>kP,_isoDuration:()=>RP,_isoTime:()=>$P,_jwt:()=>ih,_ksuid:()=>Ym,_lazy:()=>noe,_length:()=>Wc,_literal:()=>Vne,_lowercase:()=>Ql,_lt:()=>hi,_lte:()=>Zn,_mac:()=>fx,_map:()=>Fne,_max:()=>Zn,_maxLength:()=>Zc,_maxSize:()=>xa,_mime:()=>nd,_min:()=>an,_minLength:()=>as,_minSize:()=>yi,_multipleOf:()=>ba,_nan:()=>Ox,_nanoid:()=>Vm,_nativeEnum:()=>Gne,_negative:()=>zx,_never:()=>Ax,_nonnegative:()=>Mx,_nonoptional:()=>Yne,_nonpositive:()=>Nx,_normalize:()=>od,_null:()=>Ix,_nullable:()=>Kne,_number:()=>mx,_optional:()=>Wne,_overwrite:()=>$o,_parse:()=>Ul,_parseAsync:()=>Ll,_pipe:()=>eoe,_positive:()=>Cx,_promise:()=>ooe,_property:()=>Bx,_readonly:()=>toe,_record:()=>jne,_refine:()=>Lx,_regex:()=>Yl,_safeDecode:()=>Yb,_safeDecodeAsync:()=>Xb,_safeEncode:()=>Jb,_safeEncodeAsync:()=>Qb,_safeParse:()=>jl,_safeParseAsync:()=>Fl,_set:()=>qne,_size:()=>Vc,_slugify:()=>cd,_startsWith:()=>td,_string:()=>px,_stringFormat:()=>Kc,_stringbool:()=>Hx,_success:()=>Qne,_superRefine:()=>jx,_symbol:()=>Tx,_templateLiteral:()=>roe,_toLowerCase:()=>sd,_toUpperCase:()=>ad,_transform:()=>Zne,_trim:()=>id,_tuple:()=>Lne,_uint32:()=>xx,_uint64:()=>Sx,_ulid:()=>Km,_undefined:()=>Ex,_union:()=>Mne,_unknown:()=>kx,_uppercase:()=>Xl,_url:()=>Jl,_uuid:()=>jm,_uuidv4:()=>Fm,_uuidv6:()=>qm,_uuidv7:()=>Hm,_void:()=>$x,_xid:()=>Jm,_xor:()=>Bne,clone:()=>$r,config:()=>Xt,createStandardJSONSchemaMethod:()=>ud,createToJSONSchemaMethod:()=>BP,decode:()=>WM,decodeAsync:()=>JM,describe:()=>Fx,encode:()=>ZM,encodeAsync:()=>KM,extractDefs:()=>_a,finalize:()=>wa,flattenError:()=>Im,formatError:()=>Pm,globalConfig:()=>Lc,globalRegistry:()=>Rr,initializeContext:()=>va,isValidBase64:()=>EI,isValidBase64URL:()=>_4,isValidJWT:()=>w4,locales:()=>Wl,meta:()=>qx,parse:()=>qc,parseAsync:()=>Hc,prettifyError:()=>EE,process:()=>gt,regexes:()=>Rn,registry:()=>dx,safeDecode:()=>QM,safeDecodeAsync:()=>e4,safeEncode:()=>YM,safeEncodeAsync:()=>XM,safeParse:()=>ha,safeParseAsync:()=>ga,toDotPath:()=>VM,toJSONSchema:()=>Jc,treeifyError:()=>TE,util:()=>re,version:()=>xI});var zM,fE=Object.freeze({status:"aborted"});function R(e,t,r){function o(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 u=s.prototype,d=Object.keys(u);for(let p=0;p<d.length;p++){let m=d[p];if(!(m in a))a[m]=u[m].bind(a)}}let n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let u=r?.Parent?new i:this;o(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(s,"init",{value:o}),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 mE=Symbol("zod_brand");class mi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class jc extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(zM=globalThis).__zod_globalConfig??(zM.__zod_globalConfig={});var Lc=globalThis.__zod_globalConfig;function Xt(e){if(e)Object.assign(Lc,e);return Lc}var re={};Pn(re,{BIGINT_FORMAT_RANGES:()=>wE,Class:()=>HM,NUMBER_FORMAT_RANGES:()=>_E,aborted:()=>ma,allowsEval:()=>bE,assert:()=>Kte,assertEqual:()=>Gte,assertIs:()=>Zte,assertNever:()=>Wte,assertNotEqual:()=>Vte,assignProp:()=>pa,base64ToUint8Array:()=>FM,base64urlToUint8Array:()=>sre,cached:()=>Bl,captureStackTrace:()=>Hb,cleanEnum:()=>ire,cleanRegex:()=>_m,clone:()=>$r,cloneDef:()=>Yte,createTransparentProxy:()=>nre,defineLazy:()=>Ve,esc:()=>qb,escapeRegex:()=>no,explicitlyAborted:()=>SE,extend:()=>DM,finalizeIssue:()=>sn,floatSafeRemainder:()=>gE,getElementAtPath:()=>Qte,getEnumValues:()=>vm,getLengthableOrigin:()=>Tm,getParsedType:()=>rre,getSizableOrigin:()=>Sm,hexToUint8Array:()=>cre,isObject:()=>Fc,isPlainObject:()=>fa,issue:()=>Dl,joinValues:()=>M,jsonStringifyReplacer:()=>Ml,merge:()=>ore,mergeDefs:()=>ss,normalizeParams:()=>se,nullish:()=>da,numKeys:()=>tre,objectClone:()=>Jte,omit:()=>BM,optionalKeys:()=>vE,parsedType:()=>ee,partial:()=>LM,pick:()=>MM,prefixIssues:()=>An,primitiveTypes:()=>xE,promiseAllObject:()=>Xte,propertyKeyTypes:()=>wm,randomString:()=>ere,required:()=>jM,safeExtend:()=>UM,shallowClone:()=>Gb,slugify:()=>yE,stringifyPrimitive:()=>Q,uint8ArrayToBase64:()=>qM,uint8ArrayToBase64url:()=>are,uint8ArrayToHex:()=>ure,unwrapMessage:()=>xm});function Gte(e){return e}function Vte(e){return e}function Zte(e){}function Wte(e){throw Error("Unexpected value in exhaustive check")}function Kte(e){}function vm(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function M(e,t="|"){return e.map((r)=>Q(r)).join(t)}function Ml(e,t){if(typeof t==="bigint")return t.toString();return t}function Bl(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function da(e){return e===null||e===void 0}function _m(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function gE(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-o)<n)return 0;return r-o}var NM=Symbol("evaluating");function Ve(e,t,r){let o=void 0;Object.defineProperty(e,t,{get(){if(o===NM)return;if(o===void 0)o=NM,o=r();return o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Jte(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function pa(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ss(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function Yte(e){return ss(e._zod.def)}function Qte(e,t){if(!t)return e;return t.reduce((r,o)=>r?.[o],e)}function Xte(e){let t=Object.keys(e),r=t.map((o)=>e[o]);return Promise.all(r).then((o)=>{let n={};for(let i=0;i<t.length;i++)n[t[i]]=o[i];return n})}function ere(e=10){let r="";for(let o=0;o<e;o++)r+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return r}function qb(e){return JSON.stringify(e)}function yE(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Hb="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Fc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var bE=Bl(()=>{if(Lc.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function fa(e){if(Fc(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(Fc(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Gb(e){if(fa(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}function tre(e){let t=0;for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r))t++;return t}var rre=(e)=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(e))return"array";if(e===null)return"null";if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return"promise";if(typeof Map<"u"&&e instanceof Map)return"map";if(typeof Set<"u"&&e instanceof Set)return"set";if(typeof Date<"u"&&e instanceof Date)return"date";if(typeof File<"u"&&e instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},wm=new Set(["string","number","symbol"]),xE=new Set(["string","number","bigint","boolean","symbol","undefined"]);function no(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $r(e,t,r){let o=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)o._zod.parent=e;return o}function se(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 nre(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,i){return t??(t=e()),Reflect.set(t,o,n,i)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function Q(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function vE(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var _E={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]},wE={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function MM(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=ss(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 pa(this,"shape",s),s},checks:[]});return $r(e,i)}function BM(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=ss(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 pa(this,"shape",s),s},checks:[]});return $r(e,i)}function DM(e,t){if(!fa(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 n=ss(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return pa(this,"shape",i),i}});return $r(e,n)}function UM(e,t){if(!fa(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=ss(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return pa(this,"shape",o),o}});return $r(e,r)}function ore(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=ss(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return pa(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return $r(e,r)}function LM(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let s=ss(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw Error(`Unrecognized key: "${u}"`);if(!r[u])continue;c[u]=e?new e({type:"optional",innerType:a[u]}):a[u]}else for(let u in a)c[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return pa(this,"shape",c),c},checks:[]});return $r(t,s)}function jM(e,t,r){let o=ss(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};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:n[s]})}else for(let s in n)i[s]=new e({type:"nonoptional",innerType:n[s]});return pa(this,"shape",i),i}});return $r(t,o)}function ma(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 SE(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 An(e,t){return t.map((r)=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function xm(e){return typeof e==="string"?e:e?.message}function sn(e,t,r){let o=e.message?e.message:xm(e.inst?._zod.def?.error?.(e))??xm(t?.error?.(e))??xm(r.customError?.(e))??xm(r.localeError?.(e))??"Invalid input",{inst:n,continue:i,input:s,...a}=e;if(a.path??(a.path=[]),a.message=o,t?.reportInput)a.input=s;return a}function Sm(e){if(e instanceof Set)return"set";if(e instanceof Map)return"map";if(e instanceof File)return"file";return"unknown"}function Tm(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function ee(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 Dl(...e){let[t,r,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:o};return{...t}}function ire(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map((t)=>t[1])}function FM(e){let t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}function qM(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function sre(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return FM(t+r)}function are(e){return qM(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function cre(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2)r[o/2]=Number.parseInt(t.slice(o,o+2),16);return r}function ure(e){return Array.from(e).map((t)=>t.toString(16).padStart(2,"0")).join("")}class HM{constructor(...e){}}var GM=(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,Ml,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Em=R("$ZodError",GM),$n=R("$ZodError",GM,{Parent:Error});function Im(e,t=(r)=>r.message){let r={},o=[];for(let n of e.issues)if(n.path.length>0)r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n));else o.push(t(n));return{formErrors:o,fieldErrors:r}}function Pm(e,t=(r)=>r.message){let r={_errors:[]},o=(n,i=[])=>{for(let s of n.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>o({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")o({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,u=0;while(u<a.length){let d=a[u];if(u!==a.length-1)c[d]=c[d]||{_errors:[]};else c[d]=c[d]||{_errors:[]},c[d]._errors.push(t(s));c=c[d],u++}}}};return o(e),r}function TE(e,t=(r)=>r.message){let r={errors:[]},o=(n,i=[])=>{var s,a;for(let c of n.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map((u)=>o({issues:u},[...i,...c.path]));else if(c.code==="invalid_key")o({issues:c.issues},[...i,...c.path]);else if(c.code==="invalid_element")o({issues:c.issues},[...i,...c.path]);else{let u=[...i,...c.path];if(u.length===0){r.errors.push(t(c));continue}let d=r,p=0;while(p<u.length){let m=u[p],h=p===u.length-1;if(typeof m==="string")d.properties??(d.properties={}),(s=d.properties)[m]??(s[m]={errors:[]}),d=d.properties[m];else d.items??(d.items=[]),(a=d.items)[m]??(a[m]={errors:[]}),d=d.items[m];if(h)d.errors.push(t(c));p++}}};return o(e),r}function VM(e){let t=[],r=e.map((o)=>typeof o==="object"?o.key:o);for(let o of r)if(typeof o==="number")t.push(`[${o}]`);else if(typeof o==="symbol")t.push(`[${JSON.stringify(String(o))}]`);else if(/[^\w$]/.test(o))t.push(`[${JSON.stringify(o)}]`);else{if(t.length)t.push(".");t.push(o)}return t.join("")}function EE(e){let t=[],r=[...e.issues].sort((o,n)=>(o.path??[]).length-(n.path??[]).length);for(let o of r)if(t.push(`✖ ${o.message}`),o.path?.length)t.push(` → at ${VM(o.path)}`);return t.join(`
66
+ `),o=!1,n=!1,i;e.on("response",(s)=>{let{headers:a}=s;o=a["transfer-encoding"]==="chunked"&&!a["content-length"]}),e.on("socket",(s)=>{let a=()=>{if(o&&!n){let u=Error("Premature close");u.code="ERR_STREAM_PREMATURE_CLOSE",t(u)}},c=(u)=>{if(n=xb.compare(u.slice(-5),r)===0,!n&&i)n=xb.compare(i.slice(-3),r.slice(0,3))===0&&xb.compare(u.slice(-2),r.slice(3))===0;i=u};s.prependListener("close",a),s.on("data",c),e.on("close",()=>{s.removeListener("close",a),s.removeListener("data",c)})})}var mte=rn(_M(),1),hte=rn(kb(),1),gte=rn(Tl(),1),yte=rn(YT(),1),bte=rn(XT(),1),xte=rn(iE(),1),sE=rn(Ob(),1),vte=rn(PM(),1);var tt;(function(e){e.assertEqual=(n)=>{};function t(n){}e.assertIs=t;function r(n){throw Error()}e.assertNever=r,e.arrayToEnum=(n)=>{let i={};for(let s of n)i[s]=s;return i},e.getValidEnumValues=(n)=>{let i=e.objectKeys(n).filter((a)=>typeof n[n[a]]!=="number"),s={};for(let a of i)s[a]=n[a];return e.objectValues(s)},e.objectValues=(n)=>e.objectKeys(n).map(function(i){return n[i]}),e.objectKeys=typeof Object.keys==="function"?(n)=>Object.keys(n):(n)=>{let i=[];for(let s in n)if(Object.prototype.hasOwnProperty.call(n,s))i.push(s);return i},e.find=(n,i)=>{for(let s of n)if(i(s))return s;return},e.isInteger=typeof Number.isInteger==="function"?(n)=>Number.isInteger(n):(n)=>typeof n==="number"&&Number.isFinite(n)&&Math.floor(n)===n;function o(n,i=" | "){return n.map((s)=>typeof s==="string"?`'${s}'`:s).join(i)}e.joinValues=o,e.jsonStringifyReplacer=(n,i)=>{if(typeof i==="bigint")return i.toString();return i}})(tt||(tt={}));var kM;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(kM||(kM={}));var le=tt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ts=(e)=>{switch(typeof e){case"undefined":return le.undefined;case"string":return le.string;case"number":return Number.isNaN(e)?le.nan:le.number;case"boolean":return le.boolean;case"function":return le.function;case"bigint":return le.bigint;case"symbol":return le.symbol;case"object":if(Array.isArray(e))return le.array;if(e===null)return le.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return le.promise;if(typeof Map<"u"&&e instanceof Map)return le.map;if(typeof Set<"u"&&e instanceof Set)return le.set;if(typeof Date<"u"&&e instanceof Date)return le.date;return le.object;default:return le.unknown}};var ne=tt.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(n){return n.message},r={_errors:[]},o=(n)=>{for(let i of n.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(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 o(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,tt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t=Object.create(null),r=[];for(let o of this.issues)if(o.path.length>0){let n=o.path[0];t[n]=t[n]||[],t[n].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Vn.create=(e)=>new Vn(e);var _te=(e,t)=>{let r;switch(e.code){case ne.invalid_type:if(e.received===le.undefined)r="Required";else r=`Expected ${e.expected}, received ${e.received}`;break;case ne.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,tt.jsonStringifyReplacer)}`;break;case ne.unrecognized_keys:r=`Unrecognized key(s) in object: ${tt.joinValues(e.keys,", ")}`;break;case ne.invalid_union:r="Invalid input";break;case ne.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${tt.joinValues(e.options)}`;break;case ne.invalid_enum_value:r=`Invalid enum value. Expected ${tt.joinValues(e.options)}, received '${e.received}'`;break;case ne.invalid_arguments:r="Invalid function arguments";break;case ne.invalid_return_type:r="Invalid function return type";break;case ne.invalid_date:r="Invalid date";break;case ne.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 tt.assertNever(e.validation);else if(e.validation!=="regex")r=`Invalid ${e.validation}`;else r="Invalid";break;case ne.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 ne.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 ne.custom:r="Invalid input";break;case ne.invalid_intersection_types:r="Intersection results could not be merged";break;case ne.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ne.not_finite:r="Number must be finite";break;default:r=t.defaultError,tt.assertNever(e)}return{message:r}},ua=_te;var wte=ua;function im(){return wte}var zb=(e)=>{let{data:t,path:r,errorMaps:o,issueData:n}=e,i=[...r,...n.path||[]],s={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let a="",c=o.filter((u)=>!!u).slice().reverse();for(let u of c)a=u(s,{data:t,defaultError:a}).message;return{...n,path:i,message:a}};function he(e,t){let r=im(),o=zb({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===ua?void 0:ua].filter((n)=>!!n)});e.common.issues.push(o)}class Kr{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 o of t){if(o.status==="aborted")return Oe;if(o.status==="dirty")e.dirty();r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let o of t){let n=await o.key,i=await o.value;r.push({key:n,value:i})}return Kr.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let o of t){let{key:n,value:i}=o;if(n.status==="aborted")return Oe;if(i.status==="aborted")return Oe;if(n.status==="dirty")e.dirty();if(i.status==="dirty")e.dirty();if(n.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet))r[n.value]=i.value}return{status:e.value,value:r}}}var Oe=Object.freeze({status:"aborted"}),$l=(e)=>({status:"dirty",value:e}),on=(e)=>({status:"valid",value:e}),aE=(e)=>e.status==="aborted",cE=(e)=>e.status==="dirty",Bc=(e)=>e.status==="valid",sm=(e)=>typeof Promise<"u"&&e instanceof Promise;var _e;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(_e||(_e={}));class Ao{constructor(e,t,r,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=o}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 AM=(e,t)=>{if(Bc(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 He(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:o,description:n}=e;if(t&&(r||o))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:n};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??o??a.defaultError};if(s.code!=="invalid_type")return{message:a.defaultError};return{message:c??r??a.defaultError}},description:n}}class Qe{get description(){return this._def.description}_getType(e){return ts(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ts(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Kr,ctx:{common:e.parent.common,data:e.data,parsedType:ts(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(sm(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:ts(e)},o=this._parseSync({data:e,path:r.path,parent:r});return AM(r,o)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ts(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Bc(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)=>Bc(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:ts(e)},o=this._parse({data:e,path:r.path,parent:r}),n=await(sm(o)?o:Promise.resolve(o));return AM(r,n)}refine(e,t){let r=(o)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(o);else return t};return this._refinement((o,n)=>{let i=e(o),s=()=>n.addIssue({code:ne.custom,...r(o)});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,o)=>{if(!e(r))return o.addIssue(typeof t==="function"?t(r,o):t),!1;else return!0})}_refinement(e){return new fi({schema:this,typeName:ie.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 pi.create(this,this._def)}nullable(){return la.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return di.create(this)}promise(){return Nl.create(this,this._def)}or(e){return dm.create([this,e],this._def)}and(e){return pm.create(this,e,this._def)}transform(e){return new fi({...He(this._def),schema:this,typeName:ie.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new gm({...He(this._def),innerType:this,defaultValue:t,typeName:ie.ZodDefault})}brand(){return new pE({typeName:ie.ZodBranded,type:this,...He(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new ym({...He(this._def),innerType:this,catchValue:t,typeName:ie.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return Fb.create(this,e)}readonly(){return bm.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Ste=/^c[^\s-]{8,}$/i,Tte=/^[0-9a-z]+$/,Ete=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ite=/^[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,Pte=/^[a-z0-9_-]{21}$/i,kte=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ate=/^[-+]?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)?)??$/,$te=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Rte="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",uE,Ote=/^(?:(?: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])$/,Cte=/^(?:(?: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])$/,zte=/^(([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]))$/,Nte=/^(([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])$/,Mte=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Bte=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$M="((\\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])))",Dte=new RegExp(`^${$M}$`);function RM(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 Ute(e){return new RegExp(`^${RM(e)}$`)}function Lte(e){let t=`${$M}T${RM(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 jte(e,t){if((t==="v4"||!t)&&Ote.test(e))return!0;if((t==="v6"||!t)&&zte.test(e))return!0;return!1}function Fte(e,t){if(!kte.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let o=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(o));if(typeof n!=="object"||n===null)return!1;if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(t&&n.alg!==t)return!1;return!0}catch{return!1}}function qte(e,t){if((t==="v4"||!t)&&Cte.test(e))return!0;if((t==="v6"||!t)&&Nte.test(e))return!0;return!1}class ns extends Qe{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==le.string){let n=this._getOrReturnCtx(e);return he(n,{code:ne.invalid_type,expected:le.string,received:n.parsedType}),Oe}let r=new Kr,o=void 0;for(let n of this._def.checks)if(n.kind==="min"){if(e.data.length<n.value)o=this._getOrReturnCtx(e,o),he(o,{code:ne.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),r.dirty()}else if(n.kind==="max"){if(e.data.length>n.value)o=this._getOrReturnCtx(e,o),he(o,{code:ne.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),r.dirty()}else if(n.kind==="length"){let i=e.data.length>n.value,s=e.data.length<n.value;if(i||s){if(o=this._getOrReturnCtx(e,o),i)he(o,{code:ne.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message});else if(s)he(o,{code:ne.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message});r.dirty()}}else if(n.kind==="email"){if(!$te.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"email",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="emoji"){if(!uE)uE=new RegExp(Rte,"u");if(!uE.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"emoji",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="uuid"){if(!Ite.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"uuid",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="nanoid"){if(!Pte.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"nanoid",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="cuid"){if(!Ste.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"cuid",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="cuid2"){if(!Tte.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"cuid2",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="ulid"){if(!Ete.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"ulid",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),he(o,{validation:"url",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="regex"){if(n.regex.lastIndex=0,!n.regex.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"regex",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="trim")e.data=e.data.trim();else if(n.kind==="includes"){if(!e.data.includes(n.value,n.position))o=this._getOrReturnCtx(e,o),he(o,{code:ne.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),r.dirty()}else if(n.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(n.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(n.kind==="startsWith"){if(!e.data.startsWith(n.value))o=this._getOrReturnCtx(e,o),he(o,{code:ne.invalid_string,validation:{startsWith:n.value},message:n.message}),r.dirty()}else if(n.kind==="endsWith"){if(!e.data.endsWith(n.value))o=this._getOrReturnCtx(e,o),he(o,{code:ne.invalid_string,validation:{endsWith:n.value},message:n.message}),r.dirty()}else if(n.kind==="datetime"){if(!Lte(n).test(e.data))o=this._getOrReturnCtx(e,o),he(o,{code:ne.invalid_string,validation:"datetime",message:n.message}),r.dirty()}else if(n.kind==="date"){if(!Dte.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{code:ne.invalid_string,validation:"date",message:n.message}),r.dirty()}else if(n.kind==="time"){if(!Ute(n).test(e.data))o=this._getOrReturnCtx(e,o),he(o,{code:ne.invalid_string,validation:"time",message:n.message}),r.dirty()}else if(n.kind==="duration"){if(!Ate.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"duration",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="ip"){if(!jte(e.data,n.version))o=this._getOrReturnCtx(e,o),he(o,{validation:"ip",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="jwt"){if(!Fte(e.data,n.alg))o=this._getOrReturnCtx(e,o),he(o,{validation:"jwt",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="cidr"){if(!qte(e.data,n.version))o=this._getOrReturnCtx(e,o),he(o,{validation:"cidr",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="base64"){if(!Mte.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"base64",code:ne.invalid_string,message:n.message}),r.dirty()}else if(n.kind==="base64url"){if(!Bte.test(e.data))o=this._getOrReturnCtx(e,o),he(o,{validation:"base64url",code:ne.invalid_string,message:n.message}),r.dirty()}else tt.assertNever(n);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement((o)=>e.test(o),{validation:t,code:ne.invalid_string,..._e.errToObj(r)})}_addCheck(e){return new ns({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",..._e.errToObj(e)})}url(e){return this._addCheck({kind:"url",..._e.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",..._e.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",..._e.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",..._e.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",..._e.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",..._e.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",..._e.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",..._e.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",..._e.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",..._e.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",..._e.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",..._e.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,..._e.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,..._e.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",..._e.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,..._e.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,..._e.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,..._e.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,..._e.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,..._e.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,..._e.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,..._e.errToObj(t)})}nonempty(e){return this.min(1,_e.errToObj(e))}trim(){return new ns({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ns({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ns({...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}}ns.create=(e)=>new ns({checks:[],typeName:ie.ZodString,coerce:e?.coerce??!1,...He(e)});function Hte(e,t){let r=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,n=r>o?r:o,i=Number.parseInt(e.toFixed(n).replace(".","")),s=Number.parseInt(t.toFixed(n).replace(".",""));return i%s/10**n}class Ol extends Qe{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)!==le.number){let n=this._getOrReturnCtx(e);return he(n,{code:ne.invalid_type,expected:le.number,received:n.parsedType}),Oe}let r=void 0,o=new Kr;for(let n of this._def.checks)if(n.kind==="int"){if(!tt.isInteger(e.data))r=this._getOrReturnCtx(e,r),he(r,{code:ne.invalid_type,expected:"integer",received:"float",message:n.message}),o.dirty()}else if(n.kind==="min"){if(n.inclusive?e.data<n.value:e.data<=n.value)r=this._getOrReturnCtx(e,r),he(r,{code:ne.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),o.dirty()}else if(n.kind==="max"){if(n.inclusive?e.data>n.value:e.data>=n.value)r=this._getOrReturnCtx(e,r),he(r,{code:ne.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),o.dirty()}else if(n.kind==="multipleOf"){if(Hte(e.data,n.value)!==0)r=this._getOrReturnCtx(e,r),he(r,{code:ne.not_multiple_of,multipleOf:n.value,message:n.message}),o.dirty()}else if(n.kind==="finite"){if(!Number.isFinite(e.data))r=this._getOrReturnCtx(e,r),he(r,{code:ne.not_finite,message:n.message}),o.dirty()}else tt.assertNever(n);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,_e.toString(t))}gt(e,t){return this.setLimit("min",e,!1,_e.toString(t))}lte(e,t){return this.setLimit("max",e,!0,_e.toString(t))}lt(e,t){return this.setLimit("max",e,!1,_e.toString(t))}setLimit(e,t,r,o){return new Ol({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:_e.toString(o)}]})}_addCheck(e){return new Ol({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:_e.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_e.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_e.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_e.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_e.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:_e.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:_e.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_e.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_e.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"&&tt.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)}}Ol.create=(e)=>new Ol({checks:[],typeName:ie.ZodNumber,coerce:e?.coerce||!1,...He(e)});class Cl extends Qe{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)!==le.bigint)return this._getInvalidInput(e);let r=void 0,o=new Kr;for(let n of this._def.checks)if(n.kind==="min"){if(n.inclusive?e.data<n.value:e.data<=n.value)r=this._getOrReturnCtx(e,r),he(r,{code:ne.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),o.dirty()}else if(n.kind==="max"){if(n.inclusive?e.data>n.value:e.data>=n.value)r=this._getOrReturnCtx(e,r),he(r,{code:ne.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),o.dirty()}else if(n.kind==="multipleOf"){if(e.data%n.value!==BigInt(0))r=this._getOrReturnCtx(e,r),he(r,{code:ne.not_multiple_of,multipleOf:n.value,message:n.message}),o.dirty()}else tt.assertNever(n);return{status:o.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return he(t,{code:ne.invalid_type,expected:le.bigint,received:t.parsedType}),Oe}gte(e,t){return this.setLimit("min",e,!0,_e.toString(t))}gt(e,t){return this.setLimit("min",e,!1,_e.toString(t))}lte(e,t){return this.setLimit("max",e,!0,_e.toString(t))}lt(e,t){return this.setLimit("max",e,!1,_e.toString(t))}setLimit(e,t,r,o){return new Cl({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:_e.toString(o)}]})}_addCheck(e){return new Cl({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:_e.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_e.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_e.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_e.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:_e.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}}Cl.create=(e)=>new Cl({checks:[],typeName:ie.ZodBigInt,coerce:e?.coerce??!1,...He(e)});class Nb extends Qe{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==le.boolean){let r=this._getOrReturnCtx(e);return he(r,{code:ne.invalid_type,expected:le.boolean,received:r.parsedType}),Oe}return on(e.data)}}Nb.create=(e)=>new Nb({typeName:ie.ZodBoolean,coerce:e?.coerce||!1,...He(e)});class cm extends Qe{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==le.date){let n=this._getOrReturnCtx(e);return he(n,{code:ne.invalid_type,expected:le.date,received:n.parsedType}),Oe}if(Number.isNaN(e.data.getTime())){let n=this._getOrReturnCtx(e);return he(n,{code:ne.invalid_date}),Oe}let r=new Kr,o=void 0;for(let n of this._def.checks)if(n.kind==="min"){if(e.data.getTime()<n.value)o=this._getOrReturnCtx(e,o),he(o,{code:ne.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),r.dirty()}else if(n.kind==="max"){if(e.data.getTime()>n.value)o=this._getOrReturnCtx(e,o),he(o,{code:ne.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),r.dirty()}else tt.assertNever(n);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new cm({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:_e.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:_e.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}}cm.create=(e)=>new cm({checks:[],coerce:e?.coerce||!1,typeName:ie.ZodDate,...He(e)});class Mb extends Qe{_parse(e){if(this._getType(e)!==le.symbol){let r=this._getOrReturnCtx(e);return he(r,{code:ne.invalid_type,expected:le.symbol,received:r.parsedType}),Oe}return on(e.data)}}Mb.create=(e)=>new Mb({typeName:ie.ZodSymbol,...He(e)});class um extends Qe{_parse(e){if(this._getType(e)!==le.undefined){let r=this._getOrReturnCtx(e);return he(r,{code:ne.invalid_type,expected:le.undefined,received:r.parsedType}),Oe}return on(e.data)}}um.create=(e)=>new um({typeName:ie.ZodUndefined,...He(e)});class lm extends Qe{_parse(e){if(this._getType(e)!==le.null){let r=this._getOrReturnCtx(e);return he(r,{code:ne.invalid_type,expected:le.null,received:r.parsedType}),Oe}return on(e.data)}}lm.create=(e)=>new lm({typeName:ie.ZodNull,...He(e)});class Bb extends Qe{constructor(){super(...arguments);this._any=!0}_parse(e){return on(e.data)}}Bb.create=(e)=>new Bb({typeName:ie.ZodAny,...He(e)});class Dc extends Qe{constructor(){super(...arguments);this._unknown=!0}_parse(e){return on(e.data)}}Dc.create=(e)=>new Dc({typeName:ie.ZodUnknown,...He(e)});class os extends Qe{_parse(e){let t=this._getOrReturnCtx(e);return he(t,{code:ne.invalid_type,expected:le.never,received:t.parsedType}),Oe}}os.create=(e)=>new os({typeName:ie.ZodNever,...He(e)});class Db extends Qe{_parse(e){if(this._getType(e)!==le.undefined){let r=this._getOrReturnCtx(e);return he(r,{code:ne.invalid_type,expected:le.void,received:r.parsedType}),Oe}return on(e.data)}}Db.create=(e)=>new Db({typeName:ie.ZodVoid,...He(e)});class di extends Qe{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),o=this._def;if(t.parsedType!==le.array)return he(t,{code:ne.invalid_type,expected:le.array,received:t.parsedType}),Oe;if(o.exactLength!==null){let i=t.data.length>o.exactLength.value,s=t.data.length<o.exactLength.value;if(i||s)he(t,{code:i?ne.too_big:ne.too_small,minimum:s?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty()}if(o.minLength!==null){if(t.data.length<o.minLength.value)he(t,{code:ne.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()}if(o.maxLength!==null){if(t.data.length>o.maxLength.value)he(t,{code:ne.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()}if(t.common.async)return Promise.all([...t.data].map((i,s)=>o.type._parseAsync(new Ao(t,i,t.path,s)))).then((i)=>Kr.mergeArray(r,i));let n=[...t.data].map((i,s)=>o.type._parseSync(new Ao(t,i,t.path,s)));return Kr.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new di({...this._def,minLength:{value:e,message:_e.toString(t)}})}max(e,t){return new di({...this._def,maxLength:{value:e,message:_e.toString(t)}})}length(e,t){return new di({...this._def,exactLength:{value:e,message:_e.toString(t)}})}nonempty(e){return this.min(1,e)}}di.create=(e,t)=>new di({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ie.ZodArray,...He(t)});function Rl(e){if(e instanceof Qt){let t={};for(let r in e.shape){let o=e.shape[r];t[r]=pi.create(Rl(o))}return new Qt({...e._def,shape:()=>t})}else if(e instanceof di)return new di({...e._def,type:Rl(e.element)});else if(e instanceof pi)return pi.create(Rl(e.unwrap()));else if(e instanceof la)return la.create(Rl(e.unwrap()));else if(e instanceof is)return is.create(e.items.map((t)=>Rl(t)));else return e}class Qt extends Qe{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=tt.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==le.object){let c=this._getOrReturnCtx(e);return he(c,{code:ne.invalid_type,expected:le.object,received:c.parsedType}),Oe}let{status:r,ctx:o}=this._processInputParams(e),{shape:n,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof os&&this._def.unknownKeys==="strip")){for(let c in o.data)if(!i.includes(c))s.push(c)}let a=[];for(let c of i){let u=n[c],d=o.data[c];a.push({key:{status:"valid",value:c},value:u._parse(new Ao(o,d,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof os){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of s)a.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict"){if(s.length>0)he(o,{code:ne.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 u of s){let d=o.data[u];a.push({key:{status:"valid",value:u},value:c._parse(new Ao(o,d,o.path,u)),alwaysSet:u in o.data})}}if(o.common.async)return Promise.resolve().then(async()=>{let c=[];for(let u of a){let d=await u.key,p=await u.value;c.push({key:d,value:p,alwaysSet:u.alwaysSet})}return c}).then((c)=>Kr.mergeObjectSync(r,c));else return Kr.mergeObjectSync(r,a)}get shape(){return this._def.shape()}strict(e){return _e.errToObj,new Qt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let o=this._def.errorMap?.(t,r).message??r.defaultError;if(t.code==="unrecognized_keys")return{message:_e.errToObj(e).message??o};return{message:o}}}:{}})}strip(){return new Qt({...this._def,unknownKeys:"strip"})}passthrough(){return new Qt({...this._def,unknownKeys:"passthrough"})}extend(e){return new Qt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Qt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ie.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Qt({...this._def,catchall:e})}pick(e){let t={};for(let r of tt.objectKeys(e))if(e[r]&&this.shape[r])t[r]=this.shape[r];return new Qt({...this._def,shape:()=>t})}omit(e){let t={};for(let r of tt.objectKeys(this.shape))if(!e[r])t[r]=this.shape[r];return new Qt({...this._def,shape:()=>t})}deepPartial(){return Rl(this)}partial(e){let t={};for(let r of tt.objectKeys(this.shape)){let o=this.shape[r];if(e&&!e[r])t[r]=o;else t[r]=o.optional()}return new Qt({...this._def,shape:()=>t})}required(e){let t={};for(let r of tt.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let n=this.shape[r];while(n instanceof pi)n=n._def.innerType;t[r]=n}return new Qt({...this._def,shape:()=>t})}keyof(){return OM(tt.objectKeys(this.shape))}}Qt.create=(e,t)=>new Qt({shape:()=>e,unknownKeys:"strip",catchall:os.create(),typeName:ie.ZodObject,...He(t)});Qt.strictCreate=(e,t)=>new Qt({shape:()=>e,unknownKeys:"strict",catchall:os.create(),typeName:ie.ZodObject,...He(t)});Qt.lazycreate=(e,t)=>new Qt({shape:e,unknownKeys:"strip",catchall:os.create(),typeName:ie.ZodObject,...He(t)});class dm extends Qe{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function o(n){for(let s of n)if(s.result.status==="valid")return s.result;for(let s of n)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;let i=n.map((s)=>new Vn(s.ctx.common.issues));return he(t,{code:ne.invalid_union,unionErrors:i}),Oe}if(t.common.async)return Promise.all(r.map(async(n)=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await n._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(o);else{let n=void 0,i=[];for(let a of r){let c={...t,common:{...t.common,issues:[]},parent:null},u=a._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;else if(u.status==="dirty"&&!n)n={result:u,ctx:c};if(c.common.issues.length)i.push(c.common.issues)}if(n)return t.common.issues.push(...n.ctx.common.issues),n.result;let s=i.map((a)=>new Vn(a));return he(t,{code:ne.invalid_union,unionErrors:s}),Oe}}get options(){return this._def.options}}dm.create=(e,t)=>new dm({options:e,typeName:ie.ZodUnion,...He(t)});var rs=(e)=>{if(e instanceof fm)return rs(e.schema);else if(e instanceof fi)return rs(e.innerType());else if(e instanceof mm)return[e.value];else if(e instanceof Uc)return e.options;else if(e instanceof hm)return tt.objectValues(e.enum);else if(e instanceof gm)return rs(e._def.innerType);else if(e instanceof um)return[void 0];else if(e instanceof lm)return[null];else if(e instanceof pi)return[void 0,...rs(e.unwrap())];else if(e instanceof la)return[null,...rs(e.unwrap())];else if(e instanceof pE)return rs(e.unwrap());else if(e instanceof bm)return rs(e.unwrap());else if(e instanceof ym)return rs(e._def.innerType);else return[]};class dE extends Qe{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==le.object)return he(t,{code:ne.invalid_type,expected:le.object,received:t.parsedType}),Oe;let r=this.discriminator,o=t.data[r],n=this.optionsMap.get(o);if(!n)return he(t,{code:ne.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Oe;if(t.common.async)return n._parseAsync({data:t.data,path:t.path,parent:t});else return n._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 o=new Map;for(let n of t){let i=rs(n.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(o.has(s))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);o.set(s,n)}}return new dE({typeName:ie.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...He(r)})}}function lE(e,t){let r=ts(e),o=ts(t);if(e===t)return{valid:!0,data:e};else if(r===le.object&&o===le.object){let n=tt.objectKeys(t),i=tt.objectKeys(e).filter((a)=>n.indexOf(a)!==-1),s={...e,...t};for(let a of i){let c=lE(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===le.array&&o===le.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let i=0;i<e.length;i++){let s=e[i],a=t[i],c=lE(s,a);if(!c.valid)return{valid:!1};n.push(c.data)}return{valid:!0,data:n}}else if(r===le.date&&o===le.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class pm extends Qe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),o=(n,i)=>{if(aE(n)||aE(i))return Oe;let s=lE(n.value,i.value);if(!s.valid)return he(r,{code:ne.invalid_intersection_types}),Oe;if(cE(n)||cE(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(([n,i])=>o(n,i));else return o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}pm.create=(e,t,r)=>new pm({left:e,right:t,typeName:ie.ZodIntersection,...He(r)});class is extends Qe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==le.array)return he(r,{code:ne.invalid_type,expected:le.array,received:r.parsedType}),Oe;if(r.data.length<this._def.items.length)return he(r,{code:ne.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Oe;if(!this._def.rest&&r.data.length>this._def.items.length)he(r,{code:ne.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let n=[...r.data].map((i,s)=>{let a=this._def.items[s]||this._def.rest;if(!a)return null;return a._parse(new Ao(r,i,r.path,s))}).filter((i)=>!!i);if(r.common.async)return Promise.all(n).then((i)=>Kr.mergeArray(t,i));else return Kr.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new is({...this._def,rest:e})}}is.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new is({items:e,typeName:ie.ZodTuple,rest:null,...He(t)})};class Ub extends Qe{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!==le.object)return he(r,{code:ne.invalid_type,expected:le.object,received:r.parsedType}),Oe;let o=[],n=this._def.keyType,i=this._def.valueType;for(let s in r.data)o.push({key:n._parse(new Ao(r,s,r.path,s)),value:i._parse(new Ao(r,r.data[s],r.path,s)),alwaysSet:s in r.data});if(r.common.async)return Kr.mergeObjectAsync(t,o);else return Kr.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,r){if(t instanceof Qe)return new Ub({keyType:e,valueType:t,typeName:ie.ZodRecord,...He(r)});return new Ub({keyType:ns.create(),valueType:e,typeName:ie.ZodRecord,...He(t)})}}class Lb extends Qe{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!==le.map)return he(r,{code:ne.invalid_type,expected:le.map,received:r.parsedType}),Oe;let o=this._def.keyType,n=this._def.valueType,i=[...r.data.entries()].map(([s,a],c)=>({key:o._parse(new Ao(r,s,r.path,[c,"key"])),value:n._parse(new Ao(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,u=await a.value;if(c.status==="aborted"||u.status==="aborted")return Oe;if(c.status==="dirty"||u.status==="dirty")t.dirty();s.set(c.value,u.value)}return{status:t.value,value:s}})}else{let s=new Map;for(let a of i){let{key:c,value:u}=a;if(c.status==="aborted"||u.status==="aborted")return Oe;if(c.status==="dirty"||u.status==="dirty")t.dirty();s.set(c.value,u.value)}return{status:t.value,value:s}}}}Lb.create=(e,t,r)=>new Lb({valueType:t,keyType:e,typeName:ie.ZodMap,...He(r)});class zl extends Qe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==le.set)return he(r,{code:ne.invalid_type,expected:le.set,received:r.parsedType}),Oe;let o=this._def;if(o.minSize!==null){if(r.data.size<o.minSize.value)he(r,{code:ne.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()}if(o.maxSize!==null){if(r.data.size>o.maxSize.value)he(r,{code:ne.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty()}let n=this._def.valueType;function i(a){let c=new Set;for(let u of a){if(u.status==="aborted")return Oe;if(u.status==="dirty")t.dirty();c.add(u.value)}return{status:t.value,value:c}}let s=[...r.data.values()].map((a,c)=>n._parse(new Ao(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 zl({...this._def,minSize:{value:e,message:_e.toString(t)}})}max(e,t){return new zl({...this._def,maxSize:{value:e,message:_e.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}zl.create=(e,t)=>new zl({valueType:e,minSize:null,maxSize:null,typeName:ie.ZodSet,...He(t)});class am extends Qe{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==le.function)return he(t,{code:ne.invalid_type,expected:le.function,received:t.parsedType}),Oe;function r(s,a){return zb({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,im(),ua].filter((c)=>!!c),issueData:{code:ne.invalid_arguments,argumentsError:a}})}function o(s,a){return zb({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,im(),ua].filter((c)=>!!c),issueData:{code:ne.invalid_return_type,returnTypeError:a}})}let n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Nl){let s=this;return on(async function(...a){let c=new Vn([]),u=await s._def.args.parseAsync(a,n).catch((m)=>{throw c.addIssue(r(a,m)),c}),d=await Reflect.apply(i,this,u);return await s._def.returns._def.type.parseAsync(d,n).catch((m)=>{throw c.addIssue(o(d,m)),c})})}else{let s=this;return on(function(...a){let c=s._def.args.safeParse(a,n);if(!c.success)throw new Vn([r(a,c.error)]);let u=Reflect.apply(i,this,c.data),d=s._def.returns.safeParse(u,n);if(!d.success)throw new Vn([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new am({...this._def,args:is.create(e).rest(Dc.create())})}returns(e){return new am({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new am({args:e?e:is.create([]).rest(Dc.create()),returns:t||Dc.create(),typeName:ie.ZodFunction,...He(r)})}}class fm extends Qe{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})}}fm.create=(e,t)=>new fm({getter:e,typeName:ie.ZodLazy,...He(t)});class mm extends Qe{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return he(t,{received:t.data,code:ne.invalid_literal,expected:this._def.value}),Oe}return{status:"valid",value:e.data}}get value(){return this._def.value}}mm.create=(e,t)=>new mm({value:e,typeName:ie.ZodLiteral,...He(t)});function OM(e,t){return new Uc({values:e,typeName:ie.ZodEnum,...He(t)})}class Uc extends Qe{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return he(t,{expected:tt.joinValues(r),received:t.parsedType,code:ne.invalid_type}),Oe}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 he(t,{received:t.data,code:ne.invalid_enum_value,options:r}),Oe}return on(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 Uc.create(e,{...this._def,...t})}exclude(e,t=this._def){return Uc.create(this.options.filter((r)=>!e.includes(r)),{...this._def,...t})}}Uc.create=OM;class hm extends Qe{_parse(e){let t=tt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==le.string&&r.parsedType!==le.number){let o=tt.objectValues(t);return he(r,{expected:tt.joinValues(o),received:r.parsedType,code:ne.invalid_type}),Oe}if(!this._cache)this._cache=new Set(tt.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let o=tt.objectValues(t);return he(r,{received:r.data,code:ne.invalid_enum_value,options:o}),Oe}return on(e.data)}get enum(){return this._def.values}}hm.create=(e,t)=>new hm({values:e,typeName:ie.ZodNativeEnum,...He(t)});class Nl extends Qe{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==le.promise&&t.common.async===!1)return he(t,{code:ne.invalid_type,expected:le.promise,received:t.parsedType}),Oe;let r=t.parsedType===le.promise?t.data:Promise.resolve(t.data);return on(r.then((o)=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Nl.create=(e,t)=>new Nl({type:e,typeName:ie.ZodPromise,...He(t)});class fi extends Qe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ie.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),o=this._def.effect||null,n={addIssue:(i)=>{if(he(r,i),i.fatal)t.abort();else t.dirty()},get path(){return r.path}};if(n.addIssue=n.addIssue.bind(n),o.type==="preprocess"){let i=o.transform(r.data,n);if(r.common.async)return Promise.resolve(i).then(async(s)=>{if(t.value==="aborted")return Oe;let a=await this._def.schema._parseAsync({data:s,path:r.path,parent:r});if(a.status==="aborted")return Oe;if(a.status==="dirty")return $l(a.value);if(t.value==="dirty")return $l(a.value);return a});else{if(t.value==="aborted")return Oe;let s=this._def.schema._parseSync({data:i,path:r.path,parent:r});if(s.status==="aborted")return Oe;if(s.status==="dirty")return $l(s.value);if(t.value==="dirty")return $l(s.value);return s}}if(o.type==="refinement"){let i=(s)=>{let a=o.refinement(s,n);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 Oe;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 Oe;if(s.status==="dirty")t.dirty();return i(s.value).then(()=>({status:t.value,value:s.value}))})}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Bc(i))return Oe;let s=o.transform(i.value,n);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(!Bc(i))return Oe;return Promise.resolve(o.transform(i.value,n)).then((s)=>({status:t.value,value:s}))});tt.assertNever(o)}}fi.create=(e,t,r)=>new fi({schema:e,typeName:ie.ZodEffects,effect:t,...He(r)});fi.createWithPreprocess=(e,t,r)=>new fi({schema:t,effect:{type:"preprocess",transform:e},typeName:ie.ZodEffects,...He(r)});class pi extends Qe{_parse(e){if(this._getType(e)===le.undefined)return on(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pi.create=(e,t)=>new pi({innerType:e,typeName:ie.ZodOptional,...He(t)});class la extends Qe{_parse(e){if(this._getType(e)===le.null)return on(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}la.create=(e,t)=>new la({innerType:e,typeName:ie.ZodNullable,...He(t)});class gm extends Qe{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;if(t.parsedType===le.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}gm.create=(e,t)=>new gm({innerType:e,typeName:ie.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...He(t)});class ym extends Qe{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if(sm(o))return o.then((n)=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Vn(r.common.issues)},input:r.data})}));else return{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Vn(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ym.create=(e,t)=>new ym({innerType:e,typeName:ie.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...He(t)});class jb extends Qe{_parse(e){if(this._getType(e)!==le.nan){let r=this._getOrReturnCtx(e);return he(r,{code:ne.invalid_type,expected:le.nan,received:r.parsedType}),Oe}return{status:"valid",value:e.data}}}jb.create=(e)=>new jb({typeName:ie.ZodNaN,...He(e)});var $we=Symbol("zod_brand");class pE extends Qe{_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 Fb extends Qe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let n=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(n.status==="aborted")return Oe;if(n.status==="dirty")return t.dirty(),$l(n.value);else return this._def.out._parseAsync({data:n.value,path:r.path,parent:r})})();else{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(o.status==="aborted")return Oe;if(o.status==="dirty")return t.dirty(),{status:"dirty",value:o.value};else return this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,t){return new Fb({in:e,out:t,typeName:ie.ZodPipeline})}}class bm extends Qe{_parse(e){let t=this._def.innerType._parse(e),r=(o)=>{if(Bc(o))o.value=Object.freeze(o.value);return o};return sm(t)?t.then((o)=>r(o)):r(t)}unwrap(){return this._def.innerType}}bm.create=(e,t)=>new bm({innerType:e,typeName:ie.ZodReadonly,...He(t)});var Rwe={object:Qt.lazycreate},ie;(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"})(ie||(ie={}));var Owe=ns.create,Cwe=Ol.create,zwe=jb.create,Nwe=Cl.create,Mwe=Nb.create,Bwe=cm.create,Dwe=Mb.create,Uwe=um.create,Lwe=lm.create,jwe=Bb.create,Fwe=Dc.create,qwe=os.create,Hwe=Db.create,Gwe=di.create,CM=Qt.create,Vwe=Qt.strictCreate,Zwe=dm.create,Wwe=dE.create,Kwe=pm.create,Jwe=is.create,Ywe=Ub.create,Qwe=Lb.create,Xwe=zl.create,e1e=am.create,t1e=fm.create,r1e=mm.create,n1e=Uc.create,o1e=hm.create,i1e=Nl.create,s1e=fi.create,a1e=pi.create,c1e=la.create,u1e=fi.createWithPreprocess,l1e=Fb.create;var Ro={};Pn(Ro,{$ZodAny:()=>z0,$ZodArray:()=>U0,$ZodAsyncError:()=>mi,$ZodBase64:()=>T0,$ZodBase64URL:()=>E0,$ZodBigInt:()=>Om,$ZodBigIntFormat:()=>$0,$ZodBoolean:()=>Hl,$ZodCIDRv4:()=>w0,$ZodCIDRv6:()=>S0,$ZodCUID:()=>m0,$ZodCUID2:()=>h0,$ZodCatch:()=>nx,$ZodCheck:()=>Tt,$ZodCheckBigIntFormat:()=>nI,$ZodCheckEndsWith:()=>hI,$ZodCheckGreaterThan:()=>r0,$ZodCheckIncludes:()=>fI,$ZodCheckLengthEquals:()=>uI,$ZodCheckLessThan:()=>t0,$ZodCheckLowerCase:()=>dI,$ZodCheckMaxLength:()=>aI,$ZodCheckMaxSize:()=>oI,$ZodCheckMimeType:()=>yI,$ZodCheckMinLength:()=>cI,$ZodCheckMinSize:()=>iI,$ZodCheckMultipleOf:()=>tI,$ZodCheckNumberFormat:()=>rI,$ZodCheckOverwrite:()=>bI,$ZodCheckProperty:()=>gI,$ZodCheckRegex:()=>lI,$ZodCheckSizeEquals:()=>sI,$ZodCheckStartsWith:()=>mI,$ZodCheckStringFormat:()=>ql,$ZodCheckUpperCase:()=>pI,$ZodCodec:()=>Vl,$ZodCustom:()=>lx,$ZodCustomStringFormat:()=>k0,$ZodDate:()=>D0,$ZodDefault:()=>X0,$ZodDiscriminatedUnion:()=>F0,$ZodE164:()=>I0,$ZodEmail:()=>l0,$ZodEmoji:()=>p0,$ZodEncodeError:()=>jc,$ZodEnum:()=>Z0,$ZodError:()=>Em,$ZodExactOptional:()=>Y0,$ZodFile:()=>K0,$ZodFunction:()=>ax,$ZodGUID:()=>c0,$ZodIPv4:()=>x0,$ZodIPv6:()=>v0,$ZodISODate:()=>wI,$ZodISODateTime:()=>_I,$ZodISODuration:()=>TI,$ZodISOTime:()=>SI,$ZodIntersection:()=>q0,$ZodJWT:()=>P0,$ZodKSUID:()=>b0,$ZodLazy:()=>ux,$ZodLiteral:()=>W0,$ZodMAC:()=>_0,$ZodMap:()=>G0,$ZodNaN:()=>ox,$ZodNanoID:()=>f0,$ZodNever:()=>M0,$ZodNonOptional:()=>tx,$ZodNull:()=>C0,$ZodNullable:()=>Q0,$ZodNumber:()=>Rm,$ZodNumberFormat:()=>A0,$ZodObject:()=>L0,$ZodObjectJIT:()=>II,$ZodOptional:()=>zm,$ZodPipe:()=>Nm,$ZodPrefault:()=>ex,$ZodPreprocess:()=>PI,$ZodPromise:()=>cx,$ZodReadonly:()=>ix,$ZodRealError:()=>$n,$ZodRecord:()=>H0,$ZodRegistry:()=>EP,$ZodSet:()=>V0,$ZodString:()=>ya,$ZodStringFormat:()=>_t,$ZodSuccess:()=>rx,$ZodSymbol:()=>R0,$ZodTemplateLiteral:()=>sx,$ZodTransform:()=>J0,$ZodTuple:()=>Cm,$ZodType:()=>ze,$ZodULID:()=>g0,$ZodURL:()=>d0,$ZodUUID:()=>u0,$ZodUndefined:()=>O0,$ZodUnion:()=>Gl,$ZodUnknown:()=>N0,$ZodVoid:()=>B0,$ZodXID:()=>y0,$ZodXor:()=>j0,$brand:()=>mE,$constructor:()=>R,$input:()=>TP,$output:()=>SP,Doc:()=>n0,JSONSchema:()=>R4,JSONSchemaGenerator:()=>_k,NEVER:()=>fE,TimePrecision:()=>PP,_any:()=>Px,_array:()=>MP,_base64:()=>rh,_base64url:()=>nh,_bigint:()=>_x,_boolean:()=>vx,_catch:()=>Xne,_check:()=>$4,_cidrv4:()=>eh,_cidrv6:()=>th,_coercedBigint:()=>zP,_coercedBoolean:()=>CP,_coercedDate:()=>NP,_coercedNumber:()=>OP,_coercedString:()=>IP,_cuid:()=>Zm,_cuid2:()=>Wm,_custom:()=>Ux,_date:()=>Rx,_decode:()=>Zb,_decodeAsync:()=>Kb,_default:()=>Jne,_discriminatedUnion:()=>Dne,_e164:()=>oh,_email:()=>Lm,_emoji:()=>Gm,_encode:()=>Vb,_encodeAsync:()=>Wb,_endsWith:()=>rd,_enum:()=>Hne,_file:()=>Dx,_float32:()=>gx,_float64:()=>yx,_gt:()=>gi,_gte:()=>an,_guid:()=>Kl,_includes:()=>ed,_int:()=>hx,_int32:()=>bx,_int64:()=>wx,_intersection:()=>Une,_ipv4:()=>Qm,_ipv6:()=>Xm,_isoDate:()=>AP,_isoDateTime:()=>kP,_isoDuration:()=>RP,_isoTime:()=>$P,_jwt:()=>ih,_ksuid:()=>Ym,_lazy:()=>noe,_length:()=>Wc,_literal:()=>Vne,_lowercase:()=>Ql,_lt:()=>hi,_lte:()=>Zn,_mac:()=>fx,_map:()=>Fne,_max:()=>Zn,_maxLength:()=>Zc,_maxSize:()=>xa,_mime:()=>nd,_min:()=>an,_minLength:()=>as,_minSize:()=>yi,_multipleOf:()=>ba,_nan:()=>Ox,_nanoid:()=>Vm,_nativeEnum:()=>Gne,_negative:()=>zx,_never:()=>Ax,_nonnegative:()=>Mx,_nonoptional:()=>Yne,_nonpositive:()=>Nx,_normalize:()=>od,_null:()=>Ix,_nullable:()=>Kne,_number:()=>mx,_optional:()=>Wne,_overwrite:()=>$o,_parse:()=>Ul,_parseAsync:()=>Ll,_pipe:()=>eoe,_positive:()=>Cx,_promise:()=>ooe,_property:()=>Bx,_readonly:()=>toe,_record:()=>jne,_refine:()=>Lx,_regex:()=>Yl,_safeDecode:()=>Yb,_safeDecodeAsync:()=>Xb,_safeEncode:()=>Jb,_safeEncodeAsync:()=>Qb,_safeParse:()=>jl,_safeParseAsync:()=>Fl,_set:()=>qne,_size:()=>Vc,_slugify:()=>cd,_startsWith:()=>td,_string:()=>px,_stringFormat:()=>Kc,_stringbool:()=>Hx,_success:()=>Qne,_superRefine:()=>jx,_symbol:()=>Tx,_templateLiteral:()=>roe,_toLowerCase:()=>sd,_toUpperCase:()=>ad,_transform:()=>Zne,_trim:()=>id,_tuple:()=>Lne,_uint32:()=>xx,_uint64:()=>Sx,_ulid:()=>Km,_undefined:()=>Ex,_union:()=>Mne,_unknown:()=>kx,_uppercase:()=>Xl,_url:()=>Jl,_uuid:()=>jm,_uuidv4:()=>Fm,_uuidv6:()=>qm,_uuidv7:()=>Hm,_void:()=>$x,_xid:()=>Jm,_xor:()=>Bne,clone:()=>$r,config:()=>Xt,createStandardJSONSchemaMethod:()=>ud,createToJSONSchemaMethod:()=>BP,decode:()=>WM,decodeAsync:()=>JM,describe:()=>Fx,encode:()=>ZM,encodeAsync:()=>KM,extractDefs:()=>_a,finalize:()=>wa,flattenError:()=>Im,formatError:()=>Pm,globalConfig:()=>Lc,globalRegistry:()=>Rr,initializeContext:()=>va,isValidBase64:()=>EI,isValidBase64URL:()=>_4,isValidJWT:()=>w4,locales:()=>Wl,meta:()=>qx,parse:()=>qc,parseAsync:()=>Hc,prettifyError:()=>EE,process:()=>gt,regexes:()=>Rn,registry:()=>dx,safeDecode:()=>QM,safeDecodeAsync:()=>e4,safeEncode:()=>YM,safeEncodeAsync:()=>XM,safeParse:()=>ha,safeParseAsync:()=>ga,toDotPath:()=>VM,toJSONSchema:()=>Jc,treeifyError:()=>TE,util:()=>re,version:()=>xI});var zM,fE=Object.freeze({status:"aborted"});function R(e,t,r){function o(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 u=s.prototype,d=Object.keys(u);for(let p=0;p<d.length;p++){let m=d[p];if(!(m in a))a[m]=u[m].bind(a)}}let n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let u=r?.Parent?new i:this;o(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(s,"init",{value:o}),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 mE=Symbol("zod_brand");class mi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class jc extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(zM=globalThis).__zod_globalConfig??(zM.__zod_globalConfig={});var Lc=globalThis.__zod_globalConfig;function Xt(e){if(e)Object.assign(Lc,e);return Lc}var re={};Pn(re,{BIGINT_FORMAT_RANGES:()=>wE,Class:()=>HM,NUMBER_FORMAT_RANGES:()=>_E,aborted:()=>ma,allowsEval:()=>bE,assert:()=>Kte,assertEqual:()=>Gte,assertIs:()=>Zte,assertNever:()=>Wte,assertNotEqual:()=>Vte,assignProp:()=>pa,base64ToUint8Array:()=>FM,base64urlToUint8Array:()=>sre,cached:()=>Bl,captureStackTrace:()=>Hb,cleanEnum:()=>ire,cleanRegex:()=>_m,clone:()=>$r,cloneDef:()=>Yte,createTransparentProxy:()=>nre,defineLazy:()=>Ve,esc:()=>qb,escapeRegex:()=>no,explicitlyAborted:()=>SE,extend:()=>DM,finalizeIssue:()=>sn,floatSafeRemainder:()=>gE,getElementAtPath:()=>Qte,getEnumValues:()=>vm,getLengthableOrigin:()=>Tm,getParsedType:()=>rre,getSizableOrigin:()=>Sm,hexToUint8Array:()=>cre,isObject:()=>Fc,isPlainObject:()=>fa,issue:()=>Dl,joinValues:()=>M,jsonStringifyReplacer:()=>Ml,merge:()=>ore,mergeDefs:()=>ss,normalizeParams:()=>se,nullish:()=>da,numKeys:()=>tre,objectClone:()=>Jte,omit:()=>BM,optionalKeys:()=>vE,parsedType:()=>ee,partial:()=>LM,pick:()=>MM,prefixIssues:()=>An,primitiveTypes:()=>xE,promiseAllObject:()=>Xte,propertyKeyTypes:()=>wm,randomString:()=>ere,required:()=>jM,safeExtend:()=>UM,shallowClone:()=>Gb,slugify:()=>yE,stringifyPrimitive:()=>Q,uint8ArrayToBase64:()=>qM,uint8ArrayToBase64url:()=>are,uint8ArrayToHex:()=>ure,unwrapMessage:()=>xm});function Gte(e){return e}function Vte(e){return e}function Zte(e){}function Wte(e){throw Error("Unexpected value in exhaustive check")}function Kte(e){}function vm(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function M(e,t="|"){return e.map((r)=>Q(r)).join(t)}function Ml(e,t){if(typeof t==="bigint")return t.toString();return t}function Bl(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function da(e){return e===null||e===void 0}function _m(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function gE(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-o)<n)return 0;return r-o}var NM=Symbol("evaluating");function Ve(e,t,r){let o=void 0;Object.defineProperty(e,t,{get(){if(o===NM)return;if(o===void 0)o=NM,o=r();return o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Jte(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function pa(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ss(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function Yte(e){return ss(e._zod.def)}function Qte(e,t){if(!t)return e;return t.reduce((r,o)=>r?.[o],e)}function Xte(e){let t=Object.keys(e),r=t.map((o)=>e[o]);return Promise.all(r).then((o)=>{let n={};for(let i=0;i<t.length;i++)n[t[i]]=o[i];return n})}function ere(e=10){let r="";for(let o=0;o<e;o++)r+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return r}function qb(e){return JSON.stringify(e)}function yE(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Hb="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Fc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var bE=Bl(()=>{if(Lc.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function fa(e){if(Fc(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(Fc(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Gb(e){if(fa(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}function tre(e){let t=0;for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r))t++;return t}var rre=(e)=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(e))return"array";if(e===null)return"null";if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return"promise";if(typeof Map<"u"&&e instanceof Map)return"map";if(typeof Set<"u"&&e instanceof Set)return"set";if(typeof Date<"u"&&e instanceof Date)return"date";if(typeof File<"u"&&e instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},wm=new Set(["string","number","symbol"]),xE=new Set(["string","number","bigint","boolean","symbol","undefined"]);function no(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $r(e,t,r){let o=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)o._zod.parent=e;return o}function se(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 nre(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,i){return t??(t=e()),Reflect.set(t,o,n,i)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function Q(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function vE(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var _E={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]},wE={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function MM(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=ss(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 pa(this,"shape",s),s},checks:[]});return $r(e,i)}function BM(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=ss(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 pa(this,"shape",s),s},checks:[]});return $r(e,i)}function DM(e,t){if(!fa(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 n=ss(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return pa(this,"shape",i),i}});return $r(e,n)}function UM(e,t){if(!fa(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=ss(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return pa(this,"shape",o),o}});return $r(e,r)}function ore(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=ss(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return pa(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return $r(e,r)}function LM(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let s=ss(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw Error(`Unrecognized key: "${u}"`);if(!r[u])continue;c[u]=e?new e({type:"optional",innerType:a[u]}):a[u]}else for(let u in a)c[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return pa(this,"shape",c),c},checks:[]});return $r(t,s)}function jM(e,t,r){let o=ss(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};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:n[s]})}else for(let s in n)i[s]=new e({type:"nonoptional",innerType:n[s]});return pa(this,"shape",i),i}});return $r(t,o)}function ma(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 SE(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 An(e,t){return t.map((r)=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function xm(e){return typeof e==="string"?e:e?.message}function sn(e,t,r){let o=e.message?e.message:xm(e.inst?._zod.def?.error?.(e))??xm(t?.error?.(e))??xm(r.customError?.(e))??xm(r.localeError?.(e))??"Invalid input",{inst:n,continue:i,input:s,...a}=e;if(a.path??(a.path=[]),a.message=o,t?.reportInput)a.input=s;return a}function Sm(e){if(e instanceof Set)return"set";if(e instanceof Map)return"map";if(e instanceof File)return"file";return"unknown"}function Tm(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function ee(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 Dl(...e){let[t,r,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:o};return{...t}}function ire(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map((t)=>t[1])}function FM(e){let t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}function qM(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function sre(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return FM(t+r)}function are(e){return qM(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function cre(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2)r[o/2]=Number.parseInt(t.slice(o,o+2),16);return r}function ure(e){return Array.from(e).map((t)=>t.toString(16).padStart(2,"0")).join("")}class HM{constructor(...e){}}var GM=(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,Ml,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Em=R("$ZodError",GM),$n=R("$ZodError",GM,{Parent:Error});function Im(e,t=(r)=>r.message){let r={},o=[];for(let n of e.issues)if(n.path.length>0)r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n));else o.push(t(n));return{formErrors:o,fieldErrors:r}}function Pm(e,t=(r)=>r.message){let r={_errors:[]},o=(n,i=[])=>{for(let s of n.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>o({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")o({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,u=0;while(u<a.length){let d=a[u];if(u!==a.length-1)c[d]=c[d]||{_errors:[]};else c[d]=c[d]||{_errors:[]},c[d]._errors.push(t(s));c=c[d],u++}}}};return o(e),r}function TE(e,t=(r)=>r.message){let r={errors:[]},o=(n,i=[])=>{var s,a;for(let c of n.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map((u)=>o({issues:u},[...i,...c.path]));else if(c.code==="invalid_key")o({issues:c.issues},[...i,...c.path]);else if(c.code==="invalid_element")o({issues:c.issues},[...i,...c.path]);else{let u=[...i,...c.path];if(u.length===0){r.errors.push(t(c));continue}let d=r,p=0;while(p<u.length){let m=u[p],h=p===u.length-1;if(typeof m==="string")d.properties??(d.properties={}),(s=d.properties)[m]??(s[m]={errors:[]}),d=d.properties[m];else d.items??(d.items=[]),(a=d.items)[m]??(a[m]={errors:[]}),d=d.items[m];if(h)d.errors.push(t(c));p++}}};return o(e),r}function VM(e){let t=[],r=e.map((o)=>typeof o==="object"?o.key:o);for(let o of r)if(typeof o==="number")t.push(`[${o}]`);else if(typeof o==="symbol")t.push(`[${JSON.stringify(String(o))}]`);else if(/[^\w$]/.test(o))t.push(`[${JSON.stringify(o)}]`);else{if(t.length)t.push(".");t.push(o)}return t.join("")}function EE(e){let t=[],r=[...e.issues].sort((o,n)=>(o.path??[]).length-(n.path??[]).length);for(let o of r)if(t.push(`✖ ${o.message}`),o.path?.length)t.push(` → at ${VM(o.path)}`);return t.join(`
67
67
  `)}var Ul=(e)=>(t,r,o,n)=>{let i=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new mi;if(s.issues.length){let a=new(n?.Err??e)(s.issues.map((c)=>sn(c,i,Xt())));throw Hb(a,n?.callee),a}return s.value},qc=Ul($n),Ll=(e)=>async(t,r,o,n)=>{let i=o?{...o,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(n?.Err??e)(s.issues.map((c)=>sn(c,i,Xt())));throw Hb(a,n?.callee),a}return s.value},Hc=Ll($n),jl=(e)=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new mi;return i.issues.length?{success:!1,error:new(e??Em)(i.issues.map((s)=>sn(s,n,Xt())))}:{success:!0,data:i.value}},ha=jl($n),Fl=(e)=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)i=await i;return i.issues.length?{success:!1,error:new e(i.issues.map((s)=>sn(s,n,Xt())))}:{success:!0,data:i.value}},ga=Fl($n),Vb=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Ul(e)(t,r,n)},ZM=Vb($n),Zb=(e)=>(t,r,o)=>Ul(e)(t,r,o),WM=Zb($n),Wb=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Ll(e)(t,r,n)},KM=Wb($n),Kb=(e)=>async(t,r,o)=>Ll(e)(t,r,o),JM=Kb($n),Jb=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return jl(e)(t,r,n)},YM=Jb($n),Yb=(e)=>(t,r,o)=>jl(e)(t,r,o),QM=Yb($n),Qb=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Fl(e)(t,r,n)},XM=Qb($n),Xb=(e)=>async(t,r,o)=>Fl(e)(t,r,o),e4=Xb($n);var Rn={};Pn(Rn,{base64:()=>jE,base64url:()=>e0,bigint:()=>WE,boolean:()=>JE,browserEmail:()=>bre,cidrv4:()=>UE,cidrv6:()=>LE,cuid:()=>IE,cuid2:()=>PE,date:()=>HE,datetime:()=>VE,domain:()=>_re,duration:()=>OE,e164:()=>qE,email:()=>zE,emoji:()=>NE,extendedDuration:()=>dre,guid:()=>CE,hex:()=>wre,hostname:()=>vre,html5Email:()=>hre,httpProtocol:()=>FE,idnEmail:()=>yre,integer:()=>KE,ipv4:()=>ME,ipv6:()=>BE,ksuid:()=>$E,lowercase:()=>XE,mac:()=>DE,md5_base64:()=>Tre,md5_base64url:()=>Ere,md5_hex:()=>Sre,nanoid:()=>RE,null:()=>YE,number:()=>km,rfc5322Email:()=>gre,sha1_base64:()=>Pre,sha1_base64url:()=>kre,sha1_hex:()=>Ire,sha256_base64:()=>$re,sha256_base64url:()=>Rre,sha256_hex:()=>Are,sha384_base64:()=>Cre,sha384_base64url:()=>zre,sha384_hex:()=>Ore,sha512_base64:()=>Mre,sha512_base64url:()=>Bre,sha512_hex:()=>Nre,string:()=>ZE,time:()=>GE,ulid:()=>kE,undefined:()=>QE,unicodeEmail:()=>t4,uppercase:()=>eI,uuid:()=>Gc,uuid4:()=>pre,uuid6:()=>fre,uuid7:()=>mre,xid:()=>AE});var IE=/^[cC][0-9a-z]{6,}$/,PE=/^[0-9a-z]+$/,kE=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,AE=/^[0-9a-vA-V]{20}$/,$E=/^[A-Za-z0-9]{27}$/,RE=/^[a-zA-Z0-9_-]{21}$/,OE=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,dre=/^[-+]?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)?)??$/,CE=/^([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})$/,Gc=(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})$`)},pre=Gc(4),fre=Gc(6),mre=Gc(7),zE=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,hre=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,gre=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,t4=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,yre=t4,bre=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,xre="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function NE(){return new RegExp(xre,"u")}var ME=/^(?:(?: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])$/,BE=/^(([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}|:))$/,DE=(e)=>{let t=no(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},UE=/^((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])$/,LE=/^(([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])$/,jE=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,e0=/^[A-Za-z0-9_-]*$/,vre=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,_re=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,FE=/^https?$/,qE=/^\+[1-9]\d{6,14}$/,r4="(?:(?:\\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])))",HE=new RegExp(`^${r4}$`);function n4(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 GE(e){return new RegExp(`^${n4(e)}$`)}function VE(e){let t=n4({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${r4}T(?:${o})$`)}var ZE=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},WE=/^-?\d+n?$/,KE=/^-?\d+$/,km=/^-?\d+(?:\.\d+)?$/,JE=/^(?:true|false)$/i,YE=/^null$/i;var QE=/^undefined$/i;var XE=/^[^A-Z]*$/,eI=/^[^a-z]*$/,wre=/^[0-9a-fA-F]*$/;function Am(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function $m(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var Sre=/^[0-9a-fA-F]{32}$/,Tre=Am(22,"=="),Ere=$m(22),Ire=/^[0-9a-fA-F]{40}$/,Pre=Am(27,"="),kre=$m(27),Are=/^[0-9a-fA-F]{64}$/,$re=Am(43,"="),Rre=$m(43),Ore=/^[0-9a-fA-F]{96}$/,Cre=Am(64,""),zre=$m(64),Nre=/^[0-9a-fA-F]{128}$/,Mre=Am(86,"=="),Bre=$m(86);var Tt=R("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),i4={number:"number",bigint:"bigint",object:"date"},t0=R("$ZodCheckLessThan",(e,t)=>{Tt.init(e,t);let r=i4[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,i=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<i)if(t.inclusive)n.maximum=t.value;else n.exclusiveMaximum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value<=t.value:o.value<t.value)return;o.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),r0=R("$ZodCheckGreaterThan",(e,t)=>{Tt.init(e,t);let r=i4[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>i)if(t.inclusive)n.minimum=t.value;else n.exclusiveMinimum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value>=t.value:o.value>t.value)return;o.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),tI=R("$ZodCheckMultipleOf",(e,t)=>{Tt.init(e,t),e._zod.onattach.push((r)=>{var o;(o=r._zod.bag).multipleOf??(o.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):gE(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})}}),rI=R("$ZodCheckNumberFormat",(e,t)=>{Tt.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,i]=_E[t.format];e._zod.onattach.push((s)=>{let a=s._zod.bag;if(a.format=t.format,a.minimum=n,a.maximum=i,r)a.pattern=KE}),e._zod.check=(s)=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:o,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:o,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:o,inclusive:!0,continue:!t.abort});return}}if(a<n)s.issues.push({origin:"number",input:a,code:"too_small",minimum:n,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})}}),nI=R("$ZodCheckBigIntFormat",(e,t)=>{Tt.init(e,t);let[r,o]=wE[t.format];e._zod.onattach.push((n)=>{let i=n._zod.bag;i.format=t.format,i.minimum=r,i.maximum=o}),e._zod.check=(n)=>{let i=n.value;if(i<r)n.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort});if(i>o)n.issues.push({origin:"bigint",input:i,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),oI=R("$ZodCheckMaxSize",(e,t)=>{var r;Tt.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!da(n)&&n.size!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<n)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let n=o.value;if(n.size<=t.maximum)return;o.issues.push({origin:Sm(n),code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),iI=R("$ZodCheckMinSize",(e,t)=>{var r;Tt.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!da(n)&&n.size!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>n)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let n=o.value;if(n.size>=t.minimum)return;o.issues.push({origin:Sm(n),code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),sI=R("$ZodCheckSizeEquals",(e,t)=>{var r;Tt.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!da(n)&&n.size!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.minimum=t.size,n.maximum=t.size,n.size=t.size}),e._zod.check=(o)=>{let n=o.value,i=n.size;if(i===t.size)return;let s=i>t.size;o.issues.push({origin:Sm(n),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),aI=R("$ZodCheckMaxLength",(e,t)=>{var r;Tt.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!da(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<n)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let n=o.value;if(n.length<=t.maximum)return;let s=Tm(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),cI=R("$ZodCheckMinLength",(e,t)=>{var r;Tt.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!da(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>n)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let n=o.value;if(n.length>=t.minimum)return;let s=Tm(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),uI=R("$ZodCheckLengthEquals",(e,t)=>{var r;Tt.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!da(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=(o)=>{let n=o.value,i=n.length;if(i===t.length)return;let s=Tm(n),a=i>t.length;o.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),ql=R("$ZodCheckStringFormat",(e,t)=>{var r,o;if(Tt.init(e,t),e._zod.onattach.push((n)=>{let i=n._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=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(o=e._zod).check??(o.check=()=>{})}),lI=R("$ZodCheckRegex",(e,t)=>{ql.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})}}),dI=R("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=XE),ql.init(e,t)}),pI=R("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=eI),ql.init(e,t)}),fI=R("$ZodCheckIncludes",(e,t)=>{Tt.init(e,t);let r=no(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push((n)=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),e._zod.check=(n)=>{if(n.value.includes(t.includes,t.position))return;n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),mI=R("$ZodCheckStartsWith",(e,t)=>{Tt.init(e,t);let r=new RegExp(`^${no(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.startsWith(t.prefix))return;o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),hI=R("$ZodCheckEndsWith",(e,t)=>{Tt.init(e,t);let r=new RegExp(`.*${no(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.endsWith(t.suffix))return;o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});function o4(e,t,r){if(e.issues.length)t.issues.push(...An(r,e.issues))}var gI=R("$ZodCheckProperty",(e,t)=>{Tt.init(e,t),e._zod.check=(r)=>{let o=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(o instanceof Promise)return o.then((n)=>o4(n,r,t.property));o4(o,r,t.property);return}}),yI=R("$ZodCheckMimeType",(e,t)=>{Tt.init(e,t);let r=new Set(t.mime);e._zod.onattach.push((o)=>{o._zod.bag.mime=t.mime}),e._zod.check=(o)=>{if(r.has(o.value.type))return;o.issues.push({code:"invalid_value",values:t.mime,input:o.value.type,inst:e,continue:!t.abort})}}),bI=R("$ZodCheckOverwrite",(e,t)=>{Tt.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class n0{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),o=Math.min(...r.map((i)=>i.length-i.trimStart().length)),n=r.map((i)=>i.slice(o)).map((i)=>" ".repeat(this.indent*2)+i);for(let i of n)this.content.push(i)}compile(){let e=Function,t=this?.args,o=[...(this?.content??[""]).map((n)=>` ${n}`)];return new e(...t,o.join(`
69
- `))}}var xI={major:4,minor:4,patch:3};var ze=R("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=xI;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let n of o)for(let i of n._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(s,a,c)=>{let u=ma(s),d;for(let p of a){if(p._zod.def.when){if(SE(s))continue;if(!p._zod.def.when(s))continue}else if(u)continue;let m=s.issues.length,h=p._zod.check(s);if(h instanceof Promise&&c?.async===!1)throw new mi;if(d||h instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await h,s.issues.length===m)return;if(!u)u=ma(s,m)});else{if(s.issues.length===m)continue;if(!u)u=ma(s,m)}}if(d)return d.then(()=>s);return s},i=(s,a,c)=>{if(ma(s))return s.aborted=!0,s;let u=n(a,o,c);if(u instanceof Promise){if(c.async===!1)throw new mi;return u.then((d)=>e._zod.parse(d,c))}return e._zod.parse(u,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let u=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>i(d,s,a));return i(u,s,a)}let c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new mi;return c.then((u)=>n(u,o,a))}return n(c,o,a)}}Ve(e,"~standard",()=>({validate:(n)=>{try{let i=ha(e,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch(i){return ga(e,n).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),ya=R("$ZodString",(e,t)=>{ze.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ZE(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),xt=R("$ZodStringFormat",(e,t)=>{ql.init(e,t),ya.init(e,t)}),c0=R("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=CE),xt.init(e,t)}),u0=R("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Gc(o))}else t.pattern??(t.pattern=Gc());xt.init(e,t)}),l0=R("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=zE),xt.init(e,t)}),d0=R("$ZodURL",(e,t)=>{xt.init(e,t),e._zod.check=(r)=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===FE.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let n=new URL(o);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(n.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(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.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=n.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),p0=R("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=NE()),xt.init(e,t)}),f0=R("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=RE),xt.init(e,t)}),m0=R("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=IE),xt.init(e,t)}),h0=R("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=PE),xt.init(e,t)}),g0=R("$ZodULID",(e,t)=>{t.pattern??(t.pattern=kE),xt.init(e,t)}),y0=R("$ZodXID",(e,t)=>{t.pattern??(t.pattern=AE),xt.init(e,t)}),b0=R("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=$E),xt.init(e,t)}),_I=R("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=VE(t)),xt.init(e,t)}),wI=R("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=HE),xt.init(e,t)}),SI=R("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=GE(t)),xt.init(e,t)}),TI=R("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=OE),xt.init(e,t)}),x0=R("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ME),xt.init(e,t),e._zod.bag.format="ipv4"}),v0=R("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=BE),xt.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})}}}),_0=R("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=DE(t.delimiter)),xt.init(e,t),e._zod.bag.format="mac"}),w0=R("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=UE),xt.init(e,t)}),S0=R("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=LE),xt.init(e,t),e._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[n,i]=o;if(!i)throw Error();let s=Number(i);if(`${s}`!==i)throw Error();if(s<0||s>128)throw Error();new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function EI(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 T0=R("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=jE),xt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(EI(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function _4(e){if(!e0.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return EI(r)}var E0=R("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=e0),xt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(_4(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),I0=R("$ZodE164",(e,t)=>{t.pattern??(t.pattern=qE),xt.init(e,t)});function w4(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(t&&(!("alg"in n)||n.alg!==t))return!1;return!0}catch{return!1}}var P0=R("$ZodJWT",(e,t)=>{xt.init(e,t),e._zod.check=(r)=>{if(w4(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),k0=R("$ZodCustomStringFormat",(e,t)=>{xt.init(e,t),e._zod.check=(r)=>{if(t.fn(r.value))return;r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),Rm=R("$ZodNumber",(e,t)=>{ze.init(e,t),e._zod.pattern=e._zod.bag.pattern??km,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(s){}let n=r.value;if(typeof n==="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i=typeof n==="number"?Number.isNaN(n)?"NaN":!Number.isFinite(n)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}}),A0=R("$ZodNumberFormat",(e,t)=>{rI.init(e,t),Rm.init(e,t)}),Hl=R("$ZodBoolean",(e,t)=>{ze.init(e,t),e._zod.pattern=JE,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(i){}let n=r.value;if(typeof n==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}}),Om=R("$ZodBigInt",(e,t)=>{ze.init(e,t),e._zod.pattern=WE,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(n){}if(typeof r.value==="bigint")return r;return r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),$0=R("$ZodBigIntFormat",(e,t)=>{nI.init(e,t),Om.init(e,t)}),R0=R("$ZodSymbol",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(typeof n==="symbol")return r;return r.issues.push({expected:"symbol",code:"invalid_type",input:n,inst:e}),r}}),O0=R("$ZodUndefined",(e,t)=>{ze.init(e,t),e._zod.pattern=QE,e._zod.values=new Set([void 0]),e._zod.parse=(r,o)=>{let n=r.value;if(typeof n>"u")return r;return r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),r}}),C0=R("$ZodNull",(e,t)=>{ze.init(e,t),e._zod.pattern=YE,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;if(n===null)return r;return r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),z0=R("$ZodAny",(e,t)=>{ze.init(e,t),e._zod.parse=(r)=>r}),N0=R("$ZodUnknown",(e,t)=>{ze.init(e,t),e._zod.parse=(r)=>r}),M0=R("$ZodNever",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),B0=R("$ZodVoid",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(typeof n>"u")return r;return r.issues.push({expected:"void",code:"invalid_type",input:n,inst:e}),r}}),D0=R("$ZodDate",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=new Date(r.value)}catch(a){}let n=r.value,i=n instanceof Date;if(i&&!Number.isNaN(n.getTime()))return r;return r.issues.push({expected:"date",code:"invalid_type",input:n,...i?{received:"Invalid Date"}:{},inst:e}),r}});function a4(e,t,r){if(e.issues.length)t.issues.push(...An(r,e.issues));t.value[r]=e.value}var U0=R("$ZodArray",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let i=[];for(let s=0;s<n.length;s++){let a=n[s],c=t.element._zod.run({value:a,issues:[]},o);if(c instanceof Promise)i.push(c.then((u)=>a4(u,r,s)));else a4(c,r,s)}if(i.length)return Promise.all(i).then(()=>r);return r}});function a0(e,t,r,o,n,i){let s=r in o;if(e.issues.length){if(n&&i&&!s)return;t.issues.push(...An(r,e.issues))}if(!s&&!n){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 S4(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${o}": expected a Zod schema`);let r=vE(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function T4(e,t,r,o,n,i){let s=[],a=n.keySet,c=n.catchall._zod,u=c.def.type,d=c.optin==="optional",p=c.optout==="optional";for(let m in t){if(m==="__proto__")continue;if(a.has(m))continue;if(u==="never"){s.push(m);continue}let h=c.run({value:t[m],issues:[]},o);if(h instanceof Promise)e.push(h.then((y)=>a0(y,r,m,t,d,p)));else a0(h,r,m,t,d,p)}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 L0=R("$ZodObject",(e,t)=>{if(ze.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 o=Bl(()=>S4(t));Ve(e._zod,"propValues",()=>{let a=t.shape,c={};for(let u in a){let d=a[u]._zod;if(d.values){c[u]??(c[u]=new Set);for(let p of d.values)c[u].add(p)}}return c});let n=Fc,i=t.catchall,s;e._zod.parse=(a,c)=>{s??(s=o.value);let u=a.value;if(!n(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};let d=[],p=s.shape;for(let m of s.keys){let h=p[m],y=h._zod.optin==="optional",x=h._zod.optout==="optional",S=h._zod.run({value:u[m],issues:[]},c);if(S instanceof Promise)d.push(S.then((v)=>a0(v,a,m,u,y,x)));else a0(S,a,m,u,y,x)}if(!i)return d.length?Promise.all(d).then(()=>a):a;return T4(d,u,a,c,o.value,e)}}),II=R("$ZodObjectJIT",(e,t)=>{L0.init(e,t);let r=e._zod.parse,o=Bl(()=>S4(t)),n=(m)=>{let h=new n0(["shape","payload","ctx"]),y=o.value,x=(w)=>{let _=qb(w);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};h.write("const input = payload.value;");let S=Object.create(null),v=0;for(let w of y.keys)S[w]=`key_${v++}`;h.write("const newResult = {};");for(let w of y.keys){let _=S[w],T=qb(w),P=m[w],O=P?._zod?.optin==="optional",z=P?._zod?.optout==="optional";if(h.write(`const ${_} = ${x(w)};`),O&&z)h.write(`
69
+ `))}}var xI={major:4,minor:4,patch:3};var ze=R("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=xI;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let n of o)for(let i of n._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(s,a,c)=>{let u=ma(s),d;for(let p of a){if(p._zod.def.when){if(SE(s))continue;if(!p._zod.def.when(s))continue}else if(u)continue;let m=s.issues.length,h=p._zod.check(s);if(h instanceof Promise&&c?.async===!1)throw new mi;if(d||h instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await h,s.issues.length===m)return;if(!u)u=ma(s,m)});else{if(s.issues.length===m)continue;if(!u)u=ma(s,m)}}if(d)return d.then(()=>s);return s},i=(s,a,c)=>{if(ma(s))return s.aborted=!0,s;let u=n(a,o,c);if(u instanceof Promise){if(c.async===!1)throw new mi;return u.then((d)=>e._zod.parse(d,c))}return e._zod.parse(u,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let u=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>i(d,s,a));return i(u,s,a)}let c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new mi;return c.then((u)=>n(u,o,a))}return n(c,o,a)}}Ve(e,"~standard",()=>({validate:(n)=>{try{let i=ha(e,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch(i){return ga(e,n).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),ya=R("$ZodString",(e,t)=>{ze.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ZE(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),_t=R("$ZodStringFormat",(e,t)=>{ql.init(e,t),ya.init(e,t)}),c0=R("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=CE),_t.init(e,t)}),u0=R("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Gc(o))}else t.pattern??(t.pattern=Gc());_t.init(e,t)}),l0=R("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=zE),_t.init(e,t)}),d0=R("$ZodURL",(e,t)=>{_t.init(e,t),e._zod.check=(r)=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===FE.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let n=new URL(o);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(n.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(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.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=n.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),p0=R("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=NE()),_t.init(e,t)}),f0=R("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=RE),_t.init(e,t)}),m0=R("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=IE),_t.init(e,t)}),h0=R("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=PE),_t.init(e,t)}),g0=R("$ZodULID",(e,t)=>{t.pattern??(t.pattern=kE),_t.init(e,t)}),y0=R("$ZodXID",(e,t)=>{t.pattern??(t.pattern=AE),_t.init(e,t)}),b0=R("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=$E),_t.init(e,t)}),_I=R("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=VE(t)),_t.init(e,t)}),wI=R("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=HE),_t.init(e,t)}),SI=R("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=GE(t)),_t.init(e,t)}),TI=R("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=OE),_t.init(e,t)}),x0=R("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ME),_t.init(e,t),e._zod.bag.format="ipv4"}),v0=R("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=BE),_t.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})}}}),_0=R("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=DE(t.delimiter)),_t.init(e,t),e._zod.bag.format="mac"}),w0=R("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=UE),_t.init(e,t)}),S0=R("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=LE),_t.init(e,t),e._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[n,i]=o;if(!i)throw Error();let s=Number(i);if(`${s}`!==i)throw Error();if(s<0||s>128)throw Error();new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function EI(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 T0=R("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=jE),_t.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(EI(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function _4(e){if(!e0.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return EI(r)}var E0=R("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=e0),_t.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(_4(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),I0=R("$ZodE164",(e,t)=>{t.pattern??(t.pattern=qE),_t.init(e,t)});function w4(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(t&&(!("alg"in n)||n.alg!==t))return!1;return!0}catch{return!1}}var P0=R("$ZodJWT",(e,t)=>{_t.init(e,t),e._zod.check=(r)=>{if(w4(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),k0=R("$ZodCustomStringFormat",(e,t)=>{_t.init(e,t),e._zod.check=(r)=>{if(t.fn(r.value))return;r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),Rm=R("$ZodNumber",(e,t)=>{ze.init(e,t),e._zod.pattern=e._zod.bag.pattern??km,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(s){}let n=r.value;if(typeof n==="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i=typeof n==="number"?Number.isNaN(n)?"NaN":!Number.isFinite(n)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}}),A0=R("$ZodNumberFormat",(e,t)=>{rI.init(e,t),Rm.init(e,t)}),Hl=R("$ZodBoolean",(e,t)=>{ze.init(e,t),e._zod.pattern=JE,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(i){}let n=r.value;if(typeof n==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}}),Om=R("$ZodBigInt",(e,t)=>{ze.init(e,t),e._zod.pattern=WE,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(n){}if(typeof r.value==="bigint")return r;return r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),$0=R("$ZodBigIntFormat",(e,t)=>{nI.init(e,t),Om.init(e,t)}),R0=R("$ZodSymbol",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(typeof n==="symbol")return r;return r.issues.push({expected:"symbol",code:"invalid_type",input:n,inst:e}),r}}),O0=R("$ZodUndefined",(e,t)=>{ze.init(e,t),e._zod.pattern=QE,e._zod.values=new Set([void 0]),e._zod.parse=(r,o)=>{let n=r.value;if(typeof n>"u")return r;return r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),r}}),C0=R("$ZodNull",(e,t)=>{ze.init(e,t),e._zod.pattern=YE,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;if(n===null)return r;return r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),z0=R("$ZodAny",(e,t)=>{ze.init(e,t),e._zod.parse=(r)=>r}),N0=R("$ZodUnknown",(e,t)=>{ze.init(e,t),e._zod.parse=(r)=>r}),M0=R("$ZodNever",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),B0=R("$ZodVoid",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(typeof n>"u")return r;return r.issues.push({expected:"void",code:"invalid_type",input:n,inst:e}),r}}),D0=R("$ZodDate",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=new Date(r.value)}catch(a){}let n=r.value,i=n instanceof Date;if(i&&!Number.isNaN(n.getTime()))return r;return r.issues.push({expected:"date",code:"invalid_type",input:n,...i?{received:"Invalid Date"}:{},inst:e}),r}});function a4(e,t,r){if(e.issues.length)t.issues.push(...An(r,e.issues));t.value[r]=e.value}var U0=R("$ZodArray",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let i=[];for(let s=0;s<n.length;s++){let a=n[s],c=t.element._zod.run({value:a,issues:[]},o);if(c instanceof Promise)i.push(c.then((u)=>a4(u,r,s)));else a4(c,r,s)}if(i.length)return Promise.all(i).then(()=>r);return r}});function a0(e,t,r,o,n,i){let s=r in o;if(e.issues.length){if(n&&i&&!s)return;t.issues.push(...An(r,e.issues))}if(!s&&!n){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 S4(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${o}": expected a Zod schema`);let r=vE(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function T4(e,t,r,o,n,i){let s=[],a=n.keySet,c=n.catchall._zod,u=c.def.type,d=c.optin==="optional",p=c.optout==="optional";for(let m in t){if(m==="__proto__")continue;if(a.has(m))continue;if(u==="never"){s.push(m);continue}let h=c.run({value:t[m],issues:[]},o);if(h instanceof Promise)e.push(h.then((y)=>a0(y,r,m,t,d,p)));else a0(h,r,m,t,d,p)}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 L0=R("$ZodObject",(e,t)=>{if(ze.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 o=Bl(()=>S4(t));Ve(e._zod,"propValues",()=>{let a=t.shape,c={};for(let u in a){let d=a[u]._zod;if(d.values){c[u]??(c[u]=new Set);for(let p of d.values)c[u].add(p)}}return c});let n=Fc,i=t.catchall,s;e._zod.parse=(a,c)=>{s??(s=o.value);let u=a.value;if(!n(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};let d=[],p=s.shape;for(let m of s.keys){let h=p[m],y=h._zod.optin==="optional",x=h._zod.optout==="optional",S=h._zod.run({value:u[m],issues:[]},c);if(S instanceof Promise)d.push(S.then((v)=>a0(v,a,m,u,y,x)));else a0(S,a,m,u,y,x)}if(!i)return d.length?Promise.all(d).then(()=>a):a;return T4(d,u,a,c,o.value,e)}}),II=R("$ZodObjectJIT",(e,t)=>{L0.init(e,t);let r=e._zod.parse,o=Bl(()=>S4(t)),n=(m)=>{let h=new n0(["shape","payload","ctx"]),y=o.value,x=(w)=>{let _=qb(w);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};h.write("const input = payload.value;");let S=Object.create(null),v=0;for(let w of y.keys)S[w]=`key_${v++}`;h.write("const newResult = {};");for(let w of y.keys){let _=S[w],T=qb(w),P=m[w],O=P?._zod?.optin==="optional",z=P?._zod?.optout==="optional";if(h.write(`const ${_} = ${x(w)};`),O&&z)h.write(`
70
70
  if (${_}.issues.length) {
71
71
  if (${T} in input) {
72
72
  payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
@@ -127,30 +127,30 @@ ${vH(m)}`;super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessag
127
127
 
128
128
  `)}h.write("payload.value = newResult;"),h.write("return payload;");let E=h.compile();return(w,_)=>E(m,w,_)},i,s=Fc,a=!Lc.jitless,u=a&&bE.value,d=t.catchall,p;e._zod.parse=(m,h)=>{p??(p=o.value);let y=m.value;if(!s(y))return m.issues.push({expected:"object",code:"invalid_type",input:y,inst:e}),m;if(a&&u&&h?.async===!1&&h.jitless!==!0){if(!i)i=n(t.shape);if(m=i(m,h),!d)return m;return T4([],y,m,h,p,e)}return r(m,h)}});function c4(e,t,r,o){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let n=e.filter((i)=>!ma(i));if(n.length===1)return t.value=n[0].value,n[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((i)=>i.issues.map((s)=>sn(s,o,Xt())))}),t}var Gl=R("$ZodUnion",(e,t)=>{ze.init(e,t),Ve(e._zod,"optin",()=>t.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),Ve(e._zod,"optout",()=>t.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),Ve(e._zod,"values",()=>{if(t.options.every((o)=>o._zod.values))return new Set(t.options.flatMap((o)=>Array.from(o._zod.values)));return}),Ve(e._zod,"pattern",()=>{if(t.options.every((o)=>o._zod.pattern)){let o=t.options.map((n)=>n._zod.pattern);return new RegExp(`^(${o.map((n)=>_m(n.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,n)=>{if(r)return r(o,n);let i=!1,s=[];for(let a of t.options){let c=a._zod.run({value:o.value,issues:[]},n);if(c instanceof Promise)s.push(c),i=!0;else{if(c.issues.length===0)return c;s.push(c)}}if(!i)return c4(s,o,e,n);return Promise.all(s).then((a)=>c4(a,o,e,n))}});function u4(e,t,r,o){let n=e.filter((i)=>i.issues.length===0);if(n.length===1)return t.value=n[0].value,t;if(n.length===0)t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((i)=>i.issues.map((s)=>sn(s,o,Xt())))});else t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1});return t}var j0=R("$ZodXor",(e,t)=>{Gl.init(e,t),t.inclusive=!1;let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,n)=>{if(r)return r(o,n);let i=!1,s=[];for(let a of t.options){let c=a._zod.run({value:o.value,issues:[]},n);if(c instanceof Promise)s.push(c),i=!0;else s.push(c)}if(!i)return u4(s,o,e,n);return Promise.all(s).then((a)=>u4(a,o,e,n))}}),F0=R("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Gl.init(e,t);let r=e._zod.parse;Ve(e._zod,"propValues",()=>{let n={};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(!n[a])n[a]=new Set;for(let u of c)n[a].add(u)}}return n});let o=Bl(()=>{let n=t.options,i=new Map;for(let s of n){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=(n,i)=>{let s=n.value;if(!Fc(s))return n.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),n;let a=o.value.get(s?.[t.discriminator]);if(a)return a._zod.run(n,i);if(t.unionFallback||i.direction==="backward")return r(n,i);return n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(o.value.keys()),input:s,path:[t.discriminator],inst:e}),n}}),q0=R("$ZodIntersection",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{let n=r.value,i=t.left._zod.run({value:n,issues:[]},o),s=t.right._zod.run({value:n,issues:[]},o);if(i instanceof Promise||s instanceof Promise)return Promise.all([i,s]).then(([c,u])=>l4(r,c,u));return l4(r,i,s)}});function vI(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(fa(e)&&fa(t)){let r=Object.keys(t),o=Object.keys(e).filter((i)=>r.indexOf(i)!==-1),n={...e,...t};for(let i of o){let s=vI(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};n[i]=s.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<e.length;o++){let n=e[o],i=t[o],s=vI(n,i);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function l4(e,t,r){let o=new Map,n;for(let a of t.issues)if(a.code==="unrecognized_keys"){n??(n=a);for(let c of a.keys){if(!o.has(c))o.set(c,{});o.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(!o.has(c))o.set(c,{});o.get(c).r=!0}else e.issues.push(a);let i=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&n)e.issues.push({...n,keys:i});if(ma(e))return e;let s=vI(t.value,r.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var Cm=R("$ZodTuple",(e,t)=>{ze.init(e,t);let r=t.items;e._zod.parse=(o,n)=>{let i=o.value;if(!Array.isArray(i))return o.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),o;o.value=[];let s=[],a=d4(r,"optin"),c=d4(r,"optout");if(!t.rest){if(i.length<a)return o.issues.push({code:"too_small",minimum:a,inclusive:!0,input:i,inst:e,origin:"array"}),o;if(i.length>r.length)o.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:i,inst:e,origin:"array"})}let u=Array(r.length);for(let d=0;d<r.length;d++){let p=r[d]._zod.run({value:i[d],issues:[]},n);if(p instanceof Promise)s.push(p.then((m)=>{u[d]=m}));else u[d]=p}if(t.rest){let d=r.length-1,p=i.slice(r.length);for(let m of p){d++;let h=t.rest._zod.run({value:m,issues:[]},n);if(h instanceof Promise)s.push(h.then((y)=>p4(y,o,d)));else p4(h,o,d)}}if(s.length)return Promise.all(s).then(()=>f4(u,o,r,i,c));return f4(u,o,r,i,c)}});function d4(e,t){for(let r=e.length-1;r>=0;r--)if(e[r]._zod[t]!=="optional")return r+1;return 0}function p4(e,t,r){if(e.issues.length)t.issues.push(...An(r,e.issues));t.value[r]=e.value}function f4(e,t,r,o,n){for(let i=0;i<r.length;i++){let s=e[i],a=i<o.length;if(s.issues.length){if(!a&&i>=n){t.value.length=i;break}t.issues.push(...An(i,s.issues))}t.value[i]=s.value}for(let i=t.value.length-1;i>=o.length;i--)if(r[i]._zod.optout==="optional"&&t.value[i]===void 0)t.value.length=i;else break;return t}var H0=R("$ZodRecord",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!fa(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let i=[],s=t.keyType._zod.values;if(s){r.value={};let a=new Set;for(let u of s)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){a.add(typeof u==="number"?u.toString():u);let d=t.keyType._zod.run({value:u,issues:[]},o);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((h)=>sn(h,o,Xt())),input:u,path:[u],inst:e});continue}let p=d.value,m=t.valueType._zod.run({value:n[u],issues:[]},o);if(m instanceof Promise)i.push(m.then((h)=>{if(h.issues.length)r.issues.push(...An(u,h.issues));r.value[p]=h.value}));else{if(m.issues.length)r.issues.push(...An(u,m.issues));r.value[p]=m.value}}let c;for(let u in n)if(!a.has(u))c=c??[],c.push(u);if(c&&c.length>0)r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(n)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(n,a))continue;let c=t.keyType._zod.run({value:a,issues:[]},o);if(c instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&km.test(a)&&c.issues.length){let p=t.keyType._zod.run({value:Number(a),issues:[]},o);if(p instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(p.issues.length===0)c=p}if(c.issues.length){if(t.mode==="loose")r.value[a]=n[a];else r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map((p)=>sn(p,o,Xt())),input:a,path:[a],inst:e});continue}let d=t.valueType._zod.run({value:n[a],issues:[]},o);if(d instanceof Promise)i.push(d.then((p)=>{if(p.issues.length)r.issues.push(...An(a,p.issues));r.value[c.value]=p.value}));else{if(d.issues.length)r.issues.push(...An(a,d.issues));r.value[c.value]=d.value}}}if(i.length)return Promise.all(i).then(()=>r);return r}}),G0=R("$ZodMap",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!(n instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:n,inst:e}),r;let i=[];r.value=new Map;for(let[s,a]of n){let c=t.keyType._zod.run({value:s,issues:[]},o),u=t.valueType._zod.run({value:a,issues:[]},o);if(c instanceof Promise||u instanceof Promise)i.push(Promise.all([c,u]).then(([d,p])=>{m4(d,p,r,s,n,e,o)}));else m4(c,u,r,s,n,e,o)}if(i.length)return Promise.all(i).then(()=>r);return r}});function m4(e,t,r,o,n,i,s){if(e.issues.length)if(wm.has(typeof o))r.issues.push(...An(o,e.issues));else r.issues.push({code:"invalid_key",origin:"map",input:n,inst:i,issues:e.issues.map((a)=>sn(a,s,Xt()))});if(t.issues.length)if(wm.has(typeof o))r.issues.push(...An(o,t.issues));else r.issues.push({origin:"map",code:"invalid_element",input:n,inst:i,key:o,issues:t.issues.map((a)=>sn(a,s,Xt()))});r.value.set(e.value,t.value)}var V0=R("$ZodSet",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!(n instanceof Set))return r.issues.push({input:n,inst:e,expected:"set",code:"invalid_type"}),r;let i=[];r.value=new Set;for(let s of n){let a=t.valueType._zod.run({value:s,issues:[]},o);if(a instanceof Promise)i.push(a.then((c)=>h4(c,r)));else h4(a,r)}if(i.length)return Promise.all(i).then(()=>r);return r}});function h4(e,t){if(e.issues.length)t.issues.push(...e.issues);t.value.add(e.value)}var Z0=R("$ZodEnum",(e,t)=>{ze.init(e,t);let r=vm(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter((n)=>wm.has(typeof n)).map((n)=>typeof n==="string"?no(n):n.toString()).join("|")})$`),e._zod.parse=(n,i)=>{let s=n.value;if(o.has(s))return n;return n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),W0=R("$ZodLiteral",(e,t)=>{if(ze.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((o)=>typeof o==="string"?no(o):o?no(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,n)=>{let i=o.value;if(r.has(i))return o;return o.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),o}}),K0=R("$ZodFile",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(n instanceof File)return r;return r.issues.push({expected:"file",code:"invalid_type",input:n,inst:e}),r}}),J0=R("$ZodTransform",(e,t)=>{ze.init(e,t),e._zod.optin="optional",e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new jc(e.constructor.name);let n=t.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then((s)=>(r.value=s,r.fallback=!0,r));if(n instanceof Promise)throw new mi;return r.value=n,r.fallback=!0,r}});function g4(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var zm=R("$ZodOptional",(e,t)=>{ze.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ve(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ve(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${_m(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(t.innerType._zod.optin==="optional"){let n=r.value,i=t.innerType._zod.run(r,o);if(i instanceof Promise)return i.then((s)=>g4(s,n));return g4(i,n)}if(r.value===void 0)return r;return t.innerType._zod.run(r,o)}}),Y0=R("$ZodExactOptional",(e,t)=>{zm.init(e,t),Ve(e._zod,"values",()=>t.innerType._zod.values),Ve(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,o)=>t.innerType._zod.run(r,o)}),Q0=R("$ZodNullable",(e,t)=>{ze.init(e,t),Ve(e._zod,"optin",()=>t.innerType._zod.optin),Ve(e._zod,"optout",()=>t.innerType._zod.optout),Ve(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${_m(r.source)}|null)$`):void 0}),Ve(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>{if(r.value===null)return r;return t.innerType._zod.run(r,o)}}),X0=R("$ZodDefault",(e,t)=>{ze.init(e,t),e._zod.optin="optional",Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>y4(i,t));return y4(n,t)}});function y4(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var ex=R("$ZodPrefault",(e,t)=>{ze.init(e,t),e._zod.optin="optional",Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,o)}}),tx=R("$ZodNonOptional",(e,t)=>{ze.init(e,t),Ve(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>b4(i,e));return b4(n,e)}});function b4(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 rx=R("$ZodSuccess",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new jc("ZodSuccess");let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>(r.value=i.issues.length===0,r));return r.value=n.issues.length===0,r}}),nx=R("$ZodCatch",(e,t)=>{ze.init(e,t),e._zod.optin="optional",Ve(e._zod,"optout",()=>t.innerType._zod.optout),Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>{if(r.value=i.value,i.issues.length)r.value=t.catchValue({...r,error:{issues:i.issues.map((s)=>sn(s,o,Xt()))},input:r.value}),r.issues=[],r.fallback=!0;return r});if(r.value=n.value,n.issues.length)r.value=t.catchValue({...r,error:{issues:n.issues.map((i)=>sn(i,o,Xt()))},input:r.value}),r.issues=[],r.fallback=!0;return r}}),ox=R("$ZodNaN",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>{if(typeof r.value!=="number"||!Number.isNaN(r.value))return r.issues.push({input:r.value,inst:e,expected:"nan",code:"invalid_type"}),r;return r}}),Nm=R("$ZodPipe",(e,t)=>{ze.init(e,t),Ve(e._zod,"values",()=>t.in._zod.values),Ve(e._zod,"optin",()=>t.in._zod.optin),Ve(e._zod,"optout",()=>t.out._zod.optout),Ve(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if(o.direction==="backward"){let i=t.out._zod.run(r,o);if(i instanceof Promise)return i.then((s)=>o0(s,t.in,o));return o0(i,t.in,o)}let n=t.in._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>o0(i,t.out,o));return o0(n,t.out,o)}});function o0(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 Vl=R("$ZodCodec",(e,t)=>{ze.init(e,t),Ve(e._zod,"values",()=>t.in._zod.values),Ve(e._zod,"optin",()=>t.in._zod.optin),Ve(e._zod,"optout",()=>t.out._zod.optout),Ve(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if((o.direction||"forward")==="forward"){let i=t.in._zod.run(r,o);if(i instanceof Promise)return i.then((s)=>i0(s,t,o));return i0(i,t,o)}else{let i=t.out._zod.run(r,o);if(i instanceof Promise)return i.then((s)=>i0(s,t,o));return i0(i,t,o)}}});function i0(e,t,r){if(e.issues.length)return e.aborted=!0,e;if((r.direction||"forward")==="forward"){let n=t.transform(e.value,e);if(n instanceof Promise)return n.then((i)=>s0(e,i,t.out,r));return s0(e,n,t.out,r)}else{let n=t.reverseTransform(e.value,e);if(n instanceof Promise)return n.then((i)=>s0(e,i,t.in,r));return s0(e,n,t.in,r)}}function s0(e,t,r,o){if(e.issues.length)return e.aborted=!0,e;return r._zod.run({value:t,issues:e.issues},o)}var PI=R("$ZodPreprocess",(e,t)=>{Nm.init(e,t)}),ix=R("$ZodReadonly",(e,t)=>{ze.init(e,t),Ve(e._zod,"propValues",()=>t.innerType._zod.propValues),Ve(e._zod,"values",()=>t.innerType._zod.values),Ve(e._zod,"optin",()=>t.innerType?._zod?.optin),Ve(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then(x4);return x4(n)}});function x4(e){return e.value=Object.freeze(e.value),e}var sx=R("$ZodTemplateLiteral",(e,t)=>{ze.init(e,t);let r=[];for(let o of t.parts)if(typeof o==="object"&&o!==null){if(!o._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...o._zod.traits].shift()}`);let n=o._zod.pattern instanceof RegExp?o._zod.pattern.source:o._zod.pattern;if(!n)throw Error(`Invalid template literal part: ${o._zod.traits}`);let i=n.startsWith("^")?1:0,s=n.endsWith("$")?n.length-1:n.length;r.push(n.slice(i,s))}else if(o===null||xE.has(typeof o))r.push(no(`${o}`));else throw Error(`Invalid template literal part: ${o}`);e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(o,n)=>{if(typeof o.value!=="string")return o.issues.push({input:o.value,inst:e,expected:"string",code:"invalid_type"}),o;if(e._zod.pattern.lastIndex=0,!e._zod.pattern.test(o.value))return o.issues.push({input:o.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),o;return o}}),ax=R("$ZodFunction",(e,t)=>(ze.init(e,t),e._def=t,e._zod.def=t,e.implement=(r)=>{if(typeof r!=="function")throw Error("implement() must be called with a function");return function(...o){let n=e._def.input?qc(e._def.input,o):o,i=Reflect.apply(r,this,n);if(e._def.output)return qc(e._def.output,i);return i}},e.implementAsync=(r)=>{if(typeof r!=="function")throw Error("implementAsync() must be called with a function");return async function(...o){let n=e._def.input?await Hc(e._def.input,o):o,i=await Reflect.apply(r,this,n);if(e._def.output)return await Hc(e._def.output,i);return i}},e._zod.parse=(r,o)=>{if(typeof r.value!=="function")return r.issues.push({code:"invalid_type",expected:"function",input:r.value,inst:e}),r;if(e._def.output&&e._def.output._zod.def.type==="promise")r.value=e.implementAsync(r.value);else r.value=e.implement(r.value);return r},e.input=(...r)=>{let o=e.constructor;if(Array.isArray(r[0]))return new o({type:"function",input:new Cm({type:"tuple",items:r[0],rest:r[1]}),output:e._def.output});return new o({type:"function",input:r[0],output:e._def.output})},e.output=(r)=>new e.constructor({type:"function",input:e._def.input,output:r}),e)),cx=R("$ZodPromise",(e,t)=>{ze.init(e,t),e._zod.parse=(r,o)=>Promise.resolve(r.value).then((n)=>t.innerType._zod.run({value:n,issues:[]},o))}),ux=R("$ZodLazy",(e,t)=>{ze.init(e,t),Ve(e._zod,"innerType",()=>{let r=t;if(!r._cachedInner)r._cachedInner=t.getter();return r._cachedInner}),Ve(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Ve(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Ve(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Ve(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,o)=>e._zod.innerType._zod.run(r,o)}),lx=R("$ZodCustom",(e,t)=>{Tt.init(e,t),ze.init(e,t),e._zod.parse=(r,o)=>r,e._zod.check=(r)=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then((i)=>v4(i,r,o,e));v4(n,r,o,e);return}});function v4(e,t,r,o){if(!e){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};if(o._zod.def.params)n.params=o._zod.def.params;t.issues.push(Dl(n))}}var Wl={};Pn(Wl,{ar:()=>kI,az:()=>AI,be:()=>$I,bg:()=>RI,ca:()=>OI,cs:()=>CI,da:()=>zI,de:()=>NI,el:()=>MI,en:()=>Mm,eo:()=>BI,es:()=>DI,fa:()=>UI,fi:()=>LI,fr:()=>jI,frCA:()=>FI,he:()=>qI,hr:()=>HI,hu:()=>GI,hy:()=>VI,id:()=>ZI,is:()=>WI,it:()=>KI,ja:()=>JI,ka:()=>YI,kh:()=>QI,km:()=>Bm,ko:()=>XI,lt:()=>eP,mk:()=>tP,ms:()=>rP,nl:()=>nP,no:()=>oP,ota:()=>iP,pl:()=>aP,ps:()=>sP,pt:()=>cP,ro:()=>uP,ru:()=>lP,sl:()=>dP,sv:()=>pP,ta:()=>fP,th:()=>mP,tr:()=>hP,ua:()=>gP,uk:()=>Um,ur:()=>yP,uz:()=>bP,vi:()=>xP,yo:()=>wP,zhCN:()=>vP,zhTW:()=>_P});var Ure=()=>{let e={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function t(n){return e[n]??null}let r={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${n.expected}، ولكن تم إدخال ${a}`;return`مدخلات غير مقبولة: يفترض إدخال ${i}، ولكن تم إدخال ${a}`}case"invalid_value":if(n.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${Q(n.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return` أكبر من اللازم: يفترض أن تكون ${n.origin??"القيمة"} ${i} ${n.maximum.toString()} ${s.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${n.origin??"القيمة"} ${i} ${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`أصغر من اللازم: يفترض لـ ${n.origin} أن يكون ${i} ${n.minimum.toString()} ${s.unit}`;return`أصغر من اللازم: يفترض لـ ${n.origin} أن يكون ${i} ${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${n.prefix}"`;if(i.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${i.suffix}"`;if(i.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${i.includes}"`;if(i.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${i.pattern}`;return`${r[i.format]??n.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${n.divisor}`;case"unrecognized_keys":return`معرف${n.keys.length>1?"ات":""} غريب${n.keys.length>1?"ة":""}: ${M(n.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${n.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${n.origin}`;default:return"مدخل غير مقبول"}}};function kI(){return{localeError:Ure()}}var Lre=()=>{let e={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function t(n){return e[n]??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",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"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Yanlış dəyər: gözlənilən instanceof ${n.expected}, daxil olan ${a}`;return`Yanlış dəyər: gözlənilən ${i}, daxil olan ${a}`}case"invalid_value":if(n.values.length===1)return`Yanlış dəyər: gözlənilən ${Q(n.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Çox böyük: gözlənilən ${n.origin??"dəyər"} ${i}${n.maximum.toString()} ${s.unit??"element"}`;return`Çox böyük: gözlənilən ${n.origin??"dəyər"} ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Çox kiçik: gözlənilən ${n.origin} ${i}${n.minimum.toString()} ${s.unit}`;return`Çox kiçik: gözlənilən ${n.origin} ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Yanlış mətn: "${i.prefix}" ilə başlamalıdır`;if(i.format==="ends_with")return`Yanlış mətn: "${i.suffix}" ilə bitməlidir`;if(i.format==="includes")return`Yanlış mətn: "${i.includes}" daxil olmalıdır`;if(i.format==="regex")return`Yanlış mətn: ${i.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${r[i.format]??n.format}`}case"not_multiple_of":return`Yanlış ədəd: ${n.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${n.keys.length>1?"lar":""}: ${M(n.keys,", ")}`;case"invalid_key":return`${n.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${n.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function AI(){return{localeError:Lre()}}function E4(e,t,r,o){let n=Math.abs(e),i=n%10,s=n%100;if(s>=11&&s<=19)return o;if(i===1)return t;if(i>=2&&i<=4)return r;return o}var jre=()=>{let e={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function t(n){return e[n]??null}let r={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"},o={nan:"NaN",number:"лік",array:"масіў"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Няправільны ўвод: чакаўся instanceof ${n.expected}, атрымана ${a}`;return`Няправільны ўвод: чакаўся ${i}, атрымана ${a}`}case"invalid_value":if(n.values.length===1)return`Няправільны ўвод: чакалася ${Q(n.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s){let a=Number(n.maximum),c=E4(a,s.unit.one,s.unit.few,s.unit.many);return`Занадта вялікі: чакалася, што ${n.origin??"значэнне"} павінна ${s.verb} ${i}${n.maximum.toString()} ${c}`}return`Занадта вялікі: чакалася, што ${n.origin??"значэнне"} павінна быць ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s){let a=Number(n.minimum),c=E4(a,s.unit.one,s.unit.few,s.unit.many);return`Занадта малы: чакалася, што ${n.origin} павінна ${s.verb} ${i}${n.minimum.toString()} ${c}`}return`Занадта малы: чакалася, што ${n.origin} павінна быць ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${i.prefix}"`;if(i.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${i.suffix}"`;if(i.format==="includes")return`Няправільны радок: павінен змяшчаць "${i.includes}"`;if(i.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${i.pattern}`;return`Няправільны ${r[i.format]??n.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${n.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${n.keys.length>1?"ключы":"ключ"}: ${M(n.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${n.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${n.origin}`;default:return"Няправільны ўвод"}}};function $I(){return{localeError:jre()}}var Fre=()=>{let e={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function t(n){return e[n]??null}let r={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"},o={nan:"NaN",number:"число",array:"масив"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Невалиден вход: очакван instanceof ${n.expected}, получен ${a}`;return`Невалиден вход: очакван ${i}, получен ${a}`}case"invalid_value":if(n.values.length===1)return`Невалиден вход: очакван ${Q(n.values[0])}`;return`Невалидна опция: очаквано едно от ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Твърде голямо: очаква се ${n.origin??"стойност"} да съдържа ${i}${n.maximum.toString()} ${s.unit??"елемента"}`;return`Твърде голямо: очаква се ${n.origin??"стойност"} да бъде ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Твърде малко: очаква се ${n.origin} да съдържа ${i}${n.minimum.toString()} ${s.unit}`;return`Твърде малко: очаква се ${n.origin} да бъде ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Невалиден низ: трябва да започва с "${i.prefix}"`;if(i.format==="ends_with")return`Невалиден низ: трябва да завършва с "${i.suffix}"`;if(i.format==="includes")return`Невалиден низ: трябва да включва "${i.includes}"`;if(i.format==="regex")return`Невалиден низ: трябва да съвпада с ${i.pattern}`;let s="Невалиден";if(i.format==="emoji")s="Невалидно";if(i.format==="datetime")s="Невалидно";if(i.format==="date")s="Невалидна";if(i.format==="time")s="Невалидно";if(i.format==="duration")s="Невалидна";return`${s} ${r[i.format]??n.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${n.divisor}`;case"unrecognized_keys":return`Неразпознат${n.keys.length>1?"и":""} ключ${n.keys.length>1?"ове":""}: ${M(n.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${n.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${n.origin}`;default:return"Невалиден вход"}}};function RI(){return{localeError:Fre()}}var qre=()=>{let e={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(n){return e[n]??null}let r={regex:"entrada",email:"adreça electrònica",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:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Tipus invàlid: s'esperava instanceof ${n.expected}, s'ha rebut ${a}`;return`Tipus invàlid: s'esperava ${i}, s'ha rebut ${a}`}case"invalid_value":if(n.values.length===1)return`Valor invàlid: s'esperava ${Q(n.values[0])}`;return`Opció invàlida: s'esperava una de ${M(n.values," o ")}`;case"too_big":{let i=n.inclusive?"com a màxim":"menys de",s=t(n.origin);if(s)return`Massa gran: s'esperava que ${n.origin??"el valor"} contingués ${i} ${n.maximum.toString()} ${s.unit??"elements"}`;return`Massa gran: s'esperava que ${n.origin??"el valor"} fos ${i} ${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?"com a mínim":"més de",s=t(n.origin);if(s)return`Massa petit: s'esperava que ${n.origin} contingués ${i} ${n.minimum.toString()} ${s.unit}`;return`Massa petit: s'esperava que ${n.origin} fos ${i} ${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Format invàlid: ha de començar amb "${i.prefix}"`;if(i.format==="ends_with")return`Format invàlid: ha d'acabar amb "${i.suffix}"`;if(i.format==="includes")return`Format invàlid: ha d'incloure "${i.includes}"`;if(i.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${i.pattern}`;return`Format invàlid per a ${r[i.format]??n.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${n.divisor}`;case"unrecognized_keys":return`Clau${n.keys.length>1?"s":""} no reconeguda${n.keys.length>1?"s":""}: ${M(n.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${n.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${n.origin}`;default:return"Entrada invàlida"}}};function OI(){return{localeError:qre()}}var Hre=()=>{let e={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function t(n){return e[n]??null}let r={regex:"regulární výraz",email:"e-mailová adresa",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:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"},o={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Neplatný vstup: očekáváno instanceof ${n.expected}, obdrženo ${a}`;return`Neplatný vstup: očekáváno ${i}, obdrženo ${a}`}case"invalid_value":if(n.values.length===1)return`Neplatný vstup: očekáváno ${Q(n.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Hodnota je příliš velká: ${n.origin??"hodnota"} musí mít ${i}${n.maximum.toString()} ${s.unit??"prvků"}`;return`Hodnota je příliš velká: ${n.origin??"hodnota"} musí být ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Hodnota je příliš malá: ${n.origin??"hodnota"} musí mít ${i}${n.minimum.toString()} ${s.unit??"prvků"}`;return`Hodnota je příliš malá: ${n.origin??"hodnota"} musí být ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Neplatný řetězec: musí začínat na "${i.prefix}"`;if(i.format==="ends_with")return`Neplatný řetězec: musí končit na "${i.suffix}"`;if(i.format==="includes")return`Neplatný řetězec: musí obsahovat "${i.includes}"`;if(i.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${i.pattern}`;return`Neplatný formát ${r[i.format]??n.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${n.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${M(n.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${n.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${n.origin}`;default:return"Neplatný vstup"}}};function CI(){return{localeError:Hre()}}var Gre=()=>{let e={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function t(n){return e[n]??null}let r={regex:"input",email:"e-mailadresse",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 dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},o={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Ugyldigt input: forventede instanceof ${n.expected}, fik ${a}`;return`Ugyldigt input: forventede ${i}, fik ${a}`}case"invalid_value":if(n.values.length===1)return`Ugyldig værdi: forventede ${Q(n.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin),a=o[n.origin]??n.origin;if(s)return`For stor: forventede ${a??"value"} ${s.verb} ${i} ${n.maximum.toString()} ${s.unit??"elementer"}`;return`For stor: forventede ${a??"value"} havde ${i} ${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin),a=o[n.origin]??n.origin;if(s)return`For lille: forventede ${a} ${s.verb} ${i} ${n.minimum.toString()} ${s.unit}`;return`For lille: forventede ${a} havde ${i} ${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Ugyldig streng: skal starte med "${i.prefix}"`;if(i.format==="ends_with")return`Ugyldig streng: skal ende med "${i.suffix}"`;if(i.format==="includes")return`Ugyldig streng: skal indeholde "${i.includes}"`;if(i.format==="regex")return`Ugyldig streng: skal matche mønsteret ${i.pattern}`;return`Ugyldig ${r[i.format]??n.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${n.divisor}`;case"unrecognized_keys":return`${n.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${M(n.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${n.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${n.origin}`;default:return"Ugyldigt input"}}};function zI(){return{localeError:Gre()}}var Vre=()=>{let e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(n){return e[n]??null}let r={regex:"Eingabe",email:"E-Mail-Adresse",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-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},o={nan:"NaN",number:"Zahl",array:"Array"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Ungültige Eingabe: erwartet instanceof ${n.expected}, erhalten ${a}`;return`Ungültige Eingabe: erwartet ${i}, erhalten ${a}`}case"invalid_value":if(n.values.length===1)return`Ungültige Eingabe: erwartet ${Q(n.values[0])}`;return`Ungültige Option: erwartet eine von ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Zu groß: erwartet, dass ${n.origin??"Wert"} ${i}${n.maximum.toString()} ${s.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${n.origin??"Wert"} ${i}${n.maximum.toString()} ist`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Zu klein: erwartet, dass ${n.origin} ${i}${n.minimum.toString()} ${s.unit} hat`;return`Zu klein: erwartet, dass ${n.origin} ${i}${n.minimum.toString()} ist`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Ungültiger String: muss mit "${i.prefix}" beginnen`;if(i.format==="ends_with")return`Ungültiger String: muss mit "${i.suffix}" enden`;if(i.format==="includes")return`Ungültiger String: muss "${i.includes}" enthalten`;if(i.format==="regex")return`Ungültiger String: muss dem Muster ${i.pattern} entsprechen`;return`Ungültig: ${r[i.format]??n.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${n.divisor} sein`;case"unrecognized_keys":return`${n.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${M(n.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${n.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${n.origin}`;default:return"Ungültige Eingabe"}}};function NI(){return{localeError:Vre()}}var Zre=()=>{let e={string:{unit:"χαρακτήρες",verb:"να έχει"},file:{unit:"bytes",verb:"να έχει"},array:{unit:"στοιχεία",verb:"να έχει"},set:{unit:"στοιχεία",verb:"να έχει"},map:{unit:"καταχωρήσεις",verb:"να έχει"}};function t(n){return e[n]??null}let r={regex:"είσοδος",email:"διεύθυνση email",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 ημερομηνία και ώρα",date:"ISO ημερομηνία",time:"ISO ώρα",duration:"ISO διάρκεια",ipv4:"διεύθυνση IPv4",ipv6:"διεύθυνση IPv6",mac:"διεύθυνση MAC",cidrv4:"εύρος IPv4",cidrv6:"εύρος IPv6",base64:"συμβολοσειρά κωδικοποιημένη σε base64",base64url:"συμβολοσειρά κωδικοποιημένη σε base64url",json_string:"συμβολοσειρά JSON",e164:"αριθμός E.164",jwt:"JWT",template_literal:"είσοδος"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(typeof n.expected==="string"&&/^[A-Z]/.test(n.expected))return`Μη έγκυρη είσοδος: αναμενόταν instanceof ${n.expected}, λήφθηκε ${a}`;return`Μη έγκυρη είσοδος: αναμενόταν ${i}, λήφθηκε ${a}`}case"invalid_value":if(n.values.length===1)return`Μη έγκυρη είσοδος: αναμενόταν ${Q(n.values[0])}`;return`Μη έγκυρη επιλογή: αναμενόταν ένα από ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Πολύ μεγάλο: αναμενόταν ${n.origin??"τιμή"} να έχει ${i}${n.maximum.toString()} ${s.unit??"στοιχεία"}`;return`Πολύ μεγάλο: αναμενόταν ${n.origin??"τιμή"} να είναι ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Πολύ μικρό: αναμενόταν ${n.origin} να έχει ${i}${n.minimum.toString()} ${s.unit}`;return`Πολύ μικρό: αναμενόταν ${n.origin} να είναι ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Μη έγκυρη συμβολοσειρά: πρέπει να ξεκινά με "${i.prefix}"`;if(i.format==="ends_with")return`Μη έγκυρη συμβολοσειρά: πρέπει να τελειώνει με "${i.suffix}"`;if(i.format==="includes")return`Μη έγκυρη συμβολοσειρά: πρέπει να περιέχει "${i.includes}"`;if(i.format==="regex")return`Μη έγκυρη συμβολοσειρά: πρέπει να ταιριάζει με το μοτίβο ${i.pattern}`;return`Μη έγκυρο: ${r[i.format]??n.format}`}case"not_multiple_of":return`Μη έγκυρος αριθμός: πρέπει να είναι πολλαπλάσιο του ${n.divisor}`;case"unrecognized_keys":return`Άγνωστ${n.keys.length>1?"α":"ο"} κλειδ${n.keys.length>1?"ιά":"ί"}: ${M(n.keys,", ")}`;case"invalid_key":return`Μη έγκυρο κλειδί στο ${n.origin}`;case"invalid_union":return"Μη έγκυρη είσοδος";case"invalid_element":return`Μη έγκυρη τιμή στο ${n.origin}`;default:return"Μη έγκυρη είσοδος"}}};function MI(){return{localeError:Zre()}}var Wre=()=>{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(n){return e[n]??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"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;return`Invalid input: expected ${i}, received ${a}`}case"invalid_value":if(n.values.length===1)return`Invalid input: expected ${Q(n.values[0])}`;return`Invalid option: expected one of ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${s.unit??"elements"}`;return`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${s.unit}`;return`Too small: expected ${n.origin} to be ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;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]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${M(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":if(n.options&&Array.isArray(n.options)&&n.options.length>0)return`Invalid discriminator value. Expected ${n.options.map((s)=>`'${s}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function Mm(){return{localeError:Wre()}}var Kre=()=>{let e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(n){return e[n]??null}let r={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},o={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Nevalida enigo: atendiĝis instanceof ${n.expected}, riceviĝis ${a}`;return`Nevalida enigo: atendiĝis ${i}, riceviĝis ${a}`}case"invalid_value":if(n.values.length===1)return`Nevalida enigo: atendiĝis ${Q(n.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Tro granda: atendiĝis ke ${n.origin??"valoro"} havu ${i}${n.maximum.toString()} ${s.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${n.origin??"valoro"} havu ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Tro malgranda: atendiĝis ke ${n.origin} havu ${i}${n.minimum.toString()} ${s.unit}`;return`Tro malgranda: atendiĝis ke ${n.origin} estu ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${i.prefix}"`;if(i.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${i.suffix}"`;if(i.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${i.includes}"`;if(i.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${i.pattern}`;return`Nevalida ${r[i.format]??n.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${n.divisor}`;case"unrecognized_keys":return`Nekonata${n.keys.length>1?"j":""} ŝlosilo${n.keys.length>1?"j":""}: ${M(n.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${n.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${n.origin}`;default:return"Nevalida enigo"}}};function BI(){return{localeError:Kre()}}var Jre=()=>{let e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function t(n){return e[n]??null}let r={regex:"entrada",email:"dirección de correo electrónico",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:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},o={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Entrada inválida: se esperaba instanceof ${n.expected}, recibido ${a}`;return`Entrada inválida: se esperaba ${i}, recibido ${a}`}case"invalid_value":if(n.values.length===1)return`Entrada inválida: se esperaba ${Q(n.values[0])}`;return`Opción inválida: se esperaba una de ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin),a=o[n.origin]??n.origin;if(s)return`Demasiado grande: se esperaba que ${a??"valor"} tuviera ${i}${n.maximum.toString()} ${s.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${a??"valor"} fuera ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin),a=o[n.origin]??n.origin;if(s)return`Demasiado pequeño: se esperaba que ${a} tuviera ${i}${n.minimum.toString()} ${s.unit}`;return`Demasiado pequeño: se esperaba que ${a} fuera ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Cadena inválida: debe comenzar con "${i.prefix}"`;if(i.format==="ends_with")return`Cadena inválida: debe terminar en "${i.suffix}"`;if(i.format==="includes")return`Cadena inválida: debe incluir "${i.includes}"`;if(i.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${i.pattern}`;return`Inválido ${r[i.format]??n.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${n.divisor}`;case"unrecognized_keys":return`Llave${n.keys.length>1?"s":""} desconocida${n.keys.length>1?"s":""}: ${M(n.keys,", ")}`;case"invalid_key":return`Llave inválida en ${o[n.origin]??n.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${o[n.origin]??n.origin}`;default:return"Entrada inválida"}}};function DI(){return{localeError:Jre()}}var Yre=()=>{let e={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function t(n){return e[n]??null}let r={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"},o={nan:"NaN",number:"عدد",array:"آرایه"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`ورودی نامعتبر: می‌بایست instanceof ${n.expected} می‌بود، ${a} دریافت شد`;return`ورودی نامعتبر: می‌بایست ${i} می‌بود، ${a} دریافت شد`}case"invalid_value":if(n.values.length===1)return`ورودی نامعتبر: می‌بایست ${Q(n.values[0])} می‌بود`;return`گزینه نامعتبر: می‌بایست یکی از ${M(n.values,"|")} می‌بود`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`خیلی بزرگ: ${n.origin??"مقدار"} باید ${i}${n.maximum.toString()} ${s.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${n.origin??"مقدار"} باید ${i}${n.maximum.toString()} باشد`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`خیلی کوچک: ${n.origin} باید ${i}${n.minimum.toString()} ${s.unit} باشد`;return`خیلی کوچک: ${n.origin} باید ${i}${n.minimum.toString()} باشد`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`رشته نامعتبر: باید با "${i.prefix}" شروع شود`;if(i.format==="ends_with")return`رشته نامعتبر: باید با "${i.suffix}" تمام شود`;if(i.format==="includes")return`رشته نامعتبر: باید شامل "${i.includes}" باشد`;if(i.format==="regex")return`رشته نامعتبر: باید با الگوی ${i.pattern} مطابقت داشته باشد`;return`${r[i.format]??n.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${n.divisor} باشد`;case"unrecognized_keys":return`کلید${n.keys.length>1?"های":""} ناشناس: ${M(n.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${n.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${n.origin}`;default:return"ورودی نامعتبر"}}};function UI(){return{localeError:Yre()}}var Qre=()=>{let e={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function t(n){return e[n]??null}let r={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Virheellinen tyyppi: odotettiin instanceof ${n.expected}, oli ${a}`;return`Virheellinen tyyppi: odotettiin ${i}, oli ${a}`}case"invalid_value":if(n.values.length===1)return`Virheellinen syöte: täytyy olla ${Q(n.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Liian suuri: ${s.subject} täytyy olla ${i}${n.maximum.toString()} ${s.unit}`.trim();return`Liian suuri: arvon täytyy olla ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Liian pieni: ${s.subject} täytyy olla ${i}${n.minimum.toString()} ${s.unit}`.trim();return`Liian pieni: arvon täytyy olla ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${i.prefix}"`;if(i.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${i.suffix}"`;if(i.format==="includes")return`Virheellinen syöte: täytyy sisältää "${i.includes}"`;if(i.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${i.pattern}`;return`Virheellinen ${r[i.format]??n.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${n.divisor} monikerta`;case"unrecognized_keys":return`${n.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${M(n.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function LI(){return{localeError:Qre()}}var Xre=()=>{let e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(n){return e[n]??null}let r={regex:"entrée",email:"adresse e-mail",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:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},o={string:"chaîne",number:"nombre",int:"entier",boolean:"booléen",bigint:"grand entier",symbol:"symbole",undefined:"indéfini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Entrée invalide : instanceof ${n.expected} attendu, ${a} reçu`;return`Entrée invalide : ${i} attendu, ${a} reçu`}case"invalid_value":if(n.values.length===1)return`Entrée invalide : ${Q(n.values[0])} attendu`;return`Option invalide : une valeur parmi ${M(n.values,"|")} attendue`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Trop grand : ${o[n.origin]??"valeur"} doit ${s.verb} ${i}${n.maximum.toString()} ${s.unit??"élément(s)"}`;return`Trop grand : ${o[n.origin]??"valeur"} doit être ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Trop petit : ${o[n.origin]??"valeur"} doit ${s.verb} ${i}${n.minimum.toString()} ${s.unit}`;return`Trop petit : ${o[n.origin]??"valeur"} doit être ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Chaîne invalide : doit commencer par "${i.prefix}"`;if(i.format==="ends_with")return`Chaîne invalide : doit se terminer par "${i.suffix}"`;if(i.format==="includes")return`Chaîne invalide : doit inclure "${i.includes}"`;if(i.format==="regex")return`Chaîne invalide : doit correspondre au modèle ${i.pattern}`;return`${r[i.format]??n.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${n.divisor}`;case"unrecognized_keys":return`Clé${n.keys.length>1?"s":""} non reconnue${n.keys.length>1?"s":""} : ${M(n.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${n.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${n.origin}`;default:return"Entrée invalide"}}};function jI(){return{localeError:Xre()}}var ene=()=>{let e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(n){return e[n]??null}let r={regex:"entrée",email:"adresse courriel",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:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Entrée invalide : attendu instanceof ${n.expected}, reçu ${a}`;return`Entrée invalide : attendu ${i}, reçu ${a}`}case"invalid_value":if(n.values.length===1)return`Entrée invalide : attendu ${Q(n.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"≤":"<",s=t(n.origin);if(s)return`Trop grand : attendu que ${n.origin??"la valeur"} ait ${i}${n.maximum.toString()} ${s.unit}`;return`Trop grand : attendu que ${n.origin??"la valeur"} soit ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?"≥":">",s=t(n.origin);if(s)return`Trop petit : attendu que ${n.origin} ait ${i}${n.minimum.toString()} ${s.unit}`;return`Trop petit : attendu que ${n.origin} soit ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Chaîne invalide : doit commencer par "${i.prefix}"`;if(i.format==="ends_with")return`Chaîne invalide : doit se terminer par "${i.suffix}"`;if(i.format==="includes")return`Chaîne invalide : doit inclure "${i.includes}"`;if(i.format==="regex")return`Chaîne invalide : doit correspondre au motif ${i.pattern}`;return`${r[i.format]??n.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${n.divisor}`;case"unrecognized_keys":return`Clé${n.keys.length>1?"s":""} non reconnue${n.keys.length>1?"s":""} : ${M(n.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${n.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${n.origin}`;default:return"Entrée invalide"}}};function FI(){return{localeError:ene()}}var tne=()=>{let e={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},t={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},r=(u)=>u?e[u]:void 0,o=(u)=>{let d=r(u);if(d)return d.label;return u??e.unknown.label},n=(u)=>`ה${o(u)}`,i=(u)=>(r(u)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות",s=(u)=>{if(!u)return null;return t[u]??null},a={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},c={nan:"NaN"};return(u)=>{switch(u.code){case"invalid_type":{let d=u.expected,p=c[d??""]??o(d),m=ee(u.input),h=c[m]??e[m]?.label??m;if(/^[A-Z]/.test(u.expected))return`קלט לא תקין: צריך להיות instanceof ${u.expected}, התקבל ${h}`;return`קלט לא תקין: צריך להיות ${p}, התקבל ${h}`}case"invalid_value":{if(u.values.length===1)return`ערך לא תקין: הערך חייב להיות ${Q(u.values[0])}`;let d=u.values.map((h)=>Q(h));if(u.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${d[0]} או ${d[1]}`;let p=d[d.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${d.slice(0,-1).join(", ")} או ${p}`}case"too_big":{let d=s(u.origin),p=n(u.origin??"value");if(u.origin==="string")return`${d?.longLabel??"ארוך"} מדי: ${p} צריכה להכיל ${u.maximum.toString()} ${d?.unit??""} ${u.inclusive?"או פחות":"לכל היותר"}`.trim();if(u.origin==="number"){let y=u.inclusive?`קטן או שווה ל-${u.maximum}`:`קטן מ-${u.maximum}`;return`גדול מדי: ${p} צריך להיות ${y}`}if(u.origin==="array"||u.origin==="set"){let y=u.origin==="set"?"צריכה":"צריך",x=u.inclusive?`${u.maximum} ${d?.unit??""} או פחות`:`פחות מ-${u.maximum} ${d?.unit??""}`;return`גדול מדי: ${p} ${y} להכיל ${x}`.trim()}let m=u.inclusive?"<=":"<",h=i(u.origin??"value");if(d?.unit)return`${d.longLabel} מדי: ${p} ${h} ${m}${u.maximum.toString()} ${d.unit}`;return`${d?.longLabel??"גדול"} מדי: ${p} ${h} ${m}${u.maximum.toString()}`}case"too_small":{let d=s(u.origin),p=n(u.origin??"value");if(u.origin==="string")return`${d?.shortLabel??"קצר"} מדי: ${p} צריכה להכיל ${u.minimum.toString()} ${d?.unit??""} ${u.inclusive?"או יותר":"לפחות"}`.trim();if(u.origin==="number"){let y=u.inclusive?`גדול או שווה ל-${u.minimum}`:`גדול מ-${u.minimum}`;return`קטן מדי: ${p} צריך להיות ${y}`}if(u.origin==="array"||u.origin==="set"){let y=u.origin==="set"?"צריכה":"צריך";if(u.minimum===1&&u.inclusive){let S=u.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${p} ${y} להכיל ${S}`}let x=u.inclusive?`${u.minimum} ${d?.unit??""} או יותר`:`יותר מ-${u.minimum} ${d?.unit??""}`;return`קטן מדי: ${p} ${y} להכיל ${x}`.trim()}let m=u.inclusive?">=":">",h=i(u.origin??"value");if(d?.unit)return`${d.shortLabel} מדי: ${p} ${h} ${m}${u.minimum.toString()} ${d.unit}`;return`${d?.shortLabel??"קטן"} מדי: ${p} ${h} ${m}${u.minimum.toString()}`}case"invalid_format":{let d=u;if(d.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${d.prefix}"`;if(d.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${d.suffix}"`;if(d.format==="includes")return`המחרוזת חייבת לכלול "${d.includes}"`;if(d.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${d.pattern}`;let p=a[d.format],m=p?.label??d.format,y=(p?.gender??"m")==="f"?"תקינה":"תקין";return`${m} לא ${y}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${u.divisor}`;case"unrecognized_keys":return`מפתח${u.keys.length>1?"ות":""} לא מזוה${u.keys.length>1?"ים":"ה"}: ${M(u.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${n(u.origin??"array")}`;default:return"קלט לא תקין"}}};function qI(){return{localeError:tne()}}var rne=()=>{let e={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function t(n){return e[n]??null}let r={regex:"unos",email:"email adresa",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 datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},o={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Neispravan unos: očekuje se instanceof ${n.expected}, a primljeno je ${a}`;return`Neispravan unos: očekuje se ${i}, a primljeno je ${a}`}case"invalid_value":if(n.values.length===1)return`Neispravna vrijednost: očekivano ${Q(n.values[0])}`;return`Neispravna opcija: očekivano jedno od ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin),a=o[n.origin]??n.origin;if(s)return`Preveliko: očekivano da ${a??"vrijednost"} ima ${i}${n.maximum.toString()} ${s.unit??"elemenata"}`;return`Preveliko: očekivano da ${a??"vrijednost"} bude ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin),a=o[n.origin]??n.origin;if(s)return`Premalo: očekivano da ${a} ima ${i}${n.minimum.toString()} ${s.unit}`;return`Premalo: očekivano da ${a} bude ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Neispravan tekst: mora započinjati s "${i.prefix}"`;if(i.format==="ends_with")return`Neispravan tekst: mora završavati s "${i.suffix}"`;if(i.format==="includes")return`Neispravan tekst: mora sadržavati "${i.includes}"`;if(i.format==="regex")return`Neispravan tekst: mora odgovarati uzorku ${i.pattern}`;return`Neispravna ${r[i.format]??n.format}`}case"not_multiple_of":return`Neispravan broj: mora biti višekratnik od ${n.divisor}`;case"unrecognized_keys":return`Neprepoznat${n.keys.length>1?"i ključevi":" ključ"}: ${M(n.keys,", ")}`;case"invalid_key":return`Neispravan ključ u ${o[n.origin]??n.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${o[n.origin]??n.origin}`;default:return"Neispravan unos"}}};function HI(){return{localeError:rne()}}var nne=()=>{let e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(n){return e[n]??null}let r={regex:"bemenet",email:"email cím",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 időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"},o={nan:"NaN",number:"szám",array:"tömb"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Érvénytelen bemenet: a várt érték instanceof ${n.expected}, a kapott érték ${a}`;return`Érvénytelen bemenet: a várt érték ${i}, a kapott érték ${a}`}case"invalid_value":if(n.values.length===1)return`Érvénytelen bemenet: a várt érték ${Q(n.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Túl nagy: ${n.origin??"érték"} mérete túl nagy ${i}${n.maximum.toString()} ${s.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${n.origin??"érték"} túl nagy: ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Túl kicsi: a bemeneti érték ${n.origin} mérete túl kicsi ${i}${n.minimum.toString()} ${s.unit}`;return`Túl kicsi: a bemeneti érték ${n.origin} túl kicsi ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Érvénytelen string: "${i.prefix}" értékkel kell kezdődnie`;if(i.format==="ends_with")return`Érvénytelen string: "${i.suffix}" értékkel kell végződnie`;if(i.format==="includes")return`Érvénytelen string: "${i.includes}" értéket kell tartalmaznia`;if(i.format==="regex")return`Érvénytelen string: ${i.pattern} mintának kell megfelelnie`;return`Érvénytelen ${r[i.format]??n.format}`}case"not_multiple_of":return`Érvénytelen szám: ${n.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${n.keys.length>1?"s":""}: ${M(n.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${n.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${n.origin}`;default:return"Érvénytelen bemenet"}}};function GI(){return{localeError:nne()}}function I4(e,t,r){return Math.abs(e)===1?t:r}function Zl(e){if(!e)return"";let t=["ա","ե","ը","ի","ո","ու","օ"],r=e[e.length-1];return e+(t.includes(r)?"ն":"ը")}var one=()=>{let e={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function t(n){return e[n]??null}let r={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",jwt:"JWT",template_literal:"մուտք"},o={nan:"NaN",number:"թիվ",array:"զանգված"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${n.expected}, ստացվել է ${a}`;return`Սխալ մուտքագրում․ սպասվում էր ${i}, ստացվել է ${a}`}case"invalid_value":if(n.values.length===1)return`Սխալ մուտքագրում․ սպասվում էր ${Q(n.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s){let a=Number(n.maximum),c=I4(a,s.unit.one,s.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${Zl(n.origin??"արժեք")} կունենա ${i}${n.maximum.toString()} ${c}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${Zl(n.origin??"արժեք")} լինի ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s){let a=Number(n.minimum),c=I4(a,s.unit.one,s.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${Zl(n.origin)} կունենա ${i}${n.minimum.toString()} ${c}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${Zl(n.origin)} լինի ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Սխալ տող․ պետք է սկսվի "${i.prefix}"-ով`;if(i.format==="ends_with")return`Սխալ տող․ պետք է ավարտվի "${i.suffix}"-ով`;if(i.format==="includes")return`Սխալ տող․ պետք է պարունակի "${i.includes}"`;if(i.format==="regex")return`Սխալ տող․ պետք է համապատասխանի ${i.pattern} ձևաչափին`;return`Սխալ ${r[i.format]??n.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${n.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${n.keys.length>1?"ներ":""}. ${M(n.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${Zl(n.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${Zl(n.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};function VI(){return{localeError:one()}}var ine=()=>{let e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(n){return e[n]??null}let r={regex:"input",email:"alamat email",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:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Input tidak valid: diharapkan instanceof ${n.expected}, diterima ${a}`;return`Input tidak valid: diharapkan ${i}, diterima ${a}`}case"invalid_value":if(n.values.length===1)return`Input tidak valid: diharapkan ${Q(n.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Terlalu besar: diharapkan ${n.origin??"value"} memiliki ${i}${n.maximum.toString()} ${s.unit??"elemen"}`;return`Terlalu besar: diharapkan ${n.origin??"value"} menjadi ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Terlalu kecil: diharapkan ${n.origin} memiliki ${i}${n.minimum.toString()} ${s.unit}`;return`Terlalu kecil: diharapkan ${n.origin} menjadi ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`String tidak valid: harus dimulai dengan "${i.prefix}"`;if(i.format==="ends_with")return`String tidak valid: harus berakhir dengan "${i.suffix}"`;if(i.format==="includes")return`String tidak valid: harus menyertakan "${i.includes}"`;if(i.format==="regex")return`String tidak valid: harus sesuai pola ${i.pattern}`;return`${r[i.format]??n.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${n.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${n.keys.length>1?"s":""}: ${M(n.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${n.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${n.origin}`;default:return"Input tidak valid"}}};function ZI(){return{localeError:ine()}}var sne=()=>{let e={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function t(n){return e[n]??null}let r={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"},o={nan:"NaN",number:"númer",array:"fylki"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Rangt gildi: Þú slóst inn ${a} þar sem á að vera instanceof ${n.expected}`;return`Rangt gildi: Þú slóst inn ${a} þar sem á að vera ${i}`}case"invalid_value":if(n.values.length===1)return`Rangt gildi: gert ráð fyrir ${Q(n.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Of stórt: gert er ráð fyrir að ${n.origin??"gildi"} hafi ${i}${n.maximum.toString()} ${s.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${n.origin??"gildi"} sé ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Of lítið: gert er ráð fyrir að ${n.origin} hafi ${i}${n.minimum.toString()} ${s.unit}`;return`Of lítið: gert er ráð fyrir að ${n.origin} sé ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Ógildur strengur: verður að byrja á "${i.prefix}"`;if(i.format==="ends_with")return`Ógildur strengur: verður að enda á "${i.suffix}"`;if(i.format==="includes")return`Ógildur strengur: verður að innihalda "${i.includes}"`;if(i.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${i.pattern}`;return`Rangt ${r[i.format]??n.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${n.divisor}`;case"unrecognized_keys":return`Óþekkt ${n.keys.length>1?"ir lyklar":"ur lykill"}: ${M(n.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${n.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${n.origin}`;default:return"Rangt gildi"}}};function WI(){return{localeError:sne()}}var ane=()=>{let e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(n){return e[n]??null}let r={regex:"input",email:"indirizzo email",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:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},o={nan:"NaN",number:"numero",array:"vettore"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Input non valido: atteso instanceof ${n.expected}, ricevuto ${a}`;return`Input non valido: atteso ${i}, ricevuto ${a}`}case"invalid_value":if(n.values.length===1)return`Input non valido: atteso ${Q(n.values[0])}`;return`Opzione non valida: atteso uno tra ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Troppo grande: ${n.origin??"valore"} deve avere ${i}${n.maximum.toString()} ${s.unit??"elementi"}`;return`Troppo grande: ${n.origin??"valore"} deve essere ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Troppo piccolo: ${n.origin} deve avere ${i}${n.minimum.toString()} ${s.unit}`;return`Troppo piccolo: ${n.origin} deve essere ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Stringa non valida: deve iniziare con "${i.prefix}"`;if(i.format==="ends_with")return`Stringa non valida: deve terminare con "${i.suffix}"`;if(i.format==="includes")return`Stringa non valida: deve includere "${i.includes}"`;if(i.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${i.pattern}`;return`Input non valido: ${r[i.format]??n.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${n.divisor}`;case"unrecognized_keys":return`Chiav${n.keys.length>1?"i":"e"} non riconosciut${n.keys.length>1?"e":"a"}: ${M(n.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${n.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${n.origin}`;default:return"Input non valido"}}};function KI(){return{localeError:ane()}}var cne=()=>{let e={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function t(n){return e[n]??null}let r={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"},o={nan:"NaN",number:"数値",array:"配列"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`無効な入力: instanceof ${n.expected}が期待されましたが、${a}が入力されました`;return`無効な入力: ${i}が期待されましたが、${a}が入力されました`}case"invalid_value":if(n.values.length===1)return`無効な入力: ${Q(n.values[0])}が期待されました`;return`無効な選択: ${M(n.values,"、")}のいずれかである必要があります`;case"too_big":{let i=n.inclusive?"以下である":"より小さい",s=t(n.origin);if(s)return`大きすぎる値: ${n.origin??"値"}は${n.maximum.toString()}${s.unit??"要素"}${i}必要があります`;return`大きすぎる値: ${n.origin??"値"}は${n.maximum.toString()}${i}必要があります`}case"too_small":{let i=n.inclusive?"以上である":"より大きい",s=t(n.origin);if(s)return`小さすぎる値: ${n.origin}は${n.minimum.toString()}${s.unit}${i}必要があります`;return`小さすぎる値: ${n.origin}は${n.minimum.toString()}${i}必要があります`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`無効な文字列: "${i.prefix}"で始まる必要があります`;if(i.format==="ends_with")return`無効な文字列: "${i.suffix}"で終わる必要があります`;if(i.format==="includes")return`無効な文字列: "${i.includes}"を含む必要があります`;if(i.format==="regex")return`無効な文字列: パターン${i.pattern}に一致する必要があります`;return`無効な${r[i.format]??n.format}`}case"not_multiple_of":return`無効な数値: ${n.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${n.keys.length>1?"群":""}: ${M(n.keys,"、")}`;case"invalid_key":return`${n.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${n.origin}内の無効な値`;default:return"無効な入力"}}};function JI(){return{localeError:cne()}}var une=()=>{let e={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function t(n){return e[n]??null}let r={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული ველი",base64url:"base64url-კოდირებული ველი",json_string:"JSON ველი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"},o={nan:"NaN",number:"რიცხვი",string:"ველი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${n.expected}, მიღებული ${a}`;return`არასწორი შეყვანა: მოსალოდნელი ${i}, მიღებული ${a}`}case"invalid_value":if(n.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${Q(n.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${M(n.values,"|")}-დან`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`ზედმეტად დიდი: მოსალოდნელი ${n.origin??"მნიშვნელობა"} ${s.verb} ${i}${n.maximum.toString()} ${s.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${n.origin??"მნიშვნელობა"} იყოს ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`ზედმეტად პატარა: მოსალოდნელი ${n.origin} ${s.verb} ${i}${n.minimum.toString()} ${s.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${n.origin} იყოს ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`არასწორი ველი: უნდა იწყებოდეს "${i.prefix}"-ით`;if(i.format==="ends_with")return`არასწორი ველი: უნდა მთავრდებოდეს "${i.suffix}"-ით`;if(i.format==="includes")return`არასწორი ველი: უნდა შეიცავდეს "${i.includes}"-ს`;if(i.format==="regex")return`არასწორი ველი: უნდა შეესაბამებოდეს შაბლონს ${i.pattern}`;return`არასწორი ${r[i.format]??n.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${n.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${n.keys.length>1?"ები":"ი"}: ${M(n.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${n.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${n.origin}-ში`;default:return"არასწორი შეყვანა"}}};function YI(){return{localeError:une()}}var lne=()=>{let e={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function t(n){return e[n]??null}let r={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},o={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${n.expected} ប៉ុន្តែទទួលបាន ${a}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${i} ប៉ុន្តែទទួលបាន ${a}`}case"invalid_value":if(n.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${Q(n.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`ធំពេក៖ ត្រូវការ ${n.origin??"តម្លៃ"} ${i} ${n.maximum.toString()} ${s.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${n.origin??"តម្លៃ"} ${i} ${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`តូចពេក៖ ត្រូវការ ${n.origin} ${i} ${n.minimum.toString()} ${s.unit}`;return`តូចពេក៖ ត្រូវការ ${n.origin} ${i} ${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${i.prefix}"`;if(i.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${i.suffix}"`;if(i.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${i.includes}"`;if(i.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${i.pattern}`;return`មិនត្រឹមត្រូវ៖ ${r[i.format]??n.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${n.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${M(n.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${n.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${n.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function Bm(){return{localeError:lne()}}function QI(){return Bm()}var dne=()=>{let e={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`잘못된 입력: 예상 타입은 instanceof ${n.expected}, 받은 타입은 ${a}입니다`;return`잘못된 입력: 예상 타입은 ${i}, 받은 타입은 ${a}입니다`}case"invalid_value":if(n.values.length===1)return`잘못된 입력: 값은 ${Q(n.values[0])} 이어야 합니다`;return`잘못된 옵션: ${M(n.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let i=n.inclusive?"이하":"미만",s=i==="미만"?"이어야 합니다":"여야 합니다",a=t(n.origin),c=a?.unit??"요소";if(a)return`${n.origin??"값"}이 너무 큽니다: ${n.maximum.toString()}${c} ${i}${s}`;return`${n.origin??"값"}이 너무 큽니다: ${n.maximum.toString()} ${i}${s}`}case"too_small":{let i=n.inclusive?"이상":"초과",s=i==="이상"?"이어야 합니다":"여야 합니다",a=t(n.origin),c=a?.unit??"요소";if(a)return`${n.origin??"값"}이 너무 작습니다: ${n.minimum.toString()}${c} ${i}${s}`;return`${n.origin??"값"}이 너무 작습니다: ${n.minimum.toString()} ${i}${s}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`잘못된 문자열: "${i.prefix}"(으)로 시작해야 합니다`;if(i.format==="ends_with")return`잘못된 문자열: "${i.suffix}"(으)로 끝나야 합니다`;if(i.format==="includes")return`잘못된 문자열: "${i.includes}"을(를) 포함해야 합니다`;if(i.format==="regex")return`잘못된 문자열: 정규식 ${i.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${r[i.format]??n.format}`}case"not_multiple_of":return`잘못된 숫자: ${n.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${M(n.keys,", ")}`;case"invalid_key":return`잘못된 키: ${n.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${n.origin}`;default:return"잘못된 입력"}}};function XI(){return{localeError:dne()}}var Dm=(e)=>e.charAt(0).toUpperCase()+e.slice(1);function P4(e){let t=Math.abs(e),r=t%10,o=t%100;if(o>=11&&o<=19||r===0)return"many";if(r===1)return"one";return"few"}var pne=()=>{let e={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function t(n,i,s,a){let c=e[n]??null;if(c===null)return c;return{unit:c.unit[i],verb:c.verb[a][s?"inclusive":"notInclusive"]}}let r={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"},o={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Gautas tipas ${a}, o tikėtasi - instanceof ${n.expected}`;return`Gautas tipas ${a}, o tikėtasi - ${i}`}case"invalid_value":if(n.values.length===1)return`Privalo būti ${Q(n.values[0])}`;return`Privalo būti vienas iš ${M(n.values,"|")} pasirinkimų`;case"too_big":{let i=o[n.origin]??n.origin,s=t(n.origin,P4(Number(n.maximum)),n.inclusive??!1,"smaller");if(s?.verb)return`${Dm(i??n.origin??"reikšmė")} ${s.verb} ${n.maximum.toString()} ${s.unit??"elementų"}`;let a=n.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${Dm(i??n.origin??"reikšmė")} turi būti ${a} ${n.maximum.toString()} ${s?.unit}`}case"too_small":{let i=o[n.origin]??n.origin,s=t(n.origin,P4(Number(n.minimum)),n.inclusive??!1,"bigger");if(s?.verb)return`${Dm(i??n.origin??"reikšmė")} ${s.verb} ${n.minimum.toString()} ${s.unit??"elementų"}`;let a=n.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${Dm(i??n.origin??"reikšmė")} turi būti ${a} ${n.minimum.toString()} ${s?.unit}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Eilutė privalo prasidėti "${i.prefix}"`;if(i.format==="ends_with")return`Eilutė privalo pasibaigti "${i.suffix}"`;if(i.format==="includes")return`Eilutė privalo įtraukti "${i.includes}"`;if(i.format==="regex")return`Eilutė privalo atitikti ${i.pattern}`;return`Neteisingas ${r[i.format]??n.format}`}case"not_multiple_of":return`Skaičius privalo būti ${n.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${n.keys.length>1?"i":"as"} rakt${n.keys.length>1?"ai":"as"}: ${M(n.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let i=o[n.origin]??n.origin;return`${Dm(i??n.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function eP(){return{localeError:pne()}}var fne=()=>{let e={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function t(n){return e[n]??null}let r={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"},o={nan:"NaN",number:"број",array:"низа"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Грешен внес: се очекува instanceof ${n.expected}, примено ${a}`;return`Грешен внес: се очекува ${i}, примено ${a}`}case"invalid_value":if(n.values.length===1)return`Invalid input: expected ${Q(n.values[0])}`;return`Грешана опција: се очекува една ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Премногу голем: се очекува ${n.origin??"вредноста"} да има ${i}${n.maximum.toString()} ${s.unit??"елементи"}`;return`Премногу голем: се очекува ${n.origin??"вредноста"} да биде ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Премногу мал: се очекува ${n.origin} да има ${i}${n.minimum.toString()} ${s.unit}`;return`Премногу мал: се очекува ${n.origin} да биде ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Неважечка низа: мора да започнува со "${i.prefix}"`;if(i.format==="ends_with")return`Неважечка низа: мора да завршува со "${i.suffix}"`;if(i.format==="includes")return`Неважечка низа: мора да вклучува "${i.includes}"`;if(i.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${i.pattern}`;return`Invalid ${r[i.format]??n.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${n.divisor}`;case"unrecognized_keys":return`${n.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${M(n.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${n.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${n.origin}`;default:return"Грешен внес"}}};function tP(){return{localeError:fne()}}var mne=()=>{let e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(n){return e[n]??null}let r={regex:"input",email:"alamat e-mel",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:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},o={nan:"NaN",number:"nombor"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Input tidak sah: dijangka instanceof ${n.expected}, diterima ${a}`;return`Input tidak sah: dijangka ${i}, diterima ${a}`}case"invalid_value":if(n.values.length===1)return`Input tidak sah: dijangka ${Q(n.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Terlalu besar: dijangka ${n.origin??"nilai"} ${s.verb} ${i}${n.maximum.toString()} ${s.unit??"elemen"}`;return`Terlalu besar: dijangka ${n.origin??"nilai"} adalah ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Terlalu kecil: dijangka ${n.origin} ${s.verb} ${i}${n.minimum.toString()} ${s.unit}`;return`Terlalu kecil: dijangka ${n.origin} adalah ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`String tidak sah: mesti bermula dengan "${i.prefix}"`;if(i.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${i.suffix}"`;if(i.format==="includes")return`String tidak sah: mesti mengandungi "${i.includes}"`;if(i.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${i.pattern}`;return`${r[i.format]??n.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${n.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${M(n.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${n.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${n.origin}`;default:return"Input tidak sah"}}};function rP(){return{localeError:mne()}}var hne=()=>{let e={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function t(n){return e[n]??null}let r={regex:"invoer",email:"emailadres",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 datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},o={nan:"NaN",number:"getal"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Ongeldige invoer: verwacht instanceof ${n.expected}, ontving ${a}`;return`Ongeldige invoer: verwacht ${i}, ontving ${a}`}case"invalid_value":if(n.values.length===1)return`Ongeldige invoer: verwacht ${Q(n.values[0])}`;return`Ongeldige optie: verwacht één van ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin),a=n.origin==="date"?"laat":n.origin==="string"?"lang":"groot";if(s)return`Te ${a}: verwacht dat ${n.origin??"waarde"} ${i}${n.maximum.toString()} ${s.unit??"elementen"} ${s.verb}`;return`Te ${a}: verwacht dat ${n.origin??"waarde"} ${i}${n.maximum.toString()} is`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin),a=n.origin==="date"?"vroeg":n.origin==="string"?"kort":"klein";if(s)return`Te ${a}: verwacht dat ${n.origin} ${i}${n.minimum.toString()} ${s.unit} ${s.verb}`;return`Te ${a}: verwacht dat ${n.origin} ${i}${n.minimum.toString()} is`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Ongeldige tekst: moet met "${i.prefix}" beginnen`;if(i.format==="ends_with")return`Ongeldige tekst: moet op "${i.suffix}" eindigen`;if(i.format==="includes")return`Ongeldige tekst: moet "${i.includes}" bevatten`;if(i.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${i.pattern}`;return`Ongeldig: ${r[i.format]??n.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${n.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${n.keys.length>1?"s":""}: ${M(n.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${n.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${n.origin}`;default:return"Ongeldige invoer"}}};function nP(){return{localeError:hne()}}var gne=()=>{let e={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function t(n){return e[n]??null}let r={regex:"input",email:"e-postadresse",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 dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},o={nan:"NaN",number:"tall",array:"liste"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Ugyldig input: forventet instanceof ${n.expected}, fikk ${a}`;return`Ugyldig input: forventet ${i}, fikk ${a}`}case"invalid_value":if(n.values.length===1)return`Ugyldig verdi: forventet ${Q(n.values[0])}`;return`Ugyldig valg: forventet en av ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`For stor(t): forventet ${n.origin??"value"} til å ha ${i}${n.maximum.toString()} ${s.unit??"elementer"}`;return`For stor(t): forventet ${n.origin??"value"} til å ha ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`For lite(n): forventet ${n.origin} til å ha ${i}${n.minimum.toString()} ${s.unit}`;return`For lite(n): forventet ${n.origin} til å ha ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Ugyldig streng: må starte med "${i.prefix}"`;if(i.format==="ends_with")return`Ugyldig streng: må ende med "${i.suffix}"`;if(i.format==="includes")return`Ugyldig streng: må inneholde "${i.includes}"`;if(i.format==="regex")return`Ugyldig streng: må matche mønsteret ${i.pattern}`;return`Ugyldig ${r[i.format]??n.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${n.divisor}`;case"unrecognized_keys":return`${n.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${M(n.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${n.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${n.origin}`;default:return"Ugyldig input"}}};function oP(){return{localeError:gne()}}var yne=()=>{let e={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function t(n){return e[n]??null}let r={regex:"giren",email:"epostagâh",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 hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"},o={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Fâsit giren: umulan instanceof ${n.expected}, alınan ${a}`;return`Fâsit giren: umulan ${i}, alınan ${a}`}case"invalid_value":if(n.values.length===1)return`Fâsit giren: umulan ${Q(n.values[0])}`;return`Fâsit tercih: mûteberler ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Fazla büyük: ${n.origin??"value"}, ${i}${n.maximum.toString()} ${s.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${n.origin??"value"}, ${i}${n.maximum.toString()} olmalıydı.`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Fazla küçük: ${n.origin}, ${i}${n.minimum.toString()} ${s.unit} sahip olmalıydı.`;return`Fazla küçük: ${n.origin}, ${i}${n.minimum.toString()} olmalıydı.`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Fâsit metin: "${i.prefix}" ile başlamalı.`;if(i.format==="ends_with")return`Fâsit metin: "${i.suffix}" ile bitmeli.`;if(i.format==="includes")return`Fâsit metin: "${i.includes}" ihtivâ etmeli.`;if(i.format==="regex")return`Fâsit metin: ${i.pattern} nakşına uymalı.`;return`Fâsit ${r[i.format]??n.format}`}case"not_multiple_of":return`Fâsit sayı: ${n.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${n.keys.length>1?"s":""}: ${M(n.keys,", ")}`;case"invalid_key":return`${n.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${n.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function iP(){return{localeError:yne()}}var bne=()=>{let e={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function t(n){return e[n]??null}let r={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"},o={nan:"NaN",number:"عدد",array:"ارې"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`ناسم ورودي: باید instanceof ${n.expected} وای, مګر ${a} ترلاسه شو`;return`ناسم ورودي: باید ${i} وای, مګر ${a} ترلاسه شو`}case"invalid_value":if(n.values.length===1)return`ناسم ورودي: باید ${Q(n.values[0])} وای`;return`ناسم انتخاب: باید یو له ${M(n.values,"|")} څخه وای`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`ډیر لوی: ${n.origin??"ارزښت"} باید ${i}${n.maximum.toString()} ${s.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${n.origin??"ارزښت"} باید ${i}${n.maximum.toString()} وي`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`ډیر کوچنی: ${n.origin} باید ${i}${n.minimum.toString()} ${s.unit} ولري`;return`ډیر کوچنی: ${n.origin} باید ${i}${n.minimum.toString()} وي`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`ناسم متن: باید د "${i.prefix}" سره پیل شي`;if(i.format==="ends_with")return`ناسم متن: باید د "${i.suffix}" سره پای ته ورسيږي`;if(i.format==="includes")return`ناسم متن: باید "${i.includes}" ولري`;if(i.format==="regex")return`ناسم متن: باید د ${i.pattern} سره مطابقت ولري`;return`${r[i.format]??n.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${n.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${n.keys.length>1?"کلیډونه":"کلیډ"}: ${M(n.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${n.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${n.origin} کې`;default:return"ناسمه ورودي"}}};function sP(){return{localeError:bne()}}var xne=()=>{let e={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function t(n){return e[n]??null}let r={regex:"wyrażenie",email:"adres email",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:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"},o={nan:"NaN",number:"liczba",array:"tablica"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${n.expected}, otrzymano ${a}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${i}, otrzymano ${a}`}case"invalid_value":if(n.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${Q(n.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Za duża wartość: oczekiwano, że ${n.origin??"wartość"} będzie mieć ${i}${n.maximum.toString()} ${s.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${n.origin??"wartość"} będzie wynosić ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Za mała wartość: oczekiwano, że ${n.origin??"wartość"} będzie mieć ${i}${n.minimum.toString()} ${s.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${n.origin??"wartość"} będzie wynosić ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${i.prefix}"`;if(i.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${i.suffix}"`;if(i.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${i.includes}"`;if(i.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${i.pattern}`;return`Nieprawidłow(y/a/e) ${r[i.format]??n.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${n.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${n.keys.length>1?"s":""}: ${M(n.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${n.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${n.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function aP(){return{localeError:xne()}}var vne=()=>{let e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(n){return e[n]??null}let r={regex:"padrão",email:"endereço de e-mail",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:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},o={nan:"NaN",number:"número",null:"nulo"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Tipo inválido: esperado instanceof ${n.expected}, recebido ${a}`;return`Tipo inválido: esperado ${i}, recebido ${a}`}case"invalid_value":if(n.values.length===1)return`Entrada inválida: esperado ${Q(n.values[0])}`;return`Opção inválida: esperada uma das ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Muito grande: esperado que ${n.origin??"valor"} tivesse ${i}${n.maximum.toString()} ${s.unit??"elementos"}`;return`Muito grande: esperado que ${n.origin??"valor"} fosse ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Muito pequeno: esperado que ${n.origin} tivesse ${i}${n.minimum.toString()} ${s.unit}`;return`Muito pequeno: esperado que ${n.origin} fosse ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Texto inválido: deve começar com "${i.prefix}"`;if(i.format==="ends_with")return`Texto inválido: deve terminar com "${i.suffix}"`;if(i.format==="includes")return`Texto inválido: deve incluir "${i.includes}"`;if(i.format==="regex")return`Texto inválido: deve corresponder ao padrão ${i.pattern}`;return`${r[i.format]??n.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${n.divisor}`;case"unrecognized_keys":return`Chave${n.keys.length>1?"s":""} desconhecida${n.keys.length>1?"s":""}: ${M(n.keys,", ")}`;case"invalid_key":return`Chave inválida em ${n.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${n.origin}`;default:return"Campo inválido"}}};function cP(){return{localeError:vne()}}var _ne=()=>{let e={string:{unit:"caractere",verb:"să aibă"},file:{unit:"octeți",verb:"să aibă"},array:{unit:"elemente",verb:"să aibă"},set:{unit:"elemente",verb:"să aibă"},map:{unit:"intrări",verb:"să aibă"}};function t(n){return e[n]??null}let r={regex:"intrare",email:"adresă de email",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:"dată și oră ISO",date:"dată ISO",time:"oră ISO",duration:"durată ISO",ipv4:"adresă IPv4",ipv6:"adresă IPv6",mac:"adresă MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"șir codat base64",base64url:"șir codat base64url",json_string:"șir JSON",e164:"număr E.164",jwt:"JWT",template_literal:"intrare"},o={nan:"NaN",string:"șir",number:"număr",boolean:"boolean",function:"funcție",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"număr mare",void:"void",never:"never",map:"hartă",set:"set"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;return`Intrare invalidă: așteptat ${i}, primit ${a}`}case"invalid_value":if(n.values.length===1)return`Intrare invalidă: așteptat ${Q(n.values[0])}`;return`Opțiune invalidă: așteptat una dintre ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Prea mare: așteptat ca ${n.origin??"valoarea"} ${s.verb} ${i}${n.maximum.toString()} ${s.unit??"elemente"}`;return`Prea mare: așteptat ca ${n.origin??"valoarea"} să fie ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Prea mic: așteptat ca ${n.origin} ${s.verb} ${i}${n.minimum.toString()} ${s.unit}`;return`Prea mic: așteptat ca ${n.origin} să fie ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Șir invalid: trebuie să înceapă cu "${i.prefix}"`;if(i.format==="ends_with")return`Șir invalid: trebuie să se termine cu "${i.suffix}"`;if(i.format==="includes")return`Șir invalid: trebuie să includă "${i.includes}"`;if(i.format==="regex")return`Șir invalid: trebuie să se potrivească cu modelul ${i.pattern}`;return`Format invalid: ${r[i.format]??n.format}`}case"not_multiple_of":return`Număr invalid: trebuie să fie multiplu de ${n.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${M(n.keys,", ")}`;case"invalid_key":return`Cheie invalidă în ${n.origin}`;case"invalid_union":return"Intrare invalidă";case"invalid_element":return`Valoare invalidă în ${n.origin}`;default:return"Intrare invalidă"}}};function uP(){return{localeError:_ne()}}function k4(e,t,r,o){let n=Math.abs(e),i=n%10,s=n%100;if(s>=11&&s<=19)return o;if(i===1)return t;if(i>=2&&i<=4)return r;return o}var wne=()=>{let e={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function t(n){return e[n]??null}let r={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"},o={nan:"NaN",number:"число",array:"массив"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Неверный ввод: ожидалось instanceof ${n.expected}, получено ${a}`;return`Неверный ввод: ожидалось ${i}, получено ${a}`}case"invalid_value":if(n.values.length===1)return`Неверный ввод: ожидалось ${Q(n.values[0])}`;return`Неверный вариант: ожидалось одно из ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s){let a=Number(n.maximum),c=k4(a,s.unit.one,s.unit.few,s.unit.many);return`Слишком большое значение: ожидалось, что ${n.origin??"значение"} будет иметь ${i}${n.maximum.toString()} ${c}`}return`Слишком большое значение: ожидалось, что ${n.origin??"значение"} будет ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s){let a=Number(n.minimum),c=k4(a,s.unit.one,s.unit.few,s.unit.many);return`Слишком маленькое значение: ожидалось, что ${n.origin} будет иметь ${i}${n.minimum.toString()} ${c}`}return`Слишком маленькое значение: ожидалось, что ${n.origin} будет ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Неверная строка: должна начинаться с "${i.prefix}"`;if(i.format==="ends_with")return`Неверная строка: должна заканчиваться на "${i.suffix}"`;if(i.format==="includes")return`Неверная строка: должна содержать "${i.includes}"`;if(i.format==="regex")return`Неверная строка: должна соответствовать шаблону ${i.pattern}`;return`Неверный ${r[i.format]??n.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${n.divisor}`;case"unrecognized_keys":return`Нераспознанн${n.keys.length>1?"ые":"ый"} ключ${n.keys.length>1?"и":""}: ${M(n.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${n.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${n.origin}`;default:return"Неверные входные данные"}}};function lP(){return{localeError:wne()}}var Sne=()=>{let e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(n){return e[n]??null}let r={regex:"vnos",email:"e-poštni naslov",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 datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"},o={nan:"NaN",number:"število",array:"tabela"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Neveljaven vnos: pričakovano instanceof ${n.expected}, prejeto ${a}`;return`Neveljaven vnos: pričakovano ${i}, prejeto ${a}`}case"invalid_value":if(n.values.length===1)return`Neveljaven vnos: pričakovano ${Q(n.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Preveliko: pričakovano, da bo ${n.origin??"vrednost"} imelo ${i}${n.maximum.toString()} ${s.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${n.origin??"vrednost"} ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Premajhno: pričakovano, da bo ${n.origin} imelo ${i}${n.minimum.toString()} ${s.unit}`;return`Premajhno: pričakovano, da bo ${n.origin} ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Neveljaven niz: mora se začeti z "${i.prefix}"`;if(i.format==="ends_with")return`Neveljaven niz: mora se končati z "${i.suffix}"`;if(i.format==="includes")return`Neveljaven niz: mora vsebovati "${i.includes}"`;if(i.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${i.pattern}`;return`Neveljaven ${r[i.format]??n.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${n.divisor}`;case"unrecognized_keys":return`Neprepoznan${n.keys.length>1?"i ključi":" ključ"}: ${M(n.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${n.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${n.origin}`;default:return"Neveljaven vnos"}}};function dP(){return{localeError:Sne()}}var Tne=()=>{let e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function t(n){return e[n]??null}let r={regex:"reguljärt uttryck",email:"e-postadress",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-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},o={nan:"NaN",number:"antal",array:"lista"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Ogiltig inmatning: förväntat instanceof ${n.expected}, fick ${a}`;return`Ogiltig inmatning: förväntat ${i}, fick ${a}`}case"invalid_value":if(n.values.length===1)return`Ogiltig inmatning: förväntat ${Q(n.values[0])}`;return`Ogiltigt val: förväntade en av ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`För stor(t): förväntade ${n.origin??"värdet"} att ha ${i}${n.maximum.toString()} ${s.unit??"element"}`;return`För stor(t): förväntat ${n.origin??"värdet"} att ha ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`För lite(t): förväntade ${n.origin??"värdet"} att ha ${i}${n.minimum.toString()} ${s.unit}`;return`För lite(t): förväntade ${n.origin??"värdet"} att ha ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Ogiltig sträng: måste börja med "${i.prefix}"`;if(i.format==="ends_with")return`Ogiltig sträng: måste sluta med "${i.suffix}"`;if(i.format==="includes")return`Ogiltig sträng: måste innehålla "${i.includes}"`;if(i.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${i.pattern}"`;return`Ogiltig(t) ${r[i.format]??n.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${n.divisor}`;case"unrecognized_keys":return`${n.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${M(n.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${n.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${n.origin??"värdet"}`;default:return"Ogiltig input"}}};function pP(){return{localeError:Tne()}}var Ene=()=>{let e={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function t(n){return e[n]??null}let r={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",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 தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"},o={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${n.expected}, பெறப்பட்டது ${a}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${i}, பெறப்பட்டது ${a}`}case"invalid_value":if(n.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${Q(n.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${M(n.values,"|")} இல் ஒன்று`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${n.origin??"மதிப்பு"} ${i}${n.maximum.toString()} ${s.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${n.origin??"மதிப்பு"} ${i}${n.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${n.origin} ${i}${n.minimum.toString()} ${s.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${n.origin} ${i}${n.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`தவறான சரம்: "${i.prefix}" இல் தொடங்க வேண்டும்`;if(i.format==="ends_with")return`தவறான சரம்: "${i.suffix}" இல் முடிவடைய வேண்டும்`;if(i.format==="includes")return`தவறான சரம்: "${i.includes}" ஐ உள்ளடக்க வேண்டும்`;if(i.format==="regex")return`தவறான சரம்: ${i.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${r[i.format]??n.format}`}case"not_multiple_of":return`தவறான எண்: ${n.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${n.keys.length>1?"கள்":""}: ${M(n.keys,", ")}`;case"invalid_key":return`${n.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${n.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function fP(){return{localeError:Ene()}}var Ine=()=>{let e={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function t(n){return e[n]??null}let r={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},o={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${n.expected} แต่ได้รับ ${a}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${i} แต่ได้รับ ${a}`}case"invalid_value":if(n.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${Q(n.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"ไม่เกิน":"น้อยกว่า",s=t(n.origin);if(s)return`เกินกำหนด: ${n.origin??"ค่า"} ควรมี${i} ${n.maximum.toString()} ${s.unit??"รายการ"}`;return`เกินกำหนด: ${n.origin??"ค่า"} ควรมี${i} ${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?"อย่างน้อย":"มากกว่า",s=t(n.origin);if(s)return`น้อยกว่ากำหนด: ${n.origin} ควรมี${i} ${n.minimum.toString()} ${s.unit}`;return`น้อยกว่ากำหนด: ${n.origin} ควรมี${i} ${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${i.prefix}"`;if(i.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${i.suffix}"`;if(i.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${i.includes}" อยู่ในข้อความ`;if(i.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${i.pattern}`;return`รูปแบบไม่ถูกต้อง: ${r[i.format]??n.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${n.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${M(n.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${n.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${n.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function mP(){return{localeError:Ine()}}var Pne=()=>{let e={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function t(n){return e[n]??null}let r={regex:"girdi",email:"e-posta adresi",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 tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Geçersiz değer: beklenen instanceof ${n.expected}, alınan ${a}`;return`Geçersiz değer: beklenen ${i}, alınan ${a}`}case"invalid_value":if(n.values.length===1)return`Geçersiz değer: beklenen ${Q(n.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Çok büyük: beklenen ${n.origin??"değer"} ${i}${n.maximum.toString()} ${s.unit??"öğe"}`;return`Çok büyük: beklenen ${n.origin??"değer"} ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Çok küçük: beklenen ${n.origin} ${i}${n.minimum.toString()} ${s.unit}`;return`Çok küçük: beklenen ${n.origin} ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Geçersiz metin: "${i.prefix}" ile başlamalı`;if(i.format==="ends_with")return`Geçersiz metin: "${i.suffix}" ile bitmeli`;if(i.format==="includes")return`Geçersiz metin: "${i.includes}" içermeli`;if(i.format==="regex")return`Geçersiz metin: ${i.pattern} desenine uymalı`;return`Geçersiz ${r[i.format]??n.format}`}case"not_multiple_of":return`Geçersiz sayı: ${n.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${n.keys.length>1?"lar":""}: ${M(n.keys,", ")}`;case"invalid_key":return`${n.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${n.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function hP(){return{localeError:Pne()}}var kne=()=>{let e={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function t(n){return e[n]??null}let r={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"},o={nan:"NaN",number:"число",array:"масив"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Неправильні вхідні дані: очікується instanceof ${n.expected}, отримано ${a}`;return`Неправильні вхідні дані: очікується ${i}, отримано ${a}`}case"invalid_value":if(n.values.length===1)return`Неправильні вхідні дані: очікується ${Q(n.values[0])}`;return`Неправильна опція: очікується одне з ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Занадто велике: очікується, що ${n.origin??"значення"} ${s.verb} ${i}${n.maximum.toString()} ${s.unit??"елементів"}`;return`Занадто велике: очікується, що ${n.origin??"значення"} буде ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Занадто мале: очікується, що ${n.origin} ${s.verb} ${i}${n.minimum.toString()} ${s.unit}`;return`Занадто мале: очікується, що ${n.origin} буде ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Неправильний рядок: повинен починатися з "${i.prefix}"`;if(i.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${i.suffix}"`;if(i.format==="includes")return`Неправильний рядок: повинен містити "${i.includes}"`;if(i.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${i.pattern}`;return`Неправильний ${r[i.format]??n.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${n.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${n.keys.length>1?"і":""}: ${M(n.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${n.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${n.origin}`;default:return"Неправильні вхідні дані"}}};function Um(){return{localeError:kne()}}function gP(){return Um()}var Ane=()=>{let e={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function t(n){return e[n]??null}let r={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},o={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`غلط ان پٹ: instanceof ${n.expected} متوقع تھا، ${a} موصول ہوا`;return`غلط ان پٹ: ${i} متوقع تھا، ${a} موصول ہوا`}case"invalid_value":if(n.values.length===1)return`غلط ان پٹ: ${Q(n.values[0])} متوقع تھا`;return`غلط آپشن: ${M(n.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`بہت بڑا: ${n.origin??"ویلیو"} کے ${i}${n.maximum.toString()} ${s.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${n.origin??"ویلیو"} کا ${i}${n.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`بہت چھوٹا: ${n.origin} کے ${i}${n.minimum.toString()} ${s.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${n.origin} کا ${i}${n.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`غلط سٹرنگ: "${i.prefix}" سے شروع ہونا چاہیے`;if(i.format==="ends_with")return`غلط سٹرنگ: "${i.suffix}" پر ختم ہونا چاہیے`;if(i.format==="includes")return`غلط سٹرنگ: "${i.includes}" شامل ہونا چاہیے`;if(i.format==="regex")return`غلط سٹرنگ: پیٹرن ${i.pattern} سے میچ ہونا چاہیے`;return`غلط ${r[i.format]??n.format}`}case"not_multiple_of":return`غلط نمبر: ${n.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${n.keys.length>1?"ز":""}: ${M(n.keys,"، ")}`;case"invalid_key":return`${n.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${n.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function yP(){return{localeError:Ane()}}var $ne=()=>{let e={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"},map:{unit:"yozuv",verb:"bo‘lishi kerak"}};function t(n){return e[n]??null}let r={regex:"kirish",email:"elektron pochta manzili",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 sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},o={nan:"NaN",number:"raqam",array:"massiv"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${n.expected}, qabul qilingan ${a}`;return`Noto‘g‘ri kirish: kutilgan ${i}, qabul qilingan ${a}`}case"invalid_value":if(n.values.length===1)return`Noto‘g‘ri kirish: kutilgan ${Q(n.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Juda katta: kutilgan ${n.origin??"qiymat"} ${i}${n.maximum.toString()} ${s.unit} ${s.verb}`;return`Juda katta: kutilgan ${n.origin??"qiymat"} ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Juda kichik: kutilgan ${n.origin} ${i}${n.minimum.toString()} ${s.unit} ${s.verb}`;return`Juda kichik: kutilgan ${n.origin} ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Noto‘g‘ri satr: "${i.prefix}" bilan boshlanishi kerak`;if(i.format==="ends_with")return`Noto‘g‘ri satr: "${i.suffix}" bilan tugashi kerak`;if(i.format==="includes")return`Noto‘g‘ri satr: "${i.includes}" ni o‘z ichiga olishi kerak`;if(i.format==="regex")return`Noto‘g‘ri satr: ${i.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${r[i.format]??n.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${n.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${n.keys.length>1?"lar":""}: ${M(n.keys,", ")}`;case"invalid_key":return`${n.origin} dagi kalit noto‘g‘ri`;case"invalid_union":return"Noto‘g‘ri kirish";case"invalid_element":return`${n.origin} da noto‘g‘ri qiymat`;default:return"Noto‘g‘ri kirish"}}};function bP(){return{localeError:$ne()}}var Rne=()=>{let e={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function t(n){return e[n]??null}let r={regex:"đầu vào",email:"địa chỉ email",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:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"},o={nan:"NaN",number:"số",array:"mảng"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Đầu vào không hợp lệ: mong đợi instanceof ${n.expected}, nhận được ${a}`;return`Đầu vào không hợp lệ: mong đợi ${i}, nhận được ${a}`}case"invalid_value":if(n.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${Q(n.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Quá lớn: mong đợi ${n.origin??"giá trị"} ${s.verb} ${i}${n.maximum.toString()} ${s.unit??"phần tử"}`;return`Quá lớn: mong đợi ${n.origin??"giá trị"} ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Quá nhỏ: mong đợi ${n.origin} ${s.verb} ${i}${n.minimum.toString()} ${s.unit}`;return`Quá nhỏ: mong đợi ${n.origin} ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${i.prefix}"`;if(i.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${i.suffix}"`;if(i.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${i.includes}"`;if(i.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${i.pattern}`;return`${r[i.format]??n.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${n.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${M(n.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${n.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${n.origin}`;default:return"Đầu vào không hợp lệ"}}};function xP(){return{localeError:Rne()}}var One=()=>{let e={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function t(n){return e[n]??null}let r={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"},o={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`无效输入:期望 instanceof ${n.expected},实际接收 ${a}`;return`无效输入:期望 ${i},实际接收 ${a}`}case"invalid_value":if(n.values.length===1)return`无效输入:期望 ${Q(n.values[0])}`;return`无效选项:期望以下之一 ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`数值过大:期望 ${n.origin??"值"} ${i}${n.maximum.toString()} ${s.unit??"个元素"}`;return`数值过大:期望 ${n.origin??"值"} ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`数值过小:期望 ${n.origin} ${i}${n.minimum.toString()} ${s.unit}`;return`数值过小:期望 ${n.origin} ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`无效字符串:必须以 "${i.prefix}" 开头`;if(i.format==="ends_with")return`无效字符串:必须以 "${i.suffix}" 结尾`;if(i.format==="includes")return`无效字符串:必须包含 "${i.includes}"`;if(i.format==="regex")return`无效字符串:必须满足正则表达式 ${i.pattern}`;return`无效${r[i.format]??n.format}`}case"not_multiple_of":return`无效数字:必须是 ${n.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${M(n.keys,", ")}`;case"invalid_key":return`${n.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${n.origin} 中包含无效值(value)`;default:return"无效输入"}}};function vP(){return{localeError:One()}}var Cne=()=>{let e={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function t(n){return e[n]??null}let r={regex:"輸入",email:"郵件地址",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 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`無效的輸入值:預期為 instanceof ${n.expected},但收到 ${a}`;return`無效的輸入值:預期為 ${i},但收到 ${a}`}case"invalid_value":if(n.values.length===1)return`無效的輸入值:預期為 ${Q(n.values[0])}`;return`無效的選項:預期為以下其中之一 ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`數值過大:預期 ${n.origin??"值"} 應為 ${i}${n.maximum.toString()} ${s.unit??"個元素"}`;return`數值過大:預期 ${n.origin??"值"} 應為 ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`數值過小:預期 ${n.origin} 應為 ${i}${n.minimum.toString()} ${s.unit}`;return`數值過小:預期 ${n.origin} 應為 ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`無效的字串:必須以 "${i.prefix}" 開頭`;if(i.format==="ends_with")return`無效的字串:必須以 "${i.suffix}" 結尾`;if(i.format==="includes")return`無效的字串:必須包含 "${i.includes}"`;if(i.format==="regex")return`無效的字串:必須符合格式 ${i.pattern}`;return`無效的 ${r[i.format]??n.format}`}case"not_multiple_of":return`無效的數字:必須為 ${n.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${n.keys.length>1?"們":""}:${M(n.keys,"、")}`;case"invalid_key":return`${n.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${n.origin} 中有無效的值`;default:return"無效的輸入值"}}};function _P(){return{localeError:Cne()}}var zne=()=>{let e={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function t(n){return e[n]??null}let r={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",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:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},o={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=ee(n.input),a=o[s]??s;if(/^[A-Z]/.test(n.expected))return`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${n.expected}, àmọ̀ a rí ${a}`;return`Ìbáwọlé aṣìṣe: a ní láti fi ${i}, àmọ̀ a rí ${a}`}case"invalid_value":if(n.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${Q(n.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${M(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${n.origin??"iye"} ${s.verb} ${i}${n.maximum} ${s.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${i}${n.maximum}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Kéré ju: a ní láti jẹ́ pé ${n.origin} ${s.verb} ${i}${n.minimum} ${s.unit}`;return`Kéré ju: a ní láti jẹ́ ${i}${n.minimum}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${i.prefix}"`;if(i.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${i.suffix}"`;if(i.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${i.includes}"`;if(i.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${i.pattern}`;return`Aṣìṣe: ${r[i.format]??n.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${n.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${M(n.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${n.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${n.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function wP(){return{localeError:zne()}}var A4,SP=Symbol("ZodOutput"),TP=Symbol("ZodInput");class EP{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 o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function dx(){return new EP}(A4=globalThis).__zod_globalRegistry??(A4.__zod_globalRegistry=dx());var Rr=globalThis.__zod_globalRegistry;function px(e,t){return new e({type:"string",...se(t)})}function IP(e,t){return new e({type:"string",coerce:!0,...se(t)})}function Lm(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...se(t)})}function Kl(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...se(t)})}function jm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...se(t)})}function Fm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...se(t)})}function qm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...se(t)})}function Hm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...se(t)})}function Jl(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...se(t)})}function Gm(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...se(t)})}function Vm(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...se(t)})}function Zm(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...se(t)})}function Wm(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...se(t)})}function Km(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...se(t)})}function Jm(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...se(t)})}function Ym(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...se(t)})}function Qm(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...se(t)})}function Xm(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...se(t)})}function fx(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...se(t)})}function eh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...se(t)})}function th(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...se(t)})}function rh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...se(t)})}function nh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...se(t)})}function oh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...se(t)})}function ih(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...se(t)})}var PP={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function kP(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...se(t)})}function AP(e,t){return new e({type:"string",format:"date",check:"string_format",...se(t)})}function $P(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...se(t)})}function RP(e,t){return new e({type:"string",format:"duration",check:"string_format",...se(t)})}function mx(e,t){return new e({type:"number",checks:[],...se(t)})}function OP(e,t){return new e({type:"number",coerce:!0,checks:[],...se(t)})}function hx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...se(t)})}function gx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...se(t)})}function yx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...se(t)})}function bx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...se(t)})}function xx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...se(t)})}function vx(e,t){return new e({type:"boolean",...se(t)})}function CP(e,t){return new e({type:"boolean",coerce:!0,...se(t)})}function _x(e,t){return new e({type:"bigint",...se(t)})}function zP(e,t){return new e({type:"bigint",coerce:!0,...se(t)})}function wx(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...se(t)})}function Sx(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...se(t)})}function Tx(e,t){return new e({type:"symbol",...se(t)})}function Ex(e,t){return new e({type:"undefined",...se(t)})}function Ix(e,t){return new e({type:"null",...se(t)})}function Px(e){return new e({type:"any"})}function kx(e){return new e({type:"unknown"})}function Ax(e,t){return new e({type:"never",...se(t)})}function $x(e,t){return new e({type:"void",...se(t)})}function Rx(e,t){return new e({type:"date",...se(t)})}function NP(e,t){return new e({type:"date",coerce:!0,...se(t)})}function Ox(e,t){return new e({type:"nan",...se(t)})}function hi(e,t){return new t0({check:"less_than",...se(t),value:e,inclusive:!1})}function Zn(e,t){return new t0({check:"less_than",...se(t),value:e,inclusive:!0})}function gi(e,t){return new r0({check:"greater_than",...se(t),value:e,inclusive:!1})}function an(e,t){return new r0({check:"greater_than",...se(t),value:e,inclusive:!0})}function Cx(e){return gi(0,e)}function zx(e){return hi(0,e)}function Nx(e){return Zn(0,e)}function Mx(e){return an(0,e)}function ba(e,t){return new tI({check:"multiple_of",...se(t),value:e})}function xa(e,t){return new oI({check:"max_size",...se(t),maximum:e})}function yi(e,t){return new iI({check:"min_size",...se(t),minimum:e})}function Vc(e,t){return new sI({check:"size_equals",...se(t),size:e})}function Zc(e,t){return new aI({check:"max_length",...se(t),maximum:e})}function as(e,t){return new cI({check:"min_length",...se(t),minimum:e})}function Wc(e,t){return new uI({check:"length_equals",...se(t),length:e})}function Yl(e,t){return new lI({check:"string_format",format:"regex",...se(t),pattern:e})}function Ql(e){return new dI({check:"string_format",format:"lowercase",...se(e)})}function Xl(e){return new pI({check:"string_format",format:"uppercase",...se(e)})}function ed(e,t){return new fI({check:"string_format",format:"includes",...se(t),includes:e})}function td(e,t){return new mI({check:"string_format",format:"starts_with",...se(t),prefix:e})}function rd(e,t){return new hI({check:"string_format",format:"ends_with",...se(t),suffix:e})}function Bx(e,t,r){return new gI({check:"property",property:e,schema:t,...se(r)})}function nd(e,t){return new yI({check:"mime_type",mime:e,...se(t)})}function $o(e){return new bI({check:"overwrite",tx:e})}function od(e){return $o((t)=>t.normalize(e))}function id(){return $o((e)=>e.trim())}function sd(){return $o((e)=>e.toLowerCase())}function ad(){return $o((e)=>e.toUpperCase())}function cd(){return $o((e)=>yE(e))}function MP(e,t,r){return new e({type:"array",element:t,...se(r)})}function Mne(e,t,r){return new e({type:"union",options:t,...se(r)})}function Bne(e,t,r){return new e({type:"union",options:t,inclusive:!1,...se(r)})}function Dne(e,t,r,o){return new e({type:"union",options:r,discriminator:t,...se(o)})}function Une(e,t,r){return new e({type:"intersection",left:t,right:r})}function Lne(e,t,r,o){let n=r instanceof ze;return new e({type:"tuple",items:t,rest:n?r:null,...se(n?o:r)})}function jne(e,t,r,o){return new e({type:"record",keyType:t,valueType:r,...se(o)})}function Fne(e,t,r,o){return new e({type:"map",keyType:t,valueType:r,...se(o)})}function qne(e,t,r){return new e({type:"set",valueType:t,...se(r)})}function Hne(e,t,r){let o=Array.isArray(t)?Object.fromEntries(t.map((n)=>[n,n])):t;return new e({type:"enum",entries:o,...se(r)})}function Gne(e,t,r){return new e({type:"enum",entries:t,...se(r)})}function Vne(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...se(r)})}function Dx(e,t){return new e({type:"file",...se(t)})}function Zne(e,t){return new e({type:"transform",transform:t})}function Wne(e,t){return new e({type:"optional",innerType:t})}function Kne(e,t){return new e({type:"nullable",innerType:t})}function Jne(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r==="function"?r():Gb(r)}})}function Yne(e,t,r){return new e({type:"nonoptional",innerType:t,...se(r)})}function Qne(e,t){return new e({type:"success",innerType:t})}function Xne(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r==="function"?r:()=>r})}function eoe(e,t,r){return new e({type:"pipe",in:t,out:r})}function toe(e,t){return new e({type:"readonly",innerType:t})}function roe(e,t,r){return new e({type:"template_literal",parts:t,...se(r)})}function noe(e,t){return new e({type:"lazy",getter:t})}function ooe(e,t){return new e({type:"promise",innerType:t})}function Ux(e,t,r){let o=se(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function Lx(e,t,r){return new e({type:"custom",check:"custom",fn:t,...se(r)})}function jx(e,t){let r=$4((o)=>(o.addIssue=(n)=>{if(typeof n==="string")o.issues.push(Dl(n,o.value,r._zod.def));else{let i=n;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=o.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),o.issues.push(Dl(i))}},e(o.value,o)),t);return r}function $4(e,t){let r=new Tt({check:"custom",...se(t)});return r._zod.check=e,r}function Fx(e){let t=new Tt({check:"describe"});return t._zod.onattach=[(r)=>{let o=Rr.get(r)??{};Rr.add(r,{...o,description:e})}],t._zod.check=()=>{},t}function qx(e){let t=new Tt({check:"meta"});return t._zod.onattach=[(r)=>{let o=Rr.get(r)??{};Rr.add(r,{...o,...e})}],t._zod.check=()=>{},t}function Hx(e,t){let r=se(t),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];if(r.case!=="sensitive")o=o.map((h)=>typeof h==="string"?h.toLowerCase():h),n=n.map((h)=>typeof h==="string"?h.toLowerCase():h);let i=new Set(o),s=new Set(n),a=e.Codec??Vl,c=e.Boolean??Hl,d=new(e.String??ya)({type:"string",error:r.error}),p=new c({type:"boolean",error:r.error}),m=new a({type:"pipe",in:d,out:p,transform:(h,y)=>{let x=h;if(r.case!=="sensitive")x=x.toLowerCase();if(i.has(x))return!0;else if(s.has(x))return!1;else return y.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:y.value,inst:m,continue:!1}),{}},reverseTransform:(h,y)=>{if(h===!0)return o[0]||"true";else return n[0]||"false"},error:r.error});return m}function Kc(e,t,r,o={}){let n=se(o),i={...se(o),check:"string_format",type:"string",format:t,fn:typeof r==="function"?r:(a)=>r.test(a),...n};if(r instanceof RegExp)i.pattern=r;return new e(i)}function va(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??Rr,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 gt(e,t,r={path:[],schemaPath:[]}){var o;let n=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 m=s.schema,h=t.processors[n.type];if(!h)throw Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);h(e,t,m,d)}let p=e._zod.parent;if(p){if(!s.ref)s.ref=p;gt(p,t,d),t.seen.get(p).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Object.assign(s.schema,c);if(t.io==="input"&&cn(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(o=s.schema).default??(o.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function _a(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let c=o.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.`);o.set(a,s[0])}}let n=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(s[0])?.id,m=e.external.uri??((y)=>y);if(p)return{ref:m(p)};let h=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=h,{defId:h,ref:`${m("__shared")}#/${a}/${h}`}}if(s[1]===r)return{ref:"#"};let u=`${"#"}/${a}/`,d=s[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},i=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:u}=n(s);if(a.def={...a.schema},u)a.defId=u;let d=a.schema;for(let p in d)delete d[p];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 u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){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 wa(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},p=c.ref;if(c.ref=null,p){o(p);let h=e.seen.get(p),y=h.schema;if(y.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))u.allOf=u.allOf??[],u.allOf.push(y);else Object.assign(u,y);if(Object.assign(u,d),a._zod.parent===p)for(let S in u){if(S==="$ref"||S==="allOf")continue;if(!(S in d))delete u[S]}if(y.$ref&&h.def)for(let S in u){if(S==="$ref"||S==="allOf")continue;if(S in h.def&&JSON.stringify(u[S])===JSON.stringify(h.def[S]))delete u[S]}}let m=a._zod.parent;if(m&&m!==p){o(m);let h=e.seen.get(m);if(h?.schema.$ref){if(u.$ref=h.schema.$ref,h.def)for(let y in u){if(y==="$ref"||y==="allOf")continue;if(y in h.def&&JSON.stringify(u[y])===JSON.stringify(h.def[y]))delete u[y]}}}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let n={};if(e.target==="draft-2020-12")n.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")n.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")n.$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");n.$id=e.external.uri(a)}Object.assign(n,r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&n.id===i)delete n.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")n.$defs=s;else n.definitions=s;try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:ud(t,"input",e.processors),output:ud(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function cn(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return cn(o.element,r);if(o.type==="set")return cn(o.valueType,r);if(o.type==="lazy")return cn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return cn(o.innerType,r);if(o.type==="intersection")return cn(o.left,r)||cn(o.right,r);if(o.type==="record"||o.type==="map")return cn(o.keyType,r)||cn(o.valueType,r);if(o.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return cn(o.in,r)||cn(o.out,r)}if(o.type==="object"){for(let n in o.shape)if(cn(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(cn(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(cn(n,r))return!0;if(o.rest&&cn(o.rest,r))return!0;return!1}return!1}var BP=(e,t={})=>(r)=>{let o=va({...r,processors:t});return gt(e,o),_a(o,e),wa(o,e)},ud=(e,t,r={})=>(o)=>{let{libraryOptions:n,target:i}=o??{},s=va({...n??{},target:i,io:t,processors:r});return gt(e,s),_a(s,e),wa(s,e)};var ioe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},DP=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof i==="number")n.minLength=i;if(typeof s==="number")n.maxLength=s;if(a){if(n.format=ioe[a]??a,n.format==="")delete n.format;if(a==="time")delete n.format}if(u)n.contentEncoding=u;if(c&&c.size>0){let d=[...c];if(d.length===1)n.pattern=d[0].source;else if(d.length>1)n.allOf=[...d.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},UP=(e,t,r,o)=>{let n=r,{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))n.type="integer";else n.type="number";let p=typeof d==="number"&&d>=(i??Number.NEGATIVE_INFINITY),m=typeof u==="number"&&u<=(s??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";if(p)if(h)n.minimum=d,n.exclusiveMinimum=!0;else n.exclusiveMinimum=d;else if(typeof i==="number")n.minimum=i;if(m)if(h)n.maximum=u,n.exclusiveMaximum=!0;else n.exclusiveMaximum=u;else if(typeof s==="number")n.maximum=s;if(typeof c==="number")n.multipleOf=c},LP=(e,t,r,o)=>{r.type="boolean"},jP=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},FP=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},qP=(e,t,r,o)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},HP=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},GP=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},VP=(e,t,r,o)=>{r.not={}},ZP=(e,t,r,o)=>{},WP=(e,t,r,o)=>{},KP=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},JP=(e,t,r,o)=>{let n=e._zod.def,i=vm(n.entries);if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";r.enum=i},YP=(e,t,r,o)=>{let n=e._zod.def,i=[];for(let s of n.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}},QP=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},XP=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},ek=(e,t,r,o)=>{let n=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(n,i);else Object.assign(n,i),n.anyOf=c.map((u)=>({contentMediaType:u}));else Object.assign(n,i)},tk=(e,t,r,o)=>{r.type="boolean"},rk=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},nk=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},ok=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},ik=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},sk=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},ak=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")n.minItems=s;if(typeof a==="number")n.maxItems=a;n.type="array",n.items=gt(i.element,t,{...o,path:[...o.path,"items"]})},ck=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object",n.properties={};let s=i.shape;for(let u in s)n.properties[u]=gt(s[u],t,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(s)),c=new Set([...a].filter((u)=>{let d=i.shape[u]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(c.size>0)n.required=Array.from(c);if(i.catchall?._zod.def.type==="never")n.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")n.additionalProperties=!1}else if(i.catchall)n.additionalProperties=gt(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Vx=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>gt(a,t,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));if(i)r.oneOf=s;else r.anyOf=s},uk=(e,t,r,o)=>{let n=e._zod.def,i=gt(n.left,t,{...o,path:[...o.path,"allOf",0]}),s=gt(n.right,t,{...o,path:[...o.path,"allOf",1]}),a=(u)=>("allOf"in u)&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c},lk=(e,t,r,o)=>{let n=r,i=e._zod.def;n.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((m,h)=>gt(m,t,{...o,path:[...o.path,s,h]})),u=i.rest?gt(i.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(n.prefixItems=c,u)n.items=u}else if(t.target==="openapi-3.0"){if(n.items={anyOf:c},u)n.items.anyOf.push(u);if(n.minItems=c.length,!u)n.maxItems=c.length}else if(n.items=c,u)n.additionalItems=u;let{minimum:d,maximum:p}=e._zod.bag;if(typeof d==="number")n.minItems=d;if(typeof p==="number")n.maxItems=p},dk=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let s=i.keyType,c=s._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let d=gt(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let p of c)n.patternProperties[p.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")n.propertyNames=gt(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});n.additionalProperties=gt(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=s._zod.values;if(u){let d=[...u].filter((p)=>typeof p==="string"||typeof p==="number");if(d.length>0)n.required=d}},pk=(e,t,r,o)=>{let n=e._zod.def,i=gt(n.innerType,t,o),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=n.innerType,r.nullable=!0;else r.anyOf=[i,{type:"null"}]},fk=(e,t,r,o)=>{let n=e._zod.def;gt(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},mk=(e,t,r,o)=>{let n=e._zod.def;gt(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},hk=(e,t,r,o)=>{let n=e._zod.def;gt(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(n.defaultValue))},gk=(e,t,r,o)=>{let n=e._zod.def;gt(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},yk=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?n.out:n.in:n.out;gt(s,t,o);let a=t.seen.get(e);a.ref=s},bk=(e,t,r,o)=>{let n=e._zod.def;gt(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},xk=(e,t,r,o)=>{let n=e._zod.def;gt(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Zx=(e,t,r,o)=>{let n=e._zod.def;gt(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},vk=(e,t,r,o)=>{let n=e._zod.innerType;gt(n,t,o);let i=t.seen.get(e);i.ref=n},Gx={string:DP,number:UP,boolean:LP,bigint:jP,symbol:FP,null:qP,undefined:HP,void:GP,never:VP,any:ZP,unknown:WP,date:KP,enum:JP,literal:YP,nan:QP,template_literal:XP,file:ek,success:tk,custom:rk,function:nk,transform:ok,map:ik,set:sk,array:ak,object:ck,union:Vx,intersection:uk,tuple:lk,record:dk,nullable:pk,nonoptional:fk,default:mk,prefault:hk,catch:gk,pipe:yk,readonly:bk,promise:xk,optional:Zx,lazy:vk};function Jc(e,t){if("_idmap"in e){let o=e,n=va({...t,processors:Gx}),i={};for(let c of o._idmap.entries()){let[u,d]=c;gt(d,n)}let s={},a={registry:o,uri:t?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,d]=c;_a(n,d),s[u]=wa(n,d)}if(Object.keys(i).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=va({...t,processors:Gx});return gt(e,r),_a(r,e),wa(r,e)}class _k{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";this.ctx=va({processors:Gx,target:t,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,t={path:[],schemaPath:[]}){return gt(e,this.ctx,t)}emit(e,t){if(t){if(t.cycles)this.ctx.cycles=t.cycles;if(t.reused)this.ctx.reused=t.reused;if(t.external)this.ctx.external=t.external}_a(this.ctx,e);let r=wa(this.ctx,e),{"~standard":o,...n}=r;return n}}var R4={};var coe=R("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");ze.init(e,t),e.def=t,e.type=t.type,e.parse=(r,o)=>qc(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>ha(e,r,o),e.parseAsync=async(r,o)=>Hc(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>ga(e,r,o),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map((o)=>typeof o==="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]},{parent:!0}),e.with=e.check,e.clone=(r,o)=>$r(e,r,o),e.brand=()=>e,e.register=(r,o)=>(r.add(e,o),e),e.apply=(r)=>r(e)});var uoe=R("ZodMiniObject",(e,t)=>{L0.init(e,t),coe.init(e,t),Ve(e,"shape",()=>t.shape)});function wk(e,t){let r={type:"object",shape:e??{},...se(t)};return new uoe(r)}function oo(e){return!!e._zod}function Yc(e){let t=Object.values(e);if(t.length===0)return wk({});let r=t.every(oo),o=t.every((n)=>!oo(n));if(r)return wk(e);if(o)return CM(e);throw Error("Mixed Zod versions detected in object shape.")}function Sa(e,t){if(oo(e))return ha(e,t);return e.safeParse(t)}async function Wx(e,t){if(oo(e))return await ga(e,t);return await e.safeParseAsync(t)}function Ta(e){if(!e)return;let t;if(oo(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 ld(e){if(!e)return;if(typeof e==="object"){let t=e,r=e;if(!t._def&&!r._zod){let o=Object.values(e);if(o.length>0&&o.every((n)=>typeof n==="object"&&n!==null&&(n._def!==void 0||n._zod!==void 0||typeof n.parse==="function")))return Yc(e)}}if(oo(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 Kx(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 O4(e){return e.description}function C4(e){if(oo(e))return e._zod?.def?.type==="optional";let t=e;if(typeof e.isOptional==="function")return e.isOptional();return t._def?.typeName==="ZodOptional"}function Jx(e){if(oo(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 o=e.value;if(o!==void 0)return o;return}var f={};Pn(f,{$brand:()=>mE,$input:()=>TP,$output:()=>SP,NEVER:()=>fE,TimePrecision:()=>PP,ZodAny:()=>qk,ZodArray:()=>Zk,ZodBase64:()=>yv,ZodBase64URL:()=>bv,ZodBigInt:()=>yd,ZodBigIntFormat:()=>_v,ZodBoolean:()=>gd,ZodCIDRv4:()=>hv,ZodCIDRv6:()=>gv,ZodCUID:()=>cv,ZodCUID2:()=>uv,ZodCatch:()=>fA,ZodCodec:()=>yh,ZodCustom:()=>bh,ZodCustomStringFormat:()=>md,ZodDate:()=>ph,ZodDefault:()=>aA,ZodDiscriminatedUnion:()=>Kk,ZodE164:()=>xv,ZodEmail:()=>iv,ZodEmoji:()=>sv,ZodEnum:()=>pd,ZodError:()=>doe,ZodExactOptional:()=>oA,ZodFile:()=>rA,ZodFirstPartyTypeKind:()=>IA,ZodFunction:()=>SA,ZodGUID:()=>ah,ZodIPv4:()=>fv,ZodIPv6:()=>mv,ZodISODate:()=>Xx,ZodISODateTime:()=>Qx,ZodISODuration:()=>tv,ZodISOTime:()=>ev,ZodIntersection:()=>Jk,ZodIssueCode:()=>foe,ZodJWT:()=>vv,ZodKSUID:()=>pv,ZodLazy:()=>vA,ZodLiteral:()=>tA,ZodMAC:()=>Uk,ZodMap:()=>Xk,ZodNaN:()=>hA,ZodNanoID:()=>av,ZodNever:()=>Gk,ZodNonOptional:()=>Tv,ZodNull:()=>Fk,ZodNullable:()=>sA,ZodNumber:()=>hd,ZodNumberFormat:()=>Qc,ZodObject:()=>fh,ZodOptional:()=>xd,ZodPipe:()=>gh,ZodPrefault:()=>uA,ZodPreprocess:()=>gA,ZodPromise:()=>wA,ZodReadonly:()=>yA,ZodRealError:()=>On,ZodRecord:()=>dd,ZodSet:()=>eA,ZodString:()=>fd,ZodStringFormat:()=>Et,ZodSuccess:()=>pA,ZodSymbol:()=>Lk,ZodTemplateLiteral:()=>xA,ZodTransform:()=>nA,ZodTuple:()=>Yk,ZodType:()=>Ge,ZodULID:()=>lv,ZodURL:()=>lh,ZodUUID:()=>bi,ZodUndefined:()=>jk,ZodUnion:()=>mh,ZodUnknown:()=>Hk,ZodVoid:()=>Vk,ZodXID:()=>dv,ZodXor:()=>Wk,_ZodString:()=>ov,_default:()=>cA,_function:()=>DB,any:()=>xB,array:()=>Ye,base64:()=>rB,base64url:()=>nB,bigint:()=>mB,boolean:()=>rr,catch:()=>mA,check:()=>UB,cidrv4:()=>eB,cidrv6:()=>tB,clone:()=>$r,codec:()=>zB,coerce:()=>PA,config:()=>Xt,core:()=>Ro,cuid:()=>V4,cuid2:()=>Z4,custom:()=>Ev,date:()=>_B,decode:()=>Ok,decodeAsync:()=>zk,describe:()=>LB,discriminatedUnion:()=>hh,e164:()=>oB,email:()=>M4,emoji:()=>H4,encode:()=>Rk,encodeAsync:()=>Ck,endsWith:()=>rd,enum:()=>Cr,exactOptional:()=>iA,file:()=>$B,flattenError:()=>Im,float32:()=>lB,float64:()=>dB,formatError:()=>Pm,fromJSONSchema:()=>VB,function:()=>DB,getErrorMap:()=>hoe,globalRegistry:()=>Rr,gt:()=>gi,gte:()=>an,guid:()=>B4,hash:()=>uB,hex:()=>cB,hostname:()=>aB,httpUrl:()=>q4,includes:()=>ed,instanceof:()=>FB,int:()=>rv,int32:()=>pB,int64:()=>hB,intersection:()=>bd,invertCodec:()=>NB,ipv4:()=>Y4,ipv6:()=>X4,iso:()=>Ea,json:()=>HB,jwt:()=>iB,keyof:()=>wB,ksuid:()=>J4,lazy:()=>_A,length:()=>Wc,literal:()=>Se,locales:()=>Wl,looseObject:()=>Or,looseRecord:()=>IB,lowercase:()=>Ql,lt:()=>hi,lte:()=>Zn,mac:()=>Q4,map:()=>PB,maxLength:()=>Zc,maxSize:()=>xa,meta:()=>jB,mime:()=>nd,minLength:()=>as,minSize:()=>yi,multipleOf:()=>ba,nan:()=>CB,nanoid:()=>G4,nativeEnum:()=>AB,negative:()=>zx,never:()=>wv,nonnegative:()=>Mx,nonoptional:()=>dA,nonpositive:()=>Nx,normalize:()=>od,null:()=>dh,nullable:()=>ch,nullish:()=>RB,number:()=>ut,object:()=>be,optional:()=>Rt,overwrite:()=>$o,parse:()=>Pk,parseAsync:()=>kk,partialRecord:()=>EB,pipe:()=>nv,positive:()=>Cx,prefault:()=>lA,preprocess:()=>xh,prettifyError:()=>EE,promise:()=>BB,property:()=>Bx,readonly:()=>bA,record:()=>vt,refine:()=>TA,regex:()=>Yl,regexes:()=>Rn,registry:()=>dx,safeDecode:()=>Mk,safeDecodeAsync:()=>Dk,safeEncode:()=>Nk,safeEncodeAsync:()=>Bk,safeParse:()=>Ak,safeParseAsync:()=>$k,set:()=>kB,setErrorMap:()=>moe,size:()=>Vc,slugify:()=>cd,startsWith:()=>td,strictObject:()=>SB,string:()=>L,stringFormat:()=>sB,stringbool:()=>qB,success:()=>OB,superRefine:()=>EA,symbol:()=>yB,templateLiteral:()=>MB,toJSONSchema:()=>Jc,toLowerCase:()=>sd,toUpperCase:()=>ad,transform:()=>Sv,treeifyError:()=>TE,trim:()=>id,tuple:()=>Qk,uint32:()=>fB,uint64:()=>gB,ulid:()=>W4,undefined:()=>bB,union:()=>Pt,unknown:()=>It,uppercase:()=>Xl,url:()=>F4,util:()=>re,uuid:()=>D4,uuidv4:()=>U4,uuidv6:()=>L4,uuidv7:()=>j4,void:()=>vB,xid:()=>K4,xor:()=>TB});var sh={};Pn(sh,{ZodAny:()=>qk,ZodArray:()=>Zk,ZodBase64:()=>yv,ZodBase64URL:()=>bv,ZodBigInt:()=>yd,ZodBigIntFormat:()=>_v,ZodBoolean:()=>gd,ZodCIDRv4:()=>hv,ZodCIDRv6:()=>gv,ZodCUID:()=>cv,ZodCUID2:()=>uv,ZodCatch:()=>fA,ZodCodec:()=>yh,ZodCustom:()=>bh,ZodCustomStringFormat:()=>md,ZodDate:()=>ph,ZodDefault:()=>aA,ZodDiscriminatedUnion:()=>Kk,ZodE164:()=>xv,ZodEmail:()=>iv,ZodEmoji:()=>sv,ZodEnum:()=>pd,ZodExactOptional:()=>oA,ZodFile:()=>rA,ZodFunction:()=>SA,ZodGUID:()=>ah,ZodIPv4:()=>fv,ZodIPv6:()=>mv,ZodIntersection:()=>Jk,ZodJWT:()=>vv,ZodKSUID:()=>pv,ZodLazy:()=>vA,ZodLiteral:()=>tA,ZodMAC:()=>Uk,ZodMap:()=>Xk,ZodNaN:()=>hA,ZodNanoID:()=>av,ZodNever:()=>Gk,ZodNonOptional:()=>Tv,ZodNull:()=>Fk,ZodNullable:()=>sA,ZodNumber:()=>hd,ZodNumberFormat:()=>Qc,ZodObject:()=>fh,ZodOptional:()=>xd,ZodPipe:()=>gh,ZodPrefault:()=>uA,ZodPreprocess:()=>gA,ZodPromise:()=>wA,ZodReadonly:()=>yA,ZodRecord:()=>dd,ZodSet:()=>eA,ZodString:()=>fd,ZodStringFormat:()=>Et,ZodSuccess:()=>pA,ZodSymbol:()=>Lk,ZodTemplateLiteral:()=>xA,ZodTransform:()=>nA,ZodTuple:()=>Yk,ZodType:()=>Ge,ZodULID:()=>lv,ZodURL:()=>lh,ZodUUID:()=>bi,ZodUndefined:()=>jk,ZodUnion:()=>mh,ZodUnknown:()=>Hk,ZodVoid:()=>Vk,ZodXID:()=>dv,ZodXor:()=>Wk,_ZodString:()=>ov,_default:()=>cA,_function:()=>DB,any:()=>xB,array:()=>Ye,base64:()=>rB,base64url:()=>nB,bigint:()=>mB,boolean:()=>rr,catch:()=>mA,check:()=>UB,cidrv4:()=>eB,cidrv6:()=>tB,codec:()=>zB,cuid:()=>V4,cuid2:()=>Z4,custom:()=>Ev,date:()=>_B,describe:()=>LB,discriminatedUnion:()=>hh,e164:()=>oB,email:()=>M4,emoji:()=>H4,enum:()=>Cr,exactOptional:()=>iA,file:()=>$B,float32:()=>lB,float64:()=>dB,function:()=>DB,guid:()=>B4,hash:()=>uB,hex:()=>cB,hostname:()=>aB,httpUrl:()=>q4,instanceof:()=>FB,int:()=>rv,int32:()=>pB,int64:()=>hB,intersection:()=>bd,invertCodec:()=>NB,ipv4:()=>Y4,ipv6:()=>X4,json:()=>HB,jwt:()=>iB,keyof:()=>wB,ksuid:()=>J4,lazy:()=>_A,literal:()=>Se,looseObject:()=>Or,looseRecord:()=>IB,mac:()=>Q4,map:()=>PB,meta:()=>jB,nan:()=>CB,nanoid:()=>G4,nativeEnum:()=>AB,never:()=>wv,nonoptional:()=>dA,null:()=>dh,nullable:()=>ch,nullish:()=>RB,number:()=>ut,object:()=>be,optional:()=>Rt,partialRecord:()=>EB,pipe:()=>nv,prefault:()=>lA,preprocess:()=>xh,promise:()=>BB,readonly:()=>bA,record:()=>vt,refine:()=>TA,set:()=>kB,strictObject:()=>SB,string:()=>L,stringFormat:()=>sB,stringbool:()=>qB,success:()=>OB,superRefine:()=>EA,symbol:()=>yB,templateLiteral:()=>MB,transform:()=>Sv,tuple:()=>Qk,uint32:()=>fB,uint64:()=>gB,ulid:()=>W4,undefined:()=>bB,union:()=>Pt,unknown:()=>It,url:()=>F4,uuid:()=>D4,uuidv4:()=>U4,uuidv6:()=>L4,uuidv7:()=>j4,void:()=>vB,xid:()=>K4,xor:()=>TB});var Yx={};Pn(Yx,{endsWith:()=>rd,gt:()=>gi,gte:()=>an,includes:()=>ed,length:()=>Wc,lowercase:()=>Ql,lt:()=>hi,lte:()=>Zn,maxLength:()=>Zc,maxSize:()=>xa,mime:()=>nd,minLength:()=>as,minSize:()=>yi,multipleOf:()=>ba,negative:()=>zx,nonnegative:()=>Mx,nonpositive:()=>Nx,normalize:()=>od,overwrite:()=>$o,positive:()=>Cx,property:()=>Bx,regex:()=>Yl,size:()=>Vc,slugify:()=>cd,startsWith:()=>td,toLowerCase:()=>sd,toUpperCase:()=>ad,trim:()=>id,uppercase:()=>Xl});var Ea={};Pn(Ea,{ZodISODate:()=>Xx,ZodISODateTime:()=>Qx,ZodISODuration:()=>tv,ZodISOTime:()=>ev,date:()=>Tk,datetime:()=>Sk,duration:()=>Ik,time:()=>Ek});var Qx=R("ZodISODateTime",(e,t)=>{_I.init(e,t),Et.init(e,t)});function Sk(e){return kP(Qx,e)}var Xx=R("ZodISODate",(e,t)=>{wI.init(e,t),Et.init(e,t)});function Tk(e){return AP(Xx,e)}var ev=R("ZodISOTime",(e,t)=>{SI.init(e,t),Et.init(e,t)});function Ek(e){return $P(ev,e)}var tv=R("ZodISODuration",(e,t)=>{TI.init(e,t),Et.init(e,t)});function Ik(e){return RP(tv,e)}var z4=(e,t)=>{Em.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>Pm(e,r)},flatten:{value:(r)=>Im(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Ml,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Ml,2)}},isEmpty:{get(){return e.issues.length===0}}})},doe=R("ZodError",z4),On=R("ZodError",z4,{Parent:Error});var Pk=Ul(On),kk=Ll(On),Ak=jl(On),$k=Fl(On),Rk=Vb(On),Ok=Zb(On),Ck=Wb(On),zk=Kb(On),Nk=Jb(On),Mk=Yb(On),Bk=Qb(On),Dk=Xb(On);var N4=new WeakMap;function uh(e,t,r){let o=Object.getPrototypeOf(e),n=N4.get(o);if(!n)n=new Set,N4.set(o,n);if(n.has(t))return;n.add(t);for(let i in r){let s=r[i];Object.defineProperty(o,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 Ge=R("ZodType",(e,t)=>(ze.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ud(e,"input"),output:ud(e,"output")}}),e.toJSONSchema=BP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,o)=>Pk(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Ak(e,r,o),e.parseAsync=async(r,o)=>kk(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>$k(e,r,o),e.spa=e.safeParseAsync,e.encode=(r,o)=>Rk(e,r,o),e.decode=(r,o)=>Ok(e,r,o),e.encodeAsync=async(r,o)=>Ck(e,r,o),e.decodeAsync=async(r,o)=>zk(e,r,o),e.safeEncode=(r,o)=>Nk(e,r,o),e.safeDecode=(r,o)=>Mk(e,r,o),e.safeEncodeAsync=async(r,o)=>Bk(e,r,o),e.safeDecodeAsync=async(r,o)=>Dk(e,r,o),uh(e,"ZodType",{check(...r){let o=this.def;return this.clone(re.mergeDefs(o,{checks:[...o.checks??[],...r.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,o){return $r(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(TA(r,o))},superRefine(r,o){return this.check(EA(r,o))},overwrite(r){return this.check($o(r))},optional(){return Rt(this)},exactOptional(){return iA(this)},nullable(){return ch(this)},nullish(){return Rt(ch(this))},nonoptional(r){return dA(this,r)},array(){return Ye(this)},or(r){return Pt([this,r])},and(r){return bd(this,r)},transform(r){return nv(this,Sv(r))},default(r){return cA(this,r)},prefault(r){return lA(this,r)},catch(r){return mA(this,r)},pipe(r){return nv(this,r)},readonly(){return bA(this)},describe(r){let o=this.clone();return Rr.add(o,{description:r}),o},meta(...r){if(r.length===0)return Rr.get(this);let o=this.clone();return Rr.add(o,r[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return Rr.get(e)?.description},configurable:!0}),e)),ov=R("_ZodString",(e,t)=>{ya.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(o,n,i)=>DP(e,o,n,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,uh(e,"_ZodString",{regex(...o){return this.check(Yl(...o))},includes(...o){return this.check(ed(...o))},startsWith(...o){return this.check(td(...o))},endsWith(...o){return this.check(rd(...o))},min(...o){return this.check(as(...o))},max(...o){return this.check(Zc(...o))},length(...o){return this.check(Wc(...o))},nonempty(...o){return this.check(as(1,...o))},lowercase(o){return this.check(Ql(o))},uppercase(o){return this.check(Xl(o))},trim(){return this.check(id())},normalize(...o){return this.check(od(...o))},toLowerCase(){return this.check(sd())},toUpperCase(){return this.check(ad())},slugify(){return this.check(cd())}})}),fd=R("ZodString",(e,t)=>{ya.init(e,t),ov.init(e,t),e.email=(r)=>e.check(Lm(iv,r)),e.url=(r)=>e.check(Jl(lh,r)),e.jwt=(r)=>e.check(ih(vv,r)),e.emoji=(r)=>e.check(Gm(sv,r)),e.guid=(r)=>e.check(Kl(ah,r)),e.uuid=(r)=>e.check(jm(bi,r)),e.uuidv4=(r)=>e.check(Fm(bi,r)),e.uuidv6=(r)=>e.check(qm(bi,r)),e.uuidv7=(r)=>e.check(Hm(bi,r)),e.nanoid=(r)=>e.check(Vm(av,r)),e.guid=(r)=>e.check(Kl(ah,r)),e.cuid=(r)=>e.check(Zm(cv,r)),e.cuid2=(r)=>e.check(Wm(uv,r)),e.ulid=(r)=>e.check(Km(lv,r)),e.base64=(r)=>e.check(rh(yv,r)),e.base64url=(r)=>e.check(nh(bv,r)),e.xid=(r)=>e.check(Jm(dv,r)),e.ksuid=(r)=>e.check(Ym(pv,r)),e.ipv4=(r)=>e.check(Qm(fv,r)),e.ipv6=(r)=>e.check(Xm(mv,r)),e.cidrv4=(r)=>e.check(eh(hv,r)),e.cidrv6=(r)=>e.check(th(gv,r)),e.e164=(r)=>e.check(oh(xv,r)),e.datetime=(r)=>e.check(Sk(r)),e.date=(r)=>e.check(Tk(r)),e.time=(r)=>e.check(Ek(r)),e.duration=(r)=>e.check(Ik(r))});function L(e){return px(fd,e)}var Et=R("ZodStringFormat",(e,t)=>{xt.init(e,t),ov.init(e,t)}),iv=R("ZodEmail",(e,t)=>{l0.init(e,t),Et.init(e,t)});function M4(e){return Lm(iv,e)}var ah=R("ZodGUID",(e,t)=>{c0.init(e,t),Et.init(e,t)});function B4(e){return Kl(ah,e)}var bi=R("ZodUUID",(e,t)=>{u0.init(e,t),Et.init(e,t)});function D4(e){return jm(bi,e)}function U4(e){return Fm(bi,e)}function L4(e){return qm(bi,e)}function j4(e){return Hm(bi,e)}var lh=R("ZodURL",(e,t)=>{d0.init(e,t),Et.init(e,t)});function F4(e){return Jl(lh,e)}function q4(e){return Jl(lh,{protocol:Rn.httpProtocol,hostname:Rn.domain,...re.normalizeParams(e)})}var sv=R("ZodEmoji",(e,t)=>{p0.init(e,t),Et.init(e,t)});function H4(e){return Gm(sv,e)}var av=R("ZodNanoID",(e,t)=>{f0.init(e,t),Et.init(e,t)});function G4(e){return Vm(av,e)}var cv=R("ZodCUID",(e,t)=>{m0.init(e,t),Et.init(e,t)});function V4(e){return Zm(cv,e)}var uv=R("ZodCUID2",(e,t)=>{h0.init(e,t),Et.init(e,t)});function Z4(e){return Wm(uv,e)}var lv=R("ZodULID",(e,t)=>{g0.init(e,t),Et.init(e,t)});function W4(e){return Km(lv,e)}var dv=R("ZodXID",(e,t)=>{y0.init(e,t),Et.init(e,t)});function K4(e){return Jm(dv,e)}var pv=R("ZodKSUID",(e,t)=>{b0.init(e,t),Et.init(e,t)});function J4(e){return Ym(pv,e)}var fv=R("ZodIPv4",(e,t)=>{x0.init(e,t),Et.init(e,t)});function Y4(e){return Qm(fv,e)}var Uk=R("ZodMAC",(e,t)=>{_0.init(e,t),Et.init(e,t)});function Q4(e){return fx(Uk,e)}var mv=R("ZodIPv6",(e,t)=>{v0.init(e,t),Et.init(e,t)});function X4(e){return Xm(mv,e)}var hv=R("ZodCIDRv4",(e,t)=>{w0.init(e,t),Et.init(e,t)});function eB(e){return eh(hv,e)}var gv=R("ZodCIDRv6",(e,t)=>{S0.init(e,t),Et.init(e,t)});function tB(e){return th(gv,e)}var yv=R("ZodBase64",(e,t)=>{T0.init(e,t),Et.init(e,t)});function rB(e){return rh(yv,e)}var bv=R("ZodBase64URL",(e,t)=>{E0.init(e,t),Et.init(e,t)});function nB(e){return nh(bv,e)}var xv=R("ZodE164",(e,t)=>{I0.init(e,t),Et.init(e,t)});function oB(e){return oh(xv,e)}var vv=R("ZodJWT",(e,t)=>{P0.init(e,t),Et.init(e,t)});function iB(e){return ih(vv,e)}var md=R("ZodCustomStringFormat",(e,t)=>{k0.init(e,t),Et.init(e,t)});function sB(e,t,r={}){return Kc(md,e,t,r)}function aB(e){return Kc(md,"hostname",Rn.hostname,e)}function cB(e){return Kc(md,"hex",Rn.hex,e)}function uB(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Rn[o];if(!n)throw Error(`Unrecognized hash format: ${o}`);return Kc(md,o,n,t)}var hd=R("ZodNumber",(e,t)=>{Rm.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(o,n,i)=>UP(e,o,n,i),uh(e,"ZodNumber",{gt(o,n){return this.check(gi(o,n))},gte(o,n){return this.check(an(o,n))},min(o,n){return this.check(an(o,n))},lt(o,n){return this.check(hi(o,n))},lte(o,n){return this.check(Zn(o,n))},max(o,n){return this.check(Zn(o,n))},int(o){return this.check(rv(o))},safe(o){return this.check(rv(o))},positive(o){return this.check(gi(0,o))},nonnegative(o){return this.check(an(0,o))},negative(o){return this.check(hi(0,o))},nonpositive(o){return this.check(Zn(0,o))},multipleOf(o,n){return this.check(ba(o,n))},step(o,n){return this.check(ba(o,n))},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 ut(e){return mx(hd,e)}var Qc=R("ZodNumberFormat",(e,t)=>{A0.init(e,t),hd.init(e,t)});function rv(e){return hx(Qc,e)}function lB(e){return gx(Qc,e)}function dB(e){return yx(Qc,e)}function pB(e){return bx(Qc,e)}function fB(e){return xx(Qc,e)}var gd=R("ZodBoolean",(e,t)=>{Hl.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>LP(e,r,o,n)});function rr(e){return vx(gd,e)}var yd=R("ZodBigInt",(e,t)=>{Om.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(o,n,i)=>jP(e,o,n,i),e.gte=(o,n)=>e.check(an(o,n)),e.min=(o,n)=>e.check(an(o,n)),e.gt=(o,n)=>e.check(gi(o,n)),e.gte=(o,n)=>e.check(an(o,n)),e.min=(o,n)=>e.check(an(o,n)),e.lt=(o,n)=>e.check(hi(o,n)),e.lte=(o,n)=>e.check(Zn(o,n)),e.max=(o,n)=>e.check(Zn(o,n)),e.positive=(o)=>e.check(gi(BigInt(0),o)),e.negative=(o)=>e.check(hi(BigInt(0),o)),e.nonpositive=(o)=>e.check(Zn(BigInt(0),o)),e.nonnegative=(o)=>e.check(an(BigInt(0),o)),e.multipleOf=(o,n)=>e.check(ba(o,n));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function mB(e){return _x(yd,e)}var _v=R("ZodBigIntFormat",(e,t)=>{$0.init(e,t),yd.init(e,t)});function hB(e){return wx(_v,e)}function gB(e){return Sx(_v,e)}var Lk=R("ZodSymbol",(e,t)=>{R0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>FP(e,r,o,n)});function yB(e){return Tx(Lk,e)}var jk=R("ZodUndefined",(e,t)=>{O0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>HP(e,r,o,n)});function bB(e){return Ex(jk,e)}var Fk=R("ZodNull",(e,t)=>{C0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>qP(e,r,o,n)});function dh(e){return Ix(Fk,e)}var qk=R("ZodAny",(e,t)=>{z0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ZP(e,r,o,n)});function xB(){return Px(qk)}var Hk=R("ZodUnknown",(e,t)=>{N0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>WP(e,r,o,n)});function It(){return kx(Hk)}var Gk=R("ZodNever",(e,t)=>{M0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>VP(e,r,o,n)});function wv(e){return Ax(Gk,e)}var Vk=R("ZodVoid",(e,t)=>{B0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>GP(e,r,o,n)});function vB(e){return $x(Vk,e)}var ph=R("ZodDate",(e,t)=>{D0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(o,n,i)=>KP(e,o,n,i),e.min=(o,n)=>e.check(an(o,n)),e.max=(o,n)=>e.check(Zn(o,n));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});function _B(e){return Rx(ph,e)}var Zk=R("ZodArray",(e,t)=>{U0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ak(e,r,o,n),e.element=t.element,uh(e,"ZodArray",{min(r,o){return this.check(as(r,o))},nonempty(r){return this.check(as(1,r))},max(r,o){return this.check(Zc(r,o))},length(r,o){return this.check(Wc(r,o))},unwrap(){return this.element}})});function Ye(e,t){return MP(Zk,e,t)}function wB(e){let t=e._zod.def.shape;return Cr(Object.keys(t))}var fh=R("ZodObject",(e,t)=>{II.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ck(e,r,o,n),re.defineLazy(e,"shape",()=>t.shape),uh(e,"ZodObject",{keyof(){return Cr(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:It()})},loose(){return this.clone({...this._zod.def,catchall:It()})},strict(){return this.clone({...this._zod.def,catchall:wv()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return re.extend(this,r)},safeExtend(r){return re.safeExtend(this,r)},merge(r){return re.merge(this,r)},pick(r){return re.pick(this,r)},omit(r){return re.omit(this,r)},partial(...r){return re.partial(xd,this,r[0])},required(...r){return re.required(Tv,this,r[0])}})});function be(e,t){let r={type:"object",shape:e??{},...re.normalizeParams(t)};return new fh(r)}function SB(e,t){return new fh({type:"object",shape:e,catchall:wv(),...re.normalizeParams(t)})}function Or(e,t){return new fh({type:"object",shape:e,catchall:It(),...re.normalizeParams(t)})}var mh=R("ZodUnion",(e,t)=>{Gl.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vx(e,r,o,n),e.options=t.options});function Pt(e,t){return new mh({type:"union",options:e,...re.normalizeParams(t)})}var Wk=R("ZodXor",(e,t)=>{mh.init(e,t),j0.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vx(e,r,o,n),e.options=t.options});function TB(e,t){return new Wk({type:"union",options:e,inclusive:!1,...re.normalizeParams(t)})}var Kk=R("ZodDiscriminatedUnion",(e,t)=>{mh.init(e,t),F0.init(e,t)});function hh(e,t,r){return new Kk({type:"union",options:t,discriminator:e,...re.normalizeParams(r)})}var Jk=R("ZodIntersection",(e,t)=>{q0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>uk(e,r,o,n)});function bd(e,t){return new Jk({type:"intersection",left:e,right:t})}var Yk=R("ZodTuple",(e,t)=>{Cm.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>lk(e,r,o,n),e.rest=(r)=>e.clone({...e._zod.def,rest:r})});function Qk(e,t,r){let o=t instanceof ze,n=o?r:t;return new Yk({type:"tuple",items:e,rest:o?t:null,...re.normalizeParams(n)})}var dd=R("ZodRecord",(e,t)=>{H0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>dk(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function vt(e,t,r){if(!t||!t._zod)return new dd({type:"record",keyType:L(),valueType:e,...re.normalizeParams(t)});return new dd({type:"record",keyType:e,valueType:t,...re.normalizeParams(r)})}function EB(e,t,r){let o=$r(e);return o._zod.values=void 0,new dd({type:"record",keyType:o,valueType:t,...re.normalizeParams(r)})}function IB(e,t,r){return new dd({type:"record",keyType:e,valueType:t,mode:"loose",...re.normalizeParams(r)})}var Xk=R("ZodMap",(e,t)=>{G0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ik(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(yi(...r)),e.nonempty=(r)=>e.check(yi(1,r)),e.max=(...r)=>e.check(xa(...r)),e.size=(...r)=>e.check(Vc(...r))});function PB(e,t,r){return new Xk({type:"map",keyType:e,valueType:t,...re.normalizeParams(r)})}var eA=R("ZodSet",(e,t)=>{V0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>sk(e,r,o,n),e.min=(...r)=>e.check(yi(...r)),e.nonempty=(r)=>e.check(yi(1,r)),e.max=(...r)=>e.check(xa(...r)),e.size=(...r)=>e.check(Vc(...r))});function kB(e,t){return new eA({type:"set",valueType:e,...re.normalizeParams(t)})}var pd=R("ZodEnum",(e,t)=>{Z0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(o,n,i)=>JP(e,o,n,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new pd({...t,checks:[],...re.normalizeParams(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let s of o)if(r.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new pd({...t,checks:[],...re.normalizeParams(n),entries:i})}});function Cr(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new pd({type:"enum",entries:r,...re.normalizeParams(t)})}function AB(e,t){return new pd({type:"enum",entries:e,...re.normalizeParams(t)})}var tA=R("ZodLiteral",(e,t)=>{W0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>YP(e,r,o,n),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 Se(e,t){return new tA({type:"literal",values:Array.isArray(e)?e:[e],...re.normalizeParams(t)})}var rA=R("ZodFile",(e,t)=>{K0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ek(e,r,o,n),e.min=(r,o)=>e.check(yi(r,o)),e.max=(r,o)=>e.check(xa(r,o)),e.mime=(r,o)=>e.check(nd(Array.isArray(r)?r:[r],o))});function $B(e){return Dx(rA,e)}var nA=R("ZodTransform",(e,t)=>{J0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ok(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new jc(e.constructor.name);r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(re.issue(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(re.issue(s))}};let n=t.transform(r.value,r);if(n instanceof Promise)return n.then((i)=>(r.value=i,r.fallback=!0,r));return r.value=n,r.fallback=!0,r}});function Sv(e){return new nA({type:"transform",transform:e})}var xd=R("ZodOptional",(e,t)=>{zm.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zx(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Rt(e){return new xd({type:"optional",innerType:e})}var oA=R("ZodExactOptional",(e,t)=>{Y0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zx(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function iA(e){return new oA({type:"optional",innerType:e})}var sA=R("ZodNullable",(e,t)=>{Q0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>pk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ch(e){return new sA({type:"nullable",innerType:e})}function RB(e){return Rt(ch(e))}var aA=R("ZodDefault",(e,t)=>{X0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>mk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function cA(e,t){return new aA({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():re.shallowClone(t)}})}var uA=R("ZodPrefault",(e,t)=>{ex.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>hk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function lA(e,t){return new uA({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():re.shallowClone(t)}})}var Tv=R("ZodNonOptional",(e,t)=>{tx.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>fk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function dA(e,t){return new Tv({type:"nonoptional",innerType:e,...re.normalizeParams(t)})}var pA=R("ZodSuccess",(e,t)=>{rx.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>tk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function OB(e){return new pA({type:"success",innerType:e})}var fA=R("ZodCatch",(e,t)=>{nx.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>gk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function mA(e,t){return new fA({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var hA=R("ZodNaN",(e,t)=>{ox.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>QP(e,r,o,n)});function CB(e){return Ox(hA,e)}var gh=R("ZodPipe",(e,t)=>{Nm.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yk(e,r,o,n),e.in=t.in,e.out=t.out});function nv(e,t){return new gh({type:"pipe",in:e,out:t})}var yh=R("ZodCodec",(e,t)=>{gh.init(e,t),Vl.init(e,t)});function zB(e,t,r){return new yh({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function NB(e){let t=e._zod.def;return new yh({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var gA=R("ZodPreprocess",(e,t)=>{gh.init(e,t),PI.init(e,t)}),yA=R("ZodReadonly",(e,t)=>{ix.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>bk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function bA(e){return new yA({type:"readonly",innerType:e})}var xA=R("ZodTemplateLiteral",(e,t)=>{sx.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>XP(e,r,o,n)});function MB(e,t){return new xA({type:"template_literal",parts:e,...re.normalizeParams(t)})}var vA=R("ZodLazy",(e,t)=>{ux.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vk(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function _A(e){return new vA({type:"lazy",getter:e})}var wA=R("ZodPromise",(e,t)=>{cx.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function BB(e){return new wA({type:"promise",innerType:e})}var SA=R("ZodFunction",(e,t)=>{ax.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>nk(e,r,o,n)});function DB(e){return new SA({type:"function",input:Array.isArray(e?.input)?Qk(e?.input):e?.input??Ye(It()),output:e?.output??It()})}var bh=R("ZodCustom",(e,t)=>{lx.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>rk(e,r,o,n)});function UB(e){let t=new Tt({check:"custom"});return t._zod.check=e,t}function Ev(e,t){return Ux(bh,e??(()=>!0),t)}function TA(e,t={}){return Lx(bh,e,t)}function EA(e,t){return jx(e,t)}var LB=Fx,jB=qx;function FB(e,t={}){let r=new bh({type:"custom",check:"custom",fn:(o)=>o instanceof e,abort:!0,...re.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=(o)=>{if(!(o.value instanceof e))o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var qB=(...e)=>Hx({Codec:yh,Boolean:gd,String:fd},...e);function HB(e){let t=_A(()=>Pt([L(e),ut(),rr(),dh(),Ye(t),vt(L(),t)]));return t}function xh(e,t){return new gA({type:"pipe",in:Sv(e),out:t})}var foe={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"};function moe(e){Xt({customError:e})}function hoe(){return Xt().customError}var IA;(function(e){})(IA||(IA={}));var ge={...sh,...Yx,iso:Ea},goe=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function yoe(e,t){let r=e.$schema;if(r==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(r==="http://json-schema.org/draft-07/schema#")return"draft-7";if(r==="http://json-schema.org/draft-04/schema#")return"draft-4";return t??"draft-2020-12"}function boe(e,t){if(!e.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let o=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1];if(!n||!t.defs[n])throw Error(`Reference not found: ${e}`);return t.defs[n]}throw Error(`Reference not found: ${e}`)}function GB(e,t){if(e.not!==void 0){if(typeof e.not==="object"&&Object.keys(e.not).length===0)return ge.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return ge.lazy(()=>{if(!t.refs.has(n))throw Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let i=boe(n,t),s=Jr(i,t);return t.refs.set(n,s),t.processing.delete(n),s}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return ge.null();if(n.length===0)return ge.never();if(n.length===1)return ge.literal(n[0]);if(n.every((s)=>typeof s==="string"))return ge.enum(n);let i=n.map((s)=>ge.literal(s));if(i.length<2)return i[0];return ge.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return ge.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map((i)=>{let s={...e,type:i};return GB(s,t)});if(n.length===0)return ge.never();if(n.length===1)return n[0];return ge.union(n)}if(!r)return ge.any();let o;switch(r){case"string":{let n=ge.string();if(e.format){let i=e.format;if(i==="email")n=n.check(ge.email());else if(i==="uri"||i==="uri-reference")n=n.check(ge.url());else if(i==="uuid"||i==="guid")n=n.check(ge.uuid());else if(i==="date-time")n=n.check(ge.iso.datetime());else if(i==="date")n=n.check(ge.iso.date());else if(i==="time")n=n.check(ge.iso.time());else if(i==="duration")n=n.check(ge.iso.duration());else if(i==="ipv4")n=n.check(ge.ipv4());else if(i==="ipv6")n=n.check(ge.ipv6());else if(i==="mac")n=n.check(ge.mac());else if(i==="cidr")n=n.check(ge.cidrv4());else if(i==="cidr-v6")n=n.check(ge.cidrv6());else if(i==="base64")n=n.check(ge.base64());else if(i==="base64url")n=n.check(ge.base64url());else if(i==="e164")n=n.check(ge.e164());else if(i==="jwt")n=n.check(ge.jwt());else if(i==="emoji")n=n.check(ge.emoji());else if(i==="nanoid")n=n.check(ge.nanoid());else if(i==="cuid")n=n.check(ge.cuid());else if(i==="cuid2")n=n.check(ge.cuid2());else if(i==="ulid")n=n.check(ge.ulid());else if(i==="xid")n=n.check(ge.xid());else if(i==="ksuid")n=n.check(ge.ksuid())}if(typeof e.minLength==="number")n=n.min(e.minLength);if(typeof e.maxLength==="number")n=n.max(e.maxLength);if(e.pattern)n=n.regex(new RegExp(e.pattern));o=n;break}case"number":case"integer":{let n=r==="integer"?ge.number().int():ge.number();if(typeof e.minimum==="number")n=n.min(e.minimum);if(typeof e.maximum==="number")n=n.max(e.maximum);if(typeof e.exclusiveMinimum==="number")n=n.gt(e.exclusiveMinimum);else if(e.exclusiveMinimum===!0&&typeof e.minimum==="number")n=n.gt(e.minimum);if(typeof e.exclusiveMaximum==="number")n=n.lt(e.exclusiveMaximum);else if(e.exclusiveMaximum===!0&&typeof e.maximum==="number")n=n.lt(e.maximum);if(typeof e.multipleOf==="number")n=n.multipleOf(e.multipleOf);o=n;break}case"boolean":{o=ge.boolean();break}case"null":{o=ge.null();break}case"object":{let n={},i=e.properties||{},s=new Set(e.required||[]);for(let[c,u]of Object.entries(i)){let d=Jr(u,t);n[c]=s.has(c)?d:d.optional()}if(e.propertyNames){let c=Jr(e.propertyNames,t),u=e.additionalProperties&&typeof e.additionalProperties==="object"?Jr(e.additionalProperties,t):ge.any();if(Object.keys(n).length===0){o=ge.record(c,u);break}let d=ge.object(n).passthrough(),p=ge.looseRecord(c,u);o=ge.intersection(d,p);break}if(e.patternProperties){let c=e.patternProperties,u=Object.keys(c),d=[];for(let m of u){let h=Jr(c[m],t),y=ge.string().regex(new RegExp(m));d.push(ge.looseRecord(y,h))}let p=[];if(Object.keys(n).length>0)p.push(ge.object(n).passthrough());if(p.push(...d),p.length===0)o=ge.object({}).passthrough();else if(p.length===1)o=p[0];else{let m=ge.intersection(p[0],p[1]);for(let h=2;h<p.length;h++)m=ge.intersection(m,p[h]);o=m}break}let a=ge.object(n);if(e.additionalProperties===!1)o=a.strict();else if(typeof e.additionalProperties==="object")o=a.catchall(Jr(e.additionalProperties,t));else o=a.passthrough();break}case"array":{let{prefixItems:n,items:i}=e;if(n&&Array.isArray(n)){let s=n.map((c)=>Jr(c,t)),a=i&&typeof i==="object"&&!Array.isArray(i)?Jr(i,t):void 0;if(a)o=ge.tuple(s).rest(a);else o=ge.tuple(s);if(typeof e.minItems==="number")o=o.check(ge.minLength(e.minItems));if(typeof e.maxItems==="number")o=o.check(ge.maxLength(e.maxItems))}else if(Array.isArray(i)){let s=i.map((c)=>Jr(c,t)),a=e.additionalItems&&typeof e.additionalItems==="object"?Jr(e.additionalItems,t):void 0;if(a)o=ge.tuple(s).rest(a);else o=ge.tuple(s);if(typeof e.minItems==="number")o=o.check(ge.minLength(e.minItems));if(typeof e.maxItems==="number")o=o.check(ge.maxLength(e.maxItems))}else if(i!==void 0){let s=Jr(i,t),a=ge.array(s);if(typeof e.minItems==="number")a=a.min(e.minItems);if(typeof e.maxItems==="number")a=a.max(e.maxItems);o=a}else o=ge.array(ge.any());break}default:throw Error(`Unsupported type: ${r}`)}return o}function Jr(e,t){if(typeof e==="boolean")return e?ge.any():ge.never();let r=GB(e,t),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map((u)=>Jr(u,t)),c=ge.union(a);r=o?ge.intersection(r,c):c}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map((u)=>Jr(u,t)),c=ge.xor(a);r=o?ge.intersection(r,c):c}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:ge.any();else{let a=o?r:Jr(e.allOf[0],t),c=o?0:1;for(let u=c;u<e.allOf.length;u++)a=ge.intersection(a,Jr(e.allOf[u],t));r=a}if(e.nullable===!0&&t.version==="openapi-3.0")r=ge.nullable(r);if(e.readOnly===!0)r=ge.readonly(r);if(e.default!==void 0)r=r.default(e.default);let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)if(a in e)n[a]=e[a];let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)if(a in e)n[a]=e[a];for(let a of Object.keys(e))if(!goe.has(a))n[a]=e[a];if(Object.keys(n).length>0)t.registry.add(r,n);if(e.description)r=r.describe(e.description);return r}function VB(e,t){if(typeof e==="boolean")return e?ge.any():ge.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=yoe(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??Rr};return Jr(r,i)}var PA={};Pn(PA,{bigint:()=>woe,boolean:()=>_oe,date:()=>Soe,number:()=>voe,string:()=>xoe});function xoe(e){return IP(fd,e)}function voe(e){return OP(hd,e)}function _oe(e){return CP(gd,e)}function woe(e){return zP(yd,e)}function Soe(e){return NP(ph,e)}Xt(Mm());var kA="2025-11-25";var ZB=[kA,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ia="io.modelcontextprotocol/related-task",Pv="2.0",mr=Ev((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),WB=Pt([L(),ut().int()]),KB=L(),yEe=Or({ttl:ut().optional(),pollInterval:ut().optional()}),Toe=be({ttl:ut().optional()}),Eoe=be({taskId:L()}),AA=Or({progressToken:WB.optional(),[Ia]:Eoe.optional()}),Wn=be({_meta:AA.optional()}),vh=Wn.extend({task:Toe.optional()}),JB=(e)=>vh.safeParse(e).success,zr=be({method:L(),params:Wn.loose().optional()}),io=be({_meta:AA.optional()}),so=be({method:L(),params:io.loose().optional()}),Nr=Or({_meta:AA.optional()}),kv=Pt([L(),ut().int()]),YB=be({jsonrpc:Se(Pv),id:kv,...zr.shape}).strict(),$A=(e)=>YB.safeParse(e).success,QB=be({jsonrpc:Se(Pv),...so.shape}).strict(),XB=(e)=>QB.safeParse(e).success,RA=be({jsonrpc:Se(Pv),id:kv,result:Nr}).strict(),_h=(e)=>RA.safeParse(e).success;var ke;(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"})(ke||(ke={}));var OA=be({jsonrpc:Se(Pv),id:kv.optional(),error:be({code:ut().int(),message:L(),data:It().optional()})}).strict();var eD=(e)=>OA.safeParse(e).success;var tD=Pt([YB,QB,RA,OA]),bEe=Pt([RA,OA]),Av=Nr.strict(),Ioe=io.extend({requestId:kv.optional(),reason:L().optional()}),$v=so.extend({method:Se("notifications/cancelled"),params:Ioe}),Poe=be({src:L(),mimeType:L().optional(),sizes:Ye(L()).optional(),theme:Cr(["light","dark"]).optional()}),wh=be({icons:Ye(Poe).optional()}),vd=be({name:L(),title:L().optional()}),rD=vd.extend({...vd.shape,...wh.shape,version:L(),websiteUrl:L().optional(),description:L().optional()}),koe=bd(be({applyDefaults:rr().optional()}),vt(L(),It())),Aoe=xh((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},bd(be({form:koe.optional(),url:mr.optional()}),vt(L(),It()).optional())),$oe=Or({list:mr.optional(),cancel:mr.optional(),requests:Or({sampling:Or({createMessage:mr.optional()}).optional(),elicitation:Or({create:mr.optional()}).optional()}).optional()}),Roe=Or({list:mr.optional(),cancel:mr.optional(),requests:Or({tools:Or({call:mr.optional()}).optional()}).optional()}),Ooe=be({experimental:vt(L(),mr).optional(),sampling:be({context:mr.optional(),tools:mr.optional()}).optional(),elicitation:Aoe.optional(),roots:be({listChanged:rr().optional()}).optional(),tasks:$oe.optional(),extensions:vt(L(),mr).optional()}),Coe=Wn.extend({protocolVersion:L(),capabilities:Ooe,clientInfo:rD}),CA=zr.extend({method:Se("initialize"),params:Coe});var zoe=be({experimental:vt(L(),mr).optional(),logging:mr.optional(),completions:mr.optional(),prompts:be({listChanged:rr().optional()}).optional(),resources:be({subscribe:rr().optional(),listChanged:rr().optional()}).optional(),tools:be({listChanged:rr().optional()}).optional(),tasks:Roe.optional(),extensions:vt(L(),mr).optional()}),Noe=Nr.extend({protocolVersion:L(),capabilities:zoe,serverInfo:rD,instructions:L().optional()}),zA=so.extend({method:Se("notifications/initialized"),params:io.optional()});var Rv=zr.extend({method:Se("ping"),params:Wn.optional()}),Moe=be({progress:ut(),total:Rt(ut()),message:Rt(L())}),Boe=be({...io.shape,...Moe.shape,progressToken:WB}),Ov=so.extend({method:Se("notifications/progress"),params:Boe}),Doe=Wn.extend({cursor:KB.optional()}),Sh=zr.extend({params:Doe.optional()}),Th=Nr.extend({nextCursor:KB.optional()}),Uoe=Cr(["working","input_required","completed","failed","cancelled"]),Eh=be({taskId:L(),status:Uoe,ttl:Pt([ut(),dh()]),createdAt:L(),lastUpdatedAt:L(),pollInterval:Rt(ut()),statusMessage:Rt(L())}),_d=Nr.extend({task:Eh}),Loe=io.merge(Eh),Ih=so.extend({method:Se("notifications/tasks/status"),params:Loe}),Cv=zr.extend({method:Se("tasks/get"),params:Wn.extend({taskId:L()})}),zv=Nr.merge(Eh),Nv=zr.extend({method:Se("tasks/result"),params:Wn.extend({taskId:L()})}),xEe=Nr.loose(),Mv=Sh.extend({method:Se("tasks/list")}),Bv=Th.extend({tasks:Ye(Eh)}),Dv=zr.extend({method:Se("tasks/cancel"),params:Wn.extend({taskId:L()})}),nD=Nr.merge(Eh),oD=be({uri:L(),mimeType:Rt(L()),_meta:vt(L(),It()).optional()}),iD=oD.extend({text:L()}),NA=L().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),sD=oD.extend({blob:NA}),Ph=Cr(["user","assistant"]),wd=be({audience:Ye(Ph).optional(),priority:ut().min(0).max(1).optional(),lastModified:Ea.datetime({offset:!0}).optional()}),aD=be({...vd.shape,...wh.shape,uri:L(),description:Rt(L()),mimeType:Rt(L()),size:Rt(ut()),annotations:wd.optional(),_meta:Rt(Or({}))}),joe=be({...vd.shape,...wh.shape,uriTemplate:L(),description:Rt(L()),mimeType:Rt(L()),annotations:wd.optional(),_meta:Rt(Or({}))}),Uv=Sh.extend({method:Se("resources/list")}),Foe=Th.extend({resources:Ye(aD)}),Lv=Sh.extend({method:Se("resources/templates/list")}),qoe=Th.extend({resourceTemplates:Ye(joe)}),MA=Wn.extend({uri:L()}),Hoe=MA,jv=zr.extend({method:Se("resources/read"),params:Hoe}),Goe=Nr.extend({contents:Ye(Pt([iD,sD]))}),Voe=so.extend({method:Se("notifications/resources/list_changed"),params:io.optional()}),Zoe=MA,Woe=zr.extend({method:Se("resources/subscribe"),params:Zoe}),Koe=MA,Joe=zr.extend({method:Se("resources/unsubscribe"),params:Koe}),Yoe=io.extend({uri:L()}),Qoe=so.extend({method:Se("notifications/resources/updated"),params:Yoe}),Xoe=be({name:L(),description:Rt(L()),required:Rt(rr())}),eie=be({...vd.shape,...wh.shape,description:Rt(L()),arguments:Rt(Ye(Xoe)),_meta:Rt(Or({}))}),Fv=Sh.extend({method:Se("prompts/list")}),tie=Th.extend({prompts:Ye(eie)}),rie=Wn.extend({name:L(),arguments:vt(L(),L()).optional()}),qv=zr.extend({method:Se("prompts/get"),params:rie}),BA=be({type:Se("text"),text:L(),annotations:wd.optional(),_meta:vt(L(),It()).optional()}),DA=be({type:Se("image"),data:NA,mimeType:L(),annotations:wd.optional(),_meta:vt(L(),It()).optional()}),UA=be({type:Se("audio"),data:NA,mimeType:L(),annotations:wd.optional(),_meta:vt(L(),It()).optional()}),nie=be({type:Se("tool_use"),name:L(),id:L(),input:vt(L(),It()),_meta:vt(L(),It()).optional()}),oie=be({type:Se("resource"),resource:Pt([iD,sD]),annotations:wd.optional(),_meta:vt(L(),It()).optional()}),iie=aD.extend({type:Se("resource_link")}),LA=Pt([BA,DA,UA,iie,oie]),sie=be({role:Ph,content:LA}),aie=Nr.extend({description:L().optional(),messages:Ye(sie)}),cie=so.extend({method:Se("notifications/prompts/list_changed"),params:io.optional()}),uie=be({title:L().optional(),readOnlyHint:rr().optional(),destructiveHint:rr().optional(),idempotentHint:rr().optional(),openWorldHint:rr().optional()}),lie=be({taskSupport:Cr(["required","optional","forbidden"]).optional()}),cD=be({...vd.shape,...wh.shape,description:L().optional(),inputSchema:be({type:Se("object"),properties:vt(L(),mr).optional(),required:Ye(L()).optional()}).catchall(It()),outputSchema:be({type:Se("object"),properties:vt(L(),mr).optional(),required:Ye(L()).optional()}).catchall(It()).optional(),annotations:uie.optional(),execution:lie.optional(),_meta:vt(L(),It()).optional()}),Hv=Sh.extend({method:Se("tools/list")}),die=Th.extend({tools:Ye(cD)}),Gv=Nr.extend({content:Ye(LA).default([]),structuredContent:vt(L(),It()).optional(),isError:rr().optional()}),vEe=Gv.or(Nr.extend({toolResult:It()})),pie=vh.extend({name:L(),arguments:vt(L(),It()).optional()}),Sd=zr.extend({method:Se("tools/call"),params:pie}),fie=so.extend({method:Se("notifications/tools/list_changed"),params:io.optional()}),_Ee=be({autoRefresh:rr().default(!0),debounceMs:ut().int().nonnegative().default(300)}),kh=Cr(["debug","info","notice","warning","error","critical","alert","emergency"]),mie=Wn.extend({level:kh}),jA=zr.extend({method:Se("logging/setLevel"),params:mie}),hie=io.extend({level:kh,logger:L().optional(),data:It()}),gie=so.extend({method:Se("notifications/message"),params:hie}),yie=be({name:L().optional()}),bie=be({hints:Ye(yie).optional(),costPriority:ut().min(0).max(1).optional(),speedPriority:ut().min(0).max(1).optional(),intelligencePriority:ut().min(0).max(1).optional()}),xie=be({mode:Cr(["auto","required","none"]).optional()}),vie=be({type:Se("tool_result"),toolUseId:L().describe("The unique identifier for the corresponding tool call."),content:Ye(LA).default([]),structuredContent:be({}).loose().optional(),isError:rr().optional(),_meta:vt(L(),It()).optional()}),_ie=hh("type",[BA,DA,UA]),Iv=hh("type",[BA,DA,UA,nie,vie]),wie=be({role:Ph,content:Pt([Iv,Ye(Iv)]),_meta:vt(L(),It()).optional()}),Sie=vh.extend({messages:Ye(wie),modelPreferences:bie.optional(),systemPrompt:L().optional(),includeContext:Cr(["none","thisServer","allServers"]).optional(),temperature:ut().optional(),maxTokens:ut().int(),stopSequences:Ye(L()).optional(),metadata:mr.optional(),tools:Ye(cD).optional(),toolChoice:xie.optional()}),Tie=zr.extend({method:Se("sampling/createMessage"),params:Sie}),Ah=Nr.extend({model:L(),stopReason:Rt(Cr(["endTurn","stopSequence","maxTokens"]).or(L())),role:Ph,content:_ie}),FA=Nr.extend({model:L(),stopReason:Rt(Cr(["endTurn","stopSequence","maxTokens","toolUse"]).or(L())),role:Ph,content:Pt([Iv,Ye(Iv)])}),Eie=be({type:Se("boolean"),title:L().optional(),description:L().optional(),default:rr().optional()}),Iie=be({type:Se("string"),title:L().optional(),description:L().optional(),minLength:ut().optional(),maxLength:ut().optional(),format:Cr(["email","uri","date","date-time"]).optional(),default:L().optional()}),Pie=be({type:Cr(["number","integer"]),title:L().optional(),description:L().optional(),minimum:ut().optional(),maximum:ut().optional(),default:ut().optional()}),kie=be({type:Se("string"),title:L().optional(),description:L().optional(),enum:Ye(L()),default:L().optional()}),Aie=be({type:Se("string"),title:L().optional(),description:L().optional(),oneOf:Ye(be({const:L(),title:L()})),default:L().optional()}),$ie=be({type:Se("string"),title:L().optional(),description:L().optional(),enum:Ye(L()),enumNames:Ye(L()).optional(),default:L().optional()}),Rie=Pt([kie,Aie]),Oie=be({type:Se("array"),title:L().optional(),description:L().optional(),minItems:ut().optional(),maxItems:ut().optional(),items:be({type:Se("string"),enum:Ye(L())}),default:Ye(L()).optional()}),Cie=be({type:Se("array"),title:L().optional(),description:L().optional(),minItems:ut().optional(),maxItems:ut().optional(),items:be({anyOf:Ye(be({const:L(),title:L()}))}),default:Ye(L()).optional()}),zie=Pt([Oie,Cie]),Nie=Pt([$ie,Rie,zie]),Mie=Pt([Nie,Eie,Iie,Pie]),Bie=vh.extend({mode:Se("form").optional(),message:L(),requestedSchema:be({type:Se("object"),properties:vt(L(),Mie),required:Ye(L()).optional()})}),Die=vh.extend({mode:Se("url"),message:L(),elicitationId:L(),url:L().url()}),Uie=Pt([Bie,Die]),Lie=zr.extend({method:Se("elicitation/create"),params:Uie}),jie=io.extend({elicitationId:L()}),Fie=so.extend({method:Se("notifications/elicitation/complete"),params:jie}),Td=Nr.extend({action:Cr(["accept","decline","cancel"]),content:xh((e)=>e===null?void 0:e,vt(L(),Pt([L(),ut(),rr(),Ye(L())])).optional())}),qie=be({type:Se("ref/resource"),uri:L()});var Hie=be({type:Se("ref/prompt"),name:L()}),Gie=Wn.extend({ref:Pt([Hie,qie]),argument:be({name:L(),value:L()}),context:be({arguments:vt(L(),L()).optional()}).optional()}),Vv=zr.extend({method:Se("completion/complete"),params:Gie});function uD(e){if(e.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function lD(e){if(e.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var Vie=Nr.extend({completion:Or({values:Ye(L()).max(100),total:Rt(ut().int()),hasMore:Rt(rr())})}),Zie=be({uri:L().startsWith("file://"),name:L().optional(),_meta:vt(L(),It()).optional()}),Wie=zr.extend({method:Se("roots/list"),params:Wn.optional()}),qA=Nr.extend({roots:Ye(Zie)}),Kie=so.extend({method:Se("notifications/roots/list_changed"),params:io.optional()}),wEe=Pt([Rv,CA,Vv,jA,qv,Fv,Uv,Lv,jv,Woe,Joe,Sd,Hv,Cv,Nv,Mv,Dv]),SEe=Pt([$v,Ov,zA,Kie,Ih]),TEe=Pt([Av,Ah,FA,Td,qA,zv,Bv,_d]),EEe=Pt([Rv,Tie,Lie,Wie,Cv,Nv,Mv,Dv]),IEe=Pt([$v,Ov,gie,Qoe,Voe,fie,cie,Ih,Fie]),PEe=Pt([Av,Noe,Vie,aie,tie,Foe,qoe,Goe,Gv,die,zv,Bv,_d]);class Te 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===ke.UrlElicitationRequired&&r){let o=r;if(o.elicitations)return new dD(o.elicitations,t)}return new Te(e,t,r)}}class dD extends Te{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(ke.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Pa(e){return e==="completed"||e==="failed"||e==="cancelled"}var fD=Symbol("Let zodToJsonSchema decide on which parser to use");var pD={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"},mD=(e)=>typeof e==="string"?{...pD,name:e}:{...pD,...e};var hD=(e)=>{let t=mD(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(([o,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,o],jsonSchema:void 0}]))}};function HA(e,t,r,o){if(!o?.errorMessages)return;if(r)e.errorMessage={...e.errorMessage,[t]:r}}function rt(e,t,r,o,n){e[t]=r,HA(e,t,o,n)}var Zv=(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 Gt(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Zv(t,e.currentPath):t.join("/")}}function gD(e,t){let r={type:"array"};if(e.type?._def&&e.type?._def?.typeName!==ie.ZodAny)r.items=Ce(e.type._def,{...t,currentPath:[...t.currentPath,"items"]});if(e.minLength)rt(r,"minItems",e.minLength.value,e.minLength.message,t);if(e.maxLength)rt(r,"maxItems",e.maxLength.value,e.maxLength.message,t);if(e.exactLength)rt(r,"minItems",e.exactLength.value,e.exactLength.message,t),rt(r,"maxItems",e.exactLength.value,e.exactLength.message,t);return r}function yD(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let o of e.checks)switch(o.kind){case"min":if(t.target==="jsonSchema7")if(o.inclusive)rt(r,"minimum",o.value,o.message,t);else rt(r,"exclusiveMinimum",o.value,o.message,t);else{if(!o.inclusive)r.exclusiveMinimum=!0;rt(r,"minimum",o.value,o.message,t)}break;case"max":if(t.target==="jsonSchema7")if(o.inclusive)rt(r,"maximum",o.value,o.message,t);else rt(r,"exclusiveMaximum",o.value,o.message,t);else{if(!o.inclusive)r.exclusiveMaximum=!0;rt(r,"maximum",o.value,o.message,t)}break;case"multipleOf":rt(r,"multipleOf",o.value,o.message,t);break}return r}function bD(){return{type:"boolean"}}function Wv(e,t){return Ce(e.type._def,t)}var xD=(e,t)=>Ce(e.innerType._def,t);function GA(e,t,r){let o=r??t.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((n,i)=>GA(e,t,n))};switch(o){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Jie(e,t)}}var Jie=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let o of e.checks)switch(o.kind){case"min":rt(r,"minimum",o.value,o.message,t);break;case"max":rt(r,"maximum",o.value,o.message,t);break}return r};function vD(e,t){return{...Ce(e.innerType._def,t),default:e.defaultValue()}}function _D(e,t){return t.effectStrategy==="input"?Ce(e.schema._def,t):Gt(t)}function wD(e){return{type:"string",enum:Array.from(e.values)}}var Yie=(e)=>{if("type"in e&&e.type==="string")return!1;return"allOf"in e};function SD(e,t){let r=[Ce(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ce(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((i)=>!!i),o=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,n=[];return r.forEach((i)=>{if(Yie(i)){if(n.push(...i.allOf),i.unevaluatedProperties===void 0)o=void 0}else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...c}=i;s=c}else o=void 0;n.push(s)}}),n.length?{allOf:n,...o}:void 0}function TD(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 VA=void 0,Oo={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(VA===void 0)VA=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return VA},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 Kv(e,t){let r={type:"string"};if(e.checks)for(let o of e.checks)switch(o.kind){case"min":rt(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,o.value):o.value,o.message,t);break;case"max":rt(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,o.value):o.value,o.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Co(r,"email",o.message,t);break;case"format:idn-email":Co(r,"idn-email",o.message,t);break;case"pattern:zod":un(r,Oo.email,o.message,t);break}break;case"url":Co(r,"uri",o.message,t);break;case"uuid":Co(r,"uuid",o.message,t);break;case"regex":un(r,o.regex,o.message,t);break;case"cuid":un(r,Oo.cuid,o.message,t);break;case"cuid2":un(r,Oo.cuid2,o.message,t);break;case"startsWith":un(r,RegExp(`^${ZA(o.value,t)}`),o.message,t);break;case"endsWith":un(r,RegExp(`${ZA(o.value,t)}$`),o.message,t);break;case"datetime":Co(r,"date-time",o.message,t);break;case"date":Co(r,"date",o.message,t);break;case"time":Co(r,"time",o.message,t);break;case"duration":Co(r,"duration",o.message,t);break;case"length":rt(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,o.value):o.value,o.message,t),rt(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,o.value):o.value,o.message,t);break;case"includes":{un(r,RegExp(ZA(o.value,t)),o.message,t);break}case"ip":{if(o.version!=="v6")Co(r,"ipv4",o.message,t);if(o.version!=="v4")Co(r,"ipv6",o.message,t);break}case"base64url":un(r,Oo.base64url,o.message,t);break;case"jwt":un(r,Oo.jwt,o.message,t);break;case"cidr":{if(o.version!=="v6")un(r,Oo.ipv4Cidr,o.message,t);if(o.version!=="v4")un(r,Oo.ipv6Cidr,o.message,t);break}case"emoji":un(r,Oo.emoji(),o.message,t);break;case"ulid":{un(r,Oo.ulid,o.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Co(r,"binary",o.message,t);break}case"contentEncoding:base64":{rt(r,"contentEncoding","base64",o.message,t);break}case"pattern:zod":{un(r,Oo.base64,o.message,t);break}}break}case"nanoid":un(r,Oo.nanoid,o.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:((n)=>{})(o)}return r}function ZA(e,t){return t.patternStrategy==="escape"?Xie(e):e}var Qie=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Xie(e){let t="";for(let r=0;r<e.length;r++){if(!Qie.has(e[r]))t+="\\";t+=e[r]}return t}function Co(e,t,r,o){if(e.format||e.anyOf?.some((n)=>n.format)){if(!e.anyOf)e.anyOf=[];if(e.format){if(e.anyOf.push({format:e.format,...e.errorMessage&&o.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&&o.errorMessages&&{errorMessage:{format:r}}})}else rt(e,"format",t,r,o)}function un(e,t,r,o){if(e.pattern||e.allOf?.some((n)=>n.pattern)){if(!e.allOf)e.allOf=[];if(e.pattern){if(e.allOf.push({pattern:e.pattern,...e.errorMessage&&o.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:ED(t,o),...r&&o.errorMessages&&{errorMessage:{pattern:r}}})}else rt(e,"pattern",ED(t,o),r,o)}function ED(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")},o=r.i?e.source.toLowerCase():e.source,n="",i=!1,s=!1,a=!1;for(let c=0;c<o.length;c++){if(i){n+=o[c],i=!1;continue}if(r.i){if(s){if(o[c].match(/[a-z]/)){if(a)n+=o[c],n+=`${o[c-2]}-${o[c]}`.toUpperCase(),a=!1;else if(o[c+1]==="-"&&o[c+2]?.match(/[a-z]/))n+=o[c],a=!0;else n+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){n+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){n+=`(^|(?<=[\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 u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){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 wa(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},p=c.ref;if(c.ref=null,p){o(p);let h=e.seen.get(p),y=h.schema;if(y.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))u.allOf=u.allOf??[],u.allOf.push(y);else Object.assign(u,y);if(Object.assign(u,d),a._zod.parent===p)for(let S in u){if(S==="$ref"||S==="allOf")continue;if(!(S in d))delete u[S]}if(y.$ref&&h.def)for(let S in u){if(S==="$ref"||S==="allOf")continue;if(S in h.def&&JSON.stringify(u[S])===JSON.stringify(h.def[S]))delete u[S]}}let m=a._zod.parent;if(m&&m!==p){o(m);let h=e.seen.get(m);if(h?.schema.$ref){if(u.$ref=h.schema.$ref,h.def)for(let y in u){if(y==="$ref"||y==="allOf")continue;if(y in h.def&&JSON.stringify(u[y])===JSON.stringify(h.def[y]))delete u[y]}}}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let n={};if(e.target==="draft-2020-12")n.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")n.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")n.$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");n.$id=e.external.uri(a)}Object.assign(n,r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&n.id===i)delete n.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")n.$defs=s;else n.definitions=s;try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:ud(t,"input",e.processors),output:ud(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function cn(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return cn(o.element,r);if(o.type==="set")return cn(o.valueType,r);if(o.type==="lazy")return cn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return cn(o.innerType,r);if(o.type==="intersection")return cn(o.left,r)||cn(o.right,r);if(o.type==="record"||o.type==="map")return cn(o.keyType,r)||cn(o.valueType,r);if(o.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return cn(o.in,r)||cn(o.out,r)}if(o.type==="object"){for(let n in o.shape)if(cn(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(cn(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(cn(n,r))return!0;if(o.rest&&cn(o.rest,r))return!0;return!1}return!1}var BP=(e,t={})=>(r)=>{let o=va({...r,processors:t});return gt(e,o),_a(o,e),wa(o,e)},ud=(e,t,r={})=>(o)=>{let{libraryOptions:n,target:i}=o??{},s=va({...n??{},target:i,io:t,processors:r});return gt(e,s),_a(s,e),wa(s,e)};var ioe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},DP=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof i==="number")n.minLength=i;if(typeof s==="number")n.maxLength=s;if(a){if(n.format=ioe[a]??a,n.format==="")delete n.format;if(a==="time")delete n.format}if(u)n.contentEncoding=u;if(c&&c.size>0){let d=[...c];if(d.length===1)n.pattern=d[0].source;else if(d.length>1)n.allOf=[...d.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},UP=(e,t,r,o)=>{let n=r,{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))n.type="integer";else n.type="number";let p=typeof d==="number"&&d>=(i??Number.NEGATIVE_INFINITY),m=typeof u==="number"&&u<=(s??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";if(p)if(h)n.minimum=d,n.exclusiveMinimum=!0;else n.exclusiveMinimum=d;else if(typeof i==="number")n.minimum=i;if(m)if(h)n.maximum=u,n.exclusiveMaximum=!0;else n.exclusiveMaximum=u;else if(typeof s==="number")n.maximum=s;if(typeof c==="number")n.multipleOf=c},LP=(e,t,r,o)=>{r.type="boolean"},jP=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},FP=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},qP=(e,t,r,o)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},HP=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},GP=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},VP=(e,t,r,o)=>{r.not={}},ZP=(e,t,r,o)=>{},WP=(e,t,r,o)=>{},KP=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},JP=(e,t,r,o)=>{let n=e._zod.def,i=vm(n.entries);if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";r.enum=i},YP=(e,t,r,o)=>{let n=e._zod.def,i=[];for(let s of n.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}},QP=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},XP=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},ek=(e,t,r,o)=>{let n=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(n,i);else Object.assign(n,i),n.anyOf=c.map((u)=>({contentMediaType:u}));else Object.assign(n,i)},tk=(e,t,r,o)=>{r.type="boolean"},rk=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},nk=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},ok=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},ik=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},sk=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},ak=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")n.minItems=s;if(typeof a==="number")n.maxItems=a;n.type="array",n.items=gt(i.element,t,{...o,path:[...o.path,"items"]})},ck=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object",n.properties={};let s=i.shape;for(let u in s)n.properties[u]=gt(s[u],t,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(s)),c=new Set([...a].filter((u)=>{let d=i.shape[u]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(c.size>0)n.required=Array.from(c);if(i.catchall?._zod.def.type==="never")n.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")n.additionalProperties=!1}else if(i.catchall)n.additionalProperties=gt(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Vx=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>gt(a,t,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));if(i)r.oneOf=s;else r.anyOf=s},uk=(e,t,r,o)=>{let n=e._zod.def,i=gt(n.left,t,{...o,path:[...o.path,"allOf",0]}),s=gt(n.right,t,{...o,path:[...o.path,"allOf",1]}),a=(u)=>("allOf"in u)&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c},lk=(e,t,r,o)=>{let n=r,i=e._zod.def;n.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((m,h)=>gt(m,t,{...o,path:[...o.path,s,h]})),u=i.rest?gt(i.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(n.prefixItems=c,u)n.items=u}else if(t.target==="openapi-3.0"){if(n.items={anyOf:c},u)n.items.anyOf.push(u);if(n.minItems=c.length,!u)n.maxItems=c.length}else if(n.items=c,u)n.additionalItems=u;let{minimum:d,maximum:p}=e._zod.bag;if(typeof d==="number")n.minItems=d;if(typeof p==="number")n.maxItems=p},dk=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let s=i.keyType,c=s._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let d=gt(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let p of c)n.patternProperties[p.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")n.propertyNames=gt(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});n.additionalProperties=gt(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=s._zod.values;if(u){let d=[...u].filter((p)=>typeof p==="string"||typeof p==="number");if(d.length>0)n.required=d}},pk=(e,t,r,o)=>{let n=e._zod.def,i=gt(n.innerType,t,o),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=n.innerType,r.nullable=!0;else r.anyOf=[i,{type:"null"}]},fk=(e,t,r,o)=>{let n=e._zod.def;gt(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},mk=(e,t,r,o)=>{let n=e._zod.def;gt(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},hk=(e,t,r,o)=>{let n=e._zod.def;gt(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(n.defaultValue))},gk=(e,t,r,o)=>{let n=e._zod.def;gt(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},yk=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?n.out:n.in:n.out;gt(s,t,o);let a=t.seen.get(e);a.ref=s},bk=(e,t,r,o)=>{let n=e._zod.def;gt(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},xk=(e,t,r,o)=>{let n=e._zod.def;gt(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Zx=(e,t,r,o)=>{let n=e._zod.def;gt(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},vk=(e,t,r,o)=>{let n=e._zod.innerType;gt(n,t,o);let i=t.seen.get(e);i.ref=n},Gx={string:DP,number:UP,boolean:LP,bigint:jP,symbol:FP,null:qP,undefined:HP,void:GP,never:VP,any:ZP,unknown:WP,date:KP,enum:JP,literal:YP,nan:QP,template_literal:XP,file:ek,success:tk,custom:rk,function:nk,transform:ok,map:ik,set:sk,array:ak,object:ck,union:Vx,intersection:uk,tuple:lk,record:dk,nullable:pk,nonoptional:fk,default:mk,prefault:hk,catch:gk,pipe:yk,readonly:bk,promise:xk,optional:Zx,lazy:vk};function Jc(e,t){if("_idmap"in e){let o=e,n=va({...t,processors:Gx}),i={};for(let c of o._idmap.entries()){let[u,d]=c;gt(d,n)}let s={},a={registry:o,uri:t?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,d]=c;_a(n,d),s[u]=wa(n,d)}if(Object.keys(i).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=va({...t,processors:Gx});return gt(e,r),_a(r,e),wa(r,e)}class _k{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";this.ctx=va({processors:Gx,target:t,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,t={path:[],schemaPath:[]}){return gt(e,this.ctx,t)}emit(e,t){if(t){if(t.cycles)this.ctx.cycles=t.cycles;if(t.reused)this.ctx.reused=t.reused;if(t.external)this.ctx.external=t.external}_a(this.ctx,e);let r=wa(this.ctx,e),{"~standard":o,...n}=r;return n}}var R4={};var coe=R("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");ze.init(e,t),e.def=t,e.type=t.type,e.parse=(r,o)=>qc(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>ha(e,r,o),e.parseAsync=async(r,o)=>Hc(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>ga(e,r,o),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map((o)=>typeof o==="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]},{parent:!0}),e.with=e.check,e.clone=(r,o)=>$r(e,r,o),e.brand=()=>e,e.register=(r,o)=>(r.add(e,o),e),e.apply=(r)=>r(e)});var uoe=R("ZodMiniObject",(e,t)=>{L0.init(e,t),coe.init(e,t),Ve(e,"shape",()=>t.shape)});function wk(e,t){let r={type:"object",shape:e??{},...se(t)};return new uoe(r)}function oo(e){return!!e._zod}function Yc(e){let t=Object.values(e);if(t.length===0)return wk({});let r=t.every(oo),o=t.every((n)=>!oo(n));if(r)return wk(e);if(o)return CM(e);throw Error("Mixed Zod versions detected in object shape.")}function Sa(e,t){if(oo(e))return ha(e,t);return e.safeParse(t)}async function Wx(e,t){if(oo(e))return await ga(e,t);return await e.safeParseAsync(t)}function Ta(e){if(!e)return;let t;if(oo(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 ld(e){if(!e)return;if(typeof e==="object"){let t=e,r=e;if(!t._def&&!r._zod){let o=Object.values(e);if(o.length>0&&o.every((n)=>typeof n==="object"&&n!==null&&(n._def!==void 0||n._zod!==void 0||typeof n.parse==="function")))return Yc(e)}}if(oo(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 Kx(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 O4(e){return e.description}function C4(e){if(oo(e))return e._zod?.def?.type==="optional";let t=e;if(typeof e.isOptional==="function")return e.isOptional();return t._def?.typeName==="ZodOptional"}function Jx(e){if(oo(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 o=e.value;if(o!==void 0)return o;return}var f={};Pn(f,{$brand:()=>mE,$input:()=>TP,$output:()=>SP,NEVER:()=>fE,TimePrecision:()=>PP,ZodAny:()=>qk,ZodArray:()=>Zk,ZodBase64:()=>yv,ZodBase64URL:()=>bv,ZodBigInt:()=>yd,ZodBigIntFormat:()=>_v,ZodBoolean:()=>gd,ZodCIDRv4:()=>hv,ZodCIDRv6:()=>gv,ZodCUID:()=>cv,ZodCUID2:()=>uv,ZodCatch:()=>fA,ZodCodec:()=>yh,ZodCustom:()=>bh,ZodCustomStringFormat:()=>md,ZodDate:()=>ph,ZodDefault:()=>aA,ZodDiscriminatedUnion:()=>Kk,ZodE164:()=>xv,ZodEmail:()=>iv,ZodEmoji:()=>sv,ZodEnum:()=>pd,ZodError:()=>doe,ZodExactOptional:()=>oA,ZodFile:()=>rA,ZodFirstPartyTypeKind:()=>IA,ZodFunction:()=>SA,ZodGUID:()=>ah,ZodIPv4:()=>fv,ZodIPv6:()=>mv,ZodISODate:()=>Xx,ZodISODateTime:()=>Qx,ZodISODuration:()=>tv,ZodISOTime:()=>ev,ZodIntersection:()=>Jk,ZodIssueCode:()=>foe,ZodJWT:()=>vv,ZodKSUID:()=>pv,ZodLazy:()=>vA,ZodLiteral:()=>tA,ZodMAC:()=>Uk,ZodMap:()=>Xk,ZodNaN:()=>hA,ZodNanoID:()=>av,ZodNever:()=>Gk,ZodNonOptional:()=>Tv,ZodNull:()=>Fk,ZodNullable:()=>sA,ZodNumber:()=>hd,ZodNumberFormat:()=>Qc,ZodObject:()=>fh,ZodOptional:()=>xd,ZodPipe:()=>gh,ZodPrefault:()=>uA,ZodPreprocess:()=>gA,ZodPromise:()=>wA,ZodReadonly:()=>yA,ZodRealError:()=>On,ZodRecord:()=>dd,ZodSet:()=>eA,ZodString:()=>fd,ZodStringFormat:()=>Et,ZodSuccess:()=>pA,ZodSymbol:()=>Lk,ZodTemplateLiteral:()=>xA,ZodTransform:()=>nA,ZodTuple:()=>Yk,ZodType:()=>Ge,ZodULID:()=>lv,ZodURL:()=>lh,ZodUUID:()=>bi,ZodUndefined:()=>jk,ZodUnion:()=>mh,ZodUnknown:()=>Hk,ZodVoid:()=>Vk,ZodXID:()=>dv,ZodXor:()=>Wk,_ZodString:()=>ov,_default:()=>cA,_function:()=>DB,any:()=>xB,array:()=>Ye,base64:()=>rB,base64url:()=>nB,bigint:()=>mB,boolean:()=>rr,catch:()=>mA,check:()=>UB,cidrv4:()=>eB,cidrv6:()=>tB,clone:()=>$r,codec:()=>zB,coerce:()=>PA,config:()=>Xt,core:()=>Ro,cuid:()=>V4,cuid2:()=>Z4,custom:()=>Ev,date:()=>_B,decode:()=>Ok,decodeAsync:()=>zk,describe:()=>LB,discriminatedUnion:()=>hh,e164:()=>oB,email:()=>M4,emoji:()=>H4,encode:()=>Rk,encodeAsync:()=>Ck,endsWith:()=>rd,enum:()=>Cr,exactOptional:()=>iA,file:()=>$B,flattenError:()=>Im,float32:()=>lB,float64:()=>dB,formatError:()=>Pm,fromJSONSchema:()=>VB,function:()=>DB,getErrorMap:()=>hoe,globalRegistry:()=>Rr,gt:()=>gi,gte:()=>an,guid:()=>B4,hash:()=>uB,hex:()=>cB,hostname:()=>aB,httpUrl:()=>q4,includes:()=>ed,instanceof:()=>FB,int:()=>rv,int32:()=>pB,int64:()=>hB,intersection:()=>bd,invertCodec:()=>NB,ipv4:()=>Y4,ipv6:()=>X4,iso:()=>Ea,json:()=>HB,jwt:()=>iB,keyof:()=>wB,ksuid:()=>J4,lazy:()=>_A,length:()=>Wc,literal:()=>Se,locales:()=>Wl,looseObject:()=>Or,looseRecord:()=>IB,lowercase:()=>Ql,lt:()=>hi,lte:()=>Zn,mac:()=>Q4,map:()=>PB,maxLength:()=>Zc,maxSize:()=>xa,meta:()=>jB,mime:()=>nd,minLength:()=>as,minSize:()=>yi,multipleOf:()=>ba,nan:()=>CB,nanoid:()=>G4,nativeEnum:()=>AB,negative:()=>zx,never:()=>wv,nonnegative:()=>Mx,nonoptional:()=>dA,nonpositive:()=>Nx,normalize:()=>od,null:()=>dh,nullable:()=>ch,nullish:()=>RB,number:()=>ut,object:()=>be,optional:()=>Rt,overwrite:()=>$o,parse:()=>Pk,parseAsync:()=>kk,partialRecord:()=>EB,pipe:()=>nv,positive:()=>Cx,prefault:()=>lA,preprocess:()=>xh,prettifyError:()=>EE,promise:()=>BB,property:()=>Bx,readonly:()=>bA,record:()=>wt,refine:()=>TA,regex:()=>Yl,regexes:()=>Rn,registry:()=>dx,safeDecode:()=>Mk,safeDecodeAsync:()=>Dk,safeEncode:()=>Nk,safeEncodeAsync:()=>Bk,safeParse:()=>Ak,safeParseAsync:()=>$k,set:()=>kB,setErrorMap:()=>moe,size:()=>Vc,slugify:()=>cd,startsWith:()=>td,strictObject:()=>SB,string:()=>L,stringFormat:()=>sB,stringbool:()=>qB,success:()=>OB,superRefine:()=>EA,symbol:()=>yB,templateLiteral:()=>MB,toJSONSchema:()=>Jc,toLowerCase:()=>sd,toUpperCase:()=>ad,transform:()=>Sv,treeifyError:()=>TE,trim:()=>id,tuple:()=>Qk,uint32:()=>fB,uint64:()=>gB,ulid:()=>W4,undefined:()=>bB,union:()=>Pt,unknown:()=>It,uppercase:()=>Xl,url:()=>F4,util:()=>re,uuid:()=>D4,uuidv4:()=>U4,uuidv6:()=>L4,uuidv7:()=>j4,void:()=>vB,xid:()=>K4,xor:()=>TB});var sh={};Pn(sh,{ZodAny:()=>qk,ZodArray:()=>Zk,ZodBase64:()=>yv,ZodBase64URL:()=>bv,ZodBigInt:()=>yd,ZodBigIntFormat:()=>_v,ZodBoolean:()=>gd,ZodCIDRv4:()=>hv,ZodCIDRv6:()=>gv,ZodCUID:()=>cv,ZodCUID2:()=>uv,ZodCatch:()=>fA,ZodCodec:()=>yh,ZodCustom:()=>bh,ZodCustomStringFormat:()=>md,ZodDate:()=>ph,ZodDefault:()=>aA,ZodDiscriminatedUnion:()=>Kk,ZodE164:()=>xv,ZodEmail:()=>iv,ZodEmoji:()=>sv,ZodEnum:()=>pd,ZodExactOptional:()=>oA,ZodFile:()=>rA,ZodFunction:()=>SA,ZodGUID:()=>ah,ZodIPv4:()=>fv,ZodIPv6:()=>mv,ZodIntersection:()=>Jk,ZodJWT:()=>vv,ZodKSUID:()=>pv,ZodLazy:()=>vA,ZodLiteral:()=>tA,ZodMAC:()=>Uk,ZodMap:()=>Xk,ZodNaN:()=>hA,ZodNanoID:()=>av,ZodNever:()=>Gk,ZodNonOptional:()=>Tv,ZodNull:()=>Fk,ZodNullable:()=>sA,ZodNumber:()=>hd,ZodNumberFormat:()=>Qc,ZodObject:()=>fh,ZodOptional:()=>xd,ZodPipe:()=>gh,ZodPrefault:()=>uA,ZodPreprocess:()=>gA,ZodPromise:()=>wA,ZodReadonly:()=>yA,ZodRecord:()=>dd,ZodSet:()=>eA,ZodString:()=>fd,ZodStringFormat:()=>Et,ZodSuccess:()=>pA,ZodSymbol:()=>Lk,ZodTemplateLiteral:()=>xA,ZodTransform:()=>nA,ZodTuple:()=>Yk,ZodType:()=>Ge,ZodULID:()=>lv,ZodURL:()=>lh,ZodUUID:()=>bi,ZodUndefined:()=>jk,ZodUnion:()=>mh,ZodUnknown:()=>Hk,ZodVoid:()=>Vk,ZodXID:()=>dv,ZodXor:()=>Wk,_ZodString:()=>ov,_default:()=>cA,_function:()=>DB,any:()=>xB,array:()=>Ye,base64:()=>rB,base64url:()=>nB,bigint:()=>mB,boolean:()=>rr,catch:()=>mA,check:()=>UB,cidrv4:()=>eB,cidrv6:()=>tB,codec:()=>zB,cuid:()=>V4,cuid2:()=>Z4,custom:()=>Ev,date:()=>_B,describe:()=>LB,discriminatedUnion:()=>hh,e164:()=>oB,email:()=>M4,emoji:()=>H4,enum:()=>Cr,exactOptional:()=>iA,file:()=>$B,float32:()=>lB,float64:()=>dB,function:()=>DB,guid:()=>B4,hash:()=>uB,hex:()=>cB,hostname:()=>aB,httpUrl:()=>q4,instanceof:()=>FB,int:()=>rv,int32:()=>pB,int64:()=>hB,intersection:()=>bd,invertCodec:()=>NB,ipv4:()=>Y4,ipv6:()=>X4,json:()=>HB,jwt:()=>iB,keyof:()=>wB,ksuid:()=>J4,lazy:()=>_A,literal:()=>Se,looseObject:()=>Or,looseRecord:()=>IB,mac:()=>Q4,map:()=>PB,meta:()=>jB,nan:()=>CB,nanoid:()=>G4,nativeEnum:()=>AB,never:()=>wv,nonoptional:()=>dA,null:()=>dh,nullable:()=>ch,nullish:()=>RB,number:()=>ut,object:()=>be,optional:()=>Rt,partialRecord:()=>EB,pipe:()=>nv,prefault:()=>lA,preprocess:()=>xh,promise:()=>BB,readonly:()=>bA,record:()=>wt,refine:()=>TA,set:()=>kB,strictObject:()=>SB,string:()=>L,stringFormat:()=>sB,stringbool:()=>qB,success:()=>OB,superRefine:()=>EA,symbol:()=>yB,templateLiteral:()=>MB,transform:()=>Sv,tuple:()=>Qk,uint32:()=>fB,uint64:()=>gB,ulid:()=>W4,undefined:()=>bB,union:()=>Pt,unknown:()=>It,url:()=>F4,uuid:()=>D4,uuidv4:()=>U4,uuidv6:()=>L4,uuidv7:()=>j4,void:()=>vB,xid:()=>K4,xor:()=>TB});var Yx={};Pn(Yx,{endsWith:()=>rd,gt:()=>gi,gte:()=>an,includes:()=>ed,length:()=>Wc,lowercase:()=>Ql,lt:()=>hi,lte:()=>Zn,maxLength:()=>Zc,maxSize:()=>xa,mime:()=>nd,minLength:()=>as,minSize:()=>yi,multipleOf:()=>ba,negative:()=>zx,nonnegative:()=>Mx,nonpositive:()=>Nx,normalize:()=>od,overwrite:()=>$o,positive:()=>Cx,property:()=>Bx,regex:()=>Yl,size:()=>Vc,slugify:()=>cd,startsWith:()=>td,toLowerCase:()=>sd,toUpperCase:()=>ad,trim:()=>id,uppercase:()=>Xl});var Ea={};Pn(Ea,{ZodISODate:()=>Xx,ZodISODateTime:()=>Qx,ZodISODuration:()=>tv,ZodISOTime:()=>ev,date:()=>Tk,datetime:()=>Sk,duration:()=>Ik,time:()=>Ek});var Qx=R("ZodISODateTime",(e,t)=>{_I.init(e,t),Et.init(e,t)});function Sk(e){return kP(Qx,e)}var Xx=R("ZodISODate",(e,t)=>{wI.init(e,t),Et.init(e,t)});function Tk(e){return AP(Xx,e)}var ev=R("ZodISOTime",(e,t)=>{SI.init(e,t),Et.init(e,t)});function Ek(e){return $P(ev,e)}var tv=R("ZodISODuration",(e,t)=>{TI.init(e,t),Et.init(e,t)});function Ik(e){return RP(tv,e)}var z4=(e,t)=>{Em.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>Pm(e,r)},flatten:{value:(r)=>Im(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Ml,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Ml,2)}},isEmpty:{get(){return e.issues.length===0}}})},doe=R("ZodError",z4),On=R("ZodError",z4,{Parent:Error});var Pk=Ul(On),kk=Ll(On),Ak=jl(On),$k=Fl(On),Rk=Vb(On),Ok=Zb(On),Ck=Wb(On),zk=Kb(On),Nk=Jb(On),Mk=Yb(On),Bk=Qb(On),Dk=Xb(On);var N4=new WeakMap;function uh(e,t,r){let o=Object.getPrototypeOf(e),n=N4.get(o);if(!n)n=new Set,N4.set(o,n);if(n.has(t))return;n.add(t);for(let i in r){let s=r[i];Object.defineProperty(o,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 Ge=R("ZodType",(e,t)=>(ze.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ud(e,"input"),output:ud(e,"output")}}),e.toJSONSchema=BP(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,o)=>Pk(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Ak(e,r,o),e.parseAsync=async(r,o)=>kk(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>$k(e,r,o),e.spa=e.safeParseAsync,e.encode=(r,o)=>Rk(e,r,o),e.decode=(r,o)=>Ok(e,r,o),e.encodeAsync=async(r,o)=>Ck(e,r,o),e.decodeAsync=async(r,o)=>zk(e,r,o),e.safeEncode=(r,o)=>Nk(e,r,o),e.safeDecode=(r,o)=>Mk(e,r,o),e.safeEncodeAsync=async(r,o)=>Bk(e,r,o),e.safeDecodeAsync=async(r,o)=>Dk(e,r,o),uh(e,"ZodType",{check(...r){let o=this.def;return this.clone(re.mergeDefs(o,{checks:[...o.checks??[],...r.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,o){return $r(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(TA(r,o))},superRefine(r,o){return this.check(EA(r,o))},overwrite(r){return this.check($o(r))},optional(){return Rt(this)},exactOptional(){return iA(this)},nullable(){return ch(this)},nullish(){return Rt(ch(this))},nonoptional(r){return dA(this,r)},array(){return Ye(this)},or(r){return Pt([this,r])},and(r){return bd(this,r)},transform(r){return nv(this,Sv(r))},default(r){return cA(this,r)},prefault(r){return lA(this,r)},catch(r){return mA(this,r)},pipe(r){return nv(this,r)},readonly(){return bA(this)},describe(r){let o=this.clone();return Rr.add(o,{description:r}),o},meta(...r){if(r.length===0)return Rr.get(this);let o=this.clone();return Rr.add(o,r[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return Rr.get(e)?.description},configurable:!0}),e)),ov=R("_ZodString",(e,t)=>{ya.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(o,n,i)=>DP(e,o,n,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,uh(e,"_ZodString",{regex(...o){return this.check(Yl(...o))},includes(...o){return this.check(ed(...o))},startsWith(...o){return this.check(td(...o))},endsWith(...o){return this.check(rd(...o))},min(...o){return this.check(as(...o))},max(...o){return this.check(Zc(...o))},length(...o){return this.check(Wc(...o))},nonempty(...o){return this.check(as(1,...o))},lowercase(o){return this.check(Ql(o))},uppercase(o){return this.check(Xl(o))},trim(){return this.check(id())},normalize(...o){return this.check(od(...o))},toLowerCase(){return this.check(sd())},toUpperCase(){return this.check(ad())},slugify(){return this.check(cd())}})}),fd=R("ZodString",(e,t)=>{ya.init(e,t),ov.init(e,t),e.email=(r)=>e.check(Lm(iv,r)),e.url=(r)=>e.check(Jl(lh,r)),e.jwt=(r)=>e.check(ih(vv,r)),e.emoji=(r)=>e.check(Gm(sv,r)),e.guid=(r)=>e.check(Kl(ah,r)),e.uuid=(r)=>e.check(jm(bi,r)),e.uuidv4=(r)=>e.check(Fm(bi,r)),e.uuidv6=(r)=>e.check(qm(bi,r)),e.uuidv7=(r)=>e.check(Hm(bi,r)),e.nanoid=(r)=>e.check(Vm(av,r)),e.guid=(r)=>e.check(Kl(ah,r)),e.cuid=(r)=>e.check(Zm(cv,r)),e.cuid2=(r)=>e.check(Wm(uv,r)),e.ulid=(r)=>e.check(Km(lv,r)),e.base64=(r)=>e.check(rh(yv,r)),e.base64url=(r)=>e.check(nh(bv,r)),e.xid=(r)=>e.check(Jm(dv,r)),e.ksuid=(r)=>e.check(Ym(pv,r)),e.ipv4=(r)=>e.check(Qm(fv,r)),e.ipv6=(r)=>e.check(Xm(mv,r)),e.cidrv4=(r)=>e.check(eh(hv,r)),e.cidrv6=(r)=>e.check(th(gv,r)),e.e164=(r)=>e.check(oh(xv,r)),e.datetime=(r)=>e.check(Sk(r)),e.date=(r)=>e.check(Tk(r)),e.time=(r)=>e.check(Ek(r)),e.duration=(r)=>e.check(Ik(r))});function L(e){return px(fd,e)}var Et=R("ZodStringFormat",(e,t)=>{_t.init(e,t),ov.init(e,t)}),iv=R("ZodEmail",(e,t)=>{l0.init(e,t),Et.init(e,t)});function M4(e){return Lm(iv,e)}var ah=R("ZodGUID",(e,t)=>{c0.init(e,t),Et.init(e,t)});function B4(e){return Kl(ah,e)}var bi=R("ZodUUID",(e,t)=>{u0.init(e,t),Et.init(e,t)});function D4(e){return jm(bi,e)}function U4(e){return Fm(bi,e)}function L4(e){return qm(bi,e)}function j4(e){return Hm(bi,e)}var lh=R("ZodURL",(e,t)=>{d0.init(e,t),Et.init(e,t)});function F4(e){return Jl(lh,e)}function q4(e){return Jl(lh,{protocol:Rn.httpProtocol,hostname:Rn.domain,...re.normalizeParams(e)})}var sv=R("ZodEmoji",(e,t)=>{p0.init(e,t),Et.init(e,t)});function H4(e){return Gm(sv,e)}var av=R("ZodNanoID",(e,t)=>{f0.init(e,t),Et.init(e,t)});function G4(e){return Vm(av,e)}var cv=R("ZodCUID",(e,t)=>{m0.init(e,t),Et.init(e,t)});function V4(e){return Zm(cv,e)}var uv=R("ZodCUID2",(e,t)=>{h0.init(e,t),Et.init(e,t)});function Z4(e){return Wm(uv,e)}var lv=R("ZodULID",(e,t)=>{g0.init(e,t),Et.init(e,t)});function W4(e){return Km(lv,e)}var dv=R("ZodXID",(e,t)=>{y0.init(e,t),Et.init(e,t)});function K4(e){return Jm(dv,e)}var pv=R("ZodKSUID",(e,t)=>{b0.init(e,t),Et.init(e,t)});function J4(e){return Ym(pv,e)}var fv=R("ZodIPv4",(e,t)=>{x0.init(e,t),Et.init(e,t)});function Y4(e){return Qm(fv,e)}var Uk=R("ZodMAC",(e,t)=>{_0.init(e,t),Et.init(e,t)});function Q4(e){return fx(Uk,e)}var mv=R("ZodIPv6",(e,t)=>{v0.init(e,t),Et.init(e,t)});function X4(e){return Xm(mv,e)}var hv=R("ZodCIDRv4",(e,t)=>{w0.init(e,t),Et.init(e,t)});function eB(e){return eh(hv,e)}var gv=R("ZodCIDRv6",(e,t)=>{S0.init(e,t),Et.init(e,t)});function tB(e){return th(gv,e)}var yv=R("ZodBase64",(e,t)=>{T0.init(e,t),Et.init(e,t)});function rB(e){return rh(yv,e)}var bv=R("ZodBase64URL",(e,t)=>{E0.init(e,t),Et.init(e,t)});function nB(e){return nh(bv,e)}var xv=R("ZodE164",(e,t)=>{I0.init(e,t),Et.init(e,t)});function oB(e){return oh(xv,e)}var vv=R("ZodJWT",(e,t)=>{P0.init(e,t),Et.init(e,t)});function iB(e){return ih(vv,e)}var md=R("ZodCustomStringFormat",(e,t)=>{k0.init(e,t),Et.init(e,t)});function sB(e,t,r={}){return Kc(md,e,t,r)}function aB(e){return Kc(md,"hostname",Rn.hostname,e)}function cB(e){return Kc(md,"hex",Rn.hex,e)}function uB(e,t){let r=t?.enc??"hex",o=`${e}_${r}`,n=Rn[o];if(!n)throw Error(`Unrecognized hash format: ${o}`);return Kc(md,o,n,t)}var hd=R("ZodNumber",(e,t)=>{Rm.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(o,n,i)=>UP(e,o,n,i),uh(e,"ZodNumber",{gt(o,n){return this.check(gi(o,n))},gte(o,n){return this.check(an(o,n))},min(o,n){return this.check(an(o,n))},lt(o,n){return this.check(hi(o,n))},lte(o,n){return this.check(Zn(o,n))},max(o,n){return this.check(Zn(o,n))},int(o){return this.check(rv(o))},safe(o){return this.check(rv(o))},positive(o){return this.check(gi(0,o))},nonnegative(o){return this.check(an(0,o))},negative(o){return this.check(hi(0,o))},nonpositive(o){return this.check(Zn(0,o))},multipleOf(o,n){return this.check(ba(o,n))},step(o,n){return this.check(ba(o,n))},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 ut(e){return mx(hd,e)}var Qc=R("ZodNumberFormat",(e,t)=>{A0.init(e,t),hd.init(e,t)});function rv(e){return hx(Qc,e)}function lB(e){return gx(Qc,e)}function dB(e){return yx(Qc,e)}function pB(e){return bx(Qc,e)}function fB(e){return xx(Qc,e)}var gd=R("ZodBoolean",(e,t)=>{Hl.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>LP(e,r,o,n)});function rr(e){return vx(gd,e)}var yd=R("ZodBigInt",(e,t)=>{Om.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(o,n,i)=>jP(e,o,n,i),e.gte=(o,n)=>e.check(an(o,n)),e.min=(o,n)=>e.check(an(o,n)),e.gt=(o,n)=>e.check(gi(o,n)),e.gte=(o,n)=>e.check(an(o,n)),e.min=(o,n)=>e.check(an(o,n)),e.lt=(o,n)=>e.check(hi(o,n)),e.lte=(o,n)=>e.check(Zn(o,n)),e.max=(o,n)=>e.check(Zn(o,n)),e.positive=(o)=>e.check(gi(BigInt(0),o)),e.negative=(o)=>e.check(hi(BigInt(0),o)),e.nonpositive=(o)=>e.check(Zn(BigInt(0),o)),e.nonnegative=(o)=>e.check(an(BigInt(0),o)),e.multipleOf=(o,n)=>e.check(ba(o,n));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function mB(e){return _x(yd,e)}var _v=R("ZodBigIntFormat",(e,t)=>{$0.init(e,t),yd.init(e,t)});function hB(e){return wx(_v,e)}function gB(e){return Sx(_v,e)}var Lk=R("ZodSymbol",(e,t)=>{R0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>FP(e,r,o,n)});function yB(e){return Tx(Lk,e)}var jk=R("ZodUndefined",(e,t)=>{O0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>HP(e,r,o,n)});function bB(e){return Ex(jk,e)}var Fk=R("ZodNull",(e,t)=>{C0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>qP(e,r,o,n)});function dh(e){return Ix(Fk,e)}var qk=R("ZodAny",(e,t)=>{z0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ZP(e,r,o,n)});function xB(){return Px(qk)}var Hk=R("ZodUnknown",(e,t)=>{N0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>WP(e,r,o,n)});function It(){return kx(Hk)}var Gk=R("ZodNever",(e,t)=>{M0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>VP(e,r,o,n)});function wv(e){return Ax(Gk,e)}var Vk=R("ZodVoid",(e,t)=>{B0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>GP(e,r,o,n)});function vB(e){return $x(Vk,e)}var ph=R("ZodDate",(e,t)=>{D0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(o,n,i)=>KP(e,o,n,i),e.min=(o,n)=>e.check(an(o,n)),e.max=(o,n)=>e.check(Zn(o,n));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});function _B(e){return Rx(ph,e)}var Zk=R("ZodArray",(e,t)=>{U0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ak(e,r,o,n),e.element=t.element,uh(e,"ZodArray",{min(r,o){return this.check(as(r,o))},nonempty(r){return this.check(as(1,r))},max(r,o){return this.check(Zc(r,o))},length(r,o){return this.check(Wc(r,o))},unwrap(){return this.element}})});function Ye(e,t){return MP(Zk,e,t)}function wB(e){let t=e._zod.def.shape;return Cr(Object.keys(t))}var fh=R("ZodObject",(e,t)=>{II.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ck(e,r,o,n),re.defineLazy(e,"shape",()=>t.shape),uh(e,"ZodObject",{keyof(){return Cr(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:It()})},loose(){return this.clone({...this._zod.def,catchall:It()})},strict(){return this.clone({...this._zod.def,catchall:wv()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return re.extend(this,r)},safeExtend(r){return re.safeExtend(this,r)},merge(r){return re.merge(this,r)},pick(r){return re.pick(this,r)},omit(r){return re.omit(this,r)},partial(...r){return re.partial(xd,this,r[0])},required(...r){return re.required(Tv,this,r[0])}})});function be(e,t){let r={type:"object",shape:e??{},...re.normalizeParams(t)};return new fh(r)}function SB(e,t){return new fh({type:"object",shape:e,catchall:wv(),...re.normalizeParams(t)})}function Or(e,t){return new fh({type:"object",shape:e,catchall:It(),...re.normalizeParams(t)})}var mh=R("ZodUnion",(e,t)=>{Gl.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vx(e,r,o,n),e.options=t.options});function Pt(e,t){return new mh({type:"union",options:e,...re.normalizeParams(t)})}var Wk=R("ZodXor",(e,t)=>{mh.init(e,t),j0.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vx(e,r,o,n),e.options=t.options});function TB(e,t){return new Wk({type:"union",options:e,inclusive:!1,...re.normalizeParams(t)})}var Kk=R("ZodDiscriminatedUnion",(e,t)=>{mh.init(e,t),F0.init(e,t)});function hh(e,t,r){return new Kk({type:"union",options:t,discriminator:e,...re.normalizeParams(r)})}var Jk=R("ZodIntersection",(e,t)=>{q0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>uk(e,r,o,n)});function bd(e,t){return new Jk({type:"intersection",left:e,right:t})}var Yk=R("ZodTuple",(e,t)=>{Cm.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>lk(e,r,o,n),e.rest=(r)=>e.clone({...e._zod.def,rest:r})});function Qk(e,t,r){let o=t instanceof ze,n=o?r:t;return new Yk({type:"tuple",items:e,rest:o?t:null,...re.normalizeParams(n)})}var dd=R("ZodRecord",(e,t)=>{H0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>dk(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function wt(e,t,r){if(!t||!t._zod)return new dd({type:"record",keyType:L(),valueType:e,...re.normalizeParams(t)});return new dd({type:"record",keyType:e,valueType:t,...re.normalizeParams(r)})}function EB(e,t,r){let o=$r(e);return o._zod.values=void 0,new dd({type:"record",keyType:o,valueType:t,...re.normalizeParams(r)})}function IB(e,t,r){return new dd({type:"record",keyType:e,valueType:t,mode:"loose",...re.normalizeParams(r)})}var Xk=R("ZodMap",(e,t)=>{G0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ik(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(yi(...r)),e.nonempty=(r)=>e.check(yi(1,r)),e.max=(...r)=>e.check(xa(...r)),e.size=(...r)=>e.check(Vc(...r))});function PB(e,t,r){return new Xk({type:"map",keyType:e,valueType:t,...re.normalizeParams(r)})}var eA=R("ZodSet",(e,t)=>{V0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>sk(e,r,o,n),e.min=(...r)=>e.check(yi(...r)),e.nonempty=(r)=>e.check(yi(1,r)),e.max=(...r)=>e.check(xa(...r)),e.size=(...r)=>e.check(Vc(...r))});function kB(e,t){return new eA({type:"set",valueType:e,...re.normalizeParams(t)})}var pd=R("ZodEnum",(e,t)=>{Z0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(o,n,i)=>JP(e,o,n,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new pd({...t,checks:[],...re.normalizeParams(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let s of o)if(r.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new pd({...t,checks:[],...re.normalizeParams(n),entries:i})}});function Cr(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new pd({type:"enum",entries:r,...re.normalizeParams(t)})}function AB(e,t){return new pd({type:"enum",entries:e,...re.normalizeParams(t)})}var tA=R("ZodLiteral",(e,t)=>{W0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>YP(e,r,o,n),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 Se(e,t){return new tA({type:"literal",values:Array.isArray(e)?e:[e],...re.normalizeParams(t)})}var rA=R("ZodFile",(e,t)=>{K0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ek(e,r,o,n),e.min=(r,o)=>e.check(yi(r,o)),e.max=(r,o)=>e.check(xa(r,o)),e.mime=(r,o)=>e.check(nd(Array.isArray(r)?r:[r],o))});function $B(e){return Dx(rA,e)}var nA=R("ZodTransform",(e,t)=>{J0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ok(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new jc(e.constructor.name);r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(re.issue(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(re.issue(s))}};let n=t.transform(r.value,r);if(n instanceof Promise)return n.then((i)=>(r.value=i,r.fallback=!0,r));return r.value=n,r.fallback=!0,r}});function Sv(e){return new nA({type:"transform",transform:e})}var xd=R("ZodOptional",(e,t)=>{zm.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zx(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Rt(e){return new xd({type:"optional",innerType:e})}var oA=R("ZodExactOptional",(e,t)=>{Y0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zx(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function iA(e){return new oA({type:"optional",innerType:e})}var sA=R("ZodNullable",(e,t)=>{Q0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>pk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ch(e){return new sA({type:"nullable",innerType:e})}function RB(e){return Rt(ch(e))}var aA=R("ZodDefault",(e,t)=>{X0.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>mk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function cA(e,t){return new aA({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():re.shallowClone(t)}})}var uA=R("ZodPrefault",(e,t)=>{ex.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>hk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function lA(e,t){return new uA({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():re.shallowClone(t)}})}var Tv=R("ZodNonOptional",(e,t)=>{tx.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>fk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function dA(e,t){return new Tv({type:"nonoptional",innerType:e,...re.normalizeParams(t)})}var pA=R("ZodSuccess",(e,t)=>{rx.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>tk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function OB(e){return new pA({type:"success",innerType:e})}var fA=R("ZodCatch",(e,t)=>{nx.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>gk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function mA(e,t){return new fA({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var hA=R("ZodNaN",(e,t)=>{ox.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>QP(e,r,o,n)});function CB(e){return Ox(hA,e)}var gh=R("ZodPipe",(e,t)=>{Nm.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yk(e,r,o,n),e.in=t.in,e.out=t.out});function nv(e,t){return new gh({type:"pipe",in:e,out:t})}var yh=R("ZodCodec",(e,t)=>{gh.init(e,t),Vl.init(e,t)});function zB(e,t,r){return new yh({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function NB(e){let t=e._zod.def;return new yh({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var gA=R("ZodPreprocess",(e,t)=>{gh.init(e,t),PI.init(e,t)}),yA=R("ZodReadonly",(e,t)=>{ix.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>bk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function bA(e){return new yA({type:"readonly",innerType:e})}var xA=R("ZodTemplateLiteral",(e,t)=>{sx.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>XP(e,r,o,n)});function MB(e,t){return new xA({type:"template_literal",parts:e,...re.normalizeParams(t)})}var vA=R("ZodLazy",(e,t)=>{ux.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vk(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function _A(e){return new vA({type:"lazy",getter:e})}var wA=R("ZodPromise",(e,t)=>{cx.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xk(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function BB(e){return new wA({type:"promise",innerType:e})}var SA=R("ZodFunction",(e,t)=>{ax.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>nk(e,r,o,n)});function DB(e){return new SA({type:"function",input:Array.isArray(e?.input)?Qk(e?.input):e?.input??Ye(It()),output:e?.output??It()})}var bh=R("ZodCustom",(e,t)=>{lx.init(e,t),Ge.init(e,t),e._zod.processJSONSchema=(r,o,n)=>rk(e,r,o,n)});function UB(e){let t=new Tt({check:"custom"});return t._zod.check=e,t}function Ev(e,t){return Ux(bh,e??(()=>!0),t)}function TA(e,t={}){return Lx(bh,e,t)}function EA(e,t){return jx(e,t)}var LB=Fx,jB=qx;function FB(e,t={}){let r=new bh({type:"custom",check:"custom",fn:(o)=>o instanceof e,abort:!0,...re.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=(o)=>{if(!(o.value instanceof e))o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var qB=(...e)=>Hx({Codec:yh,Boolean:gd,String:fd},...e);function HB(e){let t=_A(()=>Pt([L(e),ut(),rr(),dh(),Ye(t),wt(L(),t)]));return t}function xh(e,t){return new gA({type:"pipe",in:Sv(e),out:t})}var foe={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"};function moe(e){Xt({customError:e})}function hoe(){return Xt().customError}var IA;(function(e){})(IA||(IA={}));var ge={...sh,...Yx,iso:Ea},goe=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function yoe(e,t){let r=e.$schema;if(r==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(r==="http://json-schema.org/draft-07/schema#")return"draft-7";if(r==="http://json-schema.org/draft-04/schema#")return"draft-4";return t??"draft-2020-12"}function boe(e,t){if(!e.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(r.length===0)return t.rootSchema;let o=t.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1];if(!n||!t.defs[n])throw Error(`Reference not found: ${e}`);return t.defs[n]}throw Error(`Reference not found: ${e}`)}function GB(e,t){if(e.not!==void 0){if(typeof e.not==="object"&&Object.keys(e.not).length===0)return ge.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return ge.lazy(()=>{if(!t.refs.has(n))throw Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let i=boe(n,t),s=Jr(i,t);return t.refs.set(n,s),t.processing.delete(n),s}if(e.enum!==void 0){let n=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&n.length===1&&n[0]===null)return ge.null();if(n.length===0)return ge.never();if(n.length===1)return ge.literal(n[0]);if(n.every((s)=>typeof s==="string"))return ge.enum(n);let i=n.map((s)=>ge.literal(s));if(i.length<2)return i[0];return ge.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return ge.literal(e.const);let r=e.type;if(Array.isArray(r)){let n=r.map((i)=>{let s={...e,type:i};return GB(s,t)});if(n.length===0)return ge.never();if(n.length===1)return n[0];return ge.union(n)}if(!r)return ge.any();let o;switch(r){case"string":{let n=ge.string();if(e.format){let i=e.format;if(i==="email")n=n.check(ge.email());else if(i==="uri"||i==="uri-reference")n=n.check(ge.url());else if(i==="uuid"||i==="guid")n=n.check(ge.uuid());else if(i==="date-time")n=n.check(ge.iso.datetime());else if(i==="date")n=n.check(ge.iso.date());else if(i==="time")n=n.check(ge.iso.time());else if(i==="duration")n=n.check(ge.iso.duration());else if(i==="ipv4")n=n.check(ge.ipv4());else if(i==="ipv6")n=n.check(ge.ipv6());else if(i==="mac")n=n.check(ge.mac());else if(i==="cidr")n=n.check(ge.cidrv4());else if(i==="cidr-v6")n=n.check(ge.cidrv6());else if(i==="base64")n=n.check(ge.base64());else if(i==="base64url")n=n.check(ge.base64url());else if(i==="e164")n=n.check(ge.e164());else if(i==="jwt")n=n.check(ge.jwt());else if(i==="emoji")n=n.check(ge.emoji());else if(i==="nanoid")n=n.check(ge.nanoid());else if(i==="cuid")n=n.check(ge.cuid());else if(i==="cuid2")n=n.check(ge.cuid2());else if(i==="ulid")n=n.check(ge.ulid());else if(i==="xid")n=n.check(ge.xid());else if(i==="ksuid")n=n.check(ge.ksuid())}if(typeof e.minLength==="number")n=n.min(e.minLength);if(typeof e.maxLength==="number")n=n.max(e.maxLength);if(e.pattern)n=n.regex(new RegExp(e.pattern));o=n;break}case"number":case"integer":{let n=r==="integer"?ge.number().int():ge.number();if(typeof e.minimum==="number")n=n.min(e.minimum);if(typeof e.maximum==="number")n=n.max(e.maximum);if(typeof e.exclusiveMinimum==="number")n=n.gt(e.exclusiveMinimum);else if(e.exclusiveMinimum===!0&&typeof e.minimum==="number")n=n.gt(e.minimum);if(typeof e.exclusiveMaximum==="number")n=n.lt(e.exclusiveMaximum);else if(e.exclusiveMaximum===!0&&typeof e.maximum==="number")n=n.lt(e.maximum);if(typeof e.multipleOf==="number")n=n.multipleOf(e.multipleOf);o=n;break}case"boolean":{o=ge.boolean();break}case"null":{o=ge.null();break}case"object":{let n={},i=e.properties||{},s=new Set(e.required||[]);for(let[c,u]of Object.entries(i)){let d=Jr(u,t);n[c]=s.has(c)?d:d.optional()}if(e.propertyNames){let c=Jr(e.propertyNames,t),u=e.additionalProperties&&typeof e.additionalProperties==="object"?Jr(e.additionalProperties,t):ge.any();if(Object.keys(n).length===0){o=ge.record(c,u);break}let d=ge.object(n).passthrough(),p=ge.looseRecord(c,u);o=ge.intersection(d,p);break}if(e.patternProperties){let c=e.patternProperties,u=Object.keys(c),d=[];for(let m of u){let h=Jr(c[m],t),y=ge.string().regex(new RegExp(m));d.push(ge.looseRecord(y,h))}let p=[];if(Object.keys(n).length>0)p.push(ge.object(n).passthrough());if(p.push(...d),p.length===0)o=ge.object({}).passthrough();else if(p.length===1)o=p[0];else{let m=ge.intersection(p[0],p[1]);for(let h=2;h<p.length;h++)m=ge.intersection(m,p[h]);o=m}break}let a=ge.object(n);if(e.additionalProperties===!1)o=a.strict();else if(typeof e.additionalProperties==="object")o=a.catchall(Jr(e.additionalProperties,t));else o=a.passthrough();break}case"array":{let{prefixItems:n,items:i}=e;if(n&&Array.isArray(n)){let s=n.map((c)=>Jr(c,t)),a=i&&typeof i==="object"&&!Array.isArray(i)?Jr(i,t):void 0;if(a)o=ge.tuple(s).rest(a);else o=ge.tuple(s);if(typeof e.minItems==="number")o=o.check(ge.minLength(e.minItems));if(typeof e.maxItems==="number")o=o.check(ge.maxLength(e.maxItems))}else if(Array.isArray(i)){let s=i.map((c)=>Jr(c,t)),a=e.additionalItems&&typeof e.additionalItems==="object"?Jr(e.additionalItems,t):void 0;if(a)o=ge.tuple(s).rest(a);else o=ge.tuple(s);if(typeof e.minItems==="number")o=o.check(ge.minLength(e.minItems));if(typeof e.maxItems==="number")o=o.check(ge.maxLength(e.maxItems))}else if(i!==void 0){let s=Jr(i,t),a=ge.array(s);if(typeof e.minItems==="number")a=a.min(e.minItems);if(typeof e.maxItems==="number")a=a.max(e.maxItems);o=a}else o=ge.array(ge.any());break}default:throw Error(`Unsupported type: ${r}`)}return o}function Jr(e,t){if(typeof e==="boolean")return e?ge.any():ge.never();let r=GB(e,t),o=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map((u)=>Jr(u,t)),c=ge.union(a);r=o?ge.intersection(r,c):c}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map((u)=>Jr(u,t)),c=ge.xor(a);r=o?ge.intersection(r,c):c}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)r=o?r:ge.any();else{let a=o?r:Jr(e.allOf[0],t),c=o?0:1;for(let u=c;u<e.allOf.length;u++)a=ge.intersection(a,Jr(e.allOf[u],t));r=a}if(e.nullable===!0&&t.version==="openapi-3.0")r=ge.nullable(r);if(e.readOnly===!0)r=ge.readonly(r);if(e.default!==void 0)r=r.default(e.default);let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)if(a in e)n[a]=e[a];let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)if(a in e)n[a]=e[a];for(let a of Object.keys(e))if(!goe.has(a))n[a]=e[a];if(Object.keys(n).length>0)t.registry.add(r,n);if(e.description)r=r.describe(e.description);return r}function VB(e,t){if(typeof e==="boolean")return e?ge.any():ge.never();let r;try{r=JSON.parse(JSON.stringify(e))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=yoe(r,t?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:t?.registry??Rr};return Jr(r,i)}var PA={};Pn(PA,{bigint:()=>woe,boolean:()=>_oe,date:()=>Soe,number:()=>voe,string:()=>xoe});function xoe(e){return IP(fd,e)}function voe(e){return OP(hd,e)}function _oe(e){return CP(gd,e)}function woe(e){return zP(yd,e)}function Soe(e){return NP(ph,e)}Xt(Mm());var kA="2025-11-25";var ZB=[kA,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ia="io.modelcontextprotocol/related-task",Pv="2.0",mr=Ev((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),WB=Pt([L(),ut().int()]),KB=L(),yEe=Or({ttl:ut().optional(),pollInterval:ut().optional()}),Toe=be({ttl:ut().optional()}),Eoe=be({taskId:L()}),AA=Or({progressToken:WB.optional(),[Ia]:Eoe.optional()}),Wn=be({_meta:AA.optional()}),vh=Wn.extend({task:Toe.optional()}),JB=(e)=>vh.safeParse(e).success,zr=be({method:L(),params:Wn.loose().optional()}),io=be({_meta:AA.optional()}),so=be({method:L(),params:io.loose().optional()}),Nr=Or({_meta:AA.optional()}),kv=Pt([L(),ut().int()]),YB=be({jsonrpc:Se(Pv),id:kv,...zr.shape}).strict(),$A=(e)=>YB.safeParse(e).success,QB=be({jsonrpc:Se(Pv),...so.shape}).strict(),XB=(e)=>QB.safeParse(e).success,RA=be({jsonrpc:Se(Pv),id:kv,result:Nr}).strict(),_h=(e)=>RA.safeParse(e).success;var ke;(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"})(ke||(ke={}));var OA=be({jsonrpc:Se(Pv),id:kv.optional(),error:be({code:ut().int(),message:L(),data:It().optional()})}).strict();var eD=(e)=>OA.safeParse(e).success;var tD=Pt([YB,QB,RA,OA]),bEe=Pt([RA,OA]),Av=Nr.strict(),Ioe=io.extend({requestId:kv.optional(),reason:L().optional()}),$v=so.extend({method:Se("notifications/cancelled"),params:Ioe}),Poe=be({src:L(),mimeType:L().optional(),sizes:Ye(L()).optional(),theme:Cr(["light","dark"]).optional()}),wh=be({icons:Ye(Poe).optional()}),vd=be({name:L(),title:L().optional()}),rD=vd.extend({...vd.shape,...wh.shape,version:L(),websiteUrl:L().optional(),description:L().optional()}),koe=bd(be({applyDefaults:rr().optional()}),wt(L(),It())),Aoe=xh((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},bd(be({form:koe.optional(),url:mr.optional()}),wt(L(),It()).optional())),$oe=Or({list:mr.optional(),cancel:mr.optional(),requests:Or({sampling:Or({createMessage:mr.optional()}).optional(),elicitation:Or({create:mr.optional()}).optional()}).optional()}),Roe=Or({list:mr.optional(),cancel:mr.optional(),requests:Or({tools:Or({call:mr.optional()}).optional()}).optional()}),Ooe=be({experimental:wt(L(),mr).optional(),sampling:be({context:mr.optional(),tools:mr.optional()}).optional(),elicitation:Aoe.optional(),roots:be({listChanged:rr().optional()}).optional(),tasks:$oe.optional(),extensions:wt(L(),mr).optional()}),Coe=Wn.extend({protocolVersion:L(),capabilities:Ooe,clientInfo:rD}),CA=zr.extend({method:Se("initialize"),params:Coe});var zoe=be({experimental:wt(L(),mr).optional(),logging:mr.optional(),completions:mr.optional(),prompts:be({listChanged:rr().optional()}).optional(),resources:be({subscribe:rr().optional(),listChanged:rr().optional()}).optional(),tools:be({listChanged:rr().optional()}).optional(),tasks:Roe.optional(),extensions:wt(L(),mr).optional()}),Noe=Nr.extend({protocolVersion:L(),capabilities:zoe,serverInfo:rD,instructions:L().optional()}),zA=so.extend({method:Se("notifications/initialized"),params:io.optional()});var Rv=zr.extend({method:Se("ping"),params:Wn.optional()}),Moe=be({progress:ut(),total:Rt(ut()),message:Rt(L())}),Boe=be({...io.shape,...Moe.shape,progressToken:WB}),Ov=so.extend({method:Se("notifications/progress"),params:Boe}),Doe=Wn.extend({cursor:KB.optional()}),Sh=zr.extend({params:Doe.optional()}),Th=Nr.extend({nextCursor:KB.optional()}),Uoe=Cr(["working","input_required","completed","failed","cancelled"]),Eh=be({taskId:L(),status:Uoe,ttl:Pt([ut(),dh()]),createdAt:L(),lastUpdatedAt:L(),pollInterval:Rt(ut()),statusMessage:Rt(L())}),_d=Nr.extend({task:Eh}),Loe=io.merge(Eh),Ih=so.extend({method:Se("notifications/tasks/status"),params:Loe}),Cv=zr.extend({method:Se("tasks/get"),params:Wn.extend({taskId:L()})}),zv=Nr.merge(Eh),Nv=zr.extend({method:Se("tasks/result"),params:Wn.extend({taskId:L()})}),xEe=Nr.loose(),Mv=Sh.extend({method:Se("tasks/list")}),Bv=Th.extend({tasks:Ye(Eh)}),Dv=zr.extend({method:Se("tasks/cancel"),params:Wn.extend({taskId:L()})}),nD=Nr.merge(Eh),oD=be({uri:L(),mimeType:Rt(L()),_meta:wt(L(),It()).optional()}),iD=oD.extend({text:L()}),NA=L().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),sD=oD.extend({blob:NA}),Ph=Cr(["user","assistant"]),wd=be({audience:Ye(Ph).optional(),priority:ut().min(0).max(1).optional(),lastModified:Ea.datetime({offset:!0}).optional()}),aD=be({...vd.shape,...wh.shape,uri:L(),description:Rt(L()),mimeType:Rt(L()),size:Rt(ut()),annotations:wd.optional(),_meta:Rt(Or({}))}),joe=be({...vd.shape,...wh.shape,uriTemplate:L(),description:Rt(L()),mimeType:Rt(L()),annotations:wd.optional(),_meta:Rt(Or({}))}),Uv=Sh.extend({method:Se("resources/list")}),Foe=Th.extend({resources:Ye(aD)}),Lv=Sh.extend({method:Se("resources/templates/list")}),qoe=Th.extend({resourceTemplates:Ye(joe)}),MA=Wn.extend({uri:L()}),Hoe=MA,jv=zr.extend({method:Se("resources/read"),params:Hoe}),Goe=Nr.extend({contents:Ye(Pt([iD,sD]))}),Voe=so.extend({method:Se("notifications/resources/list_changed"),params:io.optional()}),Zoe=MA,Woe=zr.extend({method:Se("resources/subscribe"),params:Zoe}),Koe=MA,Joe=zr.extend({method:Se("resources/unsubscribe"),params:Koe}),Yoe=io.extend({uri:L()}),Qoe=so.extend({method:Se("notifications/resources/updated"),params:Yoe}),Xoe=be({name:L(),description:Rt(L()),required:Rt(rr())}),eie=be({...vd.shape,...wh.shape,description:Rt(L()),arguments:Rt(Ye(Xoe)),_meta:Rt(Or({}))}),Fv=Sh.extend({method:Se("prompts/list")}),tie=Th.extend({prompts:Ye(eie)}),rie=Wn.extend({name:L(),arguments:wt(L(),L()).optional()}),qv=zr.extend({method:Se("prompts/get"),params:rie}),BA=be({type:Se("text"),text:L(),annotations:wd.optional(),_meta:wt(L(),It()).optional()}),DA=be({type:Se("image"),data:NA,mimeType:L(),annotations:wd.optional(),_meta:wt(L(),It()).optional()}),UA=be({type:Se("audio"),data:NA,mimeType:L(),annotations:wd.optional(),_meta:wt(L(),It()).optional()}),nie=be({type:Se("tool_use"),name:L(),id:L(),input:wt(L(),It()),_meta:wt(L(),It()).optional()}),oie=be({type:Se("resource"),resource:Pt([iD,sD]),annotations:wd.optional(),_meta:wt(L(),It()).optional()}),iie=aD.extend({type:Se("resource_link")}),LA=Pt([BA,DA,UA,iie,oie]),sie=be({role:Ph,content:LA}),aie=Nr.extend({description:L().optional(),messages:Ye(sie)}),cie=so.extend({method:Se("notifications/prompts/list_changed"),params:io.optional()}),uie=be({title:L().optional(),readOnlyHint:rr().optional(),destructiveHint:rr().optional(),idempotentHint:rr().optional(),openWorldHint:rr().optional()}),lie=be({taskSupport:Cr(["required","optional","forbidden"]).optional()}),cD=be({...vd.shape,...wh.shape,description:L().optional(),inputSchema:be({type:Se("object"),properties:wt(L(),mr).optional(),required:Ye(L()).optional()}).catchall(It()),outputSchema:be({type:Se("object"),properties:wt(L(),mr).optional(),required:Ye(L()).optional()}).catchall(It()).optional(),annotations:uie.optional(),execution:lie.optional(),_meta:wt(L(),It()).optional()}),Hv=Sh.extend({method:Se("tools/list")}),die=Th.extend({tools:Ye(cD)}),Gv=Nr.extend({content:Ye(LA).default([]),structuredContent:wt(L(),It()).optional(),isError:rr().optional()}),vEe=Gv.or(Nr.extend({toolResult:It()})),pie=vh.extend({name:L(),arguments:wt(L(),It()).optional()}),Sd=zr.extend({method:Se("tools/call"),params:pie}),fie=so.extend({method:Se("notifications/tools/list_changed"),params:io.optional()}),_Ee=be({autoRefresh:rr().default(!0),debounceMs:ut().int().nonnegative().default(300)}),kh=Cr(["debug","info","notice","warning","error","critical","alert","emergency"]),mie=Wn.extend({level:kh}),jA=zr.extend({method:Se("logging/setLevel"),params:mie}),hie=io.extend({level:kh,logger:L().optional(),data:It()}),gie=so.extend({method:Se("notifications/message"),params:hie}),yie=be({name:L().optional()}),bie=be({hints:Ye(yie).optional(),costPriority:ut().min(0).max(1).optional(),speedPriority:ut().min(0).max(1).optional(),intelligencePriority:ut().min(0).max(1).optional()}),xie=be({mode:Cr(["auto","required","none"]).optional()}),vie=be({type:Se("tool_result"),toolUseId:L().describe("The unique identifier for the corresponding tool call."),content:Ye(LA).default([]),structuredContent:be({}).loose().optional(),isError:rr().optional(),_meta:wt(L(),It()).optional()}),_ie=hh("type",[BA,DA,UA]),Iv=hh("type",[BA,DA,UA,nie,vie]),wie=be({role:Ph,content:Pt([Iv,Ye(Iv)]),_meta:wt(L(),It()).optional()}),Sie=vh.extend({messages:Ye(wie),modelPreferences:bie.optional(),systemPrompt:L().optional(),includeContext:Cr(["none","thisServer","allServers"]).optional(),temperature:ut().optional(),maxTokens:ut().int(),stopSequences:Ye(L()).optional(),metadata:mr.optional(),tools:Ye(cD).optional(),toolChoice:xie.optional()}),Tie=zr.extend({method:Se("sampling/createMessage"),params:Sie}),Ah=Nr.extend({model:L(),stopReason:Rt(Cr(["endTurn","stopSequence","maxTokens"]).or(L())),role:Ph,content:_ie}),FA=Nr.extend({model:L(),stopReason:Rt(Cr(["endTurn","stopSequence","maxTokens","toolUse"]).or(L())),role:Ph,content:Pt([Iv,Ye(Iv)])}),Eie=be({type:Se("boolean"),title:L().optional(),description:L().optional(),default:rr().optional()}),Iie=be({type:Se("string"),title:L().optional(),description:L().optional(),minLength:ut().optional(),maxLength:ut().optional(),format:Cr(["email","uri","date","date-time"]).optional(),default:L().optional()}),Pie=be({type:Cr(["number","integer"]),title:L().optional(),description:L().optional(),minimum:ut().optional(),maximum:ut().optional(),default:ut().optional()}),kie=be({type:Se("string"),title:L().optional(),description:L().optional(),enum:Ye(L()),default:L().optional()}),Aie=be({type:Se("string"),title:L().optional(),description:L().optional(),oneOf:Ye(be({const:L(),title:L()})),default:L().optional()}),$ie=be({type:Se("string"),title:L().optional(),description:L().optional(),enum:Ye(L()),enumNames:Ye(L()).optional(),default:L().optional()}),Rie=Pt([kie,Aie]),Oie=be({type:Se("array"),title:L().optional(),description:L().optional(),minItems:ut().optional(),maxItems:ut().optional(),items:be({type:Se("string"),enum:Ye(L())}),default:Ye(L()).optional()}),Cie=be({type:Se("array"),title:L().optional(),description:L().optional(),minItems:ut().optional(),maxItems:ut().optional(),items:be({anyOf:Ye(be({const:L(),title:L()}))}),default:Ye(L()).optional()}),zie=Pt([Oie,Cie]),Nie=Pt([$ie,Rie,zie]),Mie=Pt([Nie,Eie,Iie,Pie]),Bie=vh.extend({mode:Se("form").optional(),message:L(),requestedSchema:be({type:Se("object"),properties:wt(L(),Mie),required:Ye(L()).optional()})}),Die=vh.extend({mode:Se("url"),message:L(),elicitationId:L(),url:L().url()}),Uie=Pt([Bie,Die]),Lie=zr.extend({method:Se("elicitation/create"),params:Uie}),jie=io.extend({elicitationId:L()}),Fie=so.extend({method:Se("notifications/elicitation/complete"),params:jie}),Td=Nr.extend({action:Cr(["accept","decline","cancel"]),content:xh((e)=>e===null?void 0:e,wt(L(),Pt([L(),ut(),rr(),Ye(L())])).optional())}),qie=be({type:Se("ref/resource"),uri:L()});var Hie=be({type:Se("ref/prompt"),name:L()}),Gie=Wn.extend({ref:Pt([Hie,qie]),argument:be({name:L(),value:L()}),context:be({arguments:wt(L(),L()).optional()}).optional()}),Vv=zr.extend({method:Se("completion/complete"),params:Gie});function uD(e){if(e.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function lD(e){if(e.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var Vie=Nr.extend({completion:Or({values:Ye(L()).max(100),total:Rt(ut().int()),hasMore:Rt(rr())})}),Zie=be({uri:L().startsWith("file://"),name:L().optional(),_meta:wt(L(),It()).optional()}),Wie=zr.extend({method:Se("roots/list"),params:Wn.optional()}),qA=Nr.extend({roots:Ye(Zie)}),Kie=so.extend({method:Se("notifications/roots/list_changed"),params:io.optional()}),wEe=Pt([Rv,CA,Vv,jA,qv,Fv,Uv,Lv,jv,Woe,Joe,Sd,Hv,Cv,Nv,Mv,Dv]),SEe=Pt([$v,Ov,zA,Kie,Ih]),TEe=Pt([Av,Ah,FA,Td,qA,zv,Bv,_d]),EEe=Pt([Rv,Tie,Lie,Wie,Cv,Nv,Mv,Dv]),IEe=Pt([$v,Ov,gie,Qoe,Voe,fie,cie,Ih,Fie]),PEe=Pt([Av,Noe,Vie,aie,tie,Foe,qoe,Goe,Gv,die,zv,Bv,_d]);class Te 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===ke.UrlElicitationRequired&&r){let o=r;if(o.elicitations)return new dD(o.elicitations,t)}return new Te(e,t,r)}}class dD extends Te{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(ke.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Pa(e){return e==="completed"||e==="failed"||e==="cancelled"}var fD=Symbol("Let zodToJsonSchema decide on which parser to use");var pD={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"},mD=(e)=>typeof e==="string"?{...pD,name:e}:{...pD,...e};var hD=(e)=>{let t=mD(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(([o,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,o],jsonSchema:void 0}]))}};function HA(e,t,r,o){if(!o?.errorMessages)return;if(r)e.errorMessage={...e.errorMessage,[t]:r}}function rt(e,t,r,o,n){e[t]=r,HA(e,t,o,n)}var Zv=(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 Gt(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Zv(t,e.currentPath):t.join("/")}}function gD(e,t){let r={type:"array"};if(e.type?._def&&e.type?._def?.typeName!==ie.ZodAny)r.items=Ce(e.type._def,{...t,currentPath:[...t.currentPath,"items"]});if(e.minLength)rt(r,"minItems",e.minLength.value,e.minLength.message,t);if(e.maxLength)rt(r,"maxItems",e.maxLength.value,e.maxLength.message,t);if(e.exactLength)rt(r,"minItems",e.exactLength.value,e.exactLength.message,t),rt(r,"maxItems",e.exactLength.value,e.exactLength.message,t);return r}function yD(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let o of e.checks)switch(o.kind){case"min":if(t.target==="jsonSchema7")if(o.inclusive)rt(r,"minimum",o.value,o.message,t);else rt(r,"exclusiveMinimum",o.value,o.message,t);else{if(!o.inclusive)r.exclusiveMinimum=!0;rt(r,"minimum",o.value,o.message,t)}break;case"max":if(t.target==="jsonSchema7")if(o.inclusive)rt(r,"maximum",o.value,o.message,t);else rt(r,"exclusiveMaximum",o.value,o.message,t);else{if(!o.inclusive)r.exclusiveMaximum=!0;rt(r,"maximum",o.value,o.message,t)}break;case"multipleOf":rt(r,"multipleOf",o.value,o.message,t);break}return r}function bD(){return{type:"boolean"}}function Wv(e,t){return Ce(e.type._def,t)}var xD=(e,t)=>Ce(e.innerType._def,t);function GA(e,t,r){let o=r??t.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((n,i)=>GA(e,t,n))};switch(o){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Jie(e,t)}}var Jie=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let o of e.checks)switch(o.kind){case"min":rt(r,"minimum",o.value,o.message,t);break;case"max":rt(r,"maximum",o.value,o.message,t);break}return r};function vD(e,t){return{...Ce(e.innerType._def,t),default:e.defaultValue()}}function _D(e,t){return t.effectStrategy==="input"?Ce(e.schema._def,t):Gt(t)}function wD(e){return{type:"string",enum:Array.from(e.values)}}var Yie=(e)=>{if("type"in e&&e.type==="string")return!1;return"allOf"in e};function SD(e,t){let r=[Ce(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ce(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((i)=>!!i),o=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,n=[];return r.forEach((i)=>{if(Yie(i)){if(n.push(...i.allOf),i.unevaluatedProperties===void 0)o=void 0}else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...c}=i;s=c}else o=void 0;n.push(s)}}),n.length?{allOf:n,...o}:void 0}function TD(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 VA=void 0,Oo={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(VA===void 0)VA=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return VA},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 Kv(e,t){let r={type:"string"};if(e.checks)for(let o of e.checks)switch(o.kind){case"min":rt(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,o.value):o.value,o.message,t);break;case"max":rt(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,o.value):o.value,o.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Co(r,"email",o.message,t);break;case"format:idn-email":Co(r,"idn-email",o.message,t);break;case"pattern:zod":un(r,Oo.email,o.message,t);break}break;case"url":Co(r,"uri",o.message,t);break;case"uuid":Co(r,"uuid",o.message,t);break;case"regex":un(r,o.regex,o.message,t);break;case"cuid":un(r,Oo.cuid,o.message,t);break;case"cuid2":un(r,Oo.cuid2,o.message,t);break;case"startsWith":un(r,RegExp(`^${ZA(o.value,t)}`),o.message,t);break;case"endsWith":un(r,RegExp(`${ZA(o.value,t)}$`),o.message,t);break;case"datetime":Co(r,"date-time",o.message,t);break;case"date":Co(r,"date",o.message,t);break;case"time":Co(r,"time",o.message,t);break;case"duration":Co(r,"duration",o.message,t);break;case"length":rt(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,o.value):o.value,o.message,t),rt(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,o.value):o.value,o.message,t);break;case"includes":{un(r,RegExp(ZA(o.value,t)),o.message,t);break}case"ip":{if(o.version!=="v6")Co(r,"ipv4",o.message,t);if(o.version!=="v4")Co(r,"ipv6",o.message,t);break}case"base64url":un(r,Oo.base64url,o.message,t);break;case"jwt":un(r,Oo.jwt,o.message,t);break;case"cidr":{if(o.version!=="v6")un(r,Oo.ipv4Cidr,o.message,t);if(o.version!=="v4")un(r,Oo.ipv6Cidr,o.message,t);break}case"emoji":un(r,Oo.emoji(),o.message,t);break;case"ulid":{un(r,Oo.ulid,o.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Co(r,"binary",o.message,t);break}case"contentEncoding:base64":{rt(r,"contentEncoding","base64",o.message,t);break}case"pattern:zod":{un(r,Oo.base64,o.message,t);break}}break}case"nanoid":un(r,Oo.nanoid,o.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:((n)=>{})(o)}return r}function ZA(e,t){return t.patternStrategy==="escape"?Xie(e):e}var Qie=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Xie(e){let t="";for(let r=0;r<e.length;r++){if(!Qie.has(e[r]))t+="\\";t+=e[r]}return t}function Co(e,t,r,o){if(e.format||e.anyOf?.some((n)=>n.format)){if(!e.anyOf)e.anyOf=[];if(e.format){if(e.anyOf.push({format:e.format,...e.errorMessage&&o.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&&o.errorMessages&&{errorMessage:{format:r}}})}else rt(e,"format",t,r,o)}function un(e,t,r,o){if(e.pattern||e.allOf?.some((n)=>n.pattern)){if(!e.allOf)e.allOf=[];if(e.pattern){if(e.allOf.push({pattern:e.pattern,...e.errorMessage&&o.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:ED(t,o),...r&&o.errorMessages&&{errorMessage:{pattern:r}}})}else rt(e,"pattern",ED(t,o),r,o)}function ED(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")},o=r.i?e.source.toLowerCase():e.source,n="",i=!1,s=!1,a=!1;for(let c=0;c<o.length;c++){if(i){n+=o[c],i=!1;continue}if(r.i){if(s){if(o[c].match(/[a-z]/)){if(a)n+=o[c],n+=`${o[c-2]}-${o[c]}`.toUpperCase(),a=!1;else if(o[c+1]==="-"&&o[c+2]?.match(/[a-z]/))n+=o[c],a=!0;else n+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){n+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){n+=`(^|(?<=[\r
131
131
  ]))`;continue}else if(o[c]==="$"){n+=`($|(?=[\r
132
132
  ]))`;continue}}if(r.s&&o[c]==="."){n+=s?`${o[c]}\r
133
133
  `:`[${o[c]}\r
134
134
  ]`;continue}if(n+=o[c],o[c]==="\\")i=!0;else if(s&&o[c]==="]")s=!1;else if(!s&&o[c]==="[")s=!0}try{new RegExp(n)}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 n}function Jv(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===ie.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((o,n)=>({...o,[n]:Ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Gt(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===ie.ZodString&&e.keyType._def.checks?.length){let{type:o,...n}=Kv(e.keyType._def,t);return{...r,propertyNames:n}}else if(e.keyType?._def.typeName===ie.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===ie.ZodBranded&&e.keyType._def.type._def.typeName===ie.ZodString&&e.keyType._def.type._def.checks?.length){let{type:o,...n}=Wv(e.keyType._def,t);return{...r,propertyNames:n}}return r}function ID(e,t){if(t.mapStrategy==="record")return Jv(e,t);let r=Ce(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Gt(t),o=Ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Gt(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function PD(e){let t=e.values,o=Object.keys(e.values).filter((i)=>typeof t[t[i]]!=="number").map((i)=>t[i]),n=Array.from(new Set(o.map((i)=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function kD(e){return e.target==="openAi"?void 0:{not:Gt({...e,currentPath:[...e.currentPath,"not"]})}}function AD(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var $h={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function RD(e,t){if(t.target==="openApi3")return $D(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((o)=>(o._def.typeName in $h)&&(!o._def.checks||!o._def.checks.length))){let o=r.reduce((n,i)=>{let s=$h[i._def.typeName];return s&&!n.includes(s)?[...n,s]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every((o)=>o._def.typeName==="ZodLiteral"&&!o.description)){let o=r.reduce((n,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...n,s];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(o.length===r.length){let n=o.filter((i,s,a)=>a.indexOf(i)===s);return{type:n.length>1?n:n[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every((o)=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter((i)=>!o.includes(i))],[])};return $D(e,t)}var $D=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((o,n)=>Ce(o._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter((o)=>!!o&&(!t.strictUnions||typeof o==="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function OD(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:$h[e.innerType._def.typeName],nullable:!0};return{type:[$h[e.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let o=Ce(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(o&&"$ref"in o)return{allOf:[o],nullable:!0};return o&&{...o,nullable:!0}}let r=Ce(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function CD(e,t){let r={type:"number"};if(!e.checks)return r;for(let o of e.checks)switch(o.kind){case"int":r.type="integer",HA(r,"type",o.message,t);break;case"min":if(t.target==="jsonSchema7")if(o.inclusive)rt(r,"minimum",o.value,o.message,t);else rt(r,"exclusiveMinimum",o.value,o.message,t);else{if(!o.inclusive)r.exclusiveMinimum=!0;rt(r,"minimum",o.value,o.message,t)}break;case"max":if(t.target==="jsonSchema7")if(o.inclusive)rt(r,"maximum",o.value,o.message,t);else rt(r,"exclusiveMaximum",o.value,o.message,t);else{if(!o.inclusive)r.exclusiveMaximum=!0;rt(r,"maximum",o.value,o.message,t)}break;case"multipleOf":rt(r,"multipleOf",o.value,o.message,t);break}return r}function zD(e,t){let r=t.target==="openAi",o={type:"object",properties:{}},n=[],i=e.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let u=tse(c);if(u&&r){if(c._def.typeName==="ZodOptional")c=c._def.innerType;if(!c.isNullable())c=c.nullable();u=!1}let d=Ce(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});if(d===void 0)continue;if(o.properties[a]=d,!u)n.push(a)}if(n.length)o.required=n;let s=ese(e,t);if(s!==void 0)o.additionalProperties=s;return o}function ese(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ce(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 tse(e){try{return e.isOptional()}catch{return!0}}var ND=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Ce(e.innerType._def,t);let r=Ce(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Gt(t)},r]}:Gt(t)};var MD=(e,t)=>{if(t.pipeStrategy==="input")return Ce(e.in._def,t);else if(t.pipeStrategy==="output")return Ce(e.out._def,t);let r=Ce(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),o=Ce(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter((n)=>n!==void 0)}};function BD(e,t){return Ce(e.type._def,t)}function DD(e,t){let o={type:"array",uniqueItems:!0,items:Ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)rt(o,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)rt(o,"maxItems",e.maxSize.value,e.maxSize.message,t);return o}function UD(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,o)=>Ce(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:Ce(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,o)=>Ce(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function LD(e){return{not:Gt(e)}}function jD(e){return Gt(e)}var FD=(e,t)=>Ce(e.innerType._def,t);var qD=(e,t,r)=>{switch(t){case ie.ZodString:return Kv(e,r);case ie.ZodNumber:return CD(e,r);case ie.ZodObject:return zD(e,r);case ie.ZodBigInt:return yD(e,r);case ie.ZodBoolean:return bD();case ie.ZodDate:return GA(e,r);case ie.ZodUndefined:return LD(r);case ie.ZodNull:return AD(r);case ie.ZodArray:return gD(e,r);case ie.ZodUnion:case ie.ZodDiscriminatedUnion:return RD(e,r);case ie.ZodIntersection:return SD(e,r);case ie.ZodTuple:return UD(e,r);case ie.ZodRecord:return Jv(e,r);case ie.ZodLiteral:return TD(e,r);case ie.ZodEnum:return wD(e);case ie.ZodNativeEnum:return PD(e);case ie.ZodNullable:return OD(e,r);case ie.ZodOptional:return ND(e,r);case ie.ZodMap:return ID(e,r);case ie.ZodSet:return DD(e,r);case ie.ZodLazy:return()=>e.getter()._def;case ie.ZodPromise:return BD(e,r);case ie.ZodNaN:case ie.ZodNever:return kD(r);case ie.ZodEffects:return _D(e,r);case ie.ZodAny:return Gt(r);case ie.ZodUnknown:return jD(r);case ie.ZodDefault:return vD(e,r);case ie.ZodBranded:return Wv(e,r);case ie.ZodReadonly:return FD(e,r);case ie.ZodCatch:return xD(e,r);case ie.ZodPipeline:return MD(e,r);case ie.ZodFunction:case ie.ZodVoid:case ie.ZodSymbol:return;default:return((o)=>{return})(t)}};function Ce(e,t,r=!1){let o=t.seen.get(e);if(t.override){let a=t.override?.(e,t,o,r);if(a!==fD)return a}if(o&&!r){let a=rse(o,t);if(a!==void 0)return a}let n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);let i=qD(e,e.typeName,t),s=typeof i==="function"?Ce(i(),t):i;if(s)nse(e,t,s);if(t.postProcess){let a=t.postProcess(s,e,t);return n.jsonSchema=s,a}return n.jsonSchema=s,s}var rse=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Zv(t.currentPath,e.path)};case"none":case"seen":{if(e.path.length<t.currentPath.length&&e.path.every((r,o)=>t.currentPath[o]===r))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Gt(t);return t.$refStrategy==="seen"?Gt(t):void 0}}},nse=(e,t,r)=>{if(e.description){if(r.description=e.description,t.markdownDescription)r.markdownDescription=e.description}return r};var WA=(e,t)=>{let r=hD(t),o=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,d])=>({...c,[u]:Ce(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Gt(r)}),{}):void 0,n=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=Ce(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Gt(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(!o)o={};if(!o[r.openAiAnyTypeName])o[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}}let a=n===void 0?o?{...i,[r.definitionPath]:o}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]: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 ose(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 KA(e,t){if(oo(e))return Jc(e,{target:ose(t?.target),io:t?.pipeStrategy??"input"});return WA(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function JA(e){let r=Ta(e)?.method;if(!r)throw Error("Schema is missing a method literal");let o=Jx(r);if(typeof o!=="string")throw Error("Schema method literal must be a string");return o}function YA(e,t){let r=Sa(e,t);if(!r.success)throw r.error;return r.data}var ise=60000;class QA{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($v,(t)=>{this._oncancel(t)}),this.setNotificationHandler(Ov,(t)=>{this._onprogress(t)}),this.setRequestHandler(Rv,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(Cv,async(t,r)=>{let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Te(ke.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Nv,async(t,r)=>{let o=async()=>{let n=t.params.taskId;if(this._taskMessageQueue){let s;while(s=await this._taskMessageQueue.dequeue(n,r.sessionId)){if(s.type==="response"||s.type==="error"){let a=s.message,c=a.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),s.type==="response")u(a);else{let d=a,p=new Te(d.error.code,d.error.message,d.error.data);u(p)}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(n,r.sessionId);if(!i)throw new Te(ke.InvalidParams,`Task not found: ${n}`);if(!Pa(i.status))return await this._waitForTaskUpdate(n,r.signal),await o();if(Pa(i.status)){let s=await this._taskStore.getTaskResult(n,r.sessionId);return this._clearTaskQueue(n),{...s,_meta:{...s._meta,[Ia]:{taskId:n}}}}return await o()};return await o()}),this.setRequestHandler(Mv,async(t,r)=>{try{let{tasks:o,nextCursor:n}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:o,nextCursor:n,_meta:{}}}catch(o){throw new Te(ke.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Dv,async(t,r)=>{try{let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Te(ke.InvalidParams,`Task not found: ${t.params.taskId}`);if(Pa(o.status))throw new Te(ke.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId);let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Te(ke.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...n}}catch(o){if(o instanceof Te)throw o;throw new Te(ke.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:o})}_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),Te.fromError(ke.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=(n)=>{r?.(n),this._onerror(n)};let o=this._transport?.onmessage;this._transport.onmessage=(n,i)=>{if(o?.(n,i),_h(n)||eD(n))this._onresponse(n);else if($A(n))this._onrequest(n,i);else if(XB(n))this._onnotification(n);else this._onerror(Error(`Unknown message type: ${JSON.stringify(n)}`))},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=Te.fromError(ke.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,o=this._transport,n=e.params?._meta?.[Ia]?.taskId;if(r===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:ke.MethodNotFound,message:"Method not found"}};if(n&&this._taskMessageQueue)this._enqueueTaskMessage(n,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch((d)=>this._onerror(Error(`Failed to enqueue error response: ${d}`)));else o?.send(u).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=JB(e.params)?e.params.task:void 0,a=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,c={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async(u)=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};if(n)d.relatedTask={taskId:n};await this.notification(u,d)},sendRequest:async(u,d,p)=>{if(i.signal.aborted)throw new Te(ke.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};if(n&&!m.relatedTask)m.relatedTask={taskId:n};let h=m.relatedTask?.taskId??n;if(h&&a)await a.updateTaskStatus(h,"input_required");return await this.request(u,d,m)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:n,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(u)=>{if(i.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};if(n&&this._taskMessageQueue)await this._enqueueTaskMessage(n,{type:"response",message:d,timestamp:Date.now()},o?.sessionId);else await o?.send(d)},async(u)=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:ke.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};if(n&&this._taskMessageQueue)await this._enqueueTaskMessage(n,{type:"error",message:d,timestamp:Date.now()},o?.sessionId);else await o?.send(d)}).catch((u)=>this._onerror(Error(`Failed to send response: ${u}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===i)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),n=this._progressHandlers.get(o);if(!n){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(a);return}n(r)}_onresponse(e){let t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),_h(e))r(e);else{let i=new Te(e.error.code,e.error.message,e.error.data);r(i)}return}let o=this._responseHandlers.get(t);if(o===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 n=!1;if(_h(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")n=!0,this._taskProgressTokens.set(s.taskId,t)}}if(!n)this._progressHandlers.delete(t);if(_h(e))o(e);else{let i=Te.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){let{task:o}=r??{};if(!o){try{yield{type:"result",result:await this.request(e,t,r)}}catch(i){yield{type:"error",error:i instanceof Te?i:new Te(ke.InternalError,String(i))}}return}let n;try{let i=await this.request(e,_d,r);if(i.task)n=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Te(ke.InternalError,"Task creation did not return a task");while(!0){let s=await this.getTask({taskId:n},r);if(yield{type:"taskStatus",task:s},Pa(s.status)){if(s.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:n},t,r)};else if(s.status==="failed")yield{type:"error",error:new Te(ke.InternalError,`Task ${n} failed`)};else if(s.status==="cancelled")yield{type:"error",error:new Te(ke.InternalError,`Task ${n} was cancelled`)};return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:n},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 Te?i:new Te(ke.InternalError,String(i))}}}request(e,t,r){let{relatedRequestId:o,resumptionToken:n,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((c,u)=>{let d=(v)=>{u(v)};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(v){d(v);return}r?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};if(r?.onprogress)this._progressHandlers.set(p,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}};if(s)m.params={...m.params,task:s};if(a)m.params={...m.params,_meta:{...m.params?._meta||{},[Ia]:a}};let h=(v)=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(v)}},{relatedRequestId:o,resumptionToken:n,onresumptiontoken:i}).catch((w)=>this._onerror(Error(`Failed to send cancellation: ${w}`)));let E=v instanceof Te?v:new Te(ke.RequestTimeout,String(v));u(E)};this._responseHandlers.set(p,(v)=>{if(r?.signal?.aborted)return;if(v instanceof Error)return u(v);try{let E=Sa(t,v.result);if(!E.success)u(E.error);else c(E.data)}catch(E){u(E)}}),r?.signal?.addEventListener("abort",()=>{h(r?.signal?.reason)});let y=r?.timeout??ise,x=()=>h(Te.fromError(ke.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(p,y,r?.maxTotalTimeout,x,r?.resetTimeoutOnProgress??!1);let S=a?.taskId;if(S){let v=(E)=>{let w=this._responseHandlers.get(p);if(w)w(E);else this._onerror(Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(S,{type:"request",message:m,timestamp:Date.now()}).catch((E)=>{this._cleanupTimeout(p),u(E)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:n,onresumptiontoken:i}).catch((v)=>{this._cleanupTimeout(p),u(v)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},zv,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},Bv,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},nD,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||{},[Ia]: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||{},[Ia]: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||{},[Ia]:t.relatedTask}}};await this._transport.send(i,t)}setRequestHandler(e,t){let r=JA(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,n)=>{let i=YA(e,o);return Promise.resolve(t(i,n))})}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=JA(e);this._notificationHandlers.set(r,(o)=>{let n=YA(e,o);return Promise.resolve(t(n))})}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 o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,o)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,t);for(let o of r)if(o.type==="request"&&$A(o.message)){let n=o.message.id,i=this._requestResolvers.get(n);if(i)i(new Te(ke.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(n);else this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1000;try{let o=await this._taskStore?.getTask(e);if(o?.pollInterval)r=o.pollInterval}catch{}return new Promise((o,n)=>{if(t.aborted){n(new Te(ke.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);t.addEventListener("abort",()=>{clearTimeout(i),n(new Te(ke.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let r=this._taskStore;if(!r)throw Error("No task store configured");return{createTask:async(o)=>{if(!e)throw Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},t)},getTask:async(o)=>{let n=await r.getTask(o,t);if(!n)throw new Te(ke.InvalidParams,"Failed to retrieve task: Task not found");return n},storeTaskResult:async(o,n,i)=>{await r.storeTaskResult(o,n,i,t);let s=await r.getTask(o,t);if(s){let a=Ih.parse({method:"notifications/tasks/status",params:s});if(await this.notification(a),Pa(s.status))this._cleanupTaskProgressHandler(o)}},getTaskResult:(o)=>r.getTaskResult(o,t),updateTaskStatus:async(o,n,i)=>{let s=await r.getTask(o,t);if(!s)throw new Te(ke.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Pa(s.status))throw new Te(ke.InvalidParams,`Cannot update task "${o}" from terminal status "${s.status}" to "${n}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,n,i,t);let a=await r.getTask(o,t);if(a){let c=Ih.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Pa(a.status))this._cleanupTaskProgressHandler(o)}},listTasks:(o)=>r.listTasks(o,t)}}}function HD(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function GD(e,t){let r={...e};for(let o in t){let n=o,i=t[n];if(i===void 0)continue;let s=r[n];if(HD(s)&&HD(i))r[n]={...s,...i};else r[n]=i}return r}var P3=rn(Z6(),1),k3=rn(I3(),1);function Pme(){let e=new P3.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return k3.default(e),e}class n${constructor(e){this._ajv=e??Pme()}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 o${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 o=e.messages[e.messages.length-1],n=Array.isArray(o.content)?o.content:[o.content],i=n.some((u)=>u.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((u)=>u.type==="tool_use");if(i){if(n.some((u)=>u.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 u=new Set(a.filter((p)=>p.type==="tool_use").map((p)=>p.id)),d=new Set(n.filter((p)=>p.type==="tool_result").map((p)=>p.toolUseId));if(u.size!==d.size||![...u].every((p)=>d.has(p)))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},Ah,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){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 n=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:n},Td,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 A3(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 $3(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 i$ extends QA{constructor(e,t){super(t);if(this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(kh.options.map((r,o)=>[r,o])),this.isMessageIgnored=(r,o)=>{let n=this._loggingLevels.get(o);return n?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new n$,this.setRequestHandler(CA,(r)=>this._oninitialize(r)),this.setNotificationHandler(zA,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(jA,async(r,o)=>{let n=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,s=kh.safeParse(i);if(s.success)this._loggingLevels.set(n,s.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new o$(this)};return this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=GD(this._capabilities,e)}setRequestHandler(e,t){let o=Ta(e)?.method;if(!o)throw Error("Schema is missing a method literal");let n;if(oo(o)){let s=o;n=s._zod?.def?.value??s.value}else{let s=o;n=s._def?.value??s.value}if(typeof n!=="string")throw Error("Schema method literal must be a string");if(n==="tools/call"){let s=async(a,c)=>{let u=Sa(Sd,a);if(!u.success){let h=u.error instanceof Error?u.error.message:String(u.error);throw new Te(ke.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:d}=u.data,p=await Promise.resolve(t(a,c));if(d.task){let h=Sa(_d,p);if(!h.success){let y=h.error instanceof Error?h.error.message:String(h.error);throw new Te(ke.InvalidParams,`Invalid task creation result: ${y}`)}return h.data}let m=Sa(Gv,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new Te(ke.InvalidParams,`Invalid tools/call result: ${h}`)}return m.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){$3(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;A3(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:ZB.includes(t)?t:kA,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"},Av)}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],o=Array.isArray(r.content)?r.content:[r.content],n=o.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(n){if(o.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)),u=new Set(o.filter((d)=>d.type==="tool_result").map((d)=>d.toolUseId));if(c.size!==u.size||![...c].every((d)=>u.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},FA,t);return this.request({method:"sampling/createMessage",params:e},Ah,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 o=e;return this.request({method:"elicitation/create",params:o},Td,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},n=await this.request({method:"elicitation/create",params:o},Td,t);if(n.action==="accept"&&n.content&&o.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(o.requestedSchema)(n.content);if(!s.valid)throw new Te(ke.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(i){if(i instanceof Te)throw i;throw new Te(ke.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return n}}}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},qA,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 O3=Symbol.for("mcp.completable");function s$(e){return!!e&&typeof e==="object"&&O3 in e}function C3(e){return e[O3]?.complete}var R3;(function(e){e.Completable="McpCompletable"})(R3||(R3={}));var kme=/^[A-Za-z0-9._-]{1,128}$/;function Ame(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(!kme.test(e)){let r=e.split("").filter((o)=>!/[A-Za-z0-9._-]/.test(o)).filter((o,n,i)=>i.indexOf(o)===n);return t.push(`Tool name contains invalid characters: ${r.map((o)=>`"${o}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function $me(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 a$(e){let t=Ame(e);return $me(e,t.warnings),t.isValid}class c${constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let o={taskSupport:"required",...t.execution};if(o.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,o,t._meta,r)}}class l${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 i$(e,t)}get experimental(){if(!this._experimental)this._experimental={tasks:new c$(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(Na(Hv)),this.server.assertCanSetRequestHandler(Na(Sd)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Hv,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let o=ld(t.inputSchema);return o?KA(o,{strictUnions:!0,pipeStrategy:"input"}):Rme})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let o=ld(t.outputSchema);if(o)r.outputSchema=KA(o,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(Sd,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new Te(ke.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Te(ke.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,n=r.execution?.taskSupport,i="createTask"in r.handler;if((n==="required"||n==="optional")&&!i)throw new Te(ke.InternalError,`Tool ${e.params.name} has taskSupport '${n}' but was not registered with registerToolTask`);if(n==="required"&&!o)throw new Te(ke.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(n==="optional"&&!o&&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(o)return a;return await this.validateToolOutput(r,a,e.params.name),a}catch(r){if(r instanceof Te){if(r.code===ke.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 n=ld(e.inputSchema)??e.inputSchema,i=await Wx(n,t);if(!i.success){let s="error"in i?i.error:"Unknown error",a=Kx(s);throw new Te(ke.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 Te(ke.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=ld(e.outputSchema),n=await Wx(o,t.structuredContent);if(!n.success){let i="error"in n?n.error:"Unknown error",s=Kx(i);throw new Te(ke.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${s}`)}}async executeToolHandler(e,t,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema)return await Promise.resolve(o.createTask(t,i));else return await Promise.resolve(o.createTask(i))}if(e.inputSchema)return await Promise.resolve(o(t,r));else return await Promise.resolve(o(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,t.params.arguments,t.params.name),n=e.handler,i={...r,taskStore:r.taskStore},s=o?await Promise.resolve(n.createTask(o,i)):await Promise.resolve(n.createTask(i)),a=s.task.taskId,c=s.task,u=c.pollInterval??5000;while(c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled"){await new Promise((p)=>setTimeout(p,u));let d=await r.taskStore.getTask(a);if(!d)throw new Te(ke.InternalError,`Task ${a} not found during polling`);c=d}return await r.taskStore.getTaskResult(a)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(Na(Vv)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Vv,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return uD(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return lD(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Te(ke.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new Te(ke.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new Te(ke.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return eg;let n=Ta(r.argsSchema)?.[e.params.argument.name];if(!s$(n))return eg;let i=C3(n);if(!i)return eg;let s=await i(e.params.argument.value,e.params.context);return N3(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 eg;throw new Te(ke.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return eg;let n=await o(e.params.argument.value,e.params.context);return N3(n)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(Na(Uv)),this.server.assertCanSetRequestHandler(Na(Lv)),this.server.assertCanSetRequestHandler(Na(jv)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Uv,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([n,i])=>i.enabled).map(([n,i])=>({uri:n,name:i.name,...i.metadata})),o=[];for(let n of Object.values(this._registeredResourceTemplates)){if(!n.resourceTemplate.listCallback)continue;let i=await n.resourceTemplate.listCallback(t);for(let s of i.resources)o.push({...n.metadata,...s})}return{resources:[...r,...o]}}),this.server.setRequestHandler(Lv,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(jv,async(e,t)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new Te(ke.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,t)}for(let n of Object.values(this._registeredResourceTemplates)){let i=n.resourceTemplate.uriTemplate.match(r.toString());if(i)return n.readCallback(r,i,t)}throw new Te(ke.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(Na(Fv)),this.server.assertCanSetRequestHandler(Na(qv)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Fv,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Ome(t.argsSchema):void 0}))})),this.server.setRequestHandler(qv,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new Te(ke.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Te(ke.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=ld(r.argsSchema),n=await Wx(o,e.params.arguments);if(!n.success){let a="error"in n?n.error:"Unknown error",c=Kx(a);throw new Te(ke.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}let i=n.data,s=r.callback;return await Promise.resolve(s(i,t))}else{let o=r.callback;return await Promise.resolve(o(t))}}),this._promptHandlersInitialized=!0}resource(e,t,...r){let o;if(typeof r[0]==="object")o=r.shift();let n=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,o,n);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,o,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,t,r,o){if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,r.title,t,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,r.title,t,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}_createRegisteredResource(e,t,r,o,n){let i={name:e,title:t,metadata:o,readCallback:n,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,o,n){let i={resourceTemplate:r,title:t,metadata:o,readCallback:n,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,o,n){let i={title:t,description:r,argsSchema:o===void 0?void 0:Yc(o),callback:n,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=Yc(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,o){if(Object.values(o).some((a)=>{let c=a instanceof xd?a._def?.innerType:a;return s$(c)}))this.setCompletionRequestHandler()}return i}_createRegisteredTool(e,t,r,o,n,i,s,a,c){a$(e);let u={title:t,description:r,inputSchema:z3(o),outputSchema:z3(n),annotations:i,execution:s,_meta:a,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:(d)=>{if(typeof d.name<"u"&&d.name!==e){if(typeof d.name==="string")a$(d.name);if(delete this._registeredTools[e],d.name)this._registeredTools[d.name]=u}if(typeof d.title<"u")u.title=d.title;if(typeof d.description<"u")u.description=d.description;if(typeof d.paramsSchema<"u")u.inputSchema=Yc(d.paramsSchema);if(typeof d.outputSchema<"u")u.outputSchema=Yc(d.outputSchema);if(typeof d.callback<"u")u.handler=d.callback;if(typeof d.annotations<"u")u.annotations=d.annotations;if(typeof d._meta<"u")u._meta=d._meta;if(typeof d.enabled<"u")u.enabled=d.enabled;this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r,o,n,i;if(typeof t[0]==="string")r=t.shift();if(t.length>1){let a=t[0];if(u$(a)){if(o=t.shift(),t.length>1&&typeof t[0]==="object"&&t[0]!==null&&!u$(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,o,n,i,{taskSupport:"forbidden"},void 0,s)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:o,description:n,inputSchema:i,outputSchema:s,annotations:a,_meta:c}=t;return this._createRegisteredTool(e,o,n,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 o;if(t.length>1)o=t.shift();let n=t[0],i=this._createRegisteredPrompt(e,void 0,r,o,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:o,description:n,argsSchema:i}=t,s=this._createRegisteredPrompt(e,o,n,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 Rme={type:"object",properties:{}};function M3(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function B3(e){return"_def"in e||"_zod"in e||M3(e)}function u$(e){if(typeof e!=="object"||e===null)return!1;if(B3(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some(M3)}function z3(e){if(!e)return;if(u$(e))return Yc(e);if(!B3(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function Ome(e){let t=Ta(e);if(!t)return[];return Object.entries(t).map(([r,o])=>{let n=O4(o),i=C4(o);return{name:r,description:n,required:!i}})}function Na(e){let r=Ta(e)?.method;if(!r)throw Error("Schema is missing a method literal");let o=Jx(r);if(typeof o==="string")return o;throw Error("Schema method literal must be a string")}function N3(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var eg={completion:{values:[],hasMore:!1}};import U3 from"node:process";class d${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),Cme(t)}clear(){this._buffer=void 0}}function Cme(e){return tD.parse(JSON.parse(e))}function D3(e){return JSON.stringify(e)+`
136
- `}class p${constructor(e=U3.stdin,t=U3.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new d$,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=D3(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var C_={name:"@0xmonaco/mcp-server",version:"1.0.40",type:"module",repository:{type:"git",url:"https://github.com/Monaco-Research/monaco-sdk.git",directory:"packages/mcp-server"},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.40","@0xmonaco/types":"1.0.40","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.53.1",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var z_=["read","market-maker","full"],_i=[{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 open interest 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. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",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. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_order before retrying; never blind-retry.",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 filter).",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:"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 PitPass 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) PitPass TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom PitPass TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your PitPass rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned PitPass rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",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"}],J6e=_i.map((e)=>e.name),L3=_i.filter((e)=>e.authMode==="public").map((e)=>e.name),Y6e=_i.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),Q6e=_i.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),X6e=_i.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),e$e=_i.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),j3=_i.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name),Nme=new Map(_i.map((e)=>[e.name,e.sideEffect]));function F3(e){let t=Nme.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var q3={read:0,"market-maker":1,full:2},f$=L3,m$=Object.fromEntries(_i.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),H3=Object.fromEntries(Object.entries(m$).map(([e,t])=>[e,t.capability])),n$e=new Set(j3);function G3(e){let t=m$[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function V3(e){return G3(e)==="read"}function Z3(e,t){if(t.network==="mainnet"&&m$[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(f$.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return q3[t.capability]>=q3[G3(e)]}var Mme=new Set([...f$,...Object.keys(H3)]),Bme={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 W3(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function su(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 o=["mainnet","development","staging","local"],n=e.MONACO_NETWORK;if(t&&!n)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${o.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=n||"mainnet";if(!o.includes(i))throw Error(`MONACO_NETWORK must be one of: ${o.join(", ")}.`);let s=i,a=e.MONACO_CAPABILITY;if(a&&!z_.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${z_.join(", ")}.`);let c=a||"read",u=W3(e.MONACO_TOOL_ALLOWLIST),d=W3(e.MONACO_TOOL_DENYLIST),p=[...u,...d].filter((y)=>!Mme.has(y)).length;if(p>0)throw Error(`${p} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let m=e.MONACO_RPC_URL||Bme[s],h=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let y=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!y)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).");h=y}return{privateKey:t,clientId:r,network:s,seiRpcUrl:m,capability:c,allow:u,deny:d,delegatedOwnerUserId:h}}function Dme(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function Ma(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>Ma(r));let t={};for(let[r,o]of Object.entries(e))t[Dme(r)]=typeof o==="object"&&o!==null?Ma(o):o;return t}lo();ig();lo();O$();xu();yu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Ei=BigInt(0),mn=BigInt(1),NF=BigInt(2),she=BigInt(8),ahe={zip215:!0};function che(e){let t=cg(e);return Fo(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function MF(e){let t=che(e),{Fp:r,n:o,prehash:n,hash:i,randomBytes:s,nByteLength:a,h:c}=t,u=NF<<BigInt(a*8)-mn,d=r.create,p=vs(t.n,t.nBitLength);function m(C,U){let N=r.sqr(C),Y=r.sqr(U),X=r.add(r.mul(t.a,N),Y),ce=r.add(r.ONE,r.mul(t.d,r.mul(N,Y)));return r.eql(X,ce)}if(!m(t.Gx,t.Gy))throw Error("bad curve params: generator point");let h=t.uvRatio||((C,U)=>{try{return{isValid:!0,value:r.sqrt(C*r.inv(U))}}catch(N){return{isValid:!1,value:Ei}}}),y=t.adjustScalarBytes||((C)=>C),x=t.domain||((C,U,N)=>{if(Si("phflag",N),U.length||N)throw Error("Contexts/pre-hash are not supported");return C});function S(C,U,N=!1){let Y=N?mn:Ei;pn("coordinate "+C,U,Y,u)}function v(C){if(!(C instanceof _))throw Error("ExtendedPoint expected")}let E=Fd((C,U)=>{let{ex:N,ey:Y,ez:X}=C,ce=C.is0();if(U==null)U=ce?she:r.inv(X);let Z=d(N*U),me=d(Y*U),Me=d(X*U);if(ce)return{x:Ei,y:mn};if(Me!==mn)throw Error("invZ was invalid");return{x:Z,y:me}}),w=Fd((C)=>{let{a:U,d:N}=t;if(C.is0())throw Error("bad point: ZERO");let{ex:Y,ey:X,ez:ce,et:Z}=C,me=d(Y*Y),Me=d(X*X),Be=d(ce*ce),Le=d(Be*Be),Ut=d(me*U),bt=d(Be*d(Ut+Me)),cr=d(Le+d(N*d(me*Me)));if(bt!==cr)throw Error("bad point: equation left != right (1)");let Zr=d(Y*X),tr=d(ce*Z);if(Zr!==tr)throw Error("bad point: equation left != right (2)");return!0});class _{constructor(C,U,N,Y){S("x",C),S("y",U),S("z",N,!0),S("t",Y),this.ex=C,this.ey=U,this.ez=N,this.et=Y,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(C){if(C instanceof _)throw Error("extended point not allowed");let{x:U,y:N}=C||{};return S("x",U),S("y",N),new _(U,N,mn,d(U*N))}static normalizeZ(C){let U=xs(r,C.map((N)=>N.ez));return C.map((N,Y)=>N.toAffine(U[Y])).map(_.fromAffine)}static msm(C,U){return H_(_,p,C,U)}_setWindowSize(C){O.setWindowSize(this,C)}assertValidity(){w(this)}equals(C){v(C);let{ex:U,ey:N,ez:Y}=this,{ex:X,ey:ce,ez:Z}=C,me=d(U*Z),Me=d(X*Y),Be=d(N*Z),Le=d(ce*Y);return me===Me&&Be===Le}is0(){return this.equals(_.ZERO)}negate(){return new _(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:C}=t,{ex:U,ey:N,ez:Y}=this,X=d(U*U),ce=d(N*N),Z=d(NF*d(Y*Y)),me=d(C*X),Me=U+N,Be=d(d(Me*Me)-X-ce),Le=me+ce,Ut=Le-Z,bt=me-ce,cr=d(Be*Ut),Zr=d(Le*bt),tr=d(Be*bt),En=d(Ut*Le);return new _(cr,Zr,En,tr)}add(C){v(C);let{a:U,d:N}=t,{ex:Y,ey:X,ez:ce,et:Z}=this,{ex:me,ey:Me,ez:Be,et:Le}=C,Ut=d(Y*me),bt=d(X*Me),cr=d(Z*N*Le),Zr=d(ce*Be),tr=d((Y+X)*(me+Me)-Ut-bt),En=Zr-cr,Wr=Zr+cr,Ws=d(bt-U*Ut),Cf=d(tr*En),sl=d(Wr*Ws),Dy=d(tr*Ws),To=d(En*Wr);return new _(Cf,sl,To,Dy)}subtract(C){return this.add(C.negate())}wNAF(C){return O.wNAFCached(this,C,_.normalizeZ)}multiply(C){let U=C;pn("scalar",U,mn,o);let{p:N,f:Y}=this.wNAF(U);return _.normalizeZ([N,Y])[0]}multiplyUnsafe(C,U=_.ZERO){let N=C;if(pn("scalar",N,Ei,o),N===Ei)return P;if(this.is0()||N===mn)return this;return O.wNAFCachedUnsafe(this,N,_.normalizeZ,U)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,o).is0()}toAffine(C){return E(this,C)}clearCofactor(){let{h:C}=t;if(C===mn)return this;return this.multiplyUnsafe(C)}static fromHex(C,U=!1){let{d:N,a:Y}=t,X=r.BYTES;C=yt("pointHex",C,X),Si("zip215",U);let ce=C.slice(),Z=C[X-1];ce[X-1]=Z&-129;let me=mu(ce),Me=U?u:r.ORDER;pn("pointHex.y",me,Ei,Me);let Be=d(me*me),Le=d(Be-mn),Ut=d(N*Be-Y),{isValid:bt,value:cr}=h(Le,Ut);if(!bt)throw Error("Point.fromHex: invalid y coordinate");let Zr=(cr&mn)===mn,tr=(Z&128)!==0;if(!U&&cr===Ei&&tr)throw Error("Point.fromHex: x=0 and x_0=1");if(tr!==Zr)cr=d(-cr);return _.fromAffine({x:cr,y:me})}static fromPrivateKey(C){let{scalar:U}=k(C);return T.multiply(U)}toRawBytes(){let{x:C,y:U}=this.toAffine(),N=jd(U,r.BYTES);return N[N.length-1]|=C&mn?128:0,N}toHex(){return La(this.toRawBytes())}}_.BASE=new _(t.Gx,t.Gy,mn,d(t.Gx*t.Gy)),_.ZERO=new _(Ei,mn,mn,Ei);let{BASE:T,ZERO:P}=_,O=q_(_,a*8);function z(C){return lt(C,o)}function B(C){return z(mu(C))}function k(C){let U=r.BYTES;C=yt("private key",C,U);let N=yt("hashed private key",i(C),2*U),Y=y(N.slice(0,U)),X=N.slice(U,2*U),ce=B(Y);return{head:Y,prefix:X,scalar:ce}}function G(C){let{head:U,prefix:N,scalar:Y}=k(C),X=T.multiply(Y),ce=X.toRawBytes();return{head:U,prefix:N,scalar:Y,point:X,pointBytes:ce}}function V(C){return G(C).pointBytes}function ue(C=Uint8Array.of(),...U){let N=vr(...U);return B(i(x(N,yt("context",C),!!n)))}function W(C,U,N={}){if(C=yt("message",C),n)C=n(C);let{prefix:Y,scalar:X,pointBytes:ce}=G(U),Z=ue(N.context,Y,C),me=T.multiply(Z).toRawBytes(),Me=ue(N.context,me,ce,C),Be=z(Z+Me*X);pn("signature.s",Be,Ei,o);let Le=vr(me,jd(Be,r.BYTES));return yt("result",Le,r.BYTES*2)}let H=ahe;function fe(C,U,N,Y=H){let{context:X,zip215:ce}=Y,Z=r.BYTES;if(C=yt("signature",C,2*Z),U=yt("message",U),N=yt("publicKey",N,Z),ce!==void 0)Si("zip215",ce);if(n)U=n(U);let me=mu(C.slice(Z,2*Z)),Me,Be,Le;try{Me=_.fromHex(N,ce),Be=_.fromHex(C.slice(0,Z),ce),Le=T.multiplyUnsafe(me)}catch(cr){return!1}if(!ce&&Me.isSmallOrder())return!1;let Ut=ue(X,Be.toRawBytes(),Me.toRawBytes(),U);return Be.add(Me.multiplyUnsafe(Ut)).subtract(Le).clearCofactor().equals(_.ZERO)}return T._setWindowSize(8),{CURVE:t,getPublicKey:V,sign:W,verify:fe,ExtendedPoint:_,utils:{getExtendedPublicKey:G,randomPrivateKey:()=>s(r.BYTES),precompute(C=8,U=_.BASE){return U._setWindowSize(C),U.multiply(BigInt(3)),U}}}}xu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var C$=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),jF=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),U$e=BigInt(0),fhe=BigInt(1),FF=BigInt(2),L$e=BigInt(3),mhe=BigInt(5),hhe=BigInt(8);function ghe(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=C$,a=e*e%i*e%i,c=Vt(a,FF,i)*a%i,u=Vt(c,fhe,i)*e%i,d=Vt(u,mhe,i)*u%i,p=Vt(d,t,i)*d%i,m=Vt(p,r,i)*p%i,h=Vt(m,o,i)*m%i,y=Vt(h,n,i)*h%i,x=Vt(y,n,i)*h%i,S=Vt(x,t,i)*d%i;return{pow_p_5_8:Vt(S,FF,i)*e%i,b2:a}}function yhe(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function bhe(e,t){let r=C$,o=lt(t*t*t,r),n=lt(o*o*t,r),i=ghe(e*n).pow_p_5_8,s=lt(e*o*i,r),a=lt(t*s*s,r),c=s,u=lt(s*jF,r),d=a===e,p=a===lt(-e,r),m=a===lt(-e*jF,r);if(d)s=c;if(p||m)s=u;if(kF(s,r))s=lt(-s,r);return{isValid:d||p,value:s}}var qF=(()=>vs(C$,void 0,!0))(),xhe=(()=>({a:qF.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:qF,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:hhe,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:gF,randomBytes:Ud,adjustScalarBytes:yhe,uvRatio:bhe}))(),G_=(()=>MF(xhe))();ig();lo();function V_(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=G_.utils.randomPrivateKey();return{publicKey:G_.getPublicKey(e),privateKey:e}}function Z_(e){return uu(e.publicKey)}function W_(e){return uu(e.privateKey)}function HF(e,t){return{publicKey:tg(e),privateKey:tg(t)}}function GF(e){return uu(gs(e))}function VF(e,t,r,o){return`${e.toUpperCase()}
136
+ `}class p${constructor(e=U3.stdin,t=U3.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new d$,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=D3(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var C_={name:"@0xmonaco/mcp-server",version:"1.0.41",type:"module",repository:{type:"git",url:"https://github.com/Monaco-Research/monaco-sdk.git",directory:"packages/mcp-server"},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.41","@0xmonaco/types":"1.0.41","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.53.1",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var z_=["read","market-maker","full"],_i=[{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 open interest 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. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",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. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_orders/get_order before retrying; never blind-retry.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — after an ambiguous failure (timeout/network error/5xx with no order), reconcile with get_order before retrying; never blind-retry.",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 filter).",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:"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 PitPass 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) PitPass TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom PitPass TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your PitPass rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned PitPass rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",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"}],J6e=_i.map((e)=>e.name),L3=_i.filter((e)=>e.authMode==="public").map((e)=>e.name),Y6e=_i.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),Q6e=_i.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),X6e=_i.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),e$e=_i.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),j3=_i.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name),Nme=new Map(_i.map((e)=>[e.name,e.sideEffect]));function F3(e){let t=Nme.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var q3={read:0,"market-maker":1,full:2},f$=L3,m$=Object.fromEntries(_i.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),H3=Object.fromEntries(Object.entries(m$).map(([e,t])=>[e,t.capability])),n$e=new Set(j3);function G3(e){let t=m$[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function V3(e){return G3(e)==="read"}function Z3(e,t){if(t.network==="mainnet"&&m$[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(f$.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return q3[t.capability]>=q3[G3(e)]}var Mme=new Set([...f$,...Object.keys(H3)]),Bme={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 W3(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function su(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 o=["mainnet","development","staging","local"],n=e.MONACO_NETWORK;if(t&&!n)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${o.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=n||"mainnet";if(!o.includes(i))throw Error(`MONACO_NETWORK must be one of: ${o.join(", ")}.`);let s=i,a=e.MONACO_CAPABILITY;if(a&&!z_.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${z_.join(", ")}.`);let c=a||"read",u=W3(e.MONACO_TOOL_ALLOWLIST),d=W3(e.MONACO_TOOL_DENYLIST),p=[...u,...d].filter((y)=>!Mme.has(y)).length;if(p>0)throw Error(`${p} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let m=e.MONACO_RPC_URL||Bme[s],h=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let y=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!y)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).");h=y}return{privateKey:t,clientId:r,network:s,seiRpcUrl:m,capability:c,allow:u,deny:d,delegatedOwnerUserId:h}}function Dme(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function Ma(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>Ma(r));let t={};for(let[r,o]of Object.entries(e))t[Dme(r)]=typeof o==="object"&&o!==null?Ma(o):o;return t}lo();ig();lo();O$();xu();yu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Ei=BigInt(0),mn=BigInt(1),NF=BigInt(2),she=BigInt(8),ahe={zip215:!0};function che(e){let t=cg(e);return Fo(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function MF(e){let t=che(e),{Fp:r,n:o,prehash:n,hash:i,randomBytes:s,nByteLength:a,h:c}=t,u=NF<<BigInt(a*8)-mn,d=r.create,p=vs(t.n,t.nBitLength);function m(C,U){let N=r.sqr(C),Y=r.sqr(U),X=r.add(r.mul(t.a,N),Y),ce=r.add(r.ONE,r.mul(t.d,r.mul(N,Y)));return r.eql(X,ce)}if(!m(t.Gx,t.Gy))throw Error("bad curve params: generator point");let h=t.uvRatio||((C,U)=>{try{return{isValid:!0,value:r.sqrt(C*r.inv(U))}}catch(N){return{isValid:!1,value:Ei}}}),y=t.adjustScalarBytes||((C)=>C),x=t.domain||((C,U,N)=>{if(Si("phflag",N),U.length||N)throw Error("Contexts/pre-hash are not supported");return C});function S(C,U,N=!1){let Y=N?mn:Ei;pn("coordinate "+C,U,Y,u)}function v(C){if(!(C instanceof _))throw Error("ExtendedPoint expected")}let E=Fd((C,U)=>{let{ex:N,ey:Y,ez:X}=C,ce=C.is0();if(U==null)U=ce?she:r.inv(X);let Z=d(N*U),me=d(Y*U),Me=d(X*U);if(ce)return{x:Ei,y:mn};if(Me!==mn)throw Error("invZ was invalid");return{x:Z,y:me}}),w=Fd((C)=>{let{a:U,d:N}=t;if(C.is0())throw Error("bad point: ZERO");let{ex:Y,ey:X,ez:ce,et:Z}=C,me=d(Y*Y),Me=d(X*X),Be=d(ce*ce),Le=d(Be*Be),Ut=d(me*U),vt=d(Be*d(Ut+Me)),cr=d(Le+d(N*d(me*Me)));if(vt!==cr)throw Error("bad point: equation left != right (1)");let Zr=d(Y*X),tr=d(ce*Z);if(Zr!==tr)throw Error("bad point: equation left != right (2)");return!0});class _{constructor(C,U,N,Y){S("x",C),S("y",U),S("z",N,!0),S("t",Y),this.ex=C,this.ey=U,this.ez=N,this.et=Y,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(C){if(C instanceof _)throw Error("extended point not allowed");let{x:U,y:N}=C||{};return S("x",U),S("y",N),new _(U,N,mn,d(U*N))}static normalizeZ(C){let U=xs(r,C.map((N)=>N.ez));return C.map((N,Y)=>N.toAffine(U[Y])).map(_.fromAffine)}static msm(C,U){return H_(_,p,C,U)}_setWindowSize(C){O.setWindowSize(this,C)}assertValidity(){w(this)}equals(C){v(C);let{ex:U,ey:N,ez:Y}=this,{ex:X,ey:ce,ez:Z}=C,me=d(U*Z),Me=d(X*Y),Be=d(N*Z),Le=d(ce*Y);return me===Me&&Be===Le}is0(){return this.equals(_.ZERO)}negate(){return new _(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:C}=t,{ex:U,ey:N,ez:Y}=this,X=d(U*U),ce=d(N*N),Z=d(NF*d(Y*Y)),me=d(C*X),Me=U+N,Be=d(d(Me*Me)-X-ce),Le=me+ce,Ut=Le-Z,vt=me-ce,cr=d(Be*Ut),Zr=d(Le*vt),tr=d(Be*vt),En=d(Ut*Le);return new _(cr,Zr,En,tr)}add(C){v(C);let{a:U,d:N}=t,{ex:Y,ey:X,ez:ce,et:Z}=this,{ex:me,ey:Me,ez:Be,et:Le}=C,Ut=d(Y*me),vt=d(X*Me),cr=d(Z*N*Le),Zr=d(ce*Be),tr=d((Y+X)*(me+Me)-Ut-vt),En=Zr-cr,Wr=Zr+cr,Ws=d(vt-U*Ut),Cf=d(tr*En),sl=d(Wr*Ws),Dy=d(tr*Ws),To=d(En*Wr);return new _(Cf,sl,To,Dy)}subtract(C){return this.add(C.negate())}wNAF(C){return O.wNAFCached(this,C,_.normalizeZ)}multiply(C){let U=C;pn("scalar",U,mn,o);let{p:N,f:Y}=this.wNAF(U);return _.normalizeZ([N,Y])[0]}multiplyUnsafe(C,U=_.ZERO){let N=C;if(pn("scalar",N,Ei,o),N===Ei)return P;if(this.is0()||N===mn)return this;return O.wNAFCachedUnsafe(this,N,_.normalizeZ,U)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,o).is0()}toAffine(C){return E(this,C)}clearCofactor(){let{h:C}=t;if(C===mn)return this;return this.multiplyUnsafe(C)}static fromHex(C,U=!1){let{d:N,a:Y}=t,X=r.BYTES;C=yt("pointHex",C,X),Si("zip215",U);let ce=C.slice(),Z=C[X-1];ce[X-1]=Z&-129;let me=mu(ce),Me=U?u:r.ORDER;pn("pointHex.y",me,Ei,Me);let Be=d(me*me),Le=d(Be-mn),Ut=d(N*Be-Y),{isValid:vt,value:cr}=h(Le,Ut);if(!vt)throw Error("Point.fromHex: invalid y coordinate");let Zr=(cr&mn)===mn,tr=(Z&128)!==0;if(!U&&cr===Ei&&tr)throw Error("Point.fromHex: x=0 and x_0=1");if(tr!==Zr)cr=d(-cr);return _.fromAffine({x:cr,y:me})}static fromPrivateKey(C){let{scalar:U}=k(C);return T.multiply(U)}toRawBytes(){let{x:C,y:U}=this.toAffine(),N=jd(U,r.BYTES);return N[N.length-1]|=C&mn?128:0,N}toHex(){return La(this.toRawBytes())}}_.BASE=new _(t.Gx,t.Gy,mn,d(t.Gx*t.Gy)),_.ZERO=new _(Ei,mn,mn,Ei);let{BASE:T,ZERO:P}=_,O=q_(_,a*8);function z(C){return lt(C,o)}function B(C){return z(mu(C))}function k(C){let U=r.BYTES;C=yt("private key",C,U);let N=yt("hashed private key",i(C),2*U),Y=y(N.slice(0,U)),X=N.slice(U,2*U),ce=B(Y);return{head:Y,prefix:X,scalar:ce}}function G(C){let{head:U,prefix:N,scalar:Y}=k(C),X=T.multiply(Y),ce=X.toRawBytes();return{head:U,prefix:N,scalar:Y,point:X,pointBytes:ce}}function V(C){return G(C).pointBytes}function ue(C=Uint8Array.of(),...U){let N=vr(...U);return B(i(x(N,yt("context",C),!!n)))}function W(C,U,N={}){if(C=yt("message",C),n)C=n(C);let{prefix:Y,scalar:X,pointBytes:ce}=G(U),Z=ue(N.context,Y,C),me=T.multiply(Z).toRawBytes(),Me=ue(N.context,me,ce,C),Be=z(Z+Me*X);pn("signature.s",Be,Ei,o);let Le=vr(me,jd(Be,r.BYTES));return yt("result",Le,r.BYTES*2)}let H=ahe;function fe(C,U,N,Y=H){let{context:X,zip215:ce}=Y,Z=r.BYTES;if(C=yt("signature",C,2*Z),U=yt("message",U),N=yt("publicKey",N,Z),ce!==void 0)Si("zip215",ce);if(n)U=n(U);let me=mu(C.slice(Z,2*Z)),Me,Be,Le;try{Me=_.fromHex(N,ce),Be=_.fromHex(C.slice(0,Z),ce),Le=T.multiplyUnsafe(me)}catch(cr){return!1}if(!ce&&Me.isSmallOrder())return!1;let Ut=ue(X,Be.toRawBytes(),Me.toRawBytes(),U);return Be.add(Me.multiplyUnsafe(Ut)).subtract(Le).clearCofactor().equals(_.ZERO)}return T._setWindowSize(8),{CURVE:t,getPublicKey:V,sign:W,verify:fe,ExtendedPoint:_,utils:{getExtendedPublicKey:G,randomPrivateKey:()=>s(r.BYTES),precompute(C=8,U=_.BASE){return U._setWindowSize(C),U.multiply(BigInt(3)),U}}}}xu();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var C$=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),jF=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),U$e=BigInt(0),fhe=BigInt(1),FF=BigInt(2),L$e=BigInt(3),mhe=BigInt(5),hhe=BigInt(8);function ghe(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=C$,a=e*e%i*e%i,c=Vt(a,FF,i)*a%i,u=Vt(c,fhe,i)*e%i,d=Vt(u,mhe,i)*u%i,p=Vt(d,t,i)*d%i,m=Vt(p,r,i)*p%i,h=Vt(m,o,i)*m%i,y=Vt(h,n,i)*h%i,x=Vt(y,n,i)*h%i,S=Vt(x,t,i)*d%i;return{pow_p_5_8:Vt(S,FF,i)*e%i,b2:a}}function yhe(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function bhe(e,t){let r=C$,o=lt(t*t*t,r),n=lt(o*o*t,r),i=ghe(e*n).pow_p_5_8,s=lt(e*o*i,r),a=lt(t*s*s,r),c=s,u=lt(s*jF,r),d=a===e,p=a===lt(-e,r),m=a===lt(-e*jF,r);if(d)s=c;if(p||m)s=u;if(kF(s,r))s=lt(-s,r);return{isValid:d||p,value:s}}var qF=(()=>vs(C$,void 0,!0))(),xhe=(()=>({a:qF.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:qF,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:hhe,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:gF,randomBytes:Ud,adjustScalarBytes:yhe,uvRatio:bhe}))(),G_=(()=>MF(xhe))();ig();lo();function V_(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=G_.utils.randomPrivateKey();return{publicKey:G_.getPublicKey(e),privateKey:e}}function Z_(e){return uu(e.publicKey)}function W_(e){return uu(e.privateKey)}function HF(e,t){return{publicKey:tg(e),privateKey:tg(t)}}function GF(e){return uu(gs(e))}function VF(e,t,r,o){return`${e.toUpperCase()}
137
137
  ${t}
138
138
  ${r}
139
139
  ${o}`}function ZF(e,t){return`WS-AUTH
140
140
  ${e}
141
- ${t}`}function K_(e,t){return uu(G_.sign(Dd(t),e))}var lg=[0.0001,0.001,0.01,0.1,1,10,100,1000,1e4];var vhe=1e4,_he=15000,whe=30000,She=1000,The=["created","activated","cancelled","parent_cancelled","triggered","failed","oco_cancelled"],Ehe=["STOP_LOSS","TAKE_PROFIT"],Ihe=["MARK_PRICE"],Phe=["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],khe=["POSITION","PARENT_ORDER"];function qd(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Ct(e,t){let r=e[t];if(typeof r!=="string"||r.length===0)throw Error(`Invalid WebSocket event: ${t} must be a non-empty string`);return r}function ur(e,t){let r=e[t];if(r===void 0||r===null)return;if(typeof r!=="string")throw Error(`Invalid WebSocket event: ${t} must be a string`);return r}function Ahe(e,t){let r=e[t];if(typeof r!=="boolean")throw Error(`Invalid WebSocket event: ${t} must be a boolean`);return r}function $he(e,t){let r=e[t];if(r===void 0||r===null)return;if(typeof r!=="number"||!Number.isFinite(r))throw Error(`Invalid WebSocket event: ${t} must be a finite number`);return r}function Ii(e,t,r){let o=Ct(e,t);if(!r.includes(o))throw Error(`Invalid WebSocket event: ${t} must be one of ${r.join(", ")}`);return o}function WF(e,t,r){let o=e[t];if(o===void 0||o===null)return;if(typeof o!=="string"||!r.includes(o))throw Error(`Invalid WebSocket event: ${t} must be one of ${r.join(", ")}`);return o}function Rhe(e){if(!qd(e))throw Error("Invalid conditional order event: payload must be an object");if(!qd(e.data))throw Error("Invalid conditional order event: data must be an object");let t=Ma(e.data);return{eventType:Ii(e,"event_type",["conditional_order_update"]),userId:Ct(e,"user_id"),data:{conditionalOrderId:Ct(t,"conditionalOrderId"),tradingPairId:Ct(t,"tradingPairId"),marginAccountId:Ct(t,"marginAccountId"),positionId:ur(t,"positionId"),parentOrderId:ur(t,"parentOrderId"),associationType:WF(t,"associationType",khe),linkedGroupId:ur(t,"linkedGroupId"),conditionType:Ii(t,"conditionType",Ehe),triggerSource:Ii(t,"triggerSource",Ihe),triggerPrice:Ct(t,"triggerPrice"),side:Ii(t,"side",["BUY","SELL"]),positionSide:Ii(t,"positionSide",["LONG","SHORT","NONE"]),orderType:Ii(t,"orderType",["LIMIT","MARKET"]),limitPrice:ur(t,"limitPrice"),quantity:ur(t,"quantity"),slippageToleranceBps:$he(t,"slippageToleranceBps"),reduceOnly:Ahe(t,"reduceOnly"),timeInForce:WF(t,"timeInForce",["GTC","IOC"]),state:Ii(t,"state",Phe),triggeredOrderId:ur(t,"triggeredOrderId"),triggeredAt:ur(t,"triggeredAt"),activatedAt:ur(t,"activatedAt"),cancelledAt:ur(t,"cancelledAt"),expiresAt:ur(t,"expiresAt"),failureReason:ur(t,"failureReason"),reason:Ii(t,"reason",The),updatedAt:Ct(t,"updatedAt")}}}function Ohe(e){if(!qd(e))throw Error("Invalid position event: payload must be an object");if(!qd(e.data))throw Error("Invalid position event: data must be an object");let t=Ma(e.data);return{eventType:Ii(e,"event_type",["position_update"]),userId:Ct(e,"user_id"),data:{positionId:Ct(t,"positionId"),marginAccountId:Ct(t,"marginAccountId"),tradingPairId:Ct(t,"tradingPairId"),side:Ct(t,"side"),status:Ct(t,"status"),size:Ct(t,"size"),entryPrice:Ct(t,"entryPrice"),markPrice:ur(t,"markPrice"),unrealizedPnl:ur(t,"unrealizedPnl"),liquidationPrice:ur(t,"liquidationPrice"),isolatedMargin:Ct(t,"isolatedMargin"),leverage:Ct(t,"leverage"),tradeId:ur(t,"tradeId"),orderId:ur(t,"orderId"),reason:Ct(t,"reason"),updatedAt:Ct(t,"updatedAt")}}}function Che(e){if(!qd(e))throw Error("Invalid liquidation event: payload must be an object");if(!qd(e.data))throw Error("Invalid liquidation event: data must be an object");let t=Ma(e.data);return{eventType:Ii(e,"event_type",["liquidation_alert"]),userId:Ct(e,"user_id"),data:{liquidationId:Ct(t,"liquidationId"),marginAccountId:Ct(t,"marginAccountId"),positionId:ur(t,"positionId"),tradingPairId:ur(t,"tradingPairId"),status:Ct(t,"status"),accountState:Ct(t,"accountState"),liquidationPrice:ur(t,"liquidationPrice"),markPrice:ur(t,"markPrice"),estimatedShortfall:Ct(t,"estimatedShortfall"),message:Ct(t,"message"),triggeredAt:Ct(t,"triggeredAt")}}}function z$(e,t={}){let r=null,o=t.session,n=0,i=null,s=null,a=t.autoReconnect??!0,c=t.maxReconnectAttempts??Number.POSITIVE_INFINITY,u=Number.isFinite(t.reconnectBaseDelayMs)&&t.reconnectBaseDelayMs>0?t.reconnectBaseDelayMs:She,d=Number.isFinite(t.connectionTimeoutMs)&&t.connectionTimeoutMs>0?t.connectionTimeoutMs:vhe,p=null,m=new Map,h=()=>{if(!r)return i?"reconnecting":"disconnected";switch(r.readyState){case WebSocket.CONNECTING:return"connecting";case WebSocket.OPEN:return"connected";default:return i?"reconnecting":"disconnected"}},y=()=>e,x=()=>{if(!o||r?.readyState!==WebSocket.OPEN)return;let N=Date.now(),Y=K_(tg(o.privateKey),ZF(o.publicKey,N));r.send(JSON.stringify({type:"Authenticate",public_key:o.publicKey,timestamp:N,signature:Y}))},S=()=>{if(s)clearInterval(s),s=null},v=()=>{S(),s=setInterval(()=>{if(r?.readyState===WebSocket.OPEN)r.send(JSON.stringify({type:"Ping"}))},_he)},E=()=>{if(i)clearTimeout(i),i=null},w=()=>{if(i)return;if(!a||n>=c){console.error("WebSocket: Max reconnect attempts reached");return}let N=Math.min(u*2**n,whe);n++;let Y=Math.random()*N;i=setTimeout(()=>{if(i=null,!a)return;O().catch((X)=>{console.warn("WebSocket: Failed to reconnect:",X),w()})},Y),t.onStatusChange?.("reconnecting")},_=(N)=>{if(r?.readyState===WebSocket.OPEN)r.send(JSON.stringify(N))},T=()=>{let N=Array.from(m.keys());if(N.length>0)_({type:"Subscribe",channels:N})},P=(N)=>{if(N.type!=="Event"||!N.channel)return;for(let[Y,X]of m)if(N.channel===Y||N.channel.startsWith(`${Y}:`))for(let ce of X)ce(N.data)},O=()=>new Promise((N,Y)=>{if(r?.readyState===WebSocket.CONNECTING||r?.readyState===WebSocket.OPEN){N();return}try{let X=new WebSocket(y());r=X;let ce=setTimeout(()=>{if(r!==X){N();return}if(X.readyState===WebSocket.CONNECTING)X.close(1000,"Connection timeout"),Y(Error("WebSocket connection timeout"))},d);X.onopen=()=>{if(clearTimeout(ce),r!==X){N();return}if(n=0,E(),v(),x(),T(),t.onStatusChange?.("connected"),p!==null){let Z=p;p=null,t.onResync?.({code:Z,slowClient:Z===1013})}N()},X.onmessage=(Z)=>{if(r!==X)return;try{let me=JSON.parse(Z.data);if(me.type==="Pong")return;if(me.type==="Ping"){_({type:"Pong"});return}P(me)}catch(me){console.warn("WebSocket: Failed to parse message",me)}},X.onclose=(Z)=>{if(clearTimeout(ce),r!==X){N();return}if(r=null,S(),a&&Z.code!==1000){if(p===null||Z.code===1013)p=Z.code;w()}if(!i)t.onStatusChange?.("disconnected")},X.onerror=()=>clearTimeout(ce)}catch(X){t.onStatusChange?.("disconnected"),Y(X)}}),z=()=>{a=!1,E(),S(),p=null,m.clear(),r?.close(1000,"Client disconnect"),r=null,t.onStatusChange?.("disconnected")},B=(N,Y)=>{let X=!m.has(N);if(!m.has(N))m.set(N,new Set);if(m.get(N)?.add(Y),X&&r?.readyState===WebSocket.OPEN)_({type:"Subscribe",channels:[N]});return()=>{let ce=m.get(N);if(ce){if(ce.delete(Y),ce.size===0){if(m.delete(N),r?.readyState===WebSocket.OPEN)_({type:"Unsubscribe",channels:[N]})}}}};return{connect:O,disconnect:z,isConnected:()=>r?.readyState===WebSocket.OPEN,getStatus:h,setSessionKeypair:(N)=>{if(o=N??void 0,o&&r?.readyState===WebSocket.OPEN)x();else if(o&&(!r||r.readyState===WebSocket.CLOSED))O().catch((Y)=>{console.warn("WebSocket: Failed to connect after session update:",Y)})},orders:(N,Y,X)=>{let ce=`orders:${N}:${Y}`;return B(ce,(Z)=>{try{let me=Z,Me={orderId:me.order_id,eventType:me.event_type,timestamp:me.timestamp,data:Ma(me.data)};X(Me)}catch(me){console.error("WebSocket: Error processing order event",me)}})},orderbook:(N,Y,X,ce,Z)=>{if(!N||!Y||X===void 0||!ce)throw Error(`orderbook subscription requires all params: tradingPairId="${N}", tradingMode="${Y}", magnitude=${X} (valid: ${lg.join(", ")}), quotationMode="${ce}" (valid: "BASE", "QUOTE")`);if(!lg.includes(X))throw Error(`Invalid magnitude: ${X}. Must be one of: ${lg.join(", ")}`);let me=`orderbook:${N}:${Y}:${X}:${ce.toLowerCase()}`;return B(me,(Me)=>{try{let Be=Me,Le=Be.data,Ut={tradingPairId:Be.trading_pair_id,tradingMode:Be.trading_mode,bids:(Le?.bids||[]).map((bt)=>({price:bt.price,quantity:bt.quantity,orderCount:bt.order_count||0})),asks:(Le?.asks||[]).map((bt)=>({price:bt.price,quantity:bt.quantity,orderCount:bt.order_count||0})),bestBid:Le?.best_bid??void 0,bestAsk:Le?.best_ask??void 0,bidVolume:Le?.bid_volume||void 0,askVolume:Le?.ask_volume||void 0,priceChange:Le?.price_change?{side:Le.price_change.side,oldPrice:Le.price_change.old_price??void 0,newPrice:Le.price_change.new_price??void 0,levelRemoved:Le.price_change.level_removed||!1,levelAdded:Le.price_change.level_added||!1}:void 0,baseDecimals:Be.base_decimals||0,quoteDecimals:Be.quote_decimals||0,timestamp:Be.timestamp||new Date().toISOString(),sequence:Be.sequence_number||0};Z(Ut)}catch(Be){console.error("WebSocket: Error processing orderbook event",Be)}})},ohlcv:(N,Y,X,ce)=>{let Z=`ohlcv:${N}:${Y}:${X}`;return B(Z,(me)=>{try{let Me=me,Be=Me.data,Le={tradingPairId:Me.trading_pair_id,tradingMode:Me.trading_mode,interval:Me.interval,candlestick:{T:Be.period_start||0,t:Be.period_end||0,o:Be.open||"0",h:Be.high||"0",l:Be.low||"0",c:Be.close||"0",v:Be.volume||"0",s:Me.symbol,i:Me.interval,n:Be.trades_count||0}};ce(Le)}catch(Me){console.error("WebSocket: Error processing OHLCV event",Me)}})},trades:(N,Y)=>{let X=`trades:${N}`;return B(X,(ce)=>{try{let Z=ce,me=Z.data,Me={eventType:"trade",tradingPairId:Z.trading_pair_id,tradingMode:Z.trading_mode.toUpperCase(),data:{tradeId:me.trade_id,price:me.price,quantity:me.quantity,makerSide:me.maker_side.toUpperCase(),executedAt:me.executed_at}};Y(Me)}catch(Z){console.error("WebSocket: Error processing trade event",Z)}})},movements:(N)=>B("movements",(X)=>{try{let ce=X,Z=ce.data,me={eventType:"movement",userId:ce.user_id,data:{id:Z.id,entryType:Z.entry_type,transactionType:Z.transaction_type,status:Z.status,token:Z.token??Z.token_address,tokenAddress:Z.token??Z.token_address,assetId:Z.asset_id,amount:String(Z.amount),amountRaw:Z.amount_raw,balanceBefore:Z.balance_before!=null?String(Z.balance_before):void 0,balanceAfter:Z.balance_after!=null?String(Z.balance_after):void 0,lockedBefore:Z.locked_before!=null?String(Z.locked_before):void 0,lockedAfter:Z.locked_after!=null?String(Z.locked_after):void 0,referenceId:Z.reference_id,referenceType:Z.reference_type,description:Z.description,txHash:Z.tx_hash,blockNumber:Z.block_number,createdAt:Z.created_at,decimals:Z.decimals}};N(me)}catch(ce){console.error("WebSocket: Error processing movement event",ce)}}),userOrders:(N)=>B("orders",(X)=>{try{let ce=X,Z={orderId:ce.order_id,eventType:ce.event_type,timestamp:ce.timestamp,data:Ma(ce.data)};N(Z)}catch(ce){console.error("WebSocket: Error processing user order event",ce)}}),balances:(N)=>B("balances",(X)=>{try{let ce=X,Z=ce.data,me={eventType:"balance_update",userId:ce.user_id,data:{tokenAddress:Z.token_address,tokenSymbol:Z.token_symbol,available:Z.available,availableRaw:Z.available_raw,locked:Z.locked,lockedRaw:Z.locked_raw,total:Z.total,totalRaw:Z.total_raw,reason:Z.reason,referenceId:Z.reference_id,updatedAt:Z.updated_at}};N(me)}catch(ce){console.error("WebSocket: Error processing balance event",ce)}}),conditionalOrders:(N,Y)=>{if(!N)throw Error("conditionalOrders subscription requires a handler");if(Y!==void 0&&Y.length===0)throw Error("conditionalOrders tradingPairId cannot be empty");let X=Y?`conditional_orders:${Y}`:"conditional_orders";return B(X,(ce)=>{try{N(Rhe(ce))}catch(Z){console.error("WebSocket: Error processing conditional order event",Z)}})},positions:(N,Y)=>{if(!N)throw Error("positions subscription requires a handler");if(Y!==void 0&&Y.length===0)throw Error("positions tradingPairId cannot be empty");let X=Y?`positions:${Y}`:"positions";return B(X,(ce)=>{try{N(Ohe(ce))}catch(Z){console.error("WebSocket: Error processing position event",Z)}})},liquidations:(N,Y)=>{if(!N)throw Error("liquidations subscription requires a handler");if(Y!==void 0&&Y.length===0)throw Error("liquidations tradingPairId cannot be empty");let X=Y?`liquidations:${Y}`:"liquidations";return B(X,(ce)=>{try{N(Che(ce))}catch(Z){console.error("WebSocket: Error processing liquidation event",Z)}})}}}var Fa=rn(Y_(),1),sq=["token","accessToken","access_token","refreshToken","refresh_token","authToken","auth_token","bearerToken","bearer_token","jwtToken","jwt_token","apiKey","api_key","apikey","clientSecret","client_secret","clientId","client_id","secret","password","authorization","bearer","auth","credentials","credential","email","phone","phoneNumber","phone_number","ssn","socialSecurity","social_security","address","passport","passportNumber","passport_number","driversLicense","drivers_license","cardNumber","card_number","creditCard","credit_card","cvv","pin","signature","privateKey","private_key","publicKey","public_key","mnemonic","seed","salt","hash","certificate","cert","fingerprint","cookie","session","sessionId","session_id","sessionToken","session_token","ipAddress","ip_address","deviceId","device_id","userId","user_id","accountId","account_id"];function Hd(e,t=5,r=0){if(r>=t)return"[Max depth reached]";if(e===null||e===void 0)return e;if(Array.isArray(e)){let n=e.slice(0,10).map((i)=>Hd(i,t,r+1));if(e.length>10)n.push(`[... ${e.length-10} more items]`);return n}if(typeof e==="object"){let o={};for(let[n,i]of Object.entries(e)){let s=n.toLowerCase();if(sq.some((c)=>s.includes(c.toLowerCase())))o[n]="[REDACTED]";else if(typeof i==="string"&&i.length>500)o[n]=`${i.substring(0,500)}... [truncated]`;else o[n]=Hd(i,t,r+1)}return o}if(typeof e==="string"){if(e.length>1000)return`${e.substring(0,1000)}... [truncated]`;return e}return e}class Gd extends Error{cause;suggestion;retryable=!1;timestamp;constructor(e,t){super(e);if(this.name=this.constructor.name,this.timestamp=Date.now(),t?.cause)this.cause=t.cause;if(t?.suggestion)this.suggestion=t.suggestion;if(t?.retryable!==void 0)this.retryable=t.retryable}toJSON(){return{name:this.name,code:this.code,message:this.message,suggestion:this.suggestion,retryable:this.retryable,timestamp:this.timestamp,cause:this.cause instanceof Error?this.cause.message:this.cause}}}class Bt extends Gd{code="INVALID_CONFIG";field;value;constructor(e,t,r,o){let n=t?`Check the '${t}' configuration parameter. ${Whe(t)}`:"Review your SDK configuration and ensure all required fields are provided correctly.";super(e,{cause:o,suggestion:n,retryable:!1});this.field=t,this.value=r}toJSON(){let e;if(this.field){let t=this.field.toLowerCase();if(sq.some((o)=>t.includes(o.toLowerCase())))e="[REDACTED]";else e=Hd(this.value)}else e=Hd(this.value);return{...super.toJSON(),field:this.field,value:e}}}function Whe(e){switch(e.toLowerCase()){case"walletclient":return"Ensure you're creating the wallet client with a valid account and chain configuration.";case"seirpcurl":return"Use 'https://evm-rpc-testnet.sei-apis.com' for testnet or 'https://evm-rpc.sei-apis.com' for mainnet.";case"wsurl":return"Use 'wss://ws-develop.apimonaco.xyz/ws' for testnet or 'wss://ws.apimonaco.xyz/ws' for mainnet.";case"network":return"Valid networks are: 'mainnet', 'development', 'staging', 'local'.";default:return"Refer to the SDK documentation for correct configuration format."}}class dg extends Gd{code="INVALID_STATE";currentState;expectedState;constructor(e,t,r,o){let n=r?`${t?`Current state is '${t}', `:""}Expected state is '${r}'. Ensure operations are performed in the correct order.`:"Check that prerequisites are met before calling this method.";super(e,{cause:o,suggestion:n,retryable:!1});this.currentState=t,this.expectedState=r}toJSON(){return{...super.toJSON(),currentState:this.currentState,expectedState:this.expectedState}}}class or extends Gd{code="API_ERROR";endpoint;statusCode;responseBody;requestBody;requestId;retryAfter;constructor(e,t){let{suggestion:r,retryable:o}=Khe(t?.statusCode,e,t?.responseBody);super(e,{cause:t?.cause,suggestion:r,retryable:o});this.endpoint=t?.endpoint,this.statusCode=t?.statusCode,this.responseBody=t?.responseBody,this.requestBody=t?.requestBody,this.requestId=t?.requestId,this.retryAfter=t?.retryAfter}toJSON(){return{...super.toJSON(),endpoint:this.endpoint,statusCode:this.statusCode,responseBody:Hd(this.responseBody),requestBody:Hd(this.requestBody),requestId:this.requestId,retryAfter:this.retryAfter}}}function Khe(e,t,r){if(!e)return{suggestion:"Network request failed. Check your internet connection and try again.",retryable:!0};if(e===Fa.StatusCodes.UNAUTHORIZED){if(t?.toLowerCase().includes("expired"))return{suggestion:"Access token has expired. Call sdk.refreshAuth() to get a new token, or call sdk.login() to re-authenticate.",retryable:!1};return{suggestion:"Authentication required. Call sdk.login(clientId) to authenticate before making this request.",retryable:!1}}if(e===Fa.StatusCodes.FORBIDDEN)return{suggestion:"Access denied. Ensure your application has the required permissions and your client ID is valid.",retryable:!1};if(e===Fa.StatusCodes.NOT_FOUND)return{suggestion:"Resource not found. Check that the ID or identifier is correct and the resource exists.",retryable:!1};if(e===Fa.StatusCodes.CONFLICT)return{suggestion:"Resource conflict. The resource may have been modified. Refresh and try again.",retryable:!0};if(e===Fa.StatusCodes.BAD_REQUEST){if(t?.toLowerCase().includes("insufficient balance"))return{suggestion:"Insufficient balance. Deposit more funds using sdk.vault.deposit() or reduce the order size.",retryable:!1};if(t?.toLowerCase().includes("invalid"))return{suggestion:"Invalid request parameters. Check the API documentation for correct parameter format and values.",retryable:!1};return{suggestion:"Bad request. Verify that all required parameters are provided and correctly formatted.",retryable:!1}}if(e===Fa.StatusCodes.TOO_MANY_REQUESTS){let o;if(typeof r==="object"&&r!==null&&"retry_after"in r&&r.retry_after){let n=r.retry_after;o=` Wait ${String(n)} seconds before retrying.`}else o=" Wait a moment before retrying.";return{suggestion:`Rate limit exceeded.${o} Consider implementing exponential backoff for retries.`,retryable:!0}}if(e>=Fa.StatusCodes.INTERNAL_SERVER_ERROR&&e<600)return{suggestion:"Server error occurred. This is likely a temporary issue. Try again in a few moments.",retryable:!0};return{suggestion:void 0,retryable:!1}}class _s extends Gd{code="CONTRACT_ERROR";revertReason;transactionHash;contractAddress;constructor(e,t){let r=Jhe(t?.revertReason);super(e,{cause:t?.cause,suggestion:r,retryable:!1});this.revertReason=t?.revertReason,this.transactionHash=t?.transactionHash,this.contractAddress=t?.contractAddress}toJSON(){return{...super.toJSON(),revertReason:this.revertReason,transactionHash:this.transactionHash,contractAddress:this.contractAddress}}}function Jhe(e){if(!e)return"Smart contract execution failed. Check transaction parameters and try again.";let t=e.toLowerCase();if(t.includes("insufficient allowance"))return"Token allowance is insufficient. Call sdk.vault.approve() to increase the token allowance for the vault contract.";if(t.includes("insufficient balance"))return"Wallet balance is insufficient for this transaction. Ensure you have enough tokens and native currency for gas fees.";if(t.includes("nonce"))return"Transaction nonce error. This may be due to a pending transaction. Wait for pending transactions to complete or reset your account nonce.";if(t.includes("gas"))return"Transaction ran out of gas. Try increasing the gas limit for this transaction.";return}var Yhe={local:"http://localhost:8080",development:"https://develop.apimonaco.xyz",staging:"https://staging.apimonaco.xyz",mainnet:"https://api.monaco.xyz"},Qhe={local:"ws://localhost:8085/ws",development:"wss://ws-develop.apimonaco.xyz/ws",staging:"wss://ws-staging.apimonaco.xyz/ws",mainnet:"wss://ws.apimonaco.xyz/ws"};function j$(e){return Yhe[e]}function F$(e){return Qhe[e]}var u5=rn(Y_(),1);var Q_=256,X_;function ew(e=11){if(!X_||Q_+e>512){X_="",Q_=0;for(let t=0;t<256;t++)X_+=(256+Math.random()*256|0).toString(16).substring(1)}return X_.substring(Q_,Q_+++e)}function aq(e){let{batch:t,chain:r,ccipRead:o,dataSuffix:n,key:i="base",name:s="Base Client",type:a="base"}=e,c=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime==="number"?"pending":void 0),u=r?.blockTime??12000,d=Math.min(Math.max(Math.floor(u/2),500),4000),p=e.pollingInterval??d,m=e.cacheTime??p,h=e.account?Ft(e.account):void 0,{config:y,request:x,value:S}=e.transport({account:h,chain:r,pollingInterval:p}),v={...y,...S},E={account:h,batch:t,cacheTime:m,ccipRead:o,chain:r,dataSuffix:n,key:i,name:s,pollingInterval:p,request:x,transport:v,type:a,uid:ew(),...c?{experimental_blockTag:c}:{}};function w(_){return(T)=>{let P=T(_);for(let z in E)delete P[z];let O={..._,...P};return Object.assign(O,{extend:w(O)})}}return Object.assign(E,{extend:w(E)})}Pi();Os();ho();Pu();We();ot();Wa();function sp(e){if(!(e instanceof F))return!1;let t=e.walk((r)=>r instanceof ip);if(!(t instanceof ip))return!1;if(t.data?.errorName==="HttpError")return!0;if(t.data?.errorName==="ResolverError")return!0;if(t.data?.errorName==="ResolverNotContract")return!0;if(t.data?.errorName==="ResolverNotFound")return!0;if(t.data?.errorName==="ReverseAddressMismatch")return!0;if(t.data?.errorName==="UnsupportedResolverProfile")return!0;return!1}Rg();jr();We();Zo();function zw(e){if(e.length!==66)return null;if(e.indexOf("[")!==0)return null;if(e.indexOf("]")!==65)return null;let t=`0x${e.slice(1,65)}`;if(!sr(t))return null;return t}function Og(e){let t=new Uint8Array(32).fill(0);if(!e)return ht(t);let r=e.split(".");for(let o=r.length-1;o>=0;o-=1){let n=zw(r[o]),i=n?fo(n):zt(Vo(r[o]),"bytes");t=zt(Fr([t,i]),"bytes")}return ht(t)}jr();function PH(e){return`[${e.slice(2)}]`}jr();We();Zo();function kH(e){let t=new Uint8Array(32).fill(0);if(!e)return ht(t);return zw(e)||zt(Vo(e))}function ap(e){let t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);let r=new Uint8Array(Vo(t).byteLength+2),o=0,n=t.split(".");for(let i=0;i<n.length;i++){let s=Vo(n[i]);if(s.byteLength>255)s=Vo(PH(kH(n[i])));r[o]=s.length,r.set(s,o+1),o+=s.length+1}if(r.byteLength!==o+1)return r.slice(0,o+1);return r}function pe(e,t,r){let o=e[t.name];if(typeof o==="function")return o;let n=e[r];if(typeof n==="function")return n;return(i)=>t(e,i)}Os();ho();ir();ot();Wa();Ru();Cg();var Jge=3;function Yo(e,{abi:t,address:r,args:o,docsPath:n,functionName:i,sender:s}){let a=e instanceof zs?e:e instanceof F?e.walk((y)=>("data"in y))||e.walk():{},{code:c,data:u,details:d,message:p,shortMessage:m}=a,h=(()=>{if(e instanceof Ho)return new t2({functionName:i,cause:e});if([Jge,Ms.code].includes(c)&&(u||d||p||m)||c===yo.code&&d==="execution reverted"&&u)return new ip({abi:t,data:typeof u==="object"?u.data:u,functionName:i,message:a instanceof $u?d:m??p,cause:e});return e})();return new $g(h,{abi:t,args:o,contractAddress:r,docsPath:n,functionName:i,sender:s})}Uu();async function dr(e,t){let{abi:r,address:o,args:n,functionName:i,...s}=t,a=Kt({abi:r,args:n,functionName:i});try{let{data:c}=await pe(e,vo,"call")({...s,data:a,to:o});return Xr({abi:r,args:n,functionName:i,data:c||"0x"})}catch(c){throw Yo(c,{abi:r,address:o,args:n,docsPath:"/docs/contract/readContract",functionName:i})}}async function lG(e,t){let{blockNumber:r,blockTag:o,coinType:n,name:i,gatewayUrls:s,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return go({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some((m)=>i.endsWith(m)))return null;let p=(()=>{if(n!=null)return[Og(i),BigInt(n)];return[Og(i)]})();try{let m=Kt({abi:H$,functionName:"addr",args:p}),h={address:u,abi:rw,functionName:"resolveWithGateways",args:[Qr(ap(i)),m,s??[Ns]],blockNumber:r,blockTag:o},x=await pe(e,dr,"readContract")(h);if(x[0]==="0x")return null;let S=Xr({abi:H$,args:p,functionName:"addr",data:x[0]});if(S==="0x")return null;if(Go(S)==="0x00")return null;return S}catch(m){if(a)throw m;if(sp(m))return null;throw m}}ot();class $2 extends F{constructor({data:e}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(e)}`],name:"EnsAvatarInvalidMetadataError"})}}class Lu extends F{constructor({reason:e}){super(`ENS NFT avatar URI is invalid. ${e}`,{name:"EnsAvatarInvalidNftUriError"})}}class Vg extends F{constructor({uri:e}){super(`Unable to resolve ENS avatar URI "${e}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class R2 extends F{constructor({namespace:e}){super(`ENS NFT avatar namespace "${e}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}var yye=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,bye=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,xye=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,vye=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function _ye(e){try{let t=await fetch(e,{method:"HEAD"});if(t.status===200)return t.headers.get("content-type")?.startsWith("image/");return!1}catch(t){if(typeof t==="object"&&typeof t.response<"u")return!1;if(!Object.hasOwn(globalThis,"Image"))return!1;return new Promise((r)=>{let o=new Image;o.onload=()=>{r(!0)},o.onerror=()=>{r(!1)},o.src=e})}}function dG(e,t){if(!e)return t;if(e.endsWith("/"))return e.slice(0,-1);return e}function O2({uri:e,gatewayUrls:t}){let r=xye.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};let o=dG(t?.ipfs,"https://ipfs.io"),n=dG(t?.arweave,"https://arweave.net"),i=e.match(yye),{protocol:s,subpath:a,target:c,subtarget:u=""}=i?.groups||{},d=s==="ipns:/"||a==="ipns/",p=s==="ipfs:/"||a==="ipfs/"||bye.test(e);if(e.startsWith("http")&&!d&&!p){let h=e;if(t?.arweave)h=e.replace(/https:\/\/arweave.net/g,t?.arweave);return{uri:h,isOnChain:!1,isEncoded:!1}}if((d||p)&&c)return{uri:`${o}/${d?"ipns":"ipfs"}/${c}${u}`,isOnChain:!1,isEncoded:!1};if(s==="ar:/"&&c)return{uri:`${n}/${c}${u||""}`,isOnChain:!1,isEncoded:!1};let m=e.replace(vye,"");if(m.startsWith("<svg"))m=`data:image/svg+xml;base64,${btoa(m)}`;if(m.startsWith("data:")||m.startsWith("{"))return{uri:m,isOnChain:!0,isEncoded:!1};throw new Vg({uri:e})}function C2(e){if(typeof e!=="object"||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new $2({data:e});return e.image||e.image_url||e.image_data}async function pG({gatewayUrls:e,uri:t}){try{let r=await fetch(t).then((n)=>n.json());return await Ww({gatewayUrls:e,uri:C2(r)})}catch{throw new Vg({uri:t})}}async function Ww({gatewayUrls:e,uri:t}){let{uri:r,isOnChain:o}=O2({uri:t,gatewayUrls:e});if(o)return r;if(await _ye(r))return r;throw new Vg({uri:t})}function fG(e){let t=e;if(t.startsWith("did:nft:"))t=t.replace("did:nft:","").replace(/_/g,"/");let[r,o,n]=t.split("/"),[i,s]=r.split(":"),[a,c]=o.split(":");if(!i||i.toLowerCase()!=="eip155")throw new Lu({reason:"Only EIP-155 supported"});if(!s)throw new Lu({reason:"Chain ID not found"});if(!c)throw new Lu({reason:"Contract address not found"});if(!n)throw new Lu({reason:"Token ID not found"});if(!a)throw new Lu({reason:"ERC namespace not found"});return{chainID:Number.parseInt(s,10),namespace:a.toLowerCase(),contractAddress:c,tokenID:n}}async function mG(e,{nft:t}){if(t.namespace==="erc721")return dr(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return dr(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new R2({namespace:t.namespace})}async function hG(e,{gatewayUrls:t,record:r}){if(/eip155:/i.test(r))return wye(e,{gatewayUrls:t,record:r});return Ww({uri:r,gatewayUrls:t})}async function wye(e,{gatewayUrls:t,record:r}){let o=fG(r),n=await mG(e,{nft:o}),{uri:i,isOnChain:s,isEncoded:a}=O2({uri:n,gatewayUrls:t});if(s&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){let u=a?atob(i.replace("data:application/json;base64,","")):i,d=JSON.parse(u);return Ww({uri:C2(d),gatewayUrls:t})}let c=o.tokenID;if(o.namespace==="erc1155")c=c.replace("0x","").padStart(64,"0");return pG({gatewayUrls:t,uri:i.replace(/(?:0x)?{id}/,c)})}Pi();Os();ho();Pu();We();Rg();async function Kw(e,t){let{blockNumber:r,blockTag:o,key:n,name:i,gatewayUrls:s,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return go({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some((p)=>i.endsWith(p)))return null;try{let p={address:u,abi:rw,args:[Qr(ap(i)),Kt({abi:q$,functionName:"text",args:[Og(i),n]}),s??[Ns]],functionName:"resolveWithGateways",blockNumber:r,blockTag:o},h=await pe(e,dr,"readContract")(p);if(h[0]==="0x")return null;let y=Xr({abi:q$,functionName:"text",data:h[0]});return y===""?null:y}catch(p){if(a)throw p;if(sp(p))return null;throw p}}async function gG(e,{blockNumber:t,blockTag:r,assetGatewayUrls:o,name:n,gatewayUrls:i,strict:s,universalResolverAddress:a}){let c=await pe(e,Kw,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:n,universalResolverAddress:a,gatewayUrls:i,strict:s});if(!c)return null;try{return await hG(e,{record:c,gatewayUrls:o})}catch{return null}}Pi();Pu();Rg();async function yG(e,t){let{address:r,blockNumber:o,blockTag:n,coinType:i=60n,gatewayUrls:s,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return go({blockNumber:o,chain:c,contract:"ensUniversalResolver"})})();try{let d={address:u,abi:uq,args:[r,i,s??[Ns]],functionName:"reverseWithGateways",blockNumber:o,blockTag:n},p=pe(e,dr,"readContract"),[m]=await p(d);return m||null}catch(d){if(a)throw d;if(sp(d))return null;throw d}}Pu();We();async function bG(e,t){let{blockNumber:r,blockTag:o,name:n}=t,{chain:i}=e,s=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!i)throw Error("client chain not configured. universalResolverAddress is required.");return go({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),a=i?.ensTlds;if(a&&!a.some((u)=>n.endsWith(u)))throw Error(`${n} is not a valid ENS TLD (${a?.join(", ")}) for chain "${i.name}" (id: ${i.id}).`);let[c]=await pe(e,dr,"readContract")({address:s,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[Qr(ap(n))],blockNumber:r,blockTag:o});return c}Uu();We();T2();Np();Du();async function Jw(e,t){let{account:r=e.account,blockNumber:o,blockTag:n="latest",blobs:i,data:s,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:p,to:m,value:h,...y}=t,x=r?Ft(r):void 0;try{xo(t);let v=(typeof o==="bigint"?ye(o):void 0)||n,E=e.chain?.formatters?.transactionRequest?.format,_=(E||Ci)({...ec(y,{format:E}),account:x,blobs:i,data:s,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:p,to:m,value:h},"createAccessList"),T=await e.request({method:"eth_createAccessList",params:[_,v]});return{accessList:T.accessList,gasUsed:BigInt(T.gasUsed)}}catch(S){throw Hw(S,{...t,account:x,chain:e.chain})}}function tc(e,{method:t}){let r={};if(e.transport.type==="fallback")e.transport.onResponse?.(({method:o,response:n,status:i,transport:s})=>{if(i==="success"&&t===o)r[n]=s.request});return(o)=>r[o]||e.request}async function xG(e){let t=tc(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}ir();ot();class z2 extends F{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}jr();Zo();Ig();Ps();ws();Za();var vG="/docs/contract/encodeEventTopics";function zi(e){let{abi:t,eventName:r,args:o}=e,n=t[0];if(r){let c=Ln({abi:t,name:r});if(!c)throw new sw(r,{docsPath:vG});n=c}if(n.type!=="event")throw new sw(void 0,{docsPath:vG});let i=hr(n),s=Va(i),a=[];if(o&&"inputs"in n){let c=n.inputs?.filter((d)=>("indexed"in d)&&d.indexed),u=Array.isArray(o)?o:Object.values(o).length>0?c?.map((d)=>o[d.name])??[]:[];if(u.length>0)a=c?.map((d,p)=>{if(Array.isArray(u[p]))return u[p].map((m,h)=>_G({param:d,value:u[p][h]}));return typeof u[p]<"u"&&u[p]!==null?_G({param:d,value:u[p]}):null})??[]}return[s,...a]}function _G({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return zt(fo(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new z2(e.type);return yn([e],[t])}We();async function Yw(e,t){let{address:r,abi:o,args:n,eventName:i,fromBlock:s,strict:a,toBlock:c}=t,u=tc(e,{method:"eth_newFilter"}),d=i?zi({abi:o,args:n,eventName:i}):void 0,p=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof s==="bigint"?ye(s):s,toBlock:typeof c==="bigint"?ye(c):c,topics:d}]});return{abi:o,args:n,eventName:i,id:p,request:u(p),strict:Boolean(a),type:"event"}}We();async function Qw(e,{address:t,args:r,event:o,events:n,fromBlock:i,strict:s,toBlock:a}={}){let c=n??(o?[o]:void 0),u=tc(e,{method:"eth_newFilter"}),d=[];if(c){if(d=[c.flatMap((h)=>zi({abi:[h],eventName:h.name,args:r}))],o)d=d[0]}let p=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof i==="bigint"?ye(i):i,toBlock:typeof a==="bigint"?ye(a):a,...d.length?{topics:d}:{}}]});return{abi:c,args:r,eventName:o?o.name:void 0,fromBlock:i,id:p,request:u(p),strict:Boolean(s),toBlock:a,type:"event"}}async function Xw(e){let t=tc(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}ho();ot();Tu();Zo();function wG(e){let t=zt(`0x${e.substring(4)}`).substring(26);return Su(`0x${t}`)}po();gn();We();async function BG({hash:e,signature:t}){let r=sr(e)?e:Qr(e),{secp256k1:o}=await Promise.resolve().then(() => (oc(),Z2));return`0x${(()=>{if(typeof t==="object"&&"r"in t&&"s"in t){let{r:u,s:d,v:p,yParity:m}=t,h=Number(m??p),y=MG(h);return new o.Signature(Ur(u),Ur(d)).addRecoveryBit(y)}let s=sr(t)?t:Qr(t);if(at(s)!==65)throw Error("invalid signature length");let a=wr(`0x${s.slice(130)}`),c=MG(a);return o.Signature.fromCompact(s.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function MG(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw Error("Invalid yParityOrV value")}async function Yg({hash:e,signature:t}){return wG(await BG({hash:e,signature:t}))}jr();We();ot();mw();jr();We();function DG(e,t="hex"){let r=UG(e),o=Wd(new Uint8Array(r.length));if(r.encode(o),t==="hex")return ht(o.bytes);return o.bytes}function UG(e){if(Array.isArray(e))return Mye(e.map((t)=>UG(t)));return Bye(e)}function Mye(e){let t=e.reduce((n,i)=>n+i.length,0),r=LG(t);return{length:(()=>{if(t<=55)return 1+t;return 1+r+t})(),encode(n){if(t<=55)n.pushByte(192+t);else if(n.pushByte(247+r),r===1)n.pushUint8(t);else if(r===2)n.pushUint16(t);else if(r===3)n.pushUint24(t);else n.pushUint32(t);for(let{encode:i}of e)i(n)}}}function Bye(e){let t=typeof e==="string"?Lr(e):e,r=LG(t.length);return{length:(()=>{if(t.length===1&&t[0]<128)return 1;if(t.length<=55)return 1+t.length;return 1+r+t.length})(),encode(n){if(t.length===1&&t[0]<128)n.pushBytes(t);else if(t.length<=55)n.pushByte(128+t.length),n.pushBytes(t);else{if(n.pushByte(183+r),r===1)n.pushUint8(t.length);else if(r===2)n.pushUint16(t.length);else if(r===3)n.pushUint24(t.length);else n.pushUint32(t.length);n.pushBytes(t)}}}}function LG(e){if(e<256)return 1;if(e<65536)return 2;if(e<16777216)return 3;if(e<4294967296)return 4;throw new F("Length is too large.")}Zo();function jG(e){let{chainId:t,nonce:r,to:o}=e,n=e.contractAddress??e.address,i=zt(Wo(["0x05",DG([t?ye(t):"0x",n,r?ye(r):"0x"])]));if(o==="bytes")return Lr(i);return i}async function n1(e){let{authorization:t,signature:r}=e;return Yg({hash:jG(t),signature:r??t})}We();Cw();op();ot();Cs();class W2 extends F{constructor(e,{account:t,docsPath:r,chain:o,data:n,gas:i,gasPrice:s,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:u,to:d,value:p}){let m=ku({from:t?.address,to:d,value:typeof p<"u"&&`${np(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:n,gas:i,gasPrice:typeof s<"u"&&`${gr(s)} gwei`,maxFeePerGas:typeof a<"u"&&`${gr(a)} gwei`,maxPriorityFeePerGas:typeof c<"u"&&`${gr(c)} gwei`,nonce:u});super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",m].filter(Boolean),name:"EstimateGasExecutionError"});Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}Bu();Gg();function FG(e,{docsPath:t,...r}){let o=(()=>{let n=Xa(e,r);if(n instanceof Qo)return e;return n})();return new W2(o,{docsPath:t,...r})}Np();Zw();Du();op();ot();class Qg extends F{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class ju extends F{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class K2 extends F{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${gr(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}gn();ot();class Xg extends F{constructor({blockHash:e,blockNumber:t}){let r="Block";if(e)r=`Block at hash "${e}"`;if(t)r=`Block at number "${t}"`;super(`${r} could not be found.`,{name:"BlockNotFoundError"})}}We();gn();var J2={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Up(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?wr(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?wr(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?J2[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};if(e.authorizationList)r.authorizationList=Dye(e.authorizationList);if(r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v==="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}return})(),r.type==="legacy")delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity;if(r.type==="eip2930")delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas;if(r.type==="eip1559")delete r.maxFeePerBlobGas;return r}function Dye(e){return e.map((t)=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function o1(e,t){let r=(e.transactions??[]).map((o)=>{if(typeof o==="string")return o;return Up(o)});return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}async function Tr(e,{blockHash:t,blockNumber:r,blockTag:o=e.experimental_blockTag??"latest",includeTransactions:n}={}){let i=n??!1,s=r!==void 0?ye(r):void 0,a=null;if(t)a=await e.request({method:"eth_getBlockByHash",params:[t,i]},{dedupe:!0});else a=await e.request({method:"eth_getBlockByNumber",params:[s||o,i]},{dedupe:Boolean(s)});if(!a)throw new Xg({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||o1)(a,"getBlock")}async function Lp(e){let t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function qG(e,t){return Y2(e,t)}async function Y2(e,t){let{block:r,chain:o=e.chain,request:n}=t||{};try{let i=o?.fees?.maxPriorityFeePerGas??o?.fees?.defaultPriorityFee;if(typeof i==="function"){let a=r||await pe(e,Tr,"getBlock")({}),c=await i({block:a,client:e,request:n});if(c===null)throw Error();return c}if(typeof i<"u")return i;let s=await e.request({method:"eth_maxPriorityFeePerGas"});return Ur(s)}catch{let[i,s]=await Promise.all([r?Promise.resolve(r):pe(e,Tr,"getBlock")({}),pe(e,Lp,"getGasPrice")({})]);if(typeof i.baseFeePerGas!=="bigint")throw new ju;let a=s-i.baseFeePerGas;if(a<0n)return 0n;return a}}async function HG(e,t){return i1(e,t)}async function i1(e,t){let{block:r,chain:o=e.chain,request:n,type:i="eip1559"}=t||{},s=await(async()=>{if(typeof o?.fees?.baseFeeMultiplier==="function")return o.fees.baseFeeMultiplier({block:r,client:e,request:n});return o?.fees?.baseFeeMultiplier??1.2})();if(s<1)throw new Qg;let c=10**(s.toString().split(".")[1]?.length??0),u=(m)=>m*BigInt(Math.ceil(s*c))/BigInt(c),d=r?r:await pe(e,Tr,"getBlock")({});if(typeof o?.fees?.estimateFeesPerGas==="function"){let m=await o.fees.estimateFeesPerGas({block:r,client:e,multiply:u,request:n,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof d.baseFeePerGas!=="bigint")throw new ju;let m=typeof n?.maxPriorityFeePerGas==="bigint"?n.maxPriorityFeePerGas:await Y2(e,{block:d,chain:o,request:n}),h=u(d.baseFeePerGas);return{maxFeePerGas:n?.maxFeePerGas??h+m,maxPriorityFeePerGas:m}}return{gasPrice:n?.gasPrice??u(await pe(e,Lp,"getGasPrice")({}))}}gn();We();async function s1(e,{address:t,blockTag:r="latest",blockNumber:o}){let n=await e.request({method:"eth_getTransactionCount",params:[t,typeof o==="bigint"?ye(o):r]},{dedupe:Boolean(o)});return wr(n)}jr();We();function a1(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),o=typeof e.blobs[0]==="string"?e.blobs.map((i)=>Lr(i)):e.blobs,n=[];for(let i of o)n.push(Uint8Array.from(t.blobToKzgCommitment(i)));return r==="bytes"?n:n.map((i)=>ht(i))}jr();We();function c1(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),o=typeof e.blobs[0]==="string"?e.blobs.map((s)=>Lr(s)):e.blobs,n=typeof e.commitments[0]==="string"?e.commitments.map((s)=>Lr(s)):e.commitments,i=[];for(let s=0;s<o.length;s++){let a=o[s],c=n[s];i.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map((s)=>ht(s))}We();ig();var u1=gs;jr();We();function GG(e,t){let r=t||"hex",o=u1(sr(e,{strict:!1})?fo(e):e);if(r==="bytes")return o;return Qr(o)}function VG(e){let{commitment:t,version:r=1}=e,o=e.to??(typeof t==="string"?"hex":"bytes"),n=GG(t,"bytes");return n.set([r],0),o==="bytes"?n:ht(n)}function ZG(e){let{commitments:t,version:r}=e,o=e.to??(typeof t[0]==="string"?"hex":"bytes"),n=[];for(let i of t)n.push(VG({commitment:i,to:o,version:r}));return n}var WG=32,KG=4096,JG=131072,Q2=761855;ot();class X2 extends F{constructor({maxSize:e,size:t}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${t} bytes`],name:"BlobSizeTooLargeError"})}}class eO extends F{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}mw();po();jr();We();function YG(e){let t=e.to??(typeof e.data==="string"?"hex":"bytes"),r=typeof e.data==="string"?Lr(e.data):e.data,o=at(r);if(!o)throw new eO;if(o>Q2)throw new X2({maxSize:Q2,size:o});let n=[],i=!0,s=0;while(i){let a=Wd(new Uint8Array(JG)),c=0;while(c<KG){let u=r.slice(s,s+(WG-1));if(a.pushByte(0),a.pushBytes(u),u.length<31){a.pushByte(128),i=!1;break}c++,s+=31}n.push(a)}return t==="bytes"?n.map((a)=>a.bytes):n.map((a)=>ht(a.bytes))}function QG(e){let{data:t,kzg:r,to:o}=e,n=e.blobs??YG({data:t,to:o}),i=e.commitments??a1({blobs:n,kzg:r,to:o}),s=e.proofs??c1({blobs:n,commitments:i,kzg:r,to:o}),a=[];for(let c=0;c<n.length;c++)a.push({blob:n[c],commitment:i[c],proof:s[c]});return a}vg();Du();Cs();function XG(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u"){if(typeof e.accessList<"u")return"eip2930";return"legacy"}throw new YR({transaction:e})}Bu();Cs();Gg();function e7(e,{docsPath:t,...r}){let o=(()=>{let n=Xa(e,r);if(n instanceof Qo)return e;return n})();return new QR(o,{docsPath:t,...r})}Np();Du();gn();async function jp(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return wr(t)}async function l1(e,t){let{account:r=e.account,accessList:o,authorizationList:n,chain:i=e.chain,blobVersionedHashes:s,blobs:a,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:y,nonceManager:x,to:S,type:v,value:E,...w}=t,_=await(async()=>{if(!r)return y;if(!x)return y;if(typeof y<"u")return y;let z=Ft(r),B=i?i.id:await pe(e,jp,"getChainId")({});return await x.consume({address:z.address,chainId:B,client:e})})();xo(t);let T=i?.formatters?.transactionRequest?.format,O=(T||Ci)({...ec(w,{format:T}),account:r?Ft(r):void 0,accessList:o,authorizationList:n,blobs:a,blobVersionedHashes:s,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:_,to:S,type:v,value:E},"fillTransaction");try{let z=await e.request({method:"eth_fillTransaction",params:[O]}),k=(i?.formatters?.transaction?.format||Up)(z.tx);if(delete k.blockHash,delete k.blockNumber,delete k.r,delete k.s,delete k.transactionIndex,delete k.v,delete k.yParity,k.data=k.input,k.gas)k.gas=t.gas??k.gas;if(k.gasPrice)k.gasPrice=t.gasPrice??k.gasPrice;if(k.maxFeePerBlobGas)k.maxFeePerBlobGas=t.maxFeePerBlobGas??k.maxFeePerBlobGas;if(k.maxFeePerGas)k.maxFeePerGas=t.maxFeePerGas??k.maxFeePerGas;if(k.maxPriorityFeePerGas)k.maxPriorityFeePerGas=t.maxPriorityFeePerGas??k.maxPriorityFeePerGas;if(typeof k.nonce<"u")k.nonce=t.nonce??k.nonce;let G=await(async()=>{if(typeof i?.fees?.baseFeeMultiplier==="function"){let H=await pe(e,Tr,"getBlock")({});return i.fees.baseFeeMultiplier({block:H,client:e,request:t})}return i?.fees?.baseFeeMultiplier??1.2})();if(G<1)throw new Qg;let ue=10**(G.toString().split(".")[1]?.length??0),W=(H)=>H*BigInt(Math.ceil(G*ue))/BigInt(ue);if(!k.feePayerSignature){if(k.maxFeePerGas&&!t.maxFeePerGas)k.maxFeePerGas=W(k.maxFeePerGas);if(k.gasPrice&&!t.gasPrice)k.gasPrice=W(k.gasPrice)}return{raw:z.raw,transaction:{from:O.from,...k},...z.capabilities?{capabilities:z.capabilities}:{}}}catch(z){throw e7(z,{...t,chain:e.chain})}}var Uye=["blobVersionedHashes","chainId","fees","gas","nonce","type"],t7=new Map,tO=new Es(128);async function d1(e,t){let r=t;r.account??=e.account,r.parameters??=Uye;let{account:o,chain:n=e.chain,nonceManager:i,parameters:s}=r,a=(()=>{if(typeof n?.prepareTransactionRequest==="function")return{fn:n.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(n?.prepareTransactionRequest))return{fn:n.prepareTransactionRequest[0],runAt:n.prepareTransactionRequest[1].runAt};return})(),c;async function u(){if(c)return c;if(typeof r.chainId<"u")return r.chainId;if(n)return n.id;return c=await pe(e,jp,"getChainId")({}),c}let d=o?Ft(o):o,p=r.nonce;if(s.includes("nonce")&&typeof p>"u"&&d&&i){let _=await u();p=await i.consume({address:d.address,chainId:_,client:e})}if(a?.fn&&a.runAt?.includes("beforeFillTransaction"))r=await a.fn({...r,chain:n},{phase:"beforeFillTransaction"}),p??=r.nonce;let h=(()=>{if((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&r.kzg&&r.blobs)return!1;if(tO.get(e.uid)===!1)return!1;if(!["fees","gas"].some((T)=>s.includes(T)))return!1;if(s.includes("chainId")&&typeof r.chainId!=="number")return!0;if(s.includes("nonce")&&typeof p!=="number")return!0;if(s.includes("fees")&&typeof r.gasPrice!=="bigint"&&(typeof r.maxFeePerGas!=="bigint"||typeof r.maxPriorityFeePerGas!=="bigint"))return!0;if(s.includes("gas")&&typeof r.gas!=="bigint")return!0;return!1})()?await pe(e,l1,"fillTransaction")({...r,nonce:p}).then((_)=>{let{chainId:T,from:P,gas:O,gasPrice:z,nonce:B,maxFeePerBlobGas:k,maxFeePerGas:G,maxPriorityFeePerGas:V,type:ue,...W}=_.transaction;return tO.set(e.uid,!0),{...r,...P?{from:P}:{},...ue&&!r.type?{type:ue}:{},...typeof T<"u"?{chainId:T}:{},...typeof O<"u"?{gas:O}:{},...typeof z<"u"?{gasPrice:z}:{},...typeof B<"u"?{nonce:B}:{},...typeof k<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerBlobGas:k}:{},...typeof G<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerGas:G}:{},...typeof V<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxPriorityFeePerGas:V}:{},..."nonceKey"in W&&typeof W.nonceKey<"u"?{nonceKey:W.nonceKey}:{},..."keyAuthorization"in W&&typeof W.keyAuthorization<"u"&&W.keyAuthorization!==null&&!("keyAuthorization"in r)?{keyAuthorization:W.keyAuthorization}:{},..."feePayerSignature"in W&&typeof W.feePayerSignature<"u"&&W.feePayerSignature!==null?{feePayerSignature:W.feePayerSignature}:{},..."feeToken"in W&&typeof W.feeToken<"u"&&W.feeToken!==null&&!("feeToken"in r)?{feeToken:W.feeToken}:{},..._.capabilities?{_capabilities:_.capabilities}:{}}}).catch((_)=>{let T=_;if(T.name!=="TransactionExecutionError")return r;if(T.walk?.((z)=>z.name==="ExecutionRevertedError"))throw _;if(T.walk?.((z)=>{let B=z;return B.name==="MethodNotFoundRpcError"||B.name==="MethodNotSupportedRpcError"||B.message?.includes("eth_fillTransaction is not available")}))tO.set(e.uid,!1);return r}):r;p??=h.nonce,r={...h,...d?{from:d?.address}:{},...typeof p<"u"?{nonce:p}:{}};let{blobs:y,gas:x,kzg:S,type:v}=r;if(a?.fn&&a.runAt?.includes("beforeFillParameters"))r=await a.fn({...r,chain:n},{phase:"beforeFillParameters"});let E;async function w(){if(E)return E;return E=await pe(e,Tr,"getBlock")({blockTag:"latest"}),E}if(s.includes("nonce")&&typeof p>"u"&&d&&!i)r.nonce=await pe(e,s1,"getTransactionCount")({address:d.address,blockTag:"pending"});if((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&y&&S){let _=a1({blobs:y,kzg:S});if(s.includes("blobVersionedHashes")){let T=ZG({commitments:_,to:"hex"});r.blobVersionedHashes=T}if(s.includes("sidecars")){let T=c1({blobs:y,commitments:_,kzg:S}),P=QG({blobs:y,commitments:_,proofs:T,to:"hex"});r.sidecars=P}}if(s.includes("chainId"))r.chainId=await u();if((s.includes("fees")||s.includes("type"))&&typeof v>"u")try{r.type=XG(r)}catch{let _=t7.get(e.uid);if(typeof _>"u")_=typeof(await w())?.baseFeePerGas==="bigint",t7.set(e.uid,_);r.type=_?"eip1559":"legacy"}if(s.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){let _=await w(),{maxFeePerGas:T,maxPriorityFeePerGas:P}=await i1(e,{block:_,chain:n,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<P)throw new K2({maxPriorityFeePerGas:P});r.maxPriorityFeePerGas=P,r.maxFeePerGas=T}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new ju;if(typeof r.gasPrice>"u"){let _=await w(),{gasPrice:T}=await i1(e,{block:_,chain:n,request:r,type:"legacy"});r.gasPrice=T}}if(s.includes("gas")&&typeof x>"u")r.gas=await pe(e,Fp,"estimateGas")({...r,account:d,prepare:d?.type==="local"?[]:["blobVersionedHashes"]});if(a?.fn&&a.runAt?.includes("afterFillParameters"))r=await a.fn({...r,chain:n},{phase:"afterFillParameters"});return xo(r),delete r.parameters,r}async function Fp(e,t){let{account:r=e.account,prepare:o=!0}=t,n=r?Ft(r):void 0,i=(()=>{if(Array.isArray(o))return o;if(n?.type!=="local")return["blobVersionedHashes"];return})();try{let s=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await n1({authorization:t.authorizationList[0]}).catch(()=>{throw new F("`to` is required. Could not infer from `authorizationList`")});return})(),{accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:d,blockNumber:p,blockTag:m,data:h,gas:y,gasPrice:x,maxFeePerBlobGas:S,maxFeePerGas:v,maxPriorityFeePerGas:E,nonce:w,value:_,stateOverride:T,...P}=o?await d1(e,{...t,parameters:i,to:s}):t;if(y&&t.gas!==y)return y;let z=(typeof p==="bigint"?ye(p):void 0)||m,B=Mp(T);xo(t);let k=e.chain?.formatters?.transactionRequest?.format,V=(k||Ci)({...ec(P,{format:k}),account:n,accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:d,data:h,gasPrice:x,maxFeePerBlobGas:S,maxFeePerGas:v,maxPriorityFeePerGas:E,nonce:w,to:s,value:_},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:B?[V,z??e.experimental_blockTag??"latest",B]:z?[V,z]:[V]}))}catch(s){throw FG(s,{...t,account:n,chain:e.chain})}}async function r7(e,t){let{abi:r,address:o,args:n,functionName:i,dataSuffix:s=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=Kt({abi:r,args:n,functionName:i});try{return await pe(e,Fp,"estimateGas")({data:`${c}${s?s.replace("0x",""):""}`,to:o,...a})}catch(u){let d=a.account?Ft(a.account):void 0;throw Yo(u,{abi:r,address:o,args:n,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:d?.address})}}Pi();Os();ho();We();Uu();async function n7(e,{address:t,blockNumber:r,blockTag:o=e.experimental_blockTag??"latest"}){if(e.batch?.multicall&&e.chain?.contracts?.multicall3){let s=e.chain.contracts.multicall3.address,a=Kt({abi:qo,functionName:"getEthBalance",args:[t]}),{data:c}=await pe(e,vo,"call")({to:s,data:a,blockNumber:r,blockTag:o});return Xr({abi:qo,functionName:"getEthBalance",args:[t],data:c||"0x"})}let n=typeof r==="bigint"?ye(r):void 0,i=await e.request({method:"eth_getBalance",params:[t,n||o]});return BigInt(i)}async function o7(e){let t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}var Lye=new Map,jye=new Map;function i7(e){let t=(n,i)=>({clear:()=>i.delete(n),get:()=>i.get(n),set:(s)=>i.set(n,s)}),r=t(e,Lye),o=t(e,jye);return{clear:()=>{r.clear(),o.clear()},promise:r,response:o}}async function s7(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){let o=i7(t),n=o.response.get();if(n&&r>0){if(Date.now()-n.created.getTime()<r)return n.data}let i=o.promise.get();if(!i)i=e(),o.promise.set(i);try{let s=await i;return o.response.set({created:new Date,data:s}),s}finally{o.promise.clear()}}var Fye=(e)=>`blockNumber.${e}`;async function Ni(e,{cacheTime:t=e.cacheTime}={}){let r=await s7(()=>e.request({method:"eth_blockNumber"}),{cacheKey:Fye(e.uid),cacheTime:t});return BigInt(r)}gn();We();async function a7(e,{blockHash:t,blockNumber:r,blockTag:o="latest"}={}){let n=r!==void 0?ye(r):void 0,i;if(t)i=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0});else i=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[n||o]},{dedupe:Boolean(n)});return wr(i)}We();async function Fu(e,{address:t,blockNumber:r,blockTag:o="latest"}){let n=r!==void 0?ye(r):void 0,i=await e.request({method:"eth_getCode",params:[t,n||o]},{dedupe:Boolean(n)});if(i==="0x")return;return i}Za();Bp();jr();function Er(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}Zo();Ig();ir();gR();po();Ig();Sg();ws();var c7="/docs/contract/decodeEventLog";function qu(e){let{abi:t,data:r,strict:o,topics:n}=e,i=o??!0,[s,...a]=n;if(!s)throw new eR({docsPath:c7});let c=t.find((v)=>v.type==="event"&&s===Va(hr(v)));if(!(c&&("name"in c))||c.type!=="event")throw new tR(s,{docsPath:c7});let{name:u,inputs:d}=c,p=d?.some((v)=>!(("name"in v)&&v.name)),m=p?[]:{},h=d.map((v,E)=>[v,E]).filter(([v])=>("indexed"in v)&&v.indexed),y=[];for(let v=0;v<h.length;v++){let[E,w]=h[v],_=a[v];if(!_){if(i)throw new vu({abiItem:c,param:E});y.push([E,w]);continue}m[p?w:E.name||w]=qye({param:E,value:_})}let x=d.filter((v)=>!(("indexed"in v)&&v.indexed)),S=i?x:[...y.map(([v])=>v),...x];if(S.length>0){if(r&&r!=="0x")try{let v=ks(S,r);if(v){let E=0;if(!i)for(let[w,_]of y)m[p?_:w.name||_]=v[E++];if(p){for(let w=0;w<d.length;w++)if(m[w]===void 0&&E<v.length)m[w]=v[E++]}else for(let w=0;w<x.length;w++)m[x[w].name]=v[E++]}}catch(v){if(i){if(v instanceof mg||v instanceof _g)throw new qa({abiItem:c,data:r,params:S,size:at(r)});throw v}}else if(i)throw new qa({abiItem:c,data:"0x",params:S,size:0})}return{eventName:u,args:Object.values(m).length>0?m:void 0}}function qye({param:e,value:t}){if(e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))return t;return(ks([e],t)||[])[0]}function qp(e){let{abi:t,args:r,logs:o,strict:n=!0}=e,i=(()=>{if(!e.eventName)return;if(Array.isArray(e.eventName))return e.eventName;return[e.eventName]})(),s=t.filter((a)=>a.type==="event").map((a)=>({abi:a,selector:Va(a)}));return o.map((a)=>{let c=typeof a.blockNumber==="string"?Er(a):a,u=s.filter((m)=>c.topics[0]===m.selector);if(u.length===0)return null;let d,p;for(let m of u)try{d=qu({...c,abi:[m.abi],strict:!0}),p=m;break}catch{}if(!d&&!n){p=u[0];try{d=qu({data:c.data,topics:c.topics,abi:[p.abi],strict:!1})}catch{let m=p.abi.inputs?.some((h)=>!(("name"in h)&&h.name));return{...c,args:m?[]:{},eventName:p.abi.name}}}if(!d||!p)return null;if(i&&!i.includes(d.eventName))return null;if(!Hye({args:d.args,inputs:p.abi.inputs,matchArgs:r}))return null;return{...d,...c}}).filter(Boolean)}function Hye(e){let{args:t,inputs:r,matchArgs:o}=e;if(!o)return!0;if(!t)return!1;function n(i,s,a){try{if(i.type==="address")return Xo(s,a);if(i.type==="string"||i.type==="bytes")return zt(fo(s))===a;return s===a}catch{return!1}}if(Array.isArray(t)&&Array.isArray(o))return o.every((i,s)=>{if(i===null||i===void 0)return!0;let a=r[s];if(!a)return!1;return(Array.isArray(i)?i:[i]).some((u)=>n(a,u,t[s]))});if(typeof t==="object"&&!Array.isArray(t)&&typeof o==="object"&&!Array.isArray(o))return Object.entries(o).every(([i,s])=>{if(s===null||s===void 0)return!0;let a=r.find((u)=>u.name===i);if(!a)return!1;return(Array.isArray(s)?s:[s]).some((u)=>n(a,u,t[i]))});return!1}We();async function Hp(e,{address:t,blockHash:r,fromBlock:o,toBlock:n,event:i,events:s,args:a,strict:c}={}){let u=c??!1,d=s??(i?[i]:void 0),p=[];if(d){if(p=[d.flatMap((x)=>zi({abi:[x],eventName:x.name,args:s?void 0:a}))],i)p=p[0]}let m;if(r)m=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,blockHash:r}]});else m=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,fromBlock:typeof o==="bigint"?ye(o):o,toBlock:typeof n==="bigint"?ye(n):n}]});let h=m.map((y)=>Er(y));if(!d)return h;return qp({abi:d,args:a,logs:h,strict:u})}async function p1(e,t){let{abi:r,address:o,args:n,blockHash:i,eventName:s,fromBlock:a,toBlock:c,strict:u}=t,d=s?Ln({abi:r,name:s}):void 0,p=!d?r.filter((m)=>m.type==="event"):void 0;return pe(e,Hp,"getLogs")({address:o,args:n,blockHash:i,event:d,events:p,fromBlock:a,toBlock:c,strict:u})}Tu();po();Iu();async function u7(e,{address:t,blockNumber:r,blockTag:o="latest"}){let n=await Fu(e,{address:t,...r!==void 0?{blockNumber:r}:{blockTag:o}});if(!n)return;if(at(n)!==23)return;if(!n.startsWith("0xef0100"))return;return Eu(mo(n,3,23))}ot();class rO extends F{constructor({address:e}){super(`No EIP-712 domain found on contract "${e}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${e}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function l7(e,t){let{address:r,factory:o,factoryData:n}=t;try{let[i,s,a,c,u,d,p]=await pe(e,dr,"readContract")({abi:Gye,address:r,functionName:"eip712Domain",factory:o,factoryData:n});return{domain:{name:s,version:a,chainId:Number(c),verifyingContract:u,salt:d},extensions:p,fields:i}}catch(i){let s=i;if(s.name==="ContractFunctionExecutionError"&&s.cause.name==="ContractFunctionZeroDataError")throw new rO({address:r});throw s}}var Gye=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];We();function d7(e){return{baseFeePerGas:e.baseFeePerGas.map((t)=>BigInt(t)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:e.reward?.map((t)=>t.map((r)=>BigInt(r)))}}async function p7(e,{blockCount:t,blockNumber:r,blockTag:o="latest",rewardPercentiles:n}){let i=typeof r==="bigint"?ye(r):void 0,s=await e.request({method:"eth_feeHistory",params:[ye(t),i||o,n]},{dedupe:Boolean(i)});return d7(s)}async function ic(e,{filter:t}){let r="strict"in t&&t.strict,o=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof o[0]==="string")return o;let n=o.map((i)=>Er(i));if(!("abi"in t)||!t.abi)return n;return qp({abi:t.abi,logs:n,strict:r})}async function f7(e,{filter:t}){let r=t.strict??!1,n=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map((i)=>Er(i));if(!t.abi)return n;return qp({abi:t.abi,logs:n,strict:r})}We();gn();function Vye(e){return e.map((t)=>({...t,value:BigInt(t.value)}))}function m7(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?wr(e.nonce):void 0,storageProof:e.storageProof?Vye(e.storageProof):void 0}}async function h7(e,{address:t,blockNumber:r,blockTag:o,storageKeys:n}){let i=o??"latest",s=r!==void 0?ye(r):void 0,a=await e.request({method:"eth_getProof",params:[t,n,s||i]});return m7(a)}We();async function g7(e,{address:t,blockNumber:r,blockTag:o="latest",slot:n}){let i=r!==void 0?ye(r):void 0;return await e.request({method:"eth_getStorageAt",params:[t,n,i||o]})}Cs();We();async function Gp(e,{blockHash:t,blockNumber:r,blockTag:o,hash:n,index:i,sender:s,nonce:a}){let c=o||"latest",u=r!==void 0?ye(r):void 0,d=null;if(n)d=await e.request({method:"eth_getTransactionByHash",params:[n]},{dedupe:!0});else if(t)d=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,ye(i)]},{dedupe:!0});else if((u||c)&&typeof i==="number")d=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[u||c,ye(i)]},{dedupe:Boolean(u)});else if(s&&typeof a==="number")d=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[s,ye(a)]},{dedupe:!0});if(!d)throw new Pg({blockHash:t,blockNumber:r,blockTag:c,hash:n,index:i});return(e.chain?.formatters?.transaction?.format||Up)(d,"getTransaction")}async function y7(e,{hash:t,transactionReceipt:r}){let[o,n]=await Promise.all([pe(e,Ni,"getBlockNumber")({}),t?pe(e,Gp,"getTransaction")({hash:t}):void 0]),i=r?.blockNumber||n?.blockNumber;if(!i)return 0n;return o-i+1n}Cs();gn();var Zye={"0x0":"reverted","0x1":"success"};function f1(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map((o)=>Er(o)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?wr(e.transactionIndex):null,status:e.status?Zye[e.status]:null,type:e.type?J2[e.type]||e.type:null};if(e.blobGasPrice)r.blobGasPrice=BigInt(e.blobGasPrice);if(e.blobGasUsed)r.blobGasUsed=BigInt(e.blobGasUsed);return r}async function Vp(e,{hash:t}){let r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new kg({hash:t});return(e.chain?.formatters?.transactionReceipt?.format||f1)(r,"getTransactionReceipt")}Pi();ir();ot();Wa();Os();ho();Pu();async function b7(e,t){let{account:r,authorizationList:o,allowFailure:n=!0,blockNumber:i,blockOverrides:s,blockTag:a,stateOverride:c}=t,u=t.contracts,{batchSize:d=t.batchSize??1024,deployless:p=t.deployless??!1}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},m=(()=>{if(t.multicallAddress)return t.multicallAddress;if(p)return null;if(e.chain)return go({blockNumber:i,chain:e.chain,contract:"multicall3"});throw Error("client chain not configured. multicallAddress is required.")})(),h=[[]],y=0,x=0;for(let E=0;E<u.length;E++){let{abi:w,address:_,args:T,functionName:P}=u[E];try{let O=Kt({abi:w,args:T,functionName:P});if(x+=(O.length-2)/2,d>0&&x>d&&h[y].length>0)y++,x=(O.length-2)/2,h[y]=[];h[y]=[...h[y],{allowFailure:!0,callData:O,target:_}]}catch(O){let z=Yo(O,{abi:w,address:_,args:T,docsPath:"/docs/contract/multicall",functionName:P,sender:r});if(!n)throw z;h[y]=[...h[y],{allowFailure:!0,callData:"0x",target:_}]}}let S=await Promise.allSettled(h.map((E)=>pe(e,dr,"readContract")({...m===null?{code:zp}:{address:m},abi:qo,account:r,args:[E],authorizationList:o,blockNumber:i,blockOverrides:s,blockTag:a,functionName:"aggregate3",stateOverride:c}))),v=[];for(let E=0;E<S.length;E++){let w=S[E];if(w.status==="rejected"){if(!n)throw w.reason;for(let T=0;T<h[E].length;T++)v.push({status:"failure",error:w.reason,result:void 0});continue}let _=w.value;for(let T=0;T<_.length;T++){let{returnData:P,success:O}=_[T],{callData:z}=h[E][T],{abi:B,address:k,functionName:G,args:V}=u[v.length];try{if(z==="0x")throw new Ho;if(!O)throw new zs({data:P});let ue=Xr({abi:B,args:V,data:P,functionName:G});v.push(n?{result:ue,status:"success"}:ue)}catch(ue){let W=Yo(ue,{abi:B,address:k,args:V,docsPath:"/docs/contract/multicall",functionName:G});if(!n)throw W;v.push({error:W,result:void 0,status:"failure"})}}}if(v.length!==u.length)throw new F("multicall results mismatch");return v}_2();ir();Wa();Bu();Os();ho();We();Gg();Np();Zw();Du();async function ey(e,t){let{blockNumber:r,blockTag:o=e.experimental_blockTag??"latest",blocks:n,returnFullTransactions:i,traceTransfers:s,validation:a}=t;try{let c=[];for(let m of n){let h=m.blockOverrides?Fw(m.blockOverrides):void 0,y=m.calls.map((S)=>{let v=S,E=v.account?Ft(v.account):void 0,w=v.abi?Kt(v):v.data,_={...v,account:E,data:v.dataSuffix?Fr([w||"0x",v.dataSuffix]):w,from:v.from??E?.address};return xo(_),Ci(_)}),x=m.stateOverrides?Mp(m.stateOverrides):void 0;c.push({blockOverrides:h,calls:y,stateOverrides:x})}let d=(typeof r==="bigint"?ye(r):void 0)||o;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:s,validation:a},d]})).map((m,h)=>({...o1(m),calls:m.calls.map((y,x)=>{let{abi:S,args:v,functionName:E,to:w}=n[h].calls[x],_=y.error?.data??y.returnData,T=BigInt(y.gasUsed),P=y.logs?.map((k)=>Er(k)),O=y.status==="0x1"?"success":"failure",z=S&&O==="success"&&_!=="0x"?Xr({abi:S,data:_,functionName:E}):null,B=(()=>{if(O==="success")return;let k;if(_==="0x")k=new Ho;else if(_)k=new zs({data:_});if(!k)return;return Yo(k,{abi:S??[],address:w??"0x",args:v,functionName:E??"<unknown>"})})();return{data:_,gasUsed:T,logs:P,status:O,...O==="success"?{result:z}:{error:B}}})}))}catch(c){let u=c,d=Xa(u,{});if(d instanceof Qo)throw u;throw d}}ep();jn();pw();Ja();Sr();function Hu(e,t={}){let{as:r=typeof e==="string"?"Hex":"Bytes"}=t,o=Zd(jH(e));if(r==="Bytes")return o;return ar(o)}Sr();Ja();class oO extends Map{constructor(e){super();Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);if(super.has(e)&&t!==void 0)this.delete(e),super.set(e,t);return t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let r=this.keys().next().value;if(r)this.delete(r)}return this}}var Wye={checksum:new oO(8192)},m1=Wye.checksum;jn();Ja();jn();Sr();function x7(e,t={}){let{compressed:r}=t,{prefix:o,x:n,y:i}=e;if(r===!1||typeof n==="bigint"&&typeof i==="bigint"){if(o!==4)throw new iO({prefix:o,cause:new T7});return}if(r===!0||typeof n==="bigint"&&typeof i>"u"){if(o!==3&&o!==2)throw new iO({prefix:o,cause:new S7});return}throw new w7({publicKey:e})}function v7(e){let t=(()=>{if(Ng(e))return _7(e);if(ZH(e))return Jye(e);let{prefix:r,x:o,y:n}=e;if(typeof o==="bigint"&&typeof n==="bigint")return{prefix:r??4,x:o,y:n};return{prefix:r,x:o}})();return x7(t),t}function Jye(e){return _7(ar(e))}function _7(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new E7({publicKey:e});if(e.length===130){let o=BigInt(Wt(e,0,32)),n=BigInt(Wt(e,32,64));return{prefix:4,x:o,y:n}}if(e.length===132){let o=Number(Wt(e,0,1)),n=BigInt(Wt(e,1,33)),i=BigInt(Wt(e,33,65));return{prefix:o,x:n,y:i}}let t=Number(Wt(e,0,1)),r=BigInt(Wt(e,1,33));return{prefix:t,x:r}}function sO(e,t={}){x7(e);let{prefix:r,x:o,y:n}=e,{includePrefix:i=!0}=t;return Jt(i?pt(r,{size:1}):"0x",pt(o,{size:32}),typeof n==="bigint"?pt(n,{size:32}):"0x")}class w7 extends xe{constructor({publicKey:e}){super(`Value \`${Ya(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class iO extends xe{constructor({prefix:e,cause:t}){super(`Prefix "${e}" is invalid.`,{cause:t});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class S7 extends xe{constructor(){super("Prefix must be 2 or 3 for compressed public keys.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class T7 extends xe{constructor(){super("Prefix must be 4 for uncompressed public keys.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}class E7 extends xe{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Zt(Op(e))} bytes.`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}var Yye=/^0x[a-fA-F0-9]{40}$/;function Gu(e,t={}){let{strict:r=!0}=t;if(!Yye.test(e))throw new aO({address:e,cause:new k7});if(r){if(e.toLowerCase()===e)return;if(h1(e)!==e)throw new aO({address:e,cause:new A7})}}function h1(e){if(m1.has(e))return m1.get(e);Gu(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=Hu(FH(t),{as:"Bytes"}),o=t.split("");for(let i=0;i<40;i+=2){if(r[i>>1]>>4>=8&&o[i])o[i]=o[i].toUpperCase();if((r[i>>1]&15)>=8&&o[i+1])o[i+1]=o[i+1].toUpperCase()}let n=`0x${o.join("")}`;return m1.set(e,n),n}function Qye(e,t={}){let{checksum:r=!1}=t;if(Gu(e),r)return h1(e);return e}function P7(e,t={}){let r=Hu(`0x${sO(e).slice(4)}`).substring(26);return Qye(`0x${r}`,t)}function g1(e,t={}){let{strict:r=!0}=t??{};try{return Gu(e,{strict:r}),!0}catch{return!1}}class aO extends xe{constructor({address:e,cause:t}){super(`Address "${e}" is invalid.`,{cause:t});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class k7 extends xe{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class A7 extends xe{constructor(){super("Address does not match its checksum counterpart.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}jn();function x1(e){let t=!0,r="",o=0,n="",i=!1;for(let s=0;s<e.length;s++){let a=e[s];if(["(",")",","].includes(a))t=!0;if(a==="(")o++;if(a===")")o--;if(!t)continue;if(o===0){if(a===" "&&["event","function","error",""].includes(n))n="";else if(n+=a,a===")"){i=!0;break}continue}if(a===" "){if(e[s-1]!==","&&r!==","&&r!==",(")r="",t=!1;continue}n+=a,r+=a}if(!i)throw new xe("Unable to normalize signature.");return n}function b1(e,t){let r=typeof e,o=t.type;switch(o){case"address":return g1(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:{if(o==="tuple"&&"components"in t)return Object.values(t.components).every((n,i)=>b1(Object.values(e)[i],n));if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(o))return r==="number"||r==="bigint";if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(o))return r==="string"||e instanceof Uint8Array;if(/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(o))return Array.isArray(e)&&e.every((n)=>b1(n,{...t,type:o.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}}function cO(e,t,r){for(let o in e){let n=e[o],i=t[o];if(n.type==="tuple"&&i.type==="tuple"&&"components"in n&&"components"in i)return cO(n.components,i.components,r[o]);let s=[n.type,i.type];if((()=>{if(s.includes("address")&&s.includes("bytes20"))return!0;if(s.includes("address")&&s.includes("string"))return g1(r[o],{strict:!1});if(s.includes("address")&&s.includes("bytes"))return g1(r[o],{strict:!1});return!1})())return s}return}function v1(e,t={}){let{prepare:r=!0}=t,o=(()=>{if(Array.isArray(e))return Ew(e);if(typeof e==="string")return Ew(e);return e})();return{...o,...r?{hash:Zp(o)}:{}}}function ty(e,t,r){let{args:o=[],prepare:n=!0}=r??{},i=Ng(t,{strict:!1}),s=e.filter((u)=>{if(i){if(u.type==="function"||u.type==="error")return uO(u)===Wt(t,0,4);if(u.type==="event")return Zp(u)===t;return!1}return"name"in u&&u.name===t});if(s.length===0)throw new Vu({name:t});if(s.length===1)return{...s[0],...n?{hash:Zp(s[0])}:{}};let a;for(let u of s){if(!("inputs"in u))continue;if(!o||o.length===0){if(!u.inputs||u.inputs.length===0)return{...u,...n?{hash:Zp(u)}:{}};continue}if(!u.inputs)continue;if(u.inputs.length===0)continue;if(u.inputs.length!==o.length)continue;if(o.every((p,m)=>{let h="inputs"in u&&u.inputs[m];if(!h)return!1;return b1(p,h)})){if(a&&"inputs"in a&&a.inputs){let p=cO(u.inputs,a.inputs,o);if(p)throw new $7({abiItem:u,type:p[0]},{abiItem:a,type:p[1]})}a=u}}let c=(()=>{if(a)return a;let[u,...d]=s;return{...u,overloads:d}})();if(!c)throw new Vu({name:t});return{...c,...n?{hash:Zp(c)}:{}}}function uO(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,o]=e;return ty(r,o)}return e[0]})();return Wt(Zp(t),0,4)}function ebe(...e){let t=(()=>{if(Array.isArray(e[0])){let[o,n]=e;return ty(o,n)}return e[0]})(),r=(()=>{if(typeof t==="string")return t;return $s(t)})();return x1(r)}function Zp(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,o]=e;return ty(r,o)}return e[0]})();if(typeof t!=="string"&&"hash"in t&&t.hash)return t.hash;return Hu(Cp(ebe(t)))}class $7 extends xe{constructor(e,t){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${x1($s(e.abiItem))}\`, and`,`\`${t.type}\` in \`${x1($s(t.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class Vu extends xe{constructor({name:e,data:t,type:r="item"}){let o=(()=>{if(e)return` with name "${e}"`;if(t)return` with data "${t}"`;return""})();super(`ABI ${r}${o} not found.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}ep();Ja();jn();Sr();Ja();jn();Sr();var O7=/^(.*)\[([0-9]*)\]$/,C7=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,_1=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,kGe=2n**(8n-1n)-1n,AGe=2n**(16n-1n)-1n,$Ge=2n**(24n-1n)-1n,RGe=2n**(32n-1n)-1n,OGe=2n**(40n-1n)-1n,CGe=2n**(48n-1n)-1n,zGe=2n**(56n-1n)-1n,NGe=2n**(64n-1n)-1n,MGe=2n**(72n-1n)-1n,BGe=2n**(80n-1n)-1n,DGe=2n**(88n-1n)-1n,UGe=2n**(96n-1n)-1n,LGe=2n**(104n-1n)-1n,jGe=2n**(112n-1n)-1n,FGe=2n**(120n-1n)-1n,qGe=2n**(128n-1n)-1n,HGe=2n**(136n-1n)-1n,GGe=2n**(144n-1n)-1n,VGe=2n**(152n-1n)-1n,ZGe=2n**(160n-1n)-1n,WGe=2n**(168n-1n)-1n,KGe=2n**(176n-1n)-1n,JGe=2n**(184n-1n)-1n,YGe=2n**(192n-1n)-1n,QGe=2n**(200n-1n)-1n,XGe=2n**(208n-1n)-1n,e7e=2n**(216n-1n)-1n,t7e=2n**(224n-1n)-1n,r7e=2n**(232n-1n)-1n,n7e=2n**(240n-1n)-1n,o7e=2n**(248n-1n)-1n,i7e=2n**(256n-1n)-1n,s7e=-(2n**(8n-1n)),a7e=-(2n**(16n-1n)),c7e=-(2n**(24n-1n)),u7e=-(2n**(32n-1n)),l7e=-(2n**(40n-1n)),d7e=-(2n**(48n-1n)),p7e=-(2n**(56n-1n)),f7e=-(2n**(64n-1n)),m7e=-(2n**(72n-1n)),h7e=-(2n**(80n-1n)),g7e=-(2n**(88n-1n)),y7e=-(2n**(96n-1n)),b7e=-(2n**(104n-1n)),x7e=-(2n**(112n-1n)),v7e=-(2n**(120n-1n)),_7e=-(2n**(128n-1n)),w7e=-(2n**(136n-1n)),S7e=-(2n**(144n-1n)),T7e=-(2n**(152n-1n)),E7e=-(2n**(160n-1n)),I7e=-(2n**(168n-1n)),P7e=-(2n**(176n-1n)),k7e=-(2n**(184n-1n)),A7e=-(2n**(192n-1n)),$7e=-(2n**(200n-1n)),R7e=-(2n**(208n-1n)),O7e=-(2n**(216n-1n)),C7e=-(2n**(224n-1n)),z7e=-(2n**(232n-1n)),N7e=-(2n**(240n-1n)),M7e=-(2n**(248n-1n)),B7e=-(2n**(256n-1n)),D7e=2n**8n-1n,U7e=2n**16n-1n,L7e=2n**24n-1n,j7e=2n**32n-1n,F7e=2n**40n-1n,q7e=2n**48n-1n,H7e=2n**56n-1n,G7e=2n**64n-1n,V7e=2n**72n-1n,Z7e=2n**80n-1n,W7e=2n**88n-1n,K7e=2n**96n-1n,J7e=2n**104n-1n,Y7e=2n**112n-1n,Q7e=2n**120n-1n,X7e=2n**128n-1n,eVe=2n**136n-1n,tVe=2n**144n-1n,rVe=2n**152n-1n,nVe=2n**160n-1n,oVe=2n**168n-1n,iVe=2n**176n-1n,sVe=2n**184n-1n,aVe=2n**192n-1n,cVe=2n**200n-1n,uVe=2n**208n-1n,lVe=2n**216n-1n,dVe=2n**224n-1n,pVe=2n**232n-1n,fVe=2n**240n-1n,mVe=2n**248n-1n,lO=2n**256n-1n;function Zu(e,t,r){let{checksumAddress:o,staticPosition:n}=r,i=fO(t.type);if(i){let[s,a]=i;return rbe(e,{...t,type:a},{checksumAddress:o,length:s,staticPosition:n})}if(t.type==="tuple")return sbe(e,t,{checksumAddress:o,staticPosition:n});if(t.type==="address")return tbe(e,{checksum:o});if(t.type==="bool")return nbe(e);if(t.type.startsWith("bytes"))return obe(e,t,{staticPosition:n});if(t.type.startsWith("uint")||t.type.startsWith("int"))return ibe(e,t);if(t.type==="string")return abe(e,{staticPosition:n});throw new ny(t.type)}var N7=32,dO=32;function tbe(e,t={}){let{checksum:r=!1}=t,o=e.readBytes(32);return[((i)=>r?h1(i):i)(ar(qH(o,-20))),32]}function rbe(e,t,r){let{checksumAddress:o,length:n,staticPosition:i}=r;if(!n){let c=Ri(e.readBytes(dO)),u=i+c,d=u+N7;e.setPosition(u);let p=Ri(e.readBytes(N7)),m=ry(t),h=0,y=[];for(let x=0;x<p;++x){e.setPosition(d+(m?x*32:h));let[S,v]=Zu(e,t,{checksumAddress:o,staticPosition:d});h+=v,y.push(S)}return e.setPosition(i+32),[y,32]}if(ry(t)){let c=Ri(e.readBytes(dO)),u=i+c,d=[];for(let p=0;p<n;++p){e.setPosition(u+p*32);let[m]=Zu(e,t,{checksumAddress:o,staticPosition:u});d.push(m)}return e.setPosition(i+32),[d,32]}let s=0,a=[];for(let c=0;c<n;++c){let[u,d]=Zu(e,t,{checksumAddress:o,staticPosition:i+s});s+=d,a.push(u)}return[a,s]}function nbe(e){return[GH(e.readBytes(32),{size:32}),32]}function obe(e,t,{staticPosition:r}){let[o,n]=t.type.split("bytes");if(!n){let s=Ri(e.readBytes(32));e.setPosition(r+s);let a=Ri(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];let c=e.readBytes(a);return e.setPosition(r+32),[ar(c),32]}return[ar(e.readBytes(Number.parseInt(n,10),32)),32]}function ibe(e,t){let r=t.type.startsWith("int"),o=Number.parseInt(t.type.split("int")[1]||"256",10),n=e.readBytes(32);return[o>48?HH(n,{signed:r}):Ri(n,{signed:r}),32]}function sbe(e,t,r){let{checksumAddress:o,staticPosition:n}=r,i=t.components.length===0||t.components.some(({name:c})=>!c),s=i?[]:{},a=0;if(ry(t)){let c=Ri(e.readBytes(dO)),u=n+c;for(let d=0;d<t.components.length;++d){let p=t.components[d];e.setPosition(u+a);let[m,h]=Zu(e,p,{checksumAddress:o,staticPosition:u});a+=h,s[i?d:p?.name]=m}return e.setPosition(n+32),[s,32]}for(let c=0;c<t.components.length;++c){let u=t.components[c],[d,p]=Zu(e,u,{checksumAddress:o,staticPosition:n});s[i?c:u?.name]=d,a+=p}return[s,a]}function abe(e,{staticPosition:t}){let r=Ri(e.readBytes(32)),o=t+r;e.setPosition(o);let n=Ri(e.readBytes(32));if(n===0)return e.setPosition(t+32),["",32];let i=e.readBytes(n,32),s=VH(g2(i));return e.setPosition(t+32),[s,32]}function M7({checksumAddress:e,parameters:t,values:r}){let o=[];for(let n=0;n<t.length;n++)o.push(pO({checksumAddress:e,parameter:t[n],value:r[n]}));return o}function pO({checksumAddress:e=!1,parameter:t,value:r}){let o=t,n=fO(o.type);if(n){let[i,s]=n;return ube(r,{checksumAddress:e,length:i,parameter:{...o,type:s}})}if(o.type==="tuple")return mbe(r,{checksumAddress:e,parameter:o});if(o.type==="address")return cbe(r,{checksum:e});if(o.type==="bool")return dbe(r);if(o.type.startsWith("uint")||o.type.startsWith("int")){let i=o.type.startsWith("int"),[,,s="256"]=_1.exec(o.type)??[];return pbe(r,{signed:i,size:Number(s)})}if(o.type.startsWith("bytes"))return lbe(r,{type:o.type});if(o.type==="string")return fbe(r);throw new ny(o.type)}function w1(e){let t=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];if(s)t+=32;else t+=Zt(a)}let r=[],o=[],n=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];if(s)r.push(pt(t+n,{size:32})),o.push(a),n+=Zt(a);else r.push(a)}return Jt(...r,...o)}function cbe(e,t){let{checksum:r=!1}=t;return Gu(e,{strict:r}),{dynamic:!1,encoded:Ds(e.toLowerCase())}}function ube(e,t){let{checksumAddress:r,length:o,parameter:n}=t,i=o===null;if(!Array.isArray(e))throw new hO(e);if(!i&&e.length!==o)throw new mO({expectedLength:o,givenLength:e.length,type:`${n.type}[${o}]`});let s=!1,a=[];for(let c=0;c<e.length;c++){let u=pO({checksumAddress:r,parameter:n,value:e[c]});if(u.dynamic)s=!0;a.push(u)}if(i||s){let c=w1(a);if(i){let u=pt(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?Jt(u,c):u}}if(s)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Jt(...a.map(({encoded:c})=>c))}}function lbe(e,{type:t}){let[,r]=t.split("bytes"),o=Zt(e);if(!r){let n=e;if(o%32!==0)n=Oi(n,Math.ceil((e.length-2)/2/32)*32);return{dynamic:!0,encoded:Jt(Ds(pt(o,{size:32})),n)}}if(o!==Number.parseInt(r,10))throw new S1({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:Oi(e)}}function dbe(e){if(typeof e!=="boolean")throw new xe(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Ds(Lw(e))}}function pbe(e,{signed:t,size:r}){if(typeof r==="number"){let o=2n**(BigInt(r)-(t?1n:0n))-1n,n=t?-o-1n:0n;if(e>o||e<n)throw new jw({max:o.toString(),min:n.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:pt(e,{size:32,signed:t})}}function fbe(e){let t=Cp(e),r=Math.ceil(Zt(t)/32),o=[];for(let n=0;n<r;n++)o.push(Oi(Wt(t,n*32,(n+1)*32)));return{dynamic:!0,encoded:Jt(Oi(pt(Zt(t),{size:32})),...o)}}function mbe(e,t){let{checksumAddress:r,parameter:o}=t,n=!1,i=[];for(let s=0;s<o.components.length;s++){let a=o.components[s],c=Array.isArray(e)?s:a.name,u=pO({checksumAddress:r,parameter:a,value:e[c]});if(i.push(u),u.dynamic)n=!0}return{dynamic:n,encoded:n?w1(i):Jt(...i.map(({encoded:s})=>s))}}function fO(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function ry(e){let{type:t}=e;if(t==="string")return!0;if(t==="bytes")return!0;if(t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(ry);let r=fO(e.type);if(r&&ry({...e,type:r[1]}))return!0;return!1}jn();var gbe={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new D7({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new B7({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new gO({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new gO({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();if(this.positionReadCount.set(this.position,e+1),e>0)this.recursiveReadCount++}};function T1(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(gbe);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}class gO extends xe{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class B7 extends xe{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class D7 extends xe{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function Wp(e,t,r={}){let{as:o="Array",checksumAddress:n=!1}=r,i=typeof t==="string"?Rp(t):t,s=T1(i);if(bo(i)===0&&e.length>0)throw new j7;if(bo(i)&&bo(i)<32)throw new L7({data:typeof t==="string"?t:ar(t),parameters:e,size:bo(i)});let a=0,c=o==="Array"?[]:{};for(let u=0;u<e.length;++u){let d=e[u];s.setPosition(a);let[p,m]=Zu(s,d,{checksumAddress:n,staticPosition:0});if(a+=m,o==="Array")c.push(p);else c[d.name??u]=p}return c}function sc(e,t,r){let{checksumAddress:o=!1}=r??{};if(e.length!==t.length)throw new bO({expectedLength:e.length,givenLength:t.length});let n=M7({checksumAddress:o,parameters:e,values:t}),i=w1(n);if(i.length===0)return"0x";return i}function yO(e,t){if(e.length!==t.length)throw new bO({expectedLength:e.length,givenLength:t.length});let r=[];for(let o=0;o<e.length;o++){let n=e[o],i=t[o];r.push(yO.encode(n,i))}return Jt(...r)}(function(e){function t(r,o,n=!1){if(r==="address"){let c=o;return Gu(c),Ds(c.toLowerCase(),n?32:0)}if(r==="string")return Cp(o);if(r==="bytes")return o;if(r==="bool")return Ds(Lw(o),n?32:1);let i=r.match(_1);if(i){let[c,u,d="256"]=i,p=Number.parseInt(d,10)/8;return pt(o,{size:n?32:p,signed:u==="int"})}let s=r.match(C7);if(s){let[c,u]=s;if(Number.parseInt(u,10)!==(o.length-2)/2)throw new S1({expectedSize:Number.parseInt(u,10),value:o});return Oi(o,n?32:0)}let a=r.match(O7);if(a&&Array.isArray(o)){let[c,u]=a,d=[];for(let p=0;p<o.length;p++)d.push(t(u,o[p],!0));if(d.length===0)return"0x";return Jt(...d)}throw new ny(r)}e.encode=t})(yO||(yO={}));function iy(e){if(Array.isArray(e)&&typeof e[0]==="string")return Iw(e);if(typeof e==="string")return Iw(e);return e}class L7 extends xe{constructor({data:e,parameters:t,size:r}){super(`Data size of ${r} bytes is too small for given parameters.`,{metaMessages:[`Params: (${As(t)})`,`Data: ${e} (${r} bytes)`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class j7 extends xe{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.');Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class mO extends xe{constructor({expectedLength:e,givenLength:t,type:r}){super(`Array length mismatch for type \`${r}\`. Expected: \`${e}\`. Given: \`${t}\`.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class S1 extends xe{constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" (bytes${Zt(t)}) does not match expected size (bytes${e}).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class bO extends xe{constructor({expectedLength:e,givenLength:t}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${t}`].join(`
141
+ ${t}`}function K_(e,t){return uu(G_.sign(Dd(t),e))}var lg=[0.0001,0.001,0.01,0.1,1,10,100,1000,1e4];var vhe=1e4,_he=15000,whe=30000,She=1000,The=["created","activated","cancelled","parent_cancelled","triggered","failed","oco_cancelled"],Ehe=["STOP_LOSS","TAKE_PROFIT"],Ihe=["MARK_PRICE"],Phe=["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],khe=["POSITION","PARENT_ORDER"];function qd(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Ct(e,t){let r=e[t];if(typeof r!=="string"||r.length===0)throw Error(`Invalid WebSocket event: ${t} must be a non-empty string`);return r}function ur(e,t){let r=e[t];if(r===void 0||r===null)return;if(typeof r!=="string")throw Error(`Invalid WebSocket event: ${t} must be a string`);return r}function Ahe(e,t){let r=e[t];if(typeof r!=="boolean")throw Error(`Invalid WebSocket event: ${t} must be a boolean`);return r}function $he(e,t){let r=e[t];if(r===void 0||r===null)return;if(typeof r!=="number"||!Number.isFinite(r))throw Error(`Invalid WebSocket event: ${t} must be a finite number`);return r}function Ii(e,t,r){let o=Ct(e,t);if(!r.includes(o))throw Error(`Invalid WebSocket event: ${t} must be one of ${r.join(", ")}`);return o}function WF(e,t,r){let o=e[t];if(o===void 0||o===null)return;if(typeof o!=="string"||!r.includes(o))throw Error(`Invalid WebSocket event: ${t} must be one of ${r.join(", ")}`);return o}function Rhe(e){if(!qd(e))throw Error("Invalid conditional order event: payload must be an object");if(!qd(e.data))throw Error("Invalid conditional order event: data must be an object");let t=Ma(e.data);return{eventType:Ii(e,"event_type",["conditional_order_update"]),userId:Ct(e,"user_id"),data:{conditionalOrderId:Ct(t,"conditionalOrderId"),tradingPairId:Ct(t,"tradingPairId"),marginAccountId:Ct(t,"marginAccountId"),positionId:ur(t,"positionId"),parentOrderId:ur(t,"parentOrderId"),associationType:WF(t,"associationType",khe),linkedGroupId:ur(t,"linkedGroupId"),conditionType:Ii(t,"conditionType",Ehe),triggerSource:Ii(t,"triggerSource",Ihe),triggerPrice:Ct(t,"triggerPrice"),side:Ii(t,"side",["BUY","SELL"]),positionSide:Ii(t,"positionSide",["LONG","SHORT","NONE"]),orderType:Ii(t,"orderType",["LIMIT","MARKET"]),limitPrice:ur(t,"limitPrice"),quantity:ur(t,"quantity"),slippageToleranceBps:$he(t,"slippageToleranceBps"),reduceOnly:Ahe(t,"reduceOnly"),timeInForce:WF(t,"timeInForce",["GTC","IOC"]),state:Ii(t,"state",Phe),triggeredOrderId:ur(t,"triggeredOrderId"),triggeredAt:ur(t,"triggeredAt"),activatedAt:ur(t,"activatedAt"),cancelledAt:ur(t,"cancelledAt"),expiresAt:ur(t,"expiresAt"),failureReason:ur(t,"failureReason"),reason:Ii(t,"reason",The),updatedAt:Ct(t,"updatedAt")}}}function Ohe(e){if(!qd(e))throw Error("Invalid position event: payload must be an object");if(!qd(e.data))throw Error("Invalid position event: data must be an object");let t=Ma(e.data);return{eventType:Ii(e,"event_type",["position_update"]),userId:Ct(e,"user_id"),data:{positionId:Ct(t,"positionId"),marginAccountId:Ct(t,"marginAccountId"),tradingPairId:Ct(t,"tradingPairId"),side:Ct(t,"side"),status:Ct(t,"status"),size:Ct(t,"size"),entryPrice:Ct(t,"entryPrice"),markPrice:ur(t,"markPrice"),unrealizedPnl:ur(t,"unrealizedPnl"),liquidationPrice:ur(t,"liquidationPrice"),isolatedMargin:Ct(t,"isolatedMargin"),leverage:Ct(t,"leverage"),tradeId:ur(t,"tradeId"),orderId:ur(t,"orderId"),reason:Ct(t,"reason"),updatedAt:Ct(t,"updatedAt")}}}function Che(e){if(!qd(e))throw Error("Invalid liquidation event: payload must be an object");if(!qd(e.data))throw Error("Invalid liquidation event: data must be an object");let t=Ma(e.data);return{eventType:Ii(e,"event_type",["liquidation_alert"]),userId:Ct(e,"user_id"),data:{liquidationId:Ct(t,"liquidationId"),marginAccountId:Ct(t,"marginAccountId"),positionId:ur(t,"positionId"),tradingPairId:ur(t,"tradingPairId"),status:Ct(t,"status"),accountState:Ct(t,"accountState"),liquidationPrice:ur(t,"liquidationPrice"),markPrice:ur(t,"markPrice"),estimatedShortfall:Ct(t,"estimatedShortfall"),message:Ct(t,"message"),triggeredAt:Ct(t,"triggeredAt")}}}function z$(e,t={}){let r=null,o=t.session,n=0,i=null,s=null,a=t.autoReconnect??!0,c=t.maxReconnectAttempts??Number.POSITIVE_INFINITY,u=Number.isFinite(t.reconnectBaseDelayMs)&&t.reconnectBaseDelayMs>0?t.reconnectBaseDelayMs:She,d=Number.isFinite(t.connectionTimeoutMs)&&t.connectionTimeoutMs>0?t.connectionTimeoutMs:vhe,p=null,m=new Map,h=()=>{if(!r)return i?"reconnecting":"disconnected";switch(r.readyState){case WebSocket.CONNECTING:return"connecting";case WebSocket.OPEN:return"connected";default:return i?"reconnecting":"disconnected"}},y=()=>e,x=()=>{if(!o||r?.readyState!==WebSocket.OPEN)return;let N=Date.now(),Y=K_(tg(o.privateKey),ZF(o.publicKey,N));r.send(JSON.stringify({type:"Authenticate",public_key:o.publicKey,timestamp:N,signature:Y}))},S=()=>{if(s)clearInterval(s),s=null},v=()=>{S(),s=setInterval(()=>{if(r?.readyState===WebSocket.OPEN)r.send(JSON.stringify({type:"Ping"}))},_he)},E=()=>{if(i)clearTimeout(i),i=null},w=()=>{if(i)return;if(!a||n>=c){console.error("WebSocket: Max reconnect attempts reached");return}let N=Math.min(u*2**n,whe);n++;let Y=Math.random()*N;i=setTimeout(()=>{if(i=null,!a)return;O().catch((X)=>{console.warn("WebSocket: Failed to reconnect:",X),w()})},Y),t.onStatusChange?.("reconnecting")},_=(N)=>{if(r?.readyState===WebSocket.OPEN)r.send(JSON.stringify(N))},T=()=>{let N=Array.from(m.keys());if(N.length>0)_({type:"Subscribe",channels:N})},P=(N)=>{if(N.type!=="Event"||!N.channel)return;for(let[Y,X]of m)if(N.channel===Y||N.channel.startsWith(`${Y}:`))for(let ce of X)ce(N.data)},O=()=>new Promise((N,Y)=>{if(r?.readyState===WebSocket.CONNECTING||r?.readyState===WebSocket.OPEN){N();return}try{let X=new WebSocket(y());r=X;let ce=setTimeout(()=>{if(r!==X){N();return}if(X.readyState===WebSocket.CONNECTING)X.close(1000,"Connection timeout"),Y(Error("WebSocket connection timeout"))},d);X.onopen=()=>{if(clearTimeout(ce),r!==X){N();return}if(n=0,E(),v(),x(),T(),t.onStatusChange?.("connected"),p!==null){let Z=p;p=null,t.onResync?.({code:Z,slowClient:Z===1013})}N()},X.onmessage=(Z)=>{if(r!==X)return;try{let me=JSON.parse(Z.data);if(me.type==="Pong")return;if(me.type==="Ping"){_({type:"Pong"});return}P(me)}catch(me){console.warn("WebSocket: Failed to parse message",me)}},X.onclose=(Z)=>{if(clearTimeout(ce),r!==X){N();return}if(r=null,S(),a&&Z.code!==1000){if(p===null||Z.code===1013)p=Z.code;w()}if(!i)t.onStatusChange?.("disconnected")},X.onerror=()=>clearTimeout(ce)}catch(X){t.onStatusChange?.("disconnected"),Y(X)}}),z=()=>{a=!1,E(),S(),p=null,m.clear(),r?.close(1000,"Client disconnect"),r=null,t.onStatusChange?.("disconnected")},B=(N,Y)=>{let X=!m.has(N);if(!m.has(N))m.set(N,new Set);if(m.get(N)?.add(Y),X&&r?.readyState===WebSocket.OPEN)_({type:"Subscribe",channels:[N]});return()=>{let ce=m.get(N);if(ce){if(ce.delete(Y),ce.size===0){if(m.delete(N),r?.readyState===WebSocket.OPEN)_({type:"Unsubscribe",channels:[N]})}}}};return{connect:O,disconnect:z,isConnected:()=>r?.readyState===WebSocket.OPEN,getStatus:h,setSessionKeypair:(N)=>{if(o=N??void 0,o&&r?.readyState===WebSocket.OPEN)x();else if(o&&(!r||r.readyState===WebSocket.CLOSED))O().catch((Y)=>{console.warn("WebSocket: Failed to connect after session update:",Y)})},orders:(N,Y,X)=>{let ce=`orders:${N}:${Y}`;return B(ce,(Z)=>{try{let me=Z,Me={orderId:me.order_id,eventType:me.event_type,timestamp:me.timestamp,data:Ma(me.data)};X(Me)}catch(me){console.error("WebSocket: Error processing order event",me)}})},orderbook:(N,Y,X,ce,Z)=>{if(!N||!Y||X===void 0||!ce)throw Error(`orderbook subscription requires all params: tradingPairId="${N}", tradingMode="${Y}", magnitude=${X} (valid: ${lg.join(", ")}), quotationMode="${ce}" (valid: "BASE", "QUOTE")`);if(!lg.includes(X))throw Error(`Invalid magnitude: ${X}. Must be one of: ${lg.join(", ")}`);let me=`orderbook:${N}:${Y}:${X}:${ce.toLowerCase()}`;return B(me,(Me)=>{try{let Be=Me,Le=Be.data,Ut={tradingPairId:Be.trading_pair_id,tradingMode:Be.trading_mode,bids:(Le?.bids||[]).map((vt)=>({price:vt.price,quantity:vt.quantity,orderCount:vt.order_count||0})),asks:(Le?.asks||[]).map((vt)=>({price:vt.price,quantity:vt.quantity,orderCount:vt.order_count||0})),bestBid:Le?.best_bid??void 0,bestAsk:Le?.best_ask??void 0,bidVolume:Le?.bid_volume||void 0,askVolume:Le?.ask_volume||void 0,priceChange:Le?.price_change?{side:Le.price_change.side,oldPrice:Le.price_change.old_price??void 0,newPrice:Le.price_change.new_price??void 0,levelRemoved:Le.price_change.level_removed||!1,levelAdded:Le.price_change.level_added||!1}:void 0,baseDecimals:Be.base_decimals||0,quoteDecimals:Be.quote_decimals||0,timestamp:Be.timestamp||new Date().toISOString(),sequence:Be.sequence_number||0};Z(Ut)}catch(Be){console.error("WebSocket: Error processing orderbook event",Be)}})},ohlcv:(N,Y,X,ce)=>{let Z=`ohlcv:${N}:${Y}:${X}`;return B(Z,(me)=>{try{let Me=me,Be=Me.data,Le={tradingPairId:Me.trading_pair_id,tradingMode:Me.trading_mode,interval:Me.interval,candlestick:{T:Be.period_start||0,t:Be.period_end||0,o:Be.open||"0",h:Be.high||"0",l:Be.low||"0",c:Be.close||"0",v:Be.volume||"0",s:Me.symbol,i:Me.interval,n:Be.trades_count||0}};ce(Le)}catch(Me){console.error("WebSocket: Error processing OHLCV event",Me)}})},trades:(N,Y)=>{let X=`trades:${N}`;return B(X,(ce)=>{try{let Z=ce,me=Z.data,Me={eventType:"trade",tradingPairId:Z.trading_pair_id,tradingMode:Z.trading_mode.toUpperCase(),data:{tradeId:me.trade_id,price:me.price,quantity:me.quantity,makerSide:me.maker_side.toUpperCase(),executedAt:me.executed_at}};Y(Me)}catch(Z){console.error("WebSocket: Error processing trade event",Z)}})},movements:(N)=>B("movements",(X)=>{try{let ce=X,Z=ce.data,me={eventType:"movement",userId:ce.user_id,data:{id:Z.id,entryType:Z.entry_type,transactionType:Z.transaction_type,status:Z.status,token:Z.token??Z.token_address,tokenAddress:Z.token??Z.token_address,assetId:Z.asset_id,amount:String(Z.amount),amountRaw:Z.amount_raw,balanceBefore:Z.balance_before!=null?String(Z.balance_before):void 0,balanceAfter:Z.balance_after!=null?String(Z.balance_after):void 0,lockedBefore:Z.locked_before!=null?String(Z.locked_before):void 0,lockedAfter:Z.locked_after!=null?String(Z.locked_after):void 0,referenceId:Z.reference_id,referenceType:Z.reference_type,description:Z.description,txHash:Z.tx_hash,blockNumber:Z.block_number,createdAt:Z.created_at,decimals:Z.decimals}};N(me)}catch(ce){console.error("WebSocket: Error processing movement event",ce)}}),userOrders:(N)=>B("orders",(X)=>{try{let ce=X,Z={orderId:ce.order_id,eventType:ce.event_type,timestamp:ce.timestamp,data:Ma(ce.data)};N(Z)}catch(ce){console.error("WebSocket: Error processing user order event",ce)}}),balances:(N)=>B("balances",(X)=>{try{let ce=X,Z=ce.data,me={eventType:"balance_update",userId:ce.user_id,data:{tokenAddress:Z.token_address,tokenSymbol:Z.token_symbol,available:Z.available,availableRaw:Z.available_raw,locked:Z.locked,lockedRaw:Z.locked_raw,total:Z.total,totalRaw:Z.total_raw,reason:Z.reason,referenceId:Z.reference_id,updatedAt:Z.updated_at}};N(me)}catch(ce){console.error("WebSocket: Error processing balance event",ce)}}),conditionalOrders:(N,Y)=>{if(!N)throw Error("conditionalOrders subscription requires a handler");if(Y!==void 0&&Y.length===0)throw Error("conditionalOrders tradingPairId cannot be empty");let X=Y?`conditional_orders:${Y}`:"conditional_orders";return B(X,(ce)=>{try{N(Rhe(ce))}catch(Z){console.error("WebSocket: Error processing conditional order event",Z)}})},positions:(N,Y)=>{if(!N)throw Error("positions subscription requires a handler");if(Y!==void 0&&Y.length===0)throw Error("positions tradingPairId cannot be empty");let X=Y?`positions:${Y}`:"positions";return B(X,(ce)=>{try{N(Ohe(ce))}catch(Z){console.error("WebSocket: Error processing position event",Z)}})},liquidations:(N,Y)=>{if(!N)throw Error("liquidations subscription requires a handler");if(Y!==void 0&&Y.length===0)throw Error("liquidations tradingPairId cannot be empty");let X=Y?`liquidations:${Y}`:"liquidations";return B(X,(ce)=>{try{N(Che(ce))}catch(Z){console.error("WebSocket: Error processing liquidation event",Z)}})}}}var Fa=rn(Y_(),1),sq=["token","accessToken","access_token","refreshToken","refresh_token","authToken","auth_token","bearerToken","bearer_token","jwtToken","jwt_token","apiKey","api_key","apikey","clientSecret","client_secret","clientId","client_id","secret","password","authorization","bearer","auth","credentials","credential","email","phone","phoneNumber","phone_number","ssn","socialSecurity","social_security","address","passport","passportNumber","passport_number","driversLicense","drivers_license","cardNumber","card_number","creditCard","credit_card","cvv","pin","signature","privateKey","private_key","publicKey","public_key","mnemonic","seed","salt","hash","certificate","cert","fingerprint","cookie","session","sessionId","session_id","sessionToken","session_token","ipAddress","ip_address","deviceId","device_id","userId","user_id","accountId","account_id"];function Hd(e,t=5,r=0){if(r>=t)return"[Max depth reached]";if(e===null||e===void 0)return e;if(Array.isArray(e)){let n=e.slice(0,10).map((i)=>Hd(i,t,r+1));if(e.length>10)n.push(`[... ${e.length-10} more items]`);return n}if(typeof e==="object"){let o={};for(let[n,i]of Object.entries(e)){let s=n.toLowerCase();if(sq.some((c)=>s.includes(c.toLowerCase())))o[n]="[REDACTED]";else if(typeof i==="string"&&i.length>500)o[n]=`${i.substring(0,500)}... [truncated]`;else o[n]=Hd(i,t,r+1)}return o}if(typeof e==="string"){if(e.length>1000)return`${e.substring(0,1000)}... [truncated]`;return e}return e}class Gd extends Error{cause;suggestion;retryable=!1;timestamp;constructor(e,t){super(e);if(this.name=this.constructor.name,this.timestamp=Date.now(),t?.cause)this.cause=t.cause;if(t?.suggestion)this.suggestion=t.suggestion;if(t?.retryable!==void 0)this.retryable=t.retryable}toJSON(){return{name:this.name,code:this.code,message:this.message,suggestion:this.suggestion,retryable:this.retryable,timestamp:this.timestamp,cause:this.cause instanceof Error?this.cause.message:this.cause}}}class Bt extends Gd{code="INVALID_CONFIG";field;value;constructor(e,t,r,o){let n=t?`Check the '${t}' configuration parameter. ${Whe(t)}`:"Review your SDK configuration and ensure all required fields are provided correctly.";super(e,{cause:o,suggestion:n,retryable:!1});this.field=t,this.value=r}toJSON(){let e;if(this.field){let t=this.field.toLowerCase();if(sq.some((o)=>t.includes(o.toLowerCase())))e="[REDACTED]";else e=Hd(this.value)}else e=Hd(this.value);return{...super.toJSON(),field:this.field,value:e}}}function Whe(e){switch(e.toLowerCase()){case"walletclient":return"Ensure you're creating the wallet client with a valid account and chain configuration.";case"seirpcurl":return"Use 'https://evm-rpc-testnet.sei-apis.com' for testnet or 'https://evm-rpc.sei-apis.com' for mainnet.";case"wsurl":return"Use 'wss://ws-develop.apimonaco.xyz/ws' for testnet or 'wss://ws.apimonaco.xyz/ws' for mainnet.";case"network":return"Valid networks are: 'mainnet', 'development', 'staging', 'local'.";default:return"Refer to the SDK documentation for correct configuration format."}}class dg extends Gd{code="INVALID_STATE";currentState;expectedState;constructor(e,t,r,o){let n=r?`${t?`Current state is '${t}', `:""}Expected state is '${r}'. Ensure operations are performed in the correct order.`:"Check that prerequisites are met before calling this method.";super(e,{cause:o,suggestion:n,retryable:!1});this.currentState=t,this.expectedState=r}toJSON(){return{...super.toJSON(),currentState:this.currentState,expectedState:this.expectedState}}}class or extends Gd{code="API_ERROR";endpoint;statusCode;responseBody;requestBody;requestId;retryAfter;constructor(e,t){let{suggestion:r,retryable:o}=Khe(t?.statusCode,e,t?.responseBody);super(e,{cause:t?.cause,suggestion:r,retryable:o});this.endpoint=t?.endpoint,this.statusCode=t?.statusCode,this.responseBody=t?.responseBody,this.requestBody=t?.requestBody,this.requestId=t?.requestId,this.retryAfter=t?.retryAfter}toJSON(){return{...super.toJSON(),endpoint:this.endpoint,statusCode:this.statusCode,responseBody:Hd(this.responseBody),requestBody:Hd(this.requestBody),requestId:this.requestId,retryAfter:this.retryAfter}}}function Khe(e,t,r){if(!e)return{suggestion:"Network request failed. Check your internet connection and try again.",retryable:!0};if(e===Fa.StatusCodes.UNAUTHORIZED){if(t?.toLowerCase().includes("expired"))return{suggestion:"Access token has expired. Call sdk.refreshAuth() to get a new token, or call sdk.login() to re-authenticate.",retryable:!1};return{suggestion:"Authentication required. Call sdk.login(clientId) to authenticate before making this request.",retryable:!1}}if(e===Fa.StatusCodes.FORBIDDEN)return{suggestion:"Access denied. Ensure your application has the required permissions and your client ID is valid.",retryable:!1};if(e===Fa.StatusCodes.NOT_FOUND)return{suggestion:"Resource not found. Check that the ID or identifier is correct and the resource exists.",retryable:!1};if(e===Fa.StatusCodes.CONFLICT)return{suggestion:"Resource conflict. The resource may have been modified. Refresh and try again.",retryable:!0};if(e===Fa.StatusCodes.BAD_REQUEST){if(t?.toLowerCase().includes("insufficient balance"))return{suggestion:"Insufficient balance. Deposit more funds using sdk.vault.deposit() or reduce the order size.",retryable:!1};if(t?.toLowerCase().includes("invalid"))return{suggestion:"Invalid request parameters. Check the API documentation for correct parameter format and values.",retryable:!1};return{suggestion:"Bad request. Verify that all required parameters are provided and correctly formatted.",retryable:!1}}if(e===Fa.StatusCodes.TOO_MANY_REQUESTS){let o;if(typeof r==="object"&&r!==null&&"retry_after"in r&&r.retry_after){let n=r.retry_after;o=` Wait ${String(n)} seconds before retrying.`}else o=" Wait a moment before retrying.";return{suggestion:`Rate limit exceeded.${o} Consider implementing exponential backoff for retries.`,retryable:!0}}if(e>=Fa.StatusCodes.INTERNAL_SERVER_ERROR&&e<600)return{suggestion:"Server error occurred. This is likely a temporary issue. Try again in a few moments.",retryable:!0};return{suggestion:void 0,retryable:!1}}class _s extends Gd{code="CONTRACT_ERROR";revertReason;transactionHash;contractAddress;constructor(e,t){let r=Jhe(t?.revertReason);super(e,{cause:t?.cause,suggestion:r,retryable:!1});this.revertReason=t?.revertReason,this.transactionHash=t?.transactionHash,this.contractAddress=t?.contractAddress}toJSON(){return{...super.toJSON(),revertReason:this.revertReason,transactionHash:this.transactionHash,contractAddress:this.contractAddress}}}function Jhe(e){if(!e)return"Smart contract execution failed. Check transaction parameters and try again.";let t=e.toLowerCase();if(t.includes("insufficient allowance"))return"Token allowance is insufficient. Call sdk.vault.approve() to increase the token allowance for the vault contract.";if(t.includes("insufficient balance"))return"Wallet balance is insufficient for this transaction. Ensure you have enough tokens and native currency for gas fees.";if(t.includes("nonce"))return"Transaction nonce error. This may be due to a pending transaction. Wait for pending transactions to complete or reset your account nonce.";if(t.includes("gas"))return"Transaction ran out of gas. Try increasing the gas limit for this transaction.";return}var Yhe={local:"http://localhost:8080",development:"https://develop.apimonaco.xyz",staging:"https://staging.apimonaco.xyz",mainnet:"https://api.monaco.xyz"},Qhe={local:"ws://localhost:8085/ws",development:"wss://ws-develop.apimonaco.xyz/ws",staging:"wss://ws-staging.apimonaco.xyz/ws",mainnet:"wss://ws.apimonaco.xyz/ws"};function j$(e){return Yhe[e]}function F$(e){return Qhe[e]}var u5=rn(Y_(),1);var Q_=256,X_;function ew(e=11){if(!X_||Q_+e>512){X_="",Q_=0;for(let t=0;t<256;t++)X_+=(256+Math.random()*256|0).toString(16).substring(1)}return X_.substring(Q_,Q_+++e)}function aq(e){let{batch:t,chain:r,ccipRead:o,dataSuffix:n,key:i="base",name:s="Base Client",type:a="base"}=e,c=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime==="number"?"pending":void 0),u=r?.blockTime??12000,d=Math.min(Math.max(Math.floor(u/2),500),4000),p=e.pollingInterval??d,m=e.cacheTime??p,h=e.account?Ft(e.account):void 0,{config:y,request:x,value:S}=e.transport({account:h,chain:r,pollingInterval:p}),v={...y,...S},E={account:h,batch:t,cacheTime:m,ccipRead:o,chain:r,dataSuffix:n,key:i,name:s,pollingInterval:p,request:x,transport:v,type:a,uid:ew(),...c?{experimental_blockTag:c}:{}};function w(_){return(T)=>{let P=T(_);for(let z in E)delete P[z];let O={..._,...P};return Object.assign(O,{extend:w(O)})}}return Object.assign(E,{extend:w(E)})}Pi();Os();ho();Pu();We();ot();Wa();function sp(e){if(!(e instanceof F))return!1;let t=e.walk((r)=>r instanceof ip);if(!(t instanceof ip))return!1;if(t.data?.errorName==="HttpError")return!0;if(t.data?.errorName==="ResolverError")return!0;if(t.data?.errorName==="ResolverNotContract")return!0;if(t.data?.errorName==="ResolverNotFound")return!0;if(t.data?.errorName==="ReverseAddressMismatch")return!0;if(t.data?.errorName==="UnsupportedResolverProfile")return!0;return!1}Rg();jr();We();Zo();function zw(e){if(e.length!==66)return null;if(e.indexOf("[")!==0)return null;if(e.indexOf("]")!==65)return null;let t=`0x${e.slice(1,65)}`;if(!sr(t))return null;return t}function Og(e){let t=new Uint8Array(32).fill(0);if(!e)return ht(t);let r=e.split(".");for(let o=r.length-1;o>=0;o-=1){let n=zw(r[o]),i=n?fo(n):zt(Vo(r[o]),"bytes");t=zt(Fr([t,i]),"bytes")}return ht(t)}jr();function PH(e){return`[${e.slice(2)}]`}jr();We();Zo();function kH(e){let t=new Uint8Array(32).fill(0);if(!e)return ht(t);return zw(e)||zt(Vo(e))}function ap(e){let t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);let r=new Uint8Array(Vo(t).byteLength+2),o=0,n=t.split(".");for(let i=0;i<n.length;i++){let s=Vo(n[i]);if(s.byteLength>255)s=Vo(PH(kH(n[i])));r[o]=s.length,r.set(s,o+1),o+=s.length+1}if(r.byteLength!==o+1)return r.slice(0,o+1);return r}function pe(e,t,r){let o=e[t.name];if(typeof o==="function")return o;let n=e[r];if(typeof n==="function")return n;return(i)=>t(e,i)}Os();ho();ir();ot();Wa();Ru();Cg();var Jge=3;function Yo(e,{abi:t,address:r,args:o,docsPath:n,functionName:i,sender:s}){let a=e instanceof zs?e:e instanceof F?e.walk((y)=>("data"in y))||e.walk():{},{code:c,data:u,details:d,message:p,shortMessage:m}=a,h=(()=>{if(e instanceof Ho)return new t2({functionName:i,cause:e});if([Jge,Ms.code].includes(c)&&(u||d||p||m)||c===yo.code&&d==="execution reverted"&&u)return new ip({abi:t,data:typeof u==="object"?u.data:u,functionName:i,message:a instanceof $u?d:m??p,cause:e});return e})();return new $g(h,{abi:t,args:o,contractAddress:r,docsPath:n,functionName:i,sender:s})}Uu();async function dr(e,t){let{abi:r,address:o,args:n,functionName:i,...s}=t,a=Kt({abi:r,args:n,functionName:i});try{let{data:c}=await pe(e,vo,"call")({...s,data:a,to:o});return Xr({abi:r,args:n,functionName:i,data:c||"0x"})}catch(c){throw Yo(c,{abi:r,address:o,args:n,docsPath:"/docs/contract/readContract",functionName:i})}}async function lG(e,t){let{blockNumber:r,blockTag:o,coinType:n,name:i,gatewayUrls:s,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return go({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some((m)=>i.endsWith(m)))return null;let p=(()=>{if(n!=null)return[Og(i),BigInt(n)];return[Og(i)]})();try{let m=Kt({abi:H$,functionName:"addr",args:p}),h={address:u,abi:rw,functionName:"resolveWithGateways",args:[Qr(ap(i)),m,s??[Ns]],blockNumber:r,blockTag:o},x=await pe(e,dr,"readContract")(h);if(x[0]==="0x")return null;let S=Xr({abi:H$,args:p,functionName:"addr",data:x[0]});if(S==="0x")return null;if(Go(S)==="0x00")return null;return S}catch(m){if(a)throw m;if(sp(m))return null;throw m}}ot();class $2 extends F{constructor({data:e}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(e)}`],name:"EnsAvatarInvalidMetadataError"})}}class Lu extends F{constructor({reason:e}){super(`ENS NFT avatar URI is invalid. ${e}`,{name:"EnsAvatarInvalidNftUriError"})}}class Vg extends F{constructor({uri:e}){super(`Unable to resolve ENS avatar URI "${e}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class R2 extends F{constructor({namespace:e}){super(`ENS NFT avatar namespace "${e}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}var yye=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,bye=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,xye=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,vye=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function _ye(e){try{let t=await fetch(e,{method:"HEAD"});if(t.status===200)return t.headers.get("content-type")?.startsWith("image/");return!1}catch(t){if(typeof t==="object"&&typeof t.response<"u")return!1;if(!Object.hasOwn(globalThis,"Image"))return!1;return new Promise((r)=>{let o=new Image;o.onload=()=>{r(!0)},o.onerror=()=>{r(!1)},o.src=e})}}function dG(e,t){if(!e)return t;if(e.endsWith("/"))return e.slice(0,-1);return e}function O2({uri:e,gatewayUrls:t}){let r=xye.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};let o=dG(t?.ipfs,"https://ipfs.io"),n=dG(t?.arweave,"https://arweave.net"),i=e.match(yye),{protocol:s,subpath:a,target:c,subtarget:u=""}=i?.groups||{},d=s==="ipns:/"||a==="ipns/",p=s==="ipfs:/"||a==="ipfs/"||bye.test(e);if(e.startsWith("http")&&!d&&!p){let h=e;if(t?.arweave)h=e.replace(/https:\/\/arweave.net/g,t?.arweave);return{uri:h,isOnChain:!1,isEncoded:!1}}if((d||p)&&c)return{uri:`${o}/${d?"ipns":"ipfs"}/${c}${u}`,isOnChain:!1,isEncoded:!1};if(s==="ar:/"&&c)return{uri:`${n}/${c}${u||""}`,isOnChain:!1,isEncoded:!1};let m=e.replace(vye,"");if(m.startsWith("<svg"))m=`data:image/svg+xml;base64,${btoa(m)}`;if(m.startsWith("data:")||m.startsWith("{"))return{uri:m,isOnChain:!0,isEncoded:!1};throw new Vg({uri:e})}function C2(e){if(typeof e!=="object"||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new $2({data:e});return e.image||e.image_url||e.image_data}async function pG({gatewayUrls:e,uri:t}){try{let r=await fetch(t).then((n)=>n.json());return await Ww({gatewayUrls:e,uri:C2(r)})}catch{throw new Vg({uri:t})}}async function Ww({gatewayUrls:e,uri:t}){let{uri:r,isOnChain:o}=O2({uri:t,gatewayUrls:e});if(o)return r;if(await _ye(r))return r;throw new Vg({uri:t})}function fG(e){let t=e;if(t.startsWith("did:nft:"))t=t.replace("did:nft:","").replace(/_/g,"/");let[r,o,n]=t.split("/"),[i,s]=r.split(":"),[a,c]=o.split(":");if(!i||i.toLowerCase()!=="eip155")throw new Lu({reason:"Only EIP-155 supported"});if(!s)throw new Lu({reason:"Chain ID not found"});if(!c)throw new Lu({reason:"Contract address not found"});if(!n)throw new Lu({reason:"Token ID not found"});if(!a)throw new Lu({reason:"ERC namespace not found"});return{chainID:Number.parseInt(s,10),namespace:a.toLowerCase(),contractAddress:c,tokenID:n}}async function mG(e,{nft:t}){if(t.namespace==="erc721")return dr(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return dr(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new R2({namespace:t.namespace})}async function hG(e,{gatewayUrls:t,record:r}){if(/eip155:/i.test(r))return wye(e,{gatewayUrls:t,record:r});return Ww({uri:r,gatewayUrls:t})}async function wye(e,{gatewayUrls:t,record:r}){let o=fG(r),n=await mG(e,{nft:o}),{uri:i,isOnChain:s,isEncoded:a}=O2({uri:n,gatewayUrls:t});if(s&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){let u=a?atob(i.replace("data:application/json;base64,","")):i,d=JSON.parse(u);return Ww({uri:C2(d),gatewayUrls:t})}let c=o.tokenID;if(o.namespace==="erc1155")c=c.replace("0x","").padStart(64,"0");return pG({gatewayUrls:t,uri:i.replace(/(?:0x)?{id}/,c)})}Pi();Os();ho();Pu();We();Rg();async function Kw(e,t){let{blockNumber:r,blockTag:o,key:n,name:i,gatewayUrls:s,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return go({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some((p)=>i.endsWith(p)))return null;try{let p={address:u,abi:rw,args:[Qr(ap(i)),Kt({abi:q$,functionName:"text",args:[Og(i),n]}),s??[Ns]],functionName:"resolveWithGateways",blockNumber:r,blockTag:o},h=await pe(e,dr,"readContract")(p);if(h[0]==="0x")return null;let y=Xr({abi:q$,functionName:"text",data:h[0]});return y===""?null:y}catch(p){if(a)throw p;if(sp(p))return null;throw p}}async function gG(e,{blockNumber:t,blockTag:r,assetGatewayUrls:o,name:n,gatewayUrls:i,strict:s,universalResolverAddress:a}){let c=await pe(e,Kw,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:n,universalResolverAddress:a,gatewayUrls:i,strict:s});if(!c)return null;try{return await hG(e,{record:c,gatewayUrls:o})}catch{return null}}Pi();Pu();Rg();async function yG(e,t){let{address:r,blockNumber:o,blockTag:n,coinType:i=60n,gatewayUrls:s,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return go({blockNumber:o,chain:c,contract:"ensUniversalResolver"})})();try{let d={address:u,abi:uq,args:[r,i,s??[Ns]],functionName:"reverseWithGateways",blockNumber:o,blockTag:n},p=pe(e,dr,"readContract"),[m]=await p(d);return m||null}catch(d){if(a)throw d;if(sp(d))return null;throw d}}Pu();We();async function bG(e,t){let{blockNumber:r,blockTag:o,name:n}=t,{chain:i}=e,s=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!i)throw Error("client chain not configured. universalResolverAddress is required.");return go({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),a=i?.ensTlds;if(a&&!a.some((u)=>n.endsWith(u)))throw Error(`${n} is not a valid ENS TLD (${a?.join(", ")}) for chain "${i.name}" (id: ${i.id}).`);let[c]=await pe(e,dr,"readContract")({address:s,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[Qr(ap(n))],blockNumber:r,blockTag:o});return c}Uu();We();T2();Np();Du();async function Jw(e,t){let{account:r=e.account,blockNumber:o,blockTag:n="latest",blobs:i,data:s,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:p,to:m,value:h,...y}=t,x=r?Ft(r):void 0;try{xo(t);let v=(typeof o==="bigint"?ye(o):void 0)||n,E=e.chain?.formatters?.transactionRequest?.format,_=(E||Ci)({...ec(y,{format:E}),account:x,blobs:i,data:s,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:p,to:m,value:h},"createAccessList"),T=await e.request({method:"eth_createAccessList",params:[_,v]});return{accessList:T.accessList,gasUsed:BigInt(T.gasUsed)}}catch(S){throw Hw(S,{...t,account:x,chain:e.chain})}}function tc(e,{method:t}){let r={};if(e.transport.type==="fallback")e.transport.onResponse?.(({method:o,response:n,status:i,transport:s})=>{if(i==="success"&&t===o)r[n]=s.request});return(o)=>r[o]||e.request}async function xG(e){let t=tc(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}ir();ot();class z2 extends F{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}jr();Zo();Ig();Ps();ws();Za();var vG="/docs/contract/encodeEventTopics";function zi(e){let{abi:t,eventName:r,args:o}=e,n=t[0];if(r){let c=Ln({abi:t,name:r});if(!c)throw new sw(r,{docsPath:vG});n=c}if(n.type!=="event")throw new sw(void 0,{docsPath:vG});let i=hr(n),s=Va(i),a=[];if(o&&"inputs"in n){let c=n.inputs?.filter((d)=>("indexed"in d)&&d.indexed),u=Array.isArray(o)?o:Object.values(o).length>0?c?.map((d)=>o[d.name])??[]:[];if(u.length>0)a=c?.map((d,p)=>{if(Array.isArray(u[p]))return u[p].map((m,h)=>_G({param:d,value:u[p][h]}));return typeof u[p]<"u"&&u[p]!==null?_G({param:d,value:u[p]}):null})??[]}return[s,...a]}function _G({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return zt(fo(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new z2(e.type);return yn([e],[t])}We();async function Yw(e,t){let{address:r,abi:o,args:n,eventName:i,fromBlock:s,strict:a,toBlock:c}=t,u=tc(e,{method:"eth_newFilter"}),d=i?zi({abi:o,args:n,eventName:i}):void 0,p=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof s==="bigint"?ye(s):s,toBlock:typeof c==="bigint"?ye(c):c,topics:d}]});return{abi:o,args:n,eventName:i,id:p,request:u(p),strict:Boolean(a),type:"event"}}We();async function Qw(e,{address:t,args:r,event:o,events:n,fromBlock:i,strict:s,toBlock:a}={}){let c=n??(o?[o]:void 0),u=tc(e,{method:"eth_newFilter"}),d=[];if(c){if(d=[c.flatMap((h)=>zi({abi:[h],eventName:h.name,args:r}))],o)d=d[0]}let p=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof i==="bigint"?ye(i):i,toBlock:typeof a==="bigint"?ye(a):a,...d.length?{topics:d}:{}}]});return{abi:c,args:r,eventName:o?o.name:void 0,fromBlock:i,id:p,request:u(p),strict:Boolean(s),toBlock:a,type:"event"}}async function Xw(e){let t=tc(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}ho();ot();Tu();Zo();function wG(e){let t=zt(`0x${e.substring(4)}`).substring(26);return Su(`0x${t}`)}po();gn();We();async function BG({hash:e,signature:t}){let r=sr(e)?e:Qr(e),{secp256k1:o}=await Promise.resolve().then(() => (oc(),Z2));return`0x${(()=>{if(typeof t==="object"&&"r"in t&&"s"in t){let{r:u,s:d,v:p,yParity:m}=t,h=Number(m??p),y=MG(h);return new o.Signature(Ur(u),Ur(d)).addRecoveryBit(y)}let s=sr(t)?t:Qr(t);if(at(s)!==65)throw Error("invalid signature length");let a=wr(`0x${s.slice(130)}`),c=MG(a);return o.Signature.fromCompact(s.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function MG(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw Error("Invalid yParityOrV value")}async function Yg({hash:e,signature:t}){return wG(await BG({hash:e,signature:t}))}jr();We();ot();mw();jr();We();function DG(e,t="hex"){let r=UG(e),o=Wd(new Uint8Array(r.length));if(r.encode(o),t==="hex")return ht(o.bytes);return o.bytes}function UG(e){if(Array.isArray(e))return Mye(e.map((t)=>UG(t)));return Bye(e)}function Mye(e){let t=e.reduce((n,i)=>n+i.length,0),r=LG(t);return{length:(()=>{if(t<=55)return 1+t;return 1+r+t})(),encode(n){if(t<=55)n.pushByte(192+t);else if(n.pushByte(247+r),r===1)n.pushUint8(t);else if(r===2)n.pushUint16(t);else if(r===3)n.pushUint24(t);else n.pushUint32(t);for(let{encode:i}of e)i(n)}}}function Bye(e){let t=typeof e==="string"?Lr(e):e,r=LG(t.length);return{length:(()=>{if(t.length===1&&t[0]<128)return 1;if(t.length<=55)return 1+t.length;return 1+r+t.length})(),encode(n){if(t.length===1&&t[0]<128)n.pushBytes(t);else if(t.length<=55)n.pushByte(128+t.length),n.pushBytes(t);else{if(n.pushByte(183+r),r===1)n.pushUint8(t.length);else if(r===2)n.pushUint16(t.length);else if(r===3)n.pushUint24(t.length);else n.pushUint32(t.length);n.pushBytes(t)}}}}function LG(e){if(e<256)return 1;if(e<65536)return 2;if(e<16777216)return 3;if(e<4294967296)return 4;throw new F("Length is too large.")}Zo();function jG(e){let{chainId:t,nonce:r,to:o}=e,n=e.contractAddress??e.address,i=zt(Wo(["0x05",DG([t?ye(t):"0x",n,r?ye(r):"0x"])]));if(o==="bytes")return Lr(i);return i}async function n1(e){let{authorization:t,signature:r}=e;return Yg({hash:jG(t),signature:r??t})}We();Cw();op();ot();Cs();class W2 extends F{constructor(e,{account:t,docsPath:r,chain:o,data:n,gas:i,gasPrice:s,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:u,to:d,value:p}){let m=ku({from:t?.address,to:d,value:typeof p<"u"&&`${np(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:n,gas:i,gasPrice:typeof s<"u"&&`${gr(s)} gwei`,maxFeePerGas:typeof a<"u"&&`${gr(a)} gwei`,maxPriorityFeePerGas:typeof c<"u"&&`${gr(c)} gwei`,nonce:u});super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",m].filter(Boolean),name:"EstimateGasExecutionError"});Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}Bu();Gg();function FG(e,{docsPath:t,...r}){let o=(()=>{let n=Xa(e,r);if(n instanceof Qo)return e;return n})();return new W2(o,{docsPath:t,...r})}Np();Zw();Du();op();ot();class Qg extends F{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class ju extends F{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class K2 extends F{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${gr(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}gn();ot();class Xg extends F{constructor({blockHash:e,blockNumber:t}){let r="Block";if(e)r=`Block at hash "${e}"`;if(t)r=`Block at number "${t}"`;super(`${r} could not be found.`,{name:"BlockNotFoundError"})}}We();gn();var J2={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Up(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?wr(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?wr(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?J2[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};if(e.authorizationList)r.authorizationList=Dye(e.authorizationList);if(r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v==="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}return})(),r.type==="legacy")delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity;if(r.type==="eip2930")delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas;if(r.type==="eip1559")delete r.maxFeePerBlobGas;return r}function Dye(e){return e.map((t)=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function o1(e,t){let r=(e.transactions??[]).map((o)=>{if(typeof o==="string")return o;return Up(o)});return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}async function Tr(e,{blockHash:t,blockNumber:r,blockTag:o=e.experimental_blockTag??"latest",includeTransactions:n}={}){let i=n??!1,s=r!==void 0?ye(r):void 0,a=null;if(t)a=await e.request({method:"eth_getBlockByHash",params:[t,i]},{dedupe:!0});else a=await e.request({method:"eth_getBlockByNumber",params:[s||o,i]},{dedupe:Boolean(s)});if(!a)throw new Xg({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||o1)(a,"getBlock")}async function Lp(e){let t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function qG(e,t){return Y2(e,t)}async function Y2(e,t){let{block:r,chain:o=e.chain,request:n}=t||{};try{let i=o?.fees?.maxPriorityFeePerGas??o?.fees?.defaultPriorityFee;if(typeof i==="function"){let a=r||await pe(e,Tr,"getBlock")({}),c=await i({block:a,client:e,request:n});if(c===null)throw Error();return c}if(typeof i<"u")return i;let s=await e.request({method:"eth_maxPriorityFeePerGas"});return Ur(s)}catch{let[i,s]=await Promise.all([r?Promise.resolve(r):pe(e,Tr,"getBlock")({}),pe(e,Lp,"getGasPrice")({})]);if(typeof i.baseFeePerGas!=="bigint")throw new ju;let a=s-i.baseFeePerGas;if(a<0n)return 0n;return a}}async function HG(e,t){return i1(e,t)}async function i1(e,t){let{block:r,chain:o=e.chain,request:n,type:i="eip1559"}=t||{},s=await(async()=>{if(typeof o?.fees?.baseFeeMultiplier==="function")return o.fees.baseFeeMultiplier({block:r,client:e,request:n});return o?.fees?.baseFeeMultiplier??1.2})();if(s<1)throw new Qg;let c=10**(s.toString().split(".")[1]?.length??0),u=(m)=>m*BigInt(Math.ceil(s*c))/BigInt(c),d=r?r:await pe(e,Tr,"getBlock")({});if(typeof o?.fees?.estimateFeesPerGas==="function"){let m=await o.fees.estimateFeesPerGas({block:r,client:e,multiply:u,request:n,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof d.baseFeePerGas!=="bigint")throw new ju;let m=typeof n?.maxPriorityFeePerGas==="bigint"?n.maxPriorityFeePerGas:await Y2(e,{block:d,chain:o,request:n}),h=u(d.baseFeePerGas);return{maxFeePerGas:n?.maxFeePerGas??h+m,maxPriorityFeePerGas:m}}return{gasPrice:n?.gasPrice??u(await pe(e,Lp,"getGasPrice")({}))}}gn();We();async function s1(e,{address:t,blockTag:r="latest",blockNumber:o}){let n=await e.request({method:"eth_getTransactionCount",params:[t,typeof o==="bigint"?ye(o):r]},{dedupe:Boolean(o)});return wr(n)}jr();We();function a1(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),o=typeof e.blobs[0]==="string"?e.blobs.map((i)=>Lr(i)):e.blobs,n=[];for(let i of o)n.push(Uint8Array.from(t.blobToKzgCommitment(i)));return r==="bytes"?n:n.map((i)=>ht(i))}jr();We();function c1(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),o=typeof e.blobs[0]==="string"?e.blobs.map((s)=>Lr(s)):e.blobs,n=typeof e.commitments[0]==="string"?e.commitments.map((s)=>Lr(s)):e.commitments,i=[];for(let s=0;s<o.length;s++){let a=o[s],c=n[s];i.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map((s)=>ht(s))}We();ig();var u1=gs;jr();We();function GG(e,t){let r=t||"hex",o=u1(sr(e,{strict:!1})?fo(e):e);if(r==="bytes")return o;return Qr(o)}function VG(e){let{commitment:t,version:r=1}=e,o=e.to??(typeof t==="string"?"hex":"bytes"),n=GG(t,"bytes");return n.set([r],0),o==="bytes"?n:ht(n)}function ZG(e){let{commitments:t,version:r}=e,o=e.to??(typeof t[0]==="string"?"hex":"bytes"),n=[];for(let i of t)n.push(VG({commitment:i,to:o,version:r}));return n}var WG=32,KG=4096,JG=131072,Q2=761855;ot();class X2 extends F{constructor({maxSize:e,size:t}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${t} bytes`],name:"BlobSizeTooLargeError"})}}class eO extends F{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}mw();po();jr();We();function YG(e){let t=e.to??(typeof e.data==="string"?"hex":"bytes"),r=typeof e.data==="string"?Lr(e.data):e.data,o=at(r);if(!o)throw new eO;if(o>Q2)throw new X2({maxSize:Q2,size:o});let n=[],i=!0,s=0;while(i){let a=Wd(new Uint8Array(JG)),c=0;while(c<KG){let u=r.slice(s,s+(WG-1));if(a.pushByte(0),a.pushBytes(u),u.length<31){a.pushByte(128),i=!1;break}c++,s+=31}n.push(a)}return t==="bytes"?n.map((a)=>a.bytes):n.map((a)=>ht(a.bytes))}function QG(e){let{data:t,kzg:r,to:o}=e,n=e.blobs??YG({data:t,to:o}),i=e.commitments??a1({blobs:n,kzg:r,to:o}),s=e.proofs??c1({blobs:n,commitments:i,kzg:r,to:o}),a=[];for(let c=0;c<n.length;c++)a.push({blob:n[c],commitment:i[c],proof:s[c]});return a}vg();Du();Cs();function XG(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u"){if(typeof e.accessList<"u")return"eip2930";return"legacy"}throw new YR({transaction:e})}Bu();Cs();Gg();function e7(e,{docsPath:t,...r}){let o=(()=>{let n=Xa(e,r);if(n instanceof Qo)return e;return n})();return new QR(o,{docsPath:t,...r})}Np();Du();gn();async function jp(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return wr(t)}async function l1(e,t){let{account:r=e.account,accessList:o,authorizationList:n,chain:i=e.chain,blobVersionedHashes:s,blobs:a,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:y,nonceManager:x,to:S,type:v,value:E,...w}=t,_=await(async()=>{if(!r)return y;if(!x)return y;if(typeof y<"u")return y;let z=Ft(r),B=i?i.id:await pe(e,jp,"getChainId")({});return await x.consume({address:z.address,chainId:B,client:e})})();xo(t);let T=i?.formatters?.transactionRequest?.format,O=(T||Ci)({...ec(w,{format:T}),account:r?Ft(r):void 0,accessList:o,authorizationList:n,blobs:a,blobVersionedHashes:s,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:_,to:S,type:v,value:E},"fillTransaction");try{let z=await e.request({method:"eth_fillTransaction",params:[O]}),k=(i?.formatters?.transaction?.format||Up)(z.tx);if(delete k.blockHash,delete k.blockNumber,delete k.r,delete k.s,delete k.transactionIndex,delete k.v,delete k.yParity,k.data=k.input,k.gas)k.gas=t.gas??k.gas;if(k.gasPrice)k.gasPrice=t.gasPrice??k.gasPrice;if(k.maxFeePerBlobGas)k.maxFeePerBlobGas=t.maxFeePerBlobGas??k.maxFeePerBlobGas;if(k.maxFeePerGas)k.maxFeePerGas=t.maxFeePerGas??k.maxFeePerGas;if(k.maxPriorityFeePerGas)k.maxPriorityFeePerGas=t.maxPriorityFeePerGas??k.maxPriorityFeePerGas;if(typeof k.nonce<"u")k.nonce=t.nonce??k.nonce;let G=await(async()=>{if(typeof i?.fees?.baseFeeMultiplier==="function"){let H=await pe(e,Tr,"getBlock")({});return i.fees.baseFeeMultiplier({block:H,client:e,request:t})}return i?.fees?.baseFeeMultiplier??1.2})();if(G<1)throw new Qg;let ue=10**(G.toString().split(".")[1]?.length??0),W=(H)=>H*BigInt(Math.ceil(G*ue))/BigInt(ue);if(!k.feePayerSignature){if(k.maxFeePerGas&&!t.maxFeePerGas)k.maxFeePerGas=W(k.maxFeePerGas);if(k.gasPrice&&!t.gasPrice)k.gasPrice=W(k.gasPrice)}return{raw:z.raw,transaction:{from:O.from,...k},...z.capabilities?{capabilities:z.capabilities}:{}}}catch(z){throw e7(z,{...t,chain:e.chain})}}var Uye=["blobVersionedHashes","chainId","fees","gas","nonce","type"],t7=new Map,tO=new Es(128);async function d1(e,t){let r=t;r.account??=e.account,r.parameters??=Uye;let{account:o,chain:n=e.chain,nonceManager:i,parameters:s}=r,a=(()=>{if(typeof n?.prepareTransactionRequest==="function")return{fn:n.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(n?.prepareTransactionRequest))return{fn:n.prepareTransactionRequest[0],runAt:n.prepareTransactionRequest[1].runAt};return})(),c;async function u(){if(c)return c;if(typeof r.chainId<"u")return r.chainId;if(n)return n.id;return c=await pe(e,jp,"getChainId")({}),c}let d=o?Ft(o):o,p=r.nonce;if(s.includes("nonce")&&typeof p>"u"&&d&&i){let _=await u();p=await i.consume({address:d.address,chainId:_,client:e})}if(a?.fn&&a.runAt?.includes("beforeFillTransaction"))r=await a.fn({...r,chain:n},{phase:"beforeFillTransaction"}),p??=r.nonce;let h=(()=>{if((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&r.kzg&&r.blobs)return!1;if(tO.get(e.uid)===!1)return!1;if(!["fees","gas"].some((T)=>s.includes(T)))return!1;if(s.includes("chainId")&&typeof r.chainId!=="number")return!0;if(s.includes("nonce")&&typeof p!=="number")return!0;if(s.includes("fees")&&typeof r.gasPrice!=="bigint"&&(typeof r.maxFeePerGas!=="bigint"||typeof r.maxPriorityFeePerGas!=="bigint"))return!0;if(s.includes("gas")&&typeof r.gas!=="bigint")return!0;return!1})()?await pe(e,l1,"fillTransaction")({...r,nonce:p}).then((_)=>{let{chainId:T,from:P,gas:O,gasPrice:z,nonce:B,maxFeePerBlobGas:k,maxFeePerGas:G,maxPriorityFeePerGas:V,type:ue,...W}=_.transaction;return tO.set(e.uid,!0),{...r,...P?{from:P}:{},...ue&&!r.type?{type:ue}:{},...typeof T<"u"?{chainId:T}:{},...typeof O<"u"?{gas:O}:{},...typeof z<"u"?{gasPrice:z}:{},...typeof B<"u"?{nonce:B}:{},...typeof k<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerBlobGas:k}:{},...typeof G<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerGas:G}:{},...typeof V<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxPriorityFeePerGas:V}:{},..."nonceKey"in W&&typeof W.nonceKey<"u"?{nonceKey:W.nonceKey}:{},..."keyAuthorization"in W&&typeof W.keyAuthorization<"u"&&W.keyAuthorization!==null&&!("keyAuthorization"in r)?{keyAuthorization:W.keyAuthorization}:{},..."feePayerSignature"in W&&typeof W.feePayerSignature<"u"&&W.feePayerSignature!==null?{feePayerSignature:W.feePayerSignature}:{},..."feeToken"in W&&typeof W.feeToken<"u"&&W.feeToken!==null&&!("feeToken"in r)?{feeToken:W.feeToken}:{},..._.capabilities?{_capabilities:_.capabilities}:{}}}).catch((_)=>{let T=_;if(T.name!=="TransactionExecutionError")return r;if(T.walk?.((z)=>z.name==="ExecutionRevertedError"))throw _;if(T.walk?.((z)=>{let B=z;return B.name==="MethodNotFoundRpcError"||B.name==="MethodNotSupportedRpcError"||B.message?.includes("eth_fillTransaction is not available")}))tO.set(e.uid,!1);return r}):r;p??=h.nonce,r={...h,...d?{from:d?.address}:{},...typeof p<"u"?{nonce:p}:{}};let{blobs:y,gas:x,kzg:S,type:v}=r;if(a?.fn&&a.runAt?.includes("beforeFillParameters"))r=await a.fn({...r,chain:n},{phase:"beforeFillParameters"});let E;async function w(){if(E)return E;return E=await pe(e,Tr,"getBlock")({blockTag:"latest"}),E}if(s.includes("nonce")&&typeof p>"u"&&d&&!i)r.nonce=await pe(e,s1,"getTransactionCount")({address:d.address,blockTag:"pending"});if((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&y&&S){let _=a1({blobs:y,kzg:S});if(s.includes("blobVersionedHashes")){let T=ZG({commitments:_,to:"hex"});r.blobVersionedHashes=T}if(s.includes("sidecars")){let T=c1({blobs:y,commitments:_,kzg:S}),P=QG({blobs:y,commitments:_,proofs:T,to:"hex"});r.sidecars=P}}if(s.includes("chainId"))r.chainId=await u();if((s.includes("fees")||s.includes("type"))&&typeof v>"u")try{r.type=XG(r)}catch{let _=t7.get(e.uid);if(typeof _>"u")_=typeof(await w())?.baseFeePerGas==="bigint",t7.set(e.uid,_);r.type=_?"eip1559":"legacy"}if(s.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){let _=await w(),{maxFeePerGas:T,maxPriorityFeePerGas:P}=await i1(e,{block:_,chain:n,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<P)throw new K2({maxPriorityFeePerGas:P});r.maxPriorityFeePerGas=P,r.maxFeePerGas=T}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new ju;if(typeof r.gasPrice>"u"){let _=await w(),{gasPrice:T}=await i1(e,{block:_,chain:n,request:r,type:"legacy"});r.gasPrice=T}}if(s.includes("gas")&&typeof x>"u")r.gas=await pe(e,Fp,"estimateGas")({...r,account:d,prepare:d?.type==="local"?[]:["blobVersionedHashes"]});if(a?.fn&&a.runAt?.includes("afterFillParameters"))r=await a.fn({...r,chain:n},{phase:"afterFillParameters"});return xo(r),delete r.parameters,r}async function Fp(e,t){let{account:r=e.account,prepare:o=!0}=t,n=r?Ft(r):void 0,i=(()=>{if(Array.isArray(o))return o;if(n?.type!=="local")return["blobVersionedHashes"];return})();try{let s=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await n1({authorization:t.authorizationList[0]}).catch(()=>{throw new F("`to` is required. Could not infer from `authorizationList`")});return})(),{accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:d,blockNumber:p,blockTag:m,data:h,gas:y,gasPrice:x,maxFeePerBlobGas:S,maxFeePerGas:v,maxPriorityFeePerGas:E,nonce:w,value:_,stateOverride:T,...P}=o?await d1(e,{...t,parameters:i,to:s}):t;if(y&&t.gas!==y)return y;let z=(typeof p==="bigint"?ye(p):void 0)||m,B=Mp(T);xo(t);let k=e.chain?.formatters?.transactionRequest?.format,V=(k||Ci)({...ec(P,{format:k}),account:n,accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:d,data:h,gasPrice:x,maxFeePerBlobGas:S,maxFeePerGas:v,maxPriorityFeePerGas:E,nonce:w,to:s,value:_},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:B?[V,z??e.experimental_blockTag??"latest",B]:z?[V,z]:[V]}))}catch(s){throw FG(s,{...t,account:n,chain:e.chain})}}async function r7(e,t){let{abi:r,address:o,args:n,functionName:i,dataSuffix:s=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=Kt({abi:r,args:n,functionName:i});try{return await pe(e,Fp,"estimateGas")({data:`${c}${s?s.replace("0x",""):""}`,to:o,...a})}catch(u){let d=a.account?Ft(a.account):void 0;throw Yo(u,{abi:r,address:o,args:n,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:d?.address})}}Pi();Os();ho();We();Uu();async function n7(e,{address:t,blockNumber:r,blockTag:o=e.experimental_blockTag??"latest"}){if(e.batch?.multicall&&e.chain?.contracts?.multicall3){let s=e.chain.contracts.multicall3.address,a=Kt({abi:qo,functionName:"getEthBalance",args:[t]}),{data:c}=await pe(e,vo,"call")({to:s,data:a,blockNumber:r,blockTag:o});return Xr({abi:qo,functionName:"getEthBalance",args:[t],data:c||"0x"})}let n=typeof r==="bigint"?ye(r):void 0,i=await e.request({method:"eth_getBalance",params:[t,n||o]});return BigInt(i)}async function o7(e){let t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}var Lye=new Map,jye=new Map;function i7(e){let t=(n,i)=>({clear:()=>i.delete(n),get:()=>i.get(n),set:(s)=>i.set(n,s)}),r=t(e,Lye),o=t(e,jye);return{clear:()=>{r.clear(),o.clear()},promise:r,response:o}}async function s7(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){let o=i7(t),n=o.response.get();if(n&&r>0){if(Date.now()-n.created.getTime()<r)return n.data}let i=o.promise.get();if(!i)i=e(),o.promise.set(i);try{let s=await i;return o.response.set({created:new Date,data:s}),s}finally{o.promise.clear()}}var Fye=(e)=>`blockNumber.${e}`;async function Ni(e,{cacheTime:t=e.cacheTime}={}){let r=await s7(()=>e.request({method:"eth_blockNumber"}),{cacheKey:Fye(e.uid),cacheTime:t});return BigInt(r)}gn();We();async function a7(e,{blockHash:t,blockNumber:r,blockTag:o="latest"}={}){let n=r!==void 0?ye(r):void 0,i;if(t)i=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0});else i=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[n||o]},{dedupe:Boolean(n)});return wr(i)}We();async function Fu(e,{address:t,blockNumber:r,blockTag:o="latest"}){let n=r!==void 0?ye(r):void 0,i=await e.request({method:"eth_getCode",params:[t,n||o]},{dedupe:Boolean(n)});if(i==="0x")return;return i}Za();Bp();jr();function Er(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}Zo();Ig();ir();gR();po();Ig();Sg();ws();var c7="/docs/contract/decodeEventLog";function qu(e){let{abi:t,data:r,strict:o,topics:n}=e,i=o??!0,[s,...a]=n;if(!s)throw new eR({docsPath:c7});let c=t.find((v)=>v.type==="event"&&s===Va(hr(v)));if(!(c&&("name"in c))||c.type!=="event")throw new tR(s,{docsPath:c7});let{name:u,inputs:d}=c,p=d?.some((v)=>!(("name"in v)&&v.name)),m=p?[]:{},h=d.map((v,E)=>[v,E]).filter(([v])=>("indexed"in v)&&v.indexed),y=[];for(let v=0;v<h.length;v++){let[E,w]=h[v],_=a[v];if(!_){if(i)throw new vu({abiItem:c,param:E});y.push([E,w]);continue}m[p?w:E.name||w]=qye({param:E,value:_})}let x=d.filter((v)=>!(("indexed"in v)&&v.indexed)),S=i?x:[...y.map(([v])=>v),...x];if(S.length>0){if(r&&r!=="0x")try{let v=ks(S,r);if(v){let E=0;if(!i)for(let[w,_]of y)m[p?_:w.name||_]=v[E++];if(p){for(let w=0;w<d.length;w++)if(m[w]===void 0&&E<v.length)m[w]=v[E++]}else for(let w=0;w<x.length;w++)m[x[w].name]=v[E++]}}catch(v){if(i){if(v instanceof mg||v instanceof _g)throw new qa({abiItem:c,data:r,params:S,size:at(r)});throw v}}else if(i)throw new qa({abiItem:c,data:"0x",params:S,size:0})}return{eventName:u,args:Object.values(m).length>0?m:void 0}}function qye({param:e,value:t}){if(e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))return t;return(ks([e],t)||[])[0]}function qp(e){let{abi:t,args:r,logs:o,strict:n=!0}=e,i=(()=>{if(!e.eventName)return;if(Array.isArray(e.eventName))return e.eventName;return[e.eventName]})(),s=t.filter((a)=>a.type==="event").map((a)=>({abi:a,selector:Va(a)}));return o.map((a)=>{let c=typeof a.blockNumber==="string"?Er(a):a,u=s.filter((m)=>c.topics[0]===m.selector);if(u.length===0)return null;let d,p;for(let m of u)try{d=qu({...c,abi:[m.abi],strict:!0}),p=m;break}catch{}if(!d&&!n){p=u[0];try{d=qu({data:c.data,topics:c.topics,abi:[p.abi],strict:!1})}catch{let m=p.abi.inputs?.some((h)=>!(("name"in h)&&h.name));return{...c,args:m?[]:{},eventName:p.abi.name}}}if(!d||!p)return null;if(i&&!i.includes(d.eventName))return null;if(!Hye({args:d.args,inputs:p.abi.inputs,matchArgs:r}))return null;return{...d,...c}}).filter(Boolean)}function Hye(e){let{args:t,inputs:r,matchArgs:o}=e;if(!o)return!0;if(!t)return!1;function n(i,s,a){try{if(i.type==="address")return Xo(s,a);if(i.type==="string"||i.type==="bytes")return zt(fo(s))===a;return s===a}catch{return!1}}if(Array.isArray(t)&&Array.isArray(o))return o.every((i,s)=>{if(i===null||i===void 0)return!0;let a=r[s];if(!a)return!1;return(Array.isArray(i)?i:[i]).some((u)=>n(a,u,t[s]))});if(typeof t==="object"&&!Array.isArray(t)&&typeof o==="object"&&!Array.isArray(o))return Object.entries(o).every(([i,s])=>{if(s===null||s===void 0)return!0;let a=r.find((u)=>u.name===i);if(!a)return!1;return(Array.isArray(s)?s:[s]).some((u)=>n(a,u,t[i]))});return!1}We();async function Hp(e,{address:t,blockHash:r,fromBlock:o,toBlock:n,event:i,events:s,args:a,strict:c}={}){let u=c??!1,d=s??(i?[i]:void 0),p=[];if(d){if(p=[d.flatMap((x)=>zi({abi:[x],eventName:x.name,args:s?void 0:a}))],i)p=p[0]}let m;if(r)m=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,blockHash:r}]});else m=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,fromBlock:typeof o==="bigint"?ye(o):o,toBlock:typeof n==="bigint"?ye(n):n}]});let h=m.map((y)=>Er(y));if(!d)return h;return qp({abi:d,args:a,logs:h,strict:u})}async function p1(e,t){let{abi:r,address:o,args:n,blockHash:i,eventName:s,fromBlock:a,toBlock:c,strict:u}=t,d=s?Ln({abi:r,name:s}):void 0,p=!d?r.filter((m)=>m.type==="event"):void 0;return pe(e,Hp,"getLogs")({address:o,args:n,blockHash:i,event:d,events:p,fromBlock:a,toBlock:c,strict:u})}Tu();po();Iu();async function u7(e,{address:t,blockNumber:r,blockTag:o="latest"}){let n=await Fu(e,{address:t,...r!==void 0?{blockNumber:r}:{blockTag:o}});if(!n)return;if(at(n)!==23)return;if(!n.startsWith("0xef0100"))return;return Eu(mo(n,3,23))}ot();class rO extends F{constructor({address:e}){super(`No EIP-712 domain found on contract "${e}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${e}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function l7(e,t){let{address:r,factory:o,factoryData:n}=t;try{let[i,s,a,c,u,d,p]=await pe(e,dr,"readContract")({abi:Gye,address:r,functionName:"eip712Domain",factory:o,factoryData:n});return{domain:{name:s,version:a,chainId:Number(c),verifyingContract:u,salt:d},extensions:p,fields:i}}catch(i){let s=i;if(s.name==="ContractFunctionExecutionError"&&s.cause.name==="ContractFunctionZeroDataError")throw new rO({address:r});throw s}}var Gye=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];We();function d7(e){return{baseFeePerGas:e.baseFeePerGas.map((t)=>BigInt(t)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:e.reward?.map((t)=>t.map((r)=>BigInt(r)))}}async function p7(e,{blockCount:t,blockNumber:r,blockTag:o="latest",rewardPercentiles:n}){let i=typeof r==="bigint"?ye(r):void 0,s=await e.request({method:"eth_feeHistory",params:[ye(t),i||o,n]},{dedupe:Boolean(i)});return d7(s)}async function ic(e,{filter:t}){let r="strict"in t&&t.strict,o=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof o[0]==="string")return o;let n=o.map((i)=>Er(i));if(!("abi"in t)||!t.abi)return n;return qp({abi:t.abi,logs:n,strict:r})}async function f7(e,{filter:t}){let r=t.strict??!1,n=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map((i)=>Er(i));if(!t.abi)return n;return qp({abi:t.abi,logs:n,strict:r})}We();gn();function Vye(e){return e.map((t)=>({...t,value:BigInt(t.value)}))}function m7(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?wr(e.nonce):void 0,storageProof:e.storageProof?Vye(e.storageProof):void 0}}async function h7(e,{address:t,blockNumber:r,blockTag:o,storageKeys:n}){let i=o??"latest",s=r!==void 0?ye(r):void 0,a=await e.request({method:"eth_getProof",params:[t,n,s||i]});return m7(a)}We();async function g7(e,{address:t,blockNumber:r,blockTag:o="latest",slot:n}){let i=r!==void 0?ye(r):void 0;return await e.request({method:"eth_getStorageAt",params:[t,n,i||o]})}Cs();We();async function Gp(e,{blockHash:t,blockNumber:r,blockTag:o,hash:n,index:i,sender:s,nonce:a}){let c=o||"latest",u=r!==void 0?ye(r):void 0,d=null;if(n)d=await e.request({method:"eth_getTransactionByHash",params:[n]},{dedupe:!0});else if(t)d=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,ye(i)]},{dedupe:!0});else if((u||c)&&typeof i==="number")d=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[u||c,ye(i)]},{dedupe:Boolean(u)});else if(s&&typeof a==="number")d=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[s,ye(a)]},{dedupe:!0});if(!d)throw new Pg({blockHash:t,blockNumber:r,blockTag:c,hash:n,index:i});return(e.chain?.formatters?.transaction?.format||Up)(d,"getTransaction")}async function y7(e,{hash:t,transactionReceipt:r}){let[o,n]=await Promise.all([pe(e,Ni,"getBlockNumber")({}),t?pe(e,Gp,"getTransaction")({hash:t}):void 0]),i=r?.blockNumber||n?.blockNumber;if(!i)return 0n;return o-i+1n}Cs();gn();var Zye={"0x0":"reverted","0x1":"success"};function f1(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map((o)=>Er(o)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?wr(e.transactionIndex):null,status:e.status?Zye[e.status]:null,type:e.type?J2[e.type]||e.type:null};if(e.blobGasPrice)r.blobGasPrice=BigInt(e.blobGasPrice);if(e.blobGasUsed)r.blobGasUsed=BigInt(e.blobGasUsed);return r}async function Vp(e,{hash:t}){let r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new kg({hash:t});return(e.chain?.formatters?.transactionReceipt?.format||f1)(r,"getTransactionReceipt")}Pi();ir();ot();Wa();Os();ho();Pu();async function b7(e,t){let{account:r,authorizationList:o,allowFailure:n=!0,blockNumber:i,blockOverrides:s,blockTag:a,stateOverride:c}=t,u=t.contracts,{batchSize:d=t.batchSize??1024,deployless:p=t.deployless??!1}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},m=(()=>{if(t.multicallAddress)return t.multicallAddress;if(p)return null;if(e.chain)return go({blockNumber:i,chain:e.chain,contract:"multicall3"});throw Error("client chain not configured. multicallAddress is required.")})(),h=[[]],y=0,x=0;for(let E=0;E<u.length;E++){let{abi:w,address:_,args:T,functionName:P}=u[E];try{let O=Kt({abi:w,args:T,functionName:P});if(x+=(O.length-2)/2,d>0&&x>d&&h[y].length>0)y++,x=(O.length-2)/2,h[y]=[];h[y]=[...h[y],{allowFailure:!0,callData:O,target:_}]}catch(O){let z=Yo(O,{abi:w,address:_,args:T,docsPath:"/docs/contract/multicall",functionName:P,sender:r});if(!n)throw z;h[y]=[...h[y],{allowFailure:!0,callData:"0x",target:_}]}}let S=await Promise.allSettled(h.map((E)=>pe(e,dr,"readContract")({...m===null?{code:zp}:{address:m},abi:qo,account:r,args:[E],authorizationList:o,blockNumber:i,blockOverrides:s,blockTag:a,functionName:"aggregate3",stateOverride:c}))),v=[];for(let E=0;E<S.length;E++){let w=S[E];if(w.status==="rejected"){if(!n)throw w.reason;for(let T=0;T<h[E].length;T++)v.push({status:"failure",error:w.reason,result:void 0});continue}let _=w.value;for(let T=0;T<_.length;T++){let{returnData:P,success:O}=_[T],{callData:z}=h[E][T],{abi:B,address:k,functionName:G,args:V}=u[v.length];try{if(z==="0x")throw new Ho;if(!O)throw new zs({data:P});let ue=Xr({abi:B,args:V,data:P,functionName:G});v.push(n?{result:ue,status:"success"}:ue)}catch(ue){let W=Yo(ue,{abi:B,address:k,args:V,docsPath:"/docs/contract/multicall",functionName:G});if(!n)throw W;v.push({error:W,result:void 0,status:"failure"})}}}if(v.length!==u.length)throw new F("multicall results mismatch");return v}_2();ir();Wa();Bu();Os();ho();We();Gg();Np();Zw();Du();async function ey(e,t){let{blockNumber:r,blockTag:o=e.experimental_blockTag??"latest",blocks:n,returnFullTransactions:i,traceTransfers:s,validation:a}=t;try{let c=[];for(let m of n){let h=m.blockOverrides?Fw(m.blockOverrides):void 0,y=m.calls.map((S)=>{let v=S,E=v.account?Ft(v.account):void 0,w=v.abi?Kt(v):v.data,_={...v,account:E,data:v.dataSuffix?Fr([w||"0x",v.dataSuffix]):w,from:v.from??E?.address};return xo(_),Ci(_)}),x=m.stateOverrides?Mp(m.stateOverrides):void 0;c.push({blockOverrides:h,calls:y,stateOverrides:x})}let d=(typeof r==="bigint"?ye(r):void 0)||o;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:s,validation:a},d]})).map((m,h)=>({...o1(m),calls:m.calls.map((y,x)=>{let{abi:S,args:v,functionName:E,to:w}=n[h].calls[x],_=y.error?.data??y.returnData,T=BigInt(y.gasUsed),P=y.logs?.map((k)=>Er(k)),O=y.status==="0x1"?"success":"failure",z=S&&O==="success"&&_!=="0x"?Xr({abi:S,data:_,functionName:E}):null,B=(()=>{if(O==="success")return;let k;if(_==="0x")k=new Ho;else if(_)k=new zs({data:_});if(!k)return;return Yo(k,{abi:S??[],address:w??"0x",args:v,functionName:E??"<unknown>"})})();return{data:_,gasUsed:T,logs:P,status:O,...O==="success"?{result:z}:{error:B}}})}))}catch(c){let u=c,d=Xa(u,{});if(d instanceof Qo)throw u;throw d}}ep();jn();pw();Ja();Sr();function Hu(e,t={}){let{as:r=typeof e==="string"?"Hex":"Bytes"}=t,o=Zd(jH(e));if(r==="Bytes")return o;return ar(o)}Sr();Ja();class oO extends Map{constructor(e){super();Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);if(super.has(e)&&t!==void 0)this.delete(e),super.set(e,t);return t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let r=this.keys().next().value;if(r)this.delete(r)}return this}}var Wye={checksum:new oO(8192)},m1=Wye.checksum;jn();Ja();jn();Sr();function x7(e,t={}){let{compressed:r}=t,{prefix:o,x:n,y:i}=e;if(r===!1||typeof n==="bigint"&&typeof i==="bigint"){if(o!==4)throw new iO({prefix:o,cause:new T7});return}if(r===!0||typeof n==="bigint"&&typeof i>"u"){if(o!==3&&o!==2)throw new iO({prefix:o,cause:new S7});return}throw new w7({publicKey:e})}function v7(e){let t=(()=>{if(Ng(e))return _7(e);if(ZH(e))return Jye(e);let{prefix:r,x:o,y:n}=e;if(typeof o==="bigint"&&typeof n==="bigint")return{prefix:r??4,x:o,y:n};return{prefix:r,x:o}})();return x7(t),t}function Jye(e){return _7(ar(e))}function _7(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new E7({publicKey:e});if(e.length===130){let o=BigInt(Wt(e,0,32)),n=BigInt(Wt(e,32,64));return{prefix:4,x:o,y:n}}if(e.length===132){let o=Number(Wt(e,0,1)),n=BigInt(Wt(e,1,33)),i=BigInt(Wt(e,33,65));return{prefix:o,x:n,y:i}}let t=Number(Wt(e,0,1)),r=BigInt(Wt(e,1,33));return{prefix:t,x:r}}function sO(e,t={}){x7(e);let{prefix:r,x:o,y:n}=e,{includePrefix:i=!0}=t;return Jt(i?pt(r,{size:1}):"0x",pt(o,{size:32}),typeof n==="bigint"?pt(n,{size:32}):"0x")}class w7 extends xe{constructor({publicKey:e}){super(`Value \`${Ya(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class iO extends xe{constructor({prefix:e,cause:t}){super(`Prefix "${e}" is invalid.`,{cause:t});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class S7 extends xe{constructor(){super("Prefix must be 2 or 3 for compressed public keys.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class T7 extends xe{constructor(){super("Prefix must be 4 for uncompressed public keys.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}class E7 extends xe{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Zt(Op(e))} bytes.`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}var Yye=/^0x[a-fA-F0-9]{40}$/;function Gu(e,t={}){let{strict:r=!0}=t;if(!Yye.test(e))throw new aO({address:e,cause:new k7});if(r){if(e.toLowerCase()===e)return;if(h1(e)!==e)throw new aO({address:e,cause:new A7})}}function h1(e){if(m1.has(e))return m1.get(e);Gu(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=Hu(FH(t),{as:"Bytes"}),o=t.split("");for(let i=0;i<40;i+=2){if(r[i>>1]>>4>=8&&o[i])o[i]=o[i].toUpperCase();if((r[i>>1]&15)>=8&&o[i+1])o[i+1]=o[i+1].toUpperCase()}let n=`0x${o.join("")}`;return m1.set(e,n),n}function Qye(e,t={}){let{checksum:r=!1}=t;if(Gu(e),r)return h1(e);return e}function P7(e,t={}){let r=Hu(`0x${sO(e).slice(4)}`).substring(26);return Qye(`0x${r}`,t)}function g1(e,t={}){let{strict:r=!0}=t??{};try{return Gu(e,{strict:r}),!0}catch{return!1}}class aO extends xe{constructor({address:e,cause:t}){super(`Address "${e}" is invalid.`,{cause:t});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class k7 extends xe{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class A7 extends xe{constructor(){super("Address does not match its checksum counterpart.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}jn();function x1(e){let t=!0,r="",o=0,n="",i=!1;for(let s=0;s<e.length;s++){let a=e[s];if(["(",")",","].includes(a))t=!0;if(a==="(")o++;if(a===")")o--;if(!t)continue;if(o===0){if(a===" "&&["event","function","error",""].includes(n))n="";else if(n+=a,a===")"){i=!0;break}continue}if(a===" "){if(e[s-1]!==","&&r!==","&&r!==",(")r="",t=!1;continue}n+=a,r+=a}if(!i)throw new xe("Unable to normalize signature.");return n}function b1(e,t){let r=typeof e,o=t.type;switch(o){case"address":return g1(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:{if(o==="tuple"&&"components"in t)return Object.values(t.components).every((n,i)=>b1(Object.values(e)[i],n));if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(o))return r==="number"||r==="bigint";if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(o))return r==="string"||e instanceof Uint8Array;if(/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(o))return Array.isArray(e)&&e.every((n)=>b1(n,{...t,type:o.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}}function cO(e,t,r){for(let o in e){let n=e[o],i=t[o];if(n.type==="tuple"&&i.type==="tuple"&&"components"in n&&"components"in i)return cO(n.components,i.components,r[o]);let s=[n.type,i.type];if((()=>{if(s.includes("address")&&s.includes("bytes20"))return!0;if(s.includes("address")&&s.includes("string"))return g1(r[o],{strict:!1});if(s.includes("address")&&s.includes("bytes"))return g1(r[o],{strict:!1});return!1})())return s}return}function v1(e,t={}){let{prepare:r=!0}=t,o=(()=>{if(Array.isArray(e))return Ew(e);if(typeof e==="string")return Ew(e);return e})();return{...o,...r?{hash:Zp(o)}:{}}}function ty(e,t,r){let{args:o=[],prepare:n=!0}=r??{},i=Ng(t,{strict:!1}),s=e.filter((u)=>{if(i){if(u.type==="function"||u.type==="error")return uO(u)===Wt(t,0,4);if(u.type==="event")return Zp(u)===t;return!1}return"name"in u&&u.name===t});if(s.length===0)throw new Vu({name:t});if(s.length===1)return{...s[0],...n?{hash:Zp(s[0])}:{}};let a;for(let u of s){if(!("inputs"in u))continue;if(!o||o.length===0){if(!u.inputs||u.inputs.length===0)return{...u,...n?{hash:Zp(u)}:{}};continue}if(!u.inputs)continue;if(u.inputs.length===0)continue;if(u.inputs.length!==o.length)continue;if(o.every((p,m)=>{let h="inputs"in u&&u.inputs[m];if(!h)return!1;return b1(p,h)})){if(a&&"inputs"in a&&a.inputs){let p=cO(u.inputs,a.inputs,o);if(p)throw new $7({abiItem:u,type:p[0]},{abiItem:a,type:p[1]})}a=u}}let c=(()=>{if(a)return a;let[u,...d]=s;return{...u,overloads:d}})();if(!c)throw new Vu({name:t});return{...c,...n?{hash:Zp(c)}:{}}}function uO(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,o]=e;return ty(r,o)}return e[0]})();return Wt(Zp(t),0,4)}function ebe(...e){let t=(()=>{if(Array.isArray(e[0])){let[o,n]=e;return ty(o,n)}return e[0]})(),r=(()=>{if(typeof t==="string")return t;return $s(t)})();return x1(r)}function Zp(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,o]=e;return ty(r,o)}return e[0]})();if(typeof t!=="string"&&"hash"in t&&t.hash)return t.hash;return Hu(Cp(ebe(t)))}class $7 extends xe{constructor(e,t){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${x1($s(e.abiItem))}\`, and`,`\`${t.type}\` in \`${x1($s(t.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class Vu extends xe{constructor({name:e,data:t,type:r="item"}){let o=(()=>{if(e)return` with name "${e}"`;if(t)return` with data "${t}"`;return""})();super(`ABI ${r}${o} not found.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}ep();Ja();jn();Sr();Ja();jn();Sr();var O7=/^(.*)\[([0-9]*)\]$/,C7=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,_1=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,kGe=2n**(8n-1n)-1n,AGe=2n**(16n-1n)-1n,$Ge=2n**(24n-1n)-1n,RGe=2n**(32n-1n)-1n,OGe=2n**(40n-1n)-1n,CGe=2n**(48n-1n)-1n,zGe=2n**(56n-1n)-1n,NGe=2n**(64n-1n)-1n,MGe=2n**(72n-1n)-1n,BGe=2n**(80n-1n)-1n,DGe=2n**(88n-1n)-1n,UGe=2n**(96n-1n)-1n,LGe=2n**(104n-1n)-1n,jGe=2n**(112n-1n)-1n,FGe=2n**(120n-1n)-1n,qGe=2n**(128n-1n)-1n,HGe=2n**(136n-1n)-1n,GGe=2n**(144n-1n)-1n,VGe=2n**(152n-1n)-1n,ZGe=2n**(160n-1n)-1n,WGe=2n**(168n-1n)-1n,KGe=2n**(176n-1n)-1n,JGe=2n**(184n-1n)-1n,YGe=2n**(192n-1n)-1n,QGe=2n**(200n-1n)-1n,XGe=2n**(208n-1n)-1n,e7e=2n**(216n-1n)-1n,t7e=2n**(224n-1n)-1n,r7e=2n**(232n-1n)-1n,n7e=2n**(240n-1n)-1n,o7e=2n**(248n-1n)-1n,i7e=2n**(256n-1n)-1n,s7e=-(2n**(8n-1n)),a7e=-(2n**(16n-1n)),c7e=-(2n**(24n-1n)),u7e=-(2n**(32n-1n)),l7e=-(2n**(40n-1n)),d7e=-(2n**(48n-1n)),p7e=-(2n**(56n-1n)),f7e=-(2n**(64n-1n)),m7e=-(2n**(72n-1n)),h7e=-(2n**(80n-1n)),g7e=-(2n**(88n-1n)),y7e=-(2n**(96n-1n)),b7e=-(2n**(104n-1n)),x7e=-(2n**(112n-1n)),v7e=-(2n**(120n-1n)),_7e=-(2n**(128n-1n)),w7e=-(2n**(136n-1n)),S7e=-(2n**(144n-1n)),T7e=-(2n**(152n-1n)),E7e=-(2n**(160n-1n)),I7e=-(2n**(168n-1n)),P7e=-(2n**(176n-1n)),k7e=-(2n**(184n-1n)),A7e=-(2n**(192n-1n)),$7e=-(2n**(200n-1n)),R7e=-(2n**(208n-1n)),O7e=-(2n**(216n-1n)),C7e=-(2n**(224n-1n)),z7e=-(2n**(232n-1n)),N7e=-(2n**(240n-1n)),M7e=-(2n**(248n-1n)),B7e=-(2n**(256n-1n)),D7e=2n**8n-1n,U7e=2n**16n-1n,L7e=2n**24n-1n,j7e=2n**32n-1n,F7e=2n**40n-1n,q7e=2n**48n-1n,H7e=2n**56n-1n,G7e=2n**64n-1n,V7e=2n**72n-1n,Z7e=2n**80n-1n,W7e=2n**88n-1n,K7e=2n**96n-1n,J7e=2n**104n-1n,Y7e=2n**112n-1n,Q7e=2n**120n-1n,X7e=2n**128n-1n,eVe=2n**136n-1n,tVe=2n**144n-1n,rVe=2n**152n-1n,nVe=2n**160n-1n,oVe=2n**168n-1n,iVe=2n**176n-1n,sVe=2n**184n-1n,aVe=2n**192n-1n,cVe=2n**200n-1n,uVe=2n**208n-1n,lVe=2n**216n-1n,dVe=2n**224n-1n,pVe=2n**232n-1n,fVe=2n**240n-1n,mVe=2n**248n-1n,lO=2n**256n-1n;function Zu(e,t,r){let{checksumAddress:o,staticPosition:n}=r,i=fO(t.type);if(i){let[s,a]=i;return rbe(e,{...t,type:a},{checksumAddress:o,length:s,staticPosition:n})}if(t.type==="tuple")return sbe(e,t,{checksumAddress:o,staticPosition:n});if(t.type==="address")return tbe(e,{checksum:o});if(t.type==="bool")return nbe(e);if(t.type.startsWith("bytes"))return obe(e,t,{staticPosition:n});if(t.type.startsWith("uint")||t.type.startsWith("int"))return ibe(e,t);if(t.type==="string")return abe(e,{staticPosition:n});throw new ny(t.type)}var N7=32,dO=32;function tbe(e,t={}){let{checksum:r=!1}=t,o=e.readBytes(32);return[((i)=>r?h1(i):i)(ar(qH(o,-20))),32]}function rbe(e,t,r){let{checksumAddress:o,length:n,staticPosition:i}=r;if(!n){let c=Ri(e.readBytes(dO)),u=i+c,d=u+N7;e.setPosition(u);let p=Ri(e.readBytes(N7)),m=ry(t),h=0,y=[];for(let x=0;x<p;++x){e.setPosition(d+(m?x*32:h));let[S,v]=Zu(e,t,{checksumAddress:o,staticPosition:d});h+=v,y.push(S)}return e.setPosition(i+32),[y,32]}if(ry(t)){let c=Ri(e.readBytes(dO)),u=i+c,d=[];for(let p=0;p<n;++p){e.setPosition(u+p*32);let[m]=Zu(e,t,{checksumAddress:o,staticPosition:u});d.push(m)}return e.setPosition(i+32),[d,32]}let s=0,a=[];for(let c=0;c<n;++c){let[u,d]=Zu(e,t,{checksumAddress:o,staticPosition:i+s});s+=d,a.push(u)}return[a,s]}function nbe(e){return[GH(e.readBytes(32),{size:32}),32]}function obe(e,t,{staticPosition:r}){let[o,n]=t.type.split("bytes");if(!n){let s=Ri(e.readBytes(32));e.setPosition(r+s);let a=Ri(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];let c=e.readBytes(a);return e.setPosition(r+32),[ar(c),32]}return[ar(e.readBytes(Number.parseInt(n,10),32)),32]}function ibe(e,t){let r=t.type.startsWith("int"),o=Number.parseInt(t.type.split("int")[1]||"256",10),n=e.readBytes(32);return[o>48?HH(n,{signed:r}):Ri(n,{signed:r}),32]}function sbe(e,t,r){let{checksumAddress:o,staticPosition:n}=r,i=t.components.length===0||t.components.some(({name:c})=>!c),s=i?[]:{},a=0;if(ry(t)){let c=Ri(e.readBytes(dO)),u=n+c;for(let d=0;d<t.components.length;++d){let p=t.components[d];e.setPosition(u+a);let[m,h]=Zu(e,p,{checksumAddress:o,staticPosition:u});a+=h,s[i?d:p?.name]=m}return e.setPosition(n+32),[s,32]}for(let c=0;c<t.components.length;++c){let u=t.components[c],[d,p]=Zu(e,u,{checksumAddress:o,staticPosition:n});s[i?c:u?.name]=d,a+=p}return[s,a]}function abe(e,{staticPosition:t}){let r=Ri(e.readBytes(32)),o=t+r;e.setPosition(o);let n=Ri(e.readBytes(32));if(n===0)return e.setPosition(t+32),["",32];let i=e.readBytes(n,32),s=VH(g2(i));return e.setPosition(t+32),[s,32]}function M7({checksumAddress:e,parameters:t,values:r}){let o=[];for(let n=0;n<t.length;n++)o.push(pO({checksumAddress:e,parameter:t[n],value:r[n]}));return o}function pO({checksumAddress:e=!1,parameter:t,value:r}){let o=t,n=fO(o.type);if(n){let[i,s]=n;return ube(r,{checksumAddress:e,length:i,parameter:{...o,type:s}})}if(o.type==="tuple")return mbe(r,{checksumAddress:e,parameter:o});if(o.type==="address")return cbe(r,{checksum:e});if(o.type==="bool")return dbe(r);if(o.type.startsWith("uint")||o.type.startsWith("int")){let i=o.type.startsWith("int"),[,,s="256"]=_1.exec(o.type)??[];return pbe(r,{signed:i,size:Number(s)})}if(o.type.startsWith("bytes"))return lbe(r,{type:o.type});if(o.type==="string")return fbe(r);throw new ny(o.type)}function w1(e){let t=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];if(s)t+=32;else t+=Zt(a)}let r=[],o=[],n=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];if(s)r.push(pt(t+n,{size:32})),o.push(a),n+=Zt(a);else r.push(a)}return Jt(...r,...o)}function cbe(e,t){let{checksum:r=!1}=t;return Gu(e,{strict:r}),{dynamic:!1,encoded:Ds(e.toLowerCase())}}function ube(e,t){let{checksumAddress:r,length:o,parameter:n}=t,i=o===null;if(!Array.isArray(e))throw new hO(e);if(!i&&e.length!==o)throw new mO({expectedLength:o,givenLength:e.length,type:`${n.type}[${o}]`});let s=!1,a=[];for(let c=0;c<e.length;c++){let u=pO({checksumAddress:r,parameter:n,value:e[c]});if(u.dynamic)s=!0;a.push(u)}if(i||s){let c=w1(a);if(i){let u=pt(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?Jt(u,c):u}}if(s)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Jt(...a.map(({encoded:c})=>c))}}function lbe(e,{type:t}){let[,r]=t.split("bytes"),o=Zt(e);if(!r){let n=e;if(o%32!==0)n=Oi(n,Math.ceil((e.length-2)/2/32)*32);return{dynamic:!0,encoded:Jt(Ds(pt(o,{size:32})),n)}}if(o!==Number.parseInt(r,10))throw new S1({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:Oi(e)}}function dbe(e){if(typeof e!=="boolean")throw new xe(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Ds(Lw(e))}}function pbe(e,{signed:t,size:r}){if(typeof r==="number"){let o=2n**(BigInt(r)-(t?1n:0n))-1n,n=t?-o-1n:0n;if(e>o||e<n)throw new jw({max:o.toString(),min:n.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:pt(e,{size:32,signed:t})}}function fbe(e){let t=Cp(e),r=Math.ceil(Zt(t)/32),o=[];for(let n=0;n<r;n++)o.push(Oi(Wt(t,n*32,(n+1)*32)));return{dynamic:!0,encoded:Jt(Oi(pt(Zt(t),{size:32})),...o)}}function mbe(e,t){let{checksumAddress:r,parameter:o}=t,n=!1,i=[];for(let s=0;s<o.components.length;s++){let a=o.components[s],c=Array.isArray(e)?s:a.name,u=pO({checksumAddress:r,parameter:a,value:e[c]});if(i.push(u),u.dynamic)n=!0}return{dynamic:n,encoded:n?w1(i):Jt(...i.map(({encoded:s})=>s))}}function fO(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function ry(e){let{type:t}=e;if(t==="string")return!0;if(t==="bytes")return!0;if(t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(ry);let r=fO(e.type);if(r&&ry({...e,type:r[1]}))return!0;return!1}jn();var gbe={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new D7({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new B7({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new gO({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new gO({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();if(this.positionReadCount.set(this.position,e+1),e>0)this.recursiveReadCount++}};function T1(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(gbe);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}class gO extends xe{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class B7 extends xe{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class D7 extends xe{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function Wp(e,t,r={}){let{as:o="Array",checksumAddress:n=!1}=r,i=typeof t==="string"?Rp(t):t,s=T1(i);if(bo(i)===0&&e.length>0)throw new j7;if(bo(i)&&bo(i)<32)throw new L7({data:typeof t==="string"?t:ar(t),parameters:e,size:bo(i)});let a=0,c=o==="Array"?[]:{};for(let u=0;u<e.length;++u){let d=e[u];s.setPosition(a);let[p,m]=Zu(s,d,{checksumAddress:n,staticPosition:0});if(a+=m,o==="Array")c.push(p);else c[d.name??u]=p}return c}function sc(e,t,r){let{checksumAddress:o=!1}=r??{};if(e.length!==t.length)throw new bO({expectedLength:e.length,givenLength:t.length});let n=M7({checksumAddress:o,parameters:e,values:t}),i=w1(n);if(i.length===0)return"0x";return i}function yO(e,t){if(e.length!==t.length)throw new bO({expectedLength:e.length,givenLength:t.length});let r=[];for(let o=0;o<e.length;o++){let n=e[o],i=t[o];r.push(yO.encode(n,i))}return Jt(...r)}(function(e){function t(r,o,n=!1){if(r==="address"){let c=o;return Gu(c),Ds(c.toLowerCase(),n?32:0)}if(r==="string")return Cp(o);if(r==="bytes")return o;if(r==="bool")return Ds(Lw(o),n?32:1);let i=r.match(_1);if(i){let[c,u,d="256"]=i,p=Number.parseInt(d,10)/8;return pt(o,{size:n?32:p,signed:u==="int"})}let s=r.match(C7);if(s){let[c,u]=s;if(Number.parseInt(u,10)!==(o.length-2)/2)throw new S1({expectedSize:Number.parseInt(u,10),value:o});return Oi(o,n?32:0)}let a=r.match(O7);if(a&&Array.isArray(o)){let[c,u]=a,d=[];for(let p=0;p<o.length;p++)d.push(t(u,o[p],!0));if(d.length===0)return"0x";return Jt(...d)}throw new ny(r)}e.encode=t})(yO||(yO={}));function iy(e){if(Array.isArray(e)&&typeof e[0]==="string")return Iw(e);if(typeof e==="string")return Iw(e);return e}class L7 extends xe{constructor({data:e,parameters:t,size:r}){super(`Data size of ${r} bytes is too small for given parameters.`,{metaMessages:[`Params: (${As(t)})`,`Data: ${e} (${r} bytes)`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class j7 extends xe{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.');Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class mO extends xe{constructor({expectedLength:e,givenLength:t,type:r}){super(`Array length mismatch for type \`${r}\`. Expected: \`${e}\`. Given: \`${t}\`.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class S1 extends xe{constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" (bytes${Zt(t)}) does not match expected size (bytes${e}).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class bO extends xe{constructor({expectedLength:e,givenLength:t}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${t}`].join(`
142
142
  `));Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class hO extends xe{constructor(e){super(`Value \`${e}\` is not a valid array.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class ny extends xe{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}Sr();function F7(...e){let[t,r]=(()=>{if(Array.isArray(e[0])){let[i,s]=e;return[ybe(i),s]}return e})(),{bytecode:o,args:n}=r;return Jt(o,t.inputs?.length&&n?.length?sc(t.inputs,n):"0x")}function q7(e){return v1(e)}function ybe(e){let t=e.find((r)=>r.type==="constructor");if(!t)throw new Vu({name:"constructor"});return t}Sr();function G7(...e){let[t,r=[]]=(()=>{if(Array.isArray(e[0])){let[u,d,p]=e;return[H7(u,d,{args:p}),p]}let[a,c]=e;return[a,c]})(),{overloads:o}=t,n=o?H7([t,...o],t.name,{args:r}):t,i=xbe(n),s=r.length>0?sc(n.inputs,r):void 0;return s?Jt(i,s):i}function Wu(e,t={}){return v1(e,t)}function H7(e,t,r){let o=ty(e,t,r);if(o.type!=="function")throw new Vu({name:t,type:"function"});return o}function xbe(e){return uO(e)}var xO="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",_n="0x0000000000000000000000000000000000000000";ot();ho();var _be="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function V7(e,t){let{blockNumber:r,blockTag:o,calls:n,stateOverrides:i,traceAssetChanges:s,traceTransfers:a,validation:c}=t,u=t.account?Ft(t.account):void 0;if(s&&!u)throw new F("`account` is required when `traceAssetChanges` is true");let d=u?F7(q7("constructor(bytes, bytes)"),{bytecode:qw,args:[_be,G7(Wu("function getBalance(address)"),[u.address])]}):void 0,p=s?await Promise.all(t.calls.map(async(C)=>{if(!C.data&&!C.abi)return;let{accessList:U}=await Jw(e,{account:u.address,...C,data:C.abi?Kt(C):C.data});return U.map(({address:N,storageKeys:Y})=>Y.length>0?N:null)})).then((C)=>C.flat().filter(Boolean)):[],m=await ey(e,{blockNumber:r,blockTag:o,blocks:[...s?[{calls:[{data:d}],stateOverrides:i},{calls:p.map((C,U)=>({abi:[Wu("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:C,from:_n,nonce:U})),stateOverrides:[{address:_n,nonce:0}]}]:[],{calls:[...n,{to:_n}].map((C)=>({...C,from:u?.address})),stateOverrides:i},...s?[{calls:[{data:d}]},{calls:p.map((C,U)=>({abi:[Wu("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[u.address],to:C,from:_n,nonce:U})),stateOverrides:[{address:_n,nonce:0}]},{calls:p.map((C,U)=>({to:C,abi:[Wu("function decimals() returns (uint256)")],functionName:"decimals",from:_n,nonce:U})),stateOverrides:[{address:_n,nonce:0}]},{calls:p.map((C,U)=>({to:C,abi:[Wu("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:_n,nonce:U})),stateOverrides:[{address:_n,nonce:0}]},{calls:p.map((C,U)=>({to:C,abi:[Wu("function symbol() returns (string)")],functionName:"symbol",from:_n,nonce:U})),stateOverrides:[{address:_n,nonce:0}]}]:[]],traceTransfers:a,validation:c}),h=s?m[2]:m[0],[y,x,,S,v,E,w,_]=s?m:[],{calls:T,...P}=h,O=T.slice(0,-1)??[],z=y?.calls??[],B=x?.calls??[],k=[...z,...B].map((C)=>C.status==="success"?Ur(C.data):null),G=S?.calls??[],V=v?.calls??[],ue=[...G,...V].map((C)=>C.status==="success"?Ur(C.data):null),W=(E?.calls??[]).map((C)=>C.status==="success"?C.result:null),H=(_?.calls??[]).map((C)=>C.status==="success"?C.result:null),fe=(w?.calls??[]).map((C)=>C.status==="success"?C.result:null),we=[];for(let[C,U]of ue.entries()){let N=k[C];if(typeof U!=="bigint")continue;if(typeof N!=="bigint")continue;let Y=W[C-1],X=H[C-1],ce=fe[C-1],Z=(()=>{if(C===0)return{address:xO,decimals:18,symbol:"ETH"};return{address:p[C-1],decimals:ce||Y?Number(Y??1):void 0,symbol:X??void 0}})();if(we.some((me)=>me.token.address===Z.address))continue;we.push({token:Z,value:{pre:N,post:U,diff:U-N}})}return{assetChanges:we,block:P,results:O}}Os();ho();Uu();async function Z7(e,t){let{abi:r,address:o,args:n,functionName:i,dataSuffix:s=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=a.account?Ft(a.account):e.account,u=Kt({abi:r,args:n,functionName:i});try{let{data:d}=await pe(e,vo,"call")({batch:!1,data:`${u}${s?s.replace("0x",""):""}`,to:o,...a,account:c}),p=Xr({abi:r,args:n,functionName:i,data:d||"0x"}),m=r.filter((h)=>("name"in h)&&h.name===t.functionName);return{result:p,request:{abi:m,address:o,args:n,dataSuffix:s,functionName:i,...a,account:c}}}catch(d){throw Yo(d,{abi:r,address:o,args:n,docsPath:"/docs/contract/simulateContract",functionName:i,sender:c?.address})}}async function ac(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}var sy={};Pn(sy,{InvalidWrappedSignatureError:()=>wO,assert:()=>_O,from:()=>Tbe,magicBytes:()=>vO,universalSignatureValidatorAbi:()=>Sbe,universalSignatureValidatorBytecode:()=>wbe,unwrap:()=>W7,validate:()=>Ibe,wrap:()=>Ebe});jn();Sr();var vO="0x6492649264926492649264926492649264926492649264926492649264926492",wbe="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",Sbe=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}];function _O(e){if(Wt(e,-32)!==vO)throw new wO(e)}function Tbe(e){if(typeof e==="string")return W7(e);return e}function W7(e){_O(e);let[t,r,o]=Wp(iy("address, bytes, bytes"),e);return{data:r,signature:o,to:t}}function Ebe(e){let{data:t,signature:r,to:o}=e;return Jt(sc(iy("address, bytes, bytes"),[o,t,r]),vO)}function Ibe(e){try{return _O(e),!0}catch{return!1}}class wO extends xe{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"})}}var ay={};Pn(ay,{InvalidWrappedSignatureError:()=>AO,assert:()=>P1,from:()=>Lbe,magicBytes:()=>PO,suffixParameters:()=>kO,unwrap:()=>cV,validate:()=>Fbe,wrap:()=>jbe});Sr();Ja();jn();Sr();function Pbe(e,t){let{as:r}=t,o=J7(e),n=T1(new Uint8Array(o.length));if(o.encode(n),r==="Hex")return ar(n.bytes);return n.bytes}function K7(e,t={}){let{as:r="Hex"}=t;return Pbe(e,{as:r})}function J7(e){if(Array.isArray(e))return kbe(e.map((t)=>J7(t)));return Abe(e)}function kbe(e){let t=e.reduce((n,i)=>n+i.length,0),r=Y7(t);return{length:(()=>{if(t<=55)return 1+t;return 1+r+t})(),encode(n){if(t<=55)n.pushByte(192+t);else if(n.pushByte(247+r),r===1)n.pushUint8(t);else if(r===2)n.pushUint16(t);else if(r===3)n.pushUint24(t);else n.pushUint32(t);for(let{encode:i}of e)i(n)}}}function Abe(e){let t=typeof e==="string"?Rp(e):e,r=Y7(t.length);return{length:(()=>{if(t.length===1&&t[0]<128)return 1;if(t.length<=55)return 1+t.length;return 1+r+t.length})(),encode(n){if(t.length===1&&t[0]<128)n.pushBytes(t);else if(t.length<=55)n.pushByte(128+t.length),n.pushBytes(t);else{if(n.pushByte(183+r),r===1)n.pushUint8(t.length);else if(r===2)n.pushUint16(t.length);else if(r===3)n.pushUint24(t.length);else n.pushUint32(t.length);n.pushBytes(t)}}}}function Y7(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;if(e<=4294967295)return 4;throw new xe("Length is too large.")}jn();Sr();function SO(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new E1({signature:e});if(typeof e.s>"u")throw new E1({signature:e});if(r&&typeof e.yParity>"u")throw new E1({signature:e});if(e.r<0n||e.r>lO)throw new tV({value:e.r});if(e.s<0n||e.s>lO)throw new rV({value:e.s});if(typeof e.yParity==="number"&&e.yParity!==0&&e.yParity!==1)throw new I1({value:e.yParity})}function Rbe(e){return Q7(ar(e))}function Q7(e){if(e.length!==130&&e.length!==132)throw new eV({signature:e});let t=BigInt(Wt(e,0,32)),r=BigInt(Wt(e,32,64)),o=(()=>{let n=Number(`0x${e.slice(130)}`);if(Number.isNaN(n))return;try{return IO(n)}catch{throw new I1({value:n})}})();if(typeof o>"u")return{r:t,s:r};return{r:t,s:r,yParity:o}}function TO(e){if(typeof e.r>"u")return;if(typeof e.s>"u")return;return EO(e)}function EO(e){let t=(()=>{if(typeof e==="string")return Q7(e);if(e instanceof Uint8Array)return Rbe(e);if(typeof e.r==="string")return Cbe(e);if(e.v)return Obe(e);return{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}}})();return SO(t),t}function Obe(e){return{r:e.r,s:e.s,yParity:IO(e.v)}}function Cbe(e){let t=(()=>{let r=e.v?Number(e.v):void 0,o=e.yParity?Number(e.yParity):void 0;if(typeof r==="number"&&typeof o!=="number")o=IO(r);if(typeof o!=="number")throw new I1({value:e.yParity});return o})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function X7(e){let{r:t,s:r,yParity:o}=e;return[o?"0x01":"0x",t===0n?"0x":v2(pt(t)),r===0n?"0x":v2(pt(r))]}function IO(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 nV({value:e})}class eV extends xe{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Zt(Op(e))} bytes.`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class E1 extends xe{constructor({signature:e}){super(`Signature \`${Ya(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class tV extends xe{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 rV extends xe{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 I1 extends xe{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 nV extends xe{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 iV(e,t={}){if(typeof e.chainId==="string")return zbe(e);return{...e,...t.signature}}function zbe(e){let{address:t,chainId:r,nonce:o}=e,n=TO(e);return{address:t,chainId:Number(r),nonce:BigInt(o),...n}}function sV(e){return Nbe(e,{presign:!0})}function Nbe(e,t={}){let{presign:r}=t;return Hu(Jt("0x05",K7(Mbe(r?{address:e.address,chainId:e.chainId,nonce:e.nonce}:e))))}function Mbe(e){let{address:t,chainId:r,nonce:o}=e,n=TO(e);return[r?pt(r):"0x",t,o?pt(o):"0x",...n?X7(n):[]]}jn();Sr();oc();Sr();function aV(e){return P7(Dbe(e))}function Dbe(e){let{payload:t,signature:r}=e,{r:o,s:n,yParity:i}=r,a=new vn.Signature(BigInt(o),BigInt(n)).addRecoveryBit(i).recoverPublicKey(Op(t).substring(2));return v7(a)}var PO="0x8010801080108010801080108010801080108010801080108010801080108010",kO=iy("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function P1(e){if(typeof e==="string"){if(Wt(e,-32)!==PO)throw new AO(e)}else SO(e.authorization)}function Lbe(e){if(typeof e==="string")return cV(e);return e}function cV(e){P1(e);let t=Uw(Wt(e,-64,-32)),r=Wt(e,-t-64,-64),o=Wt(e,0,-t-64),[n,i,s]=Wp(kO,r);return{authorization:iV({address:n.delegation,chainId:Number(n.chainId),nonce:n.nonce,yParity:n.yParity,r:n.r,s:n.s}),signature:o,...s&&s!=="0x"?{data:s,to:i}:{}}}function jbe(e){let{data:t,signature:r}=e;P1(e);let o=aV({payload:sV(e.authorization),signature:EO(e.authorization)}),n=sc(kO,[{...e.authorization,delegation:e.authorization.address,chainId:BigInt(e.authorization.chainId)},e.to??o,t??"0x"]),i=pt(Zt(n),{size:32});return Jt(r,n,i,PO)}function Fbe(e){try{return P1(e),!0}catch{return!1}}class AO extends xe{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"})}}Pi();Wa();S2();ho();Tu();Bp();Tu();Bp();async function uV({address:e,authorization:t,signature:r}){return Xo(Eu(e),await n1({authorization:t,signature:r}))}gn();We();oc();gn();jr();function lV({r:e,s:t,to:r="hex",v:o,yParity:n}){let i=(()=>{if(n===0||n===1)return n;if(o&&(o===27n||o===28n||o>=35n))return o%2n===0n?1:0;throw Error("Invalid `v` or `yParity` value")})(),s=`0x${new vn.Signature(Ur(e),Ur(t)).toCompactHex()}${i===0?"1b":"1c"}`;if(r==="hex")return s;return Lr(s)}Uu();async function uc(e,t){let{address:r,chain:o=e.chain,hash:n,erc6492VerifierAddress:i=t.universalSignatureVerifierAddress??o?.contracts?.erc6492Verifier?.address,multicallAddress:s=t.multicallAddress??o?.contracts?.multicall3?.address,mode:a="auto"}=t;if(o?.verifyHash)return await o.verifyHash(e,t);let c=(()=>{let u=t.signature;if(sr(u))return u;if(typeof u==="object"&&"r"in u&&"s"in u)return lV(u);return ht(u)})();try{if(a==="eoa")try{if(Xo(Eu(r),await Yg({hash:n,signature:c})))return!0}catch{}if(ay.validate(c))return await qbe(e,{...t,multicallAddress:s,signature:c});return await Hbe(e,{...t,verifierAddress:i,signature:c})}catch(u){if(a!=="eoa")try{if(Xo(Eu(r),await Yg({hash:n,signature:c})))return!0}catch{}if(u instanceof cc)return!1;throw u}}async function qbe(e,t){let{address:r,blockNumber:o,blockTag:n,hash:i,multicallAddress:s}=t,{authorization:a,data:c,signature:u,to:d}=ay.unwrap(t.signature);if(await Fu(e,{address:r,blockNumber:o,blockTag:n})===Wo(["0xef0100",a.address]))return await Gbe(e,{address:r,blockNumber:o,blockTag:n,hash:i,signature:u});let m={address:a.address,chainId:Number(a.chainId),nonce:Number(a.nonce),r:ye(a.r,{size:32}),s:ye(a.s,{size:32}),yParity:a.yParity};if(!await uV({address:r,authorization:m}))throw new cc;let y=await pe(e,dr,"readContract")({...s?{address:s}:{code:zp},authorizationList:[m],abi:qo,blockNumber:o,blockTag:"pending",functionName:"aggregate3",args:[[...c?[{allowFailure:!0,target:d??r,callData:c}]:[],{allowFailure:!0,target:r,callData:Kt({abi:G$,functionName:"isValidSignature",args:[i,u]})}]]});if(y[y.length-1]?.returnData?.startsWith("0x1626ba7e"))return!0;throw new cc}async function Hbe(e,t){let{address:r,factory:o,factoryData:n,hash:i,signature:s,verifierAddress:a,...c}=t,u=await(async()=>{if(!o&&!n)return s;if(sy.validate(s))return s;return sy.wrap({data:n,signature:s,to:o})})(),d=a?{to:a,data:Kt({abi:pg,functionName:"isValidSig",args:[r,i,u]}),...c}:{data:Mg({abi:pg,args:[r,i,u],bytecode:eG}),...c},{data:p}=await pe(e,vo,"call")(d).catch((m)=>{if(m instanceof Ag)throw new cc;throw m});if(lR(p??"0x0"))return!0;throw new cc}async function Gbe(e,t){let{address:r,blockNumber:o,blockTag:n,hash:i,signature:s}=t;if((await pe(e,dr,"readContract")({address:r,abi:G$,args:[i,s],blockNumber:o,blockTag:n,functionName:"isValidSignature"}).catch((c)=>{if(c instanceof $g)throw new cc;throw c})).startsWith("0x1626ba7e"))return!0;throw new cc}class cc extends Error{}Zo();var dV=`\x19Ethereum Signed Message:
143
143
  `;po();We();function pV(e){let t=(()=>{if(typeof e==="string")return Vd(e);if(typeof e.raw==="string")return e.raw;return ht(e.raw)})(),r=Vd(`${dV}${at(t)}`);return Fr([r,t])}function k1(e,t){return zt(pV(e),t)}async function fV(e,{address:t,message:r,factory:o,factoryData:n,signature:i,...s}){let a=k1(r);return pe(e,uc,"verifyHash")({address:t,factory:o,factoryData:n,hash:a,signature:i,...s})}Ps();We();Zo();ir();_u();ot();class $O extends F{constructor({domain:e}){super(`Invalid domain "${dt(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class RO extends F{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 OO extends F{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}Is();po();We();bR();function mV(e){let{domain:t,message:r,primaryType:o,types:n}=e,i=(s,a)=>{for(let c of s){let{name:u,type:d}=c,p=a[u],m=d.match(hw);if(m&&(typeof p==="number"||typeof p==="bigint")){let[x,S,v]=m;ye(p,{signed:S==="int",size:Number.parseInt(v,10)/8})}if(d==="address"&&typeof p==="string"&&!lr(p))throw new hn({address:p});let h=d.match(Tq);if(h){let[x,S]=h;if(S&&at(p)!==Number.parseInt(S,10))throw new oR({expectedSize:Number.parseInt(S,10),givenSize:at(p)})}let y=n[d];if(y)Vbe(d),i(y,p)}};if(n.EIP712Domain&&t){if(typeof t!=="object")throw new $O({domain:t});i(n.EIP712Domain,t)}if(o!=="EIP712Domain")if(n[o])i(n[o],r);else throw new RO({primaryType:o,types:n})}function hV({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 Vbe(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new OO({type:e})}function gV(e){let{domain:t={},message:r,primaryType:o}=e,n={EIP712Domain:hV({domain:t}),...e.types};mV({domain:t,message:r,primaryType:o,types:n});let i=["0x1901"];if(t)i.push(Zbe({domain:t,types:n}));if(o!=="EIP712Domain")i.push(yV({data:r,primaryType:o,types:n}));return zt(Fr(i))}function Zbe({domain:e,types:t}){return yV({data:e,primaryType:"EIP712Domain",types:t})}function yV({data:e,primaryType:t,types:r}){let o=bV({data:e,primaryType:t,types:r});return zt(o)}function bV({data:e,primaryType:t,types:r}){let o=[{type:"bytes32"}],n=[Wbe({primaryType:t,types:r})];for(let i of r[t]){let[s,a]=vV({types:r,name:i.name,type:i.type,value:e[i.name]});o.push(s),n.push(a)}return yn(o,n)}function Wbe({primaryType:e,types:t}){let r=Qr(Kbe({primaryType:e,types:t}));return zt(r)}function Kbe({primaryType:e,types:t}){let r="",o=xV({primaryType:e,types:t});o.delete(e);let n=[e,...Array.from(o).sort()];for(let i of n)r+=`${i}(${t[i].map(({name:s,type:a})=>`${a} ${s}`).join(",")})`;return r}function xV({primaryType:e,types:t},r=new Set){let n=e.match(/^\w*/u)?.[0];if(r.has(n)||t[n]===void 0)return r;r.add(n);for(let i of t[n])xV({primaryType:i.type,types:t},r);return r}function vV({types:e,name:t,type:r,value:o}){if(e[r]!==void 0)return[{type:"bytes32"},zt(bV({data:o,primaryType:r,types:e}))];if(r==="bytes")return[{type:"bytes32"},zt(o)];if(r==="string")return[{type:"bytes32"},zt(Qr(o))];if(r.lastIndexOf("]")===r.length-1){let n=r.slice(0,r.lastIndexOf("[")),i=o.map((s)=>vV({name:t,type:n,types:e,value:s}));return[{type:"bytes32"},zt(yn(i.map(([s])=>s),i.map(([,s])=>s)))]}return[{type:r},o]}async function _V(e,t){let{address:r,factory:o,factoryData:n,signature:i,message:s,primaryType:a,types:c,domain:u,...d}=t,p=gV({message:s,primaryType:a,types:c,domain:u});return pe(e,uc,"verifyHash")({address:r,factory:o,factoryData:n,hash:p,signature:i,...d})}Cs();var CO=new Map,wV=new Map,Jbe=0;function Fn(e,t,r){let o=++Jbe,n=()=>CO.get(e)||[],i=()=>{let d=n();CO.set(e,d.filter((p)=>p.id!==o))},s=()=>{let d=n();if(!d.some((m)=>m.id===o))return;let p=wV.get(e);if(d.length===1&&p){let m=p();if(m instanceof Promise)m.catch(()=>{})}i()},a=n();if(CO.set(e,[...a,{id:o,fns:t}]),a&&a.length>0)return s;let c={};for(let d in t)c[d]=(...p)=>{let m=n();if(m.length===0)return;for(let h of m)h.fns[d]?.(...p)};let u=r(c);if(typeof u==="function")wV.set(e,u);return s}async function cy(e){return new Promise((t)=>setTimeout(t,e))}function uy(e,{delay:t=100,retryCount:r=2,shouldRetry:o=()=>!0}={}){return new Promise((n,i)=>{let s=async({count:a=0}={})=>{let c=async({error:u})=>{let d=typeof t==="function"?t({count:a,error:u}):t;if(d)await cy(d);s({count:a+1})};try{let u=await e();n(u)}catch(u){if(a<r&&await o({count:a,error:u}))return c({error:u});i(u)}};s()})}gn();function Mi(e,{emitOnBegin:t,initialWaitTime:r,interval:o}){let n=!0,i=()=>n=!1;return(async()=>{let a;if(t)a=await e({unpoll:i});let c=await r?.(a)??o;await cy(c);let u=async()=>{if(!n)return;await e({unpoll:i}),await cy(o),u()};u()})(),i}function A1(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:o,onError:n,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 p=dt(["watchBlockNumber",e.uid,t,r,s]);return Fn(p,{onBlockNumber:o,onError:n},(m)=>Mi(async()=>{try{let h=await pe(e,Ni,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(h===c)return;if(h-c>1&&r)for(let y=c+1n;y<h;y++)m.onBlockNumber(y,c),c=y}if(c===void 0||h>c)m.onBlockNumber(h,c),c=h}catch(h){m.onError?.(h)}},{emitOnBegin:t,interval:s}))})():(()=>{let p=dt(["watchBlockNumber",e.uid,t,r]);return Fn(p,{onBlockNumber:o,onError:n},(m)=>{let h=!0,y=()=>h=!1;return(async()=>{try{let x=(()=>{if(e.transport.type==="fallback"){let v=e.transport.transports.find((E)=>E.config.type==="webSocket"||E.config.type==="ipc");if(!v)return e.transport;return v.value}return e.transport})(),{unsubscribe:S}=await x.subscribe({params:["newHeads"],onData(v){if(!h)return;let E=Ur(v.result?.number);m.onBlockNumber(E,c),c=E},onError(v){m.onError?.(v)}});if(y=S,!h)y()}catch(x){n?.(x)}})(),()=>y()})})()}async function SV(e,t){let{checkReplacement:r=!0,confirmations:o=1,hash:n,onReplaced:i,retryCount:s=6,retryDelay:a=({count:T})=>~~(1<<T)*200,timeout:c=180000}=t,u=dt(["waitForTransactionReceipt",e.uid,n]),d=(()=>{if(t.pollingInterval)return t.pollingInterval;if(e.chain?.experimental_preconfirmationTime)return e.chain.experimental_preconfirmationTime;return e.pollingInterval})(),p,m,h,y=!1,x,S,{promise:v,resolve:E,reject:w}=Gw(),_=c?setTimeout(()=>{S?.(),x?.(),w(new e2({hash:n}))},c):void 0;return x=Fn(u,{onReplaced:i,resolve:E,reject:w},async(T)=>{if(h=await pe(e,Vp,"getTransactionReceipt")({hash:n}).catch(()=>{return}),h&&o<=1){clearTimeout(_),T.resolve(h),x?.();return}S=pe(e,A1,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:d,async onBlockNumber(P){let O=(B)=>{clearTimeout(_),S?.(),B(),x?.()},z=P;if(y)return;try{if(h){if(o>1&&(!h.blockNumber||z-h.blockNumber+1n<o))return;O(()=>T.resolve(h));return}if(r&&!p)y=!0,await uy(async()=>{if(p=await pe(e,Gp,"getTransaction")({hash:n}),p.blockNumber)z=p.blockNumber},{delay:a,retryCount:s}),y=!1;if(h=await pe(e,Vp,"getTransactionReceipt")({hash:n}),o>1&&(!h.blockNumber||z-h.blockNumber+1n<o))return;O(()=>T.resolve(h))}catch(B){if(B instanceof Pg||B instanceof kg){if(!p){y=!1;return}try{m=p,y=!0;let k=await uy(()=>pe(e,Tr,"getBlock")({blockNumber:z,includeTransactions:!0}),{delay:a,retryCount:s,shouldRetry:({error:ue})=>ue instanceof Xg});y=!1;let G=k.transactions.find(({from:ue,nonce:W})=>ue===m.from&&W===m.nonce);if(!G)return;if(h=await pe(e,Vp,"getTransactionReceipt")({hash:G.hash}),o>1&&(!h.blockNumber||z-h.blockNumber+1n<o))return;let V="replaced";if(G.to===m.to&&G.value===m.value&&G.input===m.input)V="repriced";else if(G.from===G.to&&G.value===0n)V="cancelled";O(()=>{T.onReplaced?.({reason:V,replacedTransaction:m,transaction:G,transactionReceipt:h}),T.resolve(h)})}catch(k){O(()=>T.reject(k))}}else O(()=>T.reject(B))}}})}),v}function TV(e,{blockTag:t=e.experimental_blockTag??"latest",emitMissed:r=!1,emitOnBegin:o=!1,onBlock:n,onError:i,includeTransactions:s,poll:a,pollingInterval:c=e.pollingInterval}){let u=(()=>{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,p;return u?(()=>{let y=dt(["watchBlocks",e.uid,t,r,o,d,c]);return Fn(y,{onBlock:n,onError:i},(x)=>Mi(async()=>{try{let S=await pe(e,Tr,"getBlock")({blockTag:t,includeTransactions:d});if(S.number!==null&&p?.number!=null){if(S.number===p.number)return;if(S.number-p.number>1&&r)for(let v=p?.number+1n;v<S.number;v++){let E=await pe(e,Tr,"getBlock")({blockNumber:v,includeTransactions:d});x.onBlock(E,p),p=E}}if(p?.number==null||t==="pending"&&S?.number==null||S.number!==null&&S.number>p.number)x.onBlock(S,p),p=S}catch(S){x.onError?.(S)}},{emitOnBegin:o,interval:c}))})():(()=>{let y=!0,x=!0,S=()=>y=!1;return(async()=>{try{if(o)pe(e,Tr,"getBlock")({blockTag:t,includeTransactions:d}).then((w)=>{if(!y)return;if(!x)return;n(w,void 0),x=!1}).catch(i);let v=(()=>{if(e.transport.type==="fallback"){let w=e.transport.transports.find((_)=>_.config.type==="webSocket"||_.config.type==="ipc");if(!w)return e.transport;return w.value}return e.transport})(),{unsubscribe:E}=await v.subscribe({params:["newHeads"],async onData(w){if(!y)return;let _=await pe(e,Tr,"getBlock")({blockNumber:w.result?.number,includeTransactions:d}).catch(()=>{});if(!y)return;n(_,p),x=!1,p=_},onError(w){i?.(w)}});if(S=E,!y)S()}catch(v){i?.(v)}})(),()=>S()})()}ir();Cg();function EV(e,t){let{abi:r,address:o,args:n,batch:i=!0,eventName:s,fromBlock:a,onError:c,onLogs:u,poll:d,pollingInterval:p=e.pollingInterval,strict:m}=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=m??!1,v=dt(["watchContractEvent",o,n,i,e.uid,s,p,S,a]);return Fn(v,{onLogs:u,onError:c},(E)=>{let w;if(a!==void 0)w=a-1n;let _,T=!1,P=Mi(async()=>{if(!T){try{_=await pe(e,Yw,"createContractEventFilter")({abi:r,address:o,args:n,eventName:s,strict:S,fromBlock:a})}catch{}T=!0;return}try{let O;if(_)O=await pe(e,ic,"getFilterChanges")({filter:_});else{let z=await pe(e,Ni,"getBlockNumber")({});if(w&&w<z)O=await pe(e,p1,"getContractEvents")({abi:r,address:o,args:n,eventName:s,fromBlock:w+1n,toBlock:z,strict:S});else O=[];w=z}if(O.length===0)return;if(i)E.onLogs(O);else for(let z of O)E.onLogs([z])}catch(O){if(_&&O instanceof yo)T=!1;E.onError?.(O)}},{emitOnBegin:!0,interval:p});return async()=>{if(_)await pe(e,ac,"uninstallFilter")({filter:_});P()}})})():(()=>{let S=m??!1,v=dt(["watchContractEvent",o,n,i,e.uid,s,p,S]),E=!0,w=()=>E=!1;return Fn(v,{onLogs:u,onError:c},(_)=>((async()=>{try{let T=(()=>{if(e.transport.type==="fallback"){let z=e.transport.transports.find((B)=>B.config.type==="webSocket"||B.config.type==="ipc");if(!z)return e.transport;return z.value}return e.transport})(),P=s?zi({abi:r,eventName:s,args:n}):[],{unsubscribe:O}=await T.subscribe({params:["logs",{address:o,topics:P}],onData(z){if(!E)return;let B=z.result;try{let{eventName:k,args:G}=qu({abi:r,data:B.data,topics:B.topics,strict:m}),V=Er(B,{args:G,eventName:k});_.onLogs([V])}catch(k){let G,V;if(k instanceof qa||k instanceof vu){if(m)return;G=k.abiItem.name,V=k.abiItem.inputs?.some((W)=>!(("name"in W)&&W.name))}let ue=Er(B,{args:V?[]:{},eventName:G});_.onLogs([ue])}},onError(z){_.onError?.(z)}});if(w=O,!E)w()}catch(T){c?.(T)}})(),()=>w()))})()}ir();Cg();function IV(e,{address:t,args:r,batch:o=!0,event:n,events:i,fromBlock:s,onError:a,onLogs:c,poll:u,pollingInterval:d=e.pollingInterval,strict:p}){let m=(()=>{if(typeof u<"u")return u;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})(),h=p??!1;return m?(()=>{let S=dt(["watchEvent",t,r,o,e.uid,n,d,s]);return Fn(S,{onLogs:c,onError:a},(v)=>{let E;if(s!==void 0)E=s-1n;let w,_=!1,T=Mi(async()=>{if(!_){try{w=await pe(e,Qw,"createEventFilter")({address:t,args:r,event:n,events:i,strict:h,fromBlock:s})}catch{}_=!0;return}try{let P;if(w)P=await pe(e,ic,"getFilterChanges")({filter:w});else{let O=await pe(e,Ni,"getBlockNumber")({});if(E&&E!==O)P=await pe(e,Hp,"getLogs")({address:t,args:r,event:n,events:i,fromBlock:E+1n,toBlock:O});else P=[];E=O}if(P.length===0)return;if(o)v.onLogs(P);else for(let O of P)v.onLogs([O])}catch(P){if(w&&P instanceof yo)_=!1;v.onError?.(P)}},{emitOnBegin:!0,interval:d});return async()=>{if(w)await pe(e,ac,"uninstallFilter")({filter:w});T()}})})():(()=>{let S=!0,v=()=>S=!1;return(async()=>{try{let E=(()=>{if(e.transport.type==="fallback"){let P=e.transport.transports.find((O)=>O.config.type==="webSocket"||O.config.type==="ipc");if(!P)return e.transport;return P.value}return e.transport})(),w=i??(n?[n]:void 0),_=[];if(w){if(_=[w.flatMap((O)=>zi({abi:[O],eventName:O.name,args:r}))],n)_=_[0]}let{unsubscribe:T}=await E.subscribe({params:["logs",{address:t,topics:_}],onData(P){if(!S)return;let O=P.result;try{let{eventName:z,args:B}=qu({abi:w??[],data:O.data,topics:O.topics,strict:h}),k=Er(O,{args:B,eventName:z});c([k])}catch(z){let B,k;if(z instanceof qa||z instanceof vu){if(p)return;B=z.abiItem.name,k=z.abiItem.inputs?.some((V)=>!(("name"in V)&&V.name))}let G=Er(O,{args:k?[]:{},eventName:B});c([G])}},onError(P){a?.(P)}});if(v=T,!S)v()}catch(E){a?.(E)}})(),()=>v()})()}function PV(e,{batch:t=!0,onError:r,onTransactions:o,poll:n,pollingInterval:i=e.pollingInterval}){return(typeof n<"u"?n:e.transport.type!=="webSocket"&&e.transport.type!=="ipc")?(()=>{let u=dt(["watchPendingTransactions",e.uid,t,i]);return Fn(u,{onTransactions:o,onError:r},(d)=>{let p,m=Mi(async()=>{try{if(!p)try{p=await pe(e,Xw,"createPendingTransactionFilter")({});return}catch(y){throw m(),y}let h=await pe(e,ic,"getFilterChanges")({filter:p});if(h.length===0)return;if(t)d.onTransactions(h);else for(let y of h)d.onTransactions([y])}catch(h){d.onError?.(h)}},{emitOnBegin:!0,interval:i});return async()=>{if(p)await pe(e,ac,"uninstallFilter")({filter:p});m()}})})():(()=>{let u=!0,d=()=>u=!1;return(async()=>{try{let{unsubscribe:p}=await e.transport.subscribe({params:["newPendingTransactions"],onData(m){if(!u)return;let h=m.result;o([h])},onError(m){r?.(m)}});if(d=p,!u)d()}catch(p){r?.(p)}})(),()=>d()})()}function kV(e){let{scheme:t,statement:r,...o}=e.match(Ybe)?.groups??{},{chainId:n,expirationTime:i,issuedAt:s,notBefore:a,requestId:c,...u}=e.match(Qbe)?.groups??{},d=e.split("Resources:")[1]?.split(`
144
144
  - `).slice(1);return{...o,...u,...n?{chainId:Number(n)}:{},...i?{expirationTime:new Date(i)}:{},...s?{issuedAt:new Date(s)}:{},...a?{notBefore:new Date(a)}:{},...c?{requestId:c}:{},...d?{resources:d}:{},...t?{scheme:t}:{},...r?{statement:r}:{}}}var Ybe=/^(?:(?<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)?/,Qbe=/(?: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>.+))?/;Is();Bp();function AV(e){let{address:t,domain:r,message:o,nonce:n,scheme:i,time:s=new Date}=e;if(r&&o.domain!==r)return!1;if(n&&o.nonce!==n)return!1;if(i&&o.scheme!==i)return!1;if(o.expirationTime&&s>=o.expirationTime)return!1;if(o.notBefore&&s<o.notBefore)return!1;try{if(!o.address)return!1;if(!lr(o.address,{strict:!1}))return!1;if(t&&!Xo(o.address,t))return!1}catch{return!1}return!0}async function $V(e,t){let{address:r,domain:o,message:n,nonce:i,scheme:s,signature:a,time:c=new Date,...u}=t,d=kV(n);if(!d.address)return!1;if(!AV({address:r,domain:o,message:d,nonce:i,scheme:s,time:c}))return!1;let m=k1(n);return uc(e,{address:d.address,hash:m,signature:a,...u})}async function RV(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}Cs();async function OV(e,{serializedTransaction:t,throwOnReceiptRevert:r,timeout:o}){let n=await e.request({method:"eth_sendRawTransactionSync",params:o?[t,o]:[t]},{retryCount:0}),s=(e.chain?.formatters?.transactionReceipt?.format||f1)(n);if(s.status==="reverted"&&r)throw new XR({receipt:s});return s}function CV(e){return{call:(t)=>vo(e,t),createAccessList:(t)=>Jw(e,t),createBlockFilter:()=>xG(e),createContractEventFilter:(t)=>Yw(e,t),createEventFilter:(t)=>Qw(e,t),createPendingTransactionFilter:()=>Xw(e),estimateContractGas:(t)=>r7(e,t),estimateGas:(t)=>Fp(e,t),getBalance:(t)=>n7(e,t),getBlobBaseFee:()=>o7(e),getBlock:(t)=>Tr(e,t),getBlockNumber:(t)=>Ni(e,t),getBlockTransactionCount:(t)=>a7(e,t),getBytecode:(t)=>Fu(e,t),getChainId:()=>jp(e),getCode:(t)=>Fu(e,t),getContractEvents:(t)=>p1(e,t),getDelegation:(t)=>u7(e,t),getEip712Domain:(t)=>l7(e,t),getEnsAddress:(t)=>lG(e,t),getEnsAvatar:(t)=>gG(e,t),getEnsName:(t)=>yG(e,t),getEnsResolver:(t)=>bG(e,t),getEnsText:(t)=>Kw(e,t),getFeeHistory:(t)=>p7(e,t),estimateFeesPerGas:(t)=>HG(e,t),getFilterChanges:(t)=>ic(e,t),getFilterLogs:(t)=>f7(e,t),getGasPrice:()=>Lp(e),getLogs:(t)=>Hp(e,t),getProof:(t)=>h7(e,t),estimateMaxPriorityFeePerGas:(t)=>qG(e,t),fillTransaction:(t)=>l1(e,t),getStorageAt:(t)=>g7(e,t),getTransaction:(t)=>Gp(e,t),getTransactionConfirmations:(t)=>y7(e,t),getTransactionCount:(t)=>s1(e,t),getTransactionReceipt:(t)=>Vp(e,t),multicall:(t)=>b7(e,t),prepareTransactionRequest:(t)=>d1(e,t),readContract:(t)=>dr(e,t),sendRawTransaction:(t)=>RV(e,t),sendRawTransactionSync:(t)=>OV(e,t),simulate:(t)=>ey(e,t),simulateBlocks:(t)=>ey(e,t),simulateCalls:(t)=>V7(e,t),simulateContract:(t)=>Z7(e,t),verifyHash:(t)=>uc(e,t),verifyMessage:(t)=>fV(e,t),verifySiweMessage:(t)=>$V(e,t),verifyTypedData:(t)=>_V(e,t),uninstallFilter:(t)=>ac(e,t),waitForTransactionReceipt:(t)=>SV(e,t),watchBlocks:(t)=>TV(e,t),watchBlockNumber:(t)=>A1(e,t),watchContractEvent:(t)=>EV(e,t),watchEvent:(t)=>IV(e,t),watchPendingTransactions:(t)=>PV(e,t)}}function zO(e){let{key:t="public",name:r="Public Client"}=e;return aq({...e,key:t,name:r,type:"publicClient"}).extend(CV)}Ru();ot();class NO extends F{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}I2();Ru();function zV(e,{errorInstance:t=Error("timed out"),timeout:r,signal:o}){return new Promise((n,i)=>{(async()=>{let s;try{let a=new AbortController;if(r>0)s=setTimeout(()=>{if(o)a.abort();else i(t)},r);n(await e({signal:a?.signal||null}))}catch(a){if(a?.name==="AbortError")i(t);i(a)}finally{clearTimeout(s)}})()})}function Xbe(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var MO=Xbe();function NV(e,t={}){let{url:r,headers:o}=e0e(e);return{async request(n){let{body:i,fetchFn:s=t.fetchFn??fetch,onRequest:a=t.onRequest,onResponse:c=t.onResponse,timeout:u=t.timeout??1e4}=n,d={...t.fetchOptions??{},...n.fetchOptions??{}},{headers:p,method:m,signal:h}=d;try{let y=await zV(async({signal:S})=>{let v={...d,body:Array.isArray(i)?dt(i.map((T)=>({jsonrpc:"2.0",id:T.id??MO.take(),...T}))):dt({jsonrpc:"2.0",id:i.id??MO.take(),...i}),headers:{...o,"Content-Type":"application/json",...p},method:m||"POST",signal:h||(u>0?S:null)},E=new Request(r,v),w=await a?.(E,v)??{...v,url:r};return await s(w.url??r,w)},{errorInstance:new Nw({body:i,url:r}),timeout:u,signal:!0});if(c)await c(y);let x;if(y.headers.get("Content-Type")?.startsWith("application/json"))x=await y.json();else{x=await y.text();try{x=JSON.parse(x||"{}")}catch(S){if(y.ok)throw S;x={error:x}}}if(!y.ok){if(typeof x.error?.code==="number"&&typeof x.error?.message==="string")return x;throw new Jo({body:i,details:dt(x.error)||y.statusText,headers:y.headers,status:y.status,url:r})}return x}catch(y){if(y instanceof Jo)throw y;if(y instanceof Nw)throw y;throw new Jo({body:i,cause:y,url:r})}}}}function e0e(e){try{let t=new URL(e),r=(()=>{if(t.username){let o=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;return t.username="",t.password="",{url:t.toString(),headers:{Authorization:`Basic ${btoa(o)}`}}}return})();return{url:t.toString(),...r}}catch{return{url:e}}}ot();Ru();Cg();vg();var $1=new Es(8192);function MV(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if($1.get(r))return $1.get(r);let o=e().finally(()=>$1.delete(r));return $1.set(r,o),o}function BV(e,t={}){return async(r,o={})=>{let{dedupe:n=!1,methods:i,retryDelay:s=150,retryCount:a=3,uid:c}={...t,...o},{method:u}=r;if(i?.exclude?.includes(u))throw new Ka(Error("method not supported"),{method:u});if(i?.include&&!i.include.includes(u))throw new Ka(Error("method not supported"),{method:u});let d=n?r0e(`${c}.${dt(r)}`):void 0;return MV(()=>uy(async()=>{try{return await e(r)}catch(p){let m=p;switch(m.code){case cp.code:throw new cp(m);case up.code:throw new up(m);case lp.code:throw new lp(m,{method:r.method});case dp.code:throw new dp(m);case Ms.code:throw new Ms(m);case yo.code:throw new yo(m);case pp.code:throw new pp(m);case fp.code:throw new fp(m);case mp.code:throw new mp(m);case Ka.code:throw new Ka(m,{method:r.method});case Ou.code:throw new Ou(m);case hp.code:throw new hp(m);case Cu.code:throw new Cu(m);case gp.code:throw new gp(m);case yp.code:throw new yp(m);case bp.code:throw new bp(m);case xp.code:throw new xp(m);case vp.code:throw new vp(m);case _p.code:throw new _p(m);case wp.code:throw new wp(m);case Sp.code:throw new Sp(m);case Tp.code:throw new Tp(m);case Ep.code:throw new Ep(m);case Ip.code:throw new Ip(m);case Pp.code:throw new Pp(m);case 5000:throw new Cu(m);case kp.code:throw new kp(m);default:if(p instanceof F)throw p;throw new a2(m)}}},{delay:({count:p,error:m})=>{if(m&&m instanceof Jo){let h=m?.headers?.get("Retry-After");if(h?.match(/\d/))return Number.parseInt(h,10)*1000}return~~(1<<p)*s},retryCount:a,shouldRetry:({error:p})=>t0e(p)}),{enabled:n,id:d})}}function t0e(e){if("code"in e&&typeof e.code==="number"){if(e.code===-1)return!0;if(e.code===Ou.code)return!0;if(e.code===Ms.code)return!0;if(e.code===429)return!0;return!1}if(e instanceof Jo&&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 r0e(e,t=0){let r=3735928559^t,o=1103547991^t;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);r=Math.imul(r^i,2654435761),o=Math.imul(o^i,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(o^o>>>16,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(r^r>>>16,3266489909),(4294967296*(2097151&o)+(r>>>0)).toString(36)}function DV({key:e,methods:t,name:r,request:o,retryCount:n=3,retryDelay:i=150,timeout:s,type:a},c){let u=ew();return{config:{key:e,methods:t,name:r,request:o,retryCount:n,retryDelay:i,timeout:s,type:a},request:BV(o,{methods:t,retryCount:n,retryDelay:i,uid:u}),value:c}}function BO(e,t={}){let{batch:r,fetchFn:o,fetchOptions:n,key:i="http",methods:s,name:a="HTTP JSON-RPC",onFetchRequest:c,onFetchResponse:u,retryDelay:d,raw:p}=t;return({chain:m,retryCount:h,timeout:y})=>{let{batchSize:x=1000,wait:S=0}=typeof r==="object"?r:{},v=t.retryCount??h,E=y??t.timeout??1e4,w=e||m?.rpcUrls.default.http[0];if(!w)throw new NO;let _=NV(w,{fetchFn:o,fetchOptions:n,onRequest:c,onResponse:u,timeout:E});return DV({key:i,methods:s,name:a,async request({method:T,params:P}){let O={method:T,params:P},{schedule:z}=Vw({id:w,wait:S,shouldSplitBatch(V){return V.length>x},fn:(V)=>_.request({body:V}),sort:(V,ue)=>V.id-ue.id}),B=async(V)=>r?z(V):[await _.request({body:V})],[{error:k,result:G}]=await B(O);if(p)return{error:k,result:G};if(k)throw new $u({body:O,error:k,url:w});return G},retryCount:v,retryDelay:d,timeout:E,type:"http"},{fetchOptions:n,url:w})}}Pi();function R1(e){let t={formatters:void 0,fees:void 0,serializers:void 0,...e};function r(o){return(n)=>{let i=typeof n==="function"?n(o):n,s={...o,...i};return Object.assign(s,{extend:r(s)})}}return Object.assign(t,{extend:r(t)})}var DO=R1({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 UO=R1({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});lo();var O1=rn(Y_(),1);var n0e="@0xmonaco/core",LO={Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11},jO="Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec",o0e=new RegExp(`^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d{2}) (${jO}) (\\d{4}) (\\d{2}):(\\d{2}):(\\d{2}) GMT$`),i0e=new RegExp(`^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{2})-(${jO})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2}) GMT$`),s0e=new RegExp(`^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (${jO}) ([ \\d]\\d) (\\d{2}):(\\d{2}):(\\d{2}) (\\d{4})$`);function a0e(e,t,r,o,n,i){let s=new Date(Date.now()),a=Math.floor(s.getUTCFullYear()/100)*100+e,c=Date.UTC(a,t,r,o,n,i),u=Date.UTC(s.getUTCFullYear()+50,s.getUTCMonth(),s.getUTCDate(),s.getUTCHours(),s.getUTCMinutes(),s.getUTCSeconds());return c>u?a-100:a}function c0e(e){let t,r,o,n,i,s,a=o0e.exec(e),c=i0e.exec(e),u=s0e.exec(e);if(a)t=Number(a[1]),r=LO[a[2]],o=Number(a[3]),n=Number(a[4]),i=Number(a[5]),s=Number(a[6]);else if(c){if(t=Number(c[1]),r=LO[c[2]],n=Number(c[4]),i=Number(c[5]),s=Number(c[6]),r===void 0)return;o=a0e(Number(c[3]),r,t,n,i,s)}else if(u)r=LO[u[1]],t=Number((u[2]??"").trim()),n=Number(u[3]),i=Number(u[4]),s=Number(u[5]),o=Number(u[6]);else return;if(r===void 0)return;let d=Date.UTC(o,r,t,n,i,s),p=new Date(d);if(p.getUTCFullYear()!==o||p.getUTCMonth()!==r||p.getUTCDate()!==t||p.getUTCHours()!==n||p.getUTCMinutes()!==i||p.getUTCSeconds()!==s)return;return d}class Ke{apiUrl;sessionKeypair;serverKey;retryOptions;constructor(e,t){this.apiUrl=e,this.retryOptions={maxRetries:t?.maxRetries??3,baseDelayMs:t?.baseDelayMs??1000}}setSessionKeypair(e){this.sessionKeypair=e?HF(e.publicKey,e.privateKey):void 0}setServerKey(e){this.serverKey=e}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,o)=>{t[o]=r instanceof File?`[File: ${r.name}]`:r}),t}if(e instanceof URLSearchParams){let t={};return e.forEach((r,o)=>{t[o]=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"),o;if(r!==null){let n=r.trim();if(/^\d+$/.test(n))o=Number.parseInt(n,10);else{let i=c0e(n);if(i!==void 0)o=Math.max(0,Math.ceil((i-Date.now())/1000))}}return{requestId:t,retryAfter:o}}async executeRequest(e,t,r,o){let n,i={"User-Agent":n0e,...r.headers};try{n=await fetch(e,{...r,headers:i})}catch(u){throw new or(`Network request failed for ${t}`,{endpoint:e,cause:u instanceof Error?u:Error(String(u)),requestBody:o})}let s,a=n.headers?.get("content-type")||"unknown",c=n.clone?n.clone():n;try{s=await n.json()}catch(u){let d;try{d=await c.text()}catch{d="[Unable to read response body]"}if(!n.ok){let p=`API request failed: ${n.status}. Response is not JSON (Content-Type: ${a})`,{requestId:m,retryAfter:h}=this.extractResponseMetadata(n.headers);throw new or(p,{endpoint:e,statusCode:n.status,responseBody:{rawResponse:d.substring(0,500),contentType:a,parseError:u instanceof Error?u.message:String(u)},cause:u instanceof Error?u:void 0,requestBody:o,requestId:m,retryAfter:h})}if(d.trim()==="")return;throw new or(`Expected JSON response but received ${a}`,{endpoint:e,statusCode:n.status,responseBody:{rawResponse:d.substring(0,500),contentType:a},cause:u instanceof Error?u:void 0,requestBody:o})}if(!n.ok){let u=s!==null&&typeof s==="object"?s:void 0,d=(typeof u?.message==="string"?u.message:void 0)||(typeof u?.error==="string"?u.error:void 0)||`API request failed: ${n.status}`,{requestId:p,retryAfter:m}=this.extractResponseMetadata(n.headers);throw new or(d,{endpoint:e,statusCode:n.status,responseBody:s,requestBody:o,requestId:p,retryAfter:m})}return s}async makeAuthenticatedRequest(e,t={}){if(!this.sessionKeypair)throw new or("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:O1.StatusCodes.UNAUTHORIZED});let r=`${this.apiUrl}${e}`,o=this.parseRequestBody(t.body),n=this.buildSignatureHeaders(e,t);return this.executeRequest(r,e,{...t,headers:{"Content-Type":"application/json",...n,...t.headers}},o)}buildSignatureHeaders(e,t){if(!this.sessionKeypair)throw new or("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:O1.StatusCodes.UNAUTHORIZED});let r=(t.method??"GET").toUpperCase(),o=Date.now(),n=typeof t.body==="string"?Dd(t.body):new Uint8Array(0),i=GF(n),s=VF(r,e,o,i),a=K_(this.sessionKeypair.privateKey,s);return{"X-Monaco-PublicKey":uu(this.sessionKeypair.publicKey),"X-Monaco-Timestamp":String(o),"X-Monaco-Signature":a}}async makeBackendRequest(e,t={}){if(!this.serverKey)throw new or("Server key not set. Call setServerKey(sk_...) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:O1.StatusCodes.UNAUTHORIZED});let r=`${this.apiUrl}${e}`,o=this.parseRequestBody(t.body);return this.executeRequest(r,e,{...t,headers:{"Content-Type":"application/json","x-server-key":this.serverKey,...t.headers}},o)}async makePublicRequest(e,t={}){let r=`${this.apiUrl}${e}`,o=this.parseRequestBody(t.body);return this.executeRequest(r,e,{...t,headers:{"Content-Type":"application/json",...t.headers}},o)}}function ct(e){return encodeURIComponent(e)}function qt(e,t){if(!t)return e;let r=new URLSearchParams;for(let[n,i]of Object.entries(t))if(i!==void 0)r.set(n,String(i));let o=r.toString();return o?`${e}?${o}`:e}var de={orders:{create:()=>"/api/v1/orders",list:(e)=>qt("/api/v1/orders",e),get:(e)=>`/api/v1/orders/${ct(e)}`,replace:(e)=>`/api/v1/orders/${ct(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/${ct(e)}`,batchCreate:()=>"/api/v1/orders/batch-create",batchReplace:()=>"/api/v1/orders/batch-replace",listConditional:(e)=>qt("/api/v1/orders/conditional",e),cancelConditional:(e)=>`/api/v1/orders/conditional/${ct(e)}`,getConditional:(e)=>`/api/v1/orders/conditional/${ct(e)}`},delegatedAgents:{list:()=>"/api/v1/delegated-agents",owners:()=>"/api/v1/delegated-agents/owners",byId:(e)=>`/api/v1/delegated-agents/${ct(e)}`,sessions:()=>"/api/v1/delegated-agents/sessions"},withdrawals:{initiate:()=>"/api/v1/withdrawals",byIndex:(e)=>`/api/v1/withdrawals/${ct(String(e))}`,list:(e)=>qt("/api/v1/withdrawals",e)},market:{listTradingPairs:(e)=>qt("/api/v1/market/pairs",e),getTradingPair:(e)=>`/api/v1/market/pairs/${ct(e)}`,getCandles:(e,t,r)=>qt(`/api/v1/market/pairs/charts/candlestick/${ct(e)}/${ct(t)}`,r),getMarketMetadata:(e)=>`/api/v1/market/pairs/${ct(e)}/metadata`,getPerpMarketConfig:(e)=>`/api/v1/market/pairs/${ct(e)}/perp/config`,getPerpMarketSummary:(e)=>`/api/v1/market/pairs/${ct(e)}/perp/summary`,getMarkPrice:(e)=>`/api/v1/market/pairs/${ct(e)}/mark-price`,getIndexPrice:(e)=>`/api/v1/market/pairs/${ct(e)}/index-price`,getFundingState:(e)=>`/api/v1/market/pairs/${ct(e)}/funding`,listFundingHistory:(e,t)=>qt(`/api/v1/market/pairs/${ct(e)}/funding/history`,t),listAllFundingHistory:(e)=>qt("/api/v1/market/funding/history",e),getOpenInterest:(e)=>`/api/v1/market/pairs/${ct(e)}/open-interest`,getScreener:(e)=>qt("/api/v1/market/screener",e),getMarketStats:()=>"/api/v1/market/stats"},orderbook:{get:(e,t)=>qt(`/api/v1/orderbook/${ct(e)}`,t)},trades:{publicByPair:(e,t)=>qt(`/api/v1/trades/${ct(e)}`,t),byId:(e)=>`/api/v1/trades/by-id/${ct(e)}`,user:(e)=>qt("/api/v1/accounts/trades",e)},applications:{orders:(e)=>qt("/api/v1/applications/orders",e),users:(e)=>qt("/api/v1/applications/users",e),movements:(e)=>qt("/api/v1/applications/movements",e),balances:(e)=>qt("/api/v1/applications/balances",e),stats:(e)=>qt("/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/${ct(e)}/limits`,limit:(e,t)=>`/api/v1/accounts/sub-accounts/${ct(e)}/limits/${ct(t)}`},faucet:{mint:()=>"/api/v1/faucet/mint",info:()=>"/api/v1/faucet/info"},sweeper:{register:()=>"/api/v1/sweeper/register"},whitelist:{submit:()=>"/api/v1/whitelist"},positions:{list:(e)=>qt("/api/v1/positions",e),get:(e)=>`/api/v1/positions/${ct(e)}`,close:(e)=>`/api/v1/positions/${ct(e)}/close`,batchCloseAll:()=>"/api/v1/positions/batch-close-all",risk:(e)=>`/api/v1/positions/${ct(e)}/risk`,attachTpSl:(e)=>`/api/v1/positions/${ct(e)}/tp-sl`,history:(e)=>qt("/api/v1/positions/history",e),pnlHistory:(e,t)=>qt(`/api/v1/positions/${ct(e)}/pnl/history`,t)},marginAccounts:{list:(e)=>qt("/api/v1/margin/accounts",e),parentSummary:(e)=>qt("/api/v1/margin/parent-margin-account",e),summary:(e,t)=>qt(`/api/v1/margin/accounts/${ct(e)}`,t),availableCollateral:(e)=>qt("/api/v1/margin/collateral/available",e),transferIn:(e)=>`/api/v1/margin/accounts/${ct(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/${ct(e)}/collateral/transfer-out`,transferOutParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-out",movements:(e,t)=>qt(`/api/v1/margin/accounts/${ct(e)}/movements`,t),parentMovements:(e)=>qt("/api/v1/margin/parent-margin-account/movements",e),simulateParentMarginOrderRisk:()=>"/api/v1/margin/parent-margin-account/simulate-order-risk",simulateOrderRisk:(e)=>`/api/v1/margin/accounts/${ct(e)}/simulate-order-risk`,simulateRiskBucketOrderRisk:()=>"/api/v1/margin/risk-buckets/simulate-order-risk"},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 C1 extends Ke{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 await this.makeBackendRequest(de.applications.orders(e))}async listApplicationUsers(e){return await this.makeBackendRequest(de.applications.users(e))}async listApplicationMovements(e){return await this.makeBackendRequest(de.applications.movements(e))}async listApplicationBalances(e){return await this.makeBackendRequest(de.applications.balances(e))}async getApplicationStats(e){return await this.makeBackendRequest(de.applications.stats(e))}}class FO extends Ke{async upsertDelegatedAgent(e){return this.makeAuthenticatedRequest(de.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})})}async listDelegatedAgents(){return this.makeAuthenticatedRequest(de.delegatedAgents.list())}async listDelegatedOwners(){return this.makeAuthenticatedRequest(de.delegatedAgents.owners())}async revokeDelegatedAgent(e){return this.makeAuthenticatedRequest(de.delegatedAgents.byId(e),{method:"DELETE"})}async createDelegatedSession(e){return this.makeAuthenticatedRequest(de.delegatedAgents.sessions(),{method:"POST",body:JSON.stringify({ownerUserId:e.ownerUserId,sessionPublicKey:e.sessionPublicKey})})}}class z1 extends Ke{async mint(e){return await this.makeAuthenticatedRequest(de.faucet.mint(),{method:"POST",body:JSON.stringify({turnstileToken:e.turnstileToken})})}async getInfo(){return await this.makeAuthenticatedRequest(de.faucet.info(),{method:"GET"})}}var qO=f.object({tradingPairId:f.string().trim().min(1,"Trading pair ID is required and cannot be empty"),side:f.enum(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:f.string().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:f.string().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:f.enum(["LIMIT","MARKET"]).optional(),slippageToleranceBps:f.number().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:f.ZodIssueCode.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),u0e=f.object({applicationName:f.string().nullable().optional(),applicationTakerFee:f.string(),applicationTakerFeeBps:f.number(),buyOrderLockAmount:f.string().nullable().optional(),makerTotalReceipt:f.string(),monacoMakerRebate:f.string(),monacoMakerRebateBps:f.number(),monacoMakerRebateBpsExact:f.string(),monacoTakerFee:f.string(),monacoTakerFeeBps:f.number(),monacoTakerFeeBpsExact:f.string(),notional:f.string(),takerTotalPayment:f.string(),totalTakerFees:f.string(),maxQuantity:f.string().nullable(),maxQuantityRaw:f.string().nullable(),slippageToleranceBps:f.number().nullable()}),HO=f.object({tradingPairId:f.string().trim().min(1,"Trading pair ID is required and cannot be empty")}),UV=f.object({tierLevel:f.number().int(),minVolumeThreshold:f.string(),makerFeeBps:f.string(),takerFeeBps:f.string()}),l0e=f.object({currentTierLevel:f.number().int(),weightedVolume14d:f.string(),spotVolume14d:f.string(),perpVolume14d:f.string(),volumeToNextTier:f.string().nullable().optional(),nextTierLevel:f.number().int().nullable().optional(),feeSchedule:f.array(UV)});var LV=f.object({token:f.string(),available:f.string()}),d0e=f.object({balances:f.array(LV)}),p0e=f.object({code:f.string(),createdAt:f.string(),customCode:f.string(),isCustom:f.boolean(),display:f.string()}),jV=f.enum(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),f0e=f.object({available:f.boolean(),reason:f.preprocess((e)=>e===""||e===null?void 0:e,jV.optional())}),GO=f.object({code:f.string().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")}),m0e=f.object({code:f.string()}),VO=f.object({token:f.string().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:f.string().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),h0e=f.object({rewardsBalance:f.string(),tradingBalance:f.string()});var N1=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];class FV extends Error{issues;constructor(e){let t=e.issues.map((r)=>{let o=r.path.join(".");return`${o?`${o}: `:""}${r.message}`});super(`Validation failed:
145
145
  - ${t.join(`
146
- - `)}`);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 Ee(e,t){let r=e.safeParse(t);if(!r.success)throw new FV(r.error);return r.data}var ly=f.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),U1=f.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),ZO=f.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),dy=f.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),qV=f.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),WO=f.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),Kp=f.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),wt=f.string().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"}),Ae=f.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),py=f.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),HV=f.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),fy=f.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),M1=f.object({triggerPrice:wt,orderType:Kp,limitPrice:wt.optional(),timeInForce:WO.optional(),slippageToleranceBps:fy.optional(),expiresAt:py.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"]}),B1=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0,KO=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),GV=f.object({tradingPairId:Ae,side:ly,quantity:wt,price:wt,options:f.object({tradingMode:U1.optional(),useMasterBalance:f.boolean().optional(),expirationDate:py.optional(),timeInForce:qV.optional(),marginAccountId:Ae.optional(),marginMode:ZO.optional(),riskBucketId:Ae.optional(),riskBucketCollateral:wt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:dy.optional(),leverage:wt.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().optional(),takeProfit:M1.optional(),stopLoss:M1.optional()}).optional()}).refine((e)=>KO(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)=>!B1(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!B1(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss 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"]}),VV=f.object({tradingPairId:Ae,side:ly,quantity:wt,options:f.object({tradingMode:U1.optional(),slippageTolerance:HV,marginAccountId:Ae.optional(),marginMode:ZO.optional(),riskBucketId:Ae.optional(),riskBucketCollateral:wt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:dy.optional(),leverage:wt.optional(),reduceOnly:f.boolean().optional(),takeProfit:M1.optional(),stopLoss:M1.optional()}).optional()}).refine((e)=>KO(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)=>!B1(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!B1(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss 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"]}),ZV=f.object({orderId:Ae}),WV=f.object({orderId:Ae,newOrder:f.object({price:wt.optional(),quantity:wt.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()})}),KV=f.object({status:f.union([f.enum(N1),f.array(f.enum(N1)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:Ae.optional(),tradingMode:U1.optional(),marginAccountId:Ae.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),BRt=f.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),DRt=f.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),g0e=f.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),URt=f.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),JO=f.object({conditionalOrderId:Ae}),JV=f.object({marginAccountId:Ae.optional(),tradingPairId:Ae.optional(),state:g0e.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),y0e=f.object({tradingPairId:Ae,orderType:Kp,side:ly,price:wt.optional(),quantity:wt,tradingMode:U1.optional(),slippageTolerance:HV,useMasterBalance:f.boolean().optional(),expirationDate:py.optional(),timeInForce:qV.optional(),marginAccountId:Ae.optional(),marginMode:ZO.optional(),riskBucketId:Ae.optional(),riskBucketCollateral:wt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:dy.optional(),leverage:wt.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().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)=>KO(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"]}),D1=100,YV=f.object({orders:f.array(y0e).min(1,"At least one order is required").max(D1,`At most ${D1} orders per batch request`)}),b0e=f.object({orderId:Ae,price:wt.optional(),quantity:wt.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),QV=f.object({orders:f.array(b0e).min(1,"At least one order is required").max(D1,`At most ${D1} orders per batch request`)});var YO=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),XV=YO.extend({state:f.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:Ae.optional()}),eZ=f.object({marginAccountId:Ae,tradingPairId:Ae.optional()}),tZ=f.object({tradingPairId:Ae.optional()}).optional(),rZ=f.object({asset:f.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),x0e=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:wt,tradingPairId:Ae.optional(),strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:f.enum(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),L1=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:wt}),v0e=f.object({tradingPairId:Ae,strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional()}),_0e=f.array(Ae).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),nZ=v0e.extend({marginMode:f.literal("ISOLATED").optional(),selectedTradingPairIds:f.never().optional()}),oZ=f.object({marginMode:f.literal("CROSS"),selectedTradingPairIds:_0e,strategyKey:f.never().optional()}),w0e=oZ.extend({tradingPairId:f.never().optional()}),QO=f.object({marginAccountId:Ae,request:x0e}),iZ=f.object({request:L1}),sZ=f.object({request:f.union([L1.merge(nZ).strict(),L1.merge(w0e).strict()])}),aZ=f.object({request:L1}),cZ=YO.extend({marginAccountId:Ae,movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}),uZ=YO.extend({movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),XO=f.object({tradingPairId:Ae,side:ly,positionSide:dy.optional(),orderType:Kp,price:wt.optional(),quantity:wt,leverage:wt.optional(),reduceOnly:f.boolean().optional()}),e5=(e,t)=>{if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:f.ZodIssueCode.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:f.ZodIssueCode.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},lZ=XO.strict().superRefine(e5),S0e=XO.merge(nZ).strict().superRefine(e5),T0e=XO.merge(oZ).strict().superRefine(e5).refine((e)=>e.selectedTradingPairIds.includes(e.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),E0e=f.union([S0e,T0e]),dZ=f.object({marginAccountId:Ae,request:lZ}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),pZ=f.object({request:lZ}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),fZ=f.object({request:E0e}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var mZ=f.enum(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),I0e=31536000000,P0e=946684800000,j1=f.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(P0e,{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()+I0e,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),VRt=f.object({tradingPairId:Ae,interval:mZ,startTime:j1,endTime:j1}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),ZRt=f.string().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")'}),k0e=f.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),hZ=f.object({tradingPairId:Ae,interval:mZ,startTime:j1.optional(),endTime:j1.optional(),limit:k0e}).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 WRt=f.object({tradingPairId:Ae}),KRt=f.object({query:f.string().min(1,"Search query cannot be empty").optional(),pageSize:f.number().int().min(1).max(100).optional(),page:f.number().int().min(1).optional()}),Bi=f.object({tradingPairId:Ae});var yZ=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),A0e=f.enum(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),$0e=f.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),my=f.object({positionId:Ae}),bZ=yZ.extend({marginAccountId:Ae.optional(),tradingPairId:Ae.optional(),status:A0e.optional()}),xZ=my,vZ=my.extend({request:f.object({closeType:$0e,limitPrice:wt.optional(),slippageToleranceBps:fy.optional(),quantity:wt.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"]}),_Z=f.object({tradingPairId:Ae.optional(),slippageToleranceBps:fy.optional()}),wZ=my,gZ=f.object({triggerPrice:wt,orderType:Kp,limitPrice:wt.optional(),quantity:wt.optional(),closePosition:f.boolean().optional(),timeInForce:WO.optional(),slippageToleranceBps:fy.optional(),expiresAt:py.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"]}),SZ=my.extend({request:f.object({takeProfit:gZ.optional(),stopLoss:gZ.optional(),oco:f.boolean().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss 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"]})}),TZ=yZ.extend({positionId:Ae.optional(),marginAccountId:Ae.optional(),tradingPairId:Ae.optional(),reductionOnly:f.boolean().optional()}),R0e=f.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),EZ=my.extend({params:f.object({interval:R0e,startTime:f.number().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:f.number().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 O0e=f.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),C0e=f.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),IZ=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),entryType:O0e.optional(),transactionType:C0e.optional(),assetId:Ae.optional()}),PZ=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().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:Ae.optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),kZ=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),tradingPairId:Ae.optional(),positionId:Ae.optional(),marginAccountId:Ae.optional()});var i2t=f.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),t5=f.union([f.string().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),f.bigint().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),AZ=f.object({assetId:Ae,amount:t5,autoWait:f.boolean().optional()}),$Z=f.object({assetId:Ae,amount:t5,autoWait:f.boolean().optional(),target:f.enum(["spot","margin"]).optional()}),RZ=f.object({assetId:Ae,amount:t5,destination:f.string().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:f.boolean().optional(),source:f.enum(["spot","margin"]).optional()}),s2t=f.object({assetId:Ae});class F1 extends Ke{async simulateFees(e){let t=Ee(qO,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 o=`/api/v1/fees/simulate?${r.toString()}`;return await this.makeAuthenticatedRequest(o,{method:"GET"})}async getMyFeeTier(e){let t=Ee(HO,e),r=new URLSearchParams;r.append("tradingPairId",t.tradingPairId);let o=`/api/v1/fees/tier?${r.toString()}`;return await this.makeAuthenticatedRequest(o,{method:"GET"})}}class q1 extends Ke{async listMarginAccounts(e){if(e)Ee(XV,e);return await this.makeAuthenticatedRequest(de.marginAccounts.list(e?{page:e.page,pageSize:e.pageSize,state:e.state,tradingPairId:e.tradingPairId}:void 0))}async getMarginAccountSummary(e,t){return Ee(eZ,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(de.marginAccounts.summary(e,{tradingPairId:t?.tradingPairId}))}async getParentMarginAccountSummary(e){return Ee(tZ,e),await this.makeAuthenticatedRequest(de.marginAccounts.parentSummary({tradingPairId:e?.tradingPairId}))}async getAvailableCollateral(e){return Ee(rZ,e),await this.makeAuthenticatedRequest(de.marginAccounts.availableCollateral(e))}async transferCollateralToMarginAccount(e,t){return Ee(QO,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(de.marginAccounts.transferIn(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey})})}async transferCollateralToParentMarginAccount(e){return Ee(iZ,{request:e}),await this.makeAuthenticatedRequest(de.marginAccounts.transferInParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async transferCollateralToRiskBucket(e){return Ee(sZ,{request:e}),await this.makeAuthenticatedRequest(de.marginAccounts.transferInRiskBucket(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount,tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,selectedTradingPairIds:e.selectedTradingPairIds})})}async transferCollateralFromMarginAccount(e,t){return Ee(QO,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(de.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 Ee(aZ,{request:e}),await this.makeAuthenticatedRequest(de.marginAccounts.transferOutParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async getMarginAccountMovements(e,t){return Ee(cZ,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(de.marginAccounts.movements(e,t))}async getParentMarginAccountMovements(e){return Ee(uZ,e),await this.makeAuthenticatedRequest(de.marginAccounts.parentMovements(e))}async simulateOrderRisk(e,t){return Ee(dZ,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(de.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})})}async simulateParentMarginOrderRisk(e){return Ee(pZ,{request:e}),await this.makeAuthenticatedRequest(de.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})})}async simulateRiskBucketOrderRisk(e){return Ee(fZ,{request:e}),await this.makeAuthenticatedRequest(de.marginAccounts.simulateRiskBucketOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,selectedTradingPairIds:e.selectedTradingPairIds,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly})})}}class H1 extends Ke{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(),o=r?`/api/v1/market/pairs?${r}`:"/api/v1/market/pairs";return await this.makePublicRequest(o)}async getTradingPair(e){return Ee(Bi,{tradingPairId:e}),(await this.makePublicRequest(de.market.getTradingPair(e))).tradingPair}async getTradingPairBySymbol(e,t){return(await this.getPaginatedTradingPairs({pageSize:100,marketType:t})).tradingPairs.find((o)=>o.symbol===e)}async getCandlesticks(e,t,r){Ee(hZ,{tradingPairId:e,interval:t,startTime:r?.startTime,endTime:r?.endTime,limit:r?.limit});let o=new URLSearchParams;if(r?.startTime!==void 0)o.append("startTime",r.startTime.toString());if(r?.endTime!==void 0)o.append("endTime",r.endTime.toString());if(r?.limit!==void 0)o.append("limit",r.limit.toString());let n=o.toString(),i=n?`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}?${n}`:`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}`;return(await this.makePublicRequest(i)).data||[]}async getMarketMetadata(e){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.getMarketMetadata(e))}async getPerpMarketConfig(e){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.getPerpMarketConfig(e))}async getPerpMarketSummary(e){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.getPerpMarketSummary(e))}async getMarkPrice(e){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.getMarkPrice(e))}async getIndexPrice(e){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.getIndexPrice(e))}async getFundingState(e){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.getFundingState(e))}async listFundingHistory(e,t){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.listFundingHistory(e,t))}async listAllFundingHistory(e){return await this.makePublicRequest(de.market.listAllFundingHistory(e))}async getOpenInterest(e){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.getOpenInterest(e))}async getScreener(e){return await this.makePublicRequest(de.market.getScreener(e))}async getMarketStats(){return await this.makePublicRequest(de.market.getMarketStats())}}class G1 extends Ke{async getOrderbook(e,t={}){let{depth:r=10,tradingMode:o,magnitude:n,denomination:i}=t,s=new URLSearchParams;if(s.set("levels",String(r)),o)s.set("tradingMode",o);if(n!==void 0)s.set("magnitude",String(n));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 V1 extends Ke{async getMyTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me",{method:"GET"})}async setTraderCode(e){let t=Ee(GO,{code:e});return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me/custom",{method:"PUT",body:JSON.stringify({code:t.code})})}async clearTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me/custom",{method:"DELETE"})}async checkTraderCodeAvailability(e){let t=new URLSearchParams({code:e.trim()}).toString(),r=await this.makePublicRequest(`/api/v1/pitpass/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/pitpass/codes/${t}`,{method:"GET"})}async getRewardsBalance(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/balance",{method:"GET"})}async transferRewards(e){let t=Ee(VO,e);return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/transfer",{method:"POST",body:JSON.stringify({token:t.token,amount:t.amount})})}}var hy="/api/v1/accounts/me/portfolio";function Z1(e,t){if(!t?.period)return e;return`${e}?${new URLSearchParams({period:t.period})}`}class W1 extends Ke{async getSummary(e){return await this.makeAuthenticatedRequest(Z1(`${hy}/summary`,e))}async getPerformance(e){return await this.makeAuthenticatedRequest(Z1(`${hy}/performance`,e))}async getRealizedPnl(e){return await this.makeAuthenticatedRequest(Z1(`${hy}/realized-pnl`,e))}async getAssets(e){return await this.makeAuthenticatedRequest(Z1(`${hy}/assets`,e))}async getMargin(){return await this.makeAuthenticatedRequest(`${hy}/margin`)}}class K1 extends Ke{async listPositions(e){if(e)Ee(bZ,e);return await this.makeAuthenticatedRequest(de.positions.list(e))}async getPosition(e){return Ee(xZ,{positionId:e}),await this.makeAuthenticatedRequest(de.positions.get(e))}async closePosition(e,t){return Ee(vZ,{positionId:e,request:t}),await this.makeAuthenticatedRequest(de.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)Ee(_Z,e);return await this.makeAuthenticatedRequest(de.positions.batchCloseAll(),{method:"POST",body:JSON.stringify({tradingPairId:e?.tradingPairId,slippageToleranceBps:e?.slippageToleranceBps})})}async getPositionRisk(e){return Ee(wZ,{positionId:e}),await this.makeAuthenticatedRequest(de.positions.risk(e))}async attachPositionTpSl(e,t){return Ee(SZ,{positionId:e,request:t}),await this.makeAuthenticatedRequest(de.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,oco:t.oco})})}async listPositionHistory(e){if(e)Ee(TZ,e);return await this.makeAuthenticatedRequest(de.positions.history(e))}async getPositionPnlHistory(e,t){return Ee(EZ,{positionId:e,params:t}),await this.makeAuthenticatedRequest(de.positions.pnlHistory(e,t))}}class r5 extends Ke{async getProfile(){return await this.makeAuthenticatedRequest("/api/v1/accounts/me")}async getPaginatedUserMovements(e){if(e)Ee(IZ,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?.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(),o=r?`/api/v1/accounts/movements?${r}`:"/api/v1/accounts/movements";return await this.makeAuthenticatedRequest(o)}async getUserBalances(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());let r=t.toString(),o=r?`/api/v1/accounts/balances?${r}`:"/api/v1/accounts/balances";return await this.makeAuthenticatedRequest(o)}async getUserBalanceByAssetId(e){if(!e||e.trim()==="")throw new or("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)Ee(PZ,e);let t=e?.page!==void 0&&e?.pageToken===void 0,r=new URLSearchParams;if(t&&e?.page!==void 0)r.append("page",e.page.toString());if(e?.pageSize!==void 0)r.append("pageSize",e.pageSize.toString());if(e?.tradingPairId!==void 0)r.append("tradingPairId",e.tradingPairId);if(!t)r.append("pageToken",e?.pageToken??"");let o=r.toString(),n=o?`/api/v1/accounts/trades?${o}`:"/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)Ee(kZ,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?.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(),o=r?`/api/v1/accounts/funding-payments?${r}`:"/api/v1/accounts/funding-payments";return await this.makeAuthenticatedRequest(o)}}class J1 extends Ke{async getPulse(){return await this.makePublicRequest("/api/v1/pulse",{method:"GET"})}}class Y1 extends Ke{async list(){return await this.makeAuthenticatedRequest(de.subAccounts.list())}async createLimit(e){return await this.makeAuthenticatedRequest(de.subAccounts.createLimit(),{method:"POST",body:JSON.stringify(e)})}async getLimits(e){return await this.makeAuthenticatedRequest(de.subAccounts.getLimits(e))}async updateLimit(e,t,r){return await this.makeAuthenticatedRequest(de.subAccounts.limit(e,t),{method:"PUT",body:JSON.stringify(r)})}async deleteLimit(e,t){await this.makeAuthenticatedRequest(de.subAccounts.limit(e,t),{method:"DELETE"})}}class Q1 extends Ke{async register(e){return await this.makePublicRequest(de.sweeper.register(),{method:"POST",body:JSON.stringify(e)})}}function OZ(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 n5 extends Ke{async getTrades(e,t={}){let{page:r=1}=t,o=t.pageSize!=null&&t.pageSize>0?Math.min(t.pageSize,100):25,n=new URLSearchParams;if(r>1)n.set("page",String(r));return n.set("pageSize",String(o)),(await this.makePublicRequest(`/api/v1/trades/${encodeURIComponent(e)}?${n.toString()}`)).trades.map(OZ)}async getTradeById(e){let t=await this.makePublicRequest(de.trades.byId(e));return OZ(t)}}function X1(e){if(!e)return;return{triggerPrice:e.triggerPrice,orderType:e.orderType,limitPrice:e.limitPrice,timeInForce:e.timeInForce,slippageToleranceBps:e.slippageToleranceBps,expiresAt:e.expiresAt}}class eS extends Ke{async placeLimitOrder(e,t,r,o,n){Ee(GV,{tradingPairId:e,side:t,quantity:r,price:o,options:n});let i={tradingPairId:e,orderType:"LIMIT",side:t,price:o,quantity:r,tradingMode:n?.tradingMode||"SPOT",useMasterBalance:n?.useMasterBalance,expirationDate:n?.expirationDate,timeInForce:n?.timeInForce,marginAccountId:n?.marginAccountId,marginMode:n?.marginMode,riskBucketId:n?.riskBucketId,riskBucketCollateral:n?.riskBucketCollateral,strategyKey:n?.strategyKey,positionSide:n?.positionSide,leverage:n?.leverage,reduceOnly:n?.reduceOnly,postOnly:n?.postOnly,takeProfit:X1(n?.takeProfit),stopLoss:X1(n?.stopLoss)};return await this.makeAuthenticatedRequest(de.orders.create(),{method:"POST",body:JSON.stringify(i)})}async placeMarketOrder(e,t,r,o){Ee(VV,{tradingPairId:e,side:t,quantity:r,options:o});let n={tradingPairId:e,orderType:"MARKET",side:t,slippageToleranceBps:o?.slippageTolerance!==void 0?Math.round(o.slippageTolerance*1e4):void 0,price:null,quantity:r,tradingMode:o?.tradingMode||"SPOT",marginAccountId:o?.marginAccountId,marginMode:o?.marginMode,riskBucketId:o?.riskBucketId,riskBucketCollateral:o?.riskBucketCollateral,strategyKey:o?.strategyKey,positionSide:o?.positionSide,leverage:o?.leverage,reduceOnly:o?.reduceOnly,takeProfit:X1(o?.takeProfit),stopLoss:X1(o?.stopLoss)};return await this.makeAuthenticatedRequest(de.orders.create(),{method:"POST",body:JSON.stringify(n)})}async cancelOrder(e){Ee(ZV,{orderId:e});let t={orderId:e};return await this.makeAuthenticatedRequest(de.orders.cancel(),{method:"POST",body:JSON.stringify(t)})}async cancelConditionalOrder(e){return Ee(JO,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(de.orders.cancelConditional(e),{method:"DELETE"})}async getConditionalOrder(e){return Ee(JO,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(de.orders.getConditional(e),{method:"GET"})}async listConditionalOrders(e){if(e)Ee(JV,e);let{page:t=1,pageSize:r=20,marginAccountId:o,tradingPairId:n,state:i}=e||{};return await this.makeAuthenticatedRequest(de.orders.listConditional({page:t,pageSize:Math.min(Math.max(r,1),100),marginAccountId:o,tradingPairId:n,state:i}),{method:"GET"})}async batchCancel(e){if(!e||e.length===0)throw Error("orderIds is required and must not be empty");return this.makeAuthenticatedRequest(de.orders.batchCancel(),{method:"POST",body:JSON.stringify({orderIds:e})})}async batchCancelAll(e){let t=e?de.orders.batchCancelAllByPair(e):de.orders.batchCancelAll();return this.makeAuthenticatedRequest(t,{method:"POST"})}async replaceOrder(e,t){Ee(WV,{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;return await this.makeAuthenticatedRequest(de.orders.replace(e),{method:"PUT",body:JSON.stringify(r)})}async batchCreate(e){Ee(YV,{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}))};return this.makeAuthenticatedRequest(de.orders.batchCreate(),{method:"POST",body:JSON.stringify(t)})}async batchReplace(e){Ee(QV,{orders:e});let t={orders:e.map((r)=>({orderId:r.orderId,price:r.price,quantity:r.quantity,useMasterBalance:r.useMasterBalance,postOnly:r.postOnly}))};return this.makeAuthenticatedRequest(de.orders.batchReplace(),{method:"POST",body:JSON.stringify(t)})}async getPaginatedOrders(e){if(e)Ee(KV,e);let{page:t,pageSize:r=10,status:o,tradingPairId:n,tradingMode:i,marginAccountId:s,pageToken:a}=e||{},c=r>0?r:10,u=t!==void 0&&a===void 0,d=Math.min(c,u?100:1000),p=new URLSearchParams;if(u){let y=t>0?t:1;p.append("page",y.toString())}p.append("pageSize",d.toString());let m=typeof o==="string"?o:o?.join(",");if(m)p.append("status",m);if(n)p.append("tradingPairId",n);if(i)p.append("tradingMode",i);if(s)p.append("marginAccountId",s);if(!u)p.append("pageToken",a??"");let h=`/api/v1/orders?${p.toString()}`;return await this.makeAuthenticatedRequest(h,{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(de.orders.get(e),{method:"GET"}),status:"SUCCESS"}}}var o5=[{inputs:[{internalType:"address",name:"rollup_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"NativeTransferFailed",type:"error"},{inputs:[],name:"NothingToSweep",type:"error"},{inputs:[],name:"OnlyClone",type:"error"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"SafeERC20FailedOperation",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:"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"},{inputs:[],name:"config",outputs:[{internalType:"address",name:"user",type:"address"},{internalType:"string",name:"applicationId",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"rollup",outputs:[{internalType:"contract IRollup",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"nonpayable",type:"function"}];var i5=[{inputs:[{internalType:"address",name:"rollup_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"CloneArgumentsTooLong",type:"error"},{inputs:[],name:"Create2EmptyBytecode",type:"error"},{inputs:[],name:"FailedDeployment",type:"error"},{inputs:[{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{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"}],name:"SweeperDeployed",type:"event"},{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:[],name:"implementation",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",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:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"rollup",outputs:[{internalType:"contract IRollup",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:"nonpayable",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"}];var s5=[{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 b5t=new Uint8Array(32);var a5={vault:s5,sweeper:o5,sweeperFactory:i5};var z0e=5000,N0e=300000,M0e=(e)=>new Promise((t)=>setTimeout(t,e));function CZ(e,t){return t==="margin"?JSON.stringify({clientId:e,depositTarget:"MARGIN"}):e}class tS extends Ke{publicClient;chain;applicationsAPI;profileAPI;walletClient;constructor(e,t,r,o,n,i){super(i);this.publicClient=e,this.chain=r,this.walletClient=t,this.applicationsAPI=o,this.profileAPI=n}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;try{t=(await this.profileAPI.getUserBalanceByAssetId(e)).token}catch(o){if(o instanceof or){if(o.statusCode===404)throw new _s(`Asset ID '${e}' does not exist`,{revertReason:"ASSET_NOT_FOUND",cause:o});throw new _s(`Failed to resolve asset ID '${e}': ${o.retryable?"Network error occurred":"API request failed"}`,{revertReason:o.retryable?"NETWORK_ERROR":"API_ERROR",cause:o})}throw new _s(`Failed to resolve asset ID '${e}': Unexpected error`,{revertReason:"UNKNOWN_ERROR",cause:o instanceof Error?o:void 0})}return{tokenAddress:t,isNativeToken:t===_n}}async approve(e,t,r=!0){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");Ee(AZ,{assetId:e,amount:t,autoWait:r});let o=await this.getVaultAddress(),{tokenAddress:n}=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:n,abi:nw,functionName:"approve",args:[o,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,o="spot"){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");Ee($Z,{assetId:e,amount:t,autoWait:r,target:o});let n=await this.getVaultAddress(),i=await this.getClientId(),s=CZ(i,o),{tokenAddress:a,isNativeToken:c}=await this.resolveAsset(e);if(!c){if(await this.needsApproval(e,t))throw new _s(`Approval required before deposit. Please invoke approve() first for asset ${e} (token address: ${a}).`,{revertReason:"APPROVAL_REQUIRED"})}let u=this.walletClient.account;if(!u)throw new Bt("No account available in wallet client","account");let d;if(c)d=await this.walletClient.writeContract({address:n,abi:a5.vault,functionName:"depositNative",args:[u.address,s],account:u,chain:this.chain,value:t});else d=await this.walletClient.writeContract({address:n,abi:a5.vault,functionName:"depositERC20",args:[u.address,s,a,t],account:u,chain:this.chain});let p=u.getNonce?await u.getNonce():0n,m={hash:d,status:"pending",nonce:p};return await this.waitForTransaction(m,r)}async pollWithdrawalCalldata(e,t){let r=t?.pollIntervalMs??z0e,o=t?.timeoutMs??N0e,n=Date.now()+o;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 or&&(i.statusCode===404||i.statusCode===409)))throw i}if(Date.now()+r>n)return null;await M0e(r)}}async withdraw(e,t,r=!0,o,n){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 o==="string"?o:"spot",c=typeof o==="string"?n:o;Ee(RZ,{assetId:e,amount:t,destination:s,autoWait:r,source:a});let{withdrawalIndex:u}=await this.makeAuthenticatedRequest("/api/v1/withdrawals",{method:"POST",body:JSON.stringify({assetId:e,amount:t.toString(),destination:s,source:a})});if(!r)return{withdrawalIndex:u,status:"awaiting_proof"};let d=await this.pollWithdrawalCalldata(u,c);if(!d)return{withdrawalIndex:u,status:"awaiting_proof"};let{vaultAddress:p,calldata:m}=d,h;try{h=await this.walletClient.sendTransaction({to:p,data:m,account:i,chain:this.chain})}catch(v){throw new _s(`Failed to submit executeWithdrawal for withdrawal ${u}: ${v instanceof Error?v.message:"unknown error"}`,{cause:v instanceof Error?v:void 0})}let y=i.getNonce?await i.getNonce():0n,x={hash:h,status:"pending",nonce:y};return{...await this.waitForTransaction(x,r),withdrawalIndex:u}}async retryWithdrawal(e,t=!0,r){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");let o=this.walletClient.account;if(!o)throw new Bt("No account available in wallet client","account");let n=await this.pollWithdrawalCalldata(e,r);if(!n)return{withdrawalIndex:e,status:"awaiting_proof"};let{vaultAddress:i,calldata:s}=n,a;try{a=await this.walletClient.sendTransaction({to:i,data:s,account:o,chain:this.chain})}catch(p){throw new _s(`Failed to resubmit executeWithdrawal for withdrawal ${e}: ${p instanceof Error?p.message:"unknown error"}`,{cause:p instanceof Error?p:void 0})}let c=o.getNonce?await o.getNonce():0n,u={hash:a,status:"pending",nonce:c};return{...await this.waitForTransaction(u,t),withdrawalIndex:e}}async getBalance(e){throw new or("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(),o=(await this.walletClient.getAddresses())[0];if(!o)throw new Bt("No account found in wallet client.","walletClient");let{tokenAddress:n}=await this.resolveAsset(e);return await this.publicClient.readContract({address:n,abi:nw,functionName:"allowance",args:[o,t]})}async needsApproval(e,t){return await this.getAllowance(e)<t}async waitForTransaction(e,t=!0,r={}){if(!t)return e;let{confirmations:o=1,timeout:n=60000}=r;try{let i=await this.publicClient.waitForTransactionReceipt({hash:e.hash,confirmations:o,timeout:n});return{...e,status:i.status==="success"?"confirmed":"failed",receipt:i}}catch{return{...e,status:"failed"}}}}class rS extends Ke{async submit(e){return await this.makePublicRequest(de.whitelist.submit(),{method:"POST",body:JSON.stringify(e)})}}class c5 extends Ke{async initiateWithdrawal(e){return this.makeAuthenticatedRequest(de.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(de.withdrawals.byIndex(e))}async listPendingWithdrawals(e){return this.makeAuthenticatedRequest(de.withdrawals.list({page:e?.page,pageSize:e?.pageSize}))}}class nS extends Ke{chain;walletClient;constructor(e,t,r){super(r);this.chain=t,this.walletClient=e}setWalletClient(e){this.walletClient=e}async authenticate(e,t){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");let r=this.walletClient.account;if(!r)throw new Bt("No account available in wallet client","account");let o=V_(),n={publicKey:Z_(o),privateKey:W_(o)},i=await this.createChallenge(r.address,e,n.publicKey),s=await this.signChallenge(i.message);return await this.verifySignature(r.address,s,i.nonce,e,n,t)}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 o=await this.makePublicRequest("/api/v1/auth/challenge",{method:"POST",body:JSON.stringify({address:e,clientId:t,chainId:this.chain.id,sessionPublicKey:r})});return{nonce:o.nonce,message:o.message,expiresAt:o.expiresAt}}async verifySignature(e,t,r,o,n,i){let s=await this.makePublicRequest("/api/v1/auth/verify",{method:"POST",body:JSON.stringify({address:e,signature:t,nonce:r,clientId:o,chainId:this.chain.id,sessionPublicKey:n.publicKey,...i?{referralCode:i}:{}})});return{sessionPublicKey:n.publicKey,sessionPrivateKey:n.privateKey,expiresAt:s.expiresAt,user:{id:s.user.id,address:s.user.address,username:s.user.username}}}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 B0e=750;function zZ(e,t){try{new URL(e)}catch(r){throw new Bt(`${t} must be a valid URL, got: ${e}`,t)}return e}class l5{auth;delegatedAgents;applications;fees;pitpass;vault;withdrawals;trading;market;marginAccounts;positions;portfolio;subAccounts;faucet;sweeper;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.pitpass.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.whitelist.setSessionKeypair(e),this.pulse.setSessionKeypair(e),this.profile.setSessionKeypair(e),this.orderbook.setSessionKeypair(e),this.trades.setSessionKeypair(e),this.ws.setSessionKeypair(e)}setServerKey(e){this.auth.setServerKey(e),this.delegatedAgents.setServerKey(e),this.applications.setServerKey(e),this.fees.setServerKey(e),this.pitpass.setServerKey(e),this.vault.setServerKey(e),this.withdrawals.setServerKey(e),this.trading.setServerKey(e),this.market.setServerKey(e),this.marginAccounts.setServerKey(e),this.positions.setServerKey(e),this.portfolio.setServerKey(e),this.subAccounts.setServerKey(e),this.faucet.setServerKey(e),this.sweeper.setServerKey(e),this.whitelist.setServerKey(e),this.pulse.setServerKey(e),this.profile.setServerKey(e),this.orderbook.setServerKey(e),this.trades.setServerKey(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(s){throw new Bt(`seiRpcUrl must be a valid URL, got: ${e.seiRpcUrl}`,"seiRpcUrl")}let r=e.wsUrl?zZ(e.wsUrl,"wsUrl"):F$(this.network),o=this.network==="mainnet"?DO:UO;if(this.chain=o,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 n=BO(e.seiRpcUrl);this.publicClient=zO({chain:o,transport:n,pollingInterval:e.pollingInterval??B0e});let i=e.apiUrl?zZ(e.apiUrl,"apiUrl"):j$(this.network);if(e.walletClient){if(e.walletClient.chain?.id!==o.id)throw new Bt(`Wallet client chain mismatch. Expected ${o.id}, got ${e.walletClient.chain?.id}`,"walletClient");this.walletClient=e.walletClient}this.applications=new C1(i),this.market=new H1(i),this.marginAccounts=new q1(i),this.positions=new K1(i),this.portfolio=new W1(i),this.subAccounts=new Y1(i),this.faucet=new z1(i),this.sweeper=new Q1(i),this.whitelist=new rS(i),this.pulse=new J1(i),this.auth=new nS(this.walletClient,this.chain,i),this.delegatedAgents=new FO(i),this.fees=new F1(i),this.pitpass=new V1(i),this.profile=new r5(i),this.vault=new tS(this.publicClient,this.walletClient,this.chain,this.applications,this.profile,i),this.withdrawals=new c5(i),this.trading=new eS(i),this.orderbook=new G1(i),this.trades=new n5(i),this.ws=z$(r,e.ws),this.ws.connect().catch(console.error)}async login(e,t){if(this.authState=await this.auth.authenticate(e),this.propagateSession(this.sessionFromAuthState(this.authState)),t?.connectWebSocket)await this.ws.connect();return this.authState}async loginAsDelegatedOwner(e){if(!this.authState)throw new or("No active agent session to create delegated session",{endpoint:"delegated-agents/sessions",statusCode:u5.StatusCodes.UNAUTHORIZED});let t=V_(),r={publicKey:Z_(t),privateKey:W_(t)},o=await this.delegatedAgents.createDelegatedSession({ownerUserId:e,sessionPublicKey:r.publicKey});return this.authState={sessionPublicKey:r.publicKey,sessionPrivateKey:r.privateKey,expiresAt:o.expiresAt,user:{id:o.ownerUserId,address:o.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 or("No active session to refresh",{endpoint:"auth/refresh",statusCode:u5.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 dg("Wallet client not set","walletClient");if(this.walletClient.account)return this.walletClient.account.address;throw new dg("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 d5(e){return new l5(e)}function ft(e){if(typeof e==="string")return{address:e,type:"json-rpc"};return e}var oS=256,iS;function sS(e=11){if(!iS||oS+e>512){iS="",oS=0;for(let t=0;t<256;t++)iS+=(256+Math.random()*256|0).toString(16).substring(1)}return iS.substring(oS,oS+++e)}function NZ(e){let{batch:t,chain:r,ccipRead:o,dataSuffix:n,key:i="base",name:s="Base Client",type:a="base"}=e,c=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime==="number"?"pending":void 0),u=r?.blockTime??12000,d=Math.min(Math.max(Math.floor(u/2),500),4000),p=e.pollingInterval??d,m=e.cacheTime??p,h=e.account?ft(e.account):void 0,{config:y,request:x,value:S}=e.transport({account:h,chain:r,pollingInterval:p}),v={...y,...S},E={account:h,batch:t,cacheTime:m,ccipRead:o,chain:r,dataSuffix:n,key:i,name:s,pollingInterval:p,request:x,transport:v,type:a,uid:sS(),...c?{experimental_blockTag:c}:{}};function w(_){return(T)=>{let P=T(_);for(let z in E)delete P[z];let O={..._,...P};return Object.assign(O,{extend:w(O)})}}return Object.assign(E,{extend:w(E)})}var MZ={gwei:9,wei:18},BZ={ether:-9,wei:9};function aS(e,t){let r=e.toString(),o=r.startsWith("-");if(o)r=r.slice(1);r=r.padStart(t,"0");let[n,i]=[r.slice(0,r.length-t),r.slice(r.length-t)];return i=i.replace(/(0+)$/,""),`${o?"-":""}${n||"0"}${i?`.${i}`:""}`}function wn(e,t="wei"){return aS(e,BZ[t])}var p5="2.53.1";var f5={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${p5}`};class q extends Error{constructor(e,t={}){let r=(()=>{if(t.cause instanceof q)return t.cause.details;if(t.cause?.message)return t.cause.message;return t.details})(),o=(()=>{if(t.cause instanceof q)return t.cause.docsPath||t.docsPath;return t.docsPath})(),n=f5.getDocsUrl?.({...t,docsPath:o}),i=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...r?[`Details: ${r}`]:[],...f5.version?[`Version: ${f5.version}`]:[]].join(`
146
+ - `)}`);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 Ee(e,t){let r=e.safeParse(t);if(!r.success)throw new FV(r.error);return r.data}var ly=f.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),U1=f.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),ZO=f.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),dy=f.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),qV=f.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),WO=f.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),Kp=f.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),bt=f.string().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"}),Ae=f.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),py=f.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),HV=f.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),fy=f.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),M1=f.object({triggerPrice:bt,orderType:Kp,limitPrice:bt.optional(),quantity:bt.optional(),closePosition:f.boolean().optional(),timeInForce:WO.optional(),slippageToleranceBps:fy.optional(),expiresAt:py.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"]}),B1=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0,KO=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),GV=f.object({tradingPairId:Ae,side:ly,quantity:bt,price:bt,options:f.object({tradingMode:U1.optional(),useMasterBalance:f.boolean().optional(),expirationDate:py.optional(),timeInForce:qV.optional(),marginAccountId:Ae.optional(),marginMode:ZO.optional(),riskBucketId:Ae.optional(),riskBucketCollateral:bt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:dy.optional(),leverage:bt.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().optional(),takeProfit:M1.optional(),stopLoss:M1.optional()}).optional()}).refine((e)=>KO(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)=>!B1(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!B1(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss 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"]}),VV=f.object({tradingPairId:Ae,side:ly,quantity:bt,options:f.object({tradingMode:U1.optional(),slippageTolerance:HV,marginAccountId:Ae.optional(),marginMode:ZO.optional(),riskBucketId:Ae.optional(),riskBucketCollateral:bt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:dy.optional(),leverage:bt.optional(),reduceOnly:f.boolean().optional(),takeProfit:M1.optional(),stopLoss:M1.optional()}).optional()}).refine((e)=>KO(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)=>!B1(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!B1(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss 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"]}),ZV=f.object({orderId:Ae}),WV=f.object({orderId:Ae,newOrder:f.object({price:bt.optional(),quantity:bt.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()})}),KV=f.object({status:f.union([f.enum(N1),f.array(f.enum(N1)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:Ae.optional(),tradingMode:U1.optional(),marginAccountId:Ae.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),BRt=f.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),DRt=f.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),g0e=f.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),URt=f.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),JO=f.object({conditionalOrderId:Ae}),JV=f.object({marginAccountId:Ae.optional(),tradingPairId:Ae.optional(),state:g0e.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),y0e=f.object({tradingPairId:Ae,orderType:Kp,side:ly,price:bt.optional(),quantity:bt,tradingMode:U1.optional(),slippageTolerance:HV,useMasterBalance:f.boolean().optional(),expirationDate:py.optional(),timeInForce:qV.optional(),marginAccountId:Ae.optional(),marginMode:ZO.optional(),riskBucketId:Ae.optional(),riskBucketCollateral:bt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:dy.optional(),leverage:bt.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().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)=>KO(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"]}),D1=100,YV=f.object({orders:f.array(y0e).min(1,"At least one order is required").max(D1,`At most ${D1} orders per batch request`)}),b0e=f.object({orderId:Ae,price:bt.optional(),quantity:bt.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),QV=f.object({orders:f.array(b0e).min(1,"At least one order is required").max(D1,`At most ${D1} orders per batch request`)});var YO=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),XV=YO.extend({state:f.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:Ae.optional()}),eZ=f.object({marginAccountId:Ae,tradingPairId:Ae.optional()}),tZ=f.object({tradingPairId:Ae.optional()}).optional(),rZ=f.object({asset:f.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),x0e=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:bt,tradingPairId:Ae.optional(),strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:f.enum(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),L1=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:bt}),v0e=f.object({tradingPairId:Ae,strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional()}),_0e=f.array(Ae).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),nZ=v0e.extend({marginMode:f.literal("ISOLATED").optional(),selectedTradingPairIds:f.never().optional()}),oZ=f.object({marginMode:f.literal("CROSS"),selectedTradingPairIds:_0e,strategyKey:f.never().optional()}),w0e=oZ.extend({tradingPairId:f.never().optional()}),QO=f.object({marginAccountId:Ae,request:x0e}),iZ=f.object({request:L1}),sZ=f.object({request:f.union([L1.merge(nZ).strict(),L1.merge(w0e).strict()])}),aZ=f.object({request:L1}),cZ=YO.extend({marginAccountId:Ae,movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}),uZ=YO.extend({movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),XO=f.object({tradingPairId:Ae,side:ly,positionSide:dy.optional(),orderType:Kp,price:bt.optional(),quantity:bt,leverage:bt.optional(),reduceOnly:f.boolean().optional()}),e5=(e,t)=>{if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:f.ZodIssueCode.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:f.ZodIssueCode.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},lZ=XO.strict().superRefine(e5),S0e=XO.merge(nZ).strict().superRefine(e5),T0e=XO.merge(oZ).strict().superRefine(e5).refine((e)=>e.selectedTradingPairIds.includes(e.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),E0e=f.union([S0e,T0e]),dZ=f.object({marginAccountId:Ae,request:lZ}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),pZ=f.object({request:lZ}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),fZ=f.object({request:E0e}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var mZ=f.enum(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),I0e=31536000000,P0e=946684800000,j1=f.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(P0e,{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()+I0e,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),VRt=f.object({tradingPairId:Ae,interval:mZ,startTime:j1,endTime:j1}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),ZRt=f.string().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")'}),k0e=f.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),hZ=f.object({tradingPairId:Ae,interval:mZ,startTime:j1.optional(),endTime:j1.optional(),limit:k0e}).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 WRt=f.object({tradingPairId:Ae}),KRt=f.object({query:f.string().min(1,"Search query cannot be empty").optional(),pageSize:f.number().int().min(1).max(100).optional(),page:f.number().int().min(1).optional()}),Bi=f.object({tradingPairId:Ae});var yZ=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),A0e=f.enum(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),$0e=f.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),my=f.object({positionId:Ae}),bZ=yZ.extend({marginAccountId:Ae.optional(),tradingPairId:Ae.optional(),status:A0e.optional()}),xZ=my,vZ=my.extend({request:f.object({closeType:$0e,limitPrice:bt.optional(),slippageToleranceBps:fy.optional(),quantity:bt.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"]}),_Z=f.object({tradingPairId:Ae.optional(),slippageToleranceBps:fy.optional()}),wZ=my,gZ=f.object({triggerPrice:bt,orderType:Kp,limitPrice:bt.optional(),quantity:bt.optional(),closePosition:f.boolean().optional(),timeInForce:WO.optional(),slippageToleranceBps:fy.optional(),expiresAt:py.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"]}),SZ=my.extend({request:f.object({takeProfit:gZ.optional(),stopLoss:gZ.optional(),oco:f.boolean().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss 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"]})}),TZ=yZ.extend({positionId:Ae.optional(),marginAccountId:Ae.optional(),tradingPairId:Ae.optional(),reductionOnly:f.boolean().optional()}),R0e=f.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),EZ=my.extend({params:f.object({interval:R0e,startTime:f.number().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:f.number().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 O0e=f.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),C0e=f.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),IZ=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),entryType:O0e.optional(),transactionType:C0e.optional(),assetId:Ae.optional()}),PZ=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().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:Ae.optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),kZ=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),tradingPairId:Ae.optional(),positionId:Ae.optional(),marginAccountId:Ae.optional()});var i2t=f.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),t5=f.union([f.string().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),f.bigint().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),AZ=f.object({assetId:Ae,amount:t5,autoWait:f.boolean().optional()}),$Z=f.object({assetId:Ae,amount:t5,autoWait:f.boolean().optional(),target:f.enum(["spot","margin"]).optional()}),RZ=f.object({assetId:Ae,amount:t5,destination:f.string().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:f.boolean().optional(),source:f.enum(["spot","margin"]).optional()}),s2t=f.object({assetId:Ae});class F1 extends Ke{async simulateFees(e){let t=Ee(qO,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 o=`/api/v1/fees/simulate?${r.toString()}`;return await this.makeAuthenticatedRequest(o,{method:"GET"})}async getMyFeeTier(e){let t=Ee(HO,e),r=new URLSearchParams;r.append("tradingPairId",t.tradingPairId);let o=`/api/v1/fees/tier?${r.toString()}`;return await this.makeAuthenticatedRequest(o,{method:"GET"})}}class q1 extends Ke{async listMarginAccounts(e){if(e)Ee(XV,e);return await this.makeAuthenticatedRequest(de.marginAccounts.list(e?{page:e.page,pageSize:e.pageSize,state:e.state,tradingPairId:e.tradingPairId}:void 0))}async getMarginAccountSummary(e,t){return Ee(eZ,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(de.marginAccounts.summary(e,{tradingPairId:t?.tradingPairId}))}async getParentMarginAccountSummary(e){return Ee(tZ,e),await this.makeAuthenticatedRequest(de.marginAccounts.parentSummary({tradingPairId:e?.tradingPairId}))}async getAvailableCollateral(e){return Ee(rZ,e),await this.makeAuthenticatedRequest(de.marginAccounts.availableCollateral(e))}async transferCollateralToMarginAccount(e,t){return Ee(QO,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(de.marginAccounts.transferIn(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey})})}async transferCollateralToParentMarginAccount(e){return Ee(iZ,{request:e}),await this.makeAuthenticatedRequest(de.marginAccounts.transferInParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async transferCollateralToRiskBucket(e){return Ee(sZ,{request:e}),await this.makeAuthenticatedRequest(de.marginAccounts.transferInRiskBucket(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount,tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,selectedTradingPairIds:e.selectedTradingPairIds})})}async transferCollateralFromMarginAccount(e,t){return Ee(QO,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(de.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 Ee(aZ,{request:e}),await this.makeAuthenticatedRequest(de.marginAccounts.transferOutParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async getMarginAccountMovements(e,t){return Ee(cZ,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(de.marginAccounts.movements(e,t))}async getParentMarginAccountMovements(e){return Ee(uZ,e),await this.makeAuthenticatedRequest(de.marginAccounts.parentMovements(e))}async simulateOrderRisk(e,t){return Ee(dZ,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(de.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})})}async simulateParentMarginOrderRisk(e){return Ee(pZ,{request:e}),await this.makeAuthenticatedRequest(de.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})})}async simulateRiskBucketOrderRisk(e){return Ee(fZ,{request:e}),await this.makeAuthenticatedRequest(de.marginAccounts.simulateRiskBucketOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,selectedTradingPairIds:e.selectedTradingPairIds,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly})})}}class H1 extends Ke{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(),o=r?`/api/v1/market/pairs?${r}`:"/api/v1/market/pairs";return await this.makePublicRequest(o)}async getTradingPair(e){return Ee(Bi,{tradingPairId:e}),(await this.makePublicRequest(de.market.getTradingPair(e))).tradingPair}async getTradingPairBySymbol(e,t){return(await this.getPaginatedTradingPairs({pageSize:100,marketType:t})).tradingPairs.find((o)=>o.symbol===e)}async getCandlesticks(e,t,r){Ee(hZ,{tradingPairId:e,interval:t,startTime:r?.startTime,endTime:r?.endTime,limit:r?.limit});let o=new URLSearchParams;if(r?.startTime!==void 0)o.append("startTime",r.startTime.toString());if(r?.endTime!==void 0)o.append("endTime",r.endTime.toString());if(r?.limit!==void 0)o.append("limit",r.limit.toString());let n=o.toString(),i=n?`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}?${n}`:`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}`;return(await this.makePublicRequest(i)).data||[]}async getMarketMetadata(e){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.getMarketMetadata(e))}async getPerpMarketConfig(e){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.getPerpMarketConfig(e))}async getPerpMarketSummary(e){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.getPerpMarketSummary(e))}async getMarkPrice(e){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.getMarkPrice(e))}async getIndexPrice(e){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.getIndexPrice(e))}async getFundingState(e){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.getFundingState(e))}async listFundingHistory(e,t){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.listFundingHistory(e,t))}async listAllFundingHistory(e){return await this.makePublicRequest(de.market.listAllFundingHistory(e))}async getOpenInterest(e){return Ee(Bi,{tradingPairId:e}),await this.makePublicRequest(de.market.getOpenInterest(e))}async getScreener(e){return await this.makePublicRequest(de.market.getScreener(e))}async getMarketStats(){return await this.makePublicRequest(de.market.getMarketStats())}}class G1 extends Ke{async getOrderbook(e,t={}){let{depth:r=10,tradingMode:o,magnitude:n,denomination:i}=t,s=new URLSearchParams;if(s.set("levels",String(r)),o)s.set("tradingMode",o);if(n!==void 0)s.set("magnitude",String(n));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 V1 extends Ke{async getMyTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me",{method:"GET"})}async setTraderCode(e){let t=Ee(GO,{code:e});return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me/custom",{method:"PUT",body:JSON.stringify({code:t.code})})}async clearTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me/custom",{method:"DELETE"})}async checkTraderCodeAvailability(e){let t=new URLSearchParams({code:e.trim()}).toString(),r=await this.makePublicRequest(`/api/v1/pitpass/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/pitpass/codes/${t}`,{method:"GET"})}async getRewardsBalance(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/balance",{method:"GET"})}async transferRewards(e){let t=Ee(VO,e);return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/transfer",{method:"POST",body:JSON.stringify({token:t.token,amount:t.amount})})}}var hy="/api/v1/accounts/me/portfolio";function Z1(e,t){if(!t?.period)return e;return`${e}?${new URLSearchParams({period:t.period})}`}class W1 extends Ke{async getSummary(e){return await this.makeAuthenticatedRequest(Z1(`${hy}/summary`,e))}async getPerformance(e){return await this.makeAuthenticatedRequest(Z1(`${hy}/performance`,e))}async getRealizedPnl(e){return await this.makeAuthenticatedRequest(Z1(`${hy}/realized-pnl`,e))}async getAssets(e){return await this.makeAuthenticatedRequest(Z1(`${hy}/assets`,e))}async getMargin(){return await this.makeAuthenticatedRequest(`${hy}/margin`)}}class K1 extends Ke{async listPositions(e){if(e)Ee(bZ,e);return await this.makeAuthenticatedRequest(de.positions.list(e))}async getPosition(e){return Ee(xZ,{positionId:e}),await this.makeAuthenticatedRequest(de.positions.get(e))}async closePosition(e,t){return Ee(vZ,{positionId:e,request:t}),await this.makeAuthenticatedRequest(de.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)Ee(_Z,e);return await this.makeAuthenticatedRequest(de.positions.batchCloseAll(),{method:"POST",body:JSON.stringify({tradingPairId:e?.tradingPairId,slippageToleranceBps:e?.slippageToleranceBps})})}async getPositionRisk(e){return Ee(wZ,{positionId:e}),await this.makeAuthenticatedRequest(de.positions.risk(e))}async attachPositionTpSl(e,t){return Ee(SZ,{positionId:e,request:t}),await this.makeAuthenticatedRequest(de.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,oco:t.oco})})}async listPositionHistory(e){if(e)Ee(TZ,e);return await this.makeAuthenticatedRequest(de.positions.history(e))}async getPositionPnlHistory(e,t){return Ee(EZ,{positionId:e,params:t}),await this.makeAuthenticatedRequest(de.positions.pnlHistory(e,t))}}class r5 extends Ke{async getProfile(){return await this.makeAuthenticatedRequest("/api/v1/accounts/me")}async getPaginatedUserMovements(e){if(e)Ee(IZ,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?.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(),o=r?`/api/v1/accounts/movements?${r}`:"/api/v1/accounts/movements";return await this.makeAuthenticatedRequest(o)}async getUserBalances(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());let r=t.toString(),o=r?`/api/v1/accounts/balances?${r}`:"/api/v1/accounts/balances";return await this.makeAuthenticatedRequest(o)}async getUserBalanceByAssetId(e){if(!e||e.trim()==="")throw new or("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)Ee(PZ,e);let t=e?.page!==void 0&&e?.pageToken===void 0,r=new URLSearchParams;if(t&&e?.page!==void 0)r.append("page",e.page.toString());if(e?.pageSize!==void 0)r.append("pageSize",e.pageSize.toString());if(e?.tradingPairId!==void 0)r.append("tradingPairId",e.tradingPairId);if(!t)r.append("pageToken",e?.pageToken??"");let o=r.toString(),n=o?`/api/v1/accounts/trades?${o}`:"/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)Ee(kZ,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?.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(),o=r?`/api/v1/accounts/funding-payments?${r}`:"/api/v1/accounts/funding-payments";return await this.makeAuthenticatedRequest(o)}}class J1 extends Ke{async getPulse(){return await this.makePublicRequest("/api/v1/pulse",{method:"GET"})}}class Y1 extends Ke{async list(){return await this.makeAuthenticatedRequest(de.subAccounts.list())}async createLimit(e){return await this.makeAuthenticatedRequest(de.subAccounts.createLimit(),{method:"POST",body:JSON.stringify(e)})}async getLimits(e){return await this.makeAuthenticatedRequest(de.subAccounts.getLimits(e))}async updateLimit(e,t,r){return await this.makeAuthenticatedRequest(de.subAccounts.limit(e,t),{method:"PUT",body:JSON.stringify(r)})}async deleteLimit(e,t){await this.makeAuthenticatedRequest(de.subAccounts.limit(e,t),{method:"DELETE"})}}class Q1 extends Ke{async register(e){return await this.makePublicRequest(de.sweeper.register(),{method:"POST",body:JSON.stringify(e)})}}function OZ(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 n5 extends Ke{async getTrades(e,t={}){let{page:r=1}=t,o=t.pageSize!=null&&t.pageSize>0?Math.min(t.pageSize,100):25,n=new URLSearchParams;if(r>1)n.set("page",String(r));return n.set("pageSize",String(o)),(await this.makePublicRequest(`/api/v1/trades/${encodeURIComponent(e)}?${n.toString()}`)).trades.map(OZ)}async getTradeById(e){let t=await this.makePublicRequest(de.trades.byId(e));return OZ(t)}}function X1(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}}class eS extends Ke{async placeLimitOrder(e,t,r,o,n){Ee(GV,{tradingPairId:e,side:t,quantity:r,price:o,options:n});let i={tradingPairId:e,orderType:"LIMIT",side:t,price:o,quantity:r,tradingMode:n?.tradingMode||"SPOT",useMasterBalance:n?.useMasterBalance,expirationDate:n?.expirationDate,timeInForce:n?.timeInForce,marginAccountId:n?.marginAccountId,marginMode:n?.marginMode,riskBucketId:n?.riskBucketId,riskBucketCollateral:n?.riskBucketCollateral,strategyKey:n?.strategyKey,positionSide:n?.positionSide,leverage:n?.leverage,reduceOnly:n?.reduceOnly,postOnly:n?.postOnly,clientOrderId:n?.clientOrderId,takeProfit:X1(n?.takeProfit),stopLoss:X1(n?.stopLoss)};return await this.makeAuthenticatedRequest(de.orders.create(),{method:"POST",body:JSON.stringify(i)})}async placeMarketOrder(e,t,r,o){Ee(VV,{tradingPairId:e,side:t,quantity:r,options:o});let n={tradingPairId:e,orderType:"MARKET",side:t,slippageToleranceBps:o?.slippageTolerance!==void 0?Math.round(o.slippageTolerance*1e4):void 0,price:null,quantity:r,tradingMode:o?.tradingMode||"SPOT",marginAccountId:o?.marginAccountId,marginMode:o?.marginMode,riskBucketId:o?.riskBucketId,riskBucketCollateral:o?.riskBucketCollateral,strategyKey:o?.strategyKey,positionSide:o?.positionSide,leverage:o?.leverage,reduceOnly:o?.reduceOnly,takeProfit:X1(o?.takeProfit),stopLoss:X1(o?.stopLoss),clientOrderId:o?.clientOrderId};return await this.makeAuthenticatedRequest(de.orders.create(),{method:"POST",body:JSON.stringify(n)})}async cancelOrder(e){Ee(ZV,{orderId:e});let t={orderId:e};return await this.makeAuthenticatedRequest(de.orders.cancel(),{method:"POST",body:JSON.stringify(t)})}async cancelConditionalOrder(e){return Ee(JO,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(de.orders.cancelConditional(e),{method:"DELETE"})}async getConditionalOrder(e){return Ee(JO,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(de.orders.getConditional(e),{method:"GET"})}async listConditionalOrders(e){if(e)Ee(JV,e);let{page:t=1,pageSize:r=20,marginAccountId:o,tradingPairId:n,state:i}=e||{};return await this.makeAuthenticatedRequest(de.orders.listConditional({page:t,pageSize:Math.min(Math.max(r,1),100),marginAccountId:o,tradingPairId:n,state:i}),{method:"GET"})}async batchCancel(e){if(!e||e.length===0)throw Error("orderIds is required and must not be empty");return this.makeAuthenticatedRequest(de.orders.batchCancel(),{method:"POST",body:JSON.stringify({orderIds:e})})}async batchCancelAll(e){let t=e?de.orders.batchCancelAllByPair(e):de.orders.batchCancelAll();return this.makeAuthenticatedRequest(t,{method:"POST"})}async replaceOrder(e,t){Ee(WV,{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.clientOrderId!==void 0)r.clientOrderId=t.clientOrderId;return await this.makeAuthenticatedRequest(de.orders.replace(e),{method:"PUT",body:JSON.stringify(r)})}async batchCreate(e){Ee(YV,{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,clientOrderId:r.clientOrderId}))};return this.makeAuthenticatedRequest(de.orders.batchCreate(),{method:"POST",body:JSON.stringify(t)})}async batchReplace(e){Ee(QV,{orders:e});let t={orders:e.map((r)=>({orderId:r.orderId,price:r.price,quantity:r.quantity,useMasterBalance:r.useMasterBalance,postOnly:r.postOnly,clientOrderId:r.clientOrderId}))};return this.makeAuthenticatedRequest(de.orders.batchReplace(),{method:"POST",body:JSON.stringify(t)})}async getPaginatedOrders(e){if(e)Ee(KV,e);let{page:t,pageSize:r=10,status:o,tradingPairId:n,tradingMode:i,marginAccountId:s,pageToken:a}=e||{},c=r>0?r:10,u=t!==void 0&&a===void 0,d=Math.min(c,u?100:1000),p=new URLSearchParams;if(u){let y=t>0?t:1;p.append("page",y.toString())}p.append("pageSize",d.toString());let m=typeof o==="string"?o:o?.join(",");if(m)p.append("status",m);if(n)p.append("tradingPairId",n);if(i)p.append("tradingMode",i);if(s)p.append("marginAccountId",s);if(!u)p.append("pageToken",a??"");let h=`/api/v1/orders?${p.toString()}`;return await this.makeAuthenticatedRequest(h,{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(de.orders.get(e),{method:"GET"}),status:"SUCCESS"}}}var o5=[{inputs:[{internalType:"address",name:"rollup_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"NativeTransferFailed",type:"error"},{inputs:[],name:"NothingToSweep",type:"error"},{inputs:[],name:"OnlyClone",type:"error"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"SafeERC20FailedOperation",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:"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"},{inputs:[],name:"config",outputs:[{internalType:"address",name:"user",type:"address"},{internalType:"string",name:"applicationId",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"rollup",outputs:[{internalType:"contract IRollup",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"nonpayable",type:"function"}];var i5=[{inputs:[{internalType:"address",name:"rollup_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"CloneArgumentsTooLong",type:"error"},{inputs:[],name:"Create2EmptyBytecode",type:"error"},{inputs:[],name:"FailedDeployment",type:"error"},{inputs:[{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{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"}],name:"SweeperDeployed",type:"event"},{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:[],name:"implementation",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",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:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"rollup",outputs:[{internalType:"contract IRollup",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:"nonpayable",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"}];var s5=[{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 x5t=new Uint8Array(32);var a5={vault:s5,sweeper:o5,sweeperFactory:i5};var z0e=5000,N0e=300000,M0e=(e)=>new Promise((t)=>setTimeout(t,e));function CZ(e,t){return t==="margin"?JSON.stringify({clientId:e,depositTarget:"MARGIN"}):e}class tS extends Ke{publicClient;chain;applicationsAPI;profileAPI;walletClient;constructor(e,t,r,o,n,i){super(i);this.publicClient=e,this.chain=r,this.walletClient=t,this.applicationsAPI=o,this.profileAPI=n}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;try{t=(await this.profileAPI.getUserBalanceByAssetId(e)).token}catch(o){if(o instanceof or){if(o.statusCode===404)throw new _s(`Asset ID '${e}' does not exist`,{revertReason:"ASSET_NOT_FOUND",cause:o});throw new _s(`Failed to resolve asset ID '${e}': ${o.retryable?"Network error occurred":"API request failed"}`,{revertReason:o.retryable?"NETWORK_ERROR":"API_ERROR",cause:o})}throw new _s(`Failed to resolve asset ID '${e}': Unexpected error`,{revertReason:"UNKNOWN_ERROR",cause:o instanceof Error?o:void 0})}return{tokenAddress:t,isNativeToken:t===_n}}async approve(e,t,r=!0){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");Ee(AZ,{assetId:e,amount:t,autoWait:r});let o=await this.getVaultAddress(),{tokenAddress:n}=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:n,abi:nw,functionName:"approve",args:[o,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,o="spot"){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");Ee($Z,{assetId:e,amount:t,autoWait:r,target:o});let n=await this.getVaultAddress(),i=await this.getClientId(),s=CZ(i,o),{tokenAddress:a,isNativeToken:c}=await this.resolveAsset(e);if(!c){if(await this.needsApproval(e,t))throw new _s(`Approval required before deposit. Please invoke approve() first for asset ${e} (token address: ${a}).`,{revertReason:"APPROVAL_REQUIRED"})}let u=this.walletClient.account;if(!u)throw new Bt("No account available in wallet client","account");let d;if(c)d=await this.walletClient.writeContract({address:n,abi:a5.vault,functionName:"depositNative",args:[u.address,s],account:u,chain:this.chain,value:t});else d=await this.walletClient.writeContract({address:n,abi:a5.vault,functionName:"depositERC20",args:[u.address,s,a,t],account:u,chain:this.chain});let p=u.getNonce?await u.getNonce():0n,m={hash:d,status:"pending",nonce:p};return await this.waitForTransaction(m,r)}async pollWithdrawalCalldata(e,t){let r=t?.pollIntervalMs??z0e,o=t?.timeoutMs??N0e,n=Date.now()+o;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 or&&(i.statusCode===404||i.statusCode===409)))throw i}if(Date.now()+r>n)return null;await M0e(r)}}async withdraw(e,t,r=!0,o,n){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 o==="string"?o:"spot",c=typeof o==="string"?n:o;Ee(RZ,{assetId:e,amount:t,destination:s,autoWait:r,source:a});let{withdrawalIndex:u}=await this.makeAuthenticatedRequest("/api/v1/withdrawals",{method:"POST",body:JSON.stringify({assetId:e,amount:t.toString(),destination:s,source:a})});if(!r)return{withdrawalIndex:u,status:"awaiting_proof"};let d=await this.pollWithdrawalCalldata(u,c);if(!d)return{withdrawalIndex:u,status:"awaiting_proof"};let{vaultAddress:p,calldata:m}=d,h;try{h=await this.walletClient.sendTransaction({to:p,data:m,account:i,chain:this.chain})}catch(v){throw new _s(`Failed to submit executeWithdrawal for withdrawal ${u}: ${v instanceof Error?v.message:"unknown error"}`,{cause:v instanceof Error?v:void 0})}let y=i.getNonce?await i.getNonce():0n,x={hash:h,status:"pending",nonce:y};return{...await this.waitForTransaction(x,r),withdrawalIndex:u}}async retryWithdrawal(e,t=!0,r){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");let o=this.walletClient.account;if(!o)throw new Bt("No account available in wallet client","account");let n=await this.pollWithdrawalCalldata(e,r);if(!n)return{withdrawalIndex:e,status:"awaiting_proof"};let{vaultAddress:i,calldata:s}=n,a;try{a=await this.walletClient.sendTransaction({to:i,data:s,account:o,chain:this.chain})}catch(p){throw new _s(`Failed to resubmit executeWithdrawal for withdrawal ${e}: ${p instanceof Error?p.message:"unknown error"}`,{cause:p instanceof Error?p:void 0})}let c=o.getNonce?await o.getNonce():0n,u={hash:a,status:"pending",nonce:c};return{...await this.waitForTransaction(u,t),withdrawalIndex:e}}async getBalance(e){throw new or("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(),o=(await this.walletClient.getAddresses())[0];if(!o)throw new Bt("No account found in wallet client.","walletClient");let{tokenAddress:n}=await this.resolveAsset(e);return await this.publicClient.readContract({address:n,abi:nw,functionName:"allowance",args:[o,t]})}async needsApproval(e,t){return await this.getAllowance(e)<t}async waitForTransaction(e,t=!0,r={}){if(!t)return e;let{confirmations:o=1,timeout:n=60000}=r;try{let i=await this.publicClient.waitForTransactionReceipt({hash:e.hash,confirmations:o,timeout:n});return{...e,status:i.status==="success"?"confirmed":"failed",receipt:i}}catch{return{...e,status:"failed"}}}}class rS extends Ke{async submit(e){return await this.makePublicRequest(de.whitelist.submit(),{method:"POST",body:JSON.stringify(e)})}}class c5 extends Ke{async initiateWithdrawal(e){return this.makeAuthenticatedRequest(de.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(de.withdrawals.byIndex(e))}async listPendingWithdrawals(e){return this.makeAuthenticatedRequest(de.withdrawals.list({page:e?.page,pageSize:e?.pageSize}))}}class nS extends Ke{chain;walletClient;constructor(e,t,r){super(r);this.chain=t,this.walletClient=e}setWalletClient(e){this.walletClient=e}async authenticate(e,t){if(!this.walletClient)throw new Bt("Wallet client not set. Connect a wallet first.","walletClient");let r=this.walletClient.account;if(!r)throw new Bt("No account available in wallet client","account");let o=V_(),n={publicKey:Z_(o),privateKey:W_(o)},i=await this.createChallenge(r.address,e,n.publicKey),s=await this.signChallenge(i.message);return await this.verifySignature(r.address,s,i.nonce,e,n,t)}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 o=await this.makePublicRequest("/api/v1/auth/challenge",{method:"POST",body:JSON.stringify({address:e,clientId:t,chainId:this.chain.id,sessionPublicKey:r})});return{nonce:o.nonce,message:o.message,expiresAt:o.expiresAt}}async verifySignature(e,t,r,o,n,i){let s=await this.makePublicRequest("/api/v1/auth/verify",{method:"POST",body:JSON.stringify({address:e,signature:t,nonce:r,clientId:o,chainId:this.chain.id,sessionPublicKey:n.publicKey,...i?{referralCode:i}:{}})});return{sessionPublicKey:n.publicKey,sessionPrivateKey:n.privateKey,expiresAt:s.expiresAt,user:{id:s.user.id,address:s.user.address,username:s.user.username}}}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 B0e=750;function zZ(e,t){try{new URL(e)}catch(r){throw new Bt(`${t} must be a valid URL, got: ${e}`,t)}return e}class l5{auth;delegatedAgents;applications;fees;pitpass;vault;withdrawals;trading;market;marginAccounts;positions;portfolio;subAccounts;faucet;sweeper;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.pitpass.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.whitelist.setSessionKeypair(e),this.pulse.setSessionKeypair(e),this.profile.setSessionKeypair(e),this.orderbook.setSessionKeypair(e),this.trades.setSessionKeypair(e),this.ws.setSessionKeypair(e)}setServerKey(e){this.auth.setServerKey(e),this.delegatedAgents.setServerKey(e),this.applications.setServerKey(e),this.fees.setServerKey(e),this.pitpass.setServerKey(e),this.vault.setServerKey(e),this.withdrawals.setServerKey(e),this.trading.setServerKey(e),this.market.setServerKey(e),this.marginAccounts.setServerKey(e),this.positions.setServerKey(e),this.portfolio.setServerKey(e),this.subAccounts.setServerKey(e),this.faucet.setServerKey(e),this.sweeper.setServerKey(e),this.whitelist.setServerKey(e),this.pulse.setServerKey(e),this.profile.setServerKey(e),this.orderbook.setServerKey(e),this.trades.setServerKey(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(s){throw new Bt(`seiRpcUrl must be a valid URL, got: ${e.seiRpcUrl}`,"seiRpcUrl")}let r=e.wsUrl?zZ(e.wsUrl,"wsUrl"):F$(this.network),o=this.network==="mainnet"?DO:UO;if(this.chain=o,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 n=BO(e.seiRpcUrl);this.publicClient=zO({chain:o,transport:n,pollingInterval:e.pollingInterval??B0e});let i=e.apiUrl?zZ(e.apiUrl,"apiUrl"):j$(this.network);if(e.walletClient){if(e.walletClient.chain?.id!==o.id)throw new Bt(`Wallet client chain mismatch. Expected ${o.id}, got ${e.walletClient.chain?.id}`,"walletClient");this.walletClient=e.walletClient}this.applications=new C1(i),this.market=new H1(i),this.marginAccounts=new q1(i),this.positions=new K1(i),this.portfolio=new W1(i),this.subAccounts=new Y1(i),this.faucet=new z1(i),this.sweeper=new Q1(i),this.whitelist=new rS(i),this.pulse=new J1(i),this.auth=new nS(this.walletClient,this.chain,i),this.delegatedAgents=new FO(i),this.fees=new F1(i),this.pitpass=new V1(i),this.profile=new r5(i),this.vault=new tS(this.publicClient,this.walletClient,this.chain,this.applications,this.profile,i),this.withdrawals=new c5(i),this.trading=new eS(i),this.orderbook=new G1(i),this.trades=new n5(i),this.ws=z$(r,e.ws),this.ws.connect().catch(console.error)}async login(e,t){if(this.authState=await this.auth.authenticate(e),this.propagateSession(this.sessionFromAuthState(this.authState)),t?.connectWebSocket)await this.ws.connect();return this.authState}async loginAsDelegatedOwner(e){if(!this.authState)throw new or("No active agent session to create delegated session",{endpoint:"delegated-agents/sessions",statusCode:u5.StatusCodes.UNAUTHORIZED});let t=V_(),r={publicKey:Z_(t),privateKey:W_(t)},o=await this.delegatedAgents.createDelegatedSession({ownerUserId:e,sessionPublicKey:r.publicKey});return this.authState={sessionPublicKey:r.publicKey,sessionPrivateKey:r.privateKey,expiresAt:o.expiresAt,user:{id:o.ownerUserId,address:o.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 or("No active session to refresh",{endpoint:"auth/refresh",statusCode:u5.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 dg("Wallet client not set","walletClient");if(this.walletClient.account)return this.walletClient.account.address;throw new dg("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 d5(e){return new l5(e)}function ft(e){if(typeof e==="string")return{address:e,type:"json-rpc"};return e}var oS=256,iS;function sS(e=11){if(!iS||oS+e>512){iS="",oS=0;for(let t=0;t<256;t++)iS+=(256+Math.random()*256|0).toString(16).substring(1)}return iS.substring(oS,oS+++e)}function NZ(e){let{batch:t,chain:r,ccipRead:o,dataSuffix:n,key:i="base",name:s="Base Client",type:a="base"}=e,c=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime==="number"?"pending":void 0),u=r?.blockTime??12000,d=Math.min(Math.max(Math.floor(u/2),500),4000),p=e.pollingInterval??d,m=e.cacheTime??p,h=e.account?ft(e.account):void 0,{config:y,request:x,value:S}=e.transport({account:h,chain:r,pollingInterval:p}),v={...y,...S},E={account:h,batch:t,cacheTime:m,ccipRead:o,chain:r,dataSuffix:n,key:i,name:s,pollingInterval:p,request:x,transport:v,type:a,uid:sS(),...c?{experimental_blockTag:c}:{}};function w(_){return(T)=>{let P=T(_);for(let z in E)delete P[z];let O={..._,...P};return Object.assign(O,{extend:w(O)})}}return Object.assign(E,{extend:w(E)})}var MZ={gwei:9,wei:18},BZ={ether:-9,wei:9};function aS(e,t){let r=e.toString(),o=r.startsWith("-");if(o)r=r.slice(1);r=r.padStart(t,"0");let[n,i]=[r.slice(0,r.length-t),r.slice(r.length-t)];return i=i.replace(/(0+)$/,""),`${o?"-":""}${n||"0"}${i?`.${i}`:""}`}function wn(e,t="wei"){return aS(e,BZ[t])}var p5="2.53.1";var f5={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${p5}`};class q extends Error{constructor(e,t={}){let r=(()=>{if(t.cause instanceof q)return t.cause.details;if(t.cause?.message)return t.cause.message;return t.details})(),o=(()=>{if(t.cause instanceof q)return t.cause.docsPath||t.docsPath;return t.docsPath})(),n=f5.getDocsUrl?.({...t,docsPath:o}),i=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...r?[`Details: ${r}`]:[],...f5.version?[`Version: ${f5.version}`]:[]].join(`
147
147
  `);super(i,t.cause?{cause:t.cause}:void 0);Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=r,this.docsPath=o,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=p5}walk(e){return DZ(this,e)}}function DZ(e,t){if(t?.(e))return e;if(e&&typeof e==="object"&&"cause"in e&&e.cause!==void 0)return DZ(e.cause,t);return t?null:e}class gy extends q{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class Ku extends q{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class m5 extends q{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${wn(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class lc extends q{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(lc,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(lc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});class ti extends q{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${wn(t)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(ti,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class yy extends q{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${wn(t)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}}Object.defineProperty(yy,"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/});class by extends q{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(by,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class xy extends q{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(`
148
148
  `),{cause:e,name:"NonceTooLowError"})}}Object.defineProperty(xy,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class vy extends q{constructor({cause:e,nonce:t}={}){super(`Nonce provided for the transaction ${t?`(${t}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}}Object.defineProperty(vy,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class _y extends q{constructor({cause:e}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
149
149
  `),{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(_y,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class wy extends q{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(wy,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class Sy extends q{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(Sy,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class Ty extends q{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(Ty,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class Ls extends q{constructor({cause:e,maxPriorityFeePerGas:t,maxFeePerGas:r}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${t?` = ${wn(t)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${r?` = ${wn(r)} gwei`:""}).`].join(`
150
150
  `),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(Ls,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class Ju extends q{constructor({cause:e}){super(`An error occurred while executing: ${e?.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}function cS(e,t="wei"){return aS(e,MZ[t])}function Jp(e){let t=Object.entries(e).map(([o,n])=>{if(n===void 0||n===!1)return null;return[o,n]}).filter(Boolean),r=t.reduce((o,[n])=>Math.max(o,n.length),0);return t.map(([o,n])=>` ${`${o}:`.padEnd(r+1)} ${n}`).join(`
151
151
  `)}class h5 extends q{constructor({v:e}){super(`Invalid \`v\` value "${e}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class g5 extends q{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",Jp(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class y5 extends q{constructor({storageKey:e}){super(`Size for storage key "${e}" is invalid. Expected 32 bytes. Got ${Math.floor((e.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}class b5 extends q{constructor(e,{account:t,docsPath:r,chain:o,data:n,gas:i,gasPrice:s,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:u,to:d,value:p}){let m=Jp({chain:o&&`${o?.name} (id: ${o?.id})`,from:t?.address,to:d,value:typeof p<"u"&&`${cS(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:n,gas:i,gasPrice:typeof s<"u"&&`${wn(s)} gwei`,maxFeePerGas:typeof a<"u"&&`${wn(a)} gwei`,maxPriorityFeePerGas:typeof c<"u"&&`${wn(c)} gwei`,nonce:u});super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Request Arguments:",m].filter(Boolean),name:"TransactionExecutionError"});Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}class Ey extends q{constructor({blockHash:e,blockNumber:t,blockTag:r,hash:o,index:n}){let i="Transaction";if(r&&n!==void 0)i=`Transaction at block time "${r}" at index "${n}"`;if(e&&n!==void 0)i=`Transaction at block hash "${e}" at index "${n}"`;if(t&&n!==void 0)i=`Transaction at block number "${t}" at index "${n}"`;if(o)i=`Transaction with hash "${o}"`;super(`${i} could not be found.`,{name:"TransactionNotFoundError"})}}class Iy extends q{constructor({hash:e}){super(`Transaction receipt with hash "${e}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class Yp extends q{constructor({receipt:e}){super(`Transaction with hash "${e.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"});Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=e}}class x5 extends q{constructor({hash:e}){super(`Timed out while waiting for transaction with hash "${e}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}var Yt=(e,t,r)=>JSON.stringify(e,(o,n)=>{let i=typeof n==="bigint"?n.toString():n;return typeof t==="function"?t(o,i):i},r);var UZ=(e)=>e;function ri(e){if(e?.reason)return e.reason;if(typeof DOMException==="function")return new DOMException("This operation was aborted","AbortError");let t=Error("This operation was aborted");return t.name="AbortError",t}function js(e){return typeof e==="object"&&e!==null&&"name"in e&&e.name==="AbortError"}var uS=(e)=>{try{let t=new URL(e);if(!t.username&&!t.password)return e;return t.username="",t.password="",t.toString()}catch{return e}};class dc extends q{constructor({body:e,cause:t,details:r,headers:o,status:n,url:i}){super("HTTP request failed.",{cause:t,details:r,metaMessages:[n&&`Status: ${n}`,`URL: ${uS(i)}`,e&&`Request body: ${Yt(e)}`].filter(Boolean),name:"HttpRequestError"});Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=o,this.status=n,this.url=i}}class Yu extends q{constructor({body:e,error:t,url:r}){super("RPC Request failed.",{cause:t,details:t.message,metaMessages:[`URL: ${uS(r)}`,`Request body: ${Yt(e)}`],name:"RpcRequestError"});Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t.code,this.data=t.data,this.url=r}}class lS extends q{constructor({body:e,url:t}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${uS(t)}`,`Request body: ${Yt(e)}`],name:"TimeoutError"});Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=t}}var D0e=-1;class Sn extends q{constructor(e,{code:t,docsPath:r,metaMessages:o,name:n,shortMessage:i}){super(i,{cause:e,docsPath:r,metaMessages:o||e?.metaMessages,name:n||"RpcError"});Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=n||e.name,this.code=e instanceof Yu?e.code:t??D0e}}class Tn extends Sn{constructor(e,t){super(e,t);Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t.data}}class Qp extends Sn{constructor(e){super(e,{code:Qp.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(Qp,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class Xp extends Sn{constructor(e){super(e,{code:Xp.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(Xp,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class ef extends Sn{constructor(e,{method:t}={}){super(e,{code:ef.code,name:"MethodNotFoundRpcError",shortMessage:`The method${t?` "${t}"`:""} does not exist / is not available.`})}}Object.defineProperty(ef,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class tf extends Sn{constructor(e){super(e,{code:tf.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
152
152
  `)})}}Object.defineProperty(tf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class Fs extends Sn{constructor(e){super(e,{code:Fs.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(Fs,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class pc extends Sn{constructor(e){super(e,{code:pc.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
153
- `)})}}Object.defineProperty(pc,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32000});class rf extends Sn{constructor(e){super(e,{code:rf.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(rf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class nf extends Sn{constructor(e){super(e,{code:nf.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(nf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class of extends Sn{constructor(e){super(e,{code:of.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(of,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class fc extends Sn{constructor(e,{method:t}={}){super(e,{code:fc.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${t?` "${t}"`:""} is not supported.`})}}Object.defineProperty(fc,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class Qu extends Sn{constructor(e){super(e,{code:Qu.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(Qu,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class sf extends Sn{constructor(e){super(e,{code:sf.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(sf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Xu extends Tn{constructor(e){super(e,{code:Xu.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Xu,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class af extends Tn{constructor(e){super(e,{code:af.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(af,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class cf extends Tn{constructor(e,{method:t}={}){super(e,{code:cf.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${t?` " ${t}"`:""}.`})}}Object.defineProperty(cf,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class uf extends Tn{constructor(e){super(e,{code:uf.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(uf,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class lf extends Tn{constructor(e){super(e,{code:lf.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(lf,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class df extends Tn{constructor(e){super(e,{code:df.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(df,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class mc extends Tn{constructor(e){super(e,{code:mc.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(mc,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class pf extends Tn{constructor(e){super(e,{code:pf.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(pf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class ff extends Tn{constructor(e){super(e,{code:ff.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(ff,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class mf extends Tn{constructor(e){super(e,{code:mf.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(mf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class hf extends Tn{constructor(e){super(e,{code:hf.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(hf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class gf extends Tn{constructor(e){super(e,{code:gf.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(gf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class hc extends Tn{constructor(e){super(e,{code:hc.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(hc,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class yf extends Tn{constructor(e){super(e,{code:yf.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}}Object.defineProperty(yf,"code",{enumerable:!0,configurable:!0,writable:!0,value:7000});class v5 extends Sn{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}function dS(e,t){let r=(e.details||"").toLowerCase(),o=e instanceof q?e.walk((n)=>n?.code===lc.code):e;if(o instanceof q)return new lc({cause:e,message:o.details});if(lc.nodeMessage.test(r))return new lc({cause:e,message:e.details});if(ti.nodeMessage.test(r))return new ti({cause:e,maxFeePerGas:t?.maxFeePerGas});if(yy.nodeMessage.test(r))return new yy({cause:e,maxFeePerGas:t?.maxFeePerGas});if(by.nodeMessage.test(r))return new by({cause:e,nonce:t?.nonce});if(xy.nodeMessage.test(r))return new xy({cause:e,nonce:t?.nonce});if(vy.nodeMessage.test(r))return new vy({cause:e,nonce:t?.nonce});if(_y.nodeMessage.test(r))return new _y({cause:e});if(wy.nodeMessage.test(r))return new wy({cause:e,gas:t?.gas});if(Sy.nodeMessage.test(r))return new Sy({cause:e,gas:t?.gas});if(Ty.nodeMessage.test(r))return new Ty({cause:e});if(Ls.nodeMessage.test(r))return new Ls({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas});return new Ju({cause:e})}function gc(e,{docsPath:t,...r}){let o=(()=>{let n=dS(e,r);if(n instanceof Ju)return e;return n})();return new b5(o,{docsPath:t,...r})}function yc(e,{format:t}){if(!t)return{};let r={};function o(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]))o(i[a])}}let n=t(e||{});return o(n),r}class el extends q{constructor({max:e,min:t,signed:r,size:o,value:n}){super(`Number "${n}" is not in safe ${o?`${o*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class _5 extends q{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}}class w5 extends q{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Hr(e,{strict:t=!0}={}){if(!e)return!1;if(typeof e!=="string")return!1;return t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function mt(e){if(Hr(e,{strict:!1}))return Math.ceil((e.length-2)/2);return e.length}function _o(e,{dir:t="left"}={}){let r=typeof e==="string"?e.replace("0x",""):e,o=0;for(let n=0;n<r.length-1;n++)if(r[t==="left"?n:r.length-n-1].toString()==="0")o++;else break;if(r=t==="left"?r.slice(o):r.slice(0,r.length-o),typeof e==="string"){if(r.length===1&&t==="right")r=`${r}0`;return`0x${r.length%2===1?`0${r}`:r}`}return r}class pS extends q{constructor({offset:e,position:t,size:r}){super(`Slice ${t==="start"?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${r}).`,{name:"SliceOffsetOutOfBoundsError"})}}class fS extends q{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}class mS extends q{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} is expected to be ${t} ${r} long, but is ${e} ${r} long.`,{name:"InvalidBytesLengthError"})}}function bc(e,{dir:t,size:r=32}={}){if(typeof e==="string")return qs(e,{dir:t,size:r});return U0e(e,{dir:t,size:r})}function qs(e,{dir:t,size:r=32}={}){if(r===null)return e;let o=e.replace("0x","");if(o.length>r*2)throw new fS({size:Math.ceil(o.length/2),targetSize:r,type:"hex"});return`0x${o[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function U0e(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new fS({size:e.length,targetSize:r,type:"bytes"});let o=new Uint8Array(r);for(let n=0;n<r;n++){let i=t==="right";o[i?n:r-n-1]=e[i?n:e.length-n-1]}return o}var L0e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Gr(e,t={}){if(typeof e==="number"||typeof e==="bigint")return ae(e,t);if(typeof e==="string")return xc(e,t);if(typeof e==="boolean")return S5(e,t);return Dt(e,t)}function S5(e,t={}){let r=`0x${Number(e)}`;if(typeof t.size==="number")return Yn(r,{size:t.size}),bc(r,{size:t.size});return r}function Dt(e,t={}){let r="";for(let n=0;n<e.length;n++)r+=L0e[e[n]];let o=`0x${r}`;if(typeof t.size==="number")return Yn(o,{size:t.size}),bc(o,{dir:"right",size:t.size});return o}function ae(e,t={}){let{signed:r,size:o}=t,n=BigInt(e),i;if(o)if(r)i=(1n<<BigInt(o)*8n-1n)-1n;else i=2n**(BigInt(o)*8n)-1n;else if(typeof e==="number")i=BigInt(Number.MAX_SAFE_INTEGER);let s=typeof i==="bigint"&&r?-i-1n:0;if(i&&n>i||n<s){let c=typeof e==="bigint"?"n":"";throw new el({max:i?`${i}${c}`:void 0,min:`${s}${c}`,signed:r,size:o,value:`${e}${c}`})}let a=`0x${(r&&n<0?(1n<<BigInt(o*8))+BigInt(n):n).toString(16)}`;if(o)return bc(a,{size:o});return a}var j0e=new TextEncoder;function xc(e,t={}){let r=j0e.encode(e);return Dt(r,t)}var F0e=new TextEncoder;function bf(e,t={}){if(typeof e==="number"||typeof e==="bigint")return H0e(e,t);if(typeof e==="boolean")return q0e(e,t);if(Hr(e))return yr(e,t);return T5(e,t)}function q0e(e,t={}){let r=new Uint8Array(1);if(r[0]=Number(e),typeof t.size==="number")return Yn(r,{size:t.size}),bc(r,{size:t.size});return r}var Hs={zero:48,nine:57,A:65,F:70,a:97,f:102};function LZ(e){if(e>=Hs.zero&&e<=Hs.nine)return e-Hs.zero;if(e>=Hs.A&&e<=Hs.F)return e-(Hs.A-10);if(e>=Hs.a&&e<=Hs.f)return e-(Hs.a-10);return}function yr(e,t={}){let r=e;if(t.size)Yn(r,{size:t.size}),r=bc(r,{dir:"right",size:t.size});let o=r.slice(2);if(o.length%2)o=`0${o}`;let n=o.length/2,i=new Uint8Array(n);for(let s=0,a=0;s<n;s++){let c=LZ(o.charCodeAt(a++)),u=LZ(o.charCodeAt(a++));if(c===void 0||u===void 0)throw new q(`Invalid byte sequence ("${o[a-2]}${o[a-1]}" in "${o}").`);i[s]=c*16+u}return i}function H0e(e,t){let r=ae(e,t);return yr(r)}function T5(e,t={}){let r=F0e.encode(e);if(typeof t.size==="number")return Yn(r,{size:t.size}),bc(r,{dir:"right",size:t.size});return r}function Yn(e,{size:t}){if(mt(e)>t)throw new w5({givenSize:mt(e),maxSize:t})}function Ir(e,t={}){let{signed:r}=t;if(t.size)Yn(e,{size:t.size});let o=BigInt(e);if(!r)return o;let n=(e.length-2)/2,i=(1n<<BigInt(n)*8n-1n)-1n;if(o<=i)return o;return o-BigInt(`0x${"f".padStart(n*2,"f")}`)-1n}function Pr(e,t={}){let r=Ir(e,t),o=Number(r);if(!Number.isSafeInteger(o))throw new el({max:`${Number.MAX_SAFE_INTEGER}`,min:`${Number.MIN_SAFE_INTEGER}`,signed:t.signed,size:t.size,value:`${r}n`});return o}var E5={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function xf(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?Pr(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?Pr(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?E5[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};if(e.authorizationList)r.authorizationList=G0e(e.authorizationList);if(r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v==="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}return})(),r.type==="legacy")delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity;if(r.type==="eip2930")delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas;if(r.type==="eip1559")delete r.maxFeePerBlobGas;return r}function G0e(e){return e.map((t)=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}var V0e={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function Di(e,t){let r={};if(typeof e.authorizationList<"u")r.authorizationList=Z0e(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((o)=>Dt(o));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=ae(e.gas);if(typeof e.gasPrice<"u")r.gasPrice=ae(e.gasPrice);if(typeof e.maxFeePerBlobGas<"u")r.maxFeePerBlobGas=ae(e.maxFeePerBlobGas);if(typeof e.maxFeePerGas<"u")r.maxFeePerGas=ae(e.maxFeePerGas);if(typeof e.maxPriorityFeePerGas<"u")r.maxPriorityFeePerGas=ae(e.maxPriorityFeePerGas);if(typeof e.nonce<"u")r.nonce=ae(e.nonce);if(typeof e.to<"u")r.to=e.to;if(typeof e.type<"u")r.type=V0e[e.type];if(typeof e.value<"u")r.value=ae(e.value);return r}function Z0e(e){return e.map((t)=>({address:t.address,r:t.r?ae(BigInt(t.r)):t.r,s:t.s?ae(BigInt(t.s)):t.s,chainId:ae(t.chainId),nonce:ae(t.nonce),...typeof t.yParity<"u"?{yParity:ae(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:ae(t.v)}:{}}))}function Ne(e,t,r){let o=e[t.name];if(typeof o==="function")return o;let n=e[r];if(typeof n==="function")return n;return(i)=>t(e,i)}var gNt=2n**(8n-1n)-1n,yNt=2n**(16n-1n)-1n,bNt=2n**(24n-1n)-1n,xNt=2n**(32n-1n)-1n,vNt=2n**(40n-1n)-1n,_Nt=2n**(48n-1n)-1n,wNt=2n**(56n-1n)-1n,SNt=2n**(64n-1n)-1n,TNt=2n**(72n-1n)-1n,ENt=2n**(80n-1n)-1n,INt=2n**(88n-1n)-1n,PNt=2n**(96n-1n)-1n,kNt=2n**(104n-1n)-1n,ANt=2n**(112n-1n)-1n,$Nt=2n**(120n-1n)-1n,RNt=2n**(128n-1n)-1n,ONt=2n**(136n-1n)-1n,CNt=2n**(144n-1n)-1n,zNt=2n**(152n-1n)-1n,NNt=2n**(160n-1n)-1n,MNt=2n**(168n-1n)-1n,BNt=2n**(176n-1n)-1n,DNt=2n**(184n-1n)-1n,UNt=2n**(192n-1n)-1n,LNt=2n**(200n-1n)-1n,jNt=2n**(208n-1n)-1n,FNt=2n**(216n-1n)-1n,qNt=2n**(224n-1n)-1n,HNt=2n**(232n-1n)-1n,GNt=2n**(240n-1n)-1n,VNt=2n**(248n-1n)-1n,ZNt=2n**(256n-1n)-1n,WNt=-(2n**(8n-1n)),KNt=-(2n**(16n-1n)),JNt=-(2n**(24n-1n)),YNt=-(2n**(32n-1n)),QNt=-(2n**(40n-1n)),XNt=-(2n**(48n-1n)),eMt=-(2n**(56n-1n)),tMt=-(2n**(64n-1n)),rMt=-(2n**(72n-1n)),nMt=-(2n**(80n-1n)),oMt=-(2n**(88n-1n)),iMt=-(2n**(96n-1n)),sMt=-(2n**(104n-1n)),aMt=-(2n**(112n-1n)),cMt=-(2n**(120n-1n)),uMt=-(2n**(128n-1n)),lMt=-(2n**(136n-1n)),dMt=-(2n**(144n-1n)),pMt=-(2n**(152n-1n)),fMt=-(2n**(160n-1n)),mMt=-(2n**(168n-1n)),hMt=-(2n**(176n-1n)),gMt=-(2n**(184n-1n)),yMt=-(2n**(192n-1n)),bMt=-(2n**(200n-1n)),xMt=-(2n**(208n-1n)),vMt=-(2n**(216n-1n)),_Mt=-(2n**(224n-1n)),wMt=-(2n**(232n-1n)),SMt=-(2n**(240n-1n)),TMt=-(2n**(248n-1n)),EMt=-(2n**(256n-1n)),IMt=2n**8n-1n,PMt=2n**16n-1n,kMt=2n**24n-1n,AMt=2n**32n-1n,$Mt=2n**40n-1n,RMt=2n**48n-1n,OMt=2n**56n-1n,CMt=2n**64n-1n,zMt=2n**72n-1n,NMt=2n**80n-1n,MMt=2n**88n-1n,BMt=2n**96n-1n,DMt=2n**104n-1n,UMt=2n**112n-1n,LMt=2n**120n-1n,jMt=2n**128n-1n,FMt=2n**136n-1n,qMt=2n**144n-1n,HMt=2n**152n-1n,GMt=2n**160n-1n,VMt=2n**168n-1n,ZMt=2n**176n-1n,WMt=2n**184n-1n,KMt=2n**192n-1n,JMt=2n**200n-1n,YMt=2n**208n-1n,QMt=2n**216n-1n,XMt=2n**224n-1n,e4t=2n**232n-1n,t4t=2n**240n-1n,r4t=2n**248n-1n,vf=2n**256n-1n;class Ht extends q{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}class Qn extends Map{constructor(e){super();Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);if(super.has(e))super.delete(e),super.set(e,t);return t}set(e,t){if(super.has(e))super.delete(e);if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let r=super.keys().next().value;if(r!==void 0)super.delete(r)}return this}}pw();function pr(e,t){let r=t||"hex",o=Zd(Hr(e,{strict:!1})?bf(e):e);if(r==="bytes")return o;return Gr(o)}var I5=new Qn(8192);function Gs(e,t){if(I5.has(`${e}.${t}`))return I5.get(`${e}.${t}`);let r=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),o=pr(T5(r),"bytes"),n=(t?r.substring(`${t}0x`.length):r).split("");for(let s=0;s<40;s+=2){if(o[s>>1]>>4>=8&&n[s])n[s]=n[s].toUpperCase();if((o[s>>1]&15)>=8&&n[s+1])n[s+1]=n[s+1].toUpperCase()}let i=`0x${n.join("")}`;return I5.set(`${e}.${t}`,i),i}function jZ(e,t){if(!At(e,{strict:!1}))throw new Ht({address:e});return Gs(e,t)}var W0e=/^0x[a-fA-F0-9]{40}$/,P5=new Qn(8192);function At(e,t){let{strict:r=!0}=t??{},o=`${e}.${r}`;if(P5.has(o))return P5.get(o);let n=(()=>{if(!W0e.test(e))return!1;if(e.toLowerCase()===e)return!0;if(r)return Gs(e)===e;return!0})();return P5.set(o,n),n}function wo(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:o,to:n}=e,i=t?ft(t):void 0;if(i&&!At(i.address))throw new Ht({address:i.address});if(n&&!At(n))throw new Ht({address:n});if(r&&r>vf)throw new ti({maxFeePerGas:r});if(o&&r&&o>r)throw new Ls({maxFeePerGas:r,maxPriorityFeePerGas:o})}class Py extends q{constructor({blockHash:e,blockNumber:t}){let r="Block";if(e)r=`Block at hash "${e}"`;if(t)r=`Block at number "${t}"`;super(`${r} could not be found.`,{name:"BlockNotFoundError"})}}function FZ(e,t){let r=(e.transactions??[]).map((o)=>{if(typeof o==="string")return o;return xf(o)});return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}async function ni(e,{blockHash:t,blockNumber:r,blockTag:o=e.experimental_blockTag??"latest",includeTransactions:n}={}){let i=n??!1,s=r!==void 0?ae(r):void 0,a=null;if(t)a=await e.request({method:"eth_getBlockByHash",params:[t,i]},{dedupe:!0});else a=await e.request({method:"eth_getBlockByNumber",params:[s||o,i]},{dedupe:Boolean(s)});if(!a)throw new Py({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||FZ)(a,"getBlock")}async function en(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return Pr(t)}async function hS(e,t){let{account:r=e.account,accessList:o,authorizationList:n,chain:i=e.chain,blobVersionedHashes:s,blobs:a,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:y,nonceManager:x,to:S,type:v,value:E,...w}=t,_=await(async()=>{if(!r)return y;if(!x)return y;if(typeof y<"u")return y;let z=ft(r),B=i?i.id:await Ne(e,en,"getChainId")({});return await x.consume({address:z.address,chainId:B,client:e})})();wo(t);let T=i?.formatters?.transactionRequest?.format,O=(T||Di)({...yc(w,{format:T}),account:r?ft(r):void 0,accessList:o,authorizationList:n,blobs:a,blobVersionedHashes:s,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:_,to:S,type:v,value:E},"fillTransaction");try{let z=await e.request({method:"eth_fillTransaction",params:[O]}),k=(i?.formatters?.transaction?.format||xf)(z.tx);if(delete k.blockHash,delete k.blockNumber,delete k.r,delete k.s,delete k.transactionIndex,delete k.v,delete k.yParity,k.data=k.input,k.gas)k.gas=t.gas??k.gas;if(k.gasPrice)k.gasPrice=t.gasPrice??k.gasPrice;if(k.maxFeePerBlobGas)k.maxFeePerBlobGas=t.maxFeePerBlobGas??k.maxFeePerBlobGas;if(k.maxFeePerGas)k.maxFeePerGas=t.maxFeePerGas??k.maxFeePerGas;if(k.maxPriorityFeePerGas)k.maxPriorityFeePerGas=t.maxPriorityFeePerGas??k.maxPriorityFeePerGas;if(typeof k.nonce<"u")k.nonce=t.nonce??k.nonce;let G=await(async()=>{if(typeof i?.fees?.baseFeeMultiplier==="function"){let H=await Ne(e,ni,"getBlock")({});return i.fees.baseFeeMultiplier({block:H,client:e,request:t})}return i?.fees?.baseFeeMultiplier??1.2})();if(G<1)throw new gy;let ue=10**(G.toString().split(".")[1]?.length??0),W=(H)=>H*BigInt(Math.ceil(G*ue))/BigInt(ue);if(!k.feePayerSignature){if(k.maxFeePerGas&&!t.maxFeePerGas)k.maxFeePerGas=W(k.maxFeePerGas);if(k.gasPrice&&!t.gasPrice)k.gasPrice=W(k.gasPrice)}return{raw:z.raw,transaction:{from:O.from,...k},...z.capabilities?{capabilities:z.capabilities}:{}}}catch(z){throw gc(z,{...t,chain:e.chain})}}async function qZ(e,{chain:t}){let{id:r,name:o,nativeCurrency:n,rpcUrls:i,blockExplorers:s}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:ae(r),chainName:o,nativeCurrency:n,rpcUrls:i.default.http,blockExplorerUrls:s?Object.values(s).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}function Ui(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new k5(e.type);return`${e.name}(${gS(e.inputs,{includeName:t})})`}function gS(e,{includeName:t=!1}={}){if(!e)return"";return e.map((r)=>K0e(r,{includeName:t})).join(t?", ":",")}function K0e(e,{includeName:t}){if(e.type.startsWith("tuple"))return`(${gS(e.components,{includeName:t})})${e.type.slice(5)}`;return e.type+(t&&e.name?` ${e.name}`:"")}class A5 extends q{constructor({docsPath:e}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
153
+ `)})}}Object.defineProperty(pc,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32000});class rf extends Sn{constructor(e){super(e,{code:rf.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(rf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class nf extends Sn{constructor(e){super(e,{code:nf.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(nf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class of extends Sn{constructor(e){super(e,{code:of.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(of,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class fc extends Sn{constructor(e,{method:t}={}){super(e,{code:fc.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${t?` "${t}"`:""} is not supported.`})}}Object.defineProperty(fc,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class Qu extends Sn{constructor(e){super(e,{code:Qu.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(Qu,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class sf extends Sn{constructor(e){super(e,{code:sf.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(sf,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Xu extends Tn{constructor(e){super(e,{code:Xu.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Xu,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class af extends Tn{constructor(e){super(e,{code:af.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(af,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class cf extends Tn{constructor(e,{method:t}={}){super(e,{code:cf.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${t?` " ${t}"`:""}.`})}}Object.defineProperty(cf,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class uf extends Tn{constructor(e){super(e,{code:uf.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(uf,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class lf extends Tn{constructor(e){super(e,{code:lf.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(lf,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class df extends Tn{constructor(e){super(e,{code:df.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(df,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class mc extends Tn{constructor(e){super(e,{code:mc.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(mc,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class pf extends Tn{constructor(e){super(e,{code:pf.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(pf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class ff extends Tn{constructor(e){super(e,{code:ff.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(ff,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class mf extends Tn{constructor(e){super(e,{code:mf.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(mf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class hf extends Tn{constructor(e){super(e,{code:hf.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(hf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class gf extends Tn{constructor(e){super(e,{code:gf.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(gf,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class hc extends Tn{constructor(e){super(e,{code:hc.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(hc,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class yf extends Tn{constructor(e){super(e,{code:yf.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}}Object.defineProperty(yf,"code",{enumerable:!0,configurable:!0,writable:!0,value:7000});class v5 extends Sn{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}function dS(e,t){let r=(e.details||"").toLowerCase(),o=e instanceof q?e.walk((n)=>n?.code===lc.code):e;if(o instanceof q)return new lc({cause:e,message:o.details});if(lc.nodeMessage.test(r))return new lc({cause:e,message:e.details});if(ti.nodeMessage.test(r))return new ti({cause:e,maxFeePerGas:t?.maxFeePerGas});if(yy.nodeMessage.test(r))return new yy({cause:e,maxFeePerGas:t?.maxFeePerGas});if(by.nodeMessage.test(r))return new by({cause:e,nonce:t?.nonce});if(xy.nodeMessage.test(r))return new xy({cause:e,nonce:t?.nonce});if(vy.nodeMessage.test(r))return new vy({cause:e,nonce:t?.nonce});if(_y.nodeMessage.test(r))return new _y({cause:e});if(wy.nodeMessage.test(r))return new wy({cause:e,gas:t?.gas});if(Sy.nodeMessage.test(r))return new Sy({cause:e,gas:t?.gas});if(Ty.nodeMessage.test(r))return new Ty({cause:e});if(Ls.nodeMessage.test(r))return new Ls({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas});return new Ju({cause:e})}function gc(e,{docsPath:t,...r}){let o=(()=>{let n=dS(e,r);if(n instanceof Ju)return e;return n})();return new b5(o,{docsPath:t,...r})}function yc(e,{format:t}){if(!t)return{};let r={};function o(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]))o(i[a])}}let n=t(e||{});return o(n),r}class el extends q{constructor({max:e,min:t,signed:r,size:o,value:n}){super(`Number "${n}" is not in safe ${o?`${o*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class _5 extends q{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}}class w5 extends q{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Hr(e,{strict:t=!0}={}){if(!e)return!1;if(typeof e!=="string")return!1;return t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function mt(e){if(Hr(e,{strict:!1}))return Math.ceil((e.length-2)/2);return e.length}function _o(e,{dir:t="left"}={}){let r=typeof e==="string"?e.replace("0x",""):e,o=0;for(let n=0;n<r.length-1;n++)if(r[t==="left"?n:r.length-n-1].toString()==="0")o++;else break;if(r=t==="left"?r.slice(o):r.slice(0,r.length-o),typeof e==="string"){if(r.length===1&&t==="right")r=`${r}0`;return`0x${r.length%2===1?`0${r}`:r}`}return r}class pS extends q{constructor({offset:e,position:t,size:r}){super(`Slice ${t==="start"?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${r}).`,{name:"SliceOffsetOutOfBoundsError"})}}class fS extends q{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}class mS extends q{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} is expected to be ${t} ${r} long, but is ${e} ${r} long.`,{name:"InvalidBytesLengthError"})}}function bc(e,{dir:t,size:r=32}={}){if(typeof e==="string")return qs(e,{dir:t,size:r});return U0e(e,{dir:t,size:r})}function qs(e,{dir:t,size:r=32}={}){if(r===null)return e;let o=e.replace("0x","");if(o.length>r*2)throw new fS({size:Math.ceil(o.length/2),targetSize:r,type:"hex"});return`0x${o[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function U0e(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new fS({size:e.length,targetSize:r,type:"bytes"});let o=new Uint8Array(r);for(let n=0;n<r;n++){let i=t==="right";o[i?n:r-n-1]=e[i?n:e.length-n-1]}return o}var L0e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Gr(e,t={}){if(typeof e==="number"||typeof e==="bigint")return ae(e,t);if(typeof e==="string")return xc(e,t);if(typeof e==="boolean")return S5(e,t);return Dt(e,t)}function S5(e,t={}){let r=`0x${Number(e)}`;if(typeof t.size==="number")return Yn(r,{size:t.size}),bc(r,{size:t.size});return r}function Dt(e,t={}){let r="";for(let n=0;n<e.length;n++)r+=L0e[e[n]];let o=`0x${r}`;if(typeof t.size==="number")return Yn(o,{size:t.size}),bc(o,{dir:"right",size:t.size});return o}function ae(e,t={}){let{signed:r,size:o}=t,n=BigInt(e),i;if(o)if(r)i=(1n<<BigInt(o)*8n-1n)-1n;else i=2n**(BigInt(o)*8n)-1n;else if(typeof e==="number")i=BigInt(Number.MAX_SAFE_INTEGER);let s=typeof i==="bigint"&&r?-i-1n:0;if(i&&n>i||n<s){let c=typeof e==="bigint"?"n":"";throw new el({max:i?`${i}${c}`:void 0,min:`${s}${c}`,signed:r,size:o,value:`${e}${c}`})}let a=`0x${(r&&n<0?(1n<<BigInt(o*8))+BigInt(n):n).toString(16)}`;if(o)return bc(a,{size:o});return a}var j0e=new TextEncoder;function xc(e,t={}){let r=j0e.encode(e);return Dt(r,t)}var F0e=new TextEncoder;function bf(e,t={}){if(typeof e==="number"||typeof e==="bigint")return H0e(e,t);if(typeof e==="boolean")return q0e(e,t);if(Hr(e))return yr(e,t);return T5(e,t)}function q0e(e,t={}){let r=new Uint8Array(1);if(r[0]=Number(e),typeof t.size==="number")return Yn(r,{size:t.size}),bc(r,{size:t.size});return r}var Hs={zero:48,nine:57,A:65,F:70,a:97,f:102};function LZ(e){if(e>=Hs.zero&&e<=Hs.nine)return e-Hs.zero;if(e>=Hs.A&&e<=Hs.F)return e-(Hs.A-10);if(e>=Hs.a&&e<=Hs.f)return e-(Hs.a-10);return}function yr(e,t={}){let r=e;if(t.size)Yn(r,{size:t.size}),r=bc(r,{dir:"right",size:t.size});let o=r.slice(2);if(o.length%2)o=`0${o}`;let n=o.length/2,i=new Uint8Array(n);for(let s=0,a=0;s<n;s++){let c=LZ(o.charCodeAt(a++)),u=LZ(o.charCodeAt(a++));if(c===void 0||u===void 0)throw new q(`Invalid byte sequence ("${o[a-2]}${o[a-1]}" in "${o}").`);i[s]=c*16+u}return i}function H0e(e,t){let r=ae(e,t);return yr(r)}function T5(e,t={}){let r=F0e.encode(e);if(typeof t.size==="number")return Yn(r,{size:t.size}),bc(r,{dir:"right",size:t.size});return r}function Yn(e,{size:t}){if(mt(e)>t)throw new w5({givenSize:mt(e),maxSize:t})}function Ir(e,t={}){let{signed:r}=t;if(t.size)Yn(e,{size:t.size});let o=BigInt(e);if(!r)return o;let n=(e.length-2)/2,i=(1n<<BigInt(n)*8n-1n)-1n;if(o<=i)return o;return o-BigInt(`0x${"f".padStart(n*2,"f")}`)-1n}function Pr(e,t={}){let r=Ir(e,t),o=Number(r);if(!Number.isSafeInteger(o))throw new el({max:`${Number.MAX_SAFE_INTEGER}`,min:`${Number.MIN_SAFE_INTEGER}`,signed:t.signed,size:t.size,value:`${r}n`});return o}var E5={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function xf(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?Pr(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?Pr(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?E5[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};if(e.authorizationList)r.authorizationList=G0e(e.authorizationList);if(r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v==="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}return})(),r.type==="legacy")delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity;if(r.type==="eip2930")delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas;if(r.type==="eip1559")delete r.maxFeePerBlobGas;return r}function G0e(e){return e.map((t)=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}var V0e={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function Di(e,t){let r={};if(typeof e.authorizationList<"u")r.authorizationList=Z0e(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((o)=>Dt(o));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=ae(e.gas);if(typeof e.gasPrice<"u")r.gasPrice=ae(e.gasPrice);if(typeof e.maxFeePerBlobGas<"u")r.maxFeePerBlobGas=ae(e.maxFeePerBlobGas);if(typeof e.maxFeePerGas<"u")r.maxFeePerGas=ae(e.maxFeePerGas);if(typeof e.maxPriorityFeePerGas<"u")r.maxPriorityFeePerGas=ae(e.maxPriorityFeePerGas);if(typeof e.nonce<"u")r.nonce=ae(e.nonce);if(typeof e.to<"u")r.to=e.to;if(typeof e.type<"u")r.type=V0e[e.type];if(typeof e.value<"u")r.value=ae(e.value);return r}function Z0e(e){return e.map((t)=>({address:t.address,r:t.r?ae(BigInt(t.r)):t.r,s:t.s?ae(BigInt(t.s)):t.s,chainId:ae(t.chainId),nonce:ae(t.nonce),...typeof t.yParity<"u"?{yParity:ae(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:ae(t.v)}:{}}))}function Ne(e,t,r){let o=e[t.name];if(typeof o==="function")return o;let n=e[r];if(typeof n==="function")return n;return(i)=>t(e,i)}var yNt=2n**(8n-1n)-1n,bNt=2n**(16n-1n)-1n,xNt=2n**(24n-1n)-1n,vNt=2n**(32n-1n)-1n,_Nt=2n**(40n-1n)-1n,wNt=2n**(48n-1n)-1n,SNt=2n**(56n-1n)-1n,TNt=2n**(64n-1n)-1n,ENt=2n**(72n-1n)-1n,INt=2n**(80n-1n)-1n,PNt=2n**(88n-1n)-1n,kNt=2n**(96n-1n)-1n,ANt=2n**(104n-1n)-1n,$Nt=2n**(112n-1n)-1n,RNt=2n**(120n-1n)-1n,ONt=2n**(128n-1n)-1n,CNt=2n**(136n-1n)-1n,zNt=2n**(144n-1n)-1n,NNt=2n**(152n-1n)-1n,MNt=2n**(160n-1n)-1n,BNt=2n**(168n-1n)-1n,DNt=2n**(176n-1n)-1n,UNt=2n**(184n-1n)-1n,LNt=2n**(192n-1n)-1n,jNt=2n**(200n-1n)-1n,FNt=2n**(208n-1n)-1n,qNt=2n**(216n-1n)-1n,HNt=2n**(224n-1n)-1n,GNt=2n**(232n-1n)-1n,VNt=2n**(240n-1n)-1n,ZNt=2n**(248n-1n)-1n,WNt=2n**(256n-1n)-1n,KNt=-(2n**(8n-1n)),JNt=-(2n**(16n-1n)),YNt=-(2n**(24n-1n)),QNt=-(2n**(32n-1n)),XNt=-(2n**(40n-1n)),eMt=-(2n**(48n-1n)),tMt=-(2n**(56n-1n)),rMt=-(2n**(64n-1n)),nMt=-(2n**(72n-1n)),oMt=-(2n**(80n-1n)),iMt=-(2n**(88n-1n)),sMt=-(2n**(96n-1n)),aMt=-(2n**(104n-1n)),cMt=-(2n**(112n-1n)),uMt=-(2n**(120n-1n)),lMt=-(2n**(128n-1n)),dMt=-(2n**(136n-1n)),pMt=-(2n**(144n-1n)),fMt=-(2n**(152n-1n)),mMt=-(2n**(160n-1n)),hMt=-(2n**(168n-1n)),gMt=-(2n**(176n-1n)),yMt=-(2n**(184n-1n)),bMt=-(2n**(192n-1n)),xMt=-(2n**(200n-1n)),vMt=-(2n**(208n-1n)),_Mt=-(2n**(216n-1n)),wMt=-(2n**(224n-1n)),SMt=-(2n**(232n-1n)),TMt=-(2n**(240n-1n)),EMt=-(2n**(248n-1n)),IMt=-(2n**(256n-1n)),PMt=2n**8n-1n,kMt=2n**16n-1n,AMt=2n**24n-1n,$Mt=2n**32n-1n,RMt=2n**40n-1n,OMt=2n**48n-1n,CMt=2n**56n-1n,zMt=2n**64n-1n,NMt=2n**72n-1n,MMt=2n**80n-1n,BMt=2n**88n-1n,DMt=2n**96n-1n,UMt=2n**104n-1n,LMt=2n**112n-1n,jMt=2n**120n-1n,FMt=2n**128n-1n,qMt=2n**136n-1n,HMt=2n**144n-1n,GMt=2n**152n-1n,VMt=2n**160n-1n,ZMt=2n**168n-1n,WMt=2n**176n-1n,KMt=2n**184n-1n,JMt=2n**192n-1n,YMt=2n**200n-1n,QMt=2n**208n-1n,XMt=2n**216n-1n,e4t=2n**224n-1n,t4t=2n**232n-1n,r4t=2n**240n-1n,n4t=2n**248n-1n,vf=2n**256n-1n;class Ht extends q{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}class Qn extends Map{constructor(e){super();Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);if(super.has(e))super.delete(e),super.set(e,t);return t}set(e,t){if(super.has(e))super.delete(e);if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let r=super.keys().next().value;if(r!==void 0)super.delete(r)}return this}}pw();function pr(e,t){let r=t||"hex",o=Zd(Hr(e,{strict:!1})?bf(e):e);if(r==="bytes")return o;return Gr(o)}var I5=new Qn(8192);function Gs(e,t){if(I5.has(`${e}.${t}`))return I5.get(`${e}.${t}`);let r=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),o=pr(T5(r),"bytes"),n=(t?r.substring(`${t}0x`.length):r).split("");for(let s=0;s<40;s+=2){if(o[s>>1]>>4>=8&&n[s])n[s]=n[s].toUpperCase();if((o[s>>1]&15)>=8&&n[s+1])n[s+1]=n[s+1].toUpperCase()}let i=`0x${n.join("")}`;return I5.set(`${e}.${t}`,i),i}function jZ(e,t){if(!At(e,{strict:!1}))throw new Ht({address:e});return Gs(e,t)}var W0e=/^0x[a-fA-F0-9]{40}$/,P5=new Qn(8192);function At(e,t){let{strict:r=!0}=t??{},o=`${e}.${r}`;if(P5.has(o))return P5.get(o);let n=(()=>{if(!W0e.test(e))return!1;if(e.toLowerCase()===e)return!0;if(r)return Gs(e)===e;return!0})();return P5.set(o,n),n}function wo(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:o,to:n}=e,i=t?ft(t):void 0;if(i&&!At(i.address))throw new Ht({address:i.address});if(n&&!At(n))throw new Ht({address:n});if(r&&r>vf)throw new ti({maxFeePerGas:r});if(o&&r&&o>r)throw new Ls({maxFeePerGas:r,maxPriorityFeePerGas:o})}class Py extends q{constructor({blockHash:e,blockNumber:t}){let r="Block";if(e)r=`Block at hash "${e}"`;if(t)r=`Block at number "${t}"`;super(`${r} could not be found.`,{name:"BlockNotFoundError"})}}function FZ(e,t){let r=(e.transactions??[]).map((o)=>{if(typeof o==="string")return o;return xf(o)});return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}async function ni(e,{blockHash:t,blockNumber:r,blockTag:o=e.experimental_blockTag??"latest",includeTransactions:n}={}){let i=n??!1,s=r!==void 0?ae(r):void 0,a=null;if(t)a=await e.request({method:"eth_getBlockByHash",params:[t,i]},{dedupe:!0});else a=await e.request({method:"eth_getBlockByNumber",params:[s||o,i]},{dedupe:Boolean(s)});if(!a)throw new Py({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||FZ)(a,"getBlock")}async function en(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return Pr(t)}async function hS(e,t){let{account:r=e.account,accessList:o,authorizationList:n,chain:i=e.chain,blobVersionedHashes:s,blobs:a,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:y,nonceManager:x,to:S,type:v,value:E,...w}=t,_=await(async()=>{if(!r)return y;if(!x)return y;if(typeof y<"u")return y;let z=ft(r),B=i?i.id:await Ne(e,en,"getChainId")({});return await x.consume({address:z.address,chainId:B,client:e})})();wo(t);let T=i?.formatters?.transactionRequest?.format,O=(T||Di)({...yc(w,{format:T}),account:r?ft(r):void 0,accessList:o,authorizationList:n,blobs:a,blobVersionedHashes:s,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:_,to:S,type:v,value:E},"fillTransaction");try{let z=await e.request({method:"eth_fillTransaction",params:[O]}),k=(i?.formatters?.transaction?.format||xf)(z.tx);if(delete k.blockHash,delete k.blockNumber,delete k.r,delete k.s,delete k.transactionIndex,delete k.v,delete k.yParity,k.data=k.input,k.gas)k.gas=t.gas??k.gas;if(k.gasPrice)k.gasPrice=t.gasPrice??k.gasPrice;if(k.maxFeePerBlobGas)k.maxFeePerBlobGas=t.maxFeePerBlobGas??k.maxFeePerBlobGas;if(k.maxFeePerGas)k.maxFeePerGas=t.maxFeePerGas??k.maxFeePerGas;if(k.maxPriorityFeePerGas)k.maxPriorityFeePerGas=t.maxPriorityFeePerGas??k.maxPriorityFeePerGas;if(typeof k.nonce<"u")k.nonce=t.nonce??k.nonce;let G=await(async()=>{if(typeof i?.fees?.baseFeeMultiplier==="function"){let H=await Ne(e,ni,"getBlock")({});return i.fees.baseFeeMultiplier({block:H,client:e,request:t})}return i?.fees?.baseFeeMultiplier??1.2})();if(G<1)throw new gy;let ue=10**(G.toString().split(".")[1]?.length??0),W=(H)=>H*BigInt(Math.ceil(G*ue))/BigInt(ue);if(!k.feePayerSignature){if(k.maxFeePerGas&&!t.maxFeePerGas)k.maxFeePerGas=W(k.maxFeePerGas);if(k.gasPrice&&!t.gasPrice)k.gasPrice=W(k.gasPrice)}return{raw:z.raw,transaction:{from:O.from,...k},...z.capabilities?{capabilities:z.capabilities}:{}}}catch(z){throw gc(z,{...t,chain:e.chain})}}async function qZ(e,{chain:t}){let{id:r,name:o,nativeCurrency:n,rpcUrls:i,blockExplorers:s}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:ae(r),chainName:o,nativeCurrency:n,rpcUrls:i.default.http,blockExplorerUrls:s?Object.values(s).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}function Ui(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new k5(e.type);return`${e.name}(${gS(e.inputs,{includeName:t})})`}function gS(e,{includeName:t=!1}={}){if(!e)return"";return e.map((r)=>K0e(r,{includeName:t})).join(t?", ":",")}function K0e(e,{includeName:t}){if(e.type.startsWith("tuple"))return`(${gS(e.components,{includeName:t})})${e.type.slice(5)}`;return e.type+(t&&e.name?` ${e.name}`:"")}class A5 extends q{constructor({docsPath:e}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
154
154
  `),{docsPath:e,name:"AbiConstructorNotFoundError"})}}class yS extends q{constructor({docsPath:e}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
155
155
  `),{docsPath:e,name:"AbiConstructorParamsNotFoundError"})}}class $5 extends q{constructor({data:e,params:t,size:r}){super([`Data size of ${r} bytes is too small for given parameters.`].join(`
156
156
  `),{metaMessages:[`Params: (${gS(t,{includeName:!0})})`,`Data: ${e} (${r} bytes)`],name:"AbiDecodingDataSizeTooSmallError"});Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e,this.params=t,this.size=r}}class tl extends q{constructor({cause:e}={}){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError",cause:e})}}class R5 extends q{constructor({expectedLength:e,givenLength:t,type:r}){super([`ABI encoding array length mismatch for type ${r}.`,`Expected length: ${e}`,`Given length: ${t}`].join(`
@@ -166,4 +166,4 @@ ${t}`}function K_(e,t){return uu(G_.sign(Dd(t),e))}var lg=[0.0001,0.001,0.01,0.1
166
166
  `),{name:"ChainNotFoundError"})}}class Sf extends q{constructor({chainId:e}){super(typeof e==="number"?`Chain ID "${e}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}function Tf({chain:e,currentChainId:t}){if(!e)throw new V5;if(t!==e.id)throw new G5({chain:e,currentChainId:t})}async function ES(e){let t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function XZ(e,t){let{block:r,chain:o=e.chain,request:n}=t||{};try{let i=o?.fees?.maxPriorityFeePerGas??o?.fees?.defaultPriorityFee;if(typeof i==="function"){let a=r||await Ne(e,ni,"getBlock")({}),c=await i({block:a,client:e,request:n});if(c===null)throw Error();return c}if(typeof i<"u")return i;let s=await e.request({method:"eth_maxPriorityFeePerGas"});return Ir(s)}catch{let[i,s]=await Promise.all([r?Promise.resolve(r):Ne(e,ni,"getBlock")({}),Ne(e,ES,"getGasPrice")({})]);if(typeof i.baseFeePerGas!=="bigint")throw new Ku;let a=s-i.baseFeePerGas;if(a<0n)return 0n;return a}}async function Z5(e,t){let{block:r,chain:o=e.chain,request:n,type:i="eip1559"}=t||{},s=await(async()=>{if(typeof o?.fees?.baseFeeMultiplier==="function")return o.fees.baseFeeMultiplier({block:r,client:e,request:n});return o?.fees?.baseFeeMultiplier??1.2})();if(s<1)throw new gy;let c=10**(s.toString().split(".")[1]?.length??0),u=(m)=>m*BigInt(Math.ceil(s*c))/BigInt(c),d=r?r:await Ne(e,ni,"getBlock")({});if(typeof o?.fees?.estimateFeesPerGas==="function"){let m=await o.fees.estimateFeesPerGas({block:r,client:e,multiply:u,request:n,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof d.baseFeePerGas!=="bigint")throw new Ku;let m=typeof n?.maxPriorityFeePerGas==="bigint"?n.maxPriorityFeePerGas:await XZ(e,{block:d,chain:o,request:n}),h=u(d.baseFeePerGas);return{maxFeePerGas:n?.maxFeePerGas??h+m,maxPriorityFeePerGas:m}}return{gasPrice:n?.gasPrice??u(await Ne(e,ES,"getGasPrice")({}))}}class W5 extends q{constructor(e,{account:t,docsPath:r,chain:o,data:n,gas:i,gasPrice:s,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:u,to:d,value:p}){let m=Jp({from:t?.address,to:d,value:typeof p<"u"&&`${cS(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:n,gas:i,gasPrice:typeof s<"u"&&`${wn(s)} gwei`,maxFeePerGas:typeof a<"u"&&`${wn(a)} gwei`,maxPriorityFeePerGas:typeof c<"u"&&`${wn(c)} gwei`,nonce:u});super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",m].filter(Boolean),name:"EstimateGasExecutionError"});Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}function eW(e,{docsPath:t,...r}){let o=(()=>{let n=dS(e,r);if(n instanceof Ju)return e;return n})();return new W5(o,{docsPath:t,...r})}class K5 extends q{constructor({address:e}){super(`State for account "${e}" is set multiple times.`,{name:"AccountStateConflictError"})}}class J5 extends q{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function tW(e){if(!e||e.length===0)return;return e.reduce((t,{slot:r,value:o})=>{if(r.length!==66)throw new mS({size:r.length,targetSize:66,type:"hex"});if(o.length!==66)throw new mS({size:o.length,targetSize:66,type:"hex"});return t[r]=o,t},{})}function cxe(e){let{balance:t,nonce:r,state:o,stateDiff:n,code:i}=e,s={};if(i!==void 0)s.code=i;if(t!==void 0)s.balance=ae(t);if(r!==void 0)s.nonce=ae(r);if(o!==void 0)s.state=tW(o);if(n!==void 0){if(s.state)throw new J5;s.stateDiff=tW(n)}return s}function rW(e){if(!e)return;let t={};for(let{address:r,...o}of e){if(!At(r,{strict:!1}))throw new Ht({address:r});if(t[r])throw new K5({address:r});t[r]=cxe(o)}return t}async function nW(e,t){let{account:r=e.account,prepare:o=!0}=t,n=r?ft(r):void 0,i=(()=>{if(Array.isArray(o))return o;if(n?.type!=="local")return["blobVersionedHashes"];return})();try{let s=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await wf({authorization:t.authorizationList[0]}).catch(()=>{throw new q("`to` is required. Could not infer from `authorizationList`")});return})(),{accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:d,blockNumber:p,blockTag:m,data:h,gas:y,gasPrice:x,maxFeePerBlobGas:S,maxFeePerGas:v,maxPriorityFeePerGas:E,nonce:w,value:_,stateOverride:T,...P}=o?await vc(e,{...t,parameters:i,to:s}):t;if(y&&t.gas!==y)return y;let z=(typeof p==="bigint"?ae(p):void 0)||m,B=rW(T);wo(t);let k=e.chain?.formatters?.transactionRequest?.format,V=(k||Di)({...yc(P,{format:k}),account:n,accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:d,data:h,gasPrice:x,maxFeePerBlobGas:S,maxFeePerGas:v,maxPriorityFeePerGas:E,nonce:w,to:s,value:_},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:B?[V,z??e.experimental_blockTag??"latest",B]:z?[V,z]:[V]}))}catch(s){throw eW(s,{...t,account:n,chain:e.chain})}}function oW(e){let{blockHash:t,blockNumber:r,blockTag:o,requireCanonical:n}=e;if(n!==void 0&&!t)throw new q("`requireCanonical` can only be provided when `blockHash` is set.");if(t)return n?{blockHash:t,requireCanonical:n}:{blockHash:t};if(typeof r==="bigint")return ae(r);return o??"latest"}async function IS(e,{address:t,blockHash:r,blockNumber:o,blockTag:n="latest",requireCanonical:i}){let s=oW({blockHash:r,blockNumber:o,blockTag:n,requireCanonical:i}),a=await e.request({method:"eth_getTransactionCount",params:[t,s]},{dedupe:typeof o==="bigint"||r!==void 0});return Pr(a)}function Ef(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),o=typeof e.blobs[0]==="string"?e.blobs.map((i)=>yr(i)):e.blobs,n=[];for(let i of o)n.push(Uint8Array.from(t.blobToKzgCommitment(i)));return r==="bytes"?n:n.map((i)=>Dt(i))}function If(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),o=typeof e.blobs[0]==="string"?e.blobs.map((s)=>yr(s)):e.blobs,n=typeof e.commitments[0]==="string"?e.commitments.map((s)=>yr(s)):e.commitments,i=[];for(let s=0;s<o.length;s++){let a=o[s],c=n[s];i.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map((s)=>Dt(s))}function iW(e,t){let r=t||"hex",o=u1(Hr(e,{strict:!1})?bf(e):e);if(r==="bytes")return o;return Gr(o)}function sW(e){let{commitment:t,version:r=1}=e,o=e.to??(typeof t==="string"?"hex":"bytes"),n=iW(t,"bytes");return n.set([r],0),o==="bytes"?n:Dt(n)}function PS(e){let{commitments:t,version:r}=e,o=e.to??(typeof t[0]==="string"?"hex":"bytes"),n=[];for(let i of t)n.push(sW({commitment:i,to:o,version:r}));return n}var aW=32,cW=4096,uW=131072,Y5=761855;var kS=1;class Q5 extends q{constructor({maxSize:e,size:t}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${t} bytes`],name:"BlobSizeTooLargeError"})}}class Ay extends q{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class X5 extends q{constructor({hash:e,size:t}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${t}`],name:"InvalidVersionedHashSizeError"})}}class eC extends q{constructor({hash:e,version:t}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:[`Expected: ${kS}`,`Received: ${t}`],name:"InvalidVersionedHashVersionError"})}}function lW(e){let t=e.to??(typeof e.data==="string"?"hex":"bytes"),r=typeof e.data==="string"?yr(e.data):e.data,o=mt(r);if(!o)throw new Ay;if(o>Y5)throw new Q5({maxSize:Y5,size:o});let n=[],i=!0,s=0;while(i){let a=_f(new Uint8Array(uW)),c=0;while(c<cW){let u=r.slice(s,s+(aW-1));if(a.pushByte(0),a.pushBytes(u),u.length<31){a.pushByte(128),i=!1;break}c++,s+=31}n.push(a)}return t==="bytes"?n.map((a)=>a.bytes):n.map((a)=>Dt(a.bytes))}function AS(e){let{data:t,kzg:r,to:o}=e,n=e.blobs??lW({data:t,to:o}),i=e.commitments??Ef({blobs:n,kzg:r,to:o}),s=e.proofs??If({blobs:n,commitments:i,kzg:r,to:o}),a=[];for(let c=0;c<n.length;c++)a.push({blob:n[c],commitment:i[c],proof:s[c]});return a}function $S(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u"){if(typeof e.accessList<"u")return"eip2930";return"legacy"}throw new g5({transaction:e})}var $y=["blobVersionedHashes","chainId","fees","gas","nonce","type"],dW=new Map,tC=new Qn(128);async function vc(e,t){let r=t;r.account??=e.account,r.parameters??=$y;let{account:o,chain:n=e.chain,nonceManager:i,parameters:s}=r,a=(()=>{if(typeof n?.prepareTransactionRequest==="function")return{fn:n.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(n?.prepareTransactionRequest))return{fn:n.prepareTransactionRequest[0],runAt:n.prepareTransactionRequest[1].runAt};return})(),c;async function u(){if(c)return c;if(typeof r.chainId<"u")return r.chainId;if(n)return n.id;return c=await Ne(e,en,"getChainId")({}),c}let d=o?ft(o):o,p=r.nonce;if(s.includes("nonce")&&typeof p>"u"&&d&&i){let _=await u();p=await i.consume({address:d.address,chainId:_,client:e})}if(a?.fn&&a.runAt?.includes("beforeFillTransaction"))r=await a.fn({...r,chain:n},{client:e,phase:"beforeFillTransaction"}),p??=r.nonce;let h=(()=>{if((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&r.kzg&&r.blobs)return!1;if(tC.get(e.uid)===!1)return!1;if(!["fees","gas"].some((T)=>s.includes(T)))return!1;if(s.includes("chainId")&&typeof r.chainId!=="number")return!0;if(s.includes("nonce")&&typeof p!=="number")return!0;if(s.includes("fees")&&typeof r.gasPrice!=="bigint"&&(typeof r.maxFeePerGas!=="bigint"||typeof r.maxPriorityFeePerGas!=="bigint"))return!0;if(s.includes("gas")&&typeof r.gas!=="bigint")return!0;return!1})()?await Ne(e,hS,"fillTransaction")({...r,nonce:p}).then((_)=>{let{chainId:T,from:P,gas:O,gasPrice:z,nonce:B,maxFeePerBlobGas:k,maxFeePerGas:G,maxPriorityFeePerGas:V,type:ue,...W}=_.transaction;return tC.set(e.uid,!0),{...r,...P?{from:P}:{},...ue&&!r.type?{type:ue}:{},...typeof T<"u"?{chainId:T}:{},...typeof O<"u"?{gas:O}:{},...typeof z<"u"?{gasPrice:z}:{},...typeof B<"u"?{nonce:B}:{},...typeof k<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerBlobGas:k}:{},...typeof G<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerGas:G}:{},...typeof V<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxPriorityFeePerGas:V}:{},..."nonceKey"in W&&typeof W.nonceKey<"u"?{nonceKey:W.nonceKey}:{},..."keyAuthorization"in W&&typeof W.keyAuthorization<"u"&&W.keyAuthorization!==null&&!("keyAuthorization"in r)?{keyAuthorization:W.keyAuthorization}:{},..."feePayerSignature"in W&&typeof W.feePayerSignature<"u"&&W.feePayerSignature!==null?{feePayerSignature:W.feePayerSignature}:{},..."feeToken"in W&&typeof W.feeToken<"u"&&W.feeToken!==null&&!("feeToken"in r)?{feeToken:W.feeToken}:{},..._.capabilities?{_capabilities:_.capabilities}:{}}}).catch((_)=>{let T=_;if(T.name!=="TransactionExecutionError")return r;if(T.walk?.((z)=>z.name==="ExecutionRevertedError"))throw _;if(T.walk?.((z)=>{let B=z;return B.name==="MethodNotFoundRpcError"||B.name==="MethodNotSupportedRpcError"||B.message?.includes("eth_fillTransaction is not available")}))tC.set(e.uid,!1);return r}):r;p??=h.nonce,r={...h,...d?{from:d?.address}:{},...typeof p<"u"?{nonce:p}:{}};let{blobs:y,gas:x,kzg:S,type:v}=r;if(a?.fn&&a.runAt?.includes("beforeFillParameters"))r=await a.fn({...r,chain:n},{client:e,phase:"beforeFillParameters"});let E;async function w(){if(E)return E;return E=await Ne(e,ni,"getBlock")({blockTag:"latest"}),E}if(s.includes("nonce")&&typeof p>"u"&&d&&!i)r.nonce=await Ne(e,IS,"getTransactionCount")({address:d.address,blockTag:"pending"});if((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&y&&S){let _=Ef({blobs:y,kzg:S});if(s.includes("blobVersionedHashes")){let T=PS({commitments:_,to:"hex"});r.blobVersionedHashes=T}if(s.includes("sidecars")){let T=If({blobs:y,commitments:_,kzg:S}),P=AS({blobs:y,commitments:_,proofs:T,to:"hex"});r.sidecars=P}}if(s.includes("chainId"))r.chainId=await u();if((s.includes("fees")||s.includes("type"))&&typeof v>"u")try{r.type=$S(r)}catch{let _=dW.get(e.uid);if(typeof _>"u")_=typeof(await w())?.baseFeePerGas==="bigint",dW.set(e.uid,_);r.type=_?"eip1559":"legacy"}if(s.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){let _=await w(),{maxFeePerGas:T,maxPriorityFeePerGas:P}=await Z5(e,{block:_,chain:n,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<P)throw new m5({maxPriorityFeePerGas:P});r.maxPriorityFeePerGas=P,r.maxFeePerGas=T}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new Ku;if(typeof r.gasPrice>"u"){let _=await w(),{gasPrice:T}=await Z5(e,{block:_,chain:n,request:r,type:"legacy"});r.gasPrice=T}}if(s.includes("gas")&&typeof x>"u")r.gas=await Ne(e,nW,"estimateGas")({...r,account:d,prepare:d?.type==="local"?[]:["blobVersionedHashes"]});if(a?.fn&&a.runAt?.includes("afterFillParameters"))r=await a.fn({...r,chain:n},{client:e,phase:"afterFillParameters"});return wo(r),delete r.parameters,r}async function RS(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}var rC=new Qn(128);async function _c(e,t){let{account:r=e.account,assertChainId:o=!0,chain:n=e.chain,accessList:i,authorizationList:s,blobs:a,data:c,dataSuffix:u=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,type:S,value:v,...E}=t;if(typeof r>"u")throw new Vr({docsPath:"/docs/actions/wallet/sendTransaction"});let w=r?ft(r):null,_;try{wo(t);let T=await(async()=>{if(t.to)return t.to;if(t.to===null)return;if(s&&s.length>0)return await wf({authorization:s[0]}).catch(()=>{throw new q("`to` is required. Could not infer from `authorizationList`.")});return})();if(w?.type==="json-rpc"||w===null){let P;if(n!==null){if(P=await Ne(e,en,"getChainId")({}),o)Tf({currentChainId:P,chain:n})}let O=e.chain?.formatters?.transactionRequest?.format,B=(O||Di)({...yc(E,{format:O}),accessList:i,account:w,authorizationList:s,blobs:a,chainId:P,data:u?fr([c??"0x",u]):c,gas:d,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,to:T,type:S,value:v},"sendTransaction"),k=rC.get(e.uid),G=k?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:G,params:[B]},{retryCount:0})}catch(V){if(k===!1)throw V;let ue=V;if(ue.name==="InvalidInputRpcError"||ue.name==="InvalidParamsRpcError"||ue.name==="MethodNotFoundRpcError"||ue.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[B]},{retryCount:0}).then((W)=>(rC.set(e.uid,!0),W)).catch((W)=>{let H=W;if(H.name==="MethodNotFoundRpcError"||H.name==="MethodNotSupportedRpcError")throw rC.set(e.uid,!1),ue;throw H});throw ue}}if(w?.type==="local"){if(w.nonceManager&&typeof x>"u"){let B=E.chainId,k=await(async()=>{if(typeof B==="number")return B;if(n)return n.id;return Ne(e,en,"getChainId")({})})();_={address:w.address,chainId:k}}let P=await Ne(e,vc,"prepareTransactionRequest")({account:w,accessList:i,authorizationList:s,blobs:a,chain:n,data:u?fr([c??"0x",u]):c,gas:d,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,nonceManager:w.nonceManager,parameters:[...$y,"sidecars"],type:S,value:v,...E,to:T}),O=n?.serializers?.transaction,z=await w.signTransaction(P,{serializer:O});return await Ne(e,RS,"sendRawTransaction")({serializedTransaction:z})}if(w?.type==="smart")throw new oi({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"});throw new oi({docsPath:"/docs/actions/wallet/sendTransaction",type:w?.type})}catch(T){if(T instanceof oi)throw T;if(_)w?.nonceManager?.reset(_);throw gc(T,{...t,account:w,chain:t.chain||void 0})}}function pW(e,t){let{abi:r,args:o,bytecode:n,...i}=t,s=ZZ({abi:r,args:o,bytecode:n});return _c(e,{...i,...i.authorizationList?{to:null}:{},data:s})}async function fW(e){if(e.account?.type==="local")return[e.account.address];return(await e.request({method:"eth_accounts"},{dedupe:!0})).map((r)=>Gs(r))}function mW(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}var nC={"0x0":"reverted","0x1":"success"};function OS(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map((o)=>mW(o)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Pr(e.transactionIndex):null,status:e.status?nC[e.status]:null,type:e.type?E5[e.type]||e.type:null};if(e.blobGasPrice)r.blobGasPrice=BigInt(e.blobGasPrice);if(e.blobGasUsed)r.blobGasUsed=BigInt(e.blobGasUsed);return r}var uxe=(e)=>pr(bf(e));function hW(e){return uxe(e)}ep();function gW(e){let t=!0,r="",o=0,n="",i=!1;for(let s=0;s<e.length;s++){let a=e[s];if(["(",")",","].includes(a))t=!0;if(a==="(")o++;if(a===")")o--;if(!t)continue;if(o===0){if(a===" "&&["event","function",""].includes(n))n="";else if(n+=a,a===")"){i=!0;break}continue}if(a===" "){if(e[s-1]!==","&&r!==","&&r!==",(")r="",t=!1;continue}n+=a,r+=a}if(!i)throw new q("Unable to normalize signature.");return n}var yW=(e)=>{let t=(()=>{if(typeof e==="string")return e;return $s(e)})();return gW(t)};function CS(e){return hW(yW(e))}var Pf=(e)=>Vs(CS(e),0,4);var bW=CS;function zS(e){let{abi:t,args:r=[],name:o}=e,n=Hr(o,{strict:!1}),i=t.filter((a)=>{if(n){if(a.type==="function")return Pf(a)===o;if(a.type==="event")return bW(a)===o;return!1}return"name"in a&&a.name===o});if(i.length===0)return;if(i.length===1)return i[0];let s;for(let a of i){if(!("inputs"in a))continue;if(!r||r.length===0){if(!a.inputs||a.inputs.length===0)return a;continue}if(!a.inputs)continue;if(a.inputs.length===0)continue;if(a.inputs.length!==r.length)continue;if(r.every((u,d)=>{let p="inputs"in a&&a.inputs[d];if(!p)return!1;return oC(u,p)})){if(s&&"inputs"in s&&s.inputs){let u=xW(a.inputs,s.inputs,r);if(u)throw new z5({abiItem:a,type:u[0]},{abiItem:s,type:u[1]})}s=a}}if(s)return s;return i[0]}function oC(e,t){let r=typeof e,o=t.type;switch(o){case"address":return At(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:{if(o==="tuple"&&"components"in t)return Object.values(t.components).every((n,i)=>r==="object"&&oC(Object.values(e)[i],n));if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(o))return r==="number"||r==="bigint";if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(o))return r==="string"||e instanceof Uint8Array;if(/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(o))return Array.isArray(e)&&e.every((n)=>oC(n,{...t,type:o.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}}function xW(e,t,r){for(let o in e){let n=e[o],i=t[o];if(n.type==="tuple"&&i.type==="tuple"&&"components"in n&&"components"in i)return xW(n.components,i.components,r[o]);let s=[n.type,i.type];if((()=>{if(s.includes("address")&&s.includes("bytes20"))return!0;if(s.includes("address")&&s.includes("string"))return At(r[o],{strict:!1});if(s.includes("address")&&s.includes("bytes"))return At(r[o],{strict:!1});return!1})())return s}return}var vW="/docs/contract/encodeFunctionData";function _W(e){let{abi:t,args:r,functionName:o}=e,n=t[0];if(o){let i=zS({abi:t,args:r,name:o});if(!i)throw new bS(o,{docsPath:vW});n=i}if(n.type!=="function")throw new bS(void 0,{docsPath:vW});return{abi:[n],functionName:Pf(Ui(n))}}function NS(e){let{args:t}=e,{abi:r,functionName:o}=(()=>{if(e.abi.length===1&&e.functionName?.startsWith("0x"))return e;return _W(e)})(),n=r[0],i=o,s="inputs"in n&&n.inputs?rl(n.inputs,t??[]):void 0;return So([i,s??"0x"])}var iC="0x5792579257925792579257925792579257925792579257925792579257925792",sC=ae(0,{size:32});async function MS(e,t){let{account:r=e.account,chain:o=e.chain,experimental_fallback:n,experimental_fallbackDelay:i=32,forceAtomic:s=!1,id:a,version:c="2.0.0"}=t,u=r?ft(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 p=t.calls.map((m)=>{let h=m,y=h.abi?NS({abi:h.abi,functionName:h.functionName,args:h.args}):h.data;return{data:h.dataSuffix&&y?fr([y,h.dataSuffix]):y,to:h.to,value:h.value?ae(h.value):void 0}});try{let m=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:s,calls:p,capabilities:d,chainId:ae(o.id),from:u?.address,id:a,version:c}]},{retryCount:0});if(typeof m==="string")return{id:m};return m}catch(m){let h=m;if(n&&(h.name==="MethodNotFoundRpcError"||h.name==="MethodNotSupportedRpcError"||h.name==="UnknownRpcError"||h.details.toLowerCase().includes("does not exist / is not available")||h.details.toLowerCase().includes("missing or invalid. request()")||h.details.toLowerCase().includes("did not match any variant of untagged enum")||h.details.toLowerCase().includes("account upgraded to unsupported contract")||h.details.toLowerCase().includes("eip-7702 not supported")||h.details.toLowerCase().includes("unsupported wc_ method")||h.details.toLowerCase().includes("feature toggled misconfigured")||h.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(d){if(Object.values(d).some((v)=>!v.optional))throw new mc(new q("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&&p.length>1)throw new hc(new q("`forceAtomic` is not supported on fallback to `eth_sendTransaction`.",{details:"`forceAtomic` is not supported on fallback to `eth_sendTransaction`."}));let y=[];for(let S of p){try{let v=await _c(e,{account:u,chain:o,data:S.data,to:S.to,value:S.value?Ir(S.value):void 0});y.push({status:"fulfilled",value:v})}catch(v){y.push({reason:v,status:"rejected"})}if(i>0)await new Promise((v)=>setTimeout(v,i))}if(y.every((S)=>S.status==="rejected"))throw y[0].reason;let x=y.map((S)=>{if(S.status==="fulfilled")return S.value;return sC});return{id:fr([...x,ae(o.id,{size:32}),iC])}}throw gc(m,{...t,account:u,chain:t.chain})}}async function BS(e,t){async function r(d){if(d.endsWith(iC.slice(2))){let m=_o(xS(d,-64,-32)),h=xS(d,0,-64).slice(2).match(/.{1,64}/g),y=await Promise.all(h.map((S)=>sC.slice(2)!==S?e.request({method:"eth_getTransactionReceipt",params:[`0x${S}`]},{dedupe:!0}):void 0)),x=(()=>{if(y.some((S)=>S===null))return 100;if(y.every((S)=>S?.status==="0x1"))return 200;if(y.every((S)=>S?.status==="0x0"))return 500;return 600})();return{atomic:!1,chainId:Pr(m),receipts:y.filter(Boolean),status:x,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[d]})}let{atomic:o=!1,chainId:n,receipts:i,version:s="2.0.0",...a}=await r(t.id),[c,u]=(()=>{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:o,chainId:n?Pr(n):void 0,receipts:i?.map((d)=>({...d,blockNumber:Ir(d.blockNumber),gasUsed:Ir(d.gasUsed),status:nC[d.status]}))??[],statusCode:u,status:c,version:s}}async function wW(e,t={}){let{account:r=e.account,chainId:o}=t,n=r?ft(r):void 0,i=o?[n?.address,[ae(o)]]:[n?.address],s=await e.request({method:"wallet_getCapabilities",params:i}),a={};for(let[c,u]of Object.entries(s)){a[Number(c)]={};for(let[d,p]of Object.entries(u)){if(d==="addSubAccount")d="unstable_addSubAccount";a[Number(c)][d]=p}}return typeof o==="number"?a[o]:a}async function SW(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}function TW(e,t){if(!At(e,{strict:!1}))throw new Ht({address:e});if(!At(t,{strict:!1}))throw new Ht({address:t});return e.toLowerCase()===t.toLowerCase()}async function DS(e,t){let{account:r=e.account,chainId:o,nonce:n}=t;if(!r)throw new Vr({docsPath:"/docs/eip7702/prepareAuthorization"});let i=ft(r),s=(()=>{if(!t.executor)return;if(t.executor==="self")return t.executor;return ft(t.executor)})(),a={address:t.contractAddress??t.address,chainId:o,nonce:n};if(typeof a.chainId>"u")a.chainId=e.chain?.id??await Ne(e,en,"getChainId")({});if(typeof a.nonce>"u"){if(a.nonce=await Ne(e,IS,"getTransactionCount")({address:i.address,blockTag:"pending"}),s==="self"||s?.address&&TW(s.address,i.address))a.nonce+=1}return a}async function EW(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map((r)=>jZ(r))}async function IW(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}class aC extends q{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}}var US=new Map,cC=new Map,lxe=0;function nl(e,t,r){let o=++lxe,n=()=>US.get(e)||[],i=()=>{let p=n().filter((m)=>m.id!==o);if(p.length===0){US.delete(e),cC.delete(e);return}US.set(e,p)},s=()=>{let d=n();if(!d.some((m)=>m.id===o))return;let p=cC.get(e);if(d.length===1&&p){let m=p();if(m instanceof Promise)m.catch(()=>{})}i()},a=n();if(US.set(e,[...a,{id:o,fns:t}]),a&&a.length>0)return s;let c={};for(let d in t)c[d]=(...p)=>{let m=n();if(m.length===0)return;for(let h of m)h.fns[d]?.(...p)};let u=r(c);if(typeof u==="function")cC.set(e,u);return s}async function Ry(e,{signal:t}={}){return new Promise((r,o)=>{if(t?.aborted){o(ri(t));return}let n=()=>t?.removeEventListener("abort",s),i=setTimeout(()=>{n(),r()},e),s=()=>{clearTimeout(i),n(),o(ri(t))};t?.addEventListener("abort",s,{once:!0})})}function LS(e,{emitOnBegin:t,initialWaitTime:r,interval:o}){let n=!0,i=()=>n=!1;return(async()=>{let a;if(t)a=await e({unpoll:i});let c=await r?.(a)??o;await Ry(c);let u=async()=>{if(!n)return;await e({unpoll:i}),await Ry(o),u()};u()})(),i}function kf(){let e=()=>{return},t=()=>{return};return{promise:new Promise((o,n)=>{e=o,t=n}),resolve:e,reject:t}}function ol(e,{delay:t=100,retryCount:r=2,shouldRetry:o=()=>!0,signal:n}={}){return new Promise((i,s)=>{let a=async({count:c=0}={})=>{if(n?.aborted){s(ri(n));return}let u=async({error:d})=>{let p=typeof t==="function"?t({count:c,error:d}):t;if(p)try{await Ry(p,{signal:n})}catch(m){s(m);return}a({count:c+1})};try{let d=await e();i(d)}catch(d){if(n?.aborted){s(ri(n));return}if(js(d)){s(d);return}if(c<r&&await o({count:c,error:d}))return u({error:d});s(d)}};a()})}async function jS(e,t){let{id:r,pollingInterval:o=e.pollingInterval,status:n=({statusCode:x})=>x===200||x>=300,retryCount:i=4,retryDelay:s=({count:x})=>~~(1<<x)*200,timeout:a=60000,throwOnFailure:c=!1}=t,u=Yt(["waitForCallsStatus",e.uid,r]),{promise:d,resolve:p,reject:m}=kf(),h,y=nl(u,{resolve:p,reject:m},(x)=>{let S=LS(async()=>{let v=(E)=>{clearTimeout(h),S(),E(),y()};try{let E=await ol(async()=>{let w=await Ne(e,BS,"getCallsStatus")({id:r});if(c&&w.status==="failure")throw new aC(w);return w},{retryCount:i,delay:s});if(!n(E))return;v(()=>x.resolve(E))}catch(E){v(()=>x.reject(E))}},{interval:o,emitOnBegin:!0});return S});return h=a?setTimeout(()=>{y(),clearTimeout(h),m(new PW({id:r}))},a):void 0,await d}class PW extends q{constructor({id:e}){super(`Timed out while waiting for call bundle with id "${e}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}async function kW(e,t){let{chain:r=e.chain}=t,o=t.timeout??Math.max((r?.blockTime??0)*3,5000),n=await Ne(e,MS,"sendCalls")(t);return await Ne(e,jS,"waitForCallsStatus")({...t,id:n.id,timeout:o})}async function FS(e,{serializedTransaction:t,throwOnReceiptRevert:r,timeout:o}){let n=await e.request({method:"eth_sendRawTransactionSync",params:o?[t,o]:[t]},{retryCount:0}),s=(e.chain?.formatters?.transactionReceipt?.format||OS)(n);if(s.status==="reverted"&&r)throw new Yp({receipt:s});return s}async function AW(e,{blockHash:t,blockNumber:r,blockTag:o,hash:n,index:i,sender:s,nonce:a}){let c=o||"latest",u=r!==void 0?ae(r):void 0,d=null;if(n)d=await e.request({method:"eth_getTransactionByHash",params:[n]},{dedupe:!0});else if(t)d=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,ae(i)]},{dedupe:!0});else if((u||c)&&typeof i==="number")d=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[u||c,ae(i)]},{dedupe:Boolean(u)});else if(s&&typeof a==="number")d=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[s,ae(a)]},{dedupe:!0});if(!d)throw new Ey({blockHash:t,blockNumber:r,blockTag:c,hash:n,index:i});return(e.chain?.formatters?.transaction?.format||xf)(d,"getTransaction")}async function qS(e,{hash:t}){let r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new Iy({hash:t});return(e.chain?.formatters?.transactionReceipt?.format||OS)(r,"getTransactionReceipt")}var dxe=new Map,pxe=new Map;function $W(e){let t=(n,i)=>({clear:()=>i.delete(n),get:()=>i.get(n),set:(s)=>i.set(n,s)}),r=t(e,dxe),o=t(e,pxe);return{clear:()=>{r.clear(),o.clear()},promise:r,response:o}}async function RW(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){let o=$W(t),n=o.response.get();if(n&&r>0){if(Date.now()-n.created.getTime()<r)return n.data}let i=o.promise.get();if(!i)i=e(),o.promise.set(i);try{let s=await i;return o.response.set({created:new Date,data:s}),s}finally{o.promise.clear()}}var fxe=(e)=>`blockNumber.${e}`;async function OW(e,{cacheTime:t=e.cacheTime}={}){let r=await RW(()=>e.request({method:"eth_blockNumber"}),{cacheKey:fxe(e.uid),cacheTime:t});return BigInt(r)}function CW(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:o,onError:n,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 p=Yt(["watchBlockNumber",e.uid,t,r,s]);return nl(p,{onBlockNumber:o,onError:n},(m)=>LS(async()=>{try{let h=await Ne(e,OW,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(h===c)return;if(h-c>1&&r)for(let y=c+1n;y<h;y++)m.onBlockNumber(y,c),c=y}if(c===void 0||h>c)m.onBlockNumber(h,c),c=h}catch(h){m.onError?.(h)}},{emitOnBegin:t,interval:s}))})():(()=>{let p=Yt(["watchBlockNumber",e.uid,t,r]);return nl(p,{onBlockNumber:o,onError:n},(m)=>{let h=!0,y=()=>h=!1;return(async()=>{try{let x=(()=>{if(e.transport.type==="fallback"){let v=e.transport.transports.find((E)=>E.config.type==="webSocket"||E.config.type==="ipc");if(!v)return e.transport;return v.value}return e.transport})(),{unsubscribe:S}=await x.subscribe({params:["newHeads"],onData(v){if(!h)return;let E=Ir(v.result?.number);m.onBlockNumber(E,c),c=E},onError(v){m.onError?.(v)}});if(y=S,!h)y()}catch(x){n?.(x)}})(),()=>y()})})()}async function zW(e,t){let{checkReplacement:r=!0,confirmations:o=1,hash:n,onReplaced:i,retryCount:s=6,retryDelay:a=({count:T})=>~~(1<<T)*200,timeout:c=180000}=t,u=Yt(["waitForTransactionReceipt",e.uid,n]),d=(()=>{if(t.pollingInterval)return t.pollingInterval;if(e.chain?.experimental_preconfirmationTime)return e.chain.experimental_preconfirmationTime;return e.pollingInterval})(),p,m,h,y=!1,x,S,{promise:v,resolve:E,reject:w}=kf(),_=c?setTimeout(()=>{S?.(),x?.(),w(new x5({hash:n}))},c):void 0;return x=nl(u,{onReplaced:i,resolve:E,reject:w},async(T)=>{if(h=await Ne(e,qS,"getTransactionReceipt")({hash:n}).catch(()=>{return}),h&&o<=1){clearTimeout(_),T.resolve(h),x?.();return}S=Ne(e,CW,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:d,async onBlockNumber(P){let O=(B)=>{clearTimeout(_),S?.(),B(),x?.()},z=P;if(y)return;try{if(h){if(o>1&&(!h.blockNumber||z-h.blockNumber+1n<o))return;O(()=>T.resolve(h));return}if(r&&!p)y=!0,await ol(async()=>{if(p=await Ne(e,AW,"getTransaction")({hash:n}),p.blockNumber)z=p.blockNumber},{delay:a,retryCount:s}),y=!1;if(h=await Ne(e,qS,"getTransactionReceipt")({hash:n}),o>1&&(!h.blockNumber||z-h.blockNumber+1n<o))return;O(()=>T.resolve(h))}catch(B){if(B instanceof Ey||B instanceof Iy){if(!p){y=!1;return}try{m=p,y=!0;let k=await ol(()=>Ne(e,ni,"getBlock")({blockNumber:z,includeTransactions:!0}),{delay:a,retryCount:s,shouldRetry:({error:ue})=>ue instanceof Py});y=!1;let G=k.transactions.find(({from:ue,nonce:W})=>ue===m.from&&W===m.nonce);if(!G)return;if(h=await Ne(e,qS,"getTransactionReceipt")({hash:G.hash}),o>1&&(!h.blockNumber||z-h.blockNumber+1n<o))return;let V="replaced";if(G.to===m.to&&G.value===m.value&&G.input===m.input)V="repriced";else if(G.from===G.to&&G.value===0n)V="cancelled";O(()=>{T.onReplaced?.({reason:V,replacedTransaction:m,transaction:G,transactionReceipt:h}),T.resolve(h)})}catch(k){O(()=>T.reject(k))}}else O(()=>T.reject(B))}}})}),v}var uC=new Qn(128);async function HS(e,t){let{account:r=e.account,assertChainId:o=!0,chain:n=e.chain,accessList:i,authorizationList:s,blobs:a,data:c,dataSuffix:u=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,pollingInterval:S,throwOnReceiptRevert:v,type:E,value:w,..._}=t,T=t.timeout??Math.max((n?.blockTime??0)*3,5000);if(typeof r>"u")throw new Vr({docsPath:"/docs/actions/wallet/sendTransactionSync"});let P=r?ft(r):null,O;try{wo(t);let z=await(async()=>{if(t.to)return t.to;if(t.to===null)return;if(s&&s.length>0)return await wf({authorization:s[0]}).catch(()=>{throw new q("`to` is required. Could not infer from `authorizationList`.")});return})();if(P?.type==="json-rpc"||P===null){let B;if(n!==null){if(B=await Ne(e,en,"getChainId")({}),o)Tf({currentChainId:B,chain:n})}let k=e.chain?.formatters?.transactionRequest?.format,V=(k||Di)({...yc(_,{format:k}),accessList:i,account:P,authorizationList:s,blobs:a,chainId:B,data:u?fr([c??"0x",u]):c,gas:d,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,to:z,type:E,value:w},"sendTransaction"),ue=uC.get(e.uid),W=ue?"wallet_sendTransaction":"eth_sendTransaction",H=await(async()=>{try{return await e.request({method:W,params:[V]},{retryCount:0})}catch(we){if(ue===!1)throw we;let C=we;if(C.name==="InvalidInputRpcError"||C.name==="InvalidParamsRpcError"||C.name==="MethodNotFoundRpcError"||C.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[V]},{retryCount:0}).then((U)=>(uC.set(e.uid,!0),U)).catch((U)=>{let N=U;if(N.name==="MethodNotFoundRpcError"||N.name==="MethodNotSupportedRpcError")throw uC.set(e.uid,!1),C;throw N});throw C}})(),fe=await Ne(e,zW,"waitForTransactionReceipt")({checkReplacement:!1,hash:H,pollingInterval:S,timeout:T});if(v&&fe.status==="reverted")throw new Yp({receipt:fe});return fe}if(P?.type==="local"){if(P.nonceManager&&typeof x>"u"){let V=_.chainId,ue=await(async()=>{if(typeof V==="number")return V;if(n)return n.id;return Ne(e,en,"getChainId")({})})();O={address:P.address,chainId:ue}}let B=await Ne(e,vc,"prepareTransactionRequest")({account:P,accessList:i,authorizationList:s,blobs:a,chain:n,data:u?fr([c??"0x",u]):c,gas:d,gasPrice:p,maxFeePerBlobGas:m,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:x,nonceManager:P.nonceManager,parameters:[...$y,"sidecars"],type:E,value:w,..._,to:z}),k=n?.serializers?.transaction,G=await P.signTransaction(B,{serializer:k});return await Ne(e,FS,"sendRawTransactionSync")({serializedTransaction:G,throwOnReceiptRevert:v,timeout:t.timeout})}if(P?.type==="smart")throw new oi({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"});throw new oi({docsPath:"/docs/actions/wallet/sendTransactionSync",type:P?.type})}catch(z){if(z instanceof oi)throw z;if(O&&!(z instanceof Yp))P?.nonceManager?.reset(O);throw gc(z,{...t,account:P,chain:t.chain||void 0})}}async function NW(e,t){let{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]});return}async function MW(e,t){let{account:r=e.account}=t;if(!r)throw new Vr({docsPath:"/docs/eip7702/signAuthorization"});let o=ft(r);if(!o.signAuthorization)throw new oi({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:o.type});let n=await DS(e,t);return o.signAuthorization(n)}async function BW(e,{account:t=e.account,message:r}){if(!t)throw new Vr({docsPath:"/docs/actions/wallet/signMessage"});let o=ft(t);if(o.signMessage)return o.signMessage({message:r});let n=(()=>{if(typeof r==="string")return xc(r);if(r.raw instanceof Uint8Array)return Gr(r.raw);return r.raw})();return e.request({method:"personal_sign",params:[n,o.address]},{retryCount:0})}async function DW(e,t){let{account:r=e.account,chain:o=e.chain,...n}=t;if(!r)throw new Vr({docsPath:"/docs/actions/wallet/signTransaction"});let i=ft(r);wo({account:i,...t});let s=await Ne(e,en,"getChainId")({});if(o!==null)Tf({currentChainId:s,chain:o});let c=(o?.formatters||e.chain?.formatters)?.transactionRequest?.format||Di;if(i.signTransaction)return i.signTransaction({...n,account:i,chainId:s},{serializer:e.chain?.serializers?.transaction});return await e.request({method:"eth_signTransaction",params:[{...c({...n,account:i},"signTransaction"),chainId:ae(s),from:i.address}]},{retryCount:0})}class lC extends q{constructor({domain:e}){super(`Invalid domain "${Yt(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class dC extends q{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 pC extends q{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function UW(e){let{domain:t={},message:r,primaryType:o}=e,n={EIP712Domain:VS({domain:t}),...e.types};GS({domain:t,message:r,primaryType:o,types:n});let i=["0x1901"];if(t)i.push(mxe({domain:t,types:n}));if(o!=="EIP712Domain")i.push(LW({data:r,primaryType:o,types:n}));return pr(fr(i))}function mxe({domain:e,types:t}){return LW({data:e,primaryType:"EIP712Domain",types:t})}function LW({data:e,primaryType:t,types:r}){let o=jW({data:e,primaryType:t,types:r});return pr(o)}function jW({data:e,primaryType:t,types:r}){let o=[{type:"bytes32"}],n=[hxe({primaryType:t,types:r})];for(let i of r[t]){let[s,a]=qW({types:r,name:i.name,type:i.type,value:e[i.name]});o.push(s),n.push(a)}return rl(o,n)}function hxe({primaryType:e,types:t}){let r=Gr(gxe({primaryType:e,types:t}));return pr(r)}function gxe({primaryType:e,types:t}){let r="",o=FW({primaryType:e,types:t});o.delete(e);let n=[e,...Array.from(o).sort()];for(let i of n)r+=`${i}(${t[i].map(({name:s,type:a})=>`${a} ${s}`).join(",")})`;return r}function FW({primaryType:e,types:t},r=new Set){let n=e.match(/^\w*/u)?.[0];if(r.has(n)||t[n]===void 0)return r;r.add(n);for(let i of t[n])FW({primaryType:i.type,types:t},r);return r}function qW({types:e,name:t,type:r,value:o}){if(e[r]!==void 0)return[{type:"bytes32"},pr(jW({data:o,primaryType:r,types:e}))];if(r==="bytes")return[{type:"bytes32"},pr(o)];if(r==="string")return[{type:"bytes32"},pr(Gr(o))];if(r.lastIndexOf("]")===r.length-1){let n=r.slice(0,r.lastIndexOf("[")),i=o.map((s)=>qW({name:t,type:n,types:e,value:s}));return[{type:"bytes32"},pr(rl(i.map(([s])=>s),i.map(([,s])=>s)))]}return[{type:r},o]}function HW(e){let{domain:t,message:r,primaryType:o,types:n}=e,i=(c,u)=>{let d={...u};for(let p of c){let{name:m,type:h}=p;if(h==="address")d[m]=d[m].toLowerCase()}return d},s=(()=>{if(!n.EIP712Domain)return{};if(!t)return{};return i(n.EIP712Domain,t)})(),a=(()=>{if(o==="EIP712Domain")return;return i(n[o],r)})();return Yt({domain:s,message:a,primaryType:o,types:n})}function GS(e){let{domain:t,message:r,primaryType:o,types:n}=e,i=(s,a)=>{for(let c of s){let{name:u,type:d}=c,p=a[u],m=d.match(vS);if(m&&(typeof p==="number"||typeof p==="bigint")){let[x,S,v]=m;ae(p,{signed:S==="int",size:Number.parseInt(v,10)/8})}if(d==="address"&&typeof p==="string"&&!At(p))throw new Ht({address:p});let h=d.match(VZ);if(h){let[x,S]=h;if(S&&mt(p)!==Number.parseInt(S,10))throw new N5({expectedSize:Number.parseInt(S,10),givenSize:mt(p)})}let y=n[d];if(y)yxe(d),i(y,p)}};if(n.EIP712Domain&&t){if(typeof t!=="object")throw new lC({domain:t});i(n.EIP712Domain,t)}if(o!=="EIP712Domain")if(n[o])i(n[o],r);else throw new dC({primaryType:o,types:n})}function VS({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 yxe(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new pC({type:e})}async function GW(e,t){let{account:r=e.account,domain:o,message:n,primaryType:i}=t;if(!r)throw new Vr({docsPath:"/docs/actions/wallet/signTypedData"});let s=ft(r),a={EIP712Domain:VS({domain:o}),...t.types};if(GS({domain:o,message:n,primaryType:i,types:a}),s.signTypedData)return s.signTypedData({domain:o,message:n,primaryType:i,types:a});let c=HW({domain:o,message:n,primaryType:i,types:a});return e.request({method:"eth_signTypedData_v4",params:[s.address,c]},{retryCount:0})}async function VW(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:ae(t)}]},{retryCount:0})}async function ZW(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}var WW={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."},KW={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},JW={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};function YW(e,t={}){if(typeof t.size<"u")Yn(e,{size:t.size});let r=Dt(e,t);return Ir(r,t)}function QW(e,t={}){let r=e;if(typeof t.size<"u")Yn(r,{size:t.size}),r=_o(r);if(r.length>1||r[0]>1)throw new _5(r);return Boolean(r[0])}function Li(e,t={}){if(typeof t.size<"u")Yn(e,{size:t.size});let r=Dt(e,t);return Pr(r,t)}function XW(e,t={}){let r=e;if(typeof t.size<"u")Yn(r,{size:t.size}),r=_o(r,{dir:"right"});return new TextDecoder().decode(r)}function tK(e,t){let r=typeof t==="string"?yr(t):t,o=_f(r);if(mt(r)===0&&e.length>0)throw new tl;if(mt(t)&&mt(t)<32)throw new $5({data:typeof t==="string"?t:Dt(t),params:e,size:mt(t)});let n=0,i=[];for(let s=0;s<e.length;++s){let a=e[s];o.setPosition(n);let[c,u]=Af(o,a,{staticPosition:0});n+=u,i.push(c)}return i}function Af(e,t,{staticPosition:r}){let o=_S(t.type);if(o){let[n,i]=o;return xxe(e,{...t,type:i},{length:n,staticPosition:r})}if(t.type==="tuple")return Sxe(e,t,{staticPosition:r});if(t.type==="address")return bxe(e);if(t.type==="bool")return vxe(e);if(t.type.startsWith("bytes"))return _xe(e,t,{staticPosition:r});if(t.type.startsWith("uint")||t.type.startsWith("int"))return wxe(e,t);if(t.type==="string")return Txe(e,{staticPosition:r});throw new B5(t.type,{docsPath:"/docs/contract/decodeAbiParameters"})}var eK=32,fC=32;function bxe(e){let t=e.readBytes(32);return[Gs(Dt(U5(t,-20))),32]}function xxe(e,t,{length:r,staticPosition:o}){if(!r){let s=Li(e.readBytes(fC)),a=o+s,c=a+eK;e.setPosition(a);let u=Li(e.readBytes(eK)),d=Oy(t),p=0,m=[];for(let h=0;h<u;++h){e.setPosition(c+(d?h*32:p));let[y,x]=Af(e,t,{staticPosition:c});p+=x,m.push(y)}return e.setPosition(o+32),[m,32]}if(Oy(t)){let s=Li(e.readBytes(fC)),a=o+s,c=[];for(let u=0;u<r;++u){e.setPosition(a+u*32);let[d]=Af(e,t,{staticPosition:a});c.push(d)}return e.setPosition(o+32),[c,32]}let n=0,i=[];for(let s=0;s<r;++s){let[a,c]=Af(e,t,{staticPosition:o+n});n+=c,i.push(a)}return[i,n]}function vxe(e){return[QW(e.readBytes(32),{size:32}),32]}function _xe(e,t,{staticPosition:r}){let[o,n]=t.type.split("bytes");if(!n){let s=Li(e.readBytes(32));e.setPosition(r+s);let a=Li(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];let c=e.readBytes(a);return e.setPosition(r+32),[Dt(c),32]}return[Dt(e.readBytes(Number.parseInt(n,10),32)),32]}function wxe(e,t){let r=t.type.startsWith("int"),o=Number.parseInt(t.type.split("int")[1]||"256",10),n=e.readBytes(32);return[o>48?YW(n,{signed:r}):Li(n,{signed:r}),32]}function Sxe(e,t,{staticPosition:r}){let o=t.components.length===0||t.components.some(({name:s})=>!s),n=o?[]:{},i=0;if(Oy(t)){let s=Li(e.readBytes(fC)),a=r+s;for(let c=0;c<t.components.length;++c){let u=t.components[c];e.setPosition(a+i);let[d,p]=Af(e,u,{staticPosition:a});i+=p,n[o?c:u?.name]=d}return e.setPosition(r+32),[n,32]}for(let s=0;s<t.components.length;++s){let a=t.components[s],[c,u]=Af(e,a,{staticPosition:r});n[o?s:a?.name]=c,i+=u}return[n,i]}function Txe(e,{staticPosition:t}){let r=Li(e.readBytes(32)),o=t+r;e.setPosition(o);let n=Li(e.readBytes(32));if(n===0)return e.setPosition(t+32),["",32];let i=e.readBytes(n,32),s=XW(_o(i));return e.setPosition(t+32),[s,32]}function Oy(e){let{type:t}=e;if(t==="string")return!0;if(t==="bytes")return!0;if(t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(Oy);let r=_S(e.type);if(r&&Oy({...e,type:r[1]}))return!0;return!1}function rK(e){let{abi:t,data:r,cause:o}=e,n=Vs(r,0,4);if(n==="0x")throw new tl({cause:o});let s=[...t||[],KW,JW].find((a)=>a.type==="error"&&n===Pf(Ui(a)));if(!s)throw new ky(n,{docsPath:"/docs/contract/decodeErrorResult",cause:o});return{abiItem:s,args:"inputs"in s&&s.inputs&&s.inputs.length>0?tK(s.inputs,Vs(r,4)):void 0,errorName:s.name}}function mC({abiItem:e,args:t,includeFunctionName:r=!0,includeName:o=!1}){if(!("name"in e))return;if(!("inputs"in e))return;if(!e.inputs)return;return`${r?e.name:""}(${e.inputs.map((n,i)=>`${o&&n.name?`${n.name}: `:""}${typeof t[i]==="object"?Yt(t[i]):t[i]}`).join(", ")})`}class hC extends q{constructor(e,{abi:t,args:r,contractAddress:o,docsPath:n,functionName:i,sender:s}){let a=zS({abi:t,args:r,name:i}),c=a?mC({abiItem:a,args:r,includeFunctionName:!1,includeName:!1}):void 0,u=a?Ui(a,{includeName:!0}):void 0,d=Jp({address:o&&UZ(o),function:u,args:c&&c!=="()"&&`${[...Array(i?.length??0).keys()].map(()=>" ").join("")}${c}`,sender:s});super(e.shortMessage||`An unknown error occurred while executing the contract function "${i}".`,{cause:e,docsPath:n,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],d&&"Contract Call:",d].filter(Boolean),name:"ContractFunctionExecutionError"});Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{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,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=t,this.args=r,this.cause=e,this.contractAddress=o,this.functionName=i,this.sender=s}}class gC extends q{constructor({abi:e,data:t,functionName:r,message:o,cause:n}){let i,s,a,c;if(t&&t!=="0x")try{s=rK({abi:e,data:t,cause:n});let{abiItem:d,errorName:p,args:m}=s;if(p==="Error")c=m[0];else if(p==="Panic"){let[h]=m;c=WW[h]}else{let h=d?Ui(d,{includeName:!0}):void 0,y=d&&m?mC({abiItem:d,args:m,includeFunctionName:!1,includeName:!1}):void 0;a=[h?`Error: ${h}`:"",y&&y!=="()"?` ${[...Array(p?.length??0).keys()].map(()=>" ").join("")}${y}`:""]}}catch(d){i=d}else if(o)c=o;let u;if(i instanceof ky)u=i.signature,a=[`Unable to decode signature "${u}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${u}.`];super(c&&c!=="execution reverted"||u?[`The contract function "${r}" reverted with the following ${u?"signature":"reason"}:`,c||u].join(`
167
167
  `):`The contract function "${r}" reverted.`,{cause:i??n,metaMessages:a,name:"ContractFunctionRevertedError"});Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=s,this.raw=t,this.reason=c,this.signature=u}}class yC extends q{constructor({functionName:e,cause:t}){super(`The contract function "${e}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${e}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError",cause:t})}}class bC extends q{constructor({data:e,message:t}){super(t||"",{name:"RawContractError"});Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e}}var Exe=3;function nK(e,{abi:t,address:r,args:o,docsPath:n,functionName:i,sender:s}){let a=e instanceof bC?e:e instanceof q?e.walk((y)=>("data"in y))||e.walk():{},{code:c,data:u,details:d,message:p,shortMessage:m}=a,h=(()=>{if(e instanceof tl)return new yC({functionName:i,cause:e});if([Exe,Fs.code].includes(c)&&(u||d||p||m)||c===pc.code&&d==="execution reverted"&&u)return new gC({abi:t,data:typeof u==="object"?u.data:u,functionName:i,message:a instanceof Yu?d:m??p,cause:e});return e})();return new hC(h,{abi:t,args:o,contractAddress:r,docsPath:n,functionName:i,sender:s})}async function il(e,t){return il.internal(e,_c,"sendTransaction",t)}(function(e){async function t(r,o,n,i){let{abi:s,account:a=r.account,address:c,args:u,functionName:d,...p}=i;if(typeof a>"u")throw new Vr({docsPath:"/docs/contract/writeContract"});let m=a?ft(a):null,h=NS({abi:s,args:u,functionName:d});try{return await Ne(r,o,n)({data:h,to:c,account:m,...p})}catch(y){throw nK(y,{abi:s,address:c,args:u,docsPath:"/docs/contract/writeContract",functionName:d,sender:m?.address})}}e.internal=t})(il||(il={}));async function oK(e,t){return il.internal(e,HS,"sendTransactionSync",t)}function iK(e){return{addChain:(t)=>qZ(e,t),deployContract:(t)=>pW(e,t),fillTransaction:(t)=>hS(e,t),getAddresses:()=>fW(e),getCallsStatus:(t)=>BS(e,t),getCapabilities:(t)=>wW(e,t),getChainId:()=>en(e),getPermissions:()=>SW(e),prepareAuthorization:(t)=>DS(e,t),prepareTransactionRequest:(t)=>vc(e,t),requestAddresses:()=>EW(e),requestPermissions:(t)=>IW(e,t),sendCalls:(t)=>MS(e,t),sendCallsSync:(t)=>kW(e,t),sendRawTransaction:(t)=>RS(e,t),sendRawTransactionSync:(t)=>FS(e,t),sendTransaction:(t)=>_c(e,t),sendTransactionSync:(t)=>HS(e,t),showCallsStatus:(t)=>NW(e,t),signAuthorization:(t)=>MW(e,t),signMessage:(t)=>BW(e,t),signTransaction:(t)=>DW(e,t),signTypedData:(t)=>GW(e,t),switchChain:(t)=>VW(e,t),waitForCallsStatus:(t)=>jS(e,t),watchAsset:(t)=>ZW(e,t),writeContract:(t)=>il(e,t),writeContractSync:(t)=>oK(e,t)}}function xC(e){let{key:t="wallet",name:r="Wallet Client",transport:o}=e;return NZ({...e,key:t,name:r,transport:o,type:"walletClient"}).extend(iK)}class vC extends q{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}var _C=new Map;function sK({fn:e,id:t,shouldSplitBatch:r,wait:o=0,sort:n}){let i=async()=>{let d=c();s();let p=d.map(({args:m})=>m);if(p.length===0)return;e(p).then((m)=>{if(n&&Array.isArray(m))m.sort(n);for(let h=0;h<d.length;h++){let{resolve:y}=d[h];y?.([m[h],m])}}).catch((m)=>{for(let h=0;h<d.length;h++){let{reject:y}=d[h];y?.(m)}})},s=()=>_C.delete(t),a=()=>c().map(({args:d})=>d),c=()=>_C.get(t)||[],u=(d)=>_C.set(t,[...c(),d]);return{flush:s,async schedule(d){let{promise:p,resolve:m,reject:h}=kf();if(r?.([...a(),d]))i();if(c().length>0)return u({args:d,resolve:m,reject:h}),p;return u({args:d,resolve:m,reject:h}),setTimeout(i,o),p}}}function aK(e,{errorInstance:t=Error("timed out"),timeout:r,signal:o}){return new Promise((n,i)=>{(async()=>{let s,a=new AbortController;try{if(r>0)s=setTimeout(()=>{if(o)a.abort();else i(t)},r);n(await e({signal:a?.signal||null}))}catch(c){if(a?.signal.aborted&&js(c)){i(t);return}i(c)}finally{clearTimeout(s)}})()})}function Ixe(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var wC=Ixe();function cK(e,t={}){let{url:r,headers:o}=Pxe(e);return{async request(n){let{body:i,fetchFn:s=t.fetchFn??fetch,onRequest:a=t.onRequest,onResponse:c=t.onResponse,timeout:u=t.timeout??1e4}=n,d={...t.fetchOptions??{},...n.fetchOptions??{}},{headers:p,method:m,signal:h}=d;try{let y=await aK(async({signal:S})=>{let v={...d,body:Array.isArray(i)?Yt(i.map((T)=>({jsonrpc:"2.0",id:T.id??wC.take(),...T}))):Yt({jsonrpc:"2.0",id:i.id??wC.take(),...i}),headers:{...o,"Content-Type":"application/json",...p},method:m||"POST",signal:h||(u>0?S:null)},E=new Request(r,v),w=await a?.(E,v)??{...v,url:r};return await s(w.url??r,w)},{errorInstance:new lS({body:i,url:r}),timeout:u,signal:!0});if(c)await c(y);let x;if(y.headers.get("Content-Type")?.startsWith("application/json"))x=await y.json();else{x=await y.text();try{x=JSON.parse(x||"{}")}catch(S){if(y.ok)throw S;x={error:x}}}if(!y.ok){if(typeof x.error?.code==="number"&&typeof x.error?.message==="string")return x;throw new dc({body:i,details:Yt(x.error)||y.statusText,headers:y.headers,status:y.status,url:r})}return x}catch(y){if(h?.aborted)throw ri(h);if(js(y))throw y;if(y instanceof dc)throw y;if(y instanceof lS)throw y;throw new dc({body:i,cause:y,url:r})}}}}function Pxe(e){try{let t=new URL(e),r=(()=>{if(t.username){let o=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;return t.username="",t.password="",{url:t.toString(),headers:{Authorization:`Basic ${btoa(o)}`}}}return})();return{url:t.toString(),...r}}catch{return{url:e}}}var ZS=new Qn(8192);function uK(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(ZS.get(r))return ZS.get(r);let o=e().finally(()=>ZS.delete(r));return ZS.set(r,o),o}function lK(e,t={}){return async(r,o={})=>{let{dedupe:n=!1,methods:i,retryDelay:s=150,retryCount:a=3,signal:c,uid:u}={...t,...o},{method:d}=r;if(i?.exclude?.includes(d))throw new fc(Error("method not supported"),{method:d});if(i?.include&&!i.include.includes(d))throw new fc(Error("method not supported"),{method:d});if(c?.aborted)throw ri(c);let p=n?Axe(`${u}.${Yt(r)}`):void 0;return uK(()=>ol(async()=>{try{return await e(r,c?{signal:c}:void 0)}catch(m){if(c?.aborted)throw ri(c);if(js(m))throw m;let h=m;switch(h.code){case Qp.code:throw new Qp(h);case Xp.code:throw new Xp(h);case ef.code:throw new ef(h,{method:r.method});case tf.code:throw new tf(h);case Fs.code:throw new Fs(h);case pc.code:throw new pc(h);case rf.code:throw new rf(h);case nf.code:throw new nf(h);case of.code:throw new of(h);case fc.code:throw new fc(h,{method:r.method});case Qu.code:throw new Qu(h);case sf.code:throw new sf(h);case Xu.code:throw new Xu(h);case af.code:throw new af(h);case cf.code:throw new cf(h);case uf.code:throw new uf(h);case lf.code:throw new lf(h);case df.code:throw new df(h);case mc.code:throw new mc(h);case pf.code:throw new pf(h);case ff.code:throw new ff(h);case mf.code:throw new mf(h);case hf.code:throw new hf(h);case gf.code:throw new gf(h);case hc.code:throw new hc(h);case 5000:throw new Xu(h);case yf.code:throw new yf(h);default:if(m instanceof q)throw m;throw new v5(h)}}},{delay:({count:m,error:h})=>{if(h&&h instanceof dc){let y=h?.headers?.get("Retry-After");if(y?.match(/\d/))return Number.parseInt(y,10)*1000}return~~(1<<m)*s},retryCount:a,signal:c,shouldRetry:({error:m})=>kxe(m)}),{enabled:n,id:p})}}function kxe(e){if(js(e))return!1;if("code"in e&&typeof e.code==="number"){if(e.code===-1)return!0;if(e.code===Qu.code)return!0;if(e.code===Fs.code)return!0;if(e.code===429)return!0;return!1}if(e instanceof dc&&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 Axe(e,t=0){let r=3735928559^t,o=1103547991^t;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);r=Math.imul(r^i,2654435761),o=Math.imul(o^i,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(o^o>>>16,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(r^r>>>16,3266489909),(4294967296*(2097151&o)+(r>>>0)).toString(36)}function dK({key:e,methods:t,name:r,request:o,retryCount:n=3,retryDelay:i=150,timeout:s,type:a},c){let u=sS();return{config:{key:e,methods:t,name:r,request:o,retryCount:n,retryDelay:i,timeout:s,type:a},request:lK(o,{methods:t,retryCount:n,retryDelay:i,uid:u}),value:c}}var $xe=0,pK=new WeakMap;function Rxe(e){if(!e)return"default";let t=pK.get(e);if(t!==void 0)return t;let r=$xe++;return pK.set(e,r),r}function SC(e,t={}){let{batch:r,fetchFn:o,fetchOptions:n,key:i="http",methods:s,name:a="HTTP JSON-RPC",onFetchRequest:c,onFetchResponse:u,retryDelay:d,raw:p}=t;return({chain:m,retryCount:h,timeout:y})=>{let{batchSize:x=1000,wait:S=0}=typeof r==="object"?r:{},v=t.retryCount??h,E=y??t.timeout??1e4,w=e||m?.rpcUrls.default.http[0];if(!w)throw new vC;let _=cK(w,{fetchFn:o,fetchOptions:n,onRequest:c,onResponse:u,timeout:E});return dK({key:i,methods:s,name:a,async request({method:T,params:P},O){let z={method:T,params:P},B=O?.signal?{signal:O.signal}:void 0,{schedule:k}=sK({id:`${w}.${Rxe(O?.signal)}`,wait:S,shouldSplitBatch(W){return W.length>x},fn:(W)=>_.request({body:W,fetchOptions:B}),sort:(W,H)=>W.id-H.id}),G=async(W)=>r?k(W):[await _.request({body:W,fetchOptions:B})],[{error:V,result:ue}]=await G(z);if(p)return{error:V,result:ue};if(V)throw new Yu({body:z,error:V,url:w});return ue},retryCount:v,retryDelay:d,timeout:E,type:"http"},{fetchOptions:n,url:w})}}oc();function fK(e){if(typeof e==="string"){if(!At(e,{strict:!1}))throw new Ht({address:e});return{address:e,type:"json-rpc"}}if(!At(e.address,{strict:!1}))throw new Ht({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"}}oc();oc();function mK({r:e,s:t,to:r="hex",v:o,yParity:n}){let i=(()=>{if(n===0||n===1)return n;if(o&&(o===27n||o===28n||o>=35n))return o%2n===0n?1:0;throw Error("Invalid `v` or `yParity` value")})(),s=`0x${new vn.Signature(Ir(e),Ir(t)).toCompactHex()}${i===0?"1b":"1c"}`;if(r==="hex")return s;return yr(s)}var TC=!1;async function ji({hash:e,privateKey:t,to:r="object"}){let{r:o,s:n,recovery:i}=vn.sign(e.slice(2),t.slice(2),{lowS:!0,extraEntropy:Hr(TC,{strict:!1})?yr(TC):TC}),s={r:ae(o,{size:32}),s:ae(n,{size:32}),v:i?28n:27n,yParity:i};return(()=>{if(r==="bytes"||r==="hex")return mK({...s,to:r});return s})()}async function hK(e){let{chainId:t,nonce:r,privateKey:o,to:n="object"}=e,i=e.contractAddress??e.address,s=await ji({hash:TS({address:i,chainId:t,nonce:r}),privateKey:o,to:n});if(n==="object")return{address:i,chainId:t,nonce:r,...s};return s}var gK=`\x19Ethereum Signed Message:
168
168
  `;function yK(e){let t=(()=>{if(typeof e==="string")return xc(e);if(typeof e.raw==="string")return e.raw;return Dt(e.raw)})(),r=xc(`${gK}${mt(t)}`);return fr([r,t])}function bK(e,t){return pr(yK(e),t)}async function xK({message:e,privateKey:t}){return await ji({hash:bK(e),privateKey:t,to:"hex"})}function vK(e){if(!e||e.length===0)return[];let t=[];for(let r of e){let{chainId:o,nonce:n,...i}=r,s=r.address;t.push([o?Gr(o):"0x",s,n?Gr(n):"0x",...$f({},i)])}return t}function _K(e){let{authorizationList:t}=e;if(t)for(let r of t){let{chainId:o}=r,n=r.address;if(!At(n))throw new Ht({address:n});if(o<0)throw new Sf({chainId:o})}WS(e)}function wK(e){let{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new Ay;for(let r of t){let o=mt(r),n=Pr(Vs(r,0,1));if(o!==32)throw new X5({hash:r,size:o});if(n!==kS)throw new eC({hash:r,version:n})}}WS(e)}function WS(e){let{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:o,to:n}=e;if(t<=0)throw new Sf({chainId:t});if(n&&!At(n))throw new Ht({address:n});if(o&&o>vf)throw new ti({maxFeePerGas:o});if(r&&o&&r>o)throw new Ls({maxFeePerGas:o,maxPriorityFeePerGas:r})}function SK(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:o,maxFeePerGas:n,to:i}=e;if(t<=0)throw new Sf({chainId:t});if(i&&!At(i))throw new Ht({address:i});if(r||n)throw new q("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(o&&o>vf)throw new ti({maxFeePerGas:o})}function TK(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:o,maxFeePerGas:n,to:i}=e;if(i&&!At(i))throw new Ht({address:i});if(typeof t<"u"&&t<=0)throw new Sf({chainId:t});if(r||n)throw new q("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(o&&o>vf)throw new ti({maxFeePerGas:o})}function Cy(e){if(!e||e.length===0)return[];let t=[];for(let r=0;r<e.length;r++){let{address:o,storageKeys:n}=e[r];for(let i=0;i<n.length;i++)if(n[i].length-2!==64)throw new y5({storageKey:n[i]});if(!At(o,{strict:!1}))throw new Ht({address:o});t.push([o,n])}return t}function EK(e,t){let r=$S(e);if(r==="eip1559")return zxe(e,t);if(r==="eip2930")return Nxe(e,t);if(r==="eip4844")return Cxe(e,t);if(r==="eip7702")return Oxe(e,t);return Mxe(e,t)}function Oxe(e,t){let{authorizationList:r,chainId:o,gas:n,nonce:i,to:s,value:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:d,data:p}=e;_K(e);let m=Cy(d),h=vK(r);return So(["0x04",Zs([ae(o),i?ae(i):"0x",u?ae(u):"0x",c?ae(c):"0x",n?ae(n):"0x",s??"0x",a?ae(a):"0x",p??"0x",m,h,...$f(e,t)])])}function Cxe(e,t){let{chainId:r,gas:o,nonce:n,to:i,value:s,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:d,data:p}=e;wK(e);let{blobVersionedHashes:m,sidecars:h}=e;if(e.blobs&&(typeof m>"u"||typeof h>"u")){let w=typeof e.blobs[0]==="string"?e.blobs:e.blobs.map((P)=>Dt(P)),_=e.kzg,T=Ef({blobs:w,kzg:_});if(typeof m>"u")m=PS({commitments:T});if(typeof h>"u"){let P=If({blobs:w,commitments:T,kzg:_});h=AS({blobs:w,commitments:T,proofs:P})}}let y=Cy(d),x=[ae(r),n?ae(n):"0x",u?ae(u):"0x",c?ae(c):"0x",o?ae(o):"0x",i??"0x",s?ae(s):"0x",p??"0x",y,a?ae(a):"0x",m??[],...$f(e,t)],S=[],v=[],E=[];if(h)for(let w=0;w<h.length;w++){let{blob:_,commitment:T,proof:P}=h[w];S.push(_),v.push(T),E.push(P)}return So(["0x03",h?Zs([x,S,v,E]):Zs(x)])}function zxe(e,t){let{chainId:r,gas:o,nonce:n,to:i,value:s,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:u,data:d}=e;WS(e);let p=Cy(u),m=[ae(r),n?ae(n):"0x",c?ae(c):"0x",a?ae(a):"0x",o?ae(o):"0x",i??"0x",s?ae(s):"0x",d??"0x",p,...$f(e,t)];return So(["0x02",Zs(m)])}function Nxe(e,t){let{chainId:r,gas:o,data:n,nonce:i,to:s,value:a,accessList:c,gasPrice:u}=e;SK(e);let d=Cy(c),p=[ae(r),i?ae(i):"0x",u?ae(u):"0x",o?ae(o):"0x",s??"0x",a?ae(a):"0x",n??"0x",d,...$f(e,t)];return So(["0x01",Zs(p)])}function Mxe(e,t){let{chainId:r=0,gas:o,data:n,nonce:i,to:s,value:a,gasPrice:c}=e;TK(e);let u=[i?ae(i):"0x",c?ae(c):"0x",o?ae(o):"0x",s??"0x",a?ae(a):"0x",n??"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 h=27n+(t.v===27n?0n:1n);if(t.v!==h)throw new h5({v:t.v});return h})(),p=_o(t.r),m=_o(t.s);u=[...u,ae(d),p==="0x00"?"0x":p,m==="0x00"?"0x":m]}else if(r>0)u=[...u,ae(r),"0x","0x"];return Zs(u)}function $f(e,t){let r=t??e,{v:o,yParity:n}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof o>"u"&&typeof n>"u")return[];let i=_o(r.r),s=_o(r.s);return[(()=>{if(typeof n==="number")return n?ae(1):"0x";if(o===0n)return"0x";if(o===1n)return ae(1);return o===27n?"0x":ae(1)})(),i==="0x00"?"0x":i,s==="0x00"?"0x":s]}async function IK(e){let{privateKey:t,transaction:r,serializer:o=EK}=e,n=(()=>{if(r.type==="eip4844")return{...r,sidecars:!1};return r})(),i=await ji({hash:pr(await o(n)),privateKey:t});return await o(r,i)}async function PK(e){let{privateKey:t,...r}=e;return await ji({hash:UW(r),privateKey:t,to:"hex"})}function EC(e,t={}){let{nonceManager:r}=t,o=Gr(vn.getPublicKey(e.slice(2),!1)),n=wS(o);return{...fK({address:n,nonceManager:r,async sign({hash:s}){return ji({hash:s,privateKey:e,to:"hex"})},async signAuthorization(s){return hK({...s,privateKey:e})},async signMessage({message:s}){return xK({message:s,privateKey:e})},async signTransaction(s,{serializer:a}={}){return IK({privateKey:e,transaction:s,serializer:a})},async signTypedData(s){return PK({...s,privateKey:e})}}),publicKey:o,source:"privateKey"}}function KS(e){let t={formatters:void 0,fees:void 0,serializers:void 0,...e};function r(o){return(n)=>{let i=typeof n==="function"?n(o):n,s={...o,...i};return Object.assign(s,{extend:r(s)})}}return Object.assign(t,{extend:r(t)})}var IC=KS({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 PC=KS({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 kC=null;var Bxe={privateKeyToAccount:EC,createWalletClient:xC,http:SC,createMonacoSDK:d5,sei:IC,seiTestnet:PC};function Dxe(e,t=Bxe){let r=e.network==="mainnet"?t.sei:t.seiTestnet,o;if(e.privateKey){let n=t.privateKeyToAccount(e.privateKey);o=t.createWalletClient({account:n,chain:r,transport:t.http(e.seiRpcUrl)})}return t.createMonacoSDK({walletClient:o,network:e.network,seiRpcUrl:e.seiRpcUrl})}function qe(e){if(!kC){let t=e??su();kC=Dxe(t)}return kC}var Uxe=60,JS=null;function Lxe(){return Math.floor(Date.now()/1000)}function kK(e){return e-Uxe<=Lxe()}function jxe(e){for(let t=e,r=0;t instanceof Error&&r<5;r++){if(t instanceof or&&t.statusCode===401)return!0;t=t.cause}return!1}function AC(e){if(!JS)JS=e().finally(()=>{JS=null});return JS}async function AK(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 $K(e,t){try{await e.refreshAuth()}catch{await AK(e,t)}}async function te(e){let t=qe(e),r=e??su(),o=t.getAuthState(),n=r.delegatedOwnerUserId!=null&&o?.user?.id!==r.delegatedOwnerUserId;if(!o||n)return await AC(()=>AK(t,r)),t;if(kK(o.expiresAt))await AC(()=>$K(t,r));return t}async function Fxe(e){let t=e??su();if(!t.privateKey)return!1;let r=qe(e);return await AC(()=>$K(r,t)),!0}function RK(e,t){async function r(...o){let n=qe(t).getAuthState(),i=n!==void 0&&!kK(n.expiresAt);try{return await e(...o)}catch(s){if(!jxe(s))throw s;if(!(i&&qe(t).getAuthState()!==n)){if(!await Fxe(t))throw s}return await e(...o)}}return r}function j(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function YS(e){return{content:[{type:"text",text:e}]}}function OK(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 o=await(await te()).faucet.getInfo();return j(o)})}function CK(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:f.object({turnstileToken:f.string().describe("Cloudflare Turnstile token proving the request came from a real client (required by the faucet).")})},async({turnstileToken:r})=>{let n=await(await te()).faucet.mint({turnstileToken:r});return j(n)})}function zK(e,t){CK(e,t),OK(e,t)}function NK(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:f.object({tradingPairId:f.string().describe("Trading pair UUID whose fee schedule to return")})},async({tradingPairId:t})=>{let o=await(await te()).fees.getMyFeeTier({tradingPairId:t});return j(o)})}function MK(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:f.object({tradingPairId:f.string().describe("Trading pair UUID"),side:f.enum(["BUY","SELL"]).describe("Order side"),price:f.string().describe("Price per unit as a decimal string"),quantity:f.string().describe("Quantity to trade as a decimal string")})},async({tradingPairId:t,side:r,price:o,quantity:n})=>{let s=await(await te()).fees.simulateFees({tradingPairId:t,side:r,price:o,quantity:n});return j(s)})}function BK(e){MK(e),NK(e)}function DK(e){e.registerTool("get_available_collateral",{description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",inputSchema:f.object({asset:f.string().optional().describe("Optional collateral asset symbol or ID to scope the query")})},async({asset:t})=>{let o=await(await te()).marginAccounts.getAvailableCollateral({asset:t});return j(o)})}function UK(e){e.registerTool("get_margin_accounts",{description:"List your margin accounts with optional filters (state, trading pair).",inputSchema:f.object({page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page"),state:f.string().optional().describe("Filter by margin account state"),tradingPairId:f.string().optional().describe("Filter by trading pair UUID")})},async({page:t,pageSize:r,state:o,tradingPairId:n})=>{let s=await(await te()).marginAccounts.listMarginAccounts({page:t,pageSize:r,state:o,tradingPairId:n});return j(s)})}function LK(e){e.registerTool("get_parent_margin_account_movements",{description:"List collateral movements for your parent (cross) margin account.",inputSchema:f.object({movementType:f.string().optional().describe("Filter by movement type"),page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page")})},async({movementType:t,page:r,pageSize:o})=>{let i=await(await te()).marginAccounts.getParentMarginAccountMovements({movementType:t,page:r,pageSize:o});return j(i)})}function jK(e){e.registerTool("get_parent_margin_account_summary",{description:"Get your parent (cross) margin account summary.",inputSchema:f.object({tradingPairId:f.string().optional().describe("Optional trading pair UUID to scope the summary")})},async({tradingPairId:t})=>{let o=await(await te()).marginAccounts.getParentMarginAccountSummary({tradingPairId:t});return j(o)})}function FK(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:f.object({tradingPairId:f.string().describe("Trading pair UUID"),side:f.enum(["BUY","SELL"]).describe("Order side (authoritative: BUY=LONG, SELL=SHORT)"),orderType:f.enum(["LIMIT","MARKET"]).describe("Order type"),quantity:f.string().describe("Order quantity as a decimal string"),price:f.string().optional().describe("Limit price as a decimal string — required for LIMIT"),leverage:f.string().optional().describe("Leverage as a decimal string — required unless reduceOnly is true"),reduceOnly:f.boolean().optional().describe("Whether the order can only reduce exposure")}).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"]})},async({tradingPairId:t,side:r,orderType:o,quantity:n,price:i,leverage:s,reduceOnly:a})=>{let u=await(await te()).marginAccounts.simulateParentMarginOrderRisk({tradingPairId:t,side:r,orderType:o,quantity:n,price:i,leverage:s,reduceOnly:a});return j(u)})}function qK(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).",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),side:f.enum(["BUY","SELL"]).describe("Order side (authoritative: BUY=LONG, SELL=SHORT)"),orderType:f.enum(["LIMIT","MARKET"]).describe("Order type"),quantity:f.string().describe("Order quantity as a decimal string"),price:f.string().optional().describe("Limit price as a decimal string — required for LIMIT"),leverage:f.string().optional().describe("Leverage as a decimal string — required unless reduceOnly is true"),reduceOnly:f.boolean().optional().describe("Whether the order can only reduce exposure"),marginMode:f.enum(["ISOLATED","CROSS"]).optional().describe("Risk bucket margin mode (default ISOLATED)"),strategyKey:f.string().optional().describe("Isolated risk bucket strategy key (ISOLATED only)"),selectedTradingPairIds:f.array(f.string()).optional().describe("Cross risk bucket trading pair UUIDs (CROSS only; must include tradingPairId)")}).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.marginMode!=="CROSS"||t.selectedTradingPairIds!==void 0&&t.selectedTradingPairIds.length>0,{message:"selectedTradingPairIds is required for CROSS risk buckets",path:["selectedTradingPairIds"]}).refine((t)=>t.marginMode!=="CROSS"||t.selectedTradingPairIds?.includes(t.tradingPairId),{message:"selectedTradingPairIds must include tradingPairId for CROSS risk buckets",path:["selectedTradingPairIds"]}).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.selectedTradingPairIds===void 0,{message:"selectedTradingPairIds is only allowed for CROSS risk buckets",path:["selectedTradingPairIds"]})},async({tradingPairId:t,side:r,orderType:o,quantity:n,price:i,leverage:s,reduceOnly:a,marginMode:c,strategyKey:u,selectedTradingPairIds:d})=>{let p=await te(),m={tradingPairId:t,side:r,orderType:o,quantity:n,price:i,leverage:s,reduceOnly:a},h=c==="CROSS"?await p.marginAccounts.simulateRiskBucketOrderRisk({...m,marginMode:c,selectedTradingPairIds:d??[]}):await p.marginAccounts.simulateRiskBucketOrderRisk({...m,marginMode:c,strategyKey:u});return j(h)})}function HK(e){e.registerTool("transfer_collateral_from_parent_margin_account",{description:"Move collateral out of your parent (cross) margin account back to spot.",inputSchema:f.object({asset:f.string().describe("Collateral asset symbol or ID"),amount:f.string().describe("Amount to transfer as a decimal string")})},async({asset:t,amount:r})=>{let n=await(await te()).marginAccounts.transferCollateralFromParentMarginAccount({asset:t,amount:r});return j(n)})}function GK(e){e.registerTool("transfer_collateral_to_parent_margin_account",{description:"Move collateral from spot into your parent (cross) margin account.",inputSchema:f.object({asset:f.string().describe("Collateral asset symbol or ID"),amount:f.string().describe("Amount to transfer as a decimal string")})},async({asset:t,amount:r})=>{let n=await(await te()).marginAccounts.transferCollateralToParentMarginAccount({asset:t,amount:r});return j(n)})}function VK(e){e.registerTool("transfer_collateral_to_risk_bucket",{description:"Allocate collateral into an isolated or cross risk bucket.",inputSchema:f.object({asset:f.string().describe("Collateral asset symbol or ID"),amount:f.string().describe("Amount to transfer as a decimal string"),marginMode:f.enum(["ISOLATED","CROSS"]).optional().describe("Risk bucket margin mode (default ISOLATED)"),tradingPairId:f.string().optional().describe("Trading pair UUID (required for ISOLATED; not allowed for CROSS)"),strategyKey:f.string().optional().describe("Isolated risk bucket strategy key (ISOLATED only)"),selectedTradingPairIds:f.array(f.string()).optional().describe("Trading pair UUIDs (required for CROSS; not allowed for ISOLATED)")}).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.selectedTradingPairIds!==void 0&&t.selectedTradingPairIds.length>0,{message:"selectedTradingPairIds is required for CROSS risk buckets",path:["selectedTradingPairIds"]}).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.selectedTradingPairIds===void 0,{message:"selectedTradingPairIds is only allowed for CROSS risk buckets",path:["selectedTradingPairIds"]})},async({asset:t,amount:r,marginMode:o,tradingPairId:n,strategyKey:i,selectedTradingPairIds:s})=>{let a=await te(),c=o==="CROSS"?await a.marginAccounts.transferCollateralToRiskBucket({asset:t,amount:r,marginMode:o,selectedTradingPairIds:s??[]}):await a.marginAccounts.transferCollateralToRiskBucket({asset:t,amount:r,marginMode:o,tradingPairId:n??"",strategyKey:i});return j(c)})}function ZK(e){UK(e),jK(e),DK(e),LK(e),FK(e),qK(e),GK(e),HK(e),VK(e)}function WK(e){e.registerTool("get_candlesticks",{description:"Get OHLCV candlestick data for a trading pair. Useful for charting and price analysis.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),interval:f.enum(["1m","5m","15m","1h","4h","1d"]).describe("Candlestick interval"),startTime:f.number().optional().describe("Start time as Unix timestamp (seconds)"),endTime:f.number().optional().describe("End time as Unix timestamp (seconds)"),limit:f.number().optional().describe("Max number of candlesticks to return")})},async({tradingPairId:t,interval:r,startTime:o,endTime:n,limit:i})=>{let a=await qe().market.getCandlesticks(t,r,{startTime:o,endTime:n,limit:i});return j(a)})}function KK(e){e.registerTool("get_market_metadata",{description:"Get metadata for a specific trading pair including tick size, min order size, and trading rules.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let o=await qe().market.getMarketMetadata(t);return j(o)})}function JK(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 qe().market.getMarketStats();return j(r)})}function YK(e){e.registerTool("get_screener",{description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",inputSchema:f.object({page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page"),marketType:f.enum(["SPOT","MARGIN"]).optional().describe("Filter by market type"),isActive:f.boolean().optional().describe("Filter by active status"),category:f.string().optional().describe("Filter by category (e.g. crypto, equities, commodities)")})},async({page:t,pageSize:r,marketType:o,isActive:n,category:i})=>{let a=await qe().market.getScreener({page:t,pageSize:r,marketType:o,isActive:n,category:i});return j(a)})}function QK(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:f.object({symbol:f.string().describe("Trading pair symbol (e.g. 'BTC/USDC')")})},async({symbol:t})=>{let o=await qe().market.getTradingPairBySymbol(t);if(!o)return YS(`Trading pair '${t}' not found.`);return j(o)})}function XK(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:f.object({page:f.number().optional().describe("Page number (starts from 1)"),pageSize:f.number().optional().describe("Number of items per page (max 100)"),marketType:f.enum(["SPOT","MARGIN"]).optional().describe("Filter by market type"),baseToken:f.string().optional().describe("Filter by base token"),quoteToken:f.string().optional().describe("Filter by quote token"),isActive:f.boolean().optional().describe("Filter by active status"),category:f.string().optional().describe("Filter by category (e.g. crypto, equities, commodities)")})},async(t)=>{let o=await qe().market.getPaginatedTradingPairs(t);return j(o)})}function eJ(e){XK(e),QK(e),WK(e),KK(e),YK(e),JK(e)}function tJ(e){e.registerTool("get_orderbook",{description:"Get the current orderbook snapshot for a trading pair. Shows bids, asks, best bid/ask, and volumes.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),depth:f.number().optional().describe("Number of price levels to return (max 100, default 10)"),tradingMode:f.enum(["SPOT"]).optional().describe("Trading mode (default: SPOT)"),magnitude:f.number().optional().describe("Price grouping magnitude (e.g. 0.01, 0.1, 1, 10, 100)"),denomination:f.enum(["BASE","QUOTE"]).optional().describe("Quantity denomination: BASE or QUOTE")})},async({tradingPairId:t,depth:r,tradingMode:o,magnitude:n,denomination:i})=>{let a=await qe().orderbook.getOrderbook(t,{depth:r,tradingMode:o,magnitude:n,denomination:i});return j(a)})}function rJ(e){tJ(e)}function nJ(e){e.registerTool("get_all_funding_history",{description:"List historical funding-rate records across all perpetual markets.",inputSchema:f.object({startTime:f.string().optional().describe('Start time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),endTime:f.string().optional().describe('End time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page"),orderBy:f.enum(["ASC","DESC"]).optional().describe("Sort order by time")})},async({startTime:t,endTime:r,page:o,pageSize:n,orderBy:i})=>{let a=await qe().market.listAllFundingHistory({startTime:t,endTime:r,page:o,pageSize:n,orderBy:i});return j(a)})}function oJ(e){e.registerTool("get_funding_history",{description:"List historical funding-rate records for a perpetual market.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),startTime:f.string().optional().describe('Start time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),endTime:f.string().optional().describe('End time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page"),orderBy:f.enum(["ASC","DESC"]).optional().describe("Sort order by time")})},async({tradingPairId:t,startTime:r,endTime:o,page:n,pageSize:i,orderBy:s})=>{let c=await qe().market.listFundingHistory(t,{startTime:r,endTime:o,page:n,pageSize:i,orderBy:s});return j(c)})}function iJ(e){e.registerTool("get_funding_state",{description:"Get the current funding rate and next funding time for a perpetual market.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let o=await qe().market.getFundingState(t);return j(o)})}function sJ(e){e.registerTool("get_index_price",{description:"Get the current index (oracle) price for a perpetual market.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let o=await qe().market.getIndexPrice(t);return j(o)})}function aJ(e){e.registerTool("get_mark_price",{description:"Get the current mark price for a perpetual market.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let o=await qe().market.getMarkPrice(t);return j(o)})}function cJ(e){e.registerTool("get_open_interest",{description:"Get the current open interest for a perpetual market.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let o=await qe().market.getOpenInterest(t);return j(o)})}function uJ(e){e.registerTool("get_perp_market_config",{description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let o=await qe().market.getPerpMarketConfig(t);return j(o)})}function lJ(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:f.object({tradingPairId:f.string().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let o=await qe().market.getPerpMarketSummary(t);return j(o)})}function dJ(e){uJ(e),lJ(e),aJ(e),sJ(e),iJ(e),cJ(e),oJ(e),nJ(e)}function pJ(e){e.registerTool("check_trader_code_availability",{description:"Public advisory check of whether a custom PitPass 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:f.object({code:f.string().describe("The custom handle to check for availability.")})},async({code:t})=>{let o=await qe().pitpass.checkTraderCodeAvailability(t);return j(o)})}function fJ(e){e.registerTool("clear_trader_code",{description:"Clear the authenticated caller's custom PitPass 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:f.object({})},async()=>{let r=await(await te()).pitpass.clearTraderCode();return j(r)})}function mJ(e){e.registerTool("get_my_trader_code",{description:"Return the authenticated caller's PitPass 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:f.object({})},async()=>{let r=await(await te()).pitpass.getMyTraderCode();return j(r)})}function hJ(e){e.registerTool("get_rewards_balance",{description:"Return the authenticated caller's current PitPass 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:f.object({})},async()=>{let r=await(await te()).pitpass.getRewardsBalance();return j(r)})}function gJ(e){e.registerTool("get_trader_code_info",{description:"Public lookup of a PitPass 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:f.object({code:f.string().describe("The TraderCode to look up — a wallet address (0x-prefixed) or the 'Monaco - <address>' display form.")})},async({code:t})=>{let o=await qe().pitpass.getTraderCodeInfo(t);return j(o)})}function yJ(e){e.registerTool("set_trader_code",{description:"Claim or edit the authenticated caller's custom (vanity) PitPass 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:f.object({code:f.string().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 o=await(await te()).pitpass.setTraderCode(t);return j(o)})}function bJ(e){e.registerTool("transfer_rewards",{description:"Transfer earned PitPass 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:f.object({token:f.string().describe("Reward token contract address (0x-prefixed EVM address) to transfer."),amount:f.string().describe("Amount to transfer in RAW atomic units of the token (positive integer string).")})},async({token:t,amount:r})=>{let n=await(await te()).pitpass.transferRewards({token:t,amount:r});return j(n)})}function xJ(e){gJ(e),pJ(e)}function vJ(e){mJ(e),hJ(e),bJ(e),yJ(e),fJ(e)}function _J(e){e.registerTool("get_portfolio_assets",{description:"Get your per-asset portfolio allocation and balances over a period.",inputSchema:f.object({period:f.enum(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let o=await(await te()).portfolio.getAssets({period:t});return j(o)})}function wJ(e){e.registerTool("get_portfolio_margin",{description:"Get your portfolio margin overview (collateral, maintenance margin, health)."},async()=>{let r=await(await te()).portfolio.getMargin();return j(r)})}function SJ(e){e.registerTool("get_portfolio_performance",{description:"Get your portfolio performance time series over a period.",inputSchema:f.object({period:f.enum(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let o=await(await te()).portfolio.getPerformance({period:t});return j(o)})}function TJ(e){e.registerTool("get_portfolio_realized_pnl",{description:"Get your realized PnL breakdown over a period.",inputSchema:f.object({period:f.enum(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let o=await(await te()).portfolio.getRealizedPnl({period:t});return j(o)})}function EJ(e){e.registerTool("get_portfolio_summary",{description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",inputSchema:f.object({period:f.enum(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let o=await(await te()).portfolio.getSummary({period:t});return j(o)})}function IJ(e){EJ(e),SJ(e),TJ(e),_J(e),wJ(e)}function PJ(e){e.registerTool("close_position",{description:"Close a perpetual position with a market, limit, or IOC reduce order.",inputSchema:f.object({positionId:f.string().describe("Position UUID"),closeType:f.enum(["MARKET","LIMIT","IOC"]).describe("Close order type"),limitPrice:f.string().optional().describe("Limit price as a decimal string — required for LIMIT and IOC, not allowed for MARKET"),slippageToleranceBps:f.number().optional().describe("Slippage tolerance in basis points (MARKET/IOC)"),quantity:f.string().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:o,slippageToleranceBps:n,quantity:i})=>{let a=await(await te()).positions.closePosition(t,{closeType:r,limitPrice:o,slippageToleranceBps:n,quantity:i});return j(a)})}function kJ(e){e.registerTool("get_position",{description:"Get details for a specific perpetual position by ID.",inputSchema:f.object({positionId:f.string().describe("Position UUID")})},async({positionId:t})=>{let o=await(await te()).positions.getPosition(t);return j(o)})}function AJ(e){e.registerTool("get_position_history",{description:"List historical (closed/reduced) perpetual position records with optional filters.",inputSchema:f.object({positionId:f.string().optional().describe("Filter by position UUID"),marginAccountId:f.string().optional().describe("Filter by margin account UUID"),tradingPairId:f.string().optional().describe("Filter by trading pair UUID"),page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page"),reductionOnly:f.boolean().optional().describe("Only include reduction events")})},async({positionId:t,marginAccountId:r,tradingPairId:o,page:n,pageSize:i,reductionOnly:s})=>{let c=await(await te()).positions.listPositionHistory({positionId:t,marginAccountId:r,tradingPairId:o,page:n,pageSize:i,reductionOnly:s});return j(c)})}function $J(e){e.registerTool("get_position_pnl_history",{description:"Get the PnL history time series for a perpetual position over an interval.",inputSchema:f.object({positionId:f.string().describe("Position UUID"),interval:f.enum(["1m","5m","15m","1h","4h","1d"]).describe("Sampling interval"),startTime:f.number().int().min(0).optional().describe("Start time as a Unix timestamp in milliseconds"),endTime:f.number().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:o,endTime:n})=>{let s=await(await te()).positions.getPositionPnlHistory(t,{interval:r,startTime:o,endTime:n});return j(s)})}function RJ(e){e.registerTool("get_position_risk",{description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",inputSchema:f.object({positionId:f.string().describe("Position UUID")})},async({positionId:t})=>{let o=await(await te()).positions.getPositionRisk(t);return j(o)})}function OJ(e){e.registerTool("get_positions",{description:"List your perpetual positions with optional filters (margin account, trading pair, status).",inputSchema:f.object({marginAccountId:f.string().optional().describe("Filter by margin account UUID"),tradingPairId:f.string().optional().describe("Filter by trading pair UUID"),status:f.enum(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"]).optional().describe("Filter by position status"),page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page")})},async({marginAccountId:t,tradingPairId:r,status:o,page:n,pageSize:i})=>{let a=await(await te()).positions.listPositions({marginAccountId:t,tradingPairId:r,status:o,page:n,pageSize:i});return j(a)})}function CJ(e){OJ(e),kJ(e),RJ(e),AJ(e),$J(e),PJ(e)}function zJ(e){e.registerTool("get_balance_by_asset",{description:"Get the authenticated user's balance for a specific asset by its UUID.",inputSchema:f.object({assetId:f.string().describe("The asset UUID")})},async({assetId:t})=>{let o=await(await te()).profile.getUserBalanceByAssetId(t);return j(o)})}function NJ(e){e.registerTool("get_balances",{description:"Get the authenticated user's token balances with pagination.",inputSchema:f.object({page:f.number().optional().describe("Page number (starts from 1, default: 1)"),pageSize:f.number().optional().describe("Number of items per page (default: 20, max: 100)")})},async({page:t,pageSize:r})=>{let n=await(await te()).profile.getUserBalances({page:t,pageSize:r});return j(n)})}function MJ(e){e.registerTool("get_funding_payments",{description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",inputSchema:f.object({tradingPairId:f.string().optional().describe("Filter by trading pair UUID"),positionId:f.string().optional().describe("Filter by position UUID"),marginAccountId:f.string().optional().describe("Filter by margin account UUID"),page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page")})},async({tradingPairId:t,positionId:r,marginAccountId:o,page:n,pageSize:i})=>{let a=await(await te()).profile.listFundingPayments({tradingPairId:t,positionId:r,marginAccountId:o,page:n,pageSize:i});return j(a)})}function BJ(e){e.registerTool("get_movements",{description:"Get the authenticated user's ledger movements (transaction history) with pagination.",inputSchema:f.object({page:f.number().int().min(1).optional().describe("Page number (starts from 1, default: 1)"),pageSize:f.number().int().min(1).max(100).optional().describe("Items per page (default: 20, max: 100)"),entryType:f.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"]).optional().describe("Filter by entry type (e.g. CREDIT, DEBIT, LOCK, UNLOCK, FEE)"),transactionType:f.enum(["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:f.string().uuid().optional().describe("Filter by asset ID (UUID)")})},async({page:t,pageSize:r,entryType:o,transactionType:n,assetId:i})=>{let a=await(await te()).profile.getPaginatedUserMovements({page:t,pageSize:r,entryType:o,transactionType:n,assetId:i});return j(a)})}function DJ(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 te()).profile.getProfile();return j(r)})}function UJ(e){e.registerTool("get_user_trades",{description:"List your own trade fills with optional filters and cursor pagination.",inputSchema:f.object({tradingPairId:f.string().optional().describe("Filter by trading pair UUID"),pageSize:f.number().optional().describe("Items per page"),pageToken:f.string().optional().describe("Cursor for the next page"),page:f.number().optional().describe("Page number (legacy offset mode; prefer pageToken)")})},async({tradingPairId:t,pageSize:r,pageToken:o,page:n})=>{let s=await(await te()).profile.getUserTrades({tradingPairId:t,pageSize:r,pageToken:o,page:n});return j(s)})}function LJ(e){DJ(e),NJ(e),zJ(e),BJ(e),UJ(e),MJ(e)}function jJ(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 qe().pulse.getPulse();return j(r)})}function FJ(e){jJ(e)}var qxe="https://docs.0xmonaco.com/mcp",Hxe="SearchMonacoDocs",QS=null;async function qJ(e,t,r){let o=await fetch(qxe,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...QS?{"Mcp-Session-Id":QS}:{}},body:JSON.stringify({jsonrpc:"2.0",id:r,method:e,params:t})});if(!o.ok)throw Error(`Mintlify MCP error: ${o.status}`);let n=o.headers.get("mcp-session-id");if(n)QS=n;let s=(await o.text()).split(`
169
- `).find((a)=>a.startsWith("data: "));if(!s)throw Error("No data in Mintlify MCP response");return JSON.parse(s.slice(6))}async function Gxe(){if(QS)return;await qJ("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"monaco-mcp-server",version:C_.version}},0)}async function Vxe(e){return await Gxe(),(await qJ("tools/call",{name:Hxe,arguments:{query:e}},1))?.result}function HJ(e){e.registerTool("search_docs",{description:"Search the Monaco documentation for information about the protocol, SDK, trading, and development guides.",inputSchema:f.object({query:f.string().describe("The search query")})},async({query:t})=>{try{let r=await Vxe(t);if(r?.content&&Array.isArray(r.content))return{content:r.content};return j(r)}catch(r){return YS(`Search failed: ${r instanceof Error?r.message:String(r)}`)}})}function GJ(e){HJ(e)}function VJ(e){e.registerTool("get_trades",{description:"Get historical trades for a trading pair. Returns recent trades sorted by execution time (newest first).",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),page:f.number().optional().describe("Page number (starts from 1, default: 1)"),pageSize:f.number().optional().describe("Max number of records to return (default: 25, max: 100)")})},async({tradingPairId:t,page:r,pageSize:o})=>{let i=await qe().trades.getTrades(t,{page:r,pageSize:o});return j(i)})}function ZJ(e){VJ(e)}function WJ(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:f.object({tradingPairId:f.string().optional().describe("Optional trading pair UUID to limit cancellation to")})},async({tradingPairId:t})=>{let o=await(await te()).trading.batchCancelAll(t);return j(o)})}function KJ(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:f.object({orderIds:f.array(f.string()).describe("Array of order IDs to cancel")})},async({orderIds:t})=>{let o=await(await te()).trading.batchCancel(t);return j(o)})}function JJ(e){e.registerTool("batch_close_all_positions",{description:"Close all open perpetual positions with MARKET reduce-only orders ('panic close'), optionally filtered to a specific trading pair. Best-effort: each position closes independently and per-position failures are reported in the result.",inputSchema:f.object({tradingPairId:f.string().optional().describe("Optional trading pair UUID to limit the close to"),slippageToleranceBps:f.number().int().optional().describe("Optional slippage tolerance (basis points) applied to each close")})},async({tradingPairId:t,slippageToleranceBps:r})=>{let n=await(await te()).positions.batchCloseAllPositions({tradingPairId:t,slippageToleranceBps:r});return j(n)})}function YJ(e){e.registerTool("cancel_order",{description:"Cancel an open order by its ID.",inputSchema:f.object({orderId:f.string().describe("The order ID to cancel")})},async({orderId:t})=>{let o=await(await te()).trading.cancelOrder(t);return j(o)})}function QJ(e){e.registerTool("get_order",{description:"Get detailed information about a specific order by its ID.",inputSchema:f.object({orderId:f.string().describe("The order ID to look up")})},async({orderId:t})=>{let o=await(await te()).trading.getOrder(t);return j(o)})}var Zxe=f.object({tradingPairId:f.string().trim().min(1,"Trading pair ID is required and cannot be empty"),side:f.enum(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:f.string().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:f.string().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:f.enum(["LIMIT","MARKET"]).optional(),slippageToleranceBps:f.number().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:f.ZodIssueCode.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),Wxe=f.object({applicationName:f.string().nullable().optional(),applicationTakerFee:f.string(),applicationTakerFeeBps:f.number(),buyOrderLockAmount:f.string().nullable().optional(),makerTotalReceipt:f.string(),monacoMakerRebate:f.string(),monacoMakerRebateBps:f.number(),monacoMakerRebateBpsExact:f.string(),monacoTakerFee:f.string(),monacoTakerFeeBps:f.number(),monacoTakerFeeBpsExact:f.string(),notional:f.string(),takerTotalPayment:f.string(),totalTakerFees:f.string(),maxQuantity:f.string().nullable(),maxQuantityRaw:f.string().nullable(),slippageToleranceBps:f.number().nullable()}),Kxe=f.object({tradingPairId:f.string().trim().min(1,"Trading pair ID is required and cannot be empty")}),XJ=f.object({tierLevel:f.number().int(),minVolumeThreshold:f.string(),makerFeeBps:f.string(),takerFeeBps:f.string()}),Jxe=f.object({currentTierLevel:f.number().int(),weightedVolume14d:f.string(),spotVolume14d:f.string(),perpVolume14d:f.string(),volumeToNextTier:f.string().nullable().optional(),nextTierLevel:f.number().int().nullable().optional(),feeSchedule:f.array(XJ)});var eY=f.object({token:f.string(),available:f.string()}),Yxe=f.object({balances:f.array(eY)}),Qxe=f.object({code:f.string(),createdAt:f.string(),customCode:f.string(),isCustom:f.boolean(),display:f.string()}),tY=f.enum(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),Xxe=f.object({available:f.boolean(),reason:f.preprocess((e)=>e===""||e===null?void 0:e,tY.optional())}),eve=f.object({code:f.string().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")}),tve=f.object({code:f.string()}),rve=f.object({token:f.string().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:f.string().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),nve=f.object({rewardsBalance:f.string(),tradingBalance:f.string()});var Rf=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var zy=f.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),rT=f.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),$C=f.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),Ny=f.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),rY=f.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),RC=f.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),Of=f.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),St=f.string().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"}),$e=f.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),My=f.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),nY=f.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),By=f.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),XS=f.object({triggerPrice:St,orderType:Of,limitPrice:St.optional(),timeInForce:RC.optional(),slippageToleranceBps:By.optional(),expiresAt:My.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"]}),eT=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0,OC=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),Q$r=f.object({tradingPairId:$e,side:zy,quantity:St,price:St,options:f.object({tradingMode:rT.optional(),useMasterBalance:f.boolean().optional(),expirationDate:My.optional(),timeInForce:rY.optional(),marginAccountId:$e.optional(),marginMode:$C.optional(),riskBucketId:$e.optional(),riskBucketCollateral:St.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:Ny.optional(),leverage:St.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().optional(),takeProfit:XS.optional(),stopLoss:XS.optional()}).optional()}).refine((e)=>OC(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)=>!eT(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!eT(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss 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"]}),X$r=f.object({tradingPairId:$e,side:zy,quantity:St,options:f.object({tradingMode:rT.optional(),slippageTolerance:nY,marginAccountId:$e.optional(),marginMode:$C.optional(),riskBucketId:$e.optional(),riskBucketCollateral:St.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:Ny.optional(),leverage:St.optional(),reduceOnly:f.boolean().optional(),takeProfit:XS.optional(),stopLoss:XS.optional()}).optional()}).refine((e)=>OC(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)=>!eT(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!eT(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss 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"]}),eRr=f.object({orderId:$e}),tRr=f.object({orderId:$e,newOrder:f.object({price:St.optional(),quantity:St.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()})}),rRr=f.object({status:f.union([f.enum(Rf),f.array(f.enum(Rf)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:$e.optional(),tradingMode:rT.optional(),marginAccountId:$e.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),nRr=f.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),oRr=f.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),ove=f.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),iRr=f.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),sRr=f.object({conditionalOrderId:$e}),aRr=f.object({marginAccountId:$e.optional(),tradingPairId:$e.optional(),state:ove.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),ive=f.object({tradingPairId:$e,orderType:Of,side:zy,price:St.optional(),quantity:St,tradingMode:rT.optional(),slippageTolerance:nY,useMasterBalance:f.boolean().optional(),expirationDate:My.optional(),timeInForce:rY.optional(),marginAccountId:$e.optional(),marginMode:$C.optional(),riskBucketId:$e.optional(),riskBucketCollateral:St.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:Ny.optional(),leverage:St.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().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)=>OC(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"]}),tT=100,cRr=f.object({orders:f.array(ive).min(1,"At least one order is required").max(tT,`At most ${tT} orders per batch request`)}),sve=f.object({orderId:$e,price:St.optional(),quantity:St.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),uRr=f.object({orders:f.array(sve).min(1,"At least one order is required").max(tT,`At most ${tT} orders per batch request`)});var CC=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),fRr=CC.extend({state:f.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:$e.optional()}),mRr=f.object({marginAccountId:$e,tradingPairId:$e.optional()}),hRr=f.object({tradingPairId:$e.optional()}).optional(),gRr=f.object({asset:f.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),ave=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:St,tradingPairId:$e.optional(),strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:f.enum(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),nT=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:St}),cve=f.object({tradingPairId:$e,strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional()}),uve=f.array($e).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),oY=cve.extend({marginMode:f.literal("ISOLATED").optional(),selectedTradingPairIds:f.never().optional()}),iY=f.object({marginMode:f.literal("CROSS"),selectedTradingPairIds:uve,strategyKey:f.never().optional()}),lve=iY.extend({tradingPairId:f.never().optional()}),yRr=f.object({marginAccountId:$e,request:ave}),bRr=f.object({request:nT}),xRr=f.object({request:f.union([nT.merge(oY).strict(),nT.merge(lve).strict()])}),vRr=f.object({request:nT}),_Rr=CC.extend({marginAccountId:$e,movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}),wRr=CC.extend({movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),zC=f.object({tradingPairId:$e,side:zy,positionSide:Ny.optional(),orderType:Of,price:St.optional(),quantity:St,leverage:St.optional(),reduceOnly:f.boolean().optional()}),NC=(e,t)=>{if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:f.ZodIssueCode.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:f.ZodIssueCode.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},sY=zC.strict().superRefine(NC),dve=zC.merge(oY).strict().superRefine(NC),pve=zC.merge(iY).strict().superRefine(NC).refine((e)=>e.selectedTradingPairIds.includes(e.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),fve=f.union([dve,pve]),SRr=f.object({marginAccountId:$e,request:sY}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),TRr=f.object({request:sY}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),ERr=f.object({request:fve}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var aY=f.enum(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),mve=31536000000,hve=946684800000,oT=f.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(hve,{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()+mve,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),ARr=f.object({tradingPairId:$e,interval:aY,startTime:oT,endTime:oT}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),$Rr=f.string().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")'}),gve=f.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),RRr=f.object({tradingPairId:$e,interval:aY,startTime:oT.optional(),endTime:oT.optional(),limit:gve}).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 ORr=f.object({tradingPairId:$e}),CRr=f.object({query:f.string().min(1,"Search query cannot be empty").optional(),pageSize:f.number().int().min(1).max(100).optional(),page:f.number().int().min(1).optional()}),zRr=f.object({tradingPairId:$e});var uY=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),yve=f.enum(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),bve=f.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),MC=f.object({positionId:$e}),DRr=uY.extend({marginAccountId:$e.optional(),tradingPairId:$e.optional(),status:yve.optional()});var URr=MC.extend({request:f.object({closeType:bve,limitPrice:St.optional(),slippageToleranceBps:By.optional(),quantity:St.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"]}),LRr=f.object({tradingPairId:$e.optional(),slippageToleranceBps:By.optional()});var cY=f.object({triggerPrice:St,orderType:Of,limitPrice:St.optional(),quantity:St.optional(),closePosition:f.boolean().optional(),timeInForce:RC.optional(),slippageToleranceBps:By.optional(),expiresAt:My.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"]}),jRr=MC.extend({request:f.object({takeProfit:cY.optional(),stopLoss:cY.optional(),oco:f.boolean().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss 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"]})}),FRr=uY.extend({positionId:$e.optional(),marginAccountId:$e.optional(),tradingPairId:$e.optional(),reductionOnly:f.boolean().optional()}),xve=f.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),qRr=MC.extend({params:f.object({interval:xve,startTime:f.number().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:f.number().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 vve=f.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),_ve=f.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),ZRr=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),entryType:vve.optional(),transactionType:_ve.optional(),assetId:$e.optional()}),WRr=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().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:$e.optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),KRr=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),tradingPairId:$e.optional(),positionId:$e.optional(),marginAccountId:$e.optional()});var XRr=f.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),BC=f.union([f.string().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),f.bigint().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),e2r=f.object({assetId:$e,amount:BC,autoWait:f.boolean().optional()}),t2r=f.object({assetId:$e,amount:BC,autoWait:f.boolean().optional(),target:f.enum(["spot","margin"]).optional()}),r2r=f.object({assetId:$e,amount:BC,destination:f.string().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:f.boolean().optional(),source:f.enum(["spot","margin"]).optional()}),n2r=f.object({assetId:$e});function lY(e){e.registerTool("get_orders",{description:"Get a cursor-paginated list of orders with optional filters by status and trading pair. Omit both page and 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. Cursor responses have no exact totals (total/totalPages are 0).",inputSchema:f.object({status:f.enum(Rf).optional().describe("Filter by order status (e.g. SUBMITTED, FILLED, CANCELLED)"),tradingPairId:f.string().optional().describe("Filter by trading pair UUID"),page:f.number().optional().describe("Deprecated: page number for legacy offset pagination, which only sees recent history. Use pageToken instead."),pageSize:f.number().optional().describe("Orders per page (default: 10; max 100 in legacy page mode, up to 1000 with pageToken)"),pageToken:f.string().optional().describe("Pagination cursor from a previous response's nextPageToken. Omit it (and page) to start from the newest orders.")})},async({status:t,tradingPairId:r,page:o,pageSize:n,pageToken:i})=>{let a=await(await te()).trading.getPaginatedOrders({status:t,tradingPairId:r,page:o,pageSize:n,pageToken:i});return j(a)})}function dY(e){e.registerTool("place_limit_order",{description:"Place a limit order on Monaco. Limit orders execute only when the market reaches the specified price. "+"Not idempotent: if the call fails with an ambiguous outcome (timeout, network error, or a 5xx with no order returned), do NOT blindly retry — the order may already be live. First reconcile with get_orders (match the order's pair/side/price/quantity among your recent orders, including filled ones) or get_order, then resubmit only if it did not land.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),side:f.enum(["BUY","SELL"]).describe("Order side"),quantity:f.string().describe("Order quantity as a decimal string"),price:f.string().describe("Limit price as a decimal string"),tradingMode:f.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),timeInForce:f.enum(["GTC","IOC","FOK"]).optional().describe("Time in force (default: GTC)"),expirationDate:f.string().optional().describe("Expiration date for GTC orders (ISO 8601)"),marginAccountId:f.string().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:f.enum(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:f.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:f.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:f.string().optional().describe("Optional client strategy key"),positionSide:f.enum(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:f.string().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:f.boolean().optional().describe("Whether the order can only reduce existing exposure"),postOnly:f.boolean().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.")})},async({tradingPairId:t,side:r,quantity:o,price:n,tradingMode:i,timeInForce:s,expirationDate:a,marginAccountId:c,marginMode:u,riskBucketId:d,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:y,reduceOnly:x,postOnly:S})=>{let E=await(await te()).trading.placeLimitOrder(t,r,o,n,{tradingMode:i,timeInForce:s,expirationDate:a,marginAccountId:c,marginMode:u,riskBucketId:d,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:y,reduceOnly:x,postOnly:S});return j(E)})}function pY(e){e.registerTool("place_market_order",{description:"Place a market order on Monaco. 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. Not idempotent: if the call fails with an ambiguous outcome (timeout, network error, or a 5xx with no order returned), do NOT blindly retry — the order may already be live. First reconcile with get_orders (match the order's pair/side/quantity among your recent orders, including filled ones) or get_order, then resubmit only if it did not land.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),side:f.enum(["BUY","SELL"]).describe("Order side"),quantity:f.string().describe("Order quantity as a decimal string"),tradingMode:f.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),slippageTolerance:f.number().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:f.string().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:f.enum(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:f.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:f.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:f.string().optional().describe("Optional client strategy key"),positionSide:f.enum(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:f.string().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:f.boolean().optional().describe("Whether the order can only reduce existing exposure")})},async({tradingPairId:t,side:r,quantity:o,tradingMode:n,slippageTolerance:i,marginAccountId:s,marginMode:a,riskBucketId:c,riskBucketCollateral:u,strategyKey:d,positionSide:p,leverage:m,reduceOnly:h})=>{let x=await(await te()).trading.placeMarketOrder(t,r,o,{tradingMode:n,slippageTolerance:i,marginAccountId:s,marginMode:a,riskBucketId:c,riskBucketCollateral:u,strategyKey:d,positionSide:p,leverage:m,reduceOnly:h});return j(x)})}function fY(e){e.registerTool("replace_order",{description:"Replace an existing order with new price and/or quantity. The order must be open. "+"Not idempotent: if the call fails with an ambiguous outcome (timeout, network error, or a 5xx with no order returned), do NOT blindly retry — read the order back with get_order and compare its price/quantity before replacing again.",inputSchema:f.object({orderId:f.string().describe("The order ID to replace"),price:f.string().optional().describe("New price as a decimal string"),quantity:f.string().optional().describe("New quantity as a decimal string"),postOnly:f.boolean().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.")})},async({orderId:t,price:r,quantity:o,postOnly:n})=>{let s=await(await te()).trading.replaceOrder(t,{price:r,quantity:o,postOnly:n});return j(s)})}function mY(e){dY(e),pY(e),YJ(e),KJ(e),WJ(e),JJ(e),fY(e),lY(e),QJ(e)}function hY(e){e.registerTool("vault_get_allowance",{description:"Check the current token allowance granted to the Monaco vault for a specific asset.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to check allowance for")})},async({assetId:t})=>{let o=await(await te()).vault.getAllowance(t);return j({assetId:t,allowance:o.toString()})})}function gY(e){e.registerTool("vault_approve",{description:"Approve the Monaco vault contract to spend tokens on your behalf. Required before depositing ERC20 tokens.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to approve"),amount:f.string().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 n=await(await te()).vault.approve(t,BigInt(r));return j({hash:n.hash,status:n.status})})}function yY(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:f.object({assetId:f.string().describe("The asset UUID to deposit"),amount:f.string().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:f.enum(["spot","margin"]).optional().describe("Destination ledger: 'spot' (default) or 'margin' to route into margin collateral")})},async({assetId:t,amount:r,target:o})=>{let i=await(await te()).vault.deposit(t,BigInt(r),void 0,o);return j({hash:i.hash,status:i.status})})}function bY(e){e.registerTool("get_pending_withdrawals",{description:"List your pending withdrawals still awaiting on-chain root confirmation.",inputSchema:f.object({page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page")})},async({page:t,pageSize:r})=>{let n=await(await te()).withdrawals.listPendingWithdrawals({page:t,pageSize:r});return j(n)})}function xY(e){e.registerTool("vault_needs_approval",{description:"Check if approval is needed before depositing a specific amount of tokens.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to check"),amount:f.string().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to check as a raw integer string")})},async({assetId:t,amount:r})=>{let n=await(await te()).vault.needsApproval(t,BigInt(r));return j({assetId:t,amount:r,needs_approval:n})})}function vY(e){e.registerTool("vault_withdraw",{description:"Withdraw tokens from the Monaco vault back to your wallet.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to withdraw"),amount:f.string().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 n=await(await te()).vault.withdraw(t,BigInt(r));return j({withdrawalIndex:n.withdrawalIndex,status:n.status,hash:n.hash})})}function _Y(e){gY(e),yY(e),vY(e),hY(e),xY(e),bY(e)}function wve(e){let t=e.length-1,r=e[t];if(typeof r!=="function")return e;let o=RK(r);return[...e.slice(0,t),o]}function Sve(e,t){let[r,...o]=t;if(!r||typeof r!=="object")return t;let n=F3(e);if(!n)return t;let i=r.annotations;return[{...r,annotations:{...n,...i}},...o]}function wY(e,t,r){return new Proxy(e,{get(o,n,i){if(n==="registerTool")return(a,...c)=>{if(!Z3(a,t))return;let u=Sve(a,c);if(r&&V3(a))u=wve(u);return o.registerTool(a,...u)};let s=Reflect.get(o,n,i);return typeof s==="function"?s.bind(o):s}})}function SY(e,t){let r={authenticated:t.authenticated,capability:t.capability,allow:t.allow??[],deny:t.deny??[],network:t.network},o=wY(e,r,!1);if(GJ(o),eJ(o),dJ(o),rJ(o),ZJ(o),xJ(o),FJ(o),t.authenticated){let n=wY(e,r,!0);mY(n),CJ(n),LJ(n),IJ(n),ZK(n),BK(n),_Y(n),zK(n,{network:t.network}),vJ(n)}}if(typeof globalThis.crypto?.getRandomValues!=="function")globalThis.crypto=Tve;if(!globalThis.fetch)globalThis.fetch=vb,globalThis.Headers=nn,globalThis.Request=Yi,globalThis.Response=Ar;if(!globalThis.WebSocket)globalThis.WebSocket=sE.default;async function Eve(){let e=su(),t=e.privateKey!==null,r=new l$({name:"monaco-mcp-server",version:C_.version});SY(r,{authenticated:t,network:e.network,capability:e.capability,allow:e.allow,deny:e.deny});let o=new p$;await r.connect(o),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).")}Eve().catch((e)=>{console.error("Fatal error:",e),process.exit(1)});
169
+ `).find((a)=>a.startsWith("data: "));if(!s)throw Error("No data in Mintlify MCP response");return JSON.parse(s.slice(6))}async function Gxe(){if(QS)return;await qJ("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"monaco-mcp-server",version:C_.version}},0)}async function Vxe(e){return await Gxe(),(await qJ("tools/call",{name:Hxe,arguments:{query:e}},1))?.result}function HJ(e){e.registerTool("search_docs",{description:"Search the Monaco documentation for information about the protocol, SDK, trading, and development guides.",inputSchema:f.object({query:f.string().describe("The search query")})},async({query:t})=>{try{let r=await Vxe(t);if(r?.content&&Array.isArray(r.content))return{content:r.content};return j(r)}catch(r){return YS(`Search failed: ${r instanceof Error?r.message:String(r)}`)}})}function GJ(e){HJ(e)}function VJ(e){e.registerTool("get_trades",{description:"Get historical trades for a trading pair. Returns recent trades sorted by execution time (newest first).",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),page:f.number().optional().describe("Page number (starts from 1, default: 1)"),pageSize:f.number().optional().describe("Max number of records to return (default: 25, max: 100)")})},async({tradingPairId:t,page:r,pageSize:o})=>{let i=await qe().trades.getTrades(t,{page:r,pageSize:o});return j(i)})}function ZJ(e){VJ(e)}function WJ(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:f.object({tradingPairId:f.string().optional().describe("Optional trading pair UUID to limit cancellation to")})},async({tradingPairId:t})=>{let o=await(await te()).trading.batchCancelAll(t);return j(o)})}function KJ(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:f.object({orderIds:f.array(f.string()).describe("Array of order IDs to cancel")})},async({orderIds:t})=>{let o=await(await te()).trading.batchCancel(t);return j(o)})}function JJ(e){e.registerTool("batch_close_all_positions",{description:"Close all open perpetual positions with MARKET reduce-only orders ('panic close'), optionally filtered to a specific trading pair. Best-effort: each position closes independently and per-position failures are reported in the result.",inputSchema:f.object({tradingPairId:f.string().optional().describe("Optional trading pair UUID to limit the close to"),slippageToleranceBps:f.number().int().optional().describe("Optional slippage tolerance (basis points) applied to each close")})},async({tradingPairId:t,slippageToleranceBps:r})=>{let n=await(await te()).positions.batchCloseAllPositions({tradingPairId:t,slippageToleranceBps:r});return j(n)})}function YJ(e){e.registerTool("cancel_order",{description:"Cancel an open order by its ID.",inputSchema:f.object({orderId:f.string().describe("The order ID to cancel")})},async({orderId:t})=>{let o=await(await te()).trading.cancelOrder(t);return j(o)})}function QJ(e){e.registerTool("get_order",{description:"Get detailed information about a specific order by its ID.",inputSchema:f.object({orderId:f.string().describe("The order ID to look up")})},async({orderId:t})=>{let o=await(await te()).trading.getOrder(t);return j(o)})}var Zxe=f.object({tradingPairId:f.string().trim().min(1,"Trading pair ID is required and cannot be empty"),side:f.enum(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:f.string().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:f.string().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:f.enum(["LIMIT","MARKET"]).optional(),slippageToleranceBps:f.number().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:f.ZodIssueCode.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),Wxe=f.object({applicationName:f.string().nullable().optional(),applicationTakerFee:f.string(),applicationTakerFeeBps:f.number(),buyOrderLockAmount:f.string().nullable().optional(),makerTotalReceipt:f.string(),monacoMakerRebate:f.string(),monacoMakerRebateBps:f.number(),monacoMakerRebateBpsExact:f.string(),monacoTakerFee:f.string(),monacoTakerFeeBps:f.number(),monacoTakerFeeBpsExact:f.string(),notional:f.string(),takerTotalPayment:f.string(),totalTakerFees:f.string(),maxQuantity:f.string().nullable(),maxQuantityRaw:f.string().nullable(),slippageToleranceBps:f.number().nullable()}),Kxe=f.object({tradingPairId:f.string().trim().min(1,"Trading pair ID is required and cannot be empty")}),XJ=f.object({tierLevel:f.number().int(),minVolumeThreshold:f.string(),makerFeeBps:f.string(),takerFeeBps:f.string()}),Jxe=f.object({currentTierLevel:f.number().int(),weightedVolume14d:f.string(),spotVolume14d:f.string(),perpVolume14d:f.string(),volumeToNextTier:f.string().nullable().optional(),nextTierLevel:f.number().int().nullable().optional(),feeSchedule:f.array(XJ)});var eY=f.object({token:f.string(),available:f.string()}),Yxe=f.object({balances:f.array(eY)}),Qxe=f.object({code:f.string(),createdAt:f.string(),customCode:f.string(),isCustom:f.boolean(),display:f.string()}),tY=f.enum(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),Xxe=f.object({available:f.boolean(),reason:f.preprocess((e)=>e===""||e===null?void 0:e,tY.optional())}),eve=f.object({code:f.string().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")}),tve=f.object({code:f.string()}),rve=f.object({token:f.string().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:f.string().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),nve=f.object({rewardsBalance:f.string(),tradingBalance:f.string()});var Rf=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var zy=f.enum(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),rT=f.enum(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),$C=f.enum(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),Ny=f.enum(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),rY=f.enum(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),RC=f.enum(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),Of=f.enum(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),xt=f.string().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"}),$e=f.uuid({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),My=f.iso.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),nY=f.number().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),By=f.number().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),XS=f.object({triggerPrice:xt,orderType:Of,limitPrice:xt.optional(),quantity:xt.optional(),closePosition:f.boolean().optional(),timeInForce:RC.optional(),slippageToleranceBps:By.optional(),expiresAt:My.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"]}),eT=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0,OC=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),X$r=f.object({tradingPairId:$e,side:zy,quantity:xt,price:xt,options:f.object({tradingMode:rT.optional(),useMasterBalance:f.boolean().optional(),expirationDate:My.optional(),timeInForce:rY.optional(),marginAccountId:$e.optional(),marginMode:$C.optional(),riskBucketId:$e.optional(),riskBucketCollateral:xt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:Ny.optional(),leverage:xt.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().optional(),takeProfit:XS.optional(),stopLoss:XS.optional()}).optional()}).refine((e)=>OC(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)=>!eT(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!eT(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss 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"]}),eRr=f.object({tradingPairId:$e,side:zy,quantity:xt,options:f.object({tradingMode:rT.optional(),slippageTolerance:nY,marginAccountId:$e.optional(),marginMode:$C.optional(),riskBucketId:$e.optional(),riskBucketCollateral:xt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:Ny.optional(),leverage:xt.optional(),reduceOnly:f.boolean().optional(),takeProfit:XS.optional(),stopLoss:XS.optional()}).optional()}).refine((e)=>OC(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)=>!eT(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!eT(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss 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"]}),tRr=f.object({orderId:$e}),rRr=f.object({orderId:$e,newOrder:f.object({price:xt.optional(),quantity:xt.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()})}),nRr=f.object({status:f.union([f.enum(Rf),f.array(f.enum(Rf)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:$e.optional(),tradingMode:rT.optional(),marginAccountId:$e.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),oRr=f.enum(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),iRr=f.enum(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),ove=f.enum(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),sRr=f.enum(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),aRr=f.object({conditionalOrderId:$e}),cRr=f.object({marginAccountId:$e.optional(),tradingPairId:$e.optional(),state:ove.optional(),page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),ive=f.object({tradingPairId:$e,orderType:Of,side:zy,price:xt.optional(),quantity:xt,tradingMode:rT.optional(),slippageTolerance:nY,useMasterBalance:f.boolean().optional(),expirationDate:My.optional(),timeInForce:rY.optional(),marginAccountId:$e.optional(),marginMode:$C.optional(),riskBucketId:$e.optional(),riskBucketCollateral:xt.optional(),strategyKey:f.string().min(1).max(128).optional(),positionSide:Ny.optional(),leverage:xt.optional(),reduceOnly:f.boolean().optional(),postOnly:f.boolean().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)=>OC(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"]}),tT=100,uRr=f.object({orders:f.array(ive).min(1,"At least one order is required").max(tT,`At most ${tT} orders per batch request`)}),sve=f.object({orderId:$e,price:xt.optional(),quantity:xt.optional(),useMasterBalance:f.boolean().optional(),postOnly:f.boolean().optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),lRr=f.object({orders:f.array(sve).min(1,"At least one order is required").max(tT,`At most ${tT} orders per batch request`)});var CC=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),mRr=CC.extend({state:f.string().trim().min(1,"State cannot be empty").optional(),tradingPairId:$e.optional()}),hRr=f.object({marginAccountId:$e,tradingPairId:$e.optional()}),gRr=f.object({tradingPairId:$e.optional()}).optional(),yRr=f.object({asset:f.string().trim().min(1,"Asset cannot be empty").optional()}).optional(),ave=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:xt,tradingPairId:$e.optional(),strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:f.enum(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),nT=f.object({asset:f.string().trim().min(1,"Asset cannot be empty"),amount:xt}),cve=f.object({tradingPairId:$e,strategyKey:f.string().trim().min(1,"Strategy key cannot be empty").optional()}),uve=f.array($e).min(1,"selectedTradingPairIds is required for CROSS risk buckets"),oY=cve.extend({marginMode:f.literal("ISOLATED").optional(),selectedTradingPairIds:f.never().optional()}),iY=f.object({marginMode:f.literal("CROSS"),selectedTradingPairIds:uve,strategyKey:f.never().optional()}),lve=iY.extend({tradingPairId:f.never().optional()}),bRr=f.object({marginAccountId:$e,request:ave}),xRr=f.object({request:nT}),vRr=f.object({request:f.union([nT.merge(oY).strict(),nT.merge(lve).strict()])}),_Rr=f.object({request:nT}),wRr=CC.extend({marginAccountId:$e,movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}),SRr=CC.extend({movementType:f.string().trim().min(1,"Movement type cannot be empty").optional()}).optional(),zC=f.object({tradingPairId:$e,side:zy,positionSide:Ny.optional(),orderType:Of,price:xt.optional(),quantity:xt,leverage:xt.optional(),reduceOnly:f.boolean().optional()}),NC=(e,t)=>{if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:f.ZodIssueCode.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:f.ZodIssueCode.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},sY=zC.strict().superRefine(NC),dve=zC.merge(oY).strict().superRefine(NC),pve=zC.merge(iY).strict().superRefine(NC).refine((e)=>e.selectedTradingPairIds.includes(e.tradingPairId),{message:"tradingPairId must be included in selectedTradingPairIds for CROSS risk buckets",path:["selectedTradingPairIds"]}),fve=f.union([dve,pve]),TRr=f.object({marginAccountId:$e,request:sY}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),ERr=f.object({request:sY}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),IRr=f.object({request:fve}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var aY=f.enum(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),mve=31536000000,hve=946684800000,oT=f.number().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(hve,{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()+mve,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),$Rr=f.object({tradingPairId:$e,interval:aY,startTime:oT,endTime:oT}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),RRr=f.string().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")'}),gve=f.number().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),ORr=f.object({tradingPairId:$e,interval:aY,startTime:oT.optional(),endTime:oT.optional(),limit:gve}).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 CRr=f.object({tradingPairId:$e}),zRr=f.object({query:f.string().min(1,"Search query cannot be empty").optional(),pageSize:f.number().int().min(1).max(100).optional(),page:f.number().int().min(1).optional()}),NRr=f.object({tradingPairId:$e});var uY=f.object({page:f.number().int().min(1,"Page must be at least 1").optional(),pageSize:f.number().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),yve=f.enum(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),bve=f.enum(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),MC=f.object({positionId:$e}),URr=uY.extend({marginAccountId:$e.optional(),tradingPairId:$e.optional(),status:yve.optional()});var LRr=MC.extend({request:f.object({closeType:bve,limitPrice:xt.optional(),slippageToleranceBps:By.optional(),quantity:xt.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"]}),jRr=f.object({tradingPairId:$e.optional(),slippageToleranceBps:By.optional()});var cY=f.object({triggerPrice:xt,orderType:Of,limitPrice:xt.optional(),quantity:xt.optional(),closePosition:f.boolean().optional(),timeInForce:RC.optional(),slippageToleranceBps:By.optional(),expiresAt:My.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"]}),FRr=MC.extend({request:f.object({takeProfit:cY.optional(),stopLoss:cY.optional(),oco:f.boolean().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss 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"]})}),qRr=uY.extend({positionId:$e.optional(),marginAccountId:$e.optional(),tradingPairId:$e.optional(),reductionOnly:f.boolean().optional()}),xve=f.enum(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),HRr=MC.extend({params:f.object({interval:xve,startTime:f.number().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:f.number().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 vve=f.enum(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),_ve=f.enum(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),WRr=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),entryType:vve.optional(),transactionType:_ve.optional(),assetId:$e.optional()}),KRr=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().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:$e.optional(),pageToken:f.string().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:f.ZodIssueCode.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),JRr=f.object({page:f.number().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:f.number().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),tradingPairId:$e.optional(),positionId:$e.optional(),marginAccountId:$e.optional()});var e2r=f.string().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),BC=f.union([f.string().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),f.bigint().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),t2r=f.object({assetId:$e,amount:BC,autoWait:f.boolean().optional()}),r2r=f.object({assetId:$e,amount:BC,autoWait:f.boolean().optional(),target:f.enum(["spot","margin"]).optional()}),n2r=f.object({assetId:$e,amount:BC,destination:f.string().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:f.boolean().optional(),source:f.enum(["spot","margin"]).optional()}),o2r=f.object({assetId:$e});function lY(e){e.registerTool("get_orders",{description:"Get a cursor-paginated list of orders with optional filters by status and trading pair. Omit both page and 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. Cursor responses have no exact totals (total/totalPages are 0).",inputSchema:f.object({status:f.enum(Rf).optional().describe("Filter by order status (e.g. SUBMITTED, FILLED, CANCELLED)"),tradingPairId:f.string().optional().describe("Filter by trading pair UUID"),page:f.number().optional().describe("Deprecated: page number for legacy offset pagination, which only sees recent history. Use pageToken instead."),pageSize:f.number().optional().describe("Orders per page (default: 10; max 100 in legacy page mode, up to 1000 with pageToken)"),pageToken:f.string().optional().describe("Pagination cursor from a previous response's nextPageToken. Omit it (and page) to start from the newest orders.")})},async({status:t,tradingPairId:r,page:o,pageSize:n,pageToken:i})=>{let a=await(await te()).trading.getPaginatedOrders({status:t,tradingPairId:r,page:o,pageSize:n,pageToken:i});return j(a)})}function dY(e){e.registerTool("place_limit_order",{description:"Place a limit order on Monaco. Limit orders execute only when the market reaches the specified price. "+"Not idempotent: if the call fails with an ambiguous outcome (timeout, network error, or a 5xx with no order returned), do NOT blindly retry — the order may already be live. First reconcile with get_orders (match the order's pair/side/price/quantity among your recent orders, including filled ones) or get_order, then resubmit only if it did not land.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),side:f.enum(["BUY","SELL"]).describe("Order side"),quantity:f.string().describe("Order quantity as a decimal string"),price:f.string().describe("Limit price as a decimal string"),tradingMode:f.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),timeInForce:f.enum(["GTC","IOC","FOK"]).optional().describe("Time in force (default: GTC)"),expirationDate:f.string().optional().describe("Expiration date for GTC orders (ISO 8601)"),marginAccountId:f.string().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:f.enum(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:f.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:f.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:f.string().optional().describe("Optional client strategy key"),positionSide:f.enum(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:f.string().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:f.boolean().optional().describe("Whether the order can only reduce existing exposure"),postOnly:f.boolean().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."),clientOrderId:f.string().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: not de-duplicated and not unique — reconcile a lost response via get_orders before resubmitting.")})},async({tradingPairId:t,side:r,quantity:o,price:n,tradingMode:i,timeInForce:s,expirationDate:a,marginAccountId:c,marginMode:u,riskBucketId:d,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:y,reduceOnly:x,postOnly:S,clientOrderId:v})=>{let w=await(await te()).trading.placeLimitOrder(t,r,o,n,{tradingMode:i,timeInForce:s,expirationDate:a,marginAccountId:c,marginMode:u,riskBucketId:d,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:y,reduceOnly:x,postOnly:S,clientOrderId:v});return j(w)})}function pY(e){e.registerTool("place_market_order",{description:"Place a market order on Monaco. 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. Not idempotent: if the call fails with an ambiguous outcome (timeout, network error, or a 5xx with no order returned), do NOT blindly retry — the order may already be live. First reconcile with get_orders (match the order's pair/side/quantity among your recent orders, including filled ones) or get_order, then resubmit only if it did not land.",inputSchema:f.object({tradingPairId:f.string().describe("Trading pair UUID"),side:f.enum(["BUY","SELL"]).describe("Order side"),quantity:f.string().describe("Order quantity as a decimal string"),tradingMode:f.enum(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),slippageTolerance:f.number().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:f.string().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:f.enum(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:f.string().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:f.string().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:f.string().optional().describe("Optional client strategy key"),positionSide:f.enum(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:f.string().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:f.boolean().optional().describe("Whether the order can only reduce existing exposure"),clientOrderId:f.string().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: not de-duplicated and not unique — reconcile a lost response via get_orders before resubmitting.")})},async({tradingPairId:t,side:r,quantity:o,tradingMode:n,slippageTolerance:i,marginAccountId:s,marginMode:a,riskBucketId:c,riskBucketCollateral:u,strategyKey:d,positionSide:p,leverage:m,reduceOnly:h,clientOrderId:y})=>{let S=await(await te()).trading.placeMarketOrder(t,r,o,{tradingMode:n,slippageTolerance:i,marginAccountId:s,marginMode:a,riskBucketId:c,riskBucketCollateral:u,strategyKey:d,positionSide:p,leverage:m,reduceOnly:h,clientOrderId:y});return j(S)})}function fY(e){e.registerTool("replace_order",{description:"Replace an existing order with new price and/or quantity. The order must be open. "+"Not idempotent: if the call fails with an ambiguous outcome (timeout, network error, or a 5xx with no order returned), do NOT blindly retry — read the order back with get_order and compare its price/quantity before replacing again.",inputSchema:f.object({orderId:f.string().describe("The order ID to replace"),price:f.string().optional().describe("New price as a decimal string"),quantity:f.string().optional().describe("New quantity as a decimal string"),postOnly:f.boolean().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."),clientOrderId:f.string().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: not de-duplicated and not unique.")})},async({orderId:t,price:r,quantity:o,postOnly:n,clientOrderId:i})=>{let a=await(await te()).trading.replaceOrder(t,{price:r,quantity:o,postOnly:n,clientOrderId:i});return j(a)})}function mY(e){dY(e),pY(e),YJ(e),KJ(e),WJ(e),JJ(e),fY(e),lY(e),QJ(e)}function hY(e){e.registerTool("vault_get_allowance",{description:"Check the current token allowance granted to the Monaco vault for a specific asset.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to check allowance for")})},async({assetId:t})=>{let o=await(await te()).vault.getAllowance(t);return j({assetId:t,allowance:o.toString()})})}function gY(e){e.registerTool("vault_approve",{description:"Approve the Monaco vault contract to spend tokens on your behalf. Required before depositing ERC20 tokens.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to approve"),amount:f.string().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 n=await(await te()).vault.approve(t,BigInt(r));return j({hash:n.hash,status:n.status})})}function yY(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:f.object({assetId:f.string().describe("The asset UUID to deposit"),amount:f.string().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:f.enum(["spot","margin"]).optional().describe("Destination ledger: 'spot' (default) or 'margin' to route into margin collateral")})},async({assetId:t,amount:r,target:o})=>{let i=await(await te()).vault.deposit(t,BigInt(r),void 0,o);return j({hash:i.hash,status:i.status})})}function bY(e){e.registerTool("get_pending_withdrawals",{description:"List your pending withdrawals still awaiting on-chain root confirmation.",inputSchema:f.object({page:f.number().optional().describe("Page number (1-based)"),pageSize:f.number().optional().describe("Items per page")})},async({page:t,pageSize:r})=>{let n=await(await te()).withdrawals.listPendingWithdrawals({page:t,pageSize:r});return j(n)})}function xY(e){e.registerTool("vault_needs_approval",{description:"Check if approval is needed before depositing a specific amount of tokens.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to check"),amount:f.string().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to check as a raw integer string")})},async({assetId:t,amount:r})=>{let n=await(await te()).vault.needsApproval(t,BigInt(r));return j({assetId:t,amount:r,needs_approval:n})})}function vY(e){e.registerTool("vault_withdraw",{description:"Withdraw tokens from the Monaco vault back to your wallet.",inputSchema:f.object({assetId:f.string().describe("The asset UUID to withdraw"),amount:f.string().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 n=await(await te()).vault.withdraw(t,BigInt(r));return j({withdrawalIndex:n.withdrawalIndex,status:n.status,hash:n.hash})})}function _Y(e){gY(e),yY(e),vY(e),hY(e),xY(e),bY(e)}function wve(e){let t=e.length-1,r=e[t];if(typeof r!=="function")return e;let o=RK(r);return[...e.slice(0,t),o]}function Sve(e,t){let[r,...o]=t;if(!r||typeof r!=="object")return t;let n=F3(e);if(!n)return t;let i=r.annotations;return[{...r,annotations:{...n,...i}},...o]}function wY(e,t,r){return new Proxy(e,{get(o,n,i){if(n==="registerTool")return(a,...c)=>{if(!Z3(a,t))return;let u=Sve(a,c);if(r&&V3(a))u=wve(u);return o.registerTool(a,...u)};let s=Reflect.get(o,n,i);return typeof s==="function"?s.bind(o):s}})}function SY(e,t){let r={authenticated:t.authenticated,capability:t.capability,allow:t.allow??[],deny:t.deny??[],network:t.network},o=wY(e,r,!1);if(GJ(o),eJ(o),dJ(o),rJ(o),ZJ(o),xJ(o),FJ(o),t.authenticated){let n=wY(e,r,!0);mY(n),CJ(n),LJ(n),IJ(n),ZK(n),BK(n),_Y(n),zK(n,{network:t.network}),vJ(n)}}if(typeof globalThis.crypto?.getRandomValues!=="function")globalThis.crypto=Tve;if(!globalThis.fetch)globalThis.fetch=vb,globalThis.Headers=nn,globalThis.Request=Yi,globalThis.Response=Ar;if(!globalThis.WebSocket)globalThis.WebSocket=sE.default;async function Eve(){let e=su(),t=e.privateKey!==null,r=new l$({name:"monaco-mcp-server",version:C_.version});SY(r,{authenticated:t,network:e.network,capability:e.capability,allow:e.allow,deny:e.deny});let o=new p$;await r.connect(o),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).")}Eve().catch((e)=>{console.error("Fatal error:",e),process.exit(1)});