@catena/cli 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -46
- package/dist/index.mjs +48 -41
- package/dist/mpp-C1N0QzFM.mjs +14 -0
- package/dist/{nodecrypto-BSdTIm8T.mjs → nodecrypto-86590WN-.mjs} +1 -1
- package/dist/{utils-CrMT-n--.mjs → utils-CnOz_tNs.mjs} +1 -1
- package/dist/{webcrypto-BeKbrVgs.mjs → webcrypto-CejAJWkk.mjs} +1 -1
- package/package.json +5 -5
- package/dist/mpp-CZl4wkkp.mjs +0 -14
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import{C as e,T as t,_ as n,a as r,c as i,d as a,f as o,h as s,l as c,m as l,o as u,s as d,t as f,u as p,w as m,y as h}from"./dist-w03V0QPF.mjs";import{t as g}from"./hmac-CXnNqvhW.mjs";import{A as _,C as v,D as y,E as ee,O as te,S as ne,T as re,_ as b,a as x,b as ie,c as S,d as ae,f as oe,g as C,h as se,i as ce,j as le,k as ue,l as de,m as fe,n as pe,o as me,p as he,r as ge,s as _e,t as ve,u as ye,v as be,w as xe,x as Se,y as Ce}from"./index.mjs";import{defineCommand as we}from"citty";import*as Te from"valibot";const Ee=`2.56.3`;let De={getDocsUrl:({docsBaseUrl:e,docsPath:t=``,docsSlug:n})=>t?`${e??`https://viem.sh`}${t}${n?`#${n}`:``}`:void 0,version:`viem@${Ee}`};var Oe=class e extends Error{constructor(t,n={}){let r=n.cause instanceof e?n.cause.details:n.cause?.message?n.cause.message:n.details,i=n.cause instanceof e&&n.cause.docsPath||n.docsPath,a=De.getDocsUrl?.({...n,docsPath:i}),o=[t||`An error occurred.`,``,...n.metaMessages?[...n.metaMessages,``]:[],...a?[`Docs: ${a}`]:[],...r?[`Details: ${r}`]:[],...De.version?[`Version: ${De.version}`]:[]].join(`
|
|
2
|
+
`);super(o,n.cause?{cause:n.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=i,this.metaMessages=n.metaMessages,this.name=n.name??this.name,this.shortMessage=t,this.version=Ee}walk(e){return ke(this,e)}};function ke(e,t){return t?.(e)?e:e&&typeof e==`object`&&`cause`in e&&e.cause!==void 0?ke(e.cause,t):t?null:e}function Ae(e,{strict:t=!0}={}){return!e||typeof e!=`string`?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith(`0x`)}function je(e){return Ae(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}var Me=class extends Oe{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:`SizeExceedsPaddingSizeError`})}};function w(e,{dir:t,size:n=32}={}){return typeof e==`string`?Ne(e,{dir:t,size:n}):Pe(e,{dir:t,size:n})}function Ne(e,{dir:t,size:n=32}={}){if(n===null)return e;let r=e.replace(`0x`,``);if(r.length>n*2)throw new Me({size:Math.ceil(r.length/2),targetSize:n,type:`hex`});return`0x${r[t===`right`?`padEnd`:`padStart`](n*2,`0`)}`}function Pe(e,{dir:t,size:n=32}={}){if(n===null)return e;if(e.length>n)throw new Me({size:e.length,targetSize:n,type:`bytes`});let r=new Uint8Array(n);for(let i=0;i<n;i++){let a=t===`right`;r[a?i:n-i-1]=e[a?i:e.length-i-1]}return r}var Fe=class extends Oe{constructor({max:e,min:t,signed:n,size:r,value:i}){super(`Number "${i}" is not in safe ${r?`${r*8}-bit ${n?`signed`:`unsigned`} `:``}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:`IntegerOutOfRangeError`})}},Ie=class extends Oe{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:`SizeOverflowError`})}};function Le(e,{size:t}){if(je(e)>t)throw new Ie({givenSize:je(e),maxSize:t})}const Re=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function ze(e,t={}){return typeof e==`number`||typeof e==`bigint`?He(e,t):typeof e==`string`?We(e,t):typeof e==`boolean`?Be(e,t):Ve(e,t)}function Be(e,t={}){let n=`0x${Number(e)}`;return typeof t.size==`number`?(Le(n,{size:t.size}),w(n,{size:t.size})):n}function Ve(e,t={}){let n=``;for(let t=0;t<e.length;t++)n+=Re[e[t]];let r=`0x${n}`;return typeof t.size==`number`?(Le(r,{size:t.size}),w(r,{dir:`right`,size:t.size})):r}function He(e,t={}){let{signed:n,size:r}=t,i=BigInt(e),a;r?a=n?(1n<<BigInt(r)*8n-1n)-1n:2n**(BigInt(r)*8n)-1n:typeof e==`number`&&(a=BigInt(2**53-1));let o=typeof a==`bigint`&&n?-a-1n:0;if(a&&i>a||i<o){let t=typeof e==`bigint`?`n`:``;throw new Fe({max:a?`${a}${t}`:void 0,min:`${o}${t}`,signed:n,size:r,value:`${e}${t}`})}let s=`0x${(n&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?w(s,{size:r}):s}const Ue=new TextEncoder;function We(e,t={}){return Ve(Ue.encode(e),t)}const Ge=new TextEncoder;function Ke(e,t={}){return typeof e==`number`||typeof e==`bigint`?Xe(e,t):typeof e==`boolean`?qe(e,t):Ae(e)?Ye(e,t):Ze(e,t)}function qe(e,t={}){let n=new Uint8Array(1);return n[0]=Number(e),typeof t.size==`number`?(Le(n,{size:t.size}),w(n,{size:t.size})):n}const T={zero:48,nine:57,A:65,F:70,a:97,f:102};function Je(e){if(e>=T.zero&&e<=T.nine)return e-T.zero;if(e>=T.A&&e<=T.F)return e-(T.A-10);if(e>=T.a&&e<=T.f)return e-(T.a-10)}function Ye(e,t={}){let n=e;t.size&&(Le(n,{size:t.size}),n=w(n,{dir:`right`,size:t.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);let i=r.length/2,a=new Uint8Array(i);for(let e=0,t=0;e<i;e++){let n=Je(r.charCodeAt(t++)),i=Je(r.charCodeAt(t++));if(n===void 0||i===void 0)throw new Oe(`Invalid byte sequence ("${r[t-2]}${r[t-1]}" in "${r}").`);a[e]=n*16+i}return a}function Xe(e,t){return Ye(He(e,t))}function Ze(e,t={}){let n=Ge.encode(e);return typeof t.size==`number`?(Le(n,{size:t.size}),w(n,{dir:`right`,size:t.size})):n}const Qe=BigInt(0),$e=BigInt(1),et=BigInt(2),tt=BigInt(7),nt=BigInt(256),rt=BigInt(113),it=[],at=[],ot=[];for(let e=0,t=$e,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],it.push(2*(5*r+n)),at.push((e+1)*(e+2)/2%64);let i=Qe;for(let e=0;e<7;e++)t=(t<<$e^(t>>tt)*rt)%nt,t&et&&(i^=$e<<($e<<BigInt(e))-$e);ot.push(i)}const st=c(ot,!0),ct=st[0],lt=st[1],ut=(e,t,n)=>n>32?r(e,t,n):d(e,t,n),dt=(e,t,n)=>n>32?u(e,t,n):i(e,t,n);function ft(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let t=0;t<10;t++)r[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){let n=(t+8)%10,i=(t+2)%10,a=r[i],o=r[i+1],s=ut(a,o,1)^r[n],c=dt(a,o,1)^r[n+1];for(let n=0;n<50;n+=10)e[t+n]^=s,e[t+n+1]^=c}let t=e[2],i=e[3];for(let n=0;n<24;n++){let r=at[n],a=ut(t,i,r),o=dt(t,i,r),s=it[n];t=e[s],i=e[s+1],e[s]=a,e[s+1]=o}for(let t=0;t<50;t+=10){for(let n=0;n<10;n++)r[n]=e[t+n];for(let n=0;n<10;n++)e[t+n]^=~r[(n+2)%10]&r[(n+4)%10]}e[0]^=ct[n],e[1]^=lt[n]}n(r)}var pt=class r extends p{constructor(e,n,r,i=!1,a=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=a,l(r),!(0<e&&e<200))throw Error(`only keccak-f1600 function is supported`);this.state=new Uint8Array(200),this.state32=t(this.state)}clone(){return this._cloneInto()}keccak(){e(this.state32),ft(this.state32,this.rounds),e(this.state32),this.posOut=0,this.pos=0}update(e){o(this),e=m(e),a(e);let{blockLen:t,state:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(t-this.pos,r-i);for(let t=0;t<a;t++)n[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,t&128&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){o(this,!1),a(e),this.finish();let t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();let a=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+a),r),this.posOut+=a,r+=a}return e}xofInto(e){if(!this.enableXOF)throw Error(`XOF is not possible for this instance`);return this.writeInto(e)}xof(e){return l(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(s(e,this),this.finished)throw Error(`digest() was already called`);return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,n(this.state)}_cloneInto(e){let{blockLen:t,suffix:n,outputLen:i,rounds:a,enableXOF:o}=this;return e||=new r(t,n,i,o,a),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=a,e.suffix=n,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}};const mt=((e,t,n)=>h(()=>new pt(t,e,n)))(1,136,32);function ht(e,t){let n=t||`hex`,r=mt(Ae(e,{strict:!1})?Ke(e):e);return n===`bytes`?r:ze(r)}var gt=class 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);return super.has(e)&&(super.delete(e),super.set(e,t)),t}set(e,t){if(super.has(e)&&super.delete(e),super.set(e,t),this.maxSize&&this.size>this.maxSize){let e=super.keys().next().value;e!==void 0&&super.delete(e)}return this}};const _t=/^0x[a-fA-F0-9]{40}$/,vt=new gt(8192);function yt(e,t){let{strict:n=!0}=t??{},r=`${e}.${n}`;if(vt.has(r))return vt.get(r);let i=_t.test(e)?e.toLowerCase()===e||!n||xt(e)===e:!1;return vt.set(r,i),i}const bt=new gt(8192);function xt(e,t){if(bt.has(`${e}.${t}`))return bt.get(`${e}.${t}`);let n=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),r=ht(Ze(n),`bytes`),i=(t?n.substring(`${t}0x`.length):n).split(``);for(let e=0;e<40;e+=2)r[e>>1]>>4>=8&&i[e]&&(i[e]=i[e].toUpperCase()),(r[e>>1]&15)>=8&&i[e+1]&&(i[e+1]=i[e+1].toUpperCase());let a=`0x${i.join(``)}`;return bt.set(`${e}.${t}`,a),a}function St(){return`0.1.1`}var E=class e extends Error{static setStaticOptions(t){e.prototype.docsOrigin=t.docsOrigin,e.prototype.showVersion=t.showVersion,e.prototype.version=t.version}constructor(t,n={}){let r=(()=>{if(n.cause instanceof e){if(n.cause.details)return n.cause.details;if(n.cause.shortMessage)return n.cause.shortMessage}return n.cause&&`details`in n.cause&&typeof n.cause.details==`string`?n.cause.details:n.cause?.message?n.cause.message:n.details})(),i=n.cause instanceof e&&n.cause.docsPath||n.docsPath,a=n.docsOrigin??e.prototype.docsOrigin,o=`${a}${i??``}`,s=!!(n.version??e.prototype.showVersion),c=n.version??e.prototype.version,l=[t||`An error occurred.`,...n.metaMessages?[``,...n.metaMessages]:[],...r||i||s?[``,r?`Details: ${r}`:void 0,i?`See: ${o}`:void 0,s?`Version: ${c}`:void 0]:[]].filter(e=>typeof e==`string`).join(`
|
|
3
|
+
`);super(l,n.cause?{cause:n.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=n.cause,this.details=r,this.docs=o,this.docsOrigin=a,this.docsPath=i,this.shortMessage=t,this.showVersion=s,this.version=c}walk(e){return Ct(this,e)}};Object.defineProperty(E,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:`https://oxlib.sh`,showVersion:!1,version:`ox@${St()}`}}),E.setStaticOptions(E.defaultStaticOptions);function Ct(e,t){return t?.(e)?e:e&&typeof e==`object`&&`cause`in e&&e.cause?Ct(e.cause,t):t?null:e}function wt(e,t){if(Wt(e)>t)throw new qt({givenSize:Wt(e),maxSize:t})}const D={zero:48,nine:57,A:65,F:70,a:97,f:102};function Tt(e){if(e>=D.zero&&e<=D.nine)return e-D.zero;if(e>=D.A&&e<=D.F)return e-(D.A-10);if(e>=D.a&&e<=D.f)return e-(D.a-10)}function Et(e,t={}){let{dir:n,size:r=32}=t;if(r===0)return e;if(e.length>r)throw new Jt({size:e.length,targetSize:r,type:`Bytes`});let i=new Uint8Array(r);for(let t=0;t<r;t++){let a=n===`right`;i[a?t:r-t-1]=e[a?t:e.length-t-1]}return i}function Dt(e,t={}){let{dir:n=`left`}=t,r=e,i=0;for(let e=0;e<r.length-1&&r[n===`left`?e:r.length-e-1].toString()===`0`;e++)i++;return r=n===`left`?r.slice(i):r.slice(0,r.length-i),r}function Ot(e,t){if(Pt(e)>t)throw new Ft({givenSize:Pt(e),maxSize:t})}function kt(e,t={}){let{dir:n,size:r=32}=t;if(r===0)return e;let i=e.replace(`0x`,``);if(i.length>r*2)throw new It({size:Math.ceil(i.length/2),targetSize:r,type:`Hex`});return`0x${i[n===`right`?`padEnd`:`padStart`](r*2,`0`)}`}function At(e){if(e===null||typeof e==`boolean`||typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`){if(!Number.isFinite(e))throw TypeError(`Cannot canonicalize non-finite number`);return Object.is(e,-0)?`0`:JSON.stringify(e)}if(typeof e==`bigint`)throw TypeError(`Cannot canonicalize bigint`);if(Array.isArray(e))return`[${e.map(e=>At(e)).join(`,`)}]`;if(typeof e==`object`)return`{${Object.keys(e).sort().reduce((t,n)=>{let r=e[n];return r!==void 0&&t.push(`${JSON.stringify(n)}:${At(r)}`),t},[]).join(`,`)}}`}const jt=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Mt(e,t={}){let n=``;for(let t=0;t<e.length;t++)n+=jt[e[t]];let r=`0x${n}`;return typeof t.size==`number`?(Ot(r,t.size),Nt(r,t.size)):r}function Nt(e,t){return kt(e,{dir:`right`,size:t})}function Pt(e){return Math.ceil((e.length-2)/2)}var Ft=class extends E{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`Hex.SizeOverflowError`})}},It=class extends E{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`Hex.SizeExceedsPaddingSizeError`})}};const Lt=new TextDecoder,Rt=new TextEncoder;function zt(e){return e instanceof Uint8Array?e:typeof e==`string`?Vt(e):Bt(e)}function Bt(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Vt(e,t={}){let{size:n}=t,r=e;n&&(Ot(e,n),r=Nt(e,n));let i=r.slice(2);i.length%2&&(i=`0${i}`);let a=i.length/2,o=new Uint8Array(a);for(let e=0,t=0;e<a;e++){let n=Tt(i.charCodeAt(t++)),r=Tt(i.charCodeAt(t++));if(n===void 0||r===void 0)throw new E(`Invalid byte sequence ("${i[t-2]}${i[t-1]}" in "${i}").`);o[e]=n<<4|r}return o}function Ht(e,t={}){let{size:n}=t,r=Rt.encode(e);return typeof n==`number`?(wt(r,n),Ut(r,n)):r}function Ut(e,t){return Et(e,{dir:`right`,size:t})}function Wt(e){return e.length}function Gt(e,t={}){let{size:n}=t,r=e;return n!==void 0&&(wt(r,n),r=Kt(r)),Lt.decode(r)}function Kt(e){return Dt(e,{dir:`right`})}var qt=class extends E{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`Bytes.SizeOverflowError`})}},Jt=class extends E{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`Bytes.SizeExceedsPaddingSizeError`})}};function Yt(e,t,n={}){let{as:r=typeof t==`string`?`Hex`:`Bytes`}=n,i=g(f,zt(e),zt(t));return r===`Bytes`?i:Mt(i)}const Xt=new TextEncoder,Zt=new TextDecoder,Qt=Object.fromEntries(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[t,e.charCodeAt(0)])),$t={...Object.fromEntries(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[e.charCodeAt(0),t])),61:0,45:62,95:63};function en(e,t={}){let{pad:n=!0,url:r=!1}=t,i=new Uint8Array(Math.ceil(e.length/3)*4);for(let t=0,n=0;n<e.length;t+=4,n+=3){let r=(e[n]<<16)+(e[n+1]<<8)+(e[n+2]|0);i[t]=Qt[r>>18],i[t+1]=Qt[r>>12&63],i[t+2]=Qt[r>>6&63],i[t+3]=Qt[r&63]}let a=e.length%3,o=Math.floor(e.length/3)*4+(a&&a+1),s=Zt.decode(new Uint8Array(i.buffer,0,o));return n&&a===1&&(s+=`==`),n&&a===2&&(s+=`=`),r&&(s=s.replaceAll(`+`,`-`).replaceAll(`/`,`_`)),s}function tn(e,t={}){return en(Ht(e),t)}function nn(e){let t=e.replace(/=+$/,``),n=t.length,r=new Uint8Array(n+3);Xt.encodeInto(t+`===`,r);for(let e=0,n=0;e<t.length;e+=4,n+=3){let t=($t[r[e]]<<18)+($t[r[e+1]]<<12)+($t[r[e+2]]<<6)+$t[r[e+3]];r[n]=t>>16,r[n+1]=t>>8&255,r[n+2]=t&255}let i=(n>>2)*3+(n%4&&n%4-1);return new Uint8Array(r.buffer,0,i)}function rn(e){return Gt(nn(e))}const O={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},an={payment:`Payment`};function on(e){let t=rn(e);return JSON.parse(t)}function k(e){return tn(At(e),{pad:!1,url:!0})}function sn(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function cn(e,t){return typeof t==`bigint`?t.toString():t}function ln(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function un(e){return e==null}function dn(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function fn(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}const pn=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function mn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hn(e){if(mn(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return mn(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}const gn=new Set([`string`,`number`,`symbol`]);function _n(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function vn(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function A(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}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function yn(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}function bn(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function xn(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function j(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Sn(e){return typeof e==`string`?e:e?.message}function Cn(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function M(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:Sn(e.inst?._zod.def?.error?.(e))??Sn(a?.(e))??Sn(t?.error?.(e))??Sn(n.customError?.(e))??Sn(n.localeError?.(e))??`Invalid input`,{inst:s,schema:c,continue:l,input:u,...d}=e;return d.path??=[],d.message=o,t?.reportInput&&(d.input=u),d}const wn=/[\uD800-\uDBFF]/;function Tn(e){let t=e.length;if(!wn.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function En(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Dn(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function On(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):jn(e,n,r.value)}}function kn(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function An(e,t,n){return kn(e,t,n,!1)}function jn(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:kn(this,t,n.bind(this))},set(e){kn(this,t,e)}})}function Mn(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let Nn,N=!1;const Pn={configurable:!0,get(){N=!0}};function P(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&Nn!==e._zod){Nn=void 0;return}Nn=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Pn);let e=N;N=!1;try{let r=n(this);return N?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),N||=e,r}catch(n){throw delete this[t],N||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})}function Fn(e,t,n,r){let i=Mn(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}var In;const Ln={value:void 0,enumerable:!1};let Rn=`captureStackTrace`in Error?Error:null;function zn(e){let t=Rn;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return Rn=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function F(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(!n._zod){Ln.value=new a(r);try{Object.defineProperty(n,"_zod",Ln)}finally{Ln.value=void 0}}if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),On(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?zn(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var Bn=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}};(In=globalThis).__zod_globalConfig??(In.__zod_globalConfig={});const Vn=globalThis.__zod_globalConfig;function I(e){return e&&Object.assign(Vn,e),Vn}function Hn(){let e=this._zod;return e.message??=JSON.stringify(e.def,cn,2),e.message}function Un(e){this._zod.message=e}const Wn={get:Hn,set:Un,enumerable:!0,configurable:!0},Gn={value:void 0,enumerable:!1},Kn={value:void 0,enumerable:!1},qn=new WeakSet([Object.prototype,Error.prototype]),Jn=(e,t)=>{e.name=`$ZodError`,Gn.value=e._zod,Object.defineProperty(e,"_zod",Gn),Kn.value=t,Object.defineProperty(e,"issues",Kn),Gn.value=void 0,Kn.value=void 0,Object.defineProperty(e,"message",Wn);let n=Object.getPrototypeOf(e);qn.has(n)||(qn.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},Yn=F(`$ZodError`,Jn),Xn=F(`$ZodError`,Jn,void 0,{Parent:Error}),Zn=(e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Bn;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>M(e,o,I())));throw pn(n,a?.callee??t),n}return s.value};return t})(Xn),Qn=(e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>M(e,o,I())));throw pn(n,a?.callee??t),n}return s.value};return t})(Xn),$n=(e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Bn;return a.issues.length?{success:!1,error:new(e??Yn)(a.issues.map(e=>M(e,i,I())))}:{success:!0,data:a.value}})(Xn),er=(e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>M(e,i,I())))}:{success:!0,data:a.value}})(Xn),tr=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},nr=/^-?\d+(?:\.\d+)?$/,rr=/^(?:true|false)$/i,ir=F(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ar=e=>{let t=e.value;return!un(t)&&t.length!==void 0},or=F(`$ZodCheckMinLength`,(e,t)=>{var n;ir.init(e,t),(n=e._zod.def).when??(n.when=ar),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?Tn(r):i)>=t.minimum)return;let a=En(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),sr=F(`$ZodCheckStringFormat`,(e,t)=>{var n,r;ir.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&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})}):(r=e._zod).check??(r.check=()=>{})}),cr=F(`$ZodCheckRegex`,(e,t)=>{sr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),lr={major:4,minor:5,patch:4},L=F(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=lr;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=bn(t),a;for(let o of n){if(o._zod.def.when){if(xn(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new Bn;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(Cn(t.issues,n,e),i||=bn(t,n))});else{if(t.issues.length===n)continue;Cn(t.issues,n,e),i||=bn(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(bn(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new Bn;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new Bn;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return An(this,`~standard`,dr(this))},set"~standard"(e){kn(this,`~standard`,e)}}),ur=e=>e.success?{value:e.data}:{issues:e.error?.issues};function dr(e){return{validate:t=>{try{return ur($n(e,t))}catch{return er(e,t).then(ur)}},vendor:`zod`,version:1}}const fr=F(`$ZodString`,(e,t)=>{L.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??tr(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),pr=F(`$ZodNumber`,(e,t)=>{L.init(e,t),e._zod.pattern=e._zod.bag.pattern??nr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),mr=F(`$ZodBoolean`,(e,t)=>{L.init(e,t),e._zod.pattern=rr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),hr=F(`$ZodUnknown`,(e,t)=>{L.init(e,t),e._zod.parse=e=>e}),gr=F(`$ZodNever`,(e,t)=>{L.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function _r(e,t,n){e.issues.length&&t.issues.push(...j(n,e.issues)),t.value[n]=e.value}const vr=F(`$ZodArray`,(e,t)=>{L.init(e,t);let n=Vn.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[];for(let e=0;e<a.length;e++){let n=a[e],s=t.element._zod.run({value:n,issues:[]},i);s instanceof Promise?o.push(s.then(t=>_r(t,r,e))):_r(s,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function yr(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...j(n,e.issues))}if(!o&&i===void 0){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}}const br=[];function xr(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:br,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=yn(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function Sr(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin,d=c.optout;for(let i in t){if(s.has(i))continue;if(i===`__proto__`){l===`never`&&o.push(i);continue}if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>yr(e,n,i,t,u,d))):yr(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const Cr=new WeakMap,wr=F(`$ZodObject`,(e,t)=>{if(L.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Cr.set(t,e),Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),Cr.set(t,n),n}})}let n=ln(()=>xr(t));P(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||fn(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let r=mn,i=t.catchall,a,o=Vn.memoizer;o?.attach(e),e._zod.parse=(t,s)=>{a??=n.value;let c=t.value;if(!r(c))return t.issues.push({expected:`object`,code:`invalid_type`,input:c,inst:e}),t;t.value=o?o.alloc(e,t,{},s):{};let l=[],u=a.shape;for(let e of a.allKeys){if(e===`__proto__`)continue;let n=u[e],r=n._zod.optin,i=n._zod.optout,a=n._zod.run({value:c[e],issues:[]},s);a instanceof Promise?l.push(a.then(n=>yr(n,t,e,c,r,i))):yr(a,t,e,c,r,i)}return i?Sr(l,c,t,s,n.value,e):l.length?Promise.all(l).then(()=>t):t}});function Tr(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!bn(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>M(e,r,I())))}),t)}const Er=F(`$ZodUnion`,(e,t)=>{L.init(e,t),P(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),P(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),P(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),P(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>dn(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Tr(t,r,e,i)):Tr(o,r,e,i)}}),Dr=F(`$ZodRecord`,(e,t)=>{L.init(e,t);let n=Vn.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!hn(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>M(e,i,I())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...j(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...j(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&nr.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>M(e,i,I())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...j(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...j(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),Or=F(`$ZodEnum`,(e,t)=>{L.init(e,t);let n=sn(t.entries),r=new Set(n);e._zod.values=r;let i=n.filter(e=>gn.has(typeof e));e._zod.pattern=RegExp(i.length?`^(${i.map(e=>_n(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),kr=F(`$ZodLiteral`,(e,t)=>{L.init(e,t);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(t.values.length?`^(${t.values.map(e=>typeof e==`string`?_n(e):e?_n(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}});function Ar(e,t){return e.value=t.issues.length?void 0:t.value,e}const jr=F(`$ZodOptional`,(e,t)=>{L.init(e,t),P(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,P(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),P(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${dn(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>Ar(e,t)):Ar(e,r)}return t.innerType._zod.run(e,n)}}),Mr=F(`$ZodCustom`,(e,t)=>{ir.init(e,t),L.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Nr(t,n,r,e));Nr(i,n,r,e)}});function Nr(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Dn(e))}}function Pr(e,t){return new e({type:`string`,...A(t)})}function Fr(e,t){return new e({type:`number`,checks:[],...A(t)})}function Ir(e,t){return new e({type:`boolean`,...A(t)})}function Lr(e){return new e({type:`unknown`})}function Rr(e,t){return new e({type:`never`,...A(t)})}function zr(e,t){return new or({check:`min_length`,...A(t),minimum:e})}function R(e,t){return new cr({check:`string_format`,format:`regex`,...A(t),pattern:e})}function Br(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...A(n)})}const z=F(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);L.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){kn(this,`with`,e)},parse(e,t){return Zn(this,e,t,{callee:this.parse})},parseAsync(e,t){return Qn(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return $n(this,e,t)},safeParseAsync(e,t){return er(this,e,t)},check(...e){let t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0})},clone(e,t){return vn(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return t.length===0?e(this):e(this,...t)}}),Vr=F(`ZodMiniString`,(e,t)=>{fr.init(e,t),z.init(e,t)});function B(e){return Pr(Vr,e)}const Hr=F(`ZodMiniNumber`,(e,t)=>{pr.init(e,t),z.init(e,t)});function Ur(e){return Fr(Hr,e)}const Wr=F(`ZodMiniBoolean`,(e,t)=>{mr.init(e,t),z.init(e,t)});function Gr(e){return Ir(Wr,e)}const Kr=F(`ZodMiniUnknown`,(e,t)=>{hr.init(e,t),z.init(e,t)});function V(){return Lr(Kr)}const qr=F(`ZodMiniNever`,(e,t)=>{gr.init(e,t),z.init(e,t)});function Jr(e){return Rr(qr,e)}const Yr=F(`ZodMiniArray`,(e,t)=>{vr.init(e,t),z.init(e,t)});function Xr(e,t){return new Yr({type:`array`,element:e,...A(t)})}const Zr=F(`ZodMiniObject`,(e,t)=>{wr.init(e,t),z.init(e,t),Fn(e,`shape`,e=>e._zod.def.shape,!1)});function H(e,t){let n={type:`object`,shape:e??{},...A(t)};return new Zr(n)}function Qr(e,t){return new Zr({type:`object`,shape:e,catchall:V(),...A(t)})}const $r=F(`ZodMiniUnion`,(e,t)=>{Er.init(e,t),z.init(e,t)});function ei(e,t){return new $r({type:`union`,options:e,...A(t)})}const ti=F(`ZodMiniRecord`,(e,t)=>{Dr.init(e,t),z.init(e,t)});function U(e,t,n){return!t||!t._zod?new ti({type:`record`,keyType:B(),valueType:e,...A(t)}):new ti({type:`record`,keyType:e,valueType:t,...A(n)})}const ni=F(`ZodMiniEnum`,(e,t)=>{Or.init(e,t),z.init(e,t),e.options=Object.values(t.entries)});function ri(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ni({type:`enum`,entries:n,...A(t)})}const ii=F(`ZodMiniLiteral`,(e,t)=>{kr.init(e,t),z.init(e,t)});function W(e,t){return new ii({type:`literal`,values:Array.isArray(e)?e:[e],...A(t)})}const ai=F(`ZodMiniOptional`,(e,t)=>{jr.init(e,t),z.init(e,t)});function G(e){return new ai({type:`optional`,innerType:e})}const oi=F(`ZodMiniCustom`,(e,t)=>{Mr.init(e,t),z.init(e,t)});function si(e,t={}){return Br(oi,e,t)}function ci(){return B().check(R(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function li(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function ui(){return B().check(R(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function di(){return B().check(R(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function fi(){return B().check(R(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}const pi=H({description:G(B()),digest:G(B().check(R(/^sha-256=/,`Invalid digest format`))),expires:G(ci()),header:G(B().check(R(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:B().check(zr(1)),intent:B(),method:B(),meta:G(U(B(),B())),opaque:G(B()),realm:B(),request:U(B(),V())});function mi(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=Oi(o)?void 0:o,f=e.expires?li(e.expires):void 0,p=e.opaque??(i===void 0?void 0:k(i)),m=u?ki({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return pi.parse({id:m,realm:c,method:a,intent:s,request:l,...n&&{description:n},...r&&{digest:r},...f&&{expires:f},...d!==void 0&&{header:d},...i!==void 0&&{meta:i},...p!==void 0&&{opaque:p}})}function hi(e){let t=[K(`id`,e.id),K(`realm`,e.realm),K(`method`,e.method),K(`intent`,e.intent),K(`request`,k(e.request))];e.description!==void 0&&t.push(K(`description`,e.description)),e.digest!==void 0&&t.push(K(`digest`,e.digest)),e.expires!==void 0&&t.push(K(`expires`,e.expires));let n=e.header;return n!==void 0&&!Oi(n)&&t.push(K(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(K(`opaque`,k(e.meta))):t.push(K(`opaque`,e.opaque)),`${an.payment} ${t.join(`, `)}`}function K(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function gi(e,t){let n=_i(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=vi(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>16384)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return mi({...a,request:on(r),...i&&{opaque:i}},t)}function _i(e){let t=an.payment,[n]=Si(e,t);if(n===void 0)return null;let r=n+t.length;for(;r<e.length&&/\s/.test(e[r]??``);)r++;return e.slice(r)}function vi(e){let t=Object.create(null),n=0;for(;n<e.length;){for(;n<e.length&&/[\s,]/.test(e[n]??``);)n++;if(n>=e.length)break;let r=n;for(;n<e.length&&/[A-Za-z0-9_-]/.test(e[n]??``);)n++;let i=e.slice(r,n).toLowerCase();if(!i)throw Error(`Malformed auth-param.`);for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]!==`=`)break;for(n++;n<e.length&&/\s/.test(e[n]??``);)n++;let[a,o]=yi(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function yi(e,t){if(e[t]===`"`)return bi(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function bi(e,t){let n=t,r=!1,i=t,a;for(;n<e.length;){let o=e[n];if(n++,r){a??=[];let t=o===`u`?e.slice(n,n+4):void 0;t&&/^[0-9A-Fa-f]{4}$/.test(t)?(a.push(String.fromCharCode(Number.parseInt(t,16))),n+=4):a.push(o),i=n,r=!1;continue}if(o===`\\`){a??=[],a.push(e.slice(i,n-1)),i=n,r=!0;continue}if(o===`"`)return[a?[...a,e.slice(i,n-1)].join(``):e.slice(t,n-1),n]}throw Error(`Unterminated quoted-string.`)}function xi(e,t,n){if(e.slice(t,t+n.length).toLowerCase()!==n.toLowerCase())return!1;let r=e[t+n.length];return!!(r&&/\s/.test(r))}function Si(e,t){let n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(!xi(e,a,t))continue;let s=a-1;for(;s>=0&&/\s/.test(e[s]??``);)s--;s>=0&&e[s]!==`,`||n.push(a)}return n}function Ci(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return wi(e.headers,t)}function wi(e,t){let n=e.get(O.wwwAuthenticate);if(!n)throw Error(`Missing ${O.wwwAuthenticate} header.`);return Ti(n,t)}function Ti(e,t){let n=Si(e,an.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return gi(e.slice(r,a).replace(/,\s*$/,``),t)})}function Ei(e){let t=[e.realm,e.method,e.intent,k(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!Oi(n)&&t.push(n),t.push(e.opaque??(e.meta?k(e.meta):``)),t.join(`|`)}function Di(e){return e.header??O.authorization}function Oi(e){return e?.toLowerCase()===O.authorization.toLowerCase()}function ki(e,t){let n=Ei(e);return en(Yt(Ht(t.secretKey),Ht(n),{as:`Bytes`}),{url:!0,pad:!1})}var Ai=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},ji=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function Mi(e){let t=e.match(RegExp(`^${an.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new Ai;try{let e=rn(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=Ni(r);return{challenge:pi.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:on(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new ji}}function Ni(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!Pi(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:k(e)}}function Pi(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}var Fi=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...e&&{challengeId:e}}}},Ii=class extends Fi{name=`InvalidChallengeError`;title=`Invalid Challenge`;status=402;type=`https://paymentauth.org/problems/invalid-challenge`;constructor(e={}){let{id:t,reason:n}=e,r=t?` "${t}"`:``,i=n?`: ${n}`:``;super(`Challenge${r} is invalid${i}.`)}},Li=class extends Fi{name=`PaymentExpiredError`;title=`Payment Expired`;type=`https://paymentauth.org/problems/payment-expired`;constructor(e={}){let{expires:t}=e;super(t?`Payment expired at ${t}.`:`Payment has expired.`)}};function Ri(e,t){if(!e)throw new Ii({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new Ii({...t&&{id:t},reason:`malformed expires timestamp`});if(new Date(e)<new Date)throw new Li({expires:e})}function zi(e){return e}function Bi(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}const Vi=Qr({method:B(),reference:B(),externalId:G(B()),subscriptionId:G(B()),status:W(`success`),timestamp:ci()});function Hi(e){let t=rn(e);return Ui(JSON.parse(t))}function Ui(e){return Vi.parse(e)}function Wi(e){let t=e.headers.get(O.paymentReceipt);if(!t)throw Error(`Missing ${O.paymentReceipt} header.`);return Hi(t)}function Gi(e){return{encode(t){return tn(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(rn(t)))}catch{throw new Ki}}}}var Ki=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const qi=[`exact`],Ji=`PAYMENT-REQUIRED`,Yi=`PAYMENT-SIGNATURE`,Xi=B().check(zr(1)),Zi=Ur().check(si(e=>e>0,`Must be positive`)),q=B().check(R(/^\d+$/,`Invalid atomic amount`)),J=ui(),Qi=B().check(R(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),$i=H({description:G(B()),iconUrl:G(B()),mimeType:G(B()),serviceName:G(B()),tags:G(Xr(B())),url:Xi}),ea=H({amount:q,asset:Xi,extra:G(U(B(),V())),maxTimeoutSeconds:Zi,network:Qi,payTo:Xi,scheme:ri(qi)}),ta=U(B(),H({info:U(B(),V()),schema:U(B(),V())})),na=H({accepts:Xr(ea).check(zr(1)),error:G(B()),extensions:G(ta),resource:$i,x402Version:W(2)}),ra=ei([H({authorization:H({from:J,nonce:di(),to:J,validAfter:q,validBefore:q,value:q}),signature:fi()}),H({permit2Authorization:H({deadline:q,from:J,nonce:q,permitted:H({amount:q,token:J}),spender:J,witness:H({to:J,validAfter:q})}),signature:fi()})]),ia=H({accepted:ea,extensions:G(ta),payload:ra,resource:G($i),x402Version:W(2)}),aa=H({amount:G(q),errorMessage:G(B()),errorReason:G(B()),extensions:G(ta),extra:G(U(B(),V())),network:Xi,payer:G(B()),success:Gr(),transaction:B()}),oa=Gi(na),sa=Gi(ia),ca=Gi(aa);oa.encode,oa.decode;function la(e){try{let t=JSON.parse(rn(e));return ua(t)}catch{throw new Ki}}sa.encode,sa.decode,ca.encode,ca.decode;const ua=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Ki;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Ki;let n=$i.parse(t.resource),r=t.extensions===void 0?void 0:ta.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}},da=Symbol.for(`mppx.x402.challenge`);function fa(e){return Object.defineProperty(e,da,{value:!0}),e}function pa(e){return!!e?.[da]}function ma(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=ya(n)}return t}function ha(e,t){let n=ma(e),r=Ea(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[ya(e)]??1,index:t}));return{definition:r,entries:i,header:_a(i),keys:n}}function ga(e){let t=e.split(/\s*,\s*/).map(e=>e.trim()).filter(Boolean);if(t.length===0)throw Error(`Accept-Payment header is empty.`);return t.map((e,t)=>wa(e,t))}function _a(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${Aa(n)}`}).join(`, `)}function va(e,t,n){let r=new Map;for(let e of t){let t=ya(e),n=r.get(t);n?n.push(e):r.set(t,[e])}return e.flatMap((e,t)=>{let i=r.get(ya(e));if(!i)return[];let a=ba(e,n);return!a||a.q<=0?[]:i.filter(t=>t.canHandleChallenge?.({challenge:e})??!0).map(n=>({challenge:e,index:t,match:a,method:n}))}).sort((e,t)=>Ca(e.challenge)-Ca(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function ya(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function ba(e,t){let n;for(let r of t){if(!xa(e,r))continue;let t={...r,specificity:Sa(r)};(!n||t.specificity>n.specificity||t.specificity===n.specificity&&t.q>n.q||t.specificity===n.specificity&&t.q===n.q&&t.index<n.index)&&(n=t)}return n}function xa(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function Sa(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function Ca(e){return+!!pa(e)}function wa(e,t){let n=/^(?<method>[^/;\s]+|\*)\s*\/\s*(?<intent>[^/;\s]+|\*)(?<params>(?:\s*;\s*.+)?)$/u.exec(e),r=n?.groups?.method,i=n?.groups?.intent;if(!r||!i)throw Error(`Invalid Accept-Payment entry: ${e}`);ja(r,`method`),ja(i,`intent`);let a=1;for(let t of Ta(n.groups?.params)){if(!t)continue;let n=/^(?<name>[A-Za-z0-9_-]+)\s*=\s*(?<value>\S+)$/u.exec(t),r=n?.groups?.name,i=n?.groups?.value;if(!r||!i)throw Error(`Invalid Accept-Payment parameter: ${t}`);r===`q`&&(a=Oa(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function Ta(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function Ea(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>ya(e))),a={};for(let[e,t]of Object.entries(r??{})){if(!i.has(e))throw Error(`Unknown payment preference "${e}". Available: ${[...i].join(`, `)}`);a[e]=Da(t,`payment preference "${e}"`)}return a}function Da(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return ka(e,t)}function Oa(e,t){if(!/^0(?:\.\d{0,3})?$|^1(?:\.0{0,3})?$/.test(e))throw Error(`Invalid q-value for ${t}. Expected an HTTP qvalue.`);return ka(Number(e),t)}function ka(e,t){if(e<0||e>1)throw Error(`Invalid q-value for ${t}. Expected a value between 0 and 1.`);let n=Math.round(e*1e3);if(Math.abs(e*1e3-n)>1e-9)throw Error(`Invalid q-value for ${t}. Expected at most 3 decimal places.`);return n/1e3}function Aa(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function ja(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}var Ma=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Na(e){}function Pa(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Na,onError:n=Na,onRetry:r=Na,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(`
|
|
4
|
+
`)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new Ma(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function g(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(`
|
|
5
|
+
`,n);for(;r!==-1;){if(n===r){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0,n=r+1,r=e.indexOf(`
|
|
6
|
+
`,n);continue}let i=e.charCodeAt(n);if(Fa(e,n,i)){let i=e.charCodeAt(n+5)===32?n+6:n+5,a=e.slice(i,r);if(d===0&&e.charCodeAt(r+1)===10){t({id:l,event:f,data:a}),l=void 0,u=``,f=void 0,n=r+2,r=e.indexOf(`
|
|
7
|
+
`,n);continue}u=d===0?a:`${u}
|
|
8
|
+
${a}`,d++}else Ia(e,n,i)?f=e.slice(e.charCodeAt(n+6)===32?n+7:n+6,r)||void 0:_(e,n,r);n=r+1,r=e.indexOf(`
|
|
9
|
+
`,n)}return e.slice(n)}for(;n<e.length;){let t=e.indexOf(`\r`,n),r=e.indexOf(`
|
|
10
|
+
`,n),i=-1;if(t!==-1&&r!==-1?i=t<r?t:r:t===-1?r!==-1&&(i=r):i=t===e.length-1?-1:t,i===-1)break;_(e,n,i),n=i+1,e.charCodeAt(n-1)===13&&e.charCodeAt(n)===10&&n++}return e.slice(n)}function _(e,t,n){if(t===n){y();return}let r=e.charCodeAt(t);if(Fa(e,t,r)){let r=e.charCodeAt(t+5)===32?t+6:t+5,i=e.slice(r,n);u=d===0?i:`${u}
|
|
11
|
+
${i}`,d++;return}if(Ia(e,t,r)){f=e.slice(e.charCodeAt(t+6)===32?t+7:t+6,n)||void 0;return}if(r===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let r=e.slice(e.charCodeAt(t+3)===32?t+4:t+3,n);r.includes(`\0`)||(l=r);return}if(r===58){if(i){let r=e.slice(t,n);i(r.slice(e.charCodeAt(t+1)===32?2:1))}return}let a=e.slice(t,n),o=a.indexOf(`:`);if(o===-1){v(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===32?2:1;v(s,a.slice(o+c),a)}function v(e,t,i){switch(e){case`event`:f=t||void 0;break;case`data`:u=d===0?t:`${u}
|
|
12
|
+
${t}`,d++;break;case`id`:t.includes(`\0`)||(l=t);break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Ma(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Ma(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}))}}function y(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function ee(e={}){if(e.consume&&o.length>0){let e=o.join(``);_(e,0,e.length)}c=!0,l=void 0,u=``,d=0,f=void 0,o.length=0,s=0,p=!1}return{feed:m,reset:ee}}function Fa(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Ia(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}const La=[O.authorization,Ji,`PAYMENT-RESPONSE`,Yi];function Ra(e,t,n){let r=new Headers(e.headers);for(let e of La)(e!==O.authorization||r.get(e)?.startsWith(`Payment `))&&r.delete(e);return r.set(t,n),{...e,headers:r}}function za(e){if(typeof e==`string`)try{let t=JSON.parse(e),n=t?.id;return t?.jsonrpc!==`2.0`||typeof t?.method!=`string`?void 0:typeof n==`string`||typeof n==`number`?n:void 0}catch{return}}const Ba=new WeakMap;function Va(e){let t=za(e?.body);if(t===void 0)return;let n=new Headers(e?.headers);if(n.has(`mcp-method`))return t;let r=n.get(`accept`)?.toLowerCase()??``;return r.includes(`application/json`)&&r.includes(`text/event-stream`)?t:void 0}function Ha(e){if(!e||typeof e!=`object`)return;let t=e,n=t.id;if(t.jsonrpc!==`2.0`||n!==void 0&&typeof n!=`string`&&typeof n!=`number`)return;let r=`error`in t;if(r!==`result`in t)return r?Number.isInteger(t.error?.code)&&typeof t.error?.message==`string`?e:void 0:n!==void 0&&typeof t.result==`object`?e:void 0}function Ua(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){let t=pi.safeParse(e);if(!t.success)return;n.push(t.data)}let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function Wa(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:Ua(e.error.data):Ua(e.result?._meta?.[`org.paymentauth/payment-required`])}function Ga(e,t){return!e||e.id!==t?[]:Wa(e)?.challenges??[]}async function Ka(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=!1,i,a=Pa({onEvent(e){if(!r&&e.data&&(r=!0,!(e.event&&e.event!==`message`)))try{i=Ha(JSON.parse(e.data))}catch{}}});try{for(;;){if(r)return i;let{done:e,value:o}=await t.read();if(e)return a.feed(n.decode()),a.reset({consume:!0}),i;a.feed(n.decode(o,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}function qa(e){let t=Ba.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(t.includes(`application/json`))return e.clone().json().then(Ha).catch(()=>void 0);if(t.includes(`text/event-stream`))return Ka(e)})();return Ba.set(e,n),n}function Ja(){return{getChallenges(e,t){let n=Va(t);return e.status===402||n===void 0?[]:qa(e).then(e=>Ga(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=Mi(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function Ya(){return{getChallenges(e){return e.status!==402||!e.headers.has(O.wwwAuthenticate)?[]:Ci(e)},setCredential(e,t,n){return Ra(e,n?.challenge?Di(n.challenge):O.authorization,t)}}}function Xa(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(Ji);if(!t)return[];let n=la(t);if(e.url&&n.resource.url!==e.url)throw Error(`x402 payment-required resource does not match response URL.`);return n.accepts.flatMap((e,t)=>{let r=ea.safeParse(e);if(!r.success)return[];let i=r.data;return fa(mi({id:`x402:${t}`,intent:`charge`,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return Ra(e,Yi,t)}}}function Za(e){return e}function Qa(){let e=[Ya(),Xa(),Ja()],t=new WeakMap,n=(e,n)=>{for(let r of n)t.set(r,e);return n},r=(t,r)=>{let i=(a,o)=>{for(let s=a;s<e.length;s++){let a=e[s],c=a.getChallenges(t,r);if(c instanceof Promise)return c.then(e=>i(s+1,[...o,...n(a,e)]));o.push(...n(a,c))}return o};return i(0,[])};return Za({name:`http`,isPaymentRequired(e,t){if(e.status===402)return!0;let n=r(e,t);return n instanceof Promise?n.then(e=>e.length>0):n.length>0},getChallenges(e,t){return r(e,t)},setCredential(n,r,i){let a=i?.challenge?t.get(i.challenge):void 0,o=e[0];if(!a&&!o)throw Error(`No protocol to attach the credential.`);return(a??o).setCredential(n,r,i)}})}const $a=new WeakMap;function eo(e){return $a.has(e)}function to(e,t){return Promise.resolve($a.get(e)?.(t))}const no=new WeakMap,ro=new WeakMap;function io(e,t,n){no.has(e)&&ro.set(t,n)}function ao(e,t){return Promise.resolve(no.get(e)?.(t)??t.response)}const oo=Symbol.for(`mppx.fetch.wrapper`);let so;const co=new WeakMap;async function Y(e,t){let n=e?.attempt.settle;if(!n)return t.status!==`pending`;e.attempt.settle=void 0;let r=await n(t);return r||(e.attempt.settle=n),r}function lo(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=Qa()}=e,l=e.eventDispatcher??fo(),u=t??ha(a),d=Mo(r),f=async(e,t,r)=>{let p=jo(e,t?.headers),m=p.has(O.acceptPayment),h=Lo(p,u),g=ko(e,t,p),_=Oo(e,t,p,h.header,m,n),v=await d(No(_.input),_.init),y=Ao(_.init,await g);if(!await c.isPaymentRequired(v,y))return v;let ee=t?.context,{context:te,orderChallenges:ne,...re}=y??{},b,x,ie,S;try{for(let n=0;n<i;n++){x=await c.getChallenges(v,y);let i=(await Ro(va(x,a,h.entries),ne??s))[0];if(!i){if(await Y(S,{challenges:x,response:v,status:`rejected`}),n>0)return v;throw Error(`No method found for challenges: ${x.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let u=i.challenge;b=u,ie=i.method,b.expires&&Ri(b.expires,b.id);let p=Uo(v,_.input,_.input),m=S,g=hi(u),te=m?.method===i.method&&m?.key===g,ae=!1;if(m){let e=await Y(m,{challenges:x,response:v,status:te?`pending`:`rejected`});ae=te&&!e}S=ae?m:void 0;let oe=_o(async e=>{if(e===void 0&&ae&&m)return m.promise;ae&&m&&(await Y(m,{status:`rejected`}),S=void 0);let t=e??ee;if(!eo(i.method))return Io(u,i.method,t);let n={prepare:()=>to(i.method,{challenge:u,context:t,fetch:d,input:p})},r=n.prepare().then(()=>Io(u,i.method,t,n));return S={attempt:n,key:e===void 0?g:void 0,method:i.method,promise:r},r}),C=await l.emit(`challenge.received`,vo({challenge:u,challenges:x,createCredential:oe,init:t,input:e,method:i.method,response:v}))??(o?await o(b,{createCredential:oe}):void 0)??await oe(),se=S;se&&await se.promise.catch(()=>void 0)!==C&&(await Y(se,{status:`rejected`}),S=void 0),Fo(C),await l.emit(`credential.created`,yo({challenge:u,credential:C,init:t,input:e,method:i.method,response:v})),v=await d(p,c.setCredential({...re,headers:_.headers},C,{challenge:u}));let ce=await c.isPaymentRequired(v,y);if(ce||(await Y(se,{response:v,status:v.ok?`accepted`:`rejected`}),S=void 0),v.ok&&po(l,`payment.response`)&&await l.emit(`payment.response`,bo({challenge:u,credential:C,init:t,input:e,method:i.method,response:v})),!ce)return v.ok?ao(i.method,{challenge:u,credential:C,fetch:d,headers:_.headers,input:p,...r?{refetch:()=>f(No(_.input),t,!1)}:{},response:v,signal:Po(e,t)}):v}x=void 0;try{x=await c.getChallenges(v,y)}catch{}return await Y(S,{challenges:x,response:v,status:`rejected`}),v}catch(n){throw await Y(S,{challenges:x,response:v,status:`rejected`}),await l.emit(`payment.failed`,xo({challenge:b,challenges:x,error:n,init:t,input:e,method:ie,response:v})),n}},p=(e,t)=>f(e,t,!0);return p[oo]=d,p}function uo(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);so||=globalThis.fetch,globalThis.fetch=lo({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??(Vo()?`same-origin`:`always`),fetch:globalThis.fetch})}function fo(){let e={"*":new Set,"challenge.received":new Set,"credential.created":new Set,"payment.failed":new Set,"payment.response":new Set},t={async emit(t,n){switch(t){case`challenge.received`:{let r;for(let t of e[`challenge.received`]){let e=await mo(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await go(e[`*`],t,n),r}case`credential.created`:await ho(e[`credential.created`],n),await go(e[`*`],t,n);return;case`payment.failed`:await ho(e[`payment.failed`],n),await go(e[`*`],t,n);return;case`payment.response`:await ho(e[`payment.response`],n),await go(e[`*`],t,n);return}},on:(t,n)=>{switch(t){case`*`:case`challenge.received`:case`credential.created`:case`payment.failed`:case`payment.response`:return e[t].add(n),()=>e[t].delete(n);default:throw Error(`Unknown client event "${String(t)}".`)}}};return co.set(t,t=>e[t].size>0||e[`*`].size>0),t}function po(e,t){return co.get(e)?.(t)??!0}async function mo(e,t){try{return await e(t)}catch{return}}async function ho(e,t){for(let n of e)try{await n(t)}catch{}}async function go(e,t,n){await ho(e,Object.freeze({name:t,payload:n}))}function _o(e){let t;return n=>(t??=e(n),t)}function vo(e){return Object.freeze({challenge:X(e.challenge),challenges:e.challenges.map(e=>X(e)),createCredential:e.createCredential,init:So(e.init),input:Co(e.input),method:wo(e.method),response:To(e.response)})}function yo(e){return Object.freeze({challenge:X(e.challenge),credential:e.credential,init:So(e.init),input:Co(e.input),method:wo(e.method),...e.response===void 0?{}:{response:To(e.response)}})}function bo(e){return Object.freeze({challenge:X(e.challenge),credential:e.credential,init:So(e.init),input:Co(e.input),method:wo(e.method),response:To(e.response)})}function xo(e){return Object.freeze({...e.challenge?{challenge:X(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>X(e))}:{},error:e.error,init:So(e.init),input:Co(e.input),...e.method?{method:wo(e.method)}:{},...e.response===void 0?{}:{response:To(e.response)}})}function So(e){if(e)return Do({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function Co(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function wo(e){return Do(Object.assign({},e))}function To(e){return e instanceof Response?e.clone():X(e)}function X(e){try{return Eo(structuredClone(e))}catch{return Do(e)}}function Eo(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Eo(t);return e}function Do(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function Oo(e,t,n,r,i,a){let o=!!r&&!i&&zo(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(O.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function ko(e,t,n){if(e instanceof Request&&t?.body===void 0&&e.body&&!e.bodyUsed){if(!n.has(`mcp-method`)){let e=n.get(`accept`)?.toLowerCase()??``;if(!e.includes(`application/json`)||!e.includes(`text/event-stream`))return}try{return e.clone().text().catch(()=>void 0)}catch{return}}}function Ao(e,t){return t===void 0?e:{...e,body:t}}function jo(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function Mo(e){let t=e;for(;t[oo];)t=t[oo];return t}function No(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Po(e,t){return t?.signal??(e instanceof Request?e.signal:void 0)}function Fo(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
|
|
13
|
+
`))throw Error(`Credential header value contains illegal newline characters`)}async function Io(e,t,n,r){let i=t.context&&n!==void 0?t.context.parse(n):void 0,a=i===void 0?{challenge:e}:{challenge:e,context:i};return r&&io(t,a,r),t.createCredential(a)}function Lo(e,t){let n=e.get(O.acceptPayment);if(!n)return t;try{return{...t,entries:ga(n),header:n}}catch{return t}}async function Ro(e,t){return t?t(e):e}function zo(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=Ho(e);return t===`same-origin`?!Vo()||n.origin===globalThis.location.origin:t.origins.some(e=>Bo(n,e))}function Bo(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e.hostname.endsWith(n)||e.hostname===t.slice(2)}return e.origin===new URL(t).origin}function Vo(){return globalThis.location!==void 0}function Ho(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,Vo()?globalThis.location.href:void 0)}function Uo(e,t,n){if(!e.url)return t;let r=new URL(e.url),i=Ho(n);if(r.origin!==i.origin)throw Error(`Refusing to send payment credential across redirect from ${i.origin} to ${r.origin}`);return e.url}function Wo(){let e=new Uint8Array(64);return crypto.getRandomValues(e),Object.freeze({created:Math.floor(Date.now()/1e3),nonce:en(e,{pad:!1,url:!0})})}function Go(...e){return{protocol:`composed`,async sign(t,n=Wo()){for(let r of e)t=await r.sign(t,n);return t}}}function Ko(e,t){return async(n,r)=>e(await t.sign(new Request(n,r)))}function qo(e){let{attestation:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=Qa()}=e,c=e.fetch??globalThis.fetch,l=t?Jo(c,t):c,u=e.methods.flat(),d=ha(u,e.paymentPreferences),f=fo(),p=r,m={acceptPayment:d,acceptPaymentPolicy:o,...(e.fetch||t)&&{fetch:l},eventDispatcher:f,...n!==void 0&&{maxPaymentRetries:n},...p&&{onChallenge:p},...i&&{orderChallenges:i},methods:u,transport:s},h=lo(m);a&&uo(m);function g(e){return f.on(`challenge.received`,e)}function _(e){return f.on(`credential.created`,e)}function v(e){return f.on(`payment.failed`,e)}function y(e){return f.on(`payment.response`,e)}async function ee(e,t){let n=es(e),r=await s.getChallenges(e,t?.request),a=Object.freeze(r.map(e=>Z(e))),o=rs(d.entries,t?.acceptPayment),c,l;try{let e=(await is(va(r,u,o),t?.orderChallenges??i))[0];if(!e)throw Error(`No method found for challenges: ${r.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${u.map(e=>`${e.name}.${e.intent}`).join(`, `)}`);let d=e.challenge;c=a[e.index],l=e.method,c.expires&&Ri(c.expires,c.id);let p=c,m=l,h=Yo(async e=>{try{p.expires&&Ri(p.expires,p.id);let t=Yo(t=>as(p,m,t??e)),i=await f.emit(`challenge.received`,Xo({challenge:p,challenges:r,createCredential:t,method:m,response:n}))??await t();return Fo(i),await f.emit(`credential.created`,Zo({challenge:p,credential:i,method:m,response:n})),i}catch(e){throw await f.emit(`payment.failed`,Qo({challenge:p,challenges:r,error:e,method:m,response:n})),e}});return Object.freeze({challenge:p,challenges:a,createCredential:h,method:$o(m),setCredential(e,t){return Fo(t),s.setCredential(e,t,{challenge:d})}})}catch(e){throw await f.emit(`payment.failed`,Qo({challenge:c,challenges:r,error:e,method:l,response:n})),e}}return{fetch:h,rawFetch:c,methods:u,transport:s,on:f.on,onChallengeReceived:g,onCredentialCreated:_,onPaymentFailed:v,onPaymentResponse:y,preparePayment:ee,async createCredential(e,t,n){return(await ee(e,n)).createCredential(t)}}}function Jo(e,t){let n=Object.values(t);if(n.length===0)throw TypeError(`Mppx client attestation must configure at least one signer.`);return Ko(e,Go(...n))}function Yo(e){let t;return n=>(t??=e(n),t)}function Xo(e){return Object.freeze({challenge:Z(e.challenge),challenges:e.challenges.map(e=>Z(e)),createCredential:e.createCredential,method:$o(e.method),response:es(e.response)})}function Zo(e){return Object.freeze({challenge:Z(e.challenge),credential:e.credential,method:$o(e.method),response:es(e.response)})}function Qo(e){return Object.freeze({...e.challenge?{challenge:Z(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>Z(e))}:{},error:e.error,...e.method?{method:$o(e.method)}:{},response:es(e.response)})}function $o(e){return ns(Object.assign({},e))}function es(e){if(e instanceof Response)try{return e.clone()}catch{return new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText})}return Z(e)}function Z(e){try{let t=structuredClone(e);if(e&&t&&typeof e==`object`&&typeof t==`object`)for(let n of Object.getOwnPropertySymbols(e)){let r=Object.getOwnPropertyDescriptor(e,n);r&&Object.defineProperty(t,n,r)}return ts(t)}catch{return ns(e)}}function ts(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))ts(t);return e}function ns(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function rs(e,t){return t?typeof t==`string`?ga(t):t:e}async function is(e,t){return t?t(e):e}async function as(e,t,n){let r=t.context&&n!==void 0?t.context.parse(n):void 0;return t.createCredential(r===void 0?{challenge:e}:{challenge:e,context:r})}const os=2048;var Q=class extends Error{name=`MppResourceUrlError`};function ss(e){if(e.length>os)throw new Q(`MPP resource URL is too long`);if(Array.from(e).some(e=>{let t=e.charCodeAt(0);return e===`\\`||t<=32||t===127}))throw new Q(`MPP resource URL is invalid`);let t=e.match(/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)(\?[^#]*)?(?:#.*)?$/);if(!t)throw new Q(`MPP resource URL must be absolute`);let n;try{n=new URL(e)}catch{throw new Q(`MPP resource URL is invalid`)}if(n.username||n.password)throw new Q(`MPP resource URL must not contain credentials`);let r=n.protocol.toLowerCase();if(r!==`https:`&&!(r===`http:`&&cs(n.hostname)))throw new Q(`MPP resource URL must use HTTPS or loopback HTTP`);let i=t[3]||`/`,a=t[4]||``,o=`${r}//${n.hostname.toLowerCase()}${n.port?`:${n.port}`:``}${i}${a}`;if(o.length>os)throw new Q(`MPP resource URL is too long`);return o}function cs(e){let t=e.toLowerCase();if(t===`localhost`||t===`[::1]`)return!0;let n=t.split(`.`);return n.length===4&&n[0]===`127`&&n.every(e=>/^\d{1,3}$/.test(e)&&Number(e)<=255)}const ls=/^[A-Za-z0-9_-]+$/,us=/^0x[0-9a-fA-F]{40}$/,ds=/^(?:0|[1-9]\d*)$/,fs=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/,ps=/^sha-256=:([A-Za-z0-9+/]{43}=):$/,ms=/^sha-256=([A-Za-z0-9+/]{43}=)$/,hs=new Set([`mpp_challenge_not_payable`,`mpp_network_mismatch`,`mpp_counterparty_rail_not_found`]),gs=`mpp_counterparty_rail_not_found`,_s=`mpp_network_mismatch`,vs=H({type:W(`authorization`),from:B(),to:B(),value:B(),validAfter:B(),validBefore:B(),nonce:B(),signature:B()}),ys={amount:B(),currency:B(),description:G(B()),externalId:G(B()),recipient:B()},bs=H({...ys,methodDetails:H({chainId:Ur(),credentialTypes:Xr(W(`authorization`)),decimals:W(6),permit2Address:G(B()),splits:G(Jr())})}),xs=H({...ys,methodDetails:H({type:W(`evm`),evm:H({chainId:Ur(),credentialTypes:G(Xr(W(`authorization`))),decimals:W(6),permit2Address:G(B()),splits:G(Jr())})})}),Ss=zi({name:`evm`,intent:`charge`,schema:{credential:{payload:vs},request:bs}}),Cs=zi({name:`usdc`,intent:`charge`,schema:{credential:{payload:vs},request:xs}});var ws=class extends Error{intentId;status;reasons;expiresAt;constructor(e,t){super(e),this.name=`MppPaymentError`,this.intentId=t.intentId,this.status=t.status,this.reasons=t.reasons,this.expiresAt=t.expiresAt}},$=class extends Error{intentId;reasons;constructor(e,t={}){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.name=`MppFetchPaymentError`,this.intentId=t.intentId,this.reasons=t.reasons??[]}},Ts=class extends ${accountId;requiredNetworks;constructor(e,t,n){super(`Account ${e} cannot pay on the MPP challenge's required network${t.length===1?``:`s`}: ${t.join(`, `)}`,{reasons:n}),this.name=`MppNetworkMismatchError`,this.accountId=e,this.requiredNetworks=t}},Es=class extends ${recipient;network;requiredRail;constructor(e,t,n,r){super(`No saved Catena counterparty rail can pay ${e} on ${t}`,{reasons:n}),this.name=`MppCounterpartyNotFoundError`,this.recipient=e,this.network=t,this.requiredRail=r}},Ds=class extends ${expiresAt;constructor(e,t,n){super(`The MPP payment is awaiting human approval (intent ${e}); retry the request after approval`,{intentId:e,reasons:t}),this.name=`MppApprovalPendingError`,this.expiresAt=n}},Os=class extends ${status;constructor(e,t,n){super(`Catena ${t} the MPP payment (intent ${e})`,{intentId:e,reasons:n}),this.name=`MppPaymentDeclinedError`,this.status=t}},ks=class extends ${method;atomicAmount;network;recipient;resourceUrl;constructor(e,t,n,r){super(`The MPP payment could not be confirmed (intent ${e}); reconcile it with getIntent("${e}") before paying again`,{intentId:e,cause:r}),this.name=`MppSubmitInterruptedError`,this.method=t.method,this.atomicAmount=t.atomicAmount,this.network=t.network,this.recipient=t.recipient,this.resourceUrl=n}},As=class extends ${receipt;constructor(e,t){super(`The MPP payment completed (intent ${e.intentId}) but the post-payment continuation failed; inspect getIntent("${e.intentId}") before retrying manually`,{intentId:e.intentId,cause:t}),this.name=`MppRetryFailedError`,this.receipt=e}};function js(e){let t=async({challenge:t})=>(await Hs(e,Vs(t,e.maxAtomicAmount))).credential;return[Bi(Ss,{canHandleChallenge:({challenge:t})=>Us(`evm`,t,e.maxAtomicAmount)!==void 0,createCredential:t}),Bi(Cs,{canHandleChallenge:({challenge:t})=>Us(`usdc`,t,e.maxAtomicAmount)!==void 0,createCredential:t})]}const Ms=Object.assign(e=>js(e),{charge:js});function Ns(e,t){let n=(t.baseFetch??globalThis.fetch).bind(globalThis),r={client:e,accountId:t.accountId,...t.maxAtomicAmount!==void 0&&{maxAtomicAmount:t.maxAtomicAmount}},i=qo({methods:Ms(r),fetch:n,polyfill:!1});return async(a,o)=>{let s=await n(a,o);if(s.status!==402||!s.headers.has(`WWW-Authenticate`))return s;let c;try{c=await i.transport.getChallenges(s,o)}catch{return s}if(c.length===0)return s;if(!C(a,o))throw new $(`The request body cannot be replayed after MPP payment; buffer it as a string, URLSearchParams, Blob, ArrayBuffer, or typed array`);let l=Ls(a,s),{payment:u,prepared:d}=await Ps(i,s,c,o,r,l),f={intentId:u.intentId,...u.terms,resourceUrl:l};await zs(f,async()=>{await t.onPayment?.(f)});let p=se(a,o),m=d.setCredential({...o,headers:p},u.credential),h=await zs(f,()=>n(a,m));if(h.status===402)throw new As(f,Error(`The paid MPP retry still requires payment`));return Bs(e,f.intentId,h),h}}async function Ps(e,t,n,r,i,a){let o,s=[];for(let c=0;c<5;c+=1){let l={missing:!1},u;try{u=await e.preparePayment(t,{request:r,orderChallenges:e=>{o??=e.slice(0,5).map(e=>e.index);let t=o[c],n=e.find(e=>e.index===t);return l.missing=n===void 0,n===void 0?[]:[n]}})}catch(e){let t=o??[];if(t.length===0)throw n.some(e=>Ws(e,i.maxAtomicAmount))?new $(`Every supported charge in the MPP challenge costs more than the caller's maximum amount`,{cause:e}):new $(`The MPP challenge offers no Catena-supported native USDC charge`,{cause:e});if(l.missing&&s.length>0){if(c+1<t.length)continue;break}throw new $(`The selected MPP challenge could not be prepared`,{cause:e})}let d=Vs(u.challenge,i.maxAtomicAmount);try{return{payment:await Hs(i,d,a),prepared:u}}catch(e){if(e instanceof ue&&e.code!==void 0&&hs.has(e.code))s.push({error:e,terms:d.terms});else throw Fs(e,d.terms,a)}if(c+1>=(o?.length??0))break}throw Is(i.accountId,s)}function Fs(e,t,n){if(e instanceof _&&e.outcome===`unknown`)return new ks(e.intentId,t,n,e);if(!(e instanceof ws))return e;switch(e.status){case`pending`:return new Ds(e.intentId,e.reasons,e.expiresAt);case`blocked`:case`failed`:return new Os(e.intentId,e.status,e.reasons);case`processing`:case`completed`:return new $(e.message,{intentId:e.intentId,reasons:e.reasons,cause:e})}return be(e.status)}function Is(e,t){let n=t.filter(e=>e.error.code===gs),r=t.filter(e=>e.error.code===_s),i=t.filter(e=>e.error.code!==gs&&e.error.code!==_s),a=[...new Set([...n,...r,...i].map(e=>e.error.message))],o=n.find(e=>e.error.status===404);return o?new Es(o.terms.recipient,o.terms.network,a,b(o.error.details,o.terms.recipient)):r.length>0&&n.length===0?new Ts(e,[...new Set(r.map(e=>e.terms.network))],a):new $(`No supported candidate in the MPP challenge is payable from this account`,{reasons:a})}function Ls(e,t){let n;try{n=typeof e==`string`?Rs(e):e instanceof URL?e:new URL(e.url)}catch(e){throw new $(`The MPP resource request URL must be absolute`,{cause:e})}let r;try{r=new URL(t.url||n.href)}catch(e){throw new $(`The final MPP resource URL is invalid`,{cause:e})}if(r.origin!==n.origin)throw new $(`Refusing to pay after a cross-origin redirect from ${n.origin} to ${r.origin}`);try{return ss(t.url||n.href)}catch(e){throw new $(`The final MPP resource URL cannot be bound to a payment intent`,{cause:e})}}function Rs(e){try{return new URL(e)}catch{return new URL(e,globalThis.location.href)}}async function zs(e,t){try{return await t()}catch(t){throw new As(e,t)}}function Bs(e,t,n){try{let r=Wi(n);if(!he.test(r.reference))return;fe(e,t,r.reference)}catch{return}}function Vs(e,t){let n=e.method;if(n!==`evm`&&n!==`usdc`)throw Error(`Unsupported Catena MPP challenge ${e.method}/${e.intent}`);let r=Us(n,e,t);if(r===void 0)throw Error(`Catena MPP charge challenge failed validation`);return{challenge:{id:e.id,realm:e.realm,method:n,intent:`charge`,request:r.request,...e.description!==void 0&&{description:e.description},...e.digest!==void 0&&{digest:e.digest},expires:r.expires,...r.header!==void 0&&{header:r.header},...e.opaque!==void 0&&{opaque:e.opaque}},terms:r.terms}}async function Hs(e,t,n){let r=await e.client.submitIntent({action:{type:`mpp`,accountId:e.accountId,challenge:t.challenge,...n!==void 0&&{resource:{url:n}}}});return{...t,credential:nc(r,t.challenge),intentId:r.id}}function Us(e,t,n){if(t.method!==e||t.intent!==`charge`)return;let r=Zs(t);if(r===void 0)return;let i=e===`evm`?qs(t.request,n):Js(t.request,n);return i===void 0?void 0:{...r,terms:i}}function Ws(e,t){if(t===void 0||e.method!==`evm`&&e.method!==`usdc`)return!1;let n=Us(e.method,e,void 0);return n!==void 0&&BigInt(n.terms.atomicAmount)>t}function Gs(e,t){return ec(e.amount)&&(t===void 0||BigInt(e.amount)<=t)&&tc(e.currency)&&tc(e.recipient)&&(e.description===void 0||Ks(e.description,1024))&&(e.externalId===void 0||Ks(e.externalId,256))}function Ks(e,t){if(e.length>t)return!1;for(let t of e){let e=t.codePointAt(0);if(e!==void 0&&e>=55296&&e<=57343)return!1}return!0}function qs(e,t){let n=bs.safeParse(e);if(!n.success||!Gs(n.data,t))return;let{amount:r,methodDetails:i,recipient:a}=n.data,o=Xs(i.chainId);return Ys(i)&&i.credentialTypes.length===1&&o!==void 0?{method:`evm`,atomicAmount:r,network:o,recipient:a}:void 0}function Js(e,t){let n=xs.safeParse(e);if(!n.success||!Gs(n.data,t))return;let{amount:r,methodDetails:i,recipient:a}=n.data,o=i.evm,s=Xs(o.chainId);return Ys(o)&&(o.credentialTypes===void 0||o.credentialTypes.length===1)&&s!==void 0?{method:`usdc`,atomicAmount:r,network:s,recipient:a}:void 0}function Ys(e){return Number.isSafeInteger(e.chainId)&&e.chainId>=1&&(e.permit2Address===void 0||tc(e.permit2Address))}function Xs(e){return Number.isSafeInteger(e)&&e>=1?`eip155:${e}`:void 0}function Zs(e){if(!Qs(e))return;let t=Date.parse(e.expires),n=t-Date.now();if(!Number.isFinite(t)||n<5e3||n>36e5)return;let r=k(e.request),i=new TextEncoder().encode(JSON.stringify({...e,request:r})).byteLength;return r.length>0&&r.length<=16384&&i<=32768?{request:r,expires:e.expires,header:e.header}:void 0}function Qs(e){return!(e.id.length<1||e.id.length>256||e.realm.length<1||e.realm.length>256||e.expires===void 0||!fs.test(e.expires)||e.description!==void 0&&e.description.length>1024||e.header!==void 0&&e.header!==`Payment-Authorization`||e.opaque!==void 0&&(e.opaque.length>8192||!ls.test(e.opaque))||e.digest!==void 0&&!$s(e.digest))}function $s(e){if(e.length>128)return!1;let t=ps.exec(e)??ms.exec(e);if(!t)return!1;try{let e=atob(t[1]);return e.length===32&&btoa(e)===t[1]}catch{return!1}}function ec(e){return e.length<=78&&ds.test(e)&&BigInt(e)>0n}function tc(e){return us.test(e)&&yt(e)}function nc(e,t){switch(e.status){case`completed`:{let n=le(e.data,`mpp`);if(n===void 0)throw ac(`Catena MPP payment ${e.id} completed without an MPP credential`,e);if(!rc(n,t))throw ac(`Catena MPP payment ${e.id} completed with a credential that does not match the selected challenge; reconcile with client.getIntent("${e.id}") before another payment attempt`,e);return n}case`pending`:throw ac(`Catena MPP payment ${e.id} is pending${oc(e.reasons)}`,e);case`processing`:throw ac(`Catena MPP payment ${e.id} is processing; if it was approved, re-run the paid request so a fresh challenge can consume the grant (polling never advances an approved payment); otherwise poll client.getIntent("${e.id}"), because an executing payment completes on its own`,e);case`blocked`:throw ac(`Catena MPP payment ${e.id} was blocked${oc(e.reasons)}`,e);case`failed`:throw ac(`Catena MPP payment ${e.id} failed${oc(e.reasons)}`,e)}return be(e.status)}function rc(e,t){if(e.trim().length===0||e.includes(`\r`)||e.includes(`
|
|
14
|
+
`))return!1;let n;try{n=Mi(e)}catch{return!1}let r=n.challenge;if(r.id!==t.id||r.realm!==t.realm||r.method!==t.method||r.intent!==t.intent||r.description!==t.description||r.digest!==t.digest||r.expires!==t.expires||r.header!==t.header||r.opaque!==t.opaque||k(r.request)!==t.request)return!1;let i=vs.safeParse(n.payload),a=t.method===`evm`?bs.safeParse(r.request):xs.safeParse(r.request);if(!i.success||!a.success)return!1;let o=a.data.recipient;return tc(i.data.from)&&tc(i.data.to)&&i.data.to.toLowerCase()===o.toLowerCase()&&i.data.value===a.data.amount&&ic(i.data.validAfter)&&ic(i.data.validBefore)&&BigInt(i.data.validBefore)>BigInt(i.data.validAfter)&&/^0x[0-9a-fA-F]{64}$/.test(i.data.nonce)&&/^0x[0-9a-fA-F]{130}$/.test(i.data.signature)}function ic(e){return e.length<=78&&ds.test(e)}function ac(e,t){return new ws(e,{intentId:t.id,status:t.status,reasons:t.reasons,expiresAt:t.expiresAt})}function oc(e){return e.length>0?`: ${e.join(`; `)}`:``}function sc(e){return{intentId:e.intentId,method:e.method,amountAtomicUsdc:e.atomicAmount,recipient:e.recipient,network:e.network}}const cc=/(?:^|,)\s*Payment(?![!#$%&'*+\-.^_`|~0-9A-Za-z])/i;function lc(e,t){me(e,`payment-authorization`)&&y(`--header cannot set Payment-Authorization; the payment loop attaches it after paying`),e.some(e=>e.name.toLowerCase()===`authorization`&&cc.test(e.value))&&y(`--header cannot provide the Payment authentication scheme in Authorization; the payment loop attaches it after paying`),ge(e,t)}const uc=xe({url:v({description:`The paywalled URL to fetch (an MPP endpoint)`,required:!0,schema:Te.pipe(Te.string(),Te.url())}),account:v({description:`Source wallet account id the payment draws from`,required:!0,schema:ie}),maxAmount:v({description:`Refuse challenges above this USD amount (decimal string, e.g. 0.25). Policy limits still apply server-side.`,schema:Te.pipe(Te.string(),Te.regex(/^\d+(\.\d{1,6})?$/))}),method:Se({description:`HTTP method for the request`,choices:[`GET`,`POST`]}),data:v({description:`Request body. Use @path to read a file or @- for stdin. Implies POST and a JSON content type unless overridden.`}),contentType:v({description:`Content-Type header for the request body (default application/json when --data is set)`}),output:v({description:`Write the full response body to this file (must be a regular file; written for any HTTP status — check .status). Without it .body is capped at 4000 characters; longer or non-UTF-8 bodies are saved to a file (path reported in .bodyPath)`}),header:ne({description:`Request header as "Name: Value" (repeatable, like curl -H); sent on both requests, except caller Authorization is replaced on the paid retry when MPP uses that field for its credential`,schema:S}),profile:ee,json:re}),dc=we({meta:{name:`mpp`,description:`Fetch a URL, paying its MPP challenge via USDC`},args:uc.args,async run({args:e,rawArgs:t}){let n=uc.parse(e,t),r=n.method??(n.data===void 0?`GET`:`POST`);n.data!==void 0&&r!==`POST`&&y(`--data cannot be sent with --method ${r}; a body requires POST`),n.contentType!==void 0&&n.data===void 0&&y(`--content-type has no effect without --data`),lc(n.header,n.contentType);let i=n.output===void 0?void 0:pe(n.output),a=n.data===void 0?void 0:ae(n.data),o=ce(n.header,n.contentType,a);await Ce(n)(async e=>{let t,s=Ns(e,{accountId:n.account,...n.maxAmount!==void 0&&{maxAtomicAmount:oe(n.maxAmount)},onPayment:e=>{t=e}}),c;try{c=await s(n.url,{method:r,...a!==void 0&&{body:a},...o!==void 0&&{headers:o}})}catch(e){if(e instanceof ks&&e.intentId!==void 0)throw Error(ye(e.intentId,n.profile),{cause:e});if(e instanceof As)return{status:null,paid:!0,retryFailed:!0,payment:sc(e.receipt),error:e.message};if(e instanceof Ts){let t=e.requiredNetworks.map(e=>_e(e)??e);return{status:null,paid:!1,retryFailed:!1,networkMismatch:{account:e.accountId,requiredNetworks:t,requiredNetworkIds:[...e.requiredNetworks]},error:`${e.message}. Re-run with --account set to a wallet account on ${t.join(` or `)} (your account ids are in \`catena accounts list${de(n.profile)}\`).`}}if(e instanceof Es){let t=e.requiredRail?.network??_e(e.network)??e.network,r=x(e.recipient,t,void 0,n.profile);return{status:null,paid:!1,retryFailed:!1,counterpartyNotFound:{recipient:e.recipient,network:t,networkId:e.network,...e.requiredRail!==void 0&&{requiredRail:e.requiredRail},createCommand:r,nameIsPlaceholder:!0},error:`${e.message}. Add it, then re-run:\n ${r}\n(counterparty creation may require approval per your policy)`}}if(e instanceof Ds)return{status:null,paid:!1,retryFailed:!1,approvalPending:{intentId:e.intentId,expiresAt:e.expiresAt,reasons:[...e.reasons]},error:e.message};throw e}let l={status:c.status,paid:t!==void 0,retryFailed:!1,...t!==void 0&&{payment:sc(t)}},u;try{u=Buffer.from(await c.arrayBuffer())}catch(e){let r=t===void 0?``:`; the payment completed — inspect it with \`catena intents get ${t.intentId}${de(n.profile)}\` before any manual retry`;return{...l,error:`failed to read the response body: ${te(e)}${r}`}}return{...l,...ve(u,t?.intentId,i)}},{exitCode:e=>+(`error`in e)})}});export{dc as mppCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./utils-
|
|
1
|
+
import{t as e}from"./utils-CnOz_tNs.mjs";import*as t from"crypto";const n=async n=>{let{content:r,publicKey:i,privateKey:a}=n,o=t.createPrivateKey({key:e({uncompressedPrivateKeyHex:a,compressedPublicKeyHex:i}),format:`jwk`}),s=t.createSign(`SHA256`);return s.write(Buffer.from(r)),s.end(),s.sign(o,`hex`)};export{n as signWithApiKey};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{D as e}from"./dist-w03V0QPF.mjs";import{
|
|
1
|
+
import{D as e}from"./dist-w03V0QPF.mjs";import{M as t}from"./index.mjs";
|
|
2
2
|
/**
|
|
3
3
|
* Code modified from https://github.com/google/tink/blob/6f74b99a2bfe6677e3670799116a57268fd067fa/javascript/subtle/bytes.ts
|
|
4
4
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{O as e}from"./dist-w03V0QPF.mjs";import{t}from"./utils-
|
|
1
|
+
import{O as e}from"./dist-w03V0QPF.mjs";import{t}from"./utils-CnOz_tNs.mjs";const n=async e=>{let{content:t,publicKey:n,privateKey:a}=e;return await i({key:await r({uncompressedPrivateKeyHex:a,compressedPublicKeyHex:n}),content:t})};async function r(e){let{uncompressedPrivateKeyHex:n,compressedPublicKeyHex:r}=e,i=t({uncompressedPrivateKeyHex:n,compressedPublicKeyHex:r});return await crypto.subtle.importKey(`jwk`,i,{name:`ECDSA`,namedCurve:`P-256`},!1,[`sign`])}async function i(t){let{key:n,content:r}=t,i=await crypto.subtle.sign({name:`ECDSA`,hash:`SHA-256`},n,new TextEncoder().encode(r)),o=a(new Uint8Array(i));return e(o)}function a(e){if(e.length%2!=0||e.length==0||e.length>132)throw Error(`Invalid IEEE P1363 signature encoding. Length: `+e.length);let t=o(e.subarray(0,e.length/2)),n=o(e.subarray(e.length/2,e.length)),r=0,i=2+t.length+1+1+n.length,a;return i>=128?(a=new Uint8Array(i+3),a[r++]=48,a[r++]=129,a[r++]=i):(a=new Uint8Array(i+2),a[r++]=48,a[r++]=i),a[r++]=2,a[r++]=t.length,a.set(t,r),r+=t.length,a[r++]=2,a[r++]=n.length,a.set(n,r),a}function o(e){let t=0;for(;t<e.length&&e[t]==0;)t++;t==e.length&&(t=e.length-1);let n=0;(e[t]&128)==128&&(n=1);let r=new Uint8Array(e.length-t+n);return r.set(e.subarray(t),n),r}export{n as signWithApiKey};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@catena/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "Catena CLI for agent runtimes",
|
|
5
5
|
"homepage": "https://catena.com/",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -23,15 +23,15 @@
|
|
|
23
23
|
"valibot": "1.4.2"
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
|
+
"@bank/money": "0.1.0",
|
|
27
|
+
"@bank/shared": "0.1.0",
|
|
28
|
+
"@catena/sdk": "0.2.0",
|
|
26
29
|
"@types/semver": "7.8.0",
|
|
27
30
|
"mppx": "0.9.2",
|
|
28
31
|
"publint": "0.3.24",
|
|
29
32
|
"tsdown": "0.23.0",
|
|
30
33
|
"tsx": "4.23.13",
|
|
31
|
-
"viem": "2.56.3"
|
|
32
|
-
"@bank/money": "0.1.0",
|
|
33
|
-
"@bank/shared": "0.1.0",
|
|
34
|
-
"@catena/sdk": "0.1.0"
|
|
34
|
+
"viem": "2.56.3"
|
|
35
35
|
},
|
|
36
36
|
"engines": {
|
|
37
37
|
"node": ">=20"
|
package/dist/mpp-CZl4wkkp.mjs
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import{C as e,T as t,_ as n,a as r,c as i,d as a,f as o,h as s,l as c,m as l,o as u,s as d,t as f,u as p,w as m,y as h}from"./dist-w03V0QPF.mjs";import{t as g}from"./hmac-CXnNqvhW.mjs";import{A as _,C as v,D as y,E as b,O as ee,S as x,T as te,_ as S,a as C,b as ne,c as w,d as re,f as ie,g as T,h as ae,i as oe,k as se,l as ce,m as le,n as ue,o as de,p as fe,r as pe,s as me,t as he,u as ge,v as _e,w as ve,x as ye,y as be}from"./index.mjs";import{defineCommand as xe}from"citty";import*as Se from"valibot";const Ce=`2.56.3`;let we={getDocsUrl:({docsBaseUrl:e,docsPath:t=``,docsSlug:n})=>t?`${e??`https://viem.sh`}${t}${n?`#${n}`:``}`:void 0,version:`viem@${Ce}`};var Te=class e extends Error{constructor(t,n={}){let r=n.cause instanceof e?n.cause.details:n.cause?.message?n.cause.message:n.details,i=n.cause instanceof e&&n.cause.docsPath||n.docsPath,a=we.getDocsUrl?.({...n,docsPath:i}),o=[t||`An error occurred.`,``,...n.metaMessages?[...n.metaMessages,``]:[],...a?[`Docs: ${a}`]:[],...r?[`Details: ${r}`]:[],...we.version?[`Version: ${we.version}`]:[]].join(`
|
|
2
|
-
`);super(o,n.cause?{cause:n.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=i,this.metaMessages=n.metaMessages,this.name=n.name??this.name,this.shortMessage=t,this.version=Ce}walk(e){return Ee(this,e)}};function Ee(e,t){return t?.(e)?e:e&&typeof e==`object`&&`cause`in e&&e.cause!==void 0?Ee(e.cause,t):t?null:e}function De(e,{strict:t=!0}={}){return!e||typeof e!=`string`?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith(`0x`)}function Oe(e){return De(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}var ke=class extends Te{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:`SizeExceedsPaddingSizeError`})}};function Ae(e,{dir:t,size:n=32}={}){return typeof e==`string`?je(e,{dir:t,size:n}):Me(e,{dir:t,size:n})}function je(e,{dir:t,size:n=32}={}){if(n===null)return e;let r=e.replace(`0x`,``);if(r.length>n*2)throw new ke({size:Math.ceil(r.length/2),targetSize:n,type:`hex`});return`0x${r[t===`right`?`padEnd`:`padStart`](n*2,`0`)}`}function Me(e,{dir:t,size:n=32}={}){if(n===null)return e;if(e.length>n)throw new ke({size:e.length,targetSize:n,type:`bytes`});let r=new Uint8Array(n);for(let i=0;i<n;i++){let a=t===`right`;r[a?i:n-i-1]=e[a?i:e.length-i-1]}return r}var Ne=class extends Te{constructor({max:e,min:t,signed:n,size:r,value:i}){super(`Number "${i}" is not in safe ${r?`${r*8}-bit ${n?`signed`:`unsigned`} `:``}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:`IntegerOutOfRangeError`})}},Pe=class extends Te{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:`SizeOverflowError`})}};function Fe(e,{size:t}){if(Oe(e)>t)throw new Pe({givenSize:Oe(e),maxSize:t})}const Ie=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Le(e,t={}){return typeof e==`number`||typeof e==`bigint`?Be(e,t):typeof e==`string`?He(e,t):typeof e==`boolean`?Re(e,t):ze(e,t)}function Re(e,t={}){let n=`0x${Number(e)}`;return typeof t.size==`number`?(Fe(n,{size:t.size}),Ae(n,{size:t.size})):n}function ze(e,t={}){let n=``;for(let t=0;t<e.length;t++)n+=Ie[e[t]];let r=`0x${n}`;return typeof t.size==`number`?(Fe(r,{size:t.size}),Ae(r,{dir:`right`,size:t.size})):r}function Be(e,t={}){let{signed:n,size:r}=t,i=BigInt(e),a;r?a=n?(1n<<BigInt(r)*8n-1n)-1n:2n**(BigInt(r)*8n)-1n:typeof e==`number`&&(a=BigInt(2**53-1));let o=typeof a==`bigint`&&n?-a-1n:0;if(a&&i>a||i<o){let t=typeof e==`bigint`?`n`:``;throw new Ne({max:a?`${a}${t}`:void 0,min:`${o}${t}`,signed:n,size:r,value:`${e}${t}`})}let s=`0x${(n&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?Ae(s,{size:r}):s}const Ve=new TextEncoder;function He(e,t={}){return ze(Ve.encode(e),t)}const Ue=new TextEncoder;function We(e,t={}){return typeof e==`number`||typeof e==`bigint`?Je(e,t):typeof e==`boolean`?Ge(e,t):De(e)?qe(e,t):Ye(e,t)}function Ge(e,t={}){let n=new Uint8Array(1);return n[0]=Number(e),typeof t.size==`number`?(Fe(n,{size:t.size}),Ae(n,{size:t.size})):n}const E={zero:48,nine:57,A:65,F:70,a:97,f:102};function Ke(e){if(e>=E.zero&&e<=E.nine)return e-E.zero;if(e>=E.A&&e<=E.F)return e-(E.A-10);if(e>=E.a&&e<=E.f)return e-(E.a-10)}function qe(e,t={}){let n=e;t.size&&(Fe(n,{size:t.size}),n=Ae(n,{dir:`right`,size:t.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);let i=r.length/2,a=new Uint8Array(i);for(let e=0,t=0;e<i;e++){let n=Ke(r.charCodeAt(t++)),i=Ke(r.charCodeAt(t++));if(n===void 0||i===void 0)throw new Te(`Invalid byte sequence ("${r[t-2]}${r[t-1]}" in "${r}").`);a[e]=n*16+i}return a}function Je(e,t){return qe(Be(e,t))}function Ye(e,t={}){let n=Ue.encode(e);return typeof t.size==`number`?(Fe(n,{size:t.size}),Ae(n,{dir:`right`,size:t.size})):n}const Xe=BigInt(0),Ze=BigInt(1),Qe=BigInt(2),$e=BigInt(7),et=BigInt(256),tt=BigInt(113),nt=[],rt=[],it=[];for(let e=0,t=Ze,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],nt.push(2*(5*r+n)),rt.push((e+1)*(e+2)/2%64);let i=Xe;for(let e=0;e<7;e++)t=(t<<Ze^(t>>$e)*tt)%et,t&Qe&&(i^=Ze<<(Ze<<BigInt(e))-Ze);it.push(i)}const at=c(it,!0),ot=at[0],st=at[1],ct=(e,t,n)=>n>32?r(e,t,n):d(e,t,n),lt=(e,t,n)=>n>32?u(e,t,n):i(e,t,n);function ut(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let t=0;t<10;t++)r[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){let n=(t+8)%10,i=(t+2)%10,a=r[i],o=r[i+1],s=ct(a,o,1)^r[n],c=lt(a,o,1)^r[n+1];for(let n=0;n<50;n+=10)e[t+n]^=s,e[t+n+1]^=c}let t=e[2],i=e[3];for(let n=0;n<24;n++){let r=rt[n],a=ct(t,i,r),o=lt(t,i,r),s=nt[n];t=e[s],i=e[s+1],e[s]=a,e[s+1]=o}for(let t=0;t<50;t+=10){for(let n=0;n<10;n++)r[n]=e[t+n];for(let n=0;n<10;n++)e[t+n]^=~r[(n+2)%10]&r[(n+4)%10]}e[0]^=ot[n],e[1]^=st[n]}n(r)}var dt=class r extends p{constructor(e,n,r,i=!1,a=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=a,l(r),!(0<e&&e<200))throw Error(`only keccak-f1600 function is supported`);this.state=new Uint8Array(200),this.state32=t(this.state)}clone(){return this._cloneInto()}keccak(){e(this.state32),ut(this.state32,this.rounds),e(this.state32),this.posOut=0,this.pos=0}update(e){o(this),e=m(e),a(e);let{blockLen:t,state:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(t-this.pos,r-i);for(let t=0;t<a;t++)n[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,t&128&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){o(this,!1),a(e),this.finish();let t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();let a=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+a),r),this.posOut+=a,r+=a}return e}xofInto(e){if(!this.enableXOF)throw Error(`XOF is not possible for this instance`);return this.writeInto(e)}xof(e){return l(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(s(e,this),this.finished)throw Error(`digest() was already called`);return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,n(this.state)}_cloneInto(e){let{blockLen:t,suffix:n,outputLen:i,rounds:a,enableXOF:o}=this;return e||=new r(t,n,i,o,a),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=a,e.suffix=n,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}};const ft=((e,t,n)=>h(()=>new dt(t,e,n)))(1,136,32);function pt(e,t){let n=t||`hex`,r=ft(De(e,{strict:!1})?We(e):e);return n===`bytes`?r:Le(r)}var mt=class 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);return super.has(e)&&(super.delete(e),super.set(e,t)),t}set(e,t){if(super.has(e)&&super.delete(e),super.set(e,t),this.maxSize&&this.size>this.maxSize){let e=super.keys().next().value;e!==void 0&&super.delete(e)}return this}};const ht=/^0x[a-fA-F0-9]{40}$/,gt=new mt(8192);function _t(e,t){let{strict:n=!0}=t??{},r=`${e}.${n}`;if(gt.has(r))return gt.get(r);let i=ht.test(e)?e.toLowerCase()===e||!n||yt(e)===e:!1;return gt.set(r,i),i}const vt=new mt(8192);function yt(e,t){if(vt.has(`${e}.${t}`))return vt.get(`${e}.${t}`);let n=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),r=pt(Ye(n),`bytes`),i=(t?n.substring(`${t}0x`.length):n).split(``);for(let e=0;e<40;e+=2)r[e>>1]>>4>=8&&i[e]&&(i[e]=i[e].toUpperCase()),(r[e>>1]&15)>=8&&i[e+1]&&(i[e+1]=i[e+1].toUpperCase());let a=`0x${i.join(``)}`;return vt.set(`${e}.${t}`,a),a}function bt(){return`0.1.1`}var D=class e extends Error{static setStaticOptions(t){e.prototype.docsOrigin=t.docsOrigin,e.prototype.showVersion=t.showVersion,e.prototype.version=t.version}constructor(t,n={}){let r=(()=>{if(n.cause instanceof e){if(n.cause.details)return n.cause.details;if(n.cause.shortMessage)return n.cause.shortMessage}return n.cause&&`details`in n.cause&&typeof n.cause.details==`string`?n.cause.details:n.cause?.message?n.cause.message:n.details})(),i=n.cause instanceof e&&n.cause.docsPath||n.docsPath,a=n.docsOrigin??e.prototype.docsOrigin,o=`${a}${i??``}`,s=!!(n.version??e.prototype.showVersion),c=n.version??e.prototype.version,l=[t||`An error occurred.`,...n.metaMessages?[``,...n.metaMessages]:[],...r||i||s?[``,r?`Details: ${r}`:void 0,i?`See: ${o}`:void 0,s?`Version: ${c}`:void 0]:[]].filter(e=>typeof e==`string`).join(`
|
|
3
|
-
`);super(l,n.cause?{cause:n.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=n.cause,this.details=r,this.docs=o,this.docsOrigin=a,this.docsPath=i,this.shortMessage=t,this.showVersion=s,this.version=c}walk(e){return xt(this,e)}};Object.defineProperty(D,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:`https://oxlib.sh`,showVersion:!1,version:`ox@${bt()}`}}),D.setStaticOptions(D.defaultStaticOptions);function xt(e,t){return t?.(e)?e:e&&typeof e==`object`&&`cause`in e&&e.cause?xt(e.cause,t):t?null:e}function St(e,t){if(Ht(e)>t)throw new Gt({givenSize:Ht(e),maxSize:t})}const O={zero:48,nine:57,A:65,F:70,a:97,f:102};function Ct(e){if(e>=O.zero&&e<=O.nine)return e-O.zero;if(e>=O.A&&e<=O.F)return e-(O.A-10);if(e>=O.a&&e<=O.f)return e-(O.a-10)}function wt(e,t={}){let{dir:n,size:r=32}=t;if(r===0)return e;if(e.length>r)throw new Kt({size:e.length,targetSize:r,type:`Bytes`});let i=new Uint8Array(r);for(let t=0;t<r;t++){let a=n===`right`;i[a?t:r-t-1]=e[a?t:e.length-t-1]}return i}function Tt(e,t={}){let{dir:n=`left`}=t,r=e,i=0;for(let e=0;e<r.length-1&&r[n===`left`?e:r.length-e-1].toString()===`0`;e++)i++;return r=n===`left`?r.slice(i):r.slice(0,r.length-i),r}function Et(e,t){if(Mt(e)>t)throw new Nt({givenSize:Mt(e),maxSize:t})}function Dt(e,t={}){let{dir:n,size:r=32}=t;if(r===0)return e;let i=e.replace(`0x`,``);if(i.length>r*2)throw new Pt({size:Math.ceil(i.length/2),targetSize:r,type:`Hex`});return`0x${i[n===`right`?`padEnd`:`padStart`](r*2,`0`)}`}function Ot(e){if(e===null||typeof e==`boolean`||typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`){if(!Number.isFinite(e))throw TypeError(`Cannot canonicalize non-finite number`);return Object.is(e,-0)?`0`:JSON.stringify(e)}if(typeof e==`bigint`)throw TypeError(`Cannot canonicalize bigint`);if(Array.isArray(e))return`[${e.map(e=>Ot(e)).join(`,`)}]`;if(typeof e==`object`)return`{${Object.keys(e).sort().reduce((t,n)=>{let r=e[n];return r!==void 0&&t.push(`${JSON.stringify(n)}:${Ot(r)}`),t},[]).join(`,`)}}`}const kt=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function At(e,t={}){let n=``;for(let t=0;t<e.length;t++)n+=kt[e[t]];let r=`0x${n}`;return typeof t.size==`number`?(Et(r,t.size),jt(r,t.size)):r}function jt(e,t){return Dt(e,{dir:`right`,size:t})}function Mt(e){return Math.ceil((e.length-2)/2)}var Nt=class extends D{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`})}},Pt=class extends D{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`Hex.SizeExceedsPaddingSizeError`})}};const Ft=new TextDecoder,It=new TextEncoder;function Lt(e){return e instanceof Uint8Array?e:typeof e==`string`?zt(e):Rt(e)}function Rt(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function zt(e,t={}){let{size:n}=t,r=e;n&&(Et(e,n),r=jt(e,n));let i=r.slice(2);i.length%2&&(i=`0${i}`);let a=i.length/2,o=new Uint8Array(a);for(let e=0,t=0;e<a;e++){let n=Ct(i.charCodeAt(t++)),r=Ct(i.charCodeAt(t++));if(n===void 0||r===void 0)throw new D(`Invalid byte sequence ("${i[t-2]}${i[t-1]}" in "${i}").`);o[e]=n<<4|r}return o}function Bt(e,t={}){let{size:n}=t,r=It.encode(e);return typeof n==`number`?(St(r,n),Vt(r,n)):r}function Vt(e,t){return wt(e,{dir:`right`,size:t})}function Ht(e){return e.length}function Ut(e,t={}){let{size:n}=t,r=e;return n!==void 0&&(St(r,n),r=Wt(r)),Ft.decode(r)}function Wt(e){return Tt(e,{dir:`right`})}var Gt=class extends D{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`})}},Kt=class extends D{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`Bytes.SizeExceedsPaddingSizeError`})}};function qt(e,t,n={}){let{as:r=typeof t==`string`?`Hex`:`Bytes`}=n,i=g(f,Lt(e),Lt(t));return r===`Bytes`?i:At(i)}const Jt=new TextEncoder,Yt=new TextDecoder,Xt=Object.fromEntries(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[t,e.charCodeAt(0)])),Zt={...Object.fromEntries(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[e.charCodeAt(0),t])),61:0,45:62,95:63};function Qt(e,t={}){let{pad:n=!0,url:r=!1}=t,i=new Uint8Array(Math.ceil(e.length/3)*4);for(let t=0,n=0;n<e.length;t+=4,n+=3){let r=(e[n]<<16)+(e[n+1]<<8)+(e[n+2]|0);i[t]=Xt[r>>18],i[t+1]=Xt[r>>12&63],i[t+2]=Xt[r>>6&63],i[t+3]=Xt[r&63]}let a=e.length%3,o=Math.floor(e.length/3)*4+(a&&a+1),s=Yt.decode(new Uint8Array(i.buffer,0,o));return n&&a===1&&(s+=`==`),n&&a===2&&(s+=`=`),r&&(s=s.replaceAll(`+`,`-`).replaceAll(`/`,`_`)),s}function $t(e,t={}){return Qt(Bt(e),t)}function en(e){let t=e.replace(/=+$/,``),n=t.length,r=new Uint8Array(n+3);Jt.encodeInto(t+`===`,r);for(let e=0,n=0;e<t.length;e+=4,n+=3){let t=(Zt[r[e]]<<18)+(Zt[r[e+1]]<<12)+(Zt[r[e+2]]<<6)+Zt[r[e+3]];r[n]=t>>16,r[n+1]=t>>8&255,r[n+2]=t&255}let i=(n>>2)*3+(n%4&&n%4-1);return new Uint8Array(r.buffer,0,i)}function tn(e){return Ut(en(e))}const k={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},nn={payment:`Payment`};function rn(e){let t=tn(e);return JSON.parse(t)}function A(e){return $t(Ot(e),{pad:!1,url:!0})}function an(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function on(e,t){return typeof t==`bigint`?t.toString():t}function sn(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function cn(e){return e==null}function ln(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function un(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}const dn=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function fn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pn(e){if(fn(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return fn(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}const mn=new Set([`string`,`number`,`symbol`]);function hn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function gn(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function j(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}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function _n(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}function vn(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function yn(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function M(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function bn(e){return typeof e==`string`?e:e?.message}function xn(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function N(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:bn(e.inst?._zod.def?.error?.(e))??bn(a?.(e))??bn(t?.error?.(e))??bn(n.customError?.(e))??bn(n.localeError?.(e))??`Invalid input`,{inst:s,schema:c,continue:l,input:u,...d}=e;return d.path??=[],d.message=o,t?.reportInput&&(d.input=u),d}const Sn=/[\uD800-\uDBFF]/;function Cn(e){let t=e.length;if(!Sn.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function wn(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Tn(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function En(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):kn(e,n,r.value)}}function Dn(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function On(e,t,n){return Dn(e,t,n,!1)}function kn(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:Dn(this,t,n.bind(this))},set(e){Dn(this,t,e)}})}function An(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let jn,P=!1;const Mn={configurable:!0,get(){P=!0}};function F(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&jn!==e._zod){jn=void 0;return}jn=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Mn);let e=P;P=!1;try{let r=n(this);return P?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),P||=e,r}catch(n){throw delete this[t],P||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})}function Nn(e,t,n,r){let i=An(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}var Pn;const Fn={value:void 0,enumerable:!1};let In=`captureStackTrace`in Error?Error:null;function Ln(e){let t=In;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return In=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function I(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(!n._zod){Fn.value=new a(r);try{Object.defineProperty(n,"_zod",Fn)}finally{Fn.value=void 0}}if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),En(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?Ln(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var Rn=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}};(Pn=globalThis).__zod_globalConfig??(Pn.__zod_globalConfig={});const zn=globalThis.__zod_globalConfig;function L(e){return e&&Object.assign(zn,e),zn}function Bn(){let e=this._zod;return e.message??=JSON.stringify(e.def,on,2),e.message}function Vn(e){this._zod.message=e}const Hn={get:Bn,set:Vn,enumerable:!0,configurable:!0},Un={value:void 0,enumerable:!1},Wn={value:void 0,enumerable:!1},Gn=new WeakSet([Object.prototype,Error.prototype]),Kn=(e,t)=>{e.name=`$ZodError`,Un.value=e._zod,Object.defineProperty(e,"_zod",Un),Wn.value=t,Object.defineProperty(e,"issues",Wn),Un.value=void 0,Wn.value=void 0,Object.defineProperty(e,"message",Hn);let n=Object.getPrototypeOf(e);Gn.has(n)||(Gn.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},qn=I(`$ZodError`,Kn),Jn=I(`$ZodError`,Kn,void 0,{Parent:Error}),Yn=(e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Rn;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>N(e,o,L())));throw dn(n,a?.callee??t),n}return s.value};return t})(Jn),Xn=(e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>N(e,o,L())));throw dn(n,a?.callee??t),n}return s.value};return t})(Jn),Zn=(e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Rn;return a.issues.length?{success:!1,error:new(e??qn)(a.issues.map(e=>N(e,i,L())))}:{success:!0,data:a.value}})(Jn),Qn=(e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>N(e,i,L())))}:{success:!0,data:a.value}})(Jn),$n=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},er=/^-?\d+(?:\.\d+)?$/,tr=/^(?:true|false)$/i,nr=I(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),rr=e=>{let t=e.value;return!cn(t)&&t.length!==void 0},ir=I(`$ZodCheckMinLength`,(e,t)=>{var n;nr.init(e,t),(n=e._zod.def).when??(n.when=rr),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?Cn(r):i)>=t.minimum)return;let a=wn(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),ar=I(`$ZodCheckStringFormat`,(e,t)=>{var n,r;nr.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&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})}):(r=e._zod).check??(r.check=()=>{})}),or=I(`$ZodCheckRegex`,(e,t)=>{ar.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),sr={major:4,minor:5,patch:4},R=I(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=sr;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=vn(t),a;for(let o of n){if(o._zod.def.when){if(yn(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new Rn;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(xn(t.issues,n,e),i||=vn(t,n))});else{if(t.issues.length===n)continue;xn(t.issues,n,e),i||=vn(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(vn(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new Rn;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new Rn;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return On(this,`~standard`,lr(this))},set"~standard"(e){Dn(this,`~standard`,e)}}),cr=e=>e.success?{value:e.data}:{issues:e.error?.issues};function lr(e){return{validate:t=>{try{return cr(Zn(e,t))}catch{return Qn(e,t).then(cr)}},vendor:`zod`,version:1}}const ur=I(`$ZodString`,(e,t)=>{R.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??$n(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),dr=I(`$ZodNumber`,(e,t)=>{R.init(e,t),e._zod.pattern=e._zod.bag.pattern??er,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),fr=I(`$ZodBoolean`,(e,t)=>{R.init(e,t),e._zod.pattern=tr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),pr=I(`$ZodUnknown`,(e,t)=>{R.init(e,t),e._zod.parse=e=>e}),mr=I(`$ZodNever`,(e,t)=>{R.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function hr(e,t,n){e.issues.length&&t.issues.push(...M(n,e.issues)),t.value[n]=e.value}const gr=I(`$ZodArray`,(e,t)=>{R.init(e,t);let n=zn.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[];for(let e=0;e<a.length;e++){let n=a[e],s=t.element._zod.run({value:n,issues:[]},i);s instanceof Promise?o.push(s.then(t=>hr(t,r,e))):hr(s,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function _r(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...M(n,e.issues))}if(!o&&i===void 0){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}}const vr=[];function yr(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:vr,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=_n(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function br(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin,d=c.optout;for(let i in t){if(s.has(i))continue;if(i===`__proto__`){l===`never`&&o.push(i);continue}if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>_r(e,n,i,t,u,d))):_r(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const xr=new WeakMap,Sr=I(`$ZodObject`,(e,t)=>{if(R.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;xr.set(t,e),Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),xr.set(t,n),n}})}let n=sn(()=>yr(t));F(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||un(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let r=fn,i=t.catchall,a,o=zn.memoizer;o?.attach(e),e._zod.parse=(t,s)=>{a??=n.value;let c=t.value;if(!r(c))return t.issues.push({expected:`object`,code:`invalid_type`,input:c,inst:e}),t;t.value=o?o.alloc(e,t,{},s):{};let l=[],u=a.shape;for(let e of a.allKeys){if(e===`__proto__`)continue;let n=u[e],r=n._zod.optin,i=n._zod.optout,a=n._zod.run({value:c[e],issues:[]},s);a instanceof Promise?l.push(a.then(n=>_r(n,t,e,c,r,i))):_r(a,t,e,c,r,i)}return i?br(l,c,t,s,n.value,e):l.length?Promise.all(l).then(()=>t):t}});function Cr(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!vn(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>N(e,r,L())))}),t)}const wr=I(`$ZodUnion`,(e,t)=>{R.init(e,t),F(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),F(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),F(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),F(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>ln(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Cr(t,r,e,i)):Cr(o,r,e,i)}}),Tr=I(`$ZodRecord`,(e,t)=>{R.init(e,t);let n=zn.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!pn(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>N(e,i,L())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...M(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...M(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&er.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>N(e,i,L())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...M(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...M(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),Er=I(`$ZodEnum`,(e,t)=>{R.init(e,t);let n=an(t.entries),r=new Set(n);e._zod.values=r;let i=n.filter(e=>mn.has(typeof e));e._zod.pattern=RegExp(i.length?`^(${i.map(e=>hn(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Dr=I(`$ZodLiteral`,(e,t)=>{R.init(e,t);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(t.values.length?`^(${t.values.map(e=>typeof e==`string`?hn(e):e?hn(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}});function Or(e,t){return e.value=t.issues.length?void 0:t.value,e}const kr=I(`$ZodOptional`,(e,t)=>{R.init(e,t),F(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,F(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),F(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${ln(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>Or(e,t)):Or(e,r)}return t.innerType._zod.run(e,n)}}),Ar=I(`$ZodCustom`,(e,t)=>{nr.init(e,t),R.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>jr(t,n,r,e));jr(i,n,r,e)}});function jr(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Tn(e))}}function Mr(e,t){return new e({type:`string`,...j(t)})}function Nr(e,t){return new e({type:`number`,checks:[],...j(t)})}function Pr(e,t){return new e({type:`boolean`,...j(t)})}function Fr(e){return new e({type:`unknown`})}function Ir(e,t){return new e({type:`never`,...j(t)})}function Lr(e,t){return new ir({check:`min_length`,...j(t),minimum:e})}function z(e,t){return new or({check:`string_format`,format:`regex`,...j(t),pattern:e})}function Rr(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...j(n)})}const B=I(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);R.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){Dn(this,`with`,e)},parse(e,t){return Yn(this,e,t,{callee:this.parse})},parseAsync(e,t){return Xn(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return Zn(this,e,t)},safeParseAsync(e,t){return Qn(this,e,t)},check(...e){let t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0})},clone(e,t){return gn(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return t.length===0?e(this):e(this,...t)}}),zr=I(`ZodMiniString`,(e,t)=>{ur.init(e,t),B.init(e,t)});function V(e){return Mr(zr,e)}const Br=I(`ZodMiniNumber`,(e,t)=>{dr.init(e,t),B.init(e,t)});function Vr(e){return Nr(Br,e)}const Hr=I(`ZodMiniBoolean`,(e,t)=>{fr.init(e,t),B.init(e,t)});function Ur(e){return Pr(Hr,e)}const Wr=I(`ZodMiniUnknown`,(e,t)=>{pr.init(e,t),B.init(e,t)});function Gr(){return Fr(Wr)}const Kr=I(`ZodMiniNever`,(e,t)=>{mr.init(e,t),B.init(e,t)});function qr(e){return Ir(Kr,e)}const Jr=I(`ZodMiniArray`,(e,t)=>{gr.init(e,t),B.init(e,t)});function Yr(e,t){return new Jr({type:`array`,element:e,...j(t)})}const Xr=I(`ZodMiniObject`,(e,t)=>{Sr.init(e,t),B.init(e,t),Nn(e,`shape`,e=>e._zod.def.shape,!1)});function H(e,t){let n={type:`object`,shape:e??{},...j(t)};return new Xr(n)}function Zr(e,t){return new Xr({type:`object`,shape:e,catchall:Gr(),...j(t)})}const Qr=I(`ZodMiniUnion`,(e,t)=>{wr.init(e,t),B.init(e,t)});function $r(e,t){return new Qr({type:`union`,options:e,...j(t)})}const ei=I(`ZodMiniRecord`,(e,t)=>{Tr.init(e,t),B.init(e,t)});function U(e,t,n){return!t||!t._zod?new ei({type:`record`,keyType:V(),valueType:e,...j(t)}):new ei({type:`record`,keyType:e,valueType:t,...j(n)})}const ti=I(`ZodMiniEnum`,(e,t)=>{Er.init(e,t),B.init(e,t),e.options=Object.values(t.entries)});function ni(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ti({type:`enum`,entries:n,...j(t)})}const ri=I(`ZodMiniLiteral`,(e,t)=>{Dr.init(e,t),B.init(e,t)});function W(e,t){return new ri({type:`literal`,values:Array.isArray(e)?e:[e],...j(t)})}const ii=I(`ZodMiniOptional`,(e,t)=>{kr.init(e,t),B.init(e,t)});function G(e){return new ii({type:`optional`,innerType:e})}const ai=I(`ZodMiniCustom`,(e,t)=>{Ar.init(e,t),B.init(e,t)});function oi(e,t={}){return Rr(ai,e,t)}function si(){return V().check(z(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function ci(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function li(){return V().check(z(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function ui(){return V().check(z(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function di(){return V().check(z(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}const fi=H({description:G(V()),digest:G(V().check(z(/^sha-256=/,`Invalid digest format`))),expires:G(si()),header:G(V().check(z(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:V().check(Lr(1)),intent:V(),method:V(),meta:G(U(V(),V())),opaque:G(V()),realm:V(),request:U(V(),Gr())});function pi(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=Di(o)?void 0:o,f=e.expires?ci(e.expires):void 0,p=e.opaque??(i===void 0?void 0:A(i)),m=u?Oi({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return fi.parse({id:m,realm:c,method:a,intent:s,request:l,...n&&{description:n},...r&&{digest:r},...f&&{expires:f},...d!==void 0&&{header:d},...i!==void 0&&{meta:i},...p!==void 0&&{opaque:p}})}function mi(e){let t=[K(`id`,e.id),K(`realm`,e.realm),K(`method`,e.method),K(`intent`,e.intent),K(`request`,A(e.request))];e.description!==void 0&&t.push(K(`description`,e.description)),e.digest!==void 0&&t.push(K(`digest`,e.digest)),e.expires!==void 0&&t.push(K(`expires`,e.expires));let n=e.header;return n!==void 0&&!Di(n)&&t.push(K(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(K(`opaque`,A(e.meta))):t.push(K(`opaque`,e.opaque)),`${nn.payment} ${t.join(`, `)}`}function K(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function hi(e,t){let n=gi(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=_i(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>16384)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return pi({...a,request:rn(r),...i&&{opaque:i}},t)}function gi(e){let t=nn.payment,[n]=xi(e,t);if(n===void 0)return null;let r=n+t.length;for(;r<e.length&&/\s/.test(e[r]??``);)r++;return e.slice(r)}function _i(e){let t=Object.create(null),n=0;for(;n<e.length;){for(;n<e.length&&/[\s,]/.test(e[n]??``);)n++;if(n>=e.length)break;let r=n;for(;n<e.length&&/[A-Za-z0-9_-]/.test(e[n]??``);)n++;let i=e.slice(r,n).toLowerCase();if(!i)throw Error(`Malformed auth-param.`);for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]!==`=`)break;for(n++;n<e.length&&/\s/.test(e[n]??``);)n++;let[a,o]=vi(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function vi(e,t){if(e[t]===`"`)return yi(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function yi(e,t){let n=t,r=!1,i=t,a;for(;n<e.length;){let o=e[n];if(n++,r){a??=[];let t=o===`u`?e.slice(n,n+4):void 0;t&&/^[0-9A-Fa-f]{4}$/.test(t)?(a.push(String.fromCharCode(Number.parseInt(t,16))),n+=4):a.push(o),i=n,r=!1;continue}if(o===`\\`){a??=[],a.push(e.slice(i,n-1)),i=n,r=!0;continue}if(o===`"`)return[a?[...a,e.slice(i,n-1)].join(``):e.slice(t,n-1),n]}throw Error(`Unterminated quoted-string.`)}function bi(e,t,n){if(e.slice(t,t+n.length).toLowerCase()!==n.toLowerCase())return!1;let r=e[t+n.length];return!!(r&&/\s/.test(r))}function xi(e,t){let n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(!bi(e,a,t))continue;let s=a-1;for(;s>=0&&/\s/.test(e[s]??``);)s--;s>=0&&e[s]!==`,`||n.push(a)}return n}function Si(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return Ci(e.headers,t)}function Ci(e,t){let n=e.get(k.wwwAuthenticate);if(!n)throw Error(`Missing ${k.wwwAuthenticate} header.`);return wi(n,t)}function wi(e,t){let n=xi(e,nn.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return hi(e.slice(r,a).replace(/,\s*$/,``),t)})}function Ti(e){let t=[e.realm,e.method,e.intent,A(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!Di(n)&&t.push(n),t.push(e.opaque??(e.meta?A(e.meta):``)),t.join(`|`)}function Ei(e){return e.header??k.authorization}function Di(e){return e?.toLowerCase()===k.authorization.toLowerCase()}function Oi(e,t){let n=Ti(e);return Qt(qt(Bt(t.secretKey),Bt(n),{as:`Bytes`}),{url:!0,pad:!1})}var ki=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},Ai=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function ji(e){let t=e.match(RegExp(`^${nn.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new ki;try{let e=tn(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=Mi(r);return{challenge:fi.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:rn(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new Ai}}function Mi(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!Ni(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:A(e)}}function Ni(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}var Pi=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...e&&{challengeId:e}}}},Fi=class extends Pi{name=`InvalidChallengeError`;title=`Invalid Challenge`;status=402;type=`https://paymentauth.org/problems/invalid-challenge`;constructor(e={}){let{id:t,reason:n}=e,r=t?` "${t}"`:``,i=n?`: ${n}`:``;super(`Challenge${r} is invalid${i}.`)}},Ii=class extends Pi{name=`PaymentExpiredError`;title=`Payment Expired`;type=`https://paymentauth.org/problems/payment-expired`;constructor(e={}){let{expires:t}=e;super(t?`Payment expired at ${t}.`:`Payment has expired.`)}};function Li(e,t){if(!e)throw new Fi({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new Fi({...t&&{id:t},reason:`malformed expires timestamp`});if(new Date(e)<new Date)throw new Ii({expires:e})}function Ri(e){return e}function zi(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}const Bi=Zr({method:V(),reference:V(),externalId:G(V()),subscriptionId:G(V()),status:W(`success`),timestamp:si()});function Vi(e){let t=tn(e);return Hi(JSON.parse(t))}function Hi(e){return Bi.parse(e)}function Ui(e){let t=e.headers.get(k.paymentReceipt);if(!t)throw Error(`Missing ${k.paymentReceipt} header.`);return Vi(t)}function Wi(e){return{encode(t){return $t(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(tn(t)))}catch{throw new Gi}}}}var Gi=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const Ki=[`exact`],qi=`PAYMENT-REQUIRED`,Ji=`PAYMENT-SIGNATURE`,Yi=V().check(Lr(1)),Xi=Vr().check(oi(e=>e>0,`Must be positive`)),q=V().check(z(/^\d+$/,`Invalid atomic amount`)),Zi=li(),Qi=V().check(z(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),$i=H({description:G(V()),iconUrl:G(V()),mimeType:G(V()),serviceName:G(V()),tags:G(Yr(V())),url:Yi}),ea=H({amount:q,asset:Yi,extra:G(U(V(),Gr())),maxTimeoutSeconds:Xi,network:Qi,payTo:Yi,scheme:ni(Ki)}),ta=U(V(),H({info:U(V(),Gr()),schema:U(V(),Gr())})),na=H({accepts:Yr(ea).check(Lr(1)),error:G(V()),extensions:G(ta),resource:$i,x402Version:W(2)}),ra=$r([H({authorization:H({from:Zi,nonce:ui(),to:Zi,validAfter:q,validBefore:q,value:q}),signature:di()}),H({permit2Authorization:H({deadline:q,from:Zi,nonce:q,permitted:H({amount:q,token:Zi}),spender:Zi,witness:H({to:Zi,validAfter:q})}),signature:di()})]),ia=H({accepted:ea,extensions:G(ta),payload:ra,resource:G($i),x402Version:W(2)}),aa=H({amount:G(q),errorMessage:G(V()),errorReason:G(V()),extensions:G(ta),extra:G(U(V(),Gr())),network:Yi,payer:G(V()),success:Ur(),transaction:V()}),oa=Wi(na),sa=Wi(ia),ca=Wi(aa);oa.encode,oa.decode;function la(e){try{let t=JSON.parse(tn(e));return ua(t)}catch{throw new Gi}}sa.encode,sa.decode,ca.encode,ca.decode;const ua=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Gi;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Gi;let n=$i.parse(t.resource),r=t.extensions===void 0?void 0:ta.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}},da=Symbol.for(`mppx.x402.challenge`);function fa(e){return Object.defineProperty(e,da,{value:!0}),e}function pa(e){return!!e?.[da]}function ma(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=ya(n)}return t}function ha(e,t){let n=ma(e),r=Ea(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[ya(e)]??1,index:t}));return{definition:r,entries:i,header:_a(i),keys:n}}function ga(e){let t=e.split(/\s*,\s*/).map(e=>e.trim()).filter(Boolean);if(t.length===0)throw Error(`Accept-Payment header is empty.`);return t.map((e,t)=>wa(e,t))}function _a(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${Aa(n)}`}).join(`, `)}function va(e,t,n){let r=new Map;for(let e of t){let t=ya(e),n=r.get(t);n?n.push(e):r.set(t,[e])}return e.flatMap((e,t)=>{let i=r.get(ya(e));if(!i)return[];let a=ba(e,n);return!a||a.q<=0?[]:i.filter(t=>t.canHandleChallenge?.({challenge:e})??!0).map(n=>({challenge:e,index:t,match:a,method:n}))}).sort((e,t)=>Ca(e.challenge)-Ca(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function ya(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function ba(e,t){let n;for(let r of t){if(!xa(e,r))continue;let t={...r,specificity:Sa(r)};(!n||t.specificity>n.specificity||t.specificity===n.specificity&&t.q>n.q||t.specificity===n.specificity&&t.q===n.q&&t.index<n.index)&&(n=t)}return n}function xa(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function Sa(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function Ca(e){return+!!pa(e)}function wa(e,t){let n=/^(?<method>[^/;\s]+|\*)\s*\/\s*(?<intent>[^/;\s]+|\*)(?<params>(?:\s*;\s*.+)?)$/u.exec(e),r=n?.groups?.method,i=n?.groups?.intent;if(!r||!i)throw Error(`Invalid Accept-Payment entry: ${e}`);ja(r,`method`),ja(i,`intent`);let a=1;for(let t of Ta(n.groups?.params)){if(!t)continue;let n=/^(?<name>[A-Za-z0-9_-]+)\s*=\s*(?<value>\S+)$/u.exec(t),r=n?.groups?.name,i=n?.groups?.value;if(!r||!i)throw Error(`Invalid Accept-Payment parameter: ${t}`);r===`q`&&(a=Oa(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function Ta(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function Ea(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>ya(e))),a={};for(let[e,t]of Object.entries(r??{})){if(!i.has(e))throw Error(`Unknown payment preference "${e}". Available: ${[...i].join(`, `)}`);a[e]=Da(t,`payment preference "${e}"`)}return a}function Da(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return ka(e,t)}function Oa(e,t){if(!/^0(?:\.\d{0,3})?$|^1(?:\.0{0,3})?$/.test(e))throw Error(`Invalid q-value for ${t}. Expected an HTTP qvalue.`);return ka(Number(e),t)}function ka(e,t){if(e<0||e>1)throw Error(`Invalid q-value for ${t}. Expected a value between 0 and 1.`);let n=Math.round(e*1e3);if(Math.abs(e*1e3-n)>1e-9)throw Error(`Invalid q-value for ${t}. Expected at most 3 decimal places.`);return n/1e3}function Aa(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function ja(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}var Ma=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Na(e){}function Pa(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Na,onError:n=Na,onRetry:r=Na,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(`
|
|
4
|
-
`)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new Ma(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function g(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(`
|
|
5
|
-
`,n);for(;r!==-1;){if(n===r){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0,n=r+1,r=e.indexOf(`
|
|
6
|
-
`,n);continue}let i=e.charCodeAt(n);if(Fa(e,n,i)){let i=e.charCodeAt(n+5)===32?n+6:n+5,a=e.slice(i,r);if(d===0&&e.charCodeAt(r+1)===10){t({id:l,event:f,data:a}),l=void 0,u=``,f=void 0,n=r+2,r=e.indexOf(`
|
|
7
|
-
`,n);continue}u=d===0?a:`${u}
|
|
8
|
-
${a}`,d++}else Ia(e,n,i)?f=e.slice(e.charCodeAt(n+6)===32?n+7:n+6,r)||void 0:_(e,n,r);n=r+1,r=e.indexOf(`
|
|
9
|
-
`,n)}return e.slice(n)}for(;n<e.length;){let t=e.indexOf(`\r`,n),r=e.indexOf(`
|
|
10
|
-
`,n),i=-1;if(t!==-1&&r!==-1?i=t<r?t:r:t===-1?r!==-1&&(i=r):i=t===e.length-1?-1:t,i===-1)break;_(e,n,i),n=i+1,e.charCodeAt(n-1)===13&&e.charCodeAt(n)===10&&n++}return e.slice(n)}function _(e,t,n){if(t===n){y();return}let r=e.charCodeAt(t);if(Fa(e,t,r)){let r=e.charCodeAt(t+5)===32?t+6:t+5,i=e.slice(r,n);u=d===0?i:`${u}
|
|
11
|
-
${i}`,d++;return}if(Ia(e,t,r)){f=e.slice(e.charCodeAt(t+6)===32?t+7:t+6,n)||void 0;return}if(r===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let r=e.slice(e.charCodeAt(t+3)===32?t+4:t+3,n);r.includes(`\0`)||(l=r);return}if(r===58){if(i){let r=e.slice(t,n);i(r.slice(e.charCodeAt(t+1)===32?2:1))}return}let a=e.slice(t,n),o=a.indexOf(`:`);if(o===-1){v(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===32?2:1;v(s,a.slice(o+c),a)}function v(e,t,i){switch(e){case`event`:f=t||void 0;break;case`data`:u=d===0?t:`${u}
|
|
12
|
-
${t}`,d++;break;case`id`:t.includes(`\0`)||(l=t);break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Ma(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Ma(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}))}}function y(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function b(e={}){if(e.consume&&o.length>0){let e=o.join(``);_(e,0,e.length)}c=!0,l=void 0,u=``,d=0,f=void 0,o.length=0,s=0,p=!1}return{feed:m,reset:b}}function Fa(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Ia(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}const La=[k.authorization,qi,`PAYMENT-RESPONSE`,Ji];function Ra(e,t,n){let r=new Headers(e.headers);for(let e of La)(e!==k.authorization||r.get(e)?.startsWith(`Payment `))&&r.delete(e);return r.set(t,n),{...e,headers:r}}function za(e){if(typeof e==`string`)try{let t=JSON.parse(e),n=t?.id;return t?.jsonrpc!==`2.0`||typeof t?.method!=`string`?void 0:typeof n==`string`||typeof n==`number`?n:void 0}catch{return}}const Ba=new WeakMap;function Va(e){let t=za(e?.body);if(t===void 0)return;let n=new Headers(e?.headers);if(n.has(`mcp-method`))return t;let r=n.get(`accept`)?.toLowerCase()??``;return r.includes(`application/json`)&&r.includes(`text/event-stream`)?t:void 0}function Ha(e){if(!e||typeof e!=`object`)return;let t=e,n=t.id;if(t.jsonrpc!==`2.0`||n!==void 0&&typeof n!=`string`&&typeof n!=`number`)return;let r=`error`in t;if(r!==`result`in t)return r?Number.isInteger(t.error?.code)&&typeof t.error?.message==`string`?e:void 0:n!==void 0&&typeof t.result==`object`?e:void 0}function Ua(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){let t=fi.safeParse(e);if(!t.success)return;n.push(t.data)}let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function Wa(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:Ua(e.error.data):Ua(e.result?._meta?.[`org.paymentauth/payment-required`])}function Ga(e,t){return!e||e.id!==t?[]:Wa(e)?.challenges??[]}async function Ka(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=!1,i,a=Pa({onEvent(e){if(!r&&e.data&&(r=!0,!(e.event&&e.event!==`message`)))try{i=Ha(JSON.parse(e.data))}catch{}}});try{for(;;){if(r)return i;let{done:e,value:o}=await t.read();if(e)return a.feed(n.decode()),a.reset({consume:!0}),i;a.feed(n.decode(o,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}function qa(e){let t=Ba.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(t.includes(`application/json`))return e.clone().json().then(Ha).catch(()=>void 0);if(t.includes(`text/event-stream`))return Ka(e)})();return Ba.set(e,n),n}function Ja(){return{getChallenges(e,t){let n=Va(t);return e.status===402||n===void 0?[]:qa(e).then(e=>Ga(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=ji(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function Ya(){return{getChallenges(e){return e.status!==402||!e.headers.has(k.wwwAuthenticate)?[]:Si(e)},setCredential(e,t,n){return Ra(e,n?.challenge?Ei(n.challenge):k.authorization,t)}}}function Xa(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(qi);if(!t)return[];let n=la(t);if(e.url&&n.resource.url!==e.url)throw Error(`x402 payment-required resource does not match response URL.`);return n.accepts.flatMap((e,t)=>{let r=ea.safeParse(e);if(!r.success)return[];let i=r.data;return fa(pi({id:`x402:${t}`,intent:`charge`,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return Ra(e,Ji,t)}}}function Za(e){return e}function Qa(){let e=[Ya(),Xa(),Ja()],t=new WeakMap,n=(e,n)=>{for(let r of n)t.set(r,e);return n},r=(t,r)=>{let i=(a,o)=>{for(let s=a;s<e.length;s++){let a=e[s],c=a.getChallenges(t,r);if(c instanceof Promise)return c.then(e=>i(s+1,[...o,...n(a,e)]));o.push(...n(a,c))}return o};return i(0,[])};return Za({name:`http`,isPaymentRequired(e,t){if(e.status===402)return!0;let n=r(e,t);return n instanceof Promise?n.then(e=>e.length>0):n.length>0},getChallenges(e,t){return r(e,t)},setCredential(n,r,i){let a=i?.challenge?t.get(i.challenge):void 0,o=e[0];if(!a&&!o)throw Error(`No protocol to attach the credential.`);return(a??o).setCredential(n,r,i)}})}const $a=new WeakMap;function eo(e){return $a.has(e)}function to(e,t){return Promise.resolve($a.get(e)?.(t))}const no=new WeakMap,ro=new WeakMap;function io(e,t,n){no.has(e)&&ro.set(t,n)}function ao(e,t){return Promise.resolve(no.get(e)?.(t)??t.response)}const oo=Symbol.for(`mppx.fetch.wrapper`);let so;const co=new WeakMap;async function J(e,t){let n=e?.attempt.settle;if(!n)return t.status!==`pending`;e.attempt.settle=void 0;let r=await n(t);return r||(e.attempt.settle=n),r}function lo(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=Qa()}=e,l=e.eventDispatcher??fo(),u=t??ha(a),d=Mo(r),f=async(e,t,r)=>{let p=jo(e,t?.headers),m=p.has(k.acceptPayment),h=Lo(p,u),g=ko(e,t,p),_=Oo(e,t,p,h.header,m,n),v=await d(No(_.input),_.init),y=Ao(_.init,await g);if(!await c.isPaymentRequired(v,y))return v;let b=t?.context,{context:ee,orderChallenges:x,...te}=y??{},S,C,ne,w;try{for(let n=0;n<i;n++){C=await c.getChallenges(v,y);let i=(await Ro(va(C,a,h.entries),x??s))[0];if(!i){if(await J(w,{challenges:C,response:v,status:`rejected`}),n>0)return v;throw Error(`No method found for challenges: ${C.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let u=i.challenge;S=u,ne=i.method,S.expires&&Li(S.expires,S.id);let p=Uo(v,_.input,_.input),m=w,g=mi(u),ee=m?.method===i.method&&m?.key===g,re=!1;if(m){let e=await J(m,{challenges:C,response:v,status:ee?`pending`:`rejected`});re=ee&&!e}w=re?m:void 0;let ie=_o(async e=>{if(e===void 0&&re&&m)return m.promise;re&&m&&(await J(m,{status:`rejected`}),w=void 0);let t=e??b;if(!eo(i.method))return Io(u,i.method,t);let n={prepare:()=>to(i.method,{challenge:u,context:t,fetch:d,input:p})},r=n.prepare().then(()=>Io(u,i.method,t,n));return w={attempt:n,key:e===void 0?g:void 0,method:i.method,promise:r},r}),T=await l.emit(`challenge.received`,vo({challenge:u,challenges:C,createCredential:ie,init:t,input:e,method:i.method,response:v}))??(o?await o(S,{createCredential:ie}):void 0)??await ie(),ae=w;ae&&await ae.promise.catch(()=>void 0)!==T&&(await J(ae,{status:`rejected`}),w=void 0),Fo(T),await l.emit(`credential.created`,yo({challenge:u,credential:T,init:t,input:e,method:i.method,response:v})),v=await d(p,c.setCredential({...te,headers:_.headers},T,{challenge:u}));let oe=await c.isPaymentRequired(v,y);if(oe||(await J(ae,{response:v,status:v.ok?`accepted`:`rejected`}),w=void 0),v.ok&&po(l,`payment.response`)&&await l.emit(`payment.response`,bo({challenge:u,credential:T,init:t,input:e,method:i.method,response:v})),!oe)return v.ok?ao(i.method,{challenge:u,credential:T,fetch:d,headers:_.headers,input:p,...r?{refetch:()=>f(No(_.input),t,!1)}:{},response:v,signal:Po(e,t)}):v}C=void 0;try{C=await c.getChallenges(v,y)}catch{}return await J(w,{challenges:C,response:v,status:`rejected`}),v}catch(n){throw await J(w,{challenges:C,response:v,status:`rejected`}),await l.emit(`payment.failed`,xo({challenge:S,challenges:C,error:n,init:t,input:e,method:ne,response:v})),n}},p=(e,t)=>f(e,t,!0);return p[oo]=d,p}function uo(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);so||=globalThis.fetch,globalThis.fetch=lo({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??(Vo()?`same-origin`:`always`),fetch:globalThis.fetch})}function fo(){let e={"*":new Set,"challenge.received":new Set,"credential.created":new Set,"payment.failed":new Set,"payment.response":new Set},t={async emit(t,n){switch(t){case`challenge.received`:{let r;for(let t of e[`challenge.received`]){let e=await mo(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await go(e[`*`],t,n),r}case`credential.created`:await ho(e[`credential.created`],n),await go(e[`*`],t,n);return;case`payment.failed`:await ho(e[`payment.failed`],n),await go(e[`*`],t,n);return;case`payment.response`:await ho(e[`payment.response`],n),await go(e[`*`],t,n);return}},on:(t,n)=>{switch(t){case`*`:case`challenge.received`:case`credential.created`:case`payment.failed`:case`payment.response`:return e[t].add(n),()=>e[t].delete(n);default:throw Error(`Unknown client event "${String(t)}".`)}}};return co.set(t,t=>e[t].size>0||e[`*`].size>0),t}function po(e,t){return co.get(e)?.(t)??!0}async function mo(e,t){try{return await e(t)}catch{return}}async function ho(e,t){for(let n of e)try{await n(t)}catch{}}async function go(e,t,n){await ho(e,Object.freeze({name:t,payload:n}))}function _o(e){let t;return n=>(t??=e(n),t)}function vo(e){return Object.freeze({challenge:Y(e.challenge),challenges:e.challenges.map(e=>Y(e)),createCredential:e.createCredential,init:So(e.init),input:Co(e.input),method:wo(e.method),response:To(e.response)})}function yo(e){return Object.freeze({challenge:Y(e.challenge),credential:e.credential,init:So(e.init),input:Co(e.input),method:wo(e.method),...e.response===void 0?{}:{response:To(e.response)}})}function bo(e){return Object.freeze({challenge:Y(e.challenge),credential:e.credential,init:So(e.init),input:Co(e.input),method:wo(e.method),response:To(e.response)})}function xo(e){return Object.freeze({...e.challenge?{challenge:Y(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>Y(e))}:{},error:e.error,init:So(e.init),input:Co(e.input),...e.method?{method:wo(e.method)}:{},...e.response===void 0?{}:{response:To(e.response)}})}function So(e){if(e)return Do({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function Co(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function wo(e){return Do(Object.assign({},e))}function To(e){return e instanceof Response?e.clone():Y(e)}function Y(e){try{return Eo(structuredClone(e))}catch{return Do(e)}}function Eo(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Eo(t);return e}function Do(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function Oo(e,t,n,r,i,a){let o=!!r&&!i&&zo(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(k.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function ko(e,t,n){if(e instanceof Request&&t?.body===void 0&&e.body&&!e.bodyUsed){if(!n.has(`mcp-method`)){let e=n.get(`accept`)?.toLowerCase()??``;if(!e.includes(`application/json`)||!e.includes(`text/event-stream`))return}try{return e.clone().text().catch(()=>void 0)}catch{return}}}function Ao(e,t){return t===void 0?e:{...e,body:t}}function jo(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function Mo(e){let t=e;for(;t[oo];)t=t[oo];return t}function No(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Po(e,t){return t?.signal??(e instanceof Request?e.signal:void 0)}function Fo(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
|
|
13
|
-
`))throw Error(`Credential header value contains illegal newline characters`)}async function Io(e,t,n,r){let i=t.context&&n!==void 0?t.context.parse(n):void 0,a=i===void 0?{challenge:e}:{challenge:e,context:i};return r&&io(t,a,r),t.createCredential(a)}function Lo(e,t){let n=e.get(k.acceptPayment);if(!n)return t;try{return{...t,entries:ga(n),header:n}}catch{return t}}async function Ro(e,t){return t?t(e):e}function zo(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=Ho(e);return t===`same-origin`?!Vo()||n.origin===globalThis.location.origin:t.origins.some(e=>Bo(n,e))}function Bo(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e.hostname.endsWith(n)||e.hostname===t.slice(2)}return e.origin===new URL(t).origin}function Vo(){return globalThis.location!==void 0}function Ho(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,Vo()?globalThis.location.href:void 0)}function Uo(e,t,n){if(!e.url)return t;let r=new URL(e.url),i=Ho(n);if(r.origin!==i.origin)throw Error(`Refusing to send payment credential across redirect from ${i.origin} to ${r.origin}`);return e.url}function Wo(){let e=new Uint8Array(64);return crypto.getRandomValues(e),Object.freeze({created:Math.floor(Date.now()/1e3),nonce:Qt(e,{pad:!1,url:!0})})}function Go(...e){return{protocol:`composed`,async sign(t,n=Wo()){for(let r of e)t=await r.sign(t,n);return t}}}function Ko(e,t){return async(n,r)=>e(await t.sign(new Request(n,r)))}function qo(e){let{attestation:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=Qa()}=e,c=e.fetch??globalThis.fetch,l=t?Jo(c,t):c,u=e.methods.flat(),d=ha(u,e.paymentPreferences),f=fo(),p=r,m={acceptPayment:d,acceptPaymentPolicy:o,...(e.fetch||t)&&{fetch:l},eventDispatcher:f,...n!==void 0&&{maxPaymentRetries:n},...p&&{onChallenge:p},...i&&{orderChallenges:i},methods:u,transport:s},h=lo(m);a&&uo(m);function g(e){return f.on(`challenge.received`,e)}function _(e){return f.on(`credential.created`,e)}function v(e){return f.on(`payment.failed`,e)}function y(e){return f.on(`payment.response`,e)}async function b(e,t){let n=es(e),r=await s.getChallenges(e,t?.request),a=Object.freeze(r.map(e=>X(e))),o=rs(d.entries,t?.acceptPayment),c,l;try{let e=(await is(va(r,u,o),t?.orderChallenges??i))[0];if(!e)throw Error(`No method found for challenges: ${r.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${u.map(e=>`${e.name}.${e.intent}`).join(`, `)}`);let d=e.challenge;c=a[e.index],l=e.method,c.expires&&Li(c.expires,c.id);let p=c,m=l,h=Yo(async e=>{try{p.expires&&Li(p.expires,p.id);let t=Yo(t=>as(p,m,t??e)),i=await f.emit(`challenge.received`,Xo({challenge:p,challenges:r,createCredential:t,method:m,response:n}))??await t();return Fo(i),await f.emit(`credential.created`,Zo({challenge:p,credential:i,method:m,response:n})),i}catch(e){throw await f.emit(`payment.failed`,Qo({challenge:p,challenges:r,error:e,method:m,response:n})),e}});return Object.freeze({challenge:p,challenges:a,createCredential:h,method:$o(m),setCredential(e,t){return Fo(t),s.setCredential(e,t,{challenge:d})}})}catch(e){throw await f.emit(`payment.failed`,Qo({challenge:c,challenges:r,error:e,method:l,response:n})),e}}return{fetch:h,rawFetch:c,methods:u,transport:s,on:f.on,onChallengeReceived:g,onCredentialCreated:_,onPaymentFailed:v,onPaymentResponse:y,preparePayment:b,async createCredential(e,t,n){return(await b(e,n)).createCredential(t)}}}function Jo(e,t){let n=Object.values(t);if(n.length===0)throw TypeError(`Mppx client attestation must configure at least one signer.`);return Ko(e,Go(...n))}function Yo(e){let t;return n=>(t??=e(n),t)}function Xo(e){return Object.freeze({challenge:X(e.challenge),challenges:e.challenges.map(e=>X(e)),createCredential:e.createCredential,method:$o(e.method),response:es(e.response)})}function Zo(e){return Object.freeze({challenge:X(e.challenge),credential:e.credential,method:$o(e.method),response:es(e.response)})}function Qo(e){return Object.freeze({...e.challenge?{challenge:X(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>X(e))}:{},error:e.error,...e.method?{method:$o(e.method)}:{},response:es(e.response)})}function $o(e){return ns(Object.assign({},e))}function es(e){if(e instanceof Response)try{return e.clone()}catch{return new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText})}return X(e)}function X(e){try{let t=structuredClone(e);if(e&&t&&typeof e==`object`&&typeof t==`object`)for(let n of Object.getOwnPropertySymbols(e)){let r=Object.getOwnPropertyDescriptor(e,n);r&&Object.defineProperty(t,n,r)}return ts(t)}catch{return ns(e)}}function ts(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))ts(t);return e}function ns(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function rs(e,t){return t?typeof t==`string`?ga(t):t:e}async function is(e,t){return t?t(e):e}async function as(e,t,n){let r=t.context&&n!==void 0?t.context.parse(n):void 0;return t.createCredential(r===void 0?{challenge:e}:{challenge:e,context:r})}const os=2048;var Z=class extends Error{name=`MppResourceUrlError`};function ss(e){if(e.length>os)throw new Z(`MPP resource URL is too long`);if(Array.from(e).some(e=>{let t=e.charCodeAt(0);return e===`\\`||t<=32||t===127}))throw new Z(`MPP resource URL is invalid`);let t=e.match(/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)(\?[^#]*)?(?:#.*)?$/);if(!t)throw new Z(`MPP resource URL must be absolute`);let n;try{n=new URL(e)}catch{throw new Z(`MPP resource URL is invalid`)}if(n.username||n.password)throw new Z(`MPP resource URL must not contain credentials`);let r=n.protocol.toLowerCase();if(r!==`https:`&&!(r===`http:`&&cs(n.hostname)))throw new Z(`MPP resource URL must use HTTPS or loopback HTTP`);let i=t[3]||`/`,a=t[4]||``,o=`${r}//${n.hostname.toLowerCase()}${n.port?`:${n.port}`:``}${i}${a}`;if(o.length>os)throw new Z(`MPP resource URL is too long`);return o}function cs(e){let t=e.toLowerCase();if(t===`localhost`||t===`[::1]`)return!0;let n=t.split(`.`);return n.length===4&&n[0]===`127`&&n.every(e=>/^\d{1,3}$/.test(e)&&Number(e)<=255)}const ls=/^[A-Za-z0-9_-]+$/,us=/^0x[0-9a-fA-F]{40}$/,ds=/^(?:0|[1-9]\d*)$/,fs=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/,ps=/^sha-256=:([A-Za-z0-9+/]{43}=):$/,ms=/^sha-256=([A-Za-z0-9+/]{43}=)$/,hs=new Set([`mpp_challenge_not_payable`,`mpp_network_mismatch`,`mpp_counterparty_rail_not_found`]),gs=`mpp_counterparty_rail_not_found`,_s=`mpp_network_mismatch`,vs=H({type:W(`authorization`),from:V(),to:V(),value:V(),validAfter:V(),validBefore:V(),nonce:V(),signature:V()}),ys={amount:V(),currency:V(),description:G(V()),externalId:G(V()),recipient:V()},bs=H({...ys,methodDetails:H({chainId:Vr(),credentialTypes:Yr(W(`authorization`)),decimals:W(6),permit2Address:G(V()),splits:G(qr())})}),xs=H({...ys,methodDetails:H({type:W(`evm`),evm:H({chainId:Vr(),credentialTypes:G(Yr(W(`authorization`))),decimals:W(6),permit2Address:G(V()),splits:G(qr())})})}),Ss=Ri({name:`evm`,intent:`charge`,schema:{credential:{payload:vs},request:bs}}),Cs=Ri({name:`usdc`,intent:`charge`,schema:{credential:{payload:vs},request:xs}});var ws=class extends Error{intentId;status;reasons;expiresAt;constructor(e,t){super(e),this.name=`MppPaymentError`,this.intentId=t.intentId,this.status=t.status,this.reasons=t.reasons,this.expiresAt=t.expiresAt}},Q=class extends Error{intentId;reasons;constructor(e,t={}){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.name=`MppFetchPaymentError`,this.intentId=t.intentId,this.reasons=t.reasons??[]}},Ts=class extends Q{accountId;requiredNetworks;constructor(e,t,n){super(`Account ${e} cannot pay on the MPP challenge's required network${t.length===1?``:`s`}: ${t.join(`, `)}`,{reasons:n}),this.name=`MppNetworkMismatchError`,this.accountId=e,this.requiredNetworks=t}},Es=class extends Q{recipient;network;constructor(e,t,n){super(`No saved Catena counterparty rail can pay ${e} on ${t}`,{reasons:n}),this.name=`MppCounterpartyNotFoundError`,this.recipient=e,this.network=t}},Ds=class extends Q{expiresAt;constructor(e,t,n){super(`The MPP payment is awaiting human approval (intent ${e}); retry the request after approval`,{intentId:e,reasons:t}),this.name=`MppApprovalPendingError`,this.expiresAt=n}},Os=class extends Q{status;constructor(e,t,n){super(`Catena ${t} the MPP payment (intent ${e})`,{intentId:e,reasons:n}),this.name=`MppPaymentDeclinedError`,this.status=t}},ks=class extends Q{method;atomicAmount;network;recipient;resourceUrl;constructor(e,t,n,r){super(`The MPP payment could not be confirmed (intent ${e}); reconcile it with getIntent("${e}") before paying again`,{intentId:e,cause:r}),this.name=`MppSubmitInterruptedError`,this.method=t.method,this.atomicAmount=t.atomicAmount,this.network=t.network,this.recipient=t.recipient,this.resourceUrl=n}},As=class extends Q{receipt;constructor(e,t){super(`The MPP payment completed (intent ${e.intentId}) but the post-payment continuation failed; inspect getIntent("${e.intentId}") before retrying manually`,{intentId:e.intentId,cause:t}),this.name=`MppRetryFailedError`,this.receipt=e}};function js(e){let t=async({challenge:t})=>(await Hs(e,Vs(t,e.maxAtomicAmount))).credential;return[zi(Ss,{canHandleChallenge:({challenge:t})=>Us(`evm`,t,e.maxAtomicAmount)!==void 0,createCredential:t}),zi(Cs,{canHandleChallenge:({challenge:t})=>Us(`usdc`,t,e.maxAtomicAmount)!==void 0,createCredential:t})]}const Ms=Object.assign(e=>js(e),{charge:js});function Ns(e,t){let n=(t.baseFetch??globalThis.fetch).bind(globalThis),r={client:e,accountId:t.accountId,...t.maxAtomicAmount!==void 0&&{maxAtomicAmount:t.maxAtomicAmount}},i=qo({methods:Ms(r),fetch:n,polyfill:!1});return async(a,o)=>{let s=await n(a,o);if(s.status!==402||!s.headers.has(`WWW-Authenticate`))return s;let c;try{c=await i.transport.getChallenges(s,o)}catch{return s}if(c.length===0)return s;if(!T(a,o))throw new Q(`The request body cannot be replayed after MPP payment; buffer it as a string, URLSearchParams, Blob, ArrayBuffer, or typed array`);let l=Ls(a,s),{payment:u,prepared:d}=await Ps(i,s,c,o,r,l),f={intentId:u.intentId,...u.terms,resourceUrl:l};await zs(f,async()=>{await t.onPayment?.(f)});let p=ae(a,o),m=d.setCredential({...o,headers:p},u.credential),h=await zs(f,()=>n(a,m));if(h.status===402)throw new As(f,Error(`The paid MPP retry still requires payment`));return Bs(e,f.intentId,h),h}}async function Ps(e,t,n,r,i,a){let o,s=[];for(let c=0;c<5;c+=1){let l={missing:!1},u;try{u=await e.preparePayment(t,{request:r,orderChallenges:e=>{o??=e.slice(0,5).map(e=>e.index);let t=o[c],n=e.find(e=>e.index===t);return l.missing=n===void 0,n===void 0?[]:[n]}})}catch(e){let t=o??[];if(t.length===0)throw n.some(e=>Ws(e,i.maxAtomicAmount))?new Q(`Every supported charge in the MPP challenge costs more than the caller's maximum amount`,{cause:e}):new Q(`The MPP challenge offers no Catena-supported native USDC charge`,{cause:e});if(l.missing&&s.length>0){if(c+1<t.length)continue;break}throw new Q(`The selected MPP challenge could not be prepared`,{cause:e})}let d=Vs(u.challenge,i.maxAtomicAmount);try{return{payment:await Hs(i,d,a),prepared:u}}catch(e){if(e instanceof ee&&e.code!==void 0&&hs.has(e.code))s.push({error:e,terms:d.terms});else throw Fs(e,d.terms,a)}if(c+1>=(o?.length??0))break}throw Is(i.accountId,s)}function Fs(e,t,n){if(e instanceof se&&e.outcome===`unknown`)return new ks(e.intentId,t,n,e);if(!(e instanceof ws))return e;switch(e.status){case`pending`:return new Ds(e.intentId,e.reasons,e.expiresAt);case`blocked`:case`failed`:return new Os(e.intentId,e.status,e.reasons);case`processing`:case`completed`:return new Q(e.message,{intentId:e.intentId,reasons:e.reasons,cause:e})}return S(e.status)}function Is(e,t){let n=t.filter(e=>e.error.code===gs),r=t.filter(e=>e.error.code===_s),i=t.filter(e=>e.error.code!==gs&&e.error.code!==_s),a=[...new Set([...n,...r,...i].map(e=>e.error.message))],o=n.find(e=>e.error.status===404);return o?new Es(o.terms.recipient,o.terms.network,a):r.length>0&&n.length===0?new Ts(e,[...new Set(r.map(e=>e.terms.network))],a):new Q(`No supported candidate in the MPP challenge is payable from this account`,{reasons:a})}function Ls(e,t){let n;try{n=typeof e==`string`?Rs(e):e instanceof URL?e:new URL(e.url)}catch(e){throw new Q(`The MPP resource request URL must be absolute`,{cause:e})}let r;try{r=new URL(t.url||n.href)}catch(e){throw new Q(`The final MPP resource URL is invalid`,{cause:e})}if(r.origin!==n.origin)throw new Q(`Refusing to pay after a cross-origin redirect from ${n.origin} to ${r.origin}`);try{return ss(t.url||n.href)}catch(e){throw new Q(`The final MPP resource URL cannot be bound to a payment intent`,{cause:e})}}function Rs(e){try{return new URL(e)}catch{return new URL(e,globalThis.location.href)}}async function zs(e,t){try{return await t()}catch(t){throw new As(e,t)}}function Bs(e,t,n){try{let r=Ui(n);if(!fe.test(r.reference))return;le(e,t,r.reference)}catch{return}}function Vs(e,t){let n=e.method;if(n!==`evm`&&n!==`usdc`)throw Error(`Unsupported Catena MPP challenge ${e.method}/${e.intent}`);let r=Us(n,e,t);if(r===void 0)throw Error(`Catena MPP charge challenge failed validation`);return{challenge:{id:e.id,realm:e.realm,method:n,intent:`charge`,request:r.request,...e.description!==void 0&&{description:e.description},...e.digest!==void 0&&{digest:e.digest},expires:r.expires,...r.header!==void 0&&{header:r.header},...e.opaque!==void 0&&{opaque:e.opaque}},terms:r.terms}}async function Hs(e,t,n){let r=await e.client.submitIntent({action:{type:`mpp`,accountId:e.accountId,challenge:t.challenge,...n!==void 0&&{resource:{url:n}}}});return{...t,credential:nc(r,t.challenge),intentId:r.id}}function Us(e,t,n){if(t.method!==e||t.intent!==`charge`)return;let r=Zs(t);if(r===void 0)return;let i=e===`evm`?qs(t.request,n):Js(t.request,n);return i===void 0?void 0:{...r,terms:i}}function Ws(e,t){if(t===void 0||e.method!==`evm`&&e.method!==`usdc`)return!1;let n=Us(e.method,e,void 0);return n!==void 0&&BigInt(n.terms.atomicAmount)>t}function Gs(e,t){return ec(e.amount)&&(t===void 0||BigInt(e.amount)<=t)&&tc(e.currency)&&tc(e.recipient)&&(e.description===void 0||Ks(e.description,1024))&&(e.externalId===void 0||Ks(e.externalId,256))}function Ks(e,t){if(e.length>t)return!1;for(let t of e){let e=t.codePointAt(0);if(e!==void 0&&e>=55296&&e<=57343)return!1}return!0}function qs(e,t){let n=bs.safeParse(e);if(!n.success||!Gs(n.data,t))return;let{amount:r,currency:i,methodDetails:a,recipient:o}=n.data,s=Xs(a.chainId,i);return Ys(a)&&a.credentialTypes.length===1&&s!==void 0?{method:`evm`,atomicAmount:r,network:s,recipient:o}:void 0}function Js(e,t){let n=xs.safeParse(e);if(!n.success||!Gs(n.data,t))return;let{amount:r,currency:i,methodDetails:a,recipient:o}=n.data,s=a.evm,c=Xs(s.chainId,i);return Ys(s)&&(s.credentialTypes===void 0||s.credentialTypes.length===1)&&c!==void 0?{method:`usdc`,atomicAmount:r,network:c,recipient:o}:void 0}function Ys(e){return Number.isSafeInteger(e.chainId)&&e.chainId>=1&&(e.permit2Address===void 0||tc(e.permit2Address))}function Xs(e,t){if(e===8453)return t.toLowerCase()===`0x833589fcd6edb6e08f4c7c32d4f71b54bda02913`?`eip155:8453`:void 0;if(e===84532)return t.toLowerCase()===`0x036cbd53842c5426634e7929541ec2318f3dcf7e`?`eip155:84532`:void 0}function Zs(e){if(!Qs(e))return;let t=Date.parse(e.expires),n=t-Date.now();if(!Number.isFinite(t)||n<5e3||n>36e5)return;let r=A(e.request),i=new TextEncoder().encode(JSON.stringify({...e,request:r})).byteLength;return r.length>0&&r.length<=16384&&i<=32768?{request:r,expires:e.expires,header:e.header}:void 0}function Qs(e){return!(e.id.length<1||e.id.length>256||e.realm.length<1||e.realm.length>256||e.expires===void 0||!fs.test(e.expires)||e.description!==void 0&&e.description.length>1024||e.header!==void 0&&e.header!==`Payment-Authorization`||e.opaque!==void 0&&(e.opaque.length>8192||!ls.test(e.opaque))||e.digest!==void 0&&!$s(e.digest))}function $s(e){if(e.length>128)return!1;let t=ps.exec(e)??ms.exec(e);if(!t)return!1;try{let e=atob(t[1]);return e.length===32&&btoa(e)===t[1]}catch{return!1}}function ec(e){return e.length<=78&&ds.test(e)&&BigInt(e)>0n}function tc(e){return us.test(e)&&_t(e)}function nc(e,t){switch(e.status){case`completed`:{let n=_(e.data,`mpp`);if(n===void 0)throw $(`Catena MPP payment ${e.id} completed without an MPP credential`,e);if(!rc(n,t))throw $(`Catena MPP payment ${e.id} completed with a credential that does not match the selected challenge; reconcile with client.getIntent("${e.id}") before another payment attempt`,e);return n}case`pending`:throw $(`Catena MPP payment ${e.id} is pending${ac(e.reasons)}`,e);case`processing`:throw $(`Catena MPP payment ${e.id} is processing; if it was approved, re-run the paid request so a fresh challenge can consume the grant (polling never advances an approved payment); otherwise poll client.getIntent("${e.id}"), because an executing payment completes on its own`,e);case`blocked`:throw $(`Catena MPP payment ${e.id} was blocked${ac(e.reasons)}`,e);case`failed`:throw $(`Catena MPP payment ${e.id} failed${ac(e.reasons)}`,e)}return S(e.status)}function rc(e,t){if(e.trim().length===0||e.includes(`\r`)||e.includes(`
|
|
14
|
-
`))return!1;let n;try{n=ji(e)}catch{return!1}let r=n.challenge;if(r.id!==t.id||r.realm!==t.realm||r.method!==t.method||r.intent!==t.intent||r.description!==t.description||r.digest!==t.digest||r.expires!==t.expires||r.header!==t.header||r.opaque!==t.opaque||A(r.request)!==t.request)return!1;let i=vs.safeParse(n.payload),a=t.method===`evm`?bs.safeParse(r.request):xs.safeParse(r.request);if(!i.success||!a.success)return!1;let o=a.data.recipient;return tc(i.data.from)&&tc(i.data.to)&&i.data.to.toLowerCase()===o.toLowerCase()&&i.data.value===a.data.amount&&ic(i.data.validAfter)&&ic(i.data.validBefore)&&BigInt(i.data.validBefore)>BigInt(i.data.validAfter)&&/^0x[0-9a-fA-F]{64}$/.test(i.data.nonce)&&/^0x[0-9a-fA-F]{130}$/.test(i.data.signature)}function ic(e){return e.length<=78&&ds.test(e)}function $(e,t){return new ws(e,{intentId:t.id,status:t.status,reasons:t.reasons,expiresAt:t.expiresAt})}function ac(e){return e.length>0?`: ${e.join(`; `)}`:``}function oc(e){return{intentId:e.intentId,method:e.method,amountAtomicUsdc:e.atomicAmount,recipient:e.recipient,network:e.network}}const sc=/(?:^|,)\s*Payment(?![!#$%&'*+\-.^_`|~0-9A-Za-z])/i;function cc(e,t){de(e,`payment-authorization`)&&b(`--header cannot set Payment-Authorization; the payment loop attaches it after paying`),e.some(e=>e.name.toLowerCase()===`authorization`&&sc.test(e.value))&&b(`--header cannot provide the Payment authentication scheme in Authorization; the payment loop attaches it after paying`),pe(e,t)}const lc=v({url:x({description:`The paywalled URL to fetch (an MPP endpoint)`,required:!0,schema:Se.pipe(Se.string(),Se.url())}),account:x({description:`Source wallet account id the payment draws from`,required:!0,schema:be}),maxAmount:x({description:`Refuse challenges above this USD amount (decimal string, e.g. 0.25). Policy limits still apply server-side.`,schema:Se.pipe(Se.string(),Se.regex(/^\d+(\.\d{1,6})?$/))}),method:ne({description:`HTTP method for the request`,choices:[`GET`,`POST`]}),data:x({description:`Request body. Use @path to read a file or @- for stdin. Implies POST and a JSON content type unless overridden.`}),contentType:x({description:`Content-Type header for the request body (default application/json when --data is set)`}),output:x({description:`Write the full response body to this file (must be a regular file; written for any HTTP status — check .status). Without it .body is capped at 4000 characters; longer or non-UTF-8 bodies are saved to a file (path reported in .bodyPath)`}),header:ye({description:`Request header as "Name: Value" (repeatable, like curl -H); sent on both requests, except caller Authorization is replaced on the paid retry when MPP uses that field for its credential`,schema:w}),profile:te,json:ve}),uc=xe({meta:{name:`mpp`,description:`Fetch a URL, paying its MPP challenge via USDC`},args:lc.args,async run({args:e,rawArgs:t}){let n=lc.parse(e,t),r=n.method??(n.data===void 0?`GET`:`POST`);n.data!==void 0&&r!==`POST`&&b(`--data cannot be sent with --method ${r}; a body requires POST`),n.contentType!==void 0&&n.data===void 0&&b(`--content-type has no effect without --data`),cc(n.header,n.contentType);let i=n.output===void 0?void 0:ue(n.output),a=n.data===void 0?void 0:re(n.data),o=oe(n.header,n.contentType,a);await _e(n)(async e=>{let t,s=Ns(e,{accountId:n.account,...n.maxAmount!==void 0&&{maxAtomicAmount:ie(n.maxAmount)},onPayment:e=>{t=e}}),c;try{c=await s(n.url,{method:r,...a!==void 0&&{body:a},...o!==void 0&&{headers:o}})}catch(e){if(e instanceof ks&&e.intentId!==void 0)throw Error(ge(e.intentId,n.profile),{cause:e});if(e instanceof As)return{status:null,paid:!0,retryFailed:!0,payment:oc(e.receipt),error:e.message};if(e instanceof Ts){let t=e.requiredNetworks.map(e=>me(e)??e);return{status:null,paid:!1,retryFailed:!1,networkMismatch:{account:e.accountId,requiredNetworks:t,requiredNetworkIds:[...e.requiredNetworks]},error:`${e.message}. Re-run with --account set to a wallet account on ${t.join(` or `)} (your account ids are in \`catena accounts list${ce(n.profile)}\`).`}}if(e instanceof Es){let t=C(e.recipient,e.network,void 0,n.profile);return{status:null,paid:!1,retryFailed:!1,counterpartyNotFound:{recipient:e.recipient,network:me(e.network)??e.network,networkId:e.network,createCommand:t,nameIsPlaceholder:!0},error:`${e.message}. Add it, then re-run:\n ${t}\n(counterparty creation may require approval per your policy)`}}if(e instanceof Ds)return{status:null,paid:!1,retryFailed:!1,approvalPending:{intentId:e.intentId,expiresAt:e.expiresAt,reasons:[...e.reasons]},error:e.message};throw e}let l={status:c.status,paid:t!==void 0,retryFailed:!1,...t!==void 0&&{payment:oc(t)}},u;try{u=Buffer.from(await c.arrayBuffer())}catch(e){let r=t===void 0?``:`; the payment completed — inspect it with \`catena intents get ${t.intentId}${ce(n.profile)}\` before any manual retry`;return{...l,error:`failed to read the response body: ${y(e)}${r}`}}return{...l,...he(u,t?.intentId,i)}},{exitCode:e=>+(`error`in e)})}});export{uc as mppCommand};
|