mppx 0.17.5 → 0.17.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/cli/cli.js +14 -12
  3. package/dist/cli/stripe.d.ts +6 -1
  4. package/dist/cli/stripe.js +89 -5
  5. package/dist/client/Mppx.js +1 -0
  6. package/dist/extensions/identity/email-otp/Constants.d.ts +16 -0
  7. package/dist/extensions/identity/email-otp/Constants.js +16 -0
  8. package/dist/extensions/identity/email-otp/Types.d.ts +12 -0
  9. package/dist/extensions/identity/email-otp/Types.js +2 -0
  10. package/dist/extensions/identity/email-otp/client/index.d.ts +116 -0
  11. package/dist/extensions/identity/email-otp/client/index.js +119 -0
  12. package/dist/extensions/identity/email-otp/index.d.ts +17 -0
  13. package/dist/extensions/identity/email-otp/index.js +16 -0
  14. package/dist/extensions/identity/email-otp/internal/Attestation.d.ts +66 -0
  15. package/dist/extensions/identity/email-otp/internal/Attestation.js +128 -0
  16. package/dist/extensions/identity/email-otp/internal/Constants.d.ts +20 -0
  17. package/dist/extensions/identity/email-otp/internal/Constants.js +20 -0
  18. package/dist/extensions/identity/email-otp/internal/Jwks.d.ts +30 -0
  19. package/dist/extensions/identity/email-otp/internal/Jwks.js +114 -0
  20. package/dist/extensions/identity/email-otp/internal/Prover.d.ts +46 -0
  21. package/dist/extensions/identity/email-otp/internal/Prover.js +168 -0
  22. package/dist/extensions/identity/email-otp/internal/Types.d.ts +48 -0
  23. package/dist/extensions/identity/email-otp/internal/Types.js +2 -0
  24. package/dist/extensions/identity/email-otp/internal/Verifier.d.ts +56 -0
  25. package/dist/extensions/identity/email-otp/internal/Verifier.js +116 -0
  26. package/dist/extensions/identity/email-otp/server/index.d.ts +48 -0
  27. package/dist/extensions/identity/email-otp/server/index.js +56 -0
  28. package/dist/extensions/identity/index.d.ts +2 -0
  29. package/dist/extensions/identity/index.js +2 -0
  30. package/dist/identity/Callback.d.ts +47 -0
  31. package/dist/identity/Callback.js +64 -0
  32. package/dist/identity/index.d.ts +1 -0
  33. package/dist/identity/index.js +1 -0
  34. package/dist/internal/version.d.ts +2 -2
  35. package/dist/internal/version.js +1 -1
  36. package/dist/proxy/internal/Headers.js +2 -0
  37. package/dist/tempo/server/internal/html.gen.js +1 -1
  38. package/package.json +5 -1
package/dist/cli/cli.js CHANGED
@@ -226,7 +226,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
226
226
  `)===-1&&e.indexOf(`\r`)===-1)return;let i=0,a=t.indexOf(`
227
227
  `),s=t.indexOf(`\r`);for(;a!==-1||s!==-1;){let e=a===-1?s:s===-1?a:Math.min(a,s);o(t.slice(i,e)),i=e+1,e===s&&(i===t.length?r=!0:a===i&&i++,s=t.indexOf(`\r`,i)),a!==-1&&a<i&&(a=t.indexOf(`
228
228
  `,i))}t=t.slice(i)}}}var DC=F((()=>{}));function OC(e){let{extensions:t,resource:n,...r}=e;return HC.parse(r)}var kC,AC,jC,MC,NC,PC,FC,IC,LC,RC,zC,BC,VC,HC,UC,WC,GC,KC,qC,JC,YC,XC,ZC=F((()=>{nS(),kC=`charge`,AC=[`exact`],jC=`eip155:`,MC=`x402:`,NC=`PAYMENT-REQUIRED`,PC=`PAYMENT-SIGNATURE`,FC=`PAYMENT-RESPONSE`,IC=J.string().check(J.minLength(1)),LC=J.number().check(J.refine(e=>e>0,`Must be positive`)),RC=J.string().check(J.regex(/^\d+$/,`Invalid atomic amount`)),zC=Zx(),BC=J.string().check(J.regex(RegExp(`^${jC}\\d+$`),`Invalid EVM CAIP-2 network`)),VC=J.object({description:J.optional(J.string()),iconUrl:J.optional(J.string()),mimeType:J.optional(J.string()),serviceName:J.optional(J.string()),tags:J.optional(J.array(J.string())),url:IC}),J.discriminatedUnion(`type`,[J.object({name:IC,type:J.literal(`eip3009`),version:IC}),J.object({name:J.optional(J.string()),type:J.literal(`permit2`),version:J.optional(J.string())})]),HC=J.object({amount:RC,asset:IC,extra:J.optional(J.record(J.string(),J.unknown())),maxTimeoutSeconds:LC,network:BC,payTo:IC,scheme:J.enum(AC)}),UC=J.object({info:J.record(J.string(),J.unknown()),schema:J.record(J.string(),J.unknown())}),WC=J.record(J.string(),UC),GC=J.object({accepts:J.array(HC).check(J.minLength(1)),error:J.optional(J.string()),extensions:J.optional(WC),resource:VC,x402Version:J.literal(2)}),KC=J.object({authorization:J.object({from:zC,nonce:Qx(),to:zC,validAfter:RC,validBefore:RC,value:RC}),signature:eS()}),qC=J.object({permit2Authorization:J.object({deadline:RC,from:zC,nonce:RC,permitted:J.object({amount:RC,token:zC}),spender:zC,witness:J.object({to:zC,validAfter:RC})}),signature:eS()}),JC=J.union([KC,qC]),YC=J.object({accepted:HC,extensions:J.optional(WC),payload:JC,resource:J.optional(VC),x402Version:J.literal(2)}),J.object({extensions:J.optional(WC),extra:J.optional(J.record(J.string(),J.unknown())),invalidMessage:J.optional(J.string()),invalidReason:J.optional(J.string()),isValid:J.boolean(),payer:J.optional(J.string())}),XC=J.object({amount:J.optional(RC),errorMessage:J.optional(J.string()),errorReason:J.optional(J.string()),extensions:J.optional(WC),extra:J.optional(J.record(J.string(),J.unknown())),network:IC,payer:J.optional(J.string()),success:J.boolean(),transaction:J.string()})}));function QC(e,t,n){let r=new Headers(e.headers);for(let e of $C)e===q.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}var $C,ew=F((()=>{Bx(),ZC(),$C=[q.authorization,NC,FC,PC]}));function tw(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}}function nw(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t?.method===`tools/call`&&t.params?._meta?.[`mppx/payment-client`]===!0}catch{return!1}}function rw(e){let t=tw(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 iw(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 aw(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=SS.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 ow(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:aw(e.error.data):aw(e.result?._meta?.[wC])}function sw(e,t){return!e||e.id!==t?[]:ow(e)?.challenges??[]}async function cw(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=EC(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=iw(JSON.parse(e.data))}catch{}});try{for(;;){if(i)return a;let{done:e,value:s}=await t.read();if(e)return o.feed(n.decode()),a;if(r+=s.byteLength,r>fw)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function lw(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=``;try{for(;;){let{done:e,value:a}=await t.read();if(e)return iw(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>fw)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function uw(e){let t=pw.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>fw)){if(t.includes(`application/json`))return lw(e);if(t.includes(`text/event-stream`))return cw(e)}})();return pw.set(e,n),n}function dw(){return{getChallenges(e,t){let n=rw(t);return e.status===402||n===void 0?[]:uw(e).then(e=>sw(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=MS(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,[CC]:r}}})}}}}var fw,pw,mw=F((()=>{CS(),VS(),DC(),TC(),ew(),fw=1048576,pw=new WeakMap}));function hw(){return{getChallenges(e){let t=e.headers.get(q.wwwAuthenticate);return e.status!==402||!t||!fS(t)?[]:mS(e)},setCredential(e,t,n){return QC(e,n?.challenge?vS(n.challenge):q.authorization,t)}}}var gw=F((()=>{CS(),Bx(),ew()}));function _w(e){return{encode(t){return A.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(A.toString(t)))}catch{throw new vw}}}}var vw,yw=F((()=>{vw=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}}}));function bw(e){try{let t=JSON.parse(A.toString(e));return Ew(t)}catch{throw new vw}}var xw,Sw,Cw,ww,Tw,Ew,Dw=F((()=>{yw(),ZC(),xw=_w(GC),Sw=_w(YC),Cw=_w(XC),ww=xw.encode,xw.decode,Tw=Sw.encode,Sw.decode,Cw.encode,Cw.decode,Ew=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new vw;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new vw;let n=VC.parse(t.resource),r=t.extensions===void 0?void 0:WC.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}}}));function Ow(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(NC);if(!t)return[];let n=bw(t);return n.accepts.flatMap((e,t)=>{let r=HC.safeParse(e);if(!r.success)return[];let i=r.data;return QS(rS({id:`${MC}${t}`,intent:kC,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return QC(e,PC,t)}}}var kw=F((()=>{CS(),Dw(),tC(),ZC(),ew()}));function Aw(e){return e}function jw(){let e=[hw(),Ow(),dw()],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 Aw({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)}})}var Mw=F((()=>{mw(),gw(),ew(),kw()}));function Nw(e,t){return Lw.set(e,t),e}function Pw(e){return Lw.has(e)}function Fw(e,t){return Promise.resolve(Lw.get(e)?.(t))}function Iw(e){return Lw.get(e)}var Lw,Rw=F((()=>{Lw=new WeakMap}));function zw(e,t){return Jw.set(e,t),e}function Bw(e){Jw.delete(e)}function Vw(e,t,n){Jw.has(e)&&Yw.set(t,n)}function Hw(e){return Yw.get(e)}function Uw(e,t){return Promise.resolve(Jw.get(e)?.(t)??t.response)}function Ww(e,t){return Zw.set(e,t),e}function Gw(e,t){try{return Zw.get(e)?.(t)}catch{return}}function Kw(e,t){Xw.set(e,t)}function qw(e){return Xw.get(e)??Yw.get(e)?.origin}var Jw,Yw,Xw,Zw,Qw=F((()=>{Jw=new WeakMap,Yw=new WeakMap,Xw=new WeakMap,Zw=new WeakMap}));function $w(e,t,n){if(!tT(e)&&(e.method!==`tempo`||e.intent!==`session`))return;t=typeof t==`function`?t():t;let{realm:r}=e;if(r.toLowerCase()===t.hostname.toLowerCase())return;let i=t.origin.toLowerCase();for(let[e,t]of Object.entries(n??{}))if(t===r&&nT(e)===i)return;throw Error(`Refusing to sign Tempo proof for realm ${JSON.stringify(r)} from ${t.origin}. Pin the realm to this origin with \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function eT(e,t){if(!(!tT(e)&&(e.method!==`tempo`||e.intent!==`session`))&&!t?.includes(e.realm))throw Error(`Refusing to sign Tempo proof for untrusted realm ${JSON.stringify(e.realm)}. Add it to \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function tT(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function nT(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}var rT=F((()=>{}));async function iT(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},YT);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>JT){i=!0;break}}}finally{clearTimeout(a),t.cancel().catch(()=>{})}if(!i)return e;e.body.cancel().catch(()=>{});let o=new Headers(e.headers);o.delete(`content-length`),o.set(XT,`true`);let s=new Response(new Blob(n).slice(0,JT),{headers:o,status:e.status,statusText:e.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{value:e[t]});return s}async function aT(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 oT(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=qT,methods:a,onChallenge:o,orderChallenges:s,transport:c=jw(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&AT(e.fetch)),d=e.eventDispatcher??lT(),f=t??rC(a),p=jT(r),m=async(e,t,n)=>u?(await u.send(p,new Request(e,t),n)).response:p(e,t),h=async(e,t,r)=>{let g=kT(e,t?.headers),_=g.has(q.acceptPayment),v=IT(g,f),y=DT(e,t,g),b=ET(e,t,g,v.header,_,n),x=await m(MT(b.input),b.init),S=OT(b.init,await y);if(t?.[KT]||nw(S)||!await c.isPaymentRequired(x,S))return x;let C=t?.context,{context:w,orderChallenges:T,...E}=S??{},ee,D,O,k,A;try{for(let n=0;n<i;n++){D=await c.getChallenges(x,S);let i=(await LT(sC(D,a,v.entries,C),T??s))[0];if(!i){if(await aT(k,{challenges:D,response:x,status:`rejected`}),n>0)return x;throw Error(`No method found for challenges: ${D.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let f=i.challenge;ee=f,O=i.method,ee.expires&&AS(ee.expires,ee.id),await u?.challenge(x,{challenge:f},VT(b.input).href);let g=await UT(x,b.input,b.input,E);$w(f,()=>VT(g),l);let _=k,y=iS(f),w=_?.method===i.method&&_?.key===y,te=!1;if(_){let e=await aT(_,{challenges:D,response:x,status:w?`pending`:`rejected`});te=w&&!e}k=te?_:void 0;let ne=mT(async n=>{if(n===void 0&&te&&_)return _.promise;te&&_&&(await aT(_,{status:`rejected`}),k=void 0),NT(e,t)?.throwIfAborted();let r=n??C;if(!Pw(i.method))return FT(f,i.method,r);let a={origin:VT(g).origin,prepare:()=>Fw(i.method,{challenge:f,context:r,fetch:u?KS(p,u,{challenge:f}):p,input:g,signal:NT(e,t)})},o=a.prepare().then(()=>FT(f,i.method,r,a));return k={context:r,attempt:a,key:n===void 0?y:void 0,method:i.method,promise:o},o}),j=await d.emit(`challenge.received`,hT({challenge:f,challenges:D,createCredential:ne,init:t,input:e,method:i.method,response:x}))??(o?await o(ee,{createCredential:ne}):void 0)??await ne(),re=k;re&&await re.promise.catch(()=>void 0)!==j&&(await aT(re,{status:`rejected`}),k=void 0);let M=k?k.context:C;PT(j),await d.emit(`credential.created`,gT({challenge:f,credential:j,init:t,input:e,method:i.method,response:x}));let ie=e=>new DS({cause:e,challenge:f,credential:j,transactionHash:Gw(i.method,j)});try{x=await m(g,{...c.setCredential({...E,headers:b.headers},j,{challenge:f}),redirect:`manual`},{challenge:f})}catch(e){throw A=ie(e),e}let ae=await c.isPaymentRequired(x,S);if(ae||(await aT(re,{response:x,status:x.status>=300&&x.status<400?`pending`:x.ok?`accepted`:`rejected`}),k=void 0),x.ok&&uT(d,`payment.response`)&&await d.emit(`payment.response`,_T({challenge:f,credential:j,init:t,input:e,method:i.method,response:x})),!ae){if(x.status>=500&&uT(d,`payment.failed`)){try{x=await iT(x)}catch(e){throw A=ie(e),x=new Response(null,{headers:x.headers,status:x.status,statusText:x.statusText}),e}await d.emit(`payment.failed`,vT({challenge:f,challenges:D,error:ie(),init:t,input:e,method:i.method,response:x}))}return x.ok?Uw(i.method,{context:M,challenge:f,credential:j,fetch:p,headers:b.headers,input:g,...r?{refetch:()=>h(MT(b.input),t,!1)}:{},response:x,signal:NT(e,t)}):x}}D=void 0;try{D=await c.getChallenges(x,S)}catch{}return await aT(k,{challenges:D,response:x,status:`rejected`}),x}catch(n){throw await aT(k,{challenges:D,response:x,status:`rejected`}),await d.emit(`payment.failed`,vT({challenge:ee,challenges:D,error:A??n,init:t,input:e,method:O,response:x})),n}},g=(e,t)=>h(e,t,!0);return g[WT]=p,u&&(g[GT]=u),g}function sT(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);ZT||=globalThis.fetch,globalThis.fetch=oT({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??(BT()?`same-origin`:`always`),fetch:jT(globalThis.fetch)})}function cT(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return Array.isArray(e)?Object.fromEntries(e):e}function lT(){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 dT(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await pT(e[`*`],t,n),r}case`credential.created`:await fT(e[`credential.created`],n),await pT(e[`*`],t,n);return;case`payment.failed`:await fT(e[`payment.failed`],n),await pT(e[`*`],t,n);return;case`payment.response`:await fT(e[`payment.response`],n),await pT(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 QT.set(t,t=>e[t].size>0||e[`*`].size>0),t}function uT(e,t){return QT.get(e)?.(t)??!0}async function dT(e,t){try{return await e(t)}catch{return}}async function fT(e,t){for(let n of e)try{await n(t)}catch{}}async function pT(e,t,n){await fT(e,Object.freeze({name:t,payload:n}))}function mT(e){let t;return n=>(t??=e(n),t)}function hT(e){return Object.freeze({challenge:CT(e.challenge),challenges:e.challenges.map(e=>CT(e)),createCredential:e.createCredential,init:yT(e.init),input:bT(e.input),method:xT(e.method),response:ST(e.response)})}function gT(e){return Object.freeze({challenge:CT(e.challenge),credential:e.credential,init:yT(e.init),input:bT(e.input),method:xT(e.method),...e.response===void 0?{}:{response:ST(e.response)}})}function _T(e){return Object.freeze({challenge:CT(e.challenge),credential:e.credential,init:yT(e.init),input:bT(e.input),method:xT(e.method),response:ST(e.response)})}function vT(e){return Object.freeze({...e.challenge?{challenge:CT(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>CT(e))}:{},error:e.error,init:yT(e.init),input:bT(e.input),...e.method?{method:xT(e.method)}:{},...e.response===void 0?{}:{response:ST(e.response)}})}function yT(e){if(e)return TT({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function bT(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function xT(e){return TT(Object.assign({},e))}function ST(e){if(e instanceof Response)try{return e.clone()}catch{let t=new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText});for(let n of[`redirected`,`type`,`url`])Object.defineProperty(t,n,{value:e[n]});return t}return CT(e)}function CT(e){try{return wT(structuredClone(e))}catch{return TT(e)}}function wT(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))wT(t);return e}function TT(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function ET(e,t,n,r,i,a){let o=!!r&&!i&&RT(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(q.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function DT(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 OT(e,t){return t===void 0?e:{...e,body:t}}function kT(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function AT(e){return e[GT]}function jT(e){let t=e;for(;t[WT];)t=t[WT];return t}function MT(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function NT(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function PT(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
229
- `))throw Error(`Credential header value contains illegal newline characters`)}async function FT(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?.origin&&Kw(a,r.origin),r&&Vw(t,a,r),t.createCredential(a)}function IT(e,t){let n=e.get(q.acceptPayment);if(!n)return t;try{return{...t,entries:iC(n),header:n}}catch{return t}}async function LT(e,t){return t?t(e):e}function RT(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=VT(e);return t===`same-origin`?!BT()||n.origin===globalThis.location.origin:t.origins.some(e=>zT(n,e))}function zT(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 BT(){return globalThis.location!==void 0}function VT(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,BT()?globalThis.location.href:void 0)}function HT(e,t){let n=e instanceof Request?e:void 0;if((t.mode??n?.mode)===`no-cors`)throw Error(`Cannot automatically pay a no-cors request: it cannot carry a credential.`);if((t.cache??n?.cache)===`only-if-cached`)throw Error(`Cannot automatically pay an only-if-cached request: its retry cannot reach the server.`)}async function UT(e,t,n,r){if(HT(t,r),!e.url)return t;let i=new URL(e.url),a=VT(n);if(i.origin!==a.origin)throw Error(`Refusing to send payment credential across redirect from ${a.origin} to ${i.origin}`);let o=(r.method??(t instanceof Request?t.method:`GET`)).toUpperCase();if(e.redirected&&o!==`GET`&&o!==`HEAD`)throw Error(`Cannot automatically pay a redirected ${o} request. Use prepareRequest() to preserve redirect semantics.`);if(t instanceof Request){let n=r.body==null?t.clone():t,i=new Request(n,t.mode===`navigate`&&r.mode===void 0?{...r,mode:`same-origin`}:r);return i.url.split(`#`)[0]===e.url?i:i.body?new Request(e.url,{body:await i.arrayBuffer(),cache:i.cache,credentials:i.credentials,headers:i.headers,integrity:i.integrity,keepalive:i.keepalive,method:i.method,mode:i.mode,redirect:i.redirect,referrer:i.referrer,referrerPolicy:i.referrerPolicy,signal:i.signal}):new Request(e.url,i)}return e.url}var WT,GT,KT,qT,JT,YT,XT,ZT,QT,$T=F((()=>{CS(),Bx(),kS(),jS(),ZS(),SC(),Mw(),Rw(),Qw(),rT(),mw(),WT=Symbol.for(`mppx.fetch.wrapper`),GT=Symbol.for(`mppx.fetch.identity`),KT=Symbol.for(`mppx.fetch.skipPayment`),qT=3,JT=65536,YT=2e3,XT=`Mppx-Body-Truncated`,QT=new WeakMap}));Nx(),Bx(),jS(),ZS(),SC(),$T(),Rw(),Qw(),rT(),Mw();const eE=new WeakMap;function tE(e){let{identity:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=jw(),trustedTempoProofRealms:c}=e;if(`attestation`in e)throw TypeError("Mppx client `attestation` was replaced by `identity: [prover]`.");let l=jT(e.fetch??globalThis.fetch),u=t?WS(t):e.fetch&&AT(e.fetch),d=e.methods.flat(),f=rC(d,e.paymentPreferences),p=lT(),m=r,h={acceptPayment:f,acceptPaymentPolicy:o,...e.fetch&&{fetch:l},...u&&{identity:u},eventDispatcher:p,...n!==void 0&&{maxPaymentRetries:n},...m&&{onChallenge:m},...i&&{orderChallenges:i},methods:d,transport:s,...c&&{trustedTempoProofRealms:c}},g=oT(h);a&&sT(h);function _(e){return p.on(`challenge.received`,e)}function v(e){return p.on(`credential.created`,e)}function y(e){return p.on(`payment.failed`,e)}function b(e){return p.on(`payment.response`,e)}async function x(e,t,n){let r=hE(e),a=await s.getChallenges(e,t?.request),o=Object.freeze(a.map(e=>gE(e))),l=yE(f.entries,t?.acceptPayment),u,m;try{let f=sC(a,d,l,n);f.length===0&&n===void 0&&(f=sC(a,d,l,xC));let h=(await bE(f,t?.orderChallenges??i))[0];if(!h)throw Error(`No method found for challenges: ${a.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${d.map(e=>`${e.name}.${e.intent}`).join(`, `)}`);let g=h.challenge;u=o[h.index],m=h.method,u.expires&&AS(u.expires,u.id);let _=SE(e);_?$w(u,_,c):s.name===`mcp`&&eT(u,c&&Object.values(c));let v=u,y=m,b=uE(async e=>{try{v.expires&&AS(v.expires,v.id);let t=uE(t=>xE(v,y,t??e,_?.origin)),n=await p.emit(`challenge.received`,dE({challenge:v,challenges:a,createCredential:t,method:y,response:r}))??await t();return PT(n),await p.emit(`credential.created`,fE({challenge:v,credential:n,method:y,response:r})),n}catch(e){throw await p.emit(`payment.failed`,pE({challenge:v,challenges:a,error:e,method:y,response:r})),e}}),x=Object.freeze({challenge:v,challenges:o,createCredential:b,method:mE(y),setCredential(e,t){return PT(t),s.setCredential(e,t,{challenge:g})}});return eE.set(x,y),x}catch(e){throw await p.emit(`payment.failed`,pE({challenge:u,challenges:a,error:e,method:m,response:r})),e}}async function S(e,t,n){let{maxRedirects:r=20,requirePayment:i=!1,...a}=n??{},d=await aE({acceptPayment:f.header,acceptPaymentPolicy:o,fetch:l,init:t,input:e,maxRedirects:r,identity:u}),p=oE(d.replayRequest,d.body);if(!await s.isPaymentRequired(d.response,p)){if(i)throw Error(`Response does not require payment.`);return Object.freeze({payment:void 0,request:d.request,response:d.response,redirects:d.redirects})}let m=await x(d.response,{...a,request:p});$w(m.challenge,new URL(d.replayRequest.url),c);let h=eE.get(m)??m.method,g=uE(async e=>(await u?.challenge(d.response,{challenge:m.challenge},d.replayRequest.url),Pw(h)&&await Fw(h,{challenge:m.challenge,context:e,fetch:u?KS(l,u,{challenge:m.challenge}):l,input:d.replayRequest,signal:d.replayRequest.signal}),m.createCredential(e))),_=Object.freeze({...m,createCredential:g,async pay(e){let t=await g(e),n=m.setCredential(oE(d.replayRequest,d.body),t),r=new Request(d.replayRequest.url,{...n,redirect:`manual`});if(!u)return l(r);let{response:i}=await u.send(l,r,{challenge:m.challenge});return i}});return Object.freeze({payment:_,request:d.request,response:d.response,redirects:d.redirects})}return{fetch:g,rawFetch:l,methods:d,transport:s,on:p.on,onChallengeReceived:_,onCredentialCreated:v,onPaymentFailed:y,onPaymentResponse:b,preparePayment:x,prepareRequest:S,async createCredential(e,t,n){return(await x(e,n,t)).createCredential(t)}}}const nE=new Set([301,302,303,307,308]),rE=[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`,`transfer-encoding`],iE=[`authorization`,`cookie`,`cookie2`,`host`,`payment-authorization`,`payment-signature`,`proxy-authorization`,`x-payment`];async function aE(e){let{acceptPayment:t,acceptPaymentPolicy:n,fetch:r,identity:i,init:a,input:o,maxRedirects:s}=e;if(!Number.isInteger(s)||s<0)throw TypeError(`maxRedirects must be a non-negative integer.`);let c=new Request(o,{...a,redirect:`manual`}),l=c.headers.has(q.acceptPayment),u=await sE(c,a?.body),d=[];for(;;){c=cE(c,t,l,n);let{request:e,response:a}=await(async()=>{if(i)return i.send(r,c.clone());let e=c.clone();return{request:e,response:await r(e)}})();if(a.type===`opaqueredirect`||a.status===0)throw Error(`prepareRequest requires a runtime that exposes manual redirect responses.`);if(!nE.has(a.status))return{body:u,replayRequest:c,request:e,response:a,redirects:Object.freeze(d)};let o=a.headers.get(`location`);if(!o)return{body:u,replayRequest:c,request:e,response:a,redirects:Object.freeze(d)};if(d.length>=s)throw await a.body?.cancel(),Error(`Payment request exceeded ${s} redirects.`);let f=new URL(c.url),p=new URL(o,f);if(f.protocol===`https:`&&p.protocol!==`https:`)throw await a.body?.cancel(),Error(`Payment request refused HTTPS downgrade redirect to ${p.href}`);let m=new Headers(c.headers),h=c.method;if((a.status===301||a.status===302)&&h===`POST`||a.status===303&&h!==`GET`&&h!==`HEAD`){h=`GET`,u=void 0;for(let e of rE)m.delete(e)}if(f.origin!==p.origin)for(let e of[...m.keys()]){let t=m.get(e)??``;(iE.includes(e)||t.startsWith(`Payment `))&&m.delete(e)}d.push(Object.freeze({from:f.href,status:a.status,to:p.href})),await a.body?.cancel(),c=new Request(p,lE(c,m,h,u))}}function oE(e,t){return lE(e,new Headers(e.headers),e.method,t)}async function sE(e,t){if(typeof t==`string`)return t;if(!e.body)return;let n=e.headers.get(`accept`)?.toLowerCase()??``;return e.headers.has(`mcp-method`)||n.includes(`application/json`)&&n.includes(`text/event-stream`)?e.clone().text():e.clone().arrayBuffer()}function cE(e,t,n,r){if(n)return e;let i=new Headers(e.headers);return i.delete(q.acceptPayment),t&&RT(e,r)&&i.set(q.acceptPayment,t),new Request(e,{headers:i})}function lE(e,t,n,r){return{...r?{body:r}:{},cache:e.cache,credentials:e.credentials,headers:t,integrity:e.integrity,keepalive:e.keepalive,method:n,mode:e.mode,redirect:`manual`,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal}}function uE(e){let t;return n=>(t??=e(n),t)}function dE(e){return Object.freeze({challenge:gE(e.challenge),challenges:e.challenges.map(e=>gE(e)),createCredential:e.createCredential,method:mE(e.method),response:hE(e.response)})}function fE(e){return Object.freeze({challenge:gE(e.challenge),credential:e.credential,method:mE(e.method),response:hE(e.response)})}function pE(e){return Object.freeze({...e.challenge?{challenge:gE(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>gE(e))}:{},error:e.error,...e.method?{method:mE(e.method)}:{},response:hE(e.response)})}function mE(e){return vE(Object.assign({},e))}function hE(e){return e instanceof Response?e.body===null?e.clone():new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText}):gE(e)}function gE(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 _E(t)}catch{return vE(e)}}function _E(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))_E(t);return e}function vE(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function yE(e,t){return t?typeof t==`string`?iC(t):t:e}async function bE(e,t){return t?t(e):e}async function xE(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&&Kw(a,r),t.createCredential(a)}function SE(e){if(typeof Response<`u`&&e instanceof Response&&e.url)return new URL(e.url)}function CE(){return J.string().check(J.regex(wE,`Invalid URI or path`))}var wE,TE,EE,DE,OE,kE,AE,jE,ME,NE=F((()=>{nS(),wE=/^([a-zA-Z][a-zA-Z\d+.-]*:\/\/\S+|\/\S*)$/,TE=new Set([`amount`,`currency`,`description`,`intent`,`method`]),EE=J.looseObject({amount:J.optional(J.union([J.null(),J.string().check(J.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:J.optional(J.string()),description:J.optional(J.string()),intent:J.optional(J.string()),method:J.optional(J.string())}),DE=J.pipe(J.looseObject({amount:J.optional(J.union([J.null(),J.string().check(J.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:J.optional(J.string()),description:J.optional(J.string()),intent:J.optional(J.string()),method:J.optional(J.string()),offers:J.optional(J.array(EE).check(J.minLength(1)))}).check(J.refine(e=>e.offers===void 0||Object.keys(e).every(e=>e===`offers`||!TE.has(e)),`Cannot mix offers with flat payment info fields`)),J.transform(e=>{if(e.offers)return{offers:e.offers};let t={};for(let[n,r]of Object.entries(e))n!==`offers`&&(TE.has(n)||r!==void 0)&&(t[n]=r);return{offers:[t]}})),OE=J.looseObject({apiReference:J.optional(CE()),homepage:J.optional(CE()),llms:J.optional(CE())}),kE=J.looseObject({categories:J.optional(J.array(J.string())),docs:J.optional(OE)}),AE=J.looseObject({"x-payment-info":J.optional(DE),requestBody:J.optional(J.unknown()),responses:J.optional(J.record(J.string(),J.unknown())),summary:J.optional(J.string())}),jE=J.looseObject({delete:J.optional(AE),get:J.optional(AE),head:J.optional(AE),options:J.optional(AE),patch:J.optional(AE),post:J.optional(AE),put:J.optional(AE),trace:J.optional(AE)}),ME=J.looseObject({openapi:J.string(),info:J.looseObject({title:J.string(),version:J.string()}),"x-service-info":J.optional(kE),paths:J.optional(J.record(J.string(),jE))})}));NE();function PE(e){let t=[],n=ME.safeParse(e);if(!n.success){for(let e of n.error.issues)t.push({message:e.message,path:e.path.map(String).join(`.`)||`(root)`,severity:`error`});return t}let r=n.data.paths;if(!r)return t;for(let[e,n]of Object.entries(r))for(let[r,i]of Object.entries(n)){if(!i||typeof i!=`object`||Array.isArray(i))continue;let n=i,a=`paths.${e}.${r}`,o=n[`x-payment-info`];if(!o)continue;let s=DE.safeParse(o);if(!s.success){for(let e of s.error.issues){let n=e.path.length>0?`.${e.path.map(String).join(`.`)}`:``;t.push({message:e.message,path:`${a}.x-payment-info${n}`,severity:`error`})}continue}let c=n.responses;(!c||!(`402`in c))&&t.push({message:`Operation with x-payment-info MUST have a 402 response`,path:`${a}.responses`,severity:`error`});let l=r.toUpperCase();!n.requestBody&&(l===`POST`||l===`PUT`||l===`PATCH`)&&t.push({message:`Operation with x-payment-info has no requestBody`,path:a,severity:`warning`})}return t}const FE=`2026-07-29.preview`;function IE(e){return e}function LE(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}var RE=F((()=>{}));function zE(e,t){return Ge.resolve(e).toLowerCase()===Ge.resolve(t).toLowerCase()}var BE=F((()=>{}));function VE(e){return Number.isInteger(e)&&e>0&&e<QE}function HE(e,t){return VE(t)?e===!0||(e?.includes(t)??!1):!1}function UE(e){return Re.zonePortal(e)}function WE(e){if(e>=2**32)return e%2**32;if(e>142431e4&&e<142432e4)return e-142431e4;if(e>4217e5&&e<42171e4)return e-4217e5;throw Error(`Cannot derive a Zone ID from chain ID ${e}. Pass \`zoneId\`.`)}function GE(e){if(e>=2**32)return Math.floor(e/2**32);if(e>142431e4&&e<142432e4)return 42431;if(e>4217e5&&e<42171e4)return 4217}function KE(e){return ne.keccak256(k.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function qE(e,t){let{timeoutMs:n=JE}=t;if(!Number.isFinite(n)||n<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);let r=await Te(e,{cacheTime:0}),i=r>YE?r-YE:0n,a=Date.now()+n;for(;;){if(i<=r){let n=(await Ee(e,{address:t.portal,event:ZE,args:{senderTag:t.senderTag,...t.to?{to:t.to}:{}},fromBlock:i,toBlock:r}))[0]?.transactionHash;if(n)return n;i=r+1n}if(Date.now()+XE>a)throw Error(`Zone withdrawal ${t.senderTag} did not settle on Tempo within ${n}ms.`);await new Promise(e=>setTimeout(e,XE)),r=await Te(e,{cacheTime:0})}}var JE,YE,XE,ZE,QE,$E=F((()=>{JE=6e4,YE=7200n,XE=500,ZE=ce({abi:Fe.zonePortal,name:`WithdrawalProcessed`}),QE=4217e5}));function eD(e){return J.refine(e=>{let{amount:t,decimals:n}=e;return _e(t,n)>0n},e)}function tD(e){let{periodCount:t,periodUnit:n}=e;try{let e=aD[n];return e!==void 0&&BigInt(t)*e<=iD}catch{return!1}}var nD,rD,iD,aD,oD,sD,cD,lD,uD,dD,fD,pD,mD,hD=F((()=>{Bx(),RE(),nS(),$E(),nD=[`push`,`pull`],rD=J.object({amount:Kx(),memo:J.optional(Qx()),recipient:J.pipe(J.string(),J.transform(e=>e))}),iD=(1n<<64n)-1n,aD={dev_second:1n,day:86400n,week:604800n},oD=J.pipe(Zx(),J.transform(e=>e.toLowerCase())),sD=J.object({accessKeyAddress:oD,keyType:J.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:J.optional(J.pipe(J.string().check(J.regex(/^0x[0-9a-fA-F]{120}$/)),J.transform(e=>e)))}),cD=J.object({accessKey:J.optional(sD),chainId:J.optional(J.number())}),lD=Jx(`subscriptionExpires must be a valid date`).check(J.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),uD=J.enum([`dev_second`,`day`,`week`]),dD=J.pipe(J.union([J.string(),J.bigint(),J.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),J.transform(e=>e.toString())).check(J.regex(/^[1-9]\d*$/,`Invalid periodCount`),J.refine(e=>{try{return BigInt(e)<=iD}catch{return!1}},`periodCount exceeds uint64`)),fD=IE({name:`tempo`,intent:`charge`,schema:{credential:{payload:J.discriminatedUnion(`type`,[J.object({hash:Qx(),type:J.literal(`hash`)}),J.object({signature:eS(),type:J.literal(`transaction`)}),J.object({signature:eS(),type:J.literal(`proof`)}),J.object({hash:Qx(),senderTag:Qx(),type:J.literal(`zone`),zoneId:J.number().check(J.refine(VE,`Invalid Zone ID`))})])},request:J.pipe(J.object({machineTokenEnabled:J.optional(J.boolean()),amount:Kx(),chainId:J.optional(J.number()),currency:J.string(),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),feePayer:J.optional(J.pipe(J.union([J.boolean(),J.custom()]),J.transform(e=>typeof e==`object`||e))),memo:J.optional(J.never()),recipient:J.optional(J.string()),splits:J.optional(J.array(rD).check(J.minLength(1),J.maxLength(10))),supportedModes:J.optional(J.array(J.enum(nD)).check(J.minLength(1))),zones:J.optional(J.union([J.literal(!0),J.array(J.number().check(J.refine(VE,`Invalid Zone ID`))).check(J.minLength(1))]))}).check(J.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=_e(e,t),i=n.reduce((e,n)=>e+_e(n.amount,t),0n);return n.every(e=>_e(e.amount,t)>0n)&&i<r},`Invalid splits`)),J.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,zones:c,...l})=>({...l,amount:_e(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:_e(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),pD=IE({name:`tempo`,intent:`session`,schema:{credential:{payload:J.discriminatedUnion(`action`,[J.object({action:J.literal(`open`),authorizedSigner:J.optional(J.string()),channelId:Qx(),cumulativeAmount:Kx(),descriptor:J.optional(J.custom()),signature:eS(),transaction:eS(),type:J.literal(`transaction`)}),J.object({action:J.literal(`topUp`),additionalDeposit:Kx(),channelId:Qx(),descriptor:J.optional(J.custom()),transaction:eS(),type:J.literal(`transaction`)}),J.object({action:J.literal(`voucher`),channelId:Qx(),cumulativeAmount:Kx(),descriptor:J.optional(J.custom()),signature:eS()}),J.object({action:J.literal(`close`),channelId:Qx(),closeSignature:eS(),cumulativeAmount:Kx(),descriptor:J.optional(J.custom()),signature:eS()})])},request:J.pipe(J.object({amount:Kx(),chainId:J.optional(J.number()),channelId:J.optional(Qx()),currency:J.string(),decimals:J.number(),escrowContract:J.optional(J.string()),feePayer:J.optional(J.pipe(J.union([J.boolean(),J.custom()]),J.transform(e=>typeof e==`object`||e))),feeToken:J.optional(Zx()),minVoucherDelta:J.optional(Kx()),operator:J.optional(Zx()),recipient:J.optional(J.string()),sessionProtocol:J.optional(J.enum([zx.v2,zx.v1])),sessionSnapshot:J.optional(J.custom()),suggestedDeposit:J.optional(Kx()),unitType:J.string()}).check(J.refine(({amount:e,decimals:t})=>_e(e,t)>0n,`Session amount must be greater than 0`)),J.transform(({amount:e,chainId:t,channelId:n,decimals:r,escrowContract:i,feePayer:a,feeToken:o,minVoucherDelta:s,operator:c,sessionProtocol:l,sessionSnapshot:u,suggestedDeposit:d,...f})=>({...f,amount:_e(e,r).toString(),...d?{suggestedDeposit:_e(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:_e(s,r).toString()},...t!==void 0&&{chainId:t},...a!==void 0&&{feePayer:a},...o!==void 0&&{feeToken:o},...c!==void 0&&{operator:c},...l!==void 0&&{[Rx.sessionProtocol]:l},...u!==void 0&&{[Rx.sessionSnapshot]:u}}})))}}),mD=IE({name:`tempo`,intent:`subscription`,schema:{credential:{payload:J.object({signature:eS(),type:J.literal(`keyAuthorization`)})},request:J.pipe(J.object({amount:Kx(),accessKey:J.optional(sD),chainId:J.optional(J.number()),currency:oD,decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:J.optional(cD),periodCount:dD,periodUnit:uD,recipient:oD,subscriptionExpires:lD}).check(eD(`Subscription amount must be greater than 0`),J.refine(tD,`Subscription period exceeds uint64`)),J.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:_e(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}})}));function gD(e){return e>=0n&&e<=FD}function _D(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return gD(t)?t:void 0}function vD(e){return yD(e),e}function yD(e){if(!gD(e))throw Error(`Value ${e} is outside uint96 bounds.`)}function bD(e){return typeof e==`object`&&!!e}function xD(e){return typeof e==`string`&&ID.has(e)}function SD(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!xD(t.action))}function CD(e,t=`No session credential context available.`){if(!SD(e))throw Error(t);return e}function wD(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function TD(e){return bD(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function ED(e){return bD(e)?e.method===`tempo`&&e.intent===`session`&&e.status===`success`&&typeof e.timestamp==`string`&&typeof e.reference==`string`&&typeof e.challengeId==`string`&&typeof e.channelId==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.spent==`string`&&(e.units===void 0||typeof e.units==`number`)&&(e.txHash===void 0||typeof e.txHash==`string`):!1}function DD(e){let t=A.toString(e),n=JSON.parse(t);if(!ED(n))throw Error(`Invalid session receipt.`);return n}function OD(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function kD(e){let t=`message`,n=[];for(let r of e.split(`
229
+ `))throw Error(`Credential header value contains illegal newline characters`)}async function FT(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?.origin&&Kw(a,r.origin),r&&Vw(t,a,r),t.createCredential(a)}function IT(e,t){let n=e.get(q.acceptPayment);if(!n)return t;try{return{...t,entries:iC(n),header:n}}catch{return t}}async function LT(e,t){return t?t(e):e}function RT(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=VT(e);return t===`same-origin`?!BT()||n.origin===globalThis.location.origin:t.origins.some(e=>zT(n,e))}function zT(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 BT(){return globalThis.location!==void 0}function VT(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,BT()?globalThis.location.href:void 0)}function HT(e,t){let n=e instanceof Request?e:void 0;if((t.mode??n?.mode)===`no-cors`)throw Error(`Cannot automatically pay a no-cors request: it cannot carry a credential.`);if((t.cache??n?.cache)===`only-if-cached`)throw Error(`Cannot automatically pay an only-if-cached request: its retry cannot reach the server.`)}async function UT(e,t,n,r){if(HT(t,r),!e.url)return t;let i=new URL(e.url),a=VT(n);if(i.origin!==a.origin)throw Error(`Refusing to send payment credential across redirect from ${a.origin} to ${i.origin}`);let o=(r.method??(t instanceof Request?t.method:`GET`)).toUpperCase();if(e.redirected&&o!==`GET`&&o!==`HEAD`)throw Error(`Cannot automatically pay a redirected ${o} request. Use prepareRequest() to preserve redirect semantics.`);if(t instanceof Request){let n=r.body==null?t.clone():t,i=new Request(n,t.mode===`navigate`&&r.mode===void 0?{...r,mode:`same-origin`}:r);return i.url.split(`#`)[0]===e.url?i:i.body?new Request(e.url,{body:await i.arrayBuffer(),cache:i.cache,credentials:i.credentials,headers:i.headers,integrity:i.integrity,keepalive:i.keepalive,method:i.method,mode:i.mode,redirect:i.redirect,referrer:i.referrer,referrerPolicy:i.referrerPolicy,signal:i.signal}):new Request(e.url,i)}return e.url}var WT,GT,KT,qT,JT,YT,XT,ZT,QT,$T=F((()=>{CS(),Bx(),kS(),jS(),ZS(),SC(),Mw(),Rw(),Qw(),rT(),mw(),WT=Symbol.for(`mppx.fetch.wrapper`),GT=Symbol.for(`mppx.fetch.identity`),KT=Symbol.for(`mppx.fetch.skipPayment`),qT=3,JT=65536,YT=2e3,XT=`Mppx-Body-Truncated`,QT=new WeakMap}));Nx(),Bx(),jS(),ZS(),SC(),$T(),Rw(),Qw(),rT(),Mw();const eE=new WeakMap;function tE(e){let{identity:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=jw(),trustedTempoProofRealms:c}=e;if(`attestation`in e)throw TypeError("Mppx client `attestation` was replaced by `identity: [prover]`.");let l=jT(e.fetch??globalThis.fetch),u=t?WS(t):e.fetch&&AT(e.fetch),d=e.methods.flat(),f=rC(d,e.paymentPreferences),p=lT(),m=r,h={acceptPayment:f,acceptPaymentPolicy:o,...e.fetch&&{fetch:l},...u&&{identity:u},eventDispatcher:p,...n!==void 0&&{maxPaymentRetries:n},...m&&{onChallenge:m},...i&&{orderChallenges:i},methods:d,transport:s,...c&&{trustedTempoProofRealms:c}},g=oT(h);a&&sT(h);function _(e){return p.on(`challenge.received`,e)}function v(e){return p.on(`credential.created`,e)}function y(e){return p.on(`payment.failed`,e)}function b(e){return p.on(`payment.response`,e)}async function x(e,t,n){let r=hE(e),a=await s.getChallenges(e,t?.request),o=Object.freeze(a.map(e=>gE(e))),l=yE(f.entries,t?.acceptPayment),u,m;try{let f=sC(a,d,l,n);f.length===0&&n===void 0&&(f=sC(a,d,l,xC));let h=(await bE(f,t?.orderChallenges??i))[0];if(!h)throw Error(`No method found for challenges: ${a.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${d.map(e=>`${e.name}.${e.intent}`).join(`, `)}`);let g=h.challenge;u=o[h.index],m=h.method,u.expires&&AS(u.expires,u.id);let _=SE(e);_?$w(u,_,c):s.name===`mcp`&&eT(u,c&&Object.values(c));let v=u,y=m,b=uE(async e=>{try{v.expires&&AS(v.expires,v.id);let t=uE(t=>xE(v,y,t??e,_?.origin)),n=await p.emit(`challenge.received`,dE({challenge:v,challenges:a,createCredential:t,method:y,response:r}))??await t();return PT(n),await p.emit(`credential.created`,fE({challenge:v,credential:n,method:y,response:r})),n}catch(e){throw await p.emit(`payment.failed`,pE({challenge:v,challenges:a,error:e,method:y,response:r})),e}}),x=Object.freeze({challenge:v,challenges:o,createCredential:b,method:mE(y),setCredential(e,t){return PT(t),s.setCredential(e,t,{challenge:g})}});return eE.set(x,y),x}catch(e){throw await p.emit(`payment.failed`,pE({challenge:u,challenges:a,error:e,method:m,response:r})),e}}async function S(e,t,n){let{maxRedirects:r=20,requirePayment:i=!1,...a}=n??{},d=await aE({acceptPayment:f.header,acceptPaymentPolicy:o,fetch:l,init:t,input:e,maxRedirects:r,identity:u}),p=oE(d.replayRequest,d.body);if(!await s.isPaymentRequired(d.response,p)){if(i)throw Error(`Response does not require payment.`);return Object.freeze({payment:void 0,request:d.request,response:d.response,redirects:d.redirects})}let m=await x(d.response,{...a,request:p});$w(m.challenge,new URL(d.replayRequest.url),c);let h=eE.get(m)??m.method,g=uE(async e=>(await u?.challenge(d.response,{challenge:m.challenge},d.replayRequest.url),Pw(h)&&await Fw(h,{challenge:m.challenge,context:e,fetch:u?KS(l,u,{challenge:m.challenge}):l,input:d.replayRequest,signal:d.replayRequest.signal}),m.createCredential(e))),_=Object.freeze({...m,createCredential:g,async pay(e){let t=await g(e),n=m.setCredential(oE(d.replayRequest,d.body),t),r=new Request(d.replayRequest.url,{...n,redirect:`manual`});if(!u)return l(r);let{response:i}=await u.send(l,r,{challenge:m.challenge});return i}});return Object.freeze({payment:_,request:d.request,response:d.response,redirects:d.redirects})}return{fetch:g,rawFetch:l,methods:d,transport:s,on:p.on,onChallengeReceived:_,onCredentialCreated:v,onPaymentFailed:y,onPaymentResponse:b,preparePayment:x,prepareRequest:S,async createCredential(e,t,n){return(await x(e,n,t)).createCredential(t)}}}const nE=new Set([301,302,303,307,308]),rE=[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`,`transfer-encoding`],iE=[`authorization`,`cookie`,`cookie2`,`host`,`identity-attestation`,`payment-authorization`,`payment-signature`,`proxy-authorization`,`x-payment`];async function aE(e){let{acceptPayment:t,acceptPaymentPolicy:n,fetch:r,identity:i,init:a,input:o,maxRedirects:s}=e;if(!Number.isInteger(s)||s<0)throw TypeError(`maxRedirects must be a non-negative integer.`);let c=new Request(o,{...a,redirect:`manual`}),l=c.headers.has(q.acceptPayment),u=await sE(c,a?.body),d=[];for(;;){c=cE(c,t,l,n);let{request:e,response:a}=await(async()=>{if(i)return i.send(r,c.clone());let e=c.clone();return{request:e,response:await r(e)}})();if(a.type===`opaqueredirect`||a.status===0)throw Error(`prepareRequest requires a runtime that exposes manual redirect responses.`);if(!nE.has(a.status))return{body:u,replayRequest:c,request:e,response:a,redirects:Object.freeze(d)};let o=a.headers.get(`location`);if(!o)return{body:u,replayRequest:c,request:e,response:a,redirects:Object.freeze(d)};if(d.length>=s)throw await a.body?.cancel(),Error(`Payment request exceeded ${s} redirects.`);let f=new URL(c.url),p=new URL(o,f);if(f.protocol===`https:`&&p.protocol!==`https:`)throw await a.body?.cancel(),Error(`Payment request refused HTTPS downgrade redirect to ${p.href}`);let m=new Headers(c.headers),h=c.method;if((a.status===301||a.status===302)&&h===`POST`||a.status===303&&h!==`GET`&&h!==`HEAD`){h=`GET`,u=void 0;for(let e of rE)m.delete(e)}if(f.origin!==p.origin)for(let e of[...m.keys()]){let t=m.get(e)??``;(iE.includes(e)||t.startsWith(`Payment `))&&m.delete(e)}d.push(Object.freeze({from:f.href,status:a.status,to:p.href})),await a.body?.cancel(),c=new Request(p,lE(c,m,h,u))}}function oE(e,t){return lE(e,new Headers(e.headers),e.method,t)}async function sE(e,t){if(typeof t==`string`)return t;if(!e.body)return;let n=e.headers.get(`accept`)?.toLowerCase()??``;return e.headers.has(`mcp-method`)||n.includes(`application/json`)&&n.includes(`text/event-stream`)?e.clone().text():e.clone().arrayBuffer()}function cE(e,t,n,r){if(n)return e;let i=new Headers(e.headers);return i.delete(q.acceptPayment),t&&RT(e,r)&&i.set(q.acceptPayment,t),new Request(e,{headers:i})}function lE(e,t,n,r){return{...r?{body:r}:{},cache:e.cache,credentials:e.credentials,headers:t,integrity:e.integrity,keepalive:e.keepalive,method:n,mode:e.mode,redirect:`manual`,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal}}function uE(e){let t;return n=>(t??=e(n),t)}function dE(e){return Object.freeze({challenge:gE(e.challenge),challenges:e.challenges.map(e=>gE(e)),createCredential:e.createCredential,method:mE(e.method),response:hE(e.response)})}function fE(e){return Object.freeze({challenge:gE(e.challenge),credential:e.credential,method:mE(e.method),response:hE(e.response)})}function pE(e){return Object.freeze({...e.challenge?{challenge:gE(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>gE(e))}:{},error:e.error,...e.method?{method:mE(e.method)}:{},response:hE(e.response)})}function mE(e){return vE(Object.assign({},e))}function hE(e){return e instanceof Response?e.body===null?e.clone():new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText}):gE(e)}function gE(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 _E(t)}catch{return vE(e)}}function _E(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))_E(t);return e}function vE(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function yE(e,t){return t?typeof t==`string`?iC(t):t:e}async function bE(e,t){return t?t(e):e}async function xE(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&&Kw(a,r),t.createCredential(a)}function SE(e){if(typeof Response<`u`&&e instanceof Response&&e.url)return new URL(e.url)}function CE(){return J.string().check(J.regex(wE,`Invalid URI or path`))}var wE,TE,EE,DE,OE,kE,AE,jE,ME,NE=F((()=>{nS(),wE=/^([a-zA-Z][a-zA-Z\d+.-]*:\/\/\S+|\/\S*)$/,TE=new Set([`amount`,`currency`,`description`,`intent`,`method`]),EE=J.looseObject({amount:J.optional(J.union([J.null(),J.string().check(J.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:J.optional(J.string()),description:J.optional(J.string()),intent:J.optional(J.string()),method:J.optional(J.string())}),DE=J.pipe(J.looseObject({amount:J.optional(J.union([J.null(),J.string().check(J.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:J.optional(J.string()),description:J.optional(J.string()),intent:J.optional(J.string()),method:J.optional(J.string()),offers:J.optional(J.array(EE).check(J.minLength(1)))}).check(J.refine(e=>e.offers===void 0||Object.keys(e).every(e=>e===`offers`||!TE.has(e)),`Cannot mix offers with flat payment info fields`)),J.transform(e=>{if(e.offers)return{offers:e.offers};let t={};for(let[n,r]of Object.entries(e))n!==`offers`&&(TE.has(n)||r!==void 0)&&(t[n]=r);return{offers:[t]}})),OE=J.looseObject({apiReference:J.optional(CE()),homepage:J.optional(CE()),llms:J.optional(CE())}),kE=J.looseObject({categories:J.optional(J.array(J.string())),docs:J.optional(OE)}),AE=J.looseObject({"x-payment-info":J.optional(DE),requestBody:J.optional(J.unknown()),responses:J.optional(J.record(J.string(),J.unknown())),summary:J.optional(J.string())}),jE=J.looseObject({delete:J.optional(AE),get:J.optional(AE),head:J.optional(AE),options:J.optional(AE),patch:J.optional(AE),post:J.optional(AE),put:J.optional(AE),trace:J.optional(AE)}),ME=J.looseObject({openapi:J.string(),info:J.looseObject({title:J.string(),version:J.string()}),"x-service-info":J.optional(kE),paths:J.optional(J.record(J.string(),jE))})}));NE();function PE(e){let t=[],n=ME.safeParse(e);if(!n.success){for(let e of n.error.issues)t.push({message:e.message,path:e.path.map(String).join(`.`)||`(root)`,severity:`error`});return t}let r=n.data.paths;if(!r)return t;for(let[e,n]of Object.entries(r))for(let[r,i]of Object.entries(n)){if(!i||typeof i!=`object`||Array.isArray(i))continue;let n=i,a=`paths.${e}.${r}`,o=n[`x-payment-info`];if(!o)continue;let s=DE.safeParse(o);if(!s.success){for(let e of s.error.issues){let n=e.path.length>0?`.${e.path.map(String).join(`.`)}`:``;t.push({message:e.message,path:`${a}.x-payment-info${n}`,severity:`error`})}continue}let c=n.responses;(!c||!(`402`in c))&&t.push({message:`Operation with x-payment-info MUST have a 402 response`,path:`${a}.responses`,severity:`error`});let l=r.toUpperCase();!n.requestBody&&(l===`POST`||l===`PUT`||l===`PATCH`)&&t.push({message:`Operation with x-payment-info has no requestBody`,path:a,severity:`warning`})}return t}const FE=`2026-07-29.preview`;function IE(e){return e}function LE(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}var RE=F((()=>{}));function zE(e,t){return Ge.resolve(e).toLowerCase()===Ge.resolve(t).toLowerCase()}var BE=F((()=>{}));function VE(e){return Number.isInteger(e)&&e>0&&e<QE}function HE(e,t){return VE(t)?e===!0||(e?.includes(t)??!1):!1}function UE(e){return Re.zonePortal(e)}function WE(e){if(e>=2**32)return e%2**32;if(e>142431e4&&e<142432e4)return e-142431e4;if(e>4217e5&&e<42171e4)return e-4217e5;throw Error(`Cannot derive a Zone ID from chain ID ${e}. Pass \`zoneId\`.`)}function GE(e){if(e>=2**32)return Math.floor(e/2**32);if(e>142431e4&&e<142432e4)return 42431;if(e>4217e5&&e<42171e4)return 4217}function KE(e){return ne.keccak256(k.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function qE(e,t){let{timeoutMs:n=JE}=t;if(!Number.isFinite(n)||n<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);let r=await Te(e,{cacheTime:0}),i=r>YE?r-YE:0n,a=Date.now()+n;for(;;){if(i<=r){let n=(await Ee(e,{address:t.portal,event:ZE,args:{senderTag:t.senderTag,...t.to?{to:t.to}:{}},fromBlock:i,toBlock:r}))[0]?.transactionHash;if(n)return n;i=r+1n}if(Date.now()+XE>a)throw Error(`Zone withdrawal ${t.senderTag} did not settle on Tempo within ${n}ms.`);await new Promise(e=>setTimeout(e,XE)),r=await Te(e,{cacheTime:0})}}var JE,YE,XE,ZE,QE,$E=F((()=>{JE=6e4,YE=7200n,XE=500,ZE=ce({abi:Fe.zonePortal,name:`WithdrawalProcessed`}),QE=4217e5}));function eD(e){return J.refine(e=>{let{amount:t,decimals:n}=e;return _e(t,n)>0n},e)}function tD(e){let{periodCount:t,periodUnit:n}=e;try{let e=aD[n];return e!==void 0&&BigInt(t)*e<=iD}catch{return!1}}var nD,rD,iD,aD,oD,sD,cD,lD,uD,dD,fD,pD,mD,hD=F((()=>{Bx(),RE(),nS(),$E(),nD=[`push`,`pull`],rD=J.object({amount:Kx(),memo:J.optional(Qx()),recipient:J.pipe(J.string(),J.transform(e=>e))}),iD=(1n<<64n)-1n,aD={dev_second:1n,day:86400n,week:604800n},oD=J.pipe(Zx(),J.transform(e=>e.toLowerCase())),sD=J.object({accessKeyAddress:oD,keyType:J.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:J.optional(J.pipe(J.string().check(J.regex(/^0x[0-9a-fA-F]{120}$/)),J.transform(e=>e)))}),cD=J.object({accessKey:J.optional(sD),chainId:J.optional(J.number())}),lD=Jx(`subscriptionExpires must be a valid date`).check(J.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),uD=J.enum([`dev_second`,`day`,`week`]),dD=J.pipe(J.union([J.string(),J.bigint(),J.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),J.transform(e=>e.toString())).check(J.regex(/^[1-9]\d*$/,`Invalid periodCount`),J.refine(e=>{try{return BigInt(e)<=iD}catch{return!1}},`periodCount exceeds uint64`)),fD=IE({name:`tempo`,intent:`charge`,schema:{credential:{payload:J.discriminatedUnion(`type`,[J.object({hash:Qx(),type:J.literal(`hash`)}),J.object({signature:eS(),type:J.literal(`transaction`)}),J.object({signature:eS(),type:J.literal(`proof`)}),J.object({hash:Qx(),senderTag:Qx(),type:J.literal(`zone`),zoneId:J.number().check(J.refine(VE,`Invalid Zone ID`))})])},request:J.pipe(J.object({machineTokenEnabled:J.optional(J.boolean()),amount:Kx(),chainId:J.optional(J.number()),currency:J.string(),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),feePayer:J.optional(J.pipe(J.union([J.boolean(),J.custom()]),J.transform(e=>typeof e==`object`||e))),memo:J.optional(J.never()),recipient:J.optional(J.string()),splits:J.optional(J.array(rD).check(J.minLength(1),J.maxLength(10))),supportedModes:J.optional(J.array(J.enum(nD)).check(J.minLength(1))),zones:J.optional(J.union([J.literal(!0),J.array(J.number().check(J.refine(VE,`Invalid Zone ID`))).check(J.minLength(1))]))}).check(J.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=_e(e,t),i=n.reduce((e,n)=>e+_e(n.amount,t),0n);return n.every(e=>_e(e.amount,t)>0n)&&i<r},`Invalid splits`)),J.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,zones:c,...l})=>({...l,amount:_e(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:_e(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),pD=IE({name:`tempo`,intent:`session`,schema:{credential:{payload:J.discriminatedUnion(`action`,[J.object({action:J.literal(`open`),authorizedSigner:J.optional(J.string()),channelId:Qx(),cumulativeAmount:Kx(),descriptor:J.optional(J.custom()),signature:eS(),transaction:eS(),type:J.literal(`transaction`)}),J.object({action:J.literal(`topUp`),additionalDeposit:Kx(),channelId:Qx(),descriptor:J.optional(J.custom()),transaction:eS(),type:J.literal(`transaction`)}),J.object({action:J.literal(`voucher`),channelId:Qx(),cumulativeAmount:Kx(),descriptor:J.optional(J.custom()),signature:eS()}),J.object({action:J.literal(`close`),channelId:Qx(),closeSignature:eS(),cumulativeAmount:Kx(),descriptor:J.optional(J.custom()),signature:eS()})])},request:J.pipe(J.object({amount:Kx(),chainId:J.optional(J.number()),channelId:J.optional(Qx()),currency:J.string(),decimals:J.number(),escrowContract:J.optional(J.string()),feePayer:J.optional(J.pipe(J.union([J.boolean(),J.custom()]),J.transform(e=>typeof e==`object`||e))),feeToken:J.optional(Zx()),minVoucherDelta:J.optional(Kx()),operator:J.optional(Zx()),recipient:J.optional(J.string()),sessionProtocol:J.optional(J.enum([zx.v2,zx.v1])),sessionSnapshot:J.optional(J.custom()),suggestedDeposit:J.optional(Kx()),unitType:J.string()}).check(J.refine(({amount:e,decimals:t})=>_e(e,t)>0n,`Session amount must be greater than 0`)),J.transform(({amount:e,chainId:t,channelId:n,decimals:r,escrowContract:i,feePayer:a,feeToken:o,minVoucherDelta:s,operator:c,sessionProtocol:l,sessionSnapshot:u,suggestedDeposit:d,...f})=>({...f,amount:_e(e,r).toString(),...d?{suggestedDeposit:_e(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:_e(s,r).toString()},...t!==void 0&&{chainId:t},...a!==void 0&&{feePayer:a},...o!==void 0&&{feeToken:o},...c!==void 0&&{operator:c},...l!==void 0&&{[Rx.sessionProtocol]:l},...u!==void 0&&{[Rx.sessionSnapshot]:u}}})))}}),mD=IE({name:`tempo`,intent:`subscription`,schema:{credential:{payload:J.object({signature:eS(),type:J.literal(`keyAuthorization`)})},request:J.pipe(J.object({amount:Kx(),accessKey:J.optional(sD),chainId:J.optional(J.number()),currency:oD,decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:J.optional(cD),periodCount:dD,periodUnit:uD,recipient:oD,subscriptionExpires:lD}).check(eD(`Subscription amount must be greater than 0`),J.refine(tD,`Subscription period exceeds uint64`)),J.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:_e(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}})}));function gD(e){return e>=0n&&e<=FD}function _D(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return gD(t)?t:void 0}function vD(e){return yD(e),e}function yD(e){if(!gD(e))throw Error(`Value ${e} is outside uint96 bounds.`)}function bD(e){return typeof e==`object`&&!!e}function xD(e){return typeof e==`string`&&ID.has(e)}function SD(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!xD(t.action))}function CD(e,t=`No session credential context available.`){if(!SD(e))throw Error(t);return e}function wD(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function TD(e){return bD(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function ED(e){return bD(e)?e.method===`tempo`&&e.intent===`session`&&e.status===`success`&&typeof e.timestamp==`string`&&typeof e.reference==`string`&&typeof e.challengeId==`string`&&typeof e.channelId==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.spent==`string`&&(e.units===void 0||typeof e.units==`number`)&&(e.txHash===void 0||typeof e.txHash==`string`):!1}function DD(e){let t=A.toString(e),n=JSON.parse(t);if(!ED(n))throw Error(`Invalid session receipt.`);return n}function OD(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function kD(e){let t=`message`,n=[];for(let r of e.split(`
230
230
  `))r.startsWith(`event: `)?t=r.slice(7).trim():r.startsWith(`data: `)?n.push(r.slice(6)):r===`data:`&&n.push(``);if(n.length===0)return null;let r=n.join(`
231
231
  `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=AD(r);return TD(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=AD(r);return ED(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function AD(e){try{return JSON.parse(e)}catch{return null}}function jD(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function MD(){return JSON.stringify({mpp:`payment-close-request`})}function ND(e){let t=PD(e);return t?t.mpp===`authorization`&&typeof t.authorization==`string`?{mpp:`authorization`,authorization:t.authorization}:t.mpp===`message`&&typeof t.data==`string`?{mpp:`message`,data:t.data}:t.mpp===`payment-close-request`?{mpp:`payment-close-request`}:t.mpp===`payment-close-ready`&&ED(t.data)?{mpp:`payment-close-ready`,data:t.data}:t.mpp===`payment-error`&&typeof t.status==`number`&&typeof t.message==`string`?{mpp:`payment-error`,status:t.status,message:t.message}:t.mpp===`payment-need-voucher`&&TD(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&ED(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function PD(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}var FD,ID,LD,RD=F((()=>{FD=(1n<<96n)-1n,ID=new Set([`open`,`topUp`,`voucher`,`close`]),LD=`0x4d50500000000000000000000000000000000000`}));function zD(e){return KD.encode(e)}function BD(e){return KD.decode(e)}var VD,HD,UD,WD,GD,KD,qD=F((()=>{yw(),nS(),VD=J.custom(e=>typeof e==`string`&&fe(e,{strict:!1})),HD=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),UD=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),WD=J.object({authorizedSigner:VD,expiringNonceHash:HD,operator:VD,payee:VD,payer:VD,salt:HD,token:VD}),GD=J.object({acceptedCumulative:J.string(),chainId:J.number(),channelId:HD,closeRequestedAt:J.optional(J.string()),deposit:J.string(),descriptor:WD,escrow:VD,highestVoucher:J.optional(J.object({channelId:HD,cumulativeAmount:J.string(),signature:UD})),requiredCumulative:J.string(),settled:J.string(),spent:J.string(),units:J.optional(J.number())}),KD=_w(GD)}));function JD(e){return{status:`active`,...e}}function YD(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?eO(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?eO(e,t):t.snapshot?{state:{status:`hydrating`,challengeId:t.challengeId,snapshot:t.snapshot},effects:[{type:`hydrate`,snapshot:t.snapshot}]}:{state:{status:`opening`,challengeId:t.challengeId},effects:[{type:`open`}]};case`hydrated`:return e.status===`hydrating`?{state:QD(e.challengeId,t.snapshot),effects:[]}:eO(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?eO(e,t):{state:fO({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:$D(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:eO(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?eO(e,t):{state:hO(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?ZD({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):eO(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:eO(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?eO(e,t):{state:$D(e.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]};case`settleStarted`:return e.status===`active`?{state:{status:`settling`,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[{type:`settle`,channelId:e.channelId}]}:eO(e,t);case`settled`:return e.status===`settling`?{state:$D(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:eO(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:eO(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:eO(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?eO(e,t):{state:{status:`closing`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`close`,channelId:e.channelId}]};case`closed`:return e.status!==`closing`&&e.status!==`withdrawable`?eO(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function XD(e,t){let n=YD(e.state,t);return e.state=n.state,n}function ZD(e){let{challengeId:t,descriptor:n,event:r}=e,i=BigInt(r.requiredCumulative),a=BigInt(r.deposit);return i>a?{state:{status:`toppingUp`,challengeId:t,channelId:r.channelId,descriptor:n,deposit:r.deposit},effects:[{type:`topUp`,channelId:r.channelId,amount:(i-a).toString()}]}:{state:{status:`voucherNeeded`,challengeId:t,channelId:r.channelId,descriptor:n,requiredCumulative:r.requiredCumulative,deposit:r.deposit},effects:[{type:`voucher`}]}}function QD(e,t){return JD({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function $D(e,t,n,r){return JD({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function eO(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function tO(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function nO(e){let{channel:t,maxVoucherCumulative:n,receipt:r}=e;if(!t||r.channelId!==t.channelId)return;let i=BigInt(r.acceptedCumulative),a=BigInt(r.spent);if(a>i)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(i>t.cumulativeAmount)throw Error(`receipt accepted cumulative exceeds local voucher state`);if(a>t.cumulativeAmount)throw Error(`receipt spent exceeds local voucher state`);tO({cumulativeAmount:i,maxVoucherCumulative:n}),tO({cumulativeAmount:a,maxVoucherCumulative:n})}function rO(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;nO({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function iO(e,t){return typeof e==`bigint`?e:_e(e,t)}function aO(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(sO(r,n),t!==void 0){let e=BigInt(t);if(e<r)throw Error(`opening deposit ${e} below request amount ${r}`);return e}let a=i===void 0?void 0:BigInt(i),o=a!==void 0&&a>r?a:r;return n===void 0||o<n?o:n}function oO(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;tO({cumulativeAmount:r,maxVoucherCumulative:n??null});let o=r-t,s=a??i??o,c=s>o?s:o;if(n==null)return c;let l=n-t;return c<l?c:l}function sO(e,t){tO({cumulativeAmount:e,maxVoucherCumulative:t??null})}function cO(e){let{channel:t,currentSocket:n,lastChallenge:r}=e;if(!t?.opened)return;let i=n?.challenge??r,a=n?.channelId??t.channelId;if(!i)throw Error(`Cannot close session: no challenge available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or make a request first to receive a fresh 402 challenge.`);if(!a)throw Error(`Cannot close session: no channel ID available. The session may not have been fully opened.`);return{challenge:i,channel:t,channelId:a}}function lO(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function uO(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!gD(n))throw Error(`close-ready spent is not a uint96 amount`);if(n<r)throw Error(`close-ready spent is below locally confirmed spend`);if(n>lO({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function dO(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=_D(r),s=_D(a.spent);return o===void 0||s===void 0||!gD(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function fO(e){return JD({challengeId:e.challengeId,channelId:e.entry.channelId,descriptor:e.entry.descriptor,acceptedCumulative:e.entry.cumulativeAmount.toString(),deposit:e.entry.deposit.toString(),spent:e.spent,units:e.units})}function pO(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:xO}}function mO(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=rO({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&XD(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function hO(e,t){return JD({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function gO(e){let{challengeId:t,channelId:n,closeReadyReceipt:r,cumulativeAmount:i,deliveredChunks:a=0n,socketChallengeId:o,socketChannelId:s,spent:c,tickCost:l=0n}=e;if(c>i)throw Error(`locally confirmed spend exceeds local voucher state`);if(r&&r.challengeId===t&&r.channelId===n){let e=_D(r.spent);if(e===void 0)throw Error(`close-ready spent is not a uint96 amount`);return e>c?e:c}if(o===t&&s===n&&l>0n){let e=a*l,t=c>e?c:e;return t>i?i:t}return i}function _O(e){let{channel:t,channelId:n,challengeId:r,cumulativeAmount:i,spent:a,state:o}=e;if(!(!t||t.channelId!==n)&&(t.cumulativeAmount=i,r))return YD(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function vO(e){return{channel:e.channel===null?null:{entry:e.channel,cumulativeAmount:e.channel.cumulativeAmount,deposit:e.channel.deposit,opened:e.channel.opened},spent:e.spent,state:e.state}}function yO(e,t){return e.channel?(e.channel.entry.cumulativeAmount=e.channel.cumulativeAmount,e.channel.entry.deposit=e.channel.deposit,e.channel.entry.opened=e.channel.opened,{channel:e.channel.entry,spent:e.spent,state:e.state}):(t&&(t.opened=!1),{channel:null,spent:e.spent,state:e.state})}async function bO(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(MD()),e.waitForCloseReady()))(),a=BigInt(i.spent);uO({cumulativeAmount:r.channel.cumulativeAmount,readySpent:a,spent:e.spent});let o=await e.createSessionCredential(r.challenge,{action:`close`,channelId:r.channelId,descriptor:r.channel.descriptor,cumulativeAmountRaw:a.toString()}),s=a.toString();n.expectedCloseAmount=s;try{let i=e.waitForReceipt(e=>dO({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(jD(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}var xO,SO=F((()=>{RD(),qD(),xO={status:`idle`}}));function CO(e){let t=new Map,n=!1,r=[],i=e.readyState,a=(e,n,i)=>{let a=t.get(e);if(a||(a=new Set,t.set(e,a)),a.add({once:typeof i==`object`&&i.once===!0,value:n}),e===`message`&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},o=(e,n)=>{let r=t.get(e);if(r)for(let e of r)e.value===n&&r.delete(e)};function s(e,a){if(a.type===`close`){if(n)return;n=!0,i=ck.CLOSED,r=null}if(a.type===`open`&&(i=ck.OPEN),a.type===`message`&&r){r.push(a);return}switch(a.type){case`close`:l.onclose?.(a);break;case`error`:l.onerror?.(a);break;case`message`:l.onmessage?.(a);break;case`open`:l.onopen?.(a)}let o=t.get(e);if(o)for(let e of Array.from(o))typeof e.value==`function`?e.value(a):e.value.handleEvent(a),e.once&&o.delete(e)}let c=null,l={addEventListener:a,close(t,n){e.close(t,n)},get bufferedAmount(){return e.bufferedAmount},get extensions(){return e.extensions},on(e,t){a(e,t)},onclose:null,onerror:null,get onmessage(){return c},set onmessage(e){if(c=e,e&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},onopen:null,off(e,t){o(e,t)},get protocol(){return e.protocol},get readyState(){return i},removeEventListener:o,send(t){e.send(t)},get url(){return e.url}};return{emit:s,socket:l}}function wO(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function TO(e){let{amount:t,assertVoucherWithinLocalLimit:n,channel:r,decimals:i,lastChallenge:a,lastUrl:o}=e;if(!r?.opened)throw Error(`Cannot top up session: no open channel.`);if(!a)throw Error(`Cannot top up session: no challenge available. Make a request first.`);if(!o)throw Error(`Cannot top up session: no URL available. Call fetch(), sse(), or ws() first.`);let s=iO(t,i);if(s<=0n)throw Error(`Top-up amount must be greater than zero.`);return n(r.cumulativeAmount+s),{additionalDeposit:s,challenge:a,channelId:r.channelId,input:o}}function EO(e){let{additionalDeposit:t,channel:n,channelId:r,challengeId:i,currentState:a,knownDeposit:o,receipt:s,spent:c}=e;if(n?.channelId!==r)return;let l=o!==void 0&&o>n.deposit?o:n.deposit,u={...n,deposit:l+t};return s?{channel:u,state:hO(s,u)}:i?{channel:u,state:fO({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function DO(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=wO(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,headers:e.headers,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative,...e.signal?{signal:e.signal}:{}});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:vD(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function OO(e){return e.method===Ix.tempo&&e.intent===Lx.session}function kO(e){return OO(e)&&Px(e.request.methodDetails,Rx.sessionProtocol)===zx.v2}function AO(e){return Px(e.request.methodDetails,Rx.sessionSnapshot)}function jO(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return QC({...t,redirect:`manual`,headers:{...cT(i),...cT(t?.headers)}},vS(r),n)}function MO(e){return e instanceof Request||typeof e==`object`&&!!e&&!(e instanceof URL)&&typeof e.url==`string`&&typeof e.method==`string`&&typeof e.clone==`function`}function NO(e){try{let t=typeof location>`u`?void 0:location.href,n=MO(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function PO(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function FO(e){let t=await e.text().catch(()=>``);if(!t)return``;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return t;try{return JSON.parse(t).detail??t}catch{return t}}async function IO(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);if(t.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let r=await LO({challenge:e.challenge,context:{action:`topUp`,...e.autoSwap===void 0?{}:{autoSwap:e.autoSwap},channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,headers:e.headers,input:e.input,signal:e.signal}).catch(async n=>{throw n instanceof dk&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(q.paymentReceipt);return i?DD(i):void 0}async function LO(e){let t=async t=>{e.signal?.throwIfAborted();let n=await e.createSessionCredential(t,e.context);e.signal?.throwIfAborted();let r=new AbortController,i=()=>r.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,i,{once:!0});let a=setTimeout(()=>r.abort(new DOMException(`Session management request timed out; payment outcome unknown`,`TimeoutError`)),3e4),o,s=new Promise((e,t)=>{o=()=>t(r.signal.reason),r.signal.addEventListener(`abort`,o,{once:!0})});try{return await Promise.race([e.fetch(NO(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:sk(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new dk(t):t}finally{clearTimeout(a),e.signal?.removeEventListener(`abort`,i),r.signal.removeEventListener(`abort`,o)}},n=await t(e.challenge);if(n.status!==402)return n;let r=mS(n).find(kO);return r?t(r):n}async function RO(e){let t=zO({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,headers:e.init?.headers,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,signal:e.init?.signal??(e.input instanceof Request?e.input.signal:void 0)});let s=e.getChannel();if(!s?.descriptor||s.channelId!==i.channelId)return;let c=s.cumulativeAmount>a?s.cumulativeAmount:a,l=()=>e.restoreCumulative(i.channelId,o),u;try{let t=await e.createSessionCredential(r,{action:`voucher`,channelId:i.channelId,descriptor:s.descriptor,cumulativeAmountRaw:c.toString()});u=await e.fetch(e.input,jO(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(q.paymentReceipt)&&await l(),u}function zO(e){let t=mS(e.response).find(kO);if(!t)return;let n=AO(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function BO(e){if(!e.lastUrl)throw Error(`Cannot close session: no URL available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or call fetch()/sse() before close().`);let t=e.target.challenge,n=e.signedCloseAmount,r=MO(e.lastUrl)?e.lastUrl:void 0,i=r?{cache:r.cache,credentials:r.credentials,integrity:r.integrity,keepalive:r.keepalive,mode:r.mode===`navigate`?`same-origin`:r.mode,referrer:r.referrer,referrerPolicy:r.referrerPolicy}:void 0,a=async(a,o=!1)=>{t=a,n=(o?e.resolveSignedCloseAmount?.(a):void 0)??e.signedCloseAmount;let s=await e.createSessionCredential(a,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(r?NO(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:sk(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=mS(o).find(kO);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await FO(o),t=o.headers.get(q.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${q.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(q.paymentReceipt);if(!s)return;let c=DD(s);if(!c.txHash||!j.validate(c.txHash,{strict:!0})||j.size(c.txHash)!==32||!dO({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:0n,receipt:c}))throw Error(`Session close response included a mismatched payment receipt.`);return c}async function VO(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...cT(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!OD(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),HO(e,c,{onReceipt:r,signal:o},n,s.headers)}function HO(e,t,n,r,i){if(!OD(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return UO({onNeedVoucher:t=>JO({challenge:a,driver:r,headers:i,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*UO(e){for await(let t of WO(e))t.data!==void 0&&(yield t.data)}async function*WO(e){if(!e.response.body)throw Error(`Response has no body.`);let t=e.response.body.getReader(),n=new TextDecoder,r=``,i=!1,a=()=>{t.cancel(e.signal?.reason).catch(()=>void 0)};e.signal?.addEventListener(`abort`,a,{once:!0}),e.signal?.aborted&&a();try{for(;!e.signal?.aborted;){let{done:a,value:o}=await t.read();for(a?(i=!0,r+=n.decode()):r+=n.decode(o,{stream:!0});;){let t=GO(r,a);if(!t)break;let n=t.index+t.length,i=r.slice(0,t.index),o=r.slice(0,n);if(r=r.slice(n),!i.trim())continue;let s=kD(i.replace(/\r\n|\r/g,`
232
232
  `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function GO(e,t){for(let n=0;n<e.length;n++){let r=KO(e,n,t);if(!r)continue;let i=KO(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function KO(e,t,n){return e[t]===`
@@ -245,13 +245,15 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
245
245
  `);else try{let t=JSON.parse(e);u(t.token??t.choices?.[0]?.delta?.content??e)}catch{u(e)}o=``}}};for(;;){let{done:e,value:t}=await r.read();if(e)break;a+=i.decode(t,{stream:!0});let n=a.split(`
246
246
  `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await SF({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId,fetchUrl:t.fetchUrl,fetchInit:t.fetchInit,session:t.session,info:t.info,verbose:t.verbose,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,confirmEnabled:!1})}async function SF(e){let t=await e.session.signVoucher({channelId:e.channelId,cumulativeAmount:e.cumulativeAmount,escrowContract:e.escrowContract,chainId:e.chainId,action:`close`}),n=await globalThis.fetch(e.fetchUrl,{...e.fetchInit,headers:{...cT(e.fetchInit.headers),Authorization:t}});if(n.ok){if(FF(e.channelId),e.verbose>=1){let t=n.headers.get(q.paymentReceipt),r;if(t)try{let e=JSON.parse(A.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${X.dim(Ek(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${Mk(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${X.dim(X.yellow(`Channel close failed`))} ${X.dim(`(${n.status})`)}\n`),e.info(`${X.dim(` channelId: ${e.channelId}`)}\n${X.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${X.dim(` escrowContract: ${e.escrowContract}`)}\n${X.dim(` chainId: ${e.chainId}`)}\n${X.dim(` response: ${t||`(empty)`}`)}\n`)}}function CF(e=100){return!process.stdin.isTTY||!process.stdout.isTTY?Promise.resolve(void 0):new Promise(t=>{let n=process.stdin.isRaw,r=``,i=()=>{clearTimeout(a),process.stdin.removeListener(`data`,o),process.stdin.isTTY&&process.stdin.setRawMode(n??!1),process.stdin.pause()},a=setTimeout(()=>{i(),t(void 0)},e),o=e=>{r+=e.toString();let n=r.match(/\x1b\]11;rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!n)return;i();let a=e=>Number.parseInt(e.slice(0,2),16);t({r:a(n[1]),g:a(n[2]),b:a(n[3])})};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,o),process.stdout.write(`\x1B]11;?\x07`)})}function wF(e){return OF(WF,e,GF)}function TF(e){return e.method===`tempo`&&e.intent===`charge`}async function EF(e){let t=eA(e.options.account),n=process.env.MPPX_PRIVATE_KEY?.trim()||(kk(t)?void 0:await tA(t).get()),r;if(n)r=xe(n).address;else if(kk(t)&&zF())r=RF(t)?.wallet_address;else{let e=VF();if(e){let t=await tA(e).get();t&&(r=xe(t).address)}}if(!r)return;let i=Nk(e.options.rpcUrl,{network:e.options.network}),a=M({chain:await Fk({network:e.options.network,rpcUrl:i}),transport:de(i)});return{account:r,client:a}}async function DF(e,t){let n=e.request,r=n.currency,i=n.amount;if(typeof r!=`string`||typeof i!=`string`)return`unsupported`;let a=n.methodDetails?.chainId;if(a&&t.client.chain?.id&&a!==t.client.chain.id)return`unsupported`;let o=BigInt(i);if(o===0n)return`payable`;let s=await Le.token.getBalance(t.client,{account:t.account,token:r}).then(e=>e.amount).catch(()=>void 0);return s===void 0?`unknownBalance`:s>=o?`payable`:`insufficientBalance`}function OF(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function kF(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new I({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function AF(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function jF(e){let t=AF(e.tokenIn)??AF(e.payWith);if(!(!e.autoSwap&&!t&&e.slippage===void 0)){if(e.autoSwap===!1&&!t&&e.slippage===void 0)return!1;if(e.slippage!==void 0&&(!Number.isFinite(e.slippage)||e.slippage<0))throw Error(`Invalid CLI options (slippage: expected a non-negative number)`);return{...t?{tokenIn:t}:{},...e.slippage===void 0?{}:{slippage:e.slippage}}}}function MF(){return c.join(process.env.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`mppx`,`channels`)}function NF(e){try{let n=t.readFileSync(c.join(MF(),e),`utf-8`).trim();return n?BigInt(n):void 0}catch{return}}function PF(e,n){let r=MF();t.mkdirSync(r,{recursive:!0}),t.writeFileSync(c.join(r,e),n.toString(),`utf-8`)}function FF(e){try{t.unlinkSync(c.join(MF(),e))}catch{}}function IF(){return x.platform()===`darwin`?c.join(x.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):c.join(process.env.XDG_DATA_HOME||c.join(x.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function LF(){try{let e=t.readFileSync(IF(),`utf-8`),n=[],r;for(let t of e.split(`
247
247
  `)){let e=t.trim();if(e===`[[keys]]`){r?.wallet_address&&n.push(r),r={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!r)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?r.wallet_type=o:a===`wallet_address`?r.wallet_address=o:a===`chain_id`&&(r.chain_id=Number.parseInt(o,10))}return r?.wallet_address&&n.push(r),n}catch{return[]}}function RF(e){let t=LF();if(t.length===0)return;let n=e.slice(6);if(n==="default"||n===``)return t[0];let r=Number.parseInt(n,10);if(!Number.isNaN(r)&&r>=0&&r<t.length)return t[r]}function zF(){if(qF!==void 0)return qF;try{m.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),qF=!0}catch{qF=!1}return qF}async function BF(e){return new Promise((t,n)=>{m.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function VF(){let e=$k();if(kk(e.get())&&!zF()&&x.platform()===`darwin`)try{let t=m.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===HF&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}var HF,UF,WF,GF,KF,qF,JF=F((()=>{Nx(),$T(),Bx(),VS(),mF(),RD(),JM(),sA(),qk(),sj(),HF=`mppx`,UF=p.union([p.boolean(),p.literal(`true`).transform(()=>!0),p.literal(`false`).transform(()=>!1)]),WF=p.object({allowCustomEscrow:p.optional(UF),autoSwap:p.optional(UF),channel:p.optional(p.coerce.string()),deposit:p.optional(p.union([p.string(),p.number()])),payWith:p.optional(p.string()),slippage:p.optional(p.coerce.number()),tokenIn:p.optional(p.string())}),GF=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`],KF=[`payable`,`unknownBalance`,`insufficientBalance`,`unsupported`]}));tC(),sA(),sj();const YF=[...Object.entries(mA),...Object.entries(hA),...Object.entries(gA),...Object.entries(_A)];function XF(){return oj({method:`evm`,supports:ZF,async setup({challenge:e,options:t}){let n=e.request,r=n.network?QF(wA(n.network)):void 0,i=n.network&&n.asset?YF.find(([,e])=>SA(e,n.asset,n.network)):void 0,a=n.extra?.name,o=n.extra?.version,s=n.asset&&n.network&&typeof a==`string`&&typeof o==`string`?fA({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await iA(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...aj({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function ZF(e){if(!$S(e))return!1;let t=e.request,n=t.extra,r=n?.assetTransferMethod;return t.scheme===`exact`&&typeof t.asset==`string`&&typeof t.network==`string`&&typeof n?.name==`string`&&typeof n?.version==`string`&&(r===void 0||r===`eip3009`)}function QF(e){return Object.values(Ze).find(t=>t.id===e)}CS(),SC(),Wx(),JF();const $F=[vF(),_j(),cj(),XF()];async function eI(e,t,n){let r=n;for(let n of t??[]){let t=await n.preparePayment?.({challenge:e,...r===void 0?{}:{credentialContext:r}});t&&`credentialContext`in t&&(r=t.credentialContext)}return r}function tI(e,t){let n=t?.plugins?.find(t=>aI(t,e));if(n)return{plugin:n};let r=iI(t)?.filter(t=>t.name===e.method&&t.intent===e.intent),i=r?.find(t=>t.canHandleChallenge?.({challenge:e})??!0);if(i)return{method:i};if(r?.length)return{};let a=$F.find(t=>aI(t,e));return a?{plugin:a}:{}}function nI(e,t){let n=iI(t);if(n?.length){let r=oC(e,n,rC(n,t?.paymentPreferences).entries);if(r){let e=t?.plugins?.find(e=>aI(e,r.challenge));return{challenge:r.challenge,...e?{plugin:e}:{method:r.method}}}return}for(let n of e){let e=tI(n,t);if(e.plugin||e.method)return{challenge:n,...e}}}function rI(e){let t=iI(e);if(t?.length)return rC(t,e?.paymentPreferences).header}function iI(e){return Array.isArray(e?.methods)?e.methods.flat():void 0}function aI(e,t){return e.supports?e.supports(t):e.method===t.method}async function oI(e){let t=sI(e);if(!t)return;let n=await import(t);return{config:n.default??n,path:t}}function sI(e){if(e){let n=c.resolve(e);return t.existsSync(n)?n:void 0}let n=process.env.MPPX_CONFIG?.trim();if(n){let e=c.resolve(n);return t.existsSync(e)?e:void 0}}function cI(e,t){function n(t){let n={...t.request};if(t.method===`tempo`&&t.intent===`session`){let e={...n.methodDetails};delete e.sessionSnapshot,Object.keys(e).length?n.methodDetails=e:delete n.methodDetails}let{meta:r,opaque:i,...a}=t;return JSON.stringify([iS({...a,request:n,id:e.id,expires:e.expires}),lI(t)])}if(n(t)!==n(e))throw Error(`Payment request changed on retry. Run the command again to approve the new payment.`)}function lI(e){let t=e.opaque??(e.meta?Ux(e.meta):void 0);if(t===void 0)return;let n;try{n=Vx(t)}catch{return t}if(typeof n!=`object`||!n||Array.isArray(n))return t;let r=uA(n);return r?Ux(r):void 0}JF(),CS(),rT(),lN(),EP(),IP(),fk();function uI(e){return e??globalThis.fetch.bind(globalThis)}function dI(e,t){let n=e.request.methodDetails?.chainId;if(n!==void 0&&n!==t.chainId)throw Error(`Close challenge changed the session chain.`);if(typeof e.request.recipient!=`string`||e.request.recipient.toLowerCase()!==t.descriptor.payee.toLowerCase())throw Error(`Close challenge changed the session payee.`);if(typeof e.request.currency!=`string`||e.request.currency.toLowerCase()!==t.descriptor.token.toLowerCase())throw Error(`Close challenge changed the session token.`);if(nN(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Error(`Close challenge changed the session escrow.`);let r=AO(e);if(r&&r.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Close challenge changed the session channel.`)}async function fI(e){dI(e.challenge,e.channel);let t=e.channel;if(t.origin===void 0){let n=new URL(e.input instanceof Request?e.input.url:e.input);if(![`http:`,`https:`].includes(n.protocol))throw Error(`Legacy session close requires an HTTP origin`);$w(e.challenge,n,e.manager.trustedTempoProofRealms),t={...t,origin:n.origin}}let n=uI(e.fetch),r,i=async(t,i)=>{r&&=(await e.onChallenge?.(r),void 0);let a=await n(t,i);if(a.status!==402)return a;let o=mS(a).find(OO);if(!o)throw Error(`Refreshed close response did not include tempo/session.`);return dI(o,e.channel),r=o,a},a=FP({...e.manager,bootstrap:!1,escrow:e.channel.escrow,fetch:i});wP(a).rehydrate({...e,channel:t}),t!==e.channel&&await e.manager.channelStore?.set(t);let o=await a.close();if(!o)throw Error(`Session close response did not include a payment receipt.`);return{manager:a,receipt:o}}CS(),lN(),SN(),fk(),OM(),nS();var pI=class extends Error{name=`SessionStateError`;code=`SESSION_STATE_INVALID`;file;constructor(e,t={}){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.file=t.file}},mI=class extends Error{name=`SessionBusyError`;code=`SESSION_BUSY`;exitCode=75;scope;owner;constructor(e,t){super(`Session scope is busy in process ${t.pid} on ${t.hostname}.`),this.scope=e,this.owner=t}};const hI=J.object({origin:J.optional(J.string()),channelId:Qx(),cumulativeAmount:J.string(),deposit:J.string(),descriptor:J.object({payer:Zx(),payee:Zx(),operator:Zx(),token:Zx(),salt:Qx(),authorizedSigner:Zx(),expiringNonceHash:Qx()}),escrow:Zx(),chainId:J.number(),opened:J.boolean()}),gI=J.object({name:J.optional(J.string()),address:Zx()}),_I=J.object({method:J.literal(`tempo`),intent:J.literal(`session`),status:J.literal(`success`),timestamp:J.string(),reference:J.string(),challengeId:J.string(),channelId:Qx(),acceptedCumulative:J.string(),spent:J.string(),units:J.optional(J.number()),txHash:J.optional(Qx())}),vI=J.object({version:J.literal(1),method:J.literal(`tempo`),intent:J.literal(`session`),status:J.enum([`opening`,`open`,`closing`,`stale`]),channel:hI,account:gI,endpoint:J.string(),challenge:SS,receipt:J.optional(_I),spent:J.string(),units:J.number(),createdAt:J.string(),updatedAt:J.string()}),yI=J.object({version:J.literal(1),channelId:Qx()}),bI=J.object({version:J.literal(1),scope:J.string(),hostname:J.string(),pid:J.number(),token:J.string(),createdAt:J.string()});function xI(e,t,n,r){let i=e.safeParse(t);if(!i.success)throw Z(n,r,i.error);return i.data}function SI(e){let t=MI(e);return[t.payer,t.payee,t.token,t.escrow,t.chainId].join(`:`)}function CI(e){return{payer:e.descriptor.payer,payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId}}function wI(e={}){let t=e.stateRoot??EI(),n={root:t,channels:c.join(t,`channels`),locks:c.join(t,`locks`),preferred:c.join(t,`preferred`)},r=e.hostname??x.hostname(),i=e.pid??process.pid,a=e.now??(()=>new Date),o=e.isProcessAlive??iL;async function s(){for(let e of[n.root,n.channels,n.locks,n.preferred])await w.mkdir(e,{recursive:!0,mode:448}),await w.chmod(e,448)}async function l(e){let t=AI(e),r=DI(n,t),i=await YI(r);if(i===void 0)return;let a=BI(i,r);if(a.channel.channelId.toLowerCase()!==t)throw Z(r,`Session filename does not match its channel ID.`);return VI(a)}async function u(){let e;try{e=await w.readdir(n.channels,{withFileTypes:!0})}catch(e){if(oL(e,`ENOENT`))return[];throw Z(n.channels,`Unable to list managed sessions.`,e)}let t=[];for(let n of e){if(!n.isFile()||n.name.includes(`.tmp-`)||!n.name.endsWith(`.json`))continue;let e=n.name.slice(0,-5);AI(e);let r=await l(e);r&&t.push(r)}return t.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}async function d(e){await s();let t=II(e.channel),r=AI(t.channelId),i=DI(n,r),o=await YI(i),c=o===void 0?void 0:BI(o,i);c&&HI(c,e,i);let l=c?.channel.origin??t.origin;if(c?.channel.origin&&t.origin&&c.channel.origin!==t.origin)throw Z(i,`Session payment origin mismatch.`);if(l!==void 0&&new URL(l).origin!==l)throw Z(i,`Session payment origin must be a normalized origin.`);let u=RI(e.challenge,i);WI(u,t,i);let d=e.receipt?zI(e.receipt,t.channelId,i):void 0,f=c?mN(c.channel):void 0,p=JI(t.cumulativeAmount,f?.cumulativeAmount??0n),m=JI(e.spent??0n,d?BigInt(d.spent):0n,c?BigInt(c.spent):0n);if(m>p)throw Z(i,`Session spend exceeds the locally authorized cumulative amount.`);let h=LI(pN({...t,cumulativeAmount:p,...l!==void 0&&{origin:l}}),i),g=qI(c?.updatedAt,a(),i),_=KI(c?.receipt,d),v=FI(e.account,i),y=BI({version:1,method:`tempo`,intent:`session`,status:e.status,channel:h,account:{...v.name===void 0?c?.account.name===void 0?{}:{name:c.account.name}:{name:v.name},address:v.address},endpoint:PI(e.endpoint,i),challenge:u,..._!==void 0&&{receipt:_},spent:m.toString(),units:Math.max(c?.units??0,e.units??0,d?.units??0),createdAt:c?.createdAt??g,updatedAt:g},i);return await XI(i,y),VI(y)}async function f(e){let t=kI(n,e),r=await YI(t);if(r===void 0)return;let{channelId:i}=xI(yI,r,t,`Preferred session is invalid.`),a=await l(i);if(!a)throw Z(t,`Preferred session ${i} does not exist.`);return GI(a.channel,e,t),i}async function p(e,t){let r=AI(t),i=await l(r),a=kI(n,e);if(!i)throw Z(a,`Session ${r} does not exist.`);GI(i.channel,e,a),await XI(a,{version:1,channelId:r})}async function m(e,t){let r=kI(n,e),i=t===void 0?void 0:AI(t),a=await YI(r);if(a===void 0)return;let o=xI(yI,a,r,`Preferred session is invalid.`).channelId;i&&o.toLowerCase()!==i||await nL(r,`Unable to clear preferred session.`)}async function h(e){let t=AI(e),r=await l(t);r&&(await m(CI(r.channel),t),await nL(DI(n,t),`Unable to remove session.`))}async function g(e){await s();let t=OI(n,e);for(let n=0;n<3;n++){let n={version:1,scope:e,hostname:r,pid:i,token:v(),createdAt:a().toISOString()};try{if(await ZI(t,n),await eL($I(t))){await tL(t,n);continue}return{async release(){await tL(t,n)}}}catch(e){if(!oL(e,`EEXIST`))throw e}let s=await YI(t);if(s===void 0)continue;let c=xI(bI,s,t,`Session lock is invalid.`);if(c.scope!==e)throw Z(t,`Session lock scope is invalid.`);if(c.hostname!==r||o(c.pid))throw new mI(e,c);await QI(t,c)}let c=await YI(t);throw c===void 0?Z(t,`Unable to acquire session lock.`):new mI(e,xI(bI,c,t,`Session lock is invalid.`))}async function _(e){return g(SI(e))}return{root:t,get:l,list:u,upsert:d,remove:h,getPreferred:f,setPreferred:p,clearPreferred:m,acquire:_}}function TI(e,t){let n=NI(t.scope),r=t.selection===`auto`||t.selection===`new`?void 0:AI(t.selection);function i(e){if(e.toLowerCase()!==n)throw new pI(`Session manager requested an unexpected payment scope.`)}async function a(n=!0){if(t.selection===`new`&&!r)return;let i=r??await e.getPreferred(t.scope);if(!i)return;let a=await e.get(i);if(!a)throw new pI(`Session ${i} does not exist.`);if(GI(a.channel,t.scope),!(n&&(a.status!==`open`||!a.channel.opened)))return r=i,a}return{async get(e){return i(e),(await a())?.channel},async set(n){if(i(dN(n)),GI(n,t.scope),r&&r.toLowerCase()!==n.channelId.toLowerCase())throw new pI(`Session manager selected ${r}, but attempted to store ${n.channelId}.`);r||t.onNewChannel?.(n);let a=await e.upsert({...t.context(),channel:n});r=a.channel.channelId,await e.setPreferred(t.scope,a.channel.channelId)},async delete(n){i(n);let o=await a(!1);if(!o)return;let s=t.context();await e.upsert({...o,...s,status:s.status===`closing`?`closing`:`stale`,channel:o.channel,spent:s.spent??o.spent,units:s.units??o.units}),s.status!==`closing`&&await e.clearPreferred(t.scope,o.channel.channelId),r=void 0}}}function EI(){let e=process.env.XDG_STATE_HOME||c.join(x.homedir(),`.local`,`state`);return c.join(e,`mppx`,`sessions`,`v1`)}function DI(e,t){return c.join(e.channels,`${t}.json`)}function OI(e,t){let n=_(`sha256`).update(t).digest(`hex`);return c.join(e.locks,`${n}.lock`)}function kI(e,t){let n=_(`sha256`).update(SI(t)).digest(`hex`);return c.join(e.preferred,`${n}.json`)}function AI(e){return xI(Qx(),e,void 0,`Invalid session channel ID: ${e}.`).toLowerCase()}function jI(e,t,n){return xI(Zx(),e,n,`Invalid ${t}.`).toLowerCase()}function MI(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<0)throw new pI(`Invalid session chain ID.`);return{payer:jI(e.payer,`session payer`),payee:jI(e.payee,`session payee`),token:jI(e.token,`session token`),escrow:jI(e.escrow,`session escrow`),chainId:e.chainId}}function NI(e){let t=MI(e);return[t.payee,t.token,t.escrow,t.chainId].join(`:`)}function PI(e,t){if(typeof e!=`string`)throw Z(t,`Session endpoint is invalid.`);let n;try{n=new URL(e)}catch(e){throw Z(t,`Session endpoint is invalid.`,e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Z(t,`Session endpoint must use HTTP or HTTPS.`);if(n.username||n.password)throw Z(t,`Session endpoint must not contain credentials.`);let r=e.indexOf(`#`);return r===-1?e:e.slice(0,r)}function FI(e,t){return xI(gI,e,t,`Session account is invalid.`)}function II(e){return mN(LI(pN(e)))}function LI(e,t){return xI(hI,e,t,`Stored session channel is invalid.`)}function RI(e,t){let n=SS.safeParse(e);if(!n.success||!OO(n.data))throw Z(t,`Stored session challenge is invalid.`);return n.data}function zI(e,t,n){let r=xI(_I,e,n,`Stored session receipt is invalid.`);if(r.channelId!==t.toLowerCase())throw Z(n,`Stored session receipt has a different channel ID.`);if(r.reference.toLowerCase()!==t.toLowerCase())throw Z(n,`Stored session receipt has a different reference.`);if(BigInt(r.spent)>BigInt(r.acceptedCumulative))throw Z(n,`Stored session receipt spend exceeds its accepted amount.`);return r}function BI(e,t){let n=xI(vI,e,t,`Stored session is invalid.`),{receipt:r,...i}=n,a=n.channel,o=n.account;if(o.address.toLowerCase()!==a.descriptor.payer.toLowerCase())throw Z(t,`Stored session account does not match the channel payer.`);let s=r?zI(r,a.channelId,t):void 0,c=n.spent,l=BigInt(a.cumulativeAmount);if(BigInt(c)>l)throw Z(t,`Stored session spend exceeds its cumulative authorization.`);if(s&&BigInt(s.acceptedCumulative)>l)throw Z(t,`Stored receipt exceeds the cumulative authorization.`);if(Date.parse(n.updatedAt)<Date.parse(n.createdAt))throw Z(t,`Stored session timestamps are not monotonic.`);let u=PI(n.endpoint,t);if(u!==n.endpoint)throw Z(t,`Stored session endpoint contains a fragment.`);let d=RI(n.challenge,t);return WI(d,mN(a),t),{...i,account:o,channel:a,endpoint:u,challenge:d,...s&&{receipt:s}}}function VI(e){return{version:1,status:e.status,channel:mN(e.channel),account:e.account,endpoint:e.endpoint,challenge:e.challenge,...e.receipt&&{receipt:e.receipt},spent:BigInt(e.spent),units:e.units,createdAt:e.createdAt,updatedAt:e.updatedAt}}function HI(e,t,n){let r=II(t.channel),i=FI(t.account,n),a=mN(e.channel);if(JSON.stringify(UI(r))!==JSON.stringify(UI(a)))throw Z(n,`Session update changed immutable channel identity.`);if(i.address.toLowerCase()!==e.account.address.toLowerCase())throw Z(n,`Session update changed the payer account.`)}function UI(e){return{channelId:e.channelId.toLowerCase(),descriptor:Object.fromEntries(Object.entries(e.descriptor).map(([e,t])=>[e,typeof t==`string`?t.toLowerCase():t])),escrow:e.escrow.toLowerCase(),chainId:e.chainId}}function WI(e,t,n){if(wM({...t.descriptor,chainId:t.chainId,escrow:t.escrow}).toLowerCase()!==t.channelId.toLowerCase())throw Z(n,`Session channel ID does not match its descriptor.`);let r=jI(e.request.recipient,`challenge recipient`,n),i=jI(e.request.currency,`challenge currency`,n);if(r!==t.descriptor.payee.toLowerCase())throw Z(n,`Session challenge payee does not match the channel.`);if(i!==t.descriptor.token.toLowerCase())throw Z(n,`Session challenge token does not match the channel.`);if(nN(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Z(n,`Session challenge escrow does not match the channel.`);if(aL(e.request.methodDetails)){let r=e.request.methodDetails;if(r.chainId!==void 0&&r.chainId!==t.chainId)throw Z(n,`Session challenge chain does not match the channel.`)}}function GI(e,t,n){let r=MI(t);if(e.descriptor.payer.toLowerCase()!==r.payer||e.descriptor.payee.toLowerCase()!==r.payee||e.descriptor.token.toLowerCase()!==r.token||e.escrow.toLowerCase()!==r.escrow||e.chainId!==r.chainId)throw Z(n,`Session channel does not match the selected payment scope.`)}function KI(e,t){return e?t&&Date.parse(t.timestamp)>=Date.parse(e.timestamp)?t:e:t}function qI(e,t,n){if(!Number.isFinite(t.getTime()))throw Z(n,`Session clock is invalid.`);let r=t.toISOString();return!e||Date.parse(r)>=Date.parse(e)?r:e}function JI(...e){return e.reduce((e,t)=>t>e?t:e,0n)}async function YI(e){let t;try{t=await w.readFile(e,`utf8`)}catch(t){if(oL(t,`ENOENT`))return;throw Z(e,`Unable to read session state.`,t)}try{return JSON.parse(t)}catch(t){throw Z(e,`Session state contains invalid JSON.`,t)}}async function XI(e,t){await w.mkdir(c.dirname(e),{recursive:!0,mode:448}),await w.chmod(c.dirname(e),448);let n=`${e}.tmp-${process.pid}-${v()}`,r;try{r=await w.open(n,`wx`,384),await r.writeFile(`${JSON.stringify(t,null,2)}\n`,`utf8`),await r.sync(),await r.close(),r=void 0,await w.rename(n,e),await w.chmod(e,384),await rL(c.dirname(e))}catch(t){throw await r?.close().catch(()=>void 0),await w.unlink(n).catch(()=>void 0),t instanceof pI?t:Z(e,`Unable to write session state.`,t)}}async function ZI(e,t){let n;try{n=await w.open(e,`wx`,384),await n.writeFile(`${JSON.stringify(t)}\n`,`utf8`),await n.sync(),await n.close(),n=void 0,await rL(c.dirname(e))}catch(t){throw await n?.close().catch(()=>void 0),n&&await w.unlink(e).catch(()=>void 0),t}}async function QI(e,t){let n=$I(e);try{await w.link(e,n)}catch(t){if(oL(t,`EEXIST`)||oL(t,`ENOENT`))return;throw Z(e,`Unable to claim dead lock.`,t)}try{let r=await YI(n);if(r===void 0||xI(bI,r,n,`Session lock is invalid.`).token!==t.token)return;await nL(e,`Unable to reclaim dead lock.`)}finally{await nL(n,`Unable to release dead lock claim.`)}}function $I(e){return`${e}.reclaim`}async function eL(e){try{return await w.access(e),!0}catch(t){if(oL(t,`ENOENT`))return!1;throw Z(e,`Unable to inspect session lock.`,t)}}async function tL(e,t){let n=await YI(e);n!==void 0&&xI(bI,n,e,`Session lock is invalid.`).token===t.token&&await nL(e,`Unable to release session lock.`)}async function nL(e,t){try{await w.unlink(e),await rL(c.dirname(e))}catch(n){if(!oL(n,`ENOENT`))throw Z(e,t,n)}}async function rL(e){let t=await w.open(e,`r`);try{await t.sync()}finally{await t.close()}}function iL(e){try{return process.kill(e,0),!0}catch(e){if(oL(e,`ESRCH`))return!1;if(oL(e,`EPERM`))return!0;throw e}}function aL(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function oL(e,t){return e instanceof Error&&`code`in e&&e.code===t}function Z(e,t,n){return new pI(t,{...n!==void 0&&{cause:n},file:e})}Nx(),$T(),uP(),DN(),OM(),sA(),qk();const sL=p.object({status:p.enum([`opening`,`open`,`closing`,`stale`]),channelId:p.string(),account:p.string().optional(),payer:p.string(),payee:p.string(),authorizedSigner:p.string(),token:p.string(),escrow:p.string(),chainId:p.number(),cumulativeAmount:p.string(),confirmedSpend:p.string(),deposit:p.string(),units:p.number(),resourceUrl:p.string(),createdAt:p.string(),updatedAt:p.string()}),cL=p.object({channelId:p.string(),status:p.enum([`closed`,`already-closed`]),spent:p.string(),txHash:p.string().optional()}),lL=p.object({closed:p.array(cL),failed:p.array(p.object({channelId:p.string(),message:p.string()}))});function uL(e){return e===`mainnet`?P.id:Se.id}function dL(e){if(e===P.id)return`mainnet`;if(e===Se.id)return`testnet`}function fL(e){let t={};for(let n of e??[]){let e=n.indexOf(`:`);if(e===-1)throw new I({code:`INVALID_HEADER`,message:`Invalid header format: ${n}`,exitCode:2});t[n.slice(0,e).trim()]=n.slice(e+1).trim()}return t}function pL(e){return{status:e.status,channelId:e.channel.channelId,...e.account.name&&{account:e.account.name},payer:e.channel.descriptor.payer,payee:e.channel.descriptor.payee,authorizedSigner:e.channel.descriptor.authorizedSigner,token:e.channel.descriptor.token,escrow:e.channel.escrow,chainId:e.channel.chainId,cumulativeAmount:e.channel.cumulativeAmount.toString(),confirmedSpend:e.spent.toString(),deposit:e.channel.deposit.toString(),units:e.units,resourceUrl:e.endpoint,createdAt:e.createdAt,updatedAt:e.updatedAt}}function mL(e,t){throw e instanceof I?e:e instanceof mI?new I({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e instanceof pI?new I({code:e.code,message:e.message,exitCode:65,cause:e}):new I({code:t,message:e instanceof Error?e.message:String(e),exitCode:75,...e instanceof Error&&{cause:e}})}async function hL(e,t){let n=await rA(t??e.account.name);if(!JN(n.account,e.channel.descriptor))throw new I({code:`SESSION_ACCOUNT_MISMATCH`,message:`Account ${n.account.address} cannot sign for session ${e.channel.channelId}.`,exitCode:2});return n}async function gL(e,t){if(t.network&&uL(t.network)!==e)throw new I({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, not ${t.network}.`,exitCode:2});let n=t.network??dL(e),r=Nk(t.rpcUrl,{network:n}),i=await Fk({network:n,rpcUrl:r});if(i.id!==e)throw new I({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, but RPC is chainId ${i.id}.`,exitCode:2});return M({chain:i,transport:de(r)})}const _L=pb(`sessions`,{description:`Manage persistent payment sessions (list, view, close)`}).command(`list`,{description:`List persistent payment sessions`,options:p.object({account:p.string().optional().describe(`Filter by account name`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Filter by Tempo network`)}),output:p.object({sessions:p.array(sL)}),alias:{account:`a`},async run(e){try{let t=(await wI().list()).filter(t=>!(e.options.account&&t.account.name!==e.options.account||e.options.network&&t.channel.chainId!==uL(e.options.network))).map(pL),n={sessions:t};if(e.format===`json`&&e.formatExplicit)return e.ok(n);t.length===0&&console.log(`No sessions.`);for(let[e,n]of t.entries())e>0&&console.log(``),vL(n);return}catch(e){return mL(e,`SESSION_LIST_FAILED`)}}}).command(`view`,{description:`View a persistent payment session`,args:p.object({channelId:p.string().describe(`Full session channel ID`)}),output:sL,async run(e){try{let t=await wI().get(e.args.channelId);if(!t)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e.args.channelId} was not found.`,exitCode:2});let n=pL(t);if(e.format===`json`&&e.formatExplicit)return e.ok(n);vL(n);return}catch(e){return mL(e,`SESSION_VIEW_FAILED`)}}}).command(`close`,{description:`Cooperatively close persistent payment sessions`,usage:[{suffix:`<channel-id> [options]`},{suffix:`--all --yes [options]`}],args:p.object({channelId:p.string().optional().describe(`Full session channel ID`)}),options:p.object({account:p.string().optional().describe(`Account name`),all:p.boolean().optional().default(!1).describe(`Close every matching session`),header:p.array(p.string()).optional().describe(`Add close request header (repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`),url:p.string().optional().describe(`Override the stored resource URL`),yes:p.boolean().optional().default(!1).describe(`Confirm closing every session`)}),output:p.union([cL,lL]),alias:{account:`a`,header:`H`,rpcUrl:`r`},async run(e){if(e.options.all&&e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all, not both.`,exitCode:2});if(!e.options.all&&!e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all.`,exitCode:2});if(e.options.all&&!e.options.yes)return e.error({code:`CONFIRMATION_REQUIRED`,message:`Closing all sessions requires --yes.`,exitCode:2});if(e.options.all&&(e.options.header||e.options.rpcUrl||e.options.url))return e.error({code:`INVALID_SESSION_CLOSE`,message:`--header, --rpc-url, and --url only apply to a single session.`,exitCode:2});let t=wI();async function n(e,n={}){let r=await t.get(e);if(!r)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let i=CI(r.channel),a=await t.acquire(i);try{let r=await t.get(e);if(!r)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let a=await hL(r,n.account),o=await gL(r.channel.chainId,n);if(wM({...r.channel.descriptor,escrow:r.channel.escrow,chainId:r.channel.chainId}).toLowerCase()!==r.channel.channelId.toLowerCase())throw new I({code:`SESSION_STATE_INVALID`,message:`Stored descriptor does not derive the session channel ID.`,exitCode:65});if((await wN(o,r.channel.channelId,r.channel.escrow)).deposit===0n)return await t.remove(r.channel.channelId),{channelId:r.channel.channelId,status:`already-closed`,spent:r.spent.toString()};let s=PI(n.resourceUrl??r.endpoint),c={...a.source===`keychain`&&{name:a.accountName},address:a.account.address},l=(e=r.challenge)=>({status:`closing`,account:c,endpoint:s,challenge:e,...r.receipt&&{receipt:r.receipt},spent:r.spent,units:r.units}),u=await t.upsert({...l(),channel:r.channel}),d=fL(n.headers),f=u.challenge,p=await fI({channel:u.channel,challenge:u.challenge,fetch:async(e,t)=>globalThis.fetch(e,{...t,headers:{...d,...cT(t?.headers)}}),input:s,spent:u.spent,async onChallenge(e){f=e,await t.upsert({...l(e),channel:u.channel})},manager:{account:a.account,client:o,channelStore:TI(t,{scope:i,selection:u.channel.channelId,context:()=>l(f)})}});return await t.remove(u.channel.channelId),{channelId:u.channel.channelId,status:`closed`,spent:p.receipt.spent,txHash:p.receipt.txHash}}finally{await a.release()}}try{if(e.options.all){let r=(await t.list()).filter(t=>(!e.options.account||t.account.name===e.options.account)&&(!e.options.network||t.channel.chainId===uL(e.options.network))),i=[],a=[];for(let t of r)try{i.push(await n(t.channel.channelId,{account:e.options.account,network:e.options.network}))}catch(e){a.push({channelId:t.channel.channelId,message:e instanceof Error?e.message:String(e)})}let o={closed:i,failed:a};if(a.length>0){for(let e of a)process.stderr.write(`${e.channelId}: ${e.message}\n`);process.exitCode=1}if(e.format===`json`&&e.formatExplicit)return e.ok(o);for(let e of i)console.log(`${e.channelId} ${e.status} ${e.spent}`);for(let e of a)console.log(`${e.channelId} failed ${e.message}`);return}let r=await n(e.args.channelId,{account:e.options.account,headers:e.options.header,network:e.options.network,resourceUrl:e.options.url,rpcUrl:e.options.rpcUrl});if(e.format===`json`&&e.formatExplicit)return e.ok(r);console.log(`${r.channelId} ${r.status} ${r.spent}`),r.txHash&&console.log(` transaction ${r.txHash}`);return}catch(e){return mL(e,`SESSION_CLOSE_FAILED`)}}});function vL(e){console.log(e.channelId),console.log(` status ${e.status}`),console.log(` cumulative amount ${e.cumulativeAmount}`),console.log(` confirmed spend ${e.confirmedSpend}`),console.log(` deposit ${e.deposit}`),console.log(` chain ${e.chainId}`),console.log(` payer ${e.payer}`),console.log(` payee ${e.payee}`),console.log(` token ${e.token}`),console.log(` resource ${e.resourceUrl}`)}Nx(),uP(),EP(),IP(),RD(),sA(),qk();function yL(e,t){if(t&&e!==`auto`&&t.toLowerCase()!==e.toLowerCase())throw new I({code:`SESSION_SELECTION_CONFLICT`,message:`--session and -M channel= select different sessions.`,exitCode:2});let n=t??e;if(n===`auto`||n===`new`)return n;if(/^0x[0-9a-fA-F]{64}$/.test(n))return n.toLowerCase();throw new I({code:`INVALID_SESSION`,message:`Session must be auto, new, or a 32-byte channel ID.`,exitCode:2})}function bL(e){let t=e.allowCustomEscrow;if(t!==void 0){if(t===`true`)return!0;if(t===`false`)return!1;throw new I({code:`INVALID_ALLOW_CUSTOM_ESCROW`,message:`allowCustomEscrow must be true or false.`,exitCode:2})}}function xL(e,t,n,r){if(t.deposit!==void 0)return t.deposit;let i=e.request.suggestedDeposit;return typeof i==`string`?N(BigInt(i),r):n?`10`:void 0}function SL(e,t){if(!e)return;if(e.challengeId!==t.challenge.id)throw Error(`Session receipt challenge does not match the paid request.`);if(e.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Session receipt channel does not match the selected channel.`);let n=BigInt(e.acceptedCumulative),r=BigInt(e.spent);if(n>t.cumulative)throw Error(`Session receipt exceeds the local cumulative authorization.`);if(r>n)throw Error(`Session receipt spend exceeds its accepted authorization.`);return e}function CL(e,t){return e.channel.channelId.toLowerCase()===t.toLowerCase()}function wL(e){if(e.trim()!==`[DONE]`){if(e.length===0){process.stdout.write(`
248
- `);return}try{let t=JSON.parse(e);process.stdout.write(t.token??t.choices?.[0]?.delta?.content??e)}catch{process.stdout.write(e)}}}async function TL(e){let{options:t}=e,n=await rA(t.account),r=Nk(t.rpcUrl,{network:t.network}),i=await Fk({network:t.network,rpcUrl:r}),a=M({chain:i,transport:de(r)}),o=bL(e.methodOptions),s=await HN({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new I({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let{decimals:c}=await zk(a,s.token,n.account.address,{requireDecimals:!0}),l={payer:n.account.address,payee:s.payee,token:s.token,escrow:s.escrow,chainId:s.chainId},u=yL(t.session,e.methodOptions.channel),d=e.registry??wI(),f=await d.acquire(l).catch(e=>{throw e instanceof mI?new I({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=u===`auto`?await d.getPreferred(l):u===`new`?void 0:u,s=r?await d.get(r):void 0;if(r&&!s)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&u!==`auto`&&(s.status!==`open`||!s.channel.opened||SI(CI(s.channel))!==SI(l)||!JN(n.account,s.channel.descriptor)))throw new I({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let f=s?.status===`open`&&s.channel.opened?s:void 0,p=f?`open`:`opening`,m=e.challenge,h=f?.receipt,g=f?.spent??0n,_=f?.units??0,v=PI(e.endpoint),y={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},b=TI(d,{scope:l,selection:u,context:()=>({status:p,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),onNewChannel(){p=`opening`,h=void 0,g=0n,_=0}}),{signal:x,...S}=e.init,C={...S,...x&&{signal:x},onReceipt(e){h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0)}};if(e.challengeResponse.status!==402||e.challengeResponse.bodyUsed)throw Error(`Session manager requires an unconsumed 402 challenge response.`);let w=!0,T=FP({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:b,credentialContext:e.credentialContext,decimals:c,maxDeposit:xL(e.challenge,e.methodOptions,Rk(i),c),fetch:async(t,n)=>w?(w=!1,e.challengeResponse):e.fetch(t,n)});f&&wP(T).rehydrate({channel:f.channel,challenge:e.challenge,input:e.fetchInput,spent:f.spent});let{onReceipt:E,...ee}=C,D=await T.fetch(e.fetchInput,ee);if(t.fail&&D.status>=400)throw new I({code:`HTTP_ERROR`,message:`HTTP error ${D.status}`,exitCode:22});if(D.status===402)throw new I({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});xk(D,{include:!1,verbose:t.include?Math.max(t.verbose,2):t.verbose,silent:t.silent}),m=D.challenge??e.challenge;let O=T.channelId;if(!O)throw Error(`Session manager did not select a channel.`);if(h=SL(D.receipt,{challenge:m,channelId:O,cumulative:T.cumulative})??h,OD(D)){let t=wP(T).consumeSseResponse(e.fetchInput,D,{onReceipt:E,signal:e.init.signal??void 0});for await(let e of t)wL(e)}else process.stdout.write(Buffer.from(await D.arrayBuffer()));let k=await d.get(O);if(!k||!CL(k,O))throw Error(`Session ${O} was not persisted.`);if(h){let e=SL(h,{challenge:m,channelId:O,cumulative:T.cumulative});if(!e)throw Error(`Session receipt validation failed.`);h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0),p=`open`}await d.upsert({status:p,channel:k.channel,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),t.silent||(e.info(`Session retained ${O}\n`),e.info(`Close with: mppx sessions close ${O}\n`))}finally{await f.release()}}const EL=`StripeCLI`;function DL(e){let t=e.env??process.env,n=e.secretKey?.trim();if(n)return{key:n,source:`flag`};let r=t.STRIPE_SECRET_KEY?.trim();if(r)return{key:r,source:`env`};let i=OL(e);if(i)return{key:i,source:`stripe-cli`}}function OL(e){let t=e.env??process.env,n=c.join(t.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`stripe`),r=e.projectName||t.STRIPE_PROJECT_NAME||`default`,i=ML(c.join(n,`config.toml`),r);if(!e.live)return i.test_mode_api_key||i.secret_key||i.api_key||void 0;let a=i.live_mode_api_key;if(a&&!a.includes(`*`))return a;let o=`${r}.live_mode_api_key`,s=jL(c.join(n,`credentials.json`))?.[o];return typeof s==`string`&&s?s:kL(o,e)}function kL(e,t){let n=t.platform??process.platform,r=t.exec??AL,i=(()=>{if(n===`darwin`)return[`security`,[`find-generic-password`,`-s`,EL,`-a`,e,`-w`]];if(n===`linux`)return[`secret-tool`,[`lookup`,`service`,EL,`username`,e]]})();if(i)try{let e=r(i[0],i[1]).trim();return e.startsWith(`go-keyring-base64:`)?Buffer.from(e.slice(18),`base64`).toString(`utf8`)||void 0:e||void 0}catch{return}}function AL(e,t){return g(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:3e3})}function jL(e){try{return JSON.parse(t.readFileSync(e,`utf8`))}catch{return}}function ML(e,n){let r;try{r=t.readFileSync(e,`utf8`)}catch{return{}}let i=new Set([n,`profiles.${n}`]),a={},o;for(let e of r.split(/\r?\n/)){let t=e.trim();if(!t||t.startsWith(`#`))continue;let n=/^\[\s*([^\]]+?)\s*\]$/.exec(t);if(n){o=n[1].replace(/["']/g,``).replace(/\s*\.\s*/g,`.`);continue}if(!o||!i.has(o))continue;let r=/^([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')/.exec(t);r&&(a[r[1]]=r[2]===void 0?r[3]:r[2].replace(/\\(.)/g,`$1`))}return a}function NL(e,n,r){let i=`${n}=${r}`;if(!t.existsSync(e))return t.writeFileSync(e,`${i}\n`,{mode:384});let a=t.readFileSync(e,`utf8`),o=RegExp(`^(?:export\\s+)?${n}\\s*=.*$`,`m`);if(o.test(a))return t.writeFileSync(e,a.replace(o,()=>i));let s=a===``||a.endsWith(`
248
+ `);return}try{let t=JSON.parse(e);process.stdout.write(t.token??t.choices?.[0]?.delta?.content??e)}catch{process.stdout.write(e)}}}async function TL(e){let{options:t}=e,n=await rA(t.account),r=Nk(t.rpcUrl,{network:t.network}),i=await Fk({network:t.network,rpcUrl:r}),a=M({chain:i,transport:de(r)}),o=bL(e.methodOptions),s=await HN({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new I({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let{decimals:c}=await zk(a,s.token,n.account.address,{requireDecimals:!0}),l={payer:n.account.address,payee:s.payee,token:s.token,escrow:s.escrow,chainId:s.chainId},u=yL(t.session,e.methodOptions.channel),d=e.registry??wI(),f=await d.acquire(l).catch(e=>{throw e instanceof mI?new I({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=u===`auto`?await d.getPreferred(l):u===`new`?void 0:u,s=r?await d.get(r):void 0;if(r&&!s)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&u!==`auto`&&(s.status!==`open`||!s.channel.opened||SI(CI(s.channel))!==SI(l)||!JN(n.account,s.channel.descriptor)))throw new I({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let f=s?.status===`open`&&s.channel.opened?s:void 0,p=f?`open`:`opening`,m=e.challenge,h=f?.receipt,g=f?.spent??0n,_=f?.units??0,v=PI(e.endpoint),y={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},b=TI(d,{scope:l,selection:u,context:()=>({status:p,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),onNewChannel(){p=`opening`,h=void 0,g=0n,_=0}}),{signal:x,...S}=e.init,C={...S,...x&&{signal:x},onReceipt(e){h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0)}};if(e.challengeResponse.status!==402||e.challengeResponse.bodyUsed)throw Error(`Session manager requires an unconsumed 402 challenge response.`);let w=!0,T=FP({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:b,credentialContext:e.credentialContext,decimals:c,maxDeposit:xL(e.challenge,e.methodOptions,Rk(i),c),fetch:async(t,n)=>w?(w=!1,e.challengeResponse):e.fetch(t,n)});f&&wP(T).rehydrate({channel:f.channel,challenge:e.challenge,input:e.fetchInput,spent:f.spent});let{onReceipt:E,...ee}=C,D=await T.fetch(e.fetchInput,ee);if(t.fail&&D.status>=400)throw new I({code:`HTTP_ERROR`,message:`HTTP error ${D.status}`,exitCode:22});if(D.status===402)throw new I({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});xk(D,{include:!1,verbose:t.include?Math.max(t.verbose,2):t.verbose,silent:t.silent}),m=D.challenge??e.challenge;let O=T.channelId;if(!O)throw Error(`Session manager did not select a channel.`);if(h=SL(D.receipt,{challenge:m,channelId:O,cumulative:T.cumulative})??h,OD(D)){let t=wP(T).consumeSseResponse(e.fetchInput,D,{onReceipt:E,signal:e.init.signal??void 0});for await(let e of t)wL(e)}else process.stdout.write(Buffer.from(await D.arrayBuffer()));let k=await d.get(O);if(!k||!CL(k,O))throw Error(`Session ${O} was not persisted.`);if(h){let e=SL(h,{challenge:m,channelId:O,cumulative:T.cumulative});if(!e)throw Error(`Session receipt validation failed.`);h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0),p=`open`}await d.upsert({status:p,channel:k.channel,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),t.silent||(e.info(`Session retained ${O}\n`),e.info(`Close with: mppx sessions close ${O}\n`))}finally{await f.release()}}const EL=`StripeCLI`;function DL(e){let t=e.env??process.env,n=e.secretKey?.trim();if(n)return{key:n,source:`flag`};let r=t.STRIPE_SECRET_KEY?.trim();if(r)return{key:r,source:`env`};let i=OL(e);if(i)return{key:i,source:`stripe-cli`}}function OL(e){let t=e.env??process.env,n=c.join(t.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`stripe`),r=e.projectName||t.STRIPE_PROJECT_NAME||`default`,i=ML(c.join(n,`config.toml`),r);if(!e.live)return i.test_mode_api_key||i.secret_key||i.api_key||void 0;let a=i.live_mode_api_key;if(a&&!a.includes(`*`))return a;let o=`${r}.live_mode_api_key`,s=jL(c.join(n,`credentials.json`))?.[o];return typeof s==`string`&&s?s:kL(o,e)}function kL(e,t){let n=t.platform??process.platform,r=t.exec??AL,i=(()=>{if(n===`darwin`)return[`security`,[`find-generic-password`,`-s`,EL,`-a`,e,`-w`]];if(n===`linux`)return[`secret-tool`,[`lookup`,`service`,EL,`username`,e]]})();if(i)try{let e=r(i[0],i[1]).trim();return e.startsWith(`go-keyring-base64:`)?Buffer.from(e.slice(18),`base64`).toString(`utf8`)||void 0:e||void 0}catch{return}}function AL(e,t){return g(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:3e3})}function jL(e){try{return JSON.parse(t.readFileSync(e,`utf8`))}catch{return}}function ML(e,n){let r;try{r=t.readFileSync(e,`utf8`)}catch{return{}}let i=new Set([n,`profiles.${n}`]),a={},o;for(let e of r.split(/\r?\n/)){let t=e.trim();if(!t||t.startsWith(`#`))continue;let n=/^\[\s*([^\]]+?)\s*\]$/.exec(t);if(n){o=n[1].replace(/["']/g,``).replace(/\s*\.\s*/g,`.`);continue}if(!o||!i.has(o))continue;let r=/^([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')/.exec(t);r&&(a[r[1]]=r[2]===void 0?r[3]:r[2].replace(/\\(.)/g,`$1`))}return a}function NL(e,t){return typeof t==`string`?e===`solana`?PL(t)===32:/^0x[0-9a-fA-F]{40}$/.test(t):!1}function PL(e){if(!/^[1-9A-HJ-NP-Za-km-z]{1,64}$/.test(e))return;let t=0n;for(let n of e)t=t*58n+BigInt(`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`.indexOf(n));let n=/^1*/.exec(e)[0].length,r=t===0n?``:t.toString(16);return n+Math.ceil(r.length/2)}function FL(e,n,r){if(/[\r\n]/.test(n)||/[\r\n]/.test(r))throw Error(`env values cannot contain line breaks`);let i=`${n}=${r}`;if(!t.existsSync(e))return t.writeFileSync(e,`${i}\n`,{mode:384});let a=t.readFileSync(e,`utf8`),o=RegExp(`^\\s*(?:export\\s+)?${n}\\s*=`),{lines:s,found:c}=IL(a.split(`
249
+ `),o,i),l=a===``||a.endsWith(`
249
250
  `)?``:`
250
- `;t.writeFileSync(e,`${a}${s}${i}\n`)}function PL(e){let t=e.findIndex((t,n)=>t===`stripe`&&e[n+1]===`address`);if(t===-1)return[...e];let n=e.slice(0,t+2);for(let r=t+2;r<e.length;r++){let t=e[r];if(n.push(t),t===`--`){n.push(...e.slice(r+1));break}let i=e[r+1];t===`--env`&&(i===void 0||i.startsWith(`-`))&&n.push(`.env`)}return n}$T(),qk();function Q(e,t){return t?{label:e,detail:t,severity:`pass`}:{label:e,severity:`pass`}}function $(e,t,n){let r={label:e,severity:`fail`};return t&&(r.detail=t),n&&(r.hint=n),r}function FL(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function IL(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}const LL={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function RL(e){let t=LL[e.severity],n=e.detail?`${e.label} (${e.detail})`:e.label;console.log(` ${t} ${n}`),e.hint&&e.severity!==`pass`&&console.log(X.dim(` → ${e.hint}`))}function zL(e){console.log(`\n${X.bold(e)}`)}function BL(e,t){for(let n of e)RL(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`suggested`?t.suggested++:n.severity===`skip`&&t.skipped++}async function VL(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{let n=globalThis.fetch,i=jT(n),a=AT(n),o={[KT]:!0,...t,redirect:`error`,signal:r.signal};return a?(await a.send((e,t)=>i(e,{...t,[KT]:!0}),new Request(e,o))).response:await i(e,o)}finally{clearTimeout(i)}}function HL(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const UL=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function WL(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function GL(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function KL(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!UL.has(n))return null;let r=e.slice(t+1);if(!r)return null;let i=r.startsWith(`/`)?r:`/`+r;return{method:n.toUpperCase(),path:i}}function qL(e,t){if(e){try{let n=JSON.parse(e);if(n&&typeof n==`object`&&!Array.isArray(n)){let e=Object.keys(n);if(e.length>0&&e.every(e=>e.startsWith(`/`))){let e=n[t];return e===void 0?void 0:typeof e==`string`?e:JSON.stringify(e)}}}catch{}return e}}function JL(e){if(!e)return{};let t={};for(let n of e){let e=n.indexOf(`:`);e>0&&(t[n.slice(0,e).trim().toLowerCase()]=n.slice(e+1).trim())}return t}async function YL(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await VL(t,{});if(!e.ok)return{error:`HTTP ${e.status}`};let n=await e.text();return{doc:JSON.parse(n),raw:n}}catch(e){return e instanceof DOMException&&e.name===`AbortError`?{error:`Request timed out after 15s`}:e instanceof SyntaxError?{error:`Invalid JSON`}:{error:e.message}}}async function XL(e){let t=new URL(`/llms.txt`,e).href,n=`llms.txt found and nonempty`;try{let e=await VL(t,{});if(!e.ok)throw Error(`HTTP ${e.status}`);let r=(await e.text()).trim();if(!r)throw Error(`Empty document`);let i=e.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase();if(i&&!i.startsWith(`text/`)||i===`text/html`||/^<(?:!doctype html|html|head|body)\b/i.test(r))throw Error(`Expected text documentation, received non-text or HTML content`);return Q(n,t)}catch(e){return{label:n,detail:`${t}: ${e.message}`,severity:`suggested`,hint:`Serve nonempty text documentation at /llms.txt.`}}}function ZL(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=eR(i.parameters);for(let[a,o]of Object.entries(i)){if(!UL.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=tR(r,eR(i.parameters)),c=s.length>0?s:void 0;if(i[`x-payment-info`]){let n=i[`x-payment-info`];t.push({method:a.toUpperCase(),path:e,amount:n.amount,parameters:c})}else{let t=i.responses;t&&`402`in t&&n.push({method:a.toUpperCase(),path:e,parameters:c})}}}return t.length>0?t:n}function QL(e,t){let n=e.paths;if(!n)return;let r=n[t.path];if(!r)return;let i=r[t.method.toLowerCase()];if(!i?.requestBody)return;let a=i.requestBody.content?.[`application/json`];if(!a)return;if(a.example)return JSON.stringify(a.example);if(a.examples&&typeof a.examples==`object`){let e=Object.values(a.examples)[0];if(e?.value)return JSON.stringify(e.value)}let o=a.schema,s=new Set;if(o=rR(o,e,s),!o||o.type!==`object`)return;let c=iR(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function $L(e,t,n){if(!t.path.startsWith(`/`)||t.path.startsWith(`//`)||t.path.includes(`\\`))throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let r=t.path;t.parameters&&(r=nR(r,t.parameters));let i=r.startsWith(`/`)?r.slice(1):r,a=new URL(e.replace(/\/?$/,`/`)),o=new URL(i,a);if(o.origin!==a.origin)throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let s=o.href;if(n){let e=new URL(s);for(let t of n){let[n,...r]=t.split(`=`);n&&e.searchParams.set(n,r.join(`=`))}s=e.href}return s}function eR(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;e.in===`path`&&typeof e.name==`string`&&t.push(e.schema&&typeof e.schema==`object`?{name:e.name,in:`path`,schema:e.schema,example:e.example}:{name:e.name,in:`path`,example:e.example})}return t}function tR(e,t){let n=[...e];for(let e of t){let t=n.findIndex(t=>t.name===e.name);t>=0?n[t]=e:n.push(e)}return n}function nR(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{let r=t.find(e=>e.name===n&&e.in===`path`);if(!r)return e;let i=r.example??r.schema?.example??r.schema?.default;return i===void 0?e:encodeURIComponent(String(i))})}function rR(e,t,n){if(!e||typeof e.$ref!=`string`)return e;if(n?.has(e.$ref))return;let r=e.$ref.replace(/^#\//,``).split(`/`),i=t;for(let e of r)if(i&&typeof i==`object`)i=i[e];else return;return i}function iR(e,t,n){let r=rR(e,t,n)??e;if(r.const!==void 0)return r.const;if(r.example!==void 0)return r.example;if(r.default!==void 0)return r.default;switch(r.type){case`string`:return r.enum&&Array.isArray(r.enum)?r.enum[0]:r.format===`email`?`test@example.com`:r.format===`uuid`?`00000000-0000-0000-0000-000000000000`:r.format===`uri`||r.format===`url`?`https://example.com`:r.format===`date`?`2026-01-01`:r.pattern===`^\\d{5}(?:-\\d{4})?$`?`10001`:r.pattern===`^[A-Z]{2}$`?`US`:`test`;case`number`:case`integer`:return r.minimum??1;case`boolean`:return!0;case`array`:return[];case`object`:{let e=r.properties;if(!e)return{};let i=r.required||[],a={};for(let r of i){let i=e[r];i&&(a[r]=iR(i,t,n))}return a}default:return null}}CS(),Bx(),Dw(),qk();const aR=Object.values(Ze);function oR(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&aR.find(e=>e.id===t.chainId)?.testnet===!0}async function sR(e,t,n,r){let i=[],a;try{a=$L(e,t,r?.query)}catch(e){return i.push($(`Request URL valid`,e.message)),{results:i}}let o=JL(r?.extraHeaders),s;r?.body&&!r.bodyIsAutogenerated&&(s=r.body,o[`content-type`]||=`application/json`);let c;try{let e={method:t.method};Object.keys(o).length>0&&(e.headers=o),s&&(e.body=s),c=await VL(a,e)}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}if(!s&&(c.status===400||c.status===422)){let e=r?.body??(r?.discoveryDoc?QL(r.discoveryDoc,t):void 0);if(e){n&&console.log(X.dim(` Retrying with body: ${e}`)),s=e,o[`content-type`]=`application/json`;try{c=await VL(a,{method:t.method,headers:o,body:s})}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}}}if(c.status!==402)return c.status===200?i.push(IL(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(IL(`Returns 402 without credentials`,`Got ${c.status} (endpoint requires auth before payment gate)`)):i.push($(`Returns 402 without credentials`,`Got ${c.status} instead`,c.status===400||c.status===422?`Server requires a valid request body before returning 402. Add a requestBody schema with examples to your OpenAPI doc, or use --body.`:`Endpoints that require payment must return HTTP 402 with a WWW-Authenticate: Payment header when no valid credential is provided.`)),{results:i};i.push(Q(`Returns 402 without credentials`));let l=c.headers.get(q.wwwAuthenticate),u=vR(c);if(!l)return u.length>0?(i.push(IL(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(IL(`Not an MPP endpoint`,`No WWW-Authenticate header (may be x402 or other protocol)`)),{results:i};if(u.length>0&&i.push(...u),!l.startsWith(`${Fx.payment} `))return i.push(IL(`Not an MPP endpoint`,`WWW-Authenticate scheme is not Payment`)),{results:i};i.push(Q(`WWW-Authenticate header present`,`Payment scheme`));let d;try{d=mS(c)}catch(e){let t=e.message;i.push($(`Challenge parseable`,t,`The Payment challenge must include a request="<base64url>" parameter containing JSON-encoded payment details.`));let n=l.slice(l.indexOf(` `)+1);return i.push(FL(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0)return i.push($(`Challenge parseable`,`No Payment challenges found in header`)),{results:i};let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push(Q(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=new URL(e).hostname;cR(d,i),lR(d,i),uR(d,i),dR(d,p,i);let m=d.length>1;for(let e of d){let t=e.request;fR(e,t,i,m)}if(n)for(let e of d)console.log(X.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function cR(e,t){let n=e.filter(e=>!e.id);n.length===0?t.push(Q(`Challenge has id`)):t.push($(`Challenge has id`,`${n.length} missing`,`Every challenge must include a unique id field.`))}function lR(e,t){let n=e.filter(e=>!e.realm);n.length===0?t.push(Q(`Challenge has realm`)):t.push($(`Challenge has realm`,`${n.length} missing`,`Set realm to your server's hostname.`))}function uR(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(FL(`Challenge has expiration`,`missing expires field`,`Add an expires field (ISO 8601) to prevent replay attacks.`));return}if(new Date(r.expires)<=n){t.push($(`Challenge expires in the future`,`Expired at ${r.expires}`,`The expires timestamp must be in the future.`));return}}let r=Math.min(...e.map(e=>new Date(e.expires).getTime()-n.getTime()));t.push(Q(`Challenge expires in the future`,`${Math.round(r/6e4)}m from now`))}function dR(e,t,n){let r=e=>e.toLowerCase().replace(/\.$/,``),i=r(t),a=[...new Set(e.map(e=>e.realm??``))].filter(e=>{let t=r(e);return!t||t!==i&&!i.endsWith(`.${t}`)});a.length>0?n.push($(`Realm matches server hostname`,`realm="${a[0]}" vs host="${t}"`,`Set the realm to your production hostname (or base domain) in the challenge.`)):n.push(Q(`Realm matches server hostname`))}function fR(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===Ix.tempo?pR(t,i,n,e):e.method===Ix.stripe?mR(t,i,n):e.method===Ix.evm&&hR(e,t,i,n)}function pR(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if(WL(e.recipient)?n.push(Q(`${t}Valid recipient address`)):e.recipient===void 0&&a?n.push(Q(`${t}Uses splits (no single recipient)`)):e.recipient===void 0?n.push($(`${t}Valid recipient address`,`Missing recipient (and no splits defined)`,`Set request.recipient to a valid 0x address, or use methodDetails.splits for multiple recipients.`)):n.push($(`${t}Valid recipient address`,`Got: ${String(e.recipient)}`,`Set request.recipient to a valid 0x-prefixed 40-hex-char address.`)),WL(e.currency)){let e=oR(r)?`testnet`:`mainnet`;n.push(Q(`${t}Valid currency address`,e))}else n.push($(`${t}Valid currency address`,`Got: ${String(e.currency)}`,`Set request.currency to a valid token address.`));gR(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function mR(e,t,n){gR(e,t,n,`currency's smallest unit (e.g. "100" = $1.00 for USD)`);let r=e.currency;typeof r==`string`&&/^[a-z]{3}$/i.test(r)?n.push(Q(`${t}Valid currency code`,r.toUpperCase())):n.push($(`${t}Valid currency code`,r?`Got: ${r}`:`missing`,`Must be a three-letter ISO currency code (e.g. "usd").`));let i=e.methodDetails,a=i?.networkId;a?n.push(Q(`${t}Has networkId`,a.slice(0,20))):n.push($(`${t}Has networkId`,`Missing methodDetails.networkId`,`Set methodDetails.networkId to your Stripe Business Network profile ID.`));let o=i?.paymentMethodTypes;Array.isArray(o)&&o.length>0?n.push(Q(`${t}Has paymentMethodTypes`,o.join(`, `))):n.push($(`${t}Has paymentMethodTypes`,`Missing or empty`,`Set methodDetails.paymentMethodTypes to an array (e.g. ["card"]).`))}function hR(e,t,n,r){if(WL(t.recipient)?r.push(Q(`${n}Valid recipient address`)):r.push($(`${n}Valid recipient address`,`Got: ${String(t.recipient)}`,`Set request.recipient to a valid 0x-prefixed Ethereum address.`)),WL(t.currency)){let t=oR(e)?`testnet`:`mainnet`;r.push(Q(`${n}Valid currency address`,t))}else r.push($(`${n}Valid currency address`,`Got: ${String(t.currency)}`,`Set request.currency to a valid ERC-20 token contract address.`));gR(t,n,r,`token's smallest unit`);let i=t.methodDetails?.chainId;typeof i==`number`&&i>0?r.push(Q(`${n}Has chainId`,String(i))):r.push($(`${n}Has chainId`,`Missing methodDetails.chainId`,`Set methodDetails.chainId to the EVM chain ID.`))}function gR(e,t,n,r){GL(e.amount)?n.push(Q(`${t}Amount is valid integer string`)):e.amount===void 0||e.amount===null?n.push($(`${t}Amount is valid integer string`,`Missing amount`,`Set request.amount to a string of digits in the ${r}.`)):n.push($(`${t}Amount is valid integer string`,`Got: ${String(e.amount)}`,`request.amount must be a string of digits (no decimals, no prefix).`))}async function _R(e,t,n){let r=[],i=$L(e,t,n?.query),a=JL(n?.extraHeaders),o=n?.challenge?vS(n.challenge):q.authorization;a[o.toLowerCase()]=`${Fx.payment} dGhpcyBpcyBnYXJiYWdl`;let s;n?.body&&(s=n.body,a[`content-type`]||=`application/json`);try{let e=await VL(i,{method:t.method,headers:a,body:s??null});e.status===402?(r.push(Q(`Malformed credential returns 402`,`not 500`)),e.headers.get(q.wwwAuthenticate)?.startsWith(`${Fx.payment} `)?r.push(Q(`Error response includes fresh challenge`)):r.push(FL(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the ${o} header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(FL(`Malformed credential returns 402`,`Got ${e.status}`,`When the ${o} header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function vR(e){let t=[],n=e.headers.get(`payment-required`)??e.headers.get(`x-payment-required`);if(!n)return t;let r=e.headers.get(`payment-required`)?`PAYMENT-REQUIRED`:`X-Payment-Required`;try{let e=bw(n);t.push(Q(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(FL(`x402 payment challenge`,`${r} header present but failed schema validation`,`Ensure the PAYMENT-REQUIRED header contains a valid base64-encoded JSON payload matching the x402 schema.`))}return t}const yR=[`No discovery document found, endpoints could not be automatically found.`,`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,`The MPP SDKs can automatically expose this endpoint. See https://mpp.dev/sdk.`,``,`To test a specific endpoint: mppx validate <url> --endpoint POST:/your/path`].join(`
251
- `);nS();const bR={fundingCurrency:J.optional(J.string()),method:J.string(),reference:J.string(),externalId:J.optional(J.string()),subscriptionId:J.optional(J.string()),status:J.literal(`success`),timestamp:qx()};J.object(bR);const xR=J.looseObject(bR);function SR(e){let t=A.toString(e);return CR(JSON.parse(t))}function CR(e){return xR.parse(e)}CS(),rT(),Bx(),mF(),vk(),fk(),RD(),sA(),qk();async function wR(e,t,n){try{n||console.log(X.dim(` Provisioning testnet wallet and funding via faucet...`));let t=ye(),r=xe(t),i=M({chain:Se,transport:de()});if(OO(e)){let{chainId:t,operator:n}=e.request.methodDetails??{};if(t===Se.id&&typeof n==`string`&&fe(n)&&n!==ve){let e=await Le.faucet.fund(i,{account:n});await Promise.all(e.map(e=>Pe(i,{hash:e})))}}let a=await Le.faucet.fund(i,{account:r});await Promise.all(a.map(e=>Pe(i,{hash:e}))),n||console.log(X.dim(` Using wallet: ${r.address}`));let o=e.request.currency;if(typeof o==`string`)for(let e=0;e<10;e++){let e=await Le.token.getBalance(i,{account:r.address,token:o}).catch(()=>void 0);if(e&&e.amount>0n)break;await new Promise(e=>setTimeout(e,500))}return{methods:[...dF({account:r})]}}catch(e){t&&console.log(X.dim(` Provisioning failed: ${e.message}`));return}}async function TR(){let e=eA(),{isTempoAccount:t}=await Promise.resolve().then(()=>(qk(),yk)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(JF(),hF));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await iA()).address}catch{return}}function ER(e){try{let{execSync:t}=m,n=t(`stripe config --list`,{encoding:`utf8`,timeout:5e3}).match(/test_mode_api_key\s*=\s*'([^']+)'/);if(n?.[1])return e&&console.log(X.dim(` Using Stripe test key from stripe CLI`)),n[1]}catch{}}async function DR(e,t,n){let r=M({chain:e,transport:de()}),[i,a,o]=await Promise.all([n?Oe(r,{address:t,abi:se,functionName:`balanceOf`,args:[n]}):0n,Oe(r,{address:t,abi:se,functionName:`decimals`}),Oe(r,{address:t,abi:se,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,decimals:a,symbol:o??void 0}}function OR(e){return Object.values(Ze).find(t=>t.id===e)}function kR(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function AR(e){switch(e.method){case Ix.evm:return`no EVM payment plugin yet`;case`solana`:return`no Solana payment plugin yet`;default:return`no plugin for ${e.method}/${e.intent}`}}async function jR(e,t,n,r){let i=[],a=$L(e,t,r.query),o=JL(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await VL(a,{method:t.method,headers:o,body:s??null})}catch(e){return i.push($(`Payment: fetch challenge`,e.message)),i}if(c.status!==402)return i.push(IL(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=mS(c)}catch(e){return i.push($(`Payment: parse challenge`,e.message)),i}if(l.length===0)return i.push($(`Payment: parse challenge`,`No Payment challenges in response`)),i;let u=[];dR(l,new URL(a).hostname,u);let d=u.filter(e=>e.severity===`fail`);if(d.length>0)return i.push(...d),r.onResults?.(d),i;let f=await oI().catch(()=>void 0),p=l.find(e=>{if(e.method!==Ix.tempo||iI(f?.config)?.some(t=>t.name===e.method&&t.intent===e.intent))return!1;let t=e.request.methodDetails;return typeof t?.chainId==`number`&&t.chainId!==pk.mainnet});if(p){let e=await wR(p,n,r.silent);if(e)try{let r=RR((e,t)=>VL(e,t??{},3e4));await IR(i,await tE({methods:e.methods,polyfill:!1,async onChallenge(e,{createCredential:t}){cI(p,e);let n=await t(await eI(e,f?.config.extensions));return i.push(Q(`Payment: submitted`,`ephemeral testnet wallet`)),n},fetch:r.fetch}).fetch(a,{method:t.method,headers:o,body:s??null}),n,Se,OO(p),r.receipt)}catch(e){i.push($(`Payment: create credential`,e.message))}else i.push($(`Payment: auto-provision wallet`,`Failed to create and fund testnet wallet`));r.onResults?.(i)}let m=r.interactive,h=process.env.MPPX_STRIPE_SECRET_KEY??ER(n),g=h?.startsWith(`sk_test_`)||h?.startsWith(`rk_test_`),_=new Set([Ix.tempo,Ix.evm,Ix.stripe]);for(let e of l){if(e===p||!_.has(e.method))continue;r.silent||console.log(``);let c=i.length,l=()=>{r.onResults&&i.length>c&&r.onResults(i.slice(c))},u=`Payment [${e.method}]`;try{switch(e.method){case Ix.tempo:case Ix.evm:await MR(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,options:r});break;case Ix.stripe:await NR(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,isStripeTestKey:g??!1,stripeKey:h,options:r})}}finally{l()}}return i}async function MR(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u}=n,d=e.request,f=d.methodDetails,p=GL(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,{plugin:g,method:_}=tI(e,l?.config);if(!g&&!_){r.push(IL(t,AR(e)));return}let v;if(!_){try{v=await TR()}catch{}if(!v){r.push(IL(t,`no wallet configured. Run "mppx account create" to create one.`));return}}let y;if(e.method===Ix.tempo){let e=f?.chainId??(_?void 0:P.id);e!==void 0&&(y=e===Se.id?Se:OR(e))}else if(e.method===Ix.evm){let e=f?.chainId;e&&(y=OR(e))}if(p&&h&&!y){r.push(IL(t,`unable to resolve payment chain and verify token decimals`));return}let b;if(p&&h&&y)try{let n;if(e.method===Ix.tempo){let e=await zk(M({chain:y,transport:de()}),h,v??ve,{requireDecimals:!0});n=e.balance,m=e.decimals,b=e.symbol}else{let e=await DR(y,h,v);n=e.balance,m=e.decimals,b=e.symbol}if(v&&n<p){let e=kR(p,m),i=kR(n,m),a=b??`tokens`;r.push(IL(t,`insufficient balance (have ${i}, need ${e} ${a} on ${y.name})`,`Fund wallet ${v} with at least ${e} ${a} on ${y.name}.`));return}}catch(e){c&&console.log(X.dim(` Balance check skipped: ${e.message}`)),r.push(IL(t,`unable to verify token balance and decimals from the payment chain`));return}let x=p?kR(p,m):`unknown amount`,S=b??(h?.length===3?h.toUpperCase():``),C=y?.name,w=`${x}${S?` ${S}`:``}${C?` on ${C}`:``}`;if(u.silent||console.log(X.dim(v?` Attempting payment with wallet ${v}`:` Attempting payment with configured method`)),!_&&y?.testnet)u.silent||console.log(X.dim(` Auto-approved: ${w} (testnet)`));else if(!u.yes&&!n.isInteractive){r.push(IL(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${w}`));else if(!await jk(` ${X.yellow(`Pay`)} ${w}. Continue?`,!1)){r.push(IL(t,`declined`));return}let T,E,ee;if(g)try{let t=await g.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});T=t.methods,E=t.createCredential,ee=t.credentialContext}catch(e){r.push(IL(t,e.message));return}else T=[_];if(_&&OO(e)){let n=!0,u=RR((e,t)=>VL(e,t??{},3e4)),d=tE({methods:[_],polyfill:!1,async onChallenge(n,{createCredential:i}){let a=await eI(n,l?.config.extensions);cI(e,n);let o=await i(a);return r.push(Q(`${t}: submitted`)),o},fetch:async(t,r)=>n?(n=!1,new Response(null,{status:402,headers:{[q.wwwAuthenticate]:iS(e)}})):u.fetch(t,r)});try{await IR(r,await d.fetch(i,{method:a.method,headers:o,body:s??null}),c,y,!0,u.receipt)}catch(e){r.push($(t,e.message))}return}let D=await PR(e,T,E,t,r,l?.config.extensions,ee,i);D&&(g?.prepareCredentialRequest?.({challenge:e,credential:D,headers:o}),await FR(r,i,a,D,o,s,c,y,vS(e),OO(e)))}async function NR(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u,stripeKey:d}=n,{plugin:f,method:p}=tI(e,l?.config);if(!f&&!p){r.push(IL(t,`no Stripe payment method available`));return}let m=!!(f&&!l?.config.plugins?.includes(f)&&n.isStripeTestKey),h=e.request,g=GL(h.amount)?BigInt(h.amount):void 0,_=h.decimals??2,v=h.currency,y=g?kR(g,_):`unknown amount`,b=v?.length===3?v.toUpperCase():``,x=`${y}${b?` ${b}`:``} via Stripe${m?` (testmode)`:``}`;if(m)u.silent||console.log(X.dim(` Attempting: ${x}`));else if(!u.yes&&!n.isInteractive){r.push(IL(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${x}`));else if(!await jk(` ${X.yellow(`Pay`)} ${x}. Continue?`,!1)){r.push(IL(t,`declined`));return}let S,C,w;if(f)try{let t={paymentMethod:`pm_card_visa`};d&&(t.secretKey=d);let n=await f.setup({challenge:e,options:{},methodOpts:t});S=n.methods,C=n.createCredential,w=n.credentialContext}catch(e){r.push(IL(t,e.message));return}else S=[p];let T=await PR(e,S,C,t,r,l?.config.extensions,w,i);if(T){if(f?.prepareCredentialRequest?.({challenge:e,credential:T,headers:o}),m){let n=await VL(i,{method:a.method,headers:{...o,[vS(e)]:T},body:s??null},3e4);n.status>=200&&n.status<300?r.push(Q(`${t}: successful`,`HTTP ${n.status}`)):r.push(IL(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await FR(r,i,a,T,o,s,c,void 0,vS(e))}}async function PR(e,t,n,r,i,a,o,s){let c=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:iS(e)}});try{$w(e,new URL(s),void 0);let l=await eI(e,a,o),u;return u=n?await n(c,l):await tE({methods:t,polyfill:!1}).createCredential(c,l),i.push(Q(`${r}: submitted`)),u}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(IL(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function FR(e,t,n,r,i,a,o,s,c=q.authorization,l=!1){let u;try{u=await VL(t,{method:n.method,headers:{...i,[c]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}return IR(e,u,o,s,l)}async function IR(e,t,n,r,i=!1,a){if(t.status===402){let n=await t.text().catch(()=>``),r=`Payment rejected`;try{let e=JSON.parse(n);r=e.detail??e.title??r}catch{}return e.push($(`Payment: accepted`,r,`The server rejected a valid credential. Check that your payment verification logic accepts the credential format and that the payment was processed on-chain.`)),e}if(t.status>=400&&t.status<500)e.push(FL(`Payment: post-payment response`,`Got ${t.status}`,`Payment succeeded but the endpoint returned a client error. The endpoint likely requires request body parameters. Use --body to provide them.`));else if(t.status>=500)return e.push($(`Payment: server response`,`Got ${t.status}`,`Payment was accepted but the server errored while generating the response. Check server logs for the underlying error.`)),e;else e.push(Q(`Payment: successful`,`HTTP ${t.status}`));let o=t.headers.get(`content-type`)??``,s=t.headers.get(q.paymentReceipt),c=!s&&i&&OD(t),l=await t.text().catch(()=>``);if(c){let t=a?.(),n=t===void 0?LR(l):t??void 0;n?e.push(Q(`Payment receipt in event stream`,n.reference)):e.push($(`Payment receipt in event stream`,void 0,`SSE session responses without a Payment-Receipt header must end with an "event: payment-receipt" carrying the session receipt.`))}else if(!s)e.push($(`Payment-Receipt header present`,void 0,`After accepting payment, include a Payment-Receipt header with a base64url-encoded JSON object containing: method, reference, status ("success"), and timestamp (ISO 8601).`));else{e.push(Q(`Payment-Receipt header present`));try{let t=SR(s);if(e.push(Q(`Receipt parseable`)),t.status===`success`?e.push(Q(`Receipt status is "success"`)):e.push($(`Receipt status is "success"`,`Got: ${t.status}`)),t.reference){let n=/^0x[0-9a-fA-F]{64}$/.test(t.reference),r=t.reference.startsWith(`pi_`);n||r?e.push(Q(`Receipt reference valid`,t.reference.slice(0,20)+`...`)):e.push(FL(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(FL(`Receipt has reference`,`No reference field`));if(t.timestamp){let n=new Date(t.timestamp),r=Date.now()-n.getTime();r<6e4?e.push(Q(`Receipt timestamp recent`,`${Math.round(r/1e3)}s ago`)):e.push(FL(`Receipt timestamp recent`,`${Math.round(r/6e4)}m ago`))}n&&console.log(X.dim(` Receipt: ${JSON.stringify(t,null,2)}`))}catch(t){e.push($(`Receipt parseable`,t.message))}}if(l.length>0)e.push(Q(`Response body non-empty`,`${o.split(`;`)[0]}, ${HL(l.length)}`));else{let n=[...t.headers.entries()].filter(([e])=>!e.startsWith(`x-`)&&![`content-type`,`content-length`,`date`,`server`,`connection`,`keep-alive`,`cache-control`,`vary`,`access-control-allow-origin`,`payment-receipt`,`payment-session`,`payment-session-snapshot`].includes(e.toLowerCase()));n.length>0?e.push(FL(`Response body empty -- data may be in headers only`,n.map(([e])=>e).join(`, `))):e.push(FL(`Response body empty`))}if(o?e.push(Q(`Content-Type header set`,o.split(`;`)[0])):e.push(FL(`Content-Type header set`)),s)try{let t=SR(s);if(t.reference&&/^0x[0-9a-fA-F]{64}$/.test(t.reference)){let n=r?.blockExplorers?.default?.url;if(n){let r=n.includes(`tempo`)?`receipt`:`tx`;e.push(Q(`On-chain transaction`,`${n}/${r}/${t.reference}`))}}}catch{}return e}function LR(e){for(let t of e.replace(/\r\n|\r/g,`
251
+ `,u=c?s.join(`
252
+ `):`${a}${l}${i}\n`,d=y.parseEnv;if(d){let t=d(a),i=d(u),o=new Set([...Object.keys(t),...Object.keys(i)]);if(o.delete(n),i[n]!==r||[...o].some(e=>t[e]!==i[e]))throw Error(`could not update ${n} in ${e} safely: edit it by hand`)}t.writeFileSync(e,u)}function IL(e,t,n){let r={};for(let t of[`"`,`'`,"`"]){let n=Array(e.length+1);n[e.length]=-1;for(let r=e.length-1;r>=0;r--)n[r]=LL(e[r],t)?r:n[r+1];r[t]=n}let i=[],a=!1;for(let o=0;o<e.length;o++){let s=o,c=/^[ \t]*[^#=\s][^=]*=[ \t]*(["'`])(.*)$/s.exec(e[o]);if(c&&!LL(c[2],c[1])){let e=r[c[1]][o+1];e!==-1&&(s=e)}let l=t.test(e[o]);if(l&&!a&&i.push(e[o].endsWith(`\r`)?`${n}\r`:n),a||=l,!l)for(let t=o;t<=s;t++)i.push(e[t]);o=s}return{lines:i,found:a}}function LL(e,t){return e.includes(t)}function RL(e){let t=e.findIndex((t,n)=>t===`stripe`&&e[n+1]===`address`);if(t===-1)return[...e];let n=e.slice(0,t+2);for(let r=t+2;r<e.length;r++){let t=e[r];if(n.push(t),t===`--`){n.push(...e.slice(r+1));break}let i=e[r+1];t===`--env`&&(i===void 0||i.startsWith(`-`))&&n.push(`.env`)}return n}$T(),qk();function Q(e,t){return t?{label:e,detail:t,severity:`pass`}:{label:e,severity:`pass`}}function $(e,t,n){let r={label:e,severity:`fail`};return t&&(r.detail=t),n&&(r.hint=n),r}function zL(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function BL(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}const VL={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function HL(e){let t=VL[e.severity],n=e.detail?`${e.label} (${e.detail})`:e.label;console.log(` ${t} ${n}`),e.hint&&e.severity!==`pass`&&console.log(X.dim(` → ${e.hint}`))}function UL(e){console.log(`\n${X.bold(e)}`)}function WL(e,t){for(let n of e)HL(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`suggested`?t.suggested++:n.severity===`skip`&&t.skipped++}async function GL(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{let n=globalThis.fetch,i=jT(n),a=AT(n),o={[KT]:!0,...t,redirect:`error`,signal:r.signal};return a?(await a.send((e,t)=>i(e,{...t,[KT]:!0}),new Request(e,o))).response:await i(e,o)}finally{clearTimeout(i)}}function KL(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const qL=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function JL(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function YL(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function XL(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!qL.has(n))return null;let r=e.slice(t+1);if(!r)return null;let i=r.startsWith(`/`)?r:`/`+r;return{method:n.toUpperCase(),path:i}}function ZL(e,t){if(e){try{let n=JSON.parse(e);if(n&&typeof n==`object`&&!Array.isArray(n)){let e=Object.keys(n);if(e.length>0&&e.every(e=>e.startsWith(`/`))){let e=n[t];return e===void 0?void 0:typeof e==`string`?e:JSON.stringify(e)}}}catch{}return e}}function QL(e){if(!e)return{};let t={};for(let n of e){let e=n.indexOf(`:`);e>0&&(t[n.slice(0,e).trim().toLowerCase()]=n.slice(e+1).trim())}return t}async function $L(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await GL(t,{});if(!e.ok)return{error:`HTTP ${e.status}`};let n=await e.text();return{doc:JSON.parse(n),raw:n}}catch(e){return e instanceof DOMException&&e.name===`AbortError`?{error:`Request timed out after 15s`}:e instanceof SyntaxError?{error:`Invalid JSON`}:{error:e.message}}}async function eR(e){let t=new URL(`/llms.txt`,e).href,n=`llms.txt found and nonempty`;try{let e=await GL(t,{});if(!e.ok)throw Error(`HTTP ${e.status}`);let r=(await e.text()).trim();if(!r)throw Error(`Empty document`);let i=e.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase();if(i&&!i.startsWith(`text/`)||i===`text/html`||/^<(?:!doctype html|html|head|body)\b/i.test(r))throw Error(`Expected text documentation, received non-text or HTML content`);return Q(n,t)}catch(e){return{label:n,detail:`${t}: ${e.message}`,severity:`suggested`,hint:`Serve nonempty text documentation at /llms.txt.`}}}function tR(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=iR(i.parameters);for(let[a,o]of Object.entries(i)){if(!qL.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=aR(r,iR(i.parameters)),c=s.length>0?s:void 0;if(i[`x-payment-info`]){let n=i[`x-payment-info`];t.push({method:a.toUpperCase(),path:e,amount:n.amount,parameters:c})}else{let t=i.responses;t&&`402`in t&&n.push({method:a.toUpperCase(),path:e,parameters:c})}}}return t.length>0?t:n}function nR(e,t){let n=e.paths;if(!n)return;let r=n[t.path];if(!r)return;let i=r[t.method.toLowerCase()];if(!i?.requestBody)return;let a=i.requestBody.content?.[`application/json`];if(!a)return;if(a.example)return JSON.stringify(a.example);if(a.examples&&typeof a.examples==`object`){let e=Object.values(a.examples)[0];if(e?.value)return JSON.stringify(e.value)}let o=a.schema,s=new Set;if(o=sR(o,e,s),!o||o.type!==`object`)return;let c=cR(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function rR(e,t,n){if(!t.path.startsWith(`/`)||t.path.startsWith(`//`)||t.path.includes(`\\`))throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let r=t.path;t.parameters&&(r=oR(r,t.parameters));let i=r.startsWith(`/`)?r.slice(1):r,a=new URL(e.replace(/\/?$/,`/`)),o=new URL(i,a);if(o.origin!==a.origin)throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let s=o.href;if(n){let e=new URL(s);for(let t of n){let[n,...r]=t.split(`=`);n&&e.searchParams.set(n,r.join(`=`))}s=e.href}return s}function iR(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;e.in===`path`&&typeof e.name==`string`&&t.push(e.schema&&typeof e.schema==`object`?{name:e.name,in:`path`,schema:e.schema,example:e.example}:{name:e.name,in:`path`,example:e.example})}return t}function aR(e,t){let n=[...e];for(let e of t){let t=n.findIndex(t=>t.name===e.name);t>=0?n[t]=e:n.push(e)}return n}function oR(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{let r=t.find(e=>e.name===n&&e.in===`path`);if(!r)return e;let i=r.example??r.schema?.example??r.schema?.default;return i===void 0?e:encodeURIComponent(String(i))})}function sR(e,t,n){if(!e||typeof e.$ref!=`string`)return e;if(n?.has(e.$ref))return;let r=e.$ref.replace(/^#\//,``).split(`/`),i=t;for(let e of r)if(i&&typeof i==`object`)i=i[e];else return;return i}function cR(e,t,n){let r=sR(e,t,n)??e;if(r.const!==void 0)return r.const;if(r.example!==void 0)return r.example;if(r.default!==void 0)return r.default;switch(r.type){case`string`:return r.enum&&Array.isArray(r.enum)?r.enum[0]:r.format===`email`?`test@example.com`:r.format===`uuid`?`00000000-0000-0000-0000-000000000000`:r.format===`uri`||r.format===`url`?`https://example.com`:r.format===`date`?`2026-01-01`:r.pattern===`^\\d{5}(?:-\\d{4})?$`?`10001`:r.pattern===`^[A-Z]{2}$`?`US`:`test`;case`number`:case`integer`:return r.minimum??1;case`boolean`:return!0;case`array`:return[];case`object`:{let e=r.properties;if(!e)return{};let i=r.required||[],a={};for(let r of i){let i=e[r];i&&(a[r]=cR(i,t,n))}return a}default:return null}}CS(),Bx(),Dw(),qk();const lR=Object.values(Ze);function uR(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&lR.find(e=>e.id===t.chainId)?.testnet===!0}async function dR(e,t,n,r){let i=[],a;try{a=rR(e,t,r?.query)}catch(e){return i.push($(`Request URL valid`,e.message)),{results:i}}let o=QL(r?.extraHeaders),s;r?.body&&!r.bodyIsAutogenerated&&(s=r.body,o[`content-type`]||=`application/json`);let c;try{let e={method:t.method};Object.keys(o).length>0&&(e.headers=o),s&&(e.body=s),c=await GL(a,e)}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}if(!s&&(c.status===400||c.status===422)){let e=r?.body??(r?.discoveryDoc?nR(r.discoveryDoc,t):void 0);if(e){n&&console.log(X.dim(` Retrying with body: ${e}`)),s=e,o[`content-type`]=`application/json`;try{c=await GL(a,{method:t.method,headers:o,body:s})}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}}}if(c.status!==402)return c.status===200?i.push(BL(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(BL(`Returns 402 without credentials`,`Got ${c.status} (endpoint requires auth before payment gate)`)):i.push($(`Returns 402 without credentials`,`Got ${c.status} instead`,c.status===400||c.status===422?`Server requires a valid request body before returning 402. Add a requestBody schema with examples to your OpenAPI doc, or use --body.`:`Endpoints that require payment must return HTTP 402 with a WWW-Authenticate: Payment header when no valid credential is provided.`)),{results:i};i.push(Q(`Returns 402 without credentials`));let l=c.headers.get(q.wwwAuthenticate),u=SR(c);if(!l)return u.length>0?(i.push(BL(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(BL(`Not an MPP endpoint`,`No WWW-Authenticate header (may be x402 or other protocol)`)),{results:i};if(u.length>0&&i.push(...u),!l.startsWith(`${Fx.payment} `))return i.push(BL(`Not an MPP endpoint`,`WWW-Authenticate scheme is not Payment`)),{results:i};i.push(Q(`WWW-Authenticate header present`,`Payment scheme`));let d;try{d=mS(c)}catch(e){let t=e.message;i.push($(`Challenge parseable`,t,`The Payment challenge must include a request="<base64url>" parameter containing JSON-encoded payment details.`));let n=l.slice(l.indexOf(` `)+1);return i.push(zL(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0)return i.push($(`Challenge parseable`,`No Payment challenges found in header`)),{results:i};let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push(Q(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=new URL(e).hostname;fR(d,i),pR(d,i),mR(d,i),hR(d,p,i);let m=d.length>1;for(let e of d){let t=e.request;gR(e,t,i,m)}if(n)for(let e of d)console.log(X.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function fR(e,t){let n=e.filter(e=>!e.id);n.length===0?t.push(Q(`Challenge has id`)):t.push($(`Challenge has id`,`${n.length} missing`,`Every challenge must include a unique id field.`))}function pR(e,t){let n=e.filter(e=>!e.realm);n.length===0?t.push(Q(`Challenge has realm`)):t.push($(`Challenge has realm`,`${n.length} missing`,`Set realm to your server's hostname.`))}function mR(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(zL(`Challenge has expiration`,`missing expires field`,`Add an expires field (ISO 8601) to prevent replay attacks.`));return}if(new Date(r.expires)<=n){t.push($(`Challenge expires in the future`,`Expired at ${r.expires}`,`The expires timestamp must be in the future.`));return}}let r=Math.min(...e.map(e=>new Date(e.expires).getTime()-n.getTime()));t.push(Q(`Challenge expires in the future`,`${Math.round(r/6e4)}m from now`))}function hR(e,t,n){let r=e=>e.toLowerCase().replace(/\.$/,``),i=r(t),a=[...new Set(e.map(e=>e.realm??``))].filter(e=>{let t=r(e);return!t||t!==i&&!i.endsWith(`.${t}`)});a.length>0?n.push($(`Realm matches server hostname`,`realm="${a[0]}" vs host="${t}"`,`Set the realm to your production hostname (or base domain) in the challenge.`)):n.push(Q(`Realm matches server hostname`))}function gR(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===Ix.tempo?_R(t,i,n,e):e.method===Ix.stripe?vR(t,i,n):e.method===Ix.evm&&yR(e,t,i,n)}function _R(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if(JL(e.recipient)?n.push(Q(`${t}Valid recipient address`)):e.recipient===void 0&&a?n.push(Q(`${t}Uses splits (no single recipient)`)):e.recipient===void 0?n.push($(`${t}Valid recipient address`,`Missing recipient (and no splits defined)`,`Set request.recipient to a valid 0x address, or use methodDetails.splits for multiple recipients.`)):n.push($(`${t}Valid recipient address`,`Got: ${String(e.recipient)}`,`Set request.recipient to a valid 0x-prefixed 40-hex-char address.`)),JL(e.currency)){let e=uR(r)?`testnet`:`mainnet`;n.push(Q(`${t}Valid currency address`,e))}else n.push($(`${t}Valid currency address`,`Got: ${String(e.currency)}`,`Set request.currency to a valid token address.`));bR(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function vR(e,t,n){bR(e,t,n,`currency's smallest unit (e.g. "100" = $1.00 for USD)`);let r=e.currency;typeof r==`string`&&/^[a-z]{3}$/i.test(r)?n.push(Q(`${t}Valid currency code`,r.toUpperCase())):n.push($(`${t}Valid currency code`,r?`Got: ${r}`:`missing`,`Must be a three-letter ISO currency code (e.g. "usd").`));let i=e.methodDetails,a=i?.networkId;a?n.push(Q(`${t}Has networkId`,a.slice(0,20))):n.push($(`${t}Has networkId`,`Missing methodDetails.networkId`,`Set methodDetails.networkId to your Stripe Business Network profile ID.`));let o=i?.paymentMethodTypes;Array.isArray(o)&&o.length>0?n.push(Q(`${t}Has paymentMethodTypes`,o.join(`, `))):n.push($(`${t}Has paymentMethodTypes`,`Missing or empty`,`Set methodDetails.paymentMethodTypes to an array (e.g. ["card"]).`))}function yR(e,t,n,r){if(JL(t.recipient)?r.push(Q(`${n}Valid recipient address`)):r.push($(`${n}Valid recipient address`,`Got: ${String(t.recipient)}`,`Set request.recipient to a valid 0x-prefixed Ethereum address.`)),JL(t.currency)){let t=uR(e)?`testnet`:`mainnet`;r.push(Q(`${n}Valid currency address`,t))}else r.push($(`${n}Valid currency address`,`Got: ${String(t.currency)}`,`Set request.currency to a valid ERC-20 token contract address.`));bR(t,n,r,`token's smallest unit`);let i=t.methodDetails?.chainId;typeof i==`number`&&i>0?r.push(Q(`${n}Has chainId`,String(i))):r.push($(`${n}Has chainId`,`Missing methodDetails.chainId`,`Set methodDetails.chainId to the EVM chain ID.`))}function bR(e,t,n,r){YL(e.amount)?n.push(Q(`${t}Amount is valid integer string`)):e.amount===void 0||e.amount===null?n.push($(`${t}Amount is valid integer string`,`Missing amount`,`Set request.amount to a string of digits in the ${r}.`)):n.push($(`${t}Amount is valid integer string`,`Got: ${String(e.amount)}`,`request.amount must be a string of digits (no decimals, no prefix).`))}async function xR(e,t,n){let r=[],i=rR(e,t,n?.query),a=QL(n?.extraHeaders),o=n?.challenge?vS(n.challenge):q.authorization;a[o.toLowerCase()]=`${Fx.payment} dGhpcyBpcyBnYXJiYWdl`;let s;n?.body&&(s=n.body,a[`content-type`]||=`application/json`);try{let e=await GL(i,{method:t.method,headers:a,body:s??null});e.status===402?(r.push(Q(`Malformed credential returns 402`,`not 500`)),e.headers.get(q.wwwAuthenticate)?.startsWith(`${Fx.payment} `)?r.push(Q(`Error response includes fresh challenge`)):r.push(zL(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the ${o} header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(zL(`Malformed credential returns 402`,`Got ${e.status}`,`When the ${o} header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function SR(e){let t=[],n=e.headers.get(`payment-required`)??e.headers.get(`x-payment-required`);if(!n)return t;let r=e.headers.get(`payment-required`)?`PAYMENT-REQUIRED`:`X-Payment-Required`;try{let e=bw(n);t.push(Q(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(zL(`x402 payment challenge`,`${r} header present but failed schema validation`,`Ensure the PAYMENT-REQUIRED header contains a valid base64-encoded JSON payload matching the x402 schema.`))}return t}const CR=[`No discovery document found, endpoints could not be automatically found.`,`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,`The MPP SDKs can automatically expose this endpoint. See https://mpp.dev/sdk.`,``,`To test a specific endpoint: mppx validate <url> --endpoint POST:/your/path`].join(`
253
+ `);nS();const wR={fundingCurrency:J.optional(J.string()),method:J.string(),reference:J.string(),externalId:J.optional(J.string()),subscriptionId:J.optional(J.string()),status:J.literal(`success`),timestamp:qx()};J.object(wR);const TR=J.looseObject(wR);function ER(e){let t=A.toString(e);return DR(JSON.parse(t))}function DR(e){return TR.parse(e)}CS(),rT(),Bx(),mF(),vk(),fk(),RD(),sA(),qk();async function OR(e,t,n){try{n||console.log(X.dim(` Provisioning testnet wallet and funding via faucet...`));let t=ye(),r=xe(t),i=M({chain:Se,transport:de()});if(OO(e)){let{chainId:t,operator:n}=e.request.methodDetails??{};if(t===Se.id&&typeof n==`string`&&fe(n)&&n!==ve){let e=await Le.faucet.fund(i,{account:n});await Promise.all(e.map(e=>Pe(i,{hash:e})))}}let a=await Le.faucet.fund(i,{account:r});await Promise.all(a.map(e=>Pe(i,{hash:e}))),n||console.log(X.dim(` Using wallet: ${r.address}`));let o=e.request.currency;if(typeof o==`string`)for(let e=0;e<10;e++){let e=await Le.token.getBalance(i,{account:r.address,token:o}).catch(()=>void 0);if(e&&e.amount>0n)break;await new Promise(e=>setTimeout(e,500))}return{methods:[...dF({account:r})]}}catch(e){t&&console.log(X.dim(` Provisioning failed: ${e.message}`));return}}async function kR(){let e=eA(),{isTempoAccount:t}=await Promise.resolve().then(()=>(qk(),yk)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(JF(),hF));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await iA()).address}catch{return}}function AR(e){try{let{execSync:t}=m,n=t(`stripe config --list`,{encoding:`utf8`,timeout:5e3}).match(/test_mode_api_key\s*=\s*'([^']+)'/);if(n?.[1])return e&&console.log(X.dim(` Using Stripe test key from stripe CLI`)),n[1]}catch{}}async function jR(e,t,n){let r=M({chain:e,transport:de()}),[i,a,o]=await Promise.all([n?Oe(r,{address:t,abi:se,functionName:`balanceOf`,args:[n]}):0n,Oe(r,{address:t,abi:se,functionName:`decimals`}),Oe(r,{address:t,abi:se,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,decimals:a,symbol:o??void 0}}function MR(e){return Object.values(Ze).find(t=>t.id===e)}function NR(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function PR(e){switch(e.method){case Ix.evm:return`no EVM payment plugin yet`;case`solana`:return`no Solana payment plugin yet`;default:return`no plugin for ${e.method}/${e.intent}`}}async function FR(e,t,n,r){let i=[],a=rR(e,t,r.query),o=QL(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await GL(a,{method:t.method,headers:o,body:s??null})}catch(e){return i.push($(`Payment: fetch challenge`,e.message)),i}if(c.status!==402)return i.push(BL(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=mS(c)}catch(e){return i.push($(`Payment: parse challenge`,e.message)),i}if(l.length===0)return i.push($(`Payment: parse challenge`,`No Payment challenges in response`)),i;let u=[];hR(l,new URL(a).hostname,u);let d=u.filter(e=>e.severity===`fail`);if(d.length>0)return i.push(...d),r.onResults?.(d),i;let f=await oI().catch(()=>void 0),p=l.find(e=>{if(e.method!==Ix.tempo||iI(f?.config)?.some(t=>t.name===e.method&&t.intent===e.intent))return!1;let t=e.request.methodDetails;return typeof t?.chainId==`number`&&t.chainId!==pk.mainnet});if(p){let e=await OR(p,n,r.silent);if(e)try{let r=HR((e,t)=>GL(e,t??{},3e4));await BR(i,await tE({methods:e.methods,polyfill:!1,async onChallenge(e,{createCredential:t}){cI(p,e);let n=await t(await eI(e,f?.config.extensions));return i.push(Q(`Payment: submitted`,`ephemeral testnet wallet`)),n},fetch:r.fetch}).fetch(a,{method:t.method,headers:o,body:s??null}),n,Se,OO(p),r.receipt)}catch(e){i.push($(`Payment: create credential`,e.message))}else i.push($(`Payment: auto-provision wallet`,`Failed to create and fund testnet wallet`));r.onResults?.(i)}let m=r.interactive,h=process.env.MPPX_STRIPE_SECRET_KEY??AR(n),g=h?.startsWith(`sk_test_`)||h?.startsWith(`rk_test_`),_=new Set([Ix.tempo,Ix.evm,Ix.stripe]);for(let e of l){if(e===p||!_.has(e.method))continue;r.silent||console.log(``);let c=i.length,l=()=>{r.onResults&&i.length>c&&r.onResults(i.slice(c))},u=`Payment [${e.method}]`;try{switch(e.method){case Ix.tempo:case Ix.evm:await IR(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,options:r});break;case Ix.stripe:await LR(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,isStripeTestKey:g??!1,stripeKey:h,options:r})}}finally{l()}}return i}async function IR(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u}=n,d=e.request,f=d.methodDetails,p=YL(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,{plugin:g,method:_}=tI(e,l?.config);if(!g&&!_){r.push(BL(t,PR(e)));return}let v;if(!_){try{v=await kR()}catch{}if(!v){r.push(BL(t,`no wallet configured. Run "mppx account create" to create one.`));return}}let y;if(e.method===Ix.tempo){let e=f?.chainId??(_?void 0:P.id);e!==void 0&&(y=e===Se.id?Se:MR(e))}else if(e.method===Ix.evm){let e=f?.chainId;e&&(y=MR(e))}if(p&&h&&!y){r.push(BL(t,`unable to resolve payment chain and verify token decimals`));return}let b;if(p&&h&&y)try{let n;if(e.method===Ix.tempo){let e=await zk(M({chain:y,transport:de()}),h,v??ve,{requireDecimals:!0});n=e.balance,m=e.decimals,b=e.symbol}else{let e=await jR(y,h,v);n=e.balance,m=e.decimals,b=e.symbol}if(v&&n<p){let e=NR(p,m),i=NR(n,m),a=b??`tokens`;r.push(BL(t,`insufficient balance (have ${i}, need ${e} ${a} on ${y.name})`,`Fund wallet ${v} with at least ${e} ${a} on ${y.name}.`));return}}catch(e){c&&console.log(X.dim(` Balance check skipped: ${e.message}`)),r.push(BL(t,`unable to verify token balance and decimals from the payment chain`));return}let x=p?NR(p,m):`unknown amount`,S=b??(h?.length===3?h.toUpperCase():``),C=y?.name,w=`${x}${S?` ${S}`:``}${C?` on ${C}`:``}`;if(u.silent||console.log(X.dim(v?` Attempting payment with wallet ${v}`:` Attempting payment with configured method`)),!_&&y?.testnet)u.silent||console.log(X.dim(` Auto-approved: ${w} (testnet)`));else if(!u.yes&&!n.isInteractive){r.push(BL(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${w}`));else if(!await jk(` ${X.yellow(`Pay`)} ${w}. Continue?`,!1)){r.push(BL(t,`declined`));return}let T,E,ee;if(g)try{let t=await g.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});T=t.methods,E=t.createCredential,ee=t.credentialContext}catch(e){r.push(BL(t,e.message));return}else T=[_];if(_&&OO(e)){let n=!0,u=HR((e,t)=>GL(e,t??{},3e4)),d=tE({methods:[_],polyfill:!1,async onChallenge(n,{createCredential:i}){let a=await eI(n,l?.config.extensions);cI(e,n);let o=await i(a);return r.push(Q(`${t}: submitted`)),o},fetch:async(t,r)=>n?(n=!1,new Response(null,{status:402,headers:{[q.wwwAuthenticate]:iS(e)}})):u.fetch(t,r)});try{await BR(r,await d.fetch(i,{method:a.method,headers:o,body:s??null}),c,y,!0,u.receipt)}catch(e){r.push($(t,e.message))}return}let D=await RR(e,T,E,t,r,l?.config.extensions,ee,i);D&&(g?.prepareCredentialRequest?.({challenge:e,credential:D,headers:o}),await zR(r,i,a,D,o,s,c,y,vS(e),OO(e)))}async function LR(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u,stripeKey:d}=n,{plugin:f,method:p}=tI(e,l?.config);if(!f&&!p){r.push(BL(t,`no Stripe payment method available`));return}let m=!!(f&&!l?.config.plugins?.includes(f)&&n.isStripeTestKey),h=e.request,g=YL(h.amount)?BigInt(h.amount):void 0,_=h.decimals??2,v=h.currency,y=g?NR(g,_):`unknown amount`,b=v?.length===3?v.toUpperCase():``,x=`${y}${b?` ${b}`:``} via Stripe${m?` (testmode)`:``}`;if(m)u.silent||console.log(X.dim(` Attempting: ${x}`));else if(!u.yes&&!n.isInteractive){r.push(BL(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${x}`));else if(!await jk(` ${X.yellow(`Pay`)} ${x}. Continue?`,!1)){r.push(BL(t,`declined`));return}let S,C,w;if(f)try{let t={paymentMethod:`pm_card_visa`};d&&(t.secretKey=d);let n=await f.setup({challenge:e,options:{},methodOpts:t});S=n.methods,C=n.createCredential,w=n.credentialContext}catch(e){r.push(BL(t,e.message));return}else S=[p];let T=await RR(e,S,C,t,r,l?.config.extensions,w,i);if(T){if(f?.prepareCredentialRequest?.({challenge:e,credential:T,headers:o}),m){let n=await GL(i,{method:a.method,headers:{...o,[vS(e)]:T},body:s??null},3e4);n.status>=200&&n.status<300?r.push(Q(`${t}: successful`,`HTTP ${n.status}`)):r.push(BL(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await zR(r,i,a,T,o,s,c,void 0,vS(e))}}async function RR(e,t,n,r,i,a,o,s){let c=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:iS(e)}});try{$w(e,new URL(s),void 0);let l=await eI(e,a,o),u;return u=n?await n(c,l):await tE({methods:t,polyfill:!1}).createCredential(c,l),i.push(Q(`${r}: submitted`)),u}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(BL(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function zR(e,t,n,r,i,a,o,s,c=q.authorization,l=!1){let u;try{u=await GL(t,{method:n.method,headers:{...i,[c]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}return BR(e,u,o,s,l)}async function BR(e,t,n,r,i=!1,a){if(t.status===402){let n=await t.text().catch(()=>``),r=`Payment rejected`;try{let e=JSON.parse(n);r=e.detail??e.title??r}catch{}return e.push($(`Payment: accepted`,r,`The server rejected a valid credential. Check that your payment verification logic accepts the credential format and that the payment was processed on-chain.`)),e}if(t.status>=400&&t.status<500)e.push(zL(`Payment: post-payment response`,`Got ${t.status}`,`Payment succeeded but the endpoint returned a client error. The endpoint likely requires request body parameters. Use --body to provide them.`));else if(t.status>=500)return e.push($(`Payment: server response`,`Got ${t.status}`,`Payment was accepted but the server errored while generating the response. Check server logs for the underlying error.`)),e;else e.push(Q(`Payment: successful`,`HTTP ${t.status}`));let o=t.headers.get(`content-type`)??``,s=t.headers.get(q.paymentReceipt),c=!s&&i&&OD(t),l=await t.text().catch(()=>``);if(c){let t=a?.(),n=t===void 0?VR(l):t??void 0;n?e.push(Q(`Payment receipt in event stream`,n.reference)):e.push($(`Payment receipt in event stream`,void 0,`SSE session responses without a Payment-Receipt header must end with an "event: payment-receipt" carrying the session receipt.`))}else if(!s)e.push($(`Payment-Receipt header present`,void 0,`After accepting payment, include a Payment-Receipt header with a base64url-encoded JSON object containing: method, reference, status ("success"), and timestamp (ISO 8601).`));else{e.push(Q(`Payment-Receipt header present`));try{let t=ER(s);if(e.push(Q(`Receipt parseable`)),t.status===`success`?e.push(Q(`Receipt status is "success"`)):e.push($(`Receipt status is "success"`,`Got: ${t.status}`)),t.reference){let n=/^0x[0-9a-fA-F]{64}$/.test(t.reference),r=t.reference.startsWith(`pi_`);n||r?e.push(Q(`Receipt reference valid`,t.reference.slice(0,20)+`...`)):e.push(zL(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(zL(`Receipt has reference`,`No reference field`));if(t.timestamp){let n=new Date(t.timestamp),r=Date.now()-n.getTime();r<6e4?e.push(Q(`Receipt timestamp recent`,`${Math.round(r/1e3)}s ago`)):e.push(zL(`Receipt timestamp recent`,`${Math.round(r/6e4)}m ago`))}n&&console.log(X.dim(` Receipt: ${JSON.stringify(t,null,2)}`))}catch(t){e.push($(`Receipt parseable`,t.message))}}if(l.length>0)e.push(Q(`Response body non-empty`,`${o.split(`;`)[0]}, ${KL(l.length)}`));else{let n=[...t.headers.entries()].filter(([e])=>!e.startsWith(`x-`)&&![`content-type`,`content-length`,`date`,`server`,`connection`,`keep-alive`,`cache-control`,`vary`,`access-control-allow-origin`,`payment-receipt`,`payment-session`,`payment-session-snapshot`].includes(e.toLowerCase()));n.length>0?e.push(zL(`Response body empty -- data may be in headers only`,n.map(([e])=>e).join(`, `))):e.push(zL(`Response body empty`))}if(o?e.push(Q(`Content-Type header set`,o.split(`;`)[0])):e.push(zL(`Content-Type header set`)),s)try{let t=ER(s);if(t.reference&&/^0x[0-9a-fA-F]{64}$/.test(t.reference)){let n=r?.blockExplorers?.default?.url;if(n){let r=n.includes(`tempo`)?`receipt`:`tx`;e.push(Q(`On-chain transaction`,`${n}/${r}/${t.reference}`))}}}catch{}return e}function VR(e){for(let t of e.replace(/\r\n|\r/g,`
252
254
  `).split(`
253
255
 
254
- `)){let e=kD(t);if(e?.type===`payment-receipt`)return e.data}}function RR(e){let t;return{async fetch(n,r){let i=await e(n,r);if(!i.body||!OD(i)||i.headers.get(q.paymentReceipt))return i;t??=null;let a=new TextDecoder,o=[],s=0,c=!1,l=!1,u=(e,n)=>{let r=c?`\r${e}`:e;c=!n&&r.endsWith(`\r`),c&&(r=r.slice(0,-1));let i=r.replace(/\r\n|\r/g,`
256
+ `)){let e=kD(t);if(e?.type===`payment-receipt`)return e.data}}function HR(e){let t;return{async fetch(n,r){let i=await e(n,r);if(!i.body||!OD(i)||i.headers.get(q.paymentReceipt))return i;t??=null;let a=new TextDecoder,o=[],s=0,c=!1,l=!1,u=(e,n)=>{let r=c?`\r${e}`:e;c=!n&&r.endsWith(`\r`),c&&(r=r.slice(0,-1));let i=r.replace(/\r\n|\r/g,`
255
257
  `),a=[];i.startsWith(`
256
258
  `)&&o.at(-1)?.endsWith(`
257
259
  `)&&(a.push(o.join(``).slice(0,-1)),o=[],s=0,i=i.slice(1));for(let e=i.indexOf(`
@@ -260,18 +262,18 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
260
262
 
261
263
  `))a.push(o.join(``)+i.slice(0,e)),o=[],s=0,i=i.slice(e+2);i&&(o.push(i),s+=i.length),n&&(a.push(o.join(``)),o=[],s=0),l&&a.length>0&&(a.shift(),l=!1),s>1048576&&(o=o.at(-1)?.endsWith(`
262
264
  `)?[`
263
- `]:[],s=o.length,l=!0);for(let e of a){let n=kD(e);n?.type===`payment-receipt`&&!t&&(t=n.data)}},d=i.body.pipeThrough(new TransformStream({transform(e,t){u(a.decode(e,{stream:!0}),!1),t.enqueue(e)},flush(){u(a.decode(),!0)}})),f=new Response(d,{headers:i.headers,status:i.status,statusText:i.statusText});return Object.defineProperty(f,"url",{value:i.url}),f},receipt:()=>t}}async function*zR(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await WR(t,e);yield{phase:`discovery`,discovery:r,results:r.checks};for(let i of r.endpoints){yield{phase:`endpoint`,endpoint:i};let a,o=!1;e.endpoint?a=e.body:(a=qL(e.body,i.path),!a&&r.doc&&(a=QL(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await sR(t,i,n,{body:a,bodyIsAutogenerated:o,query:e.query,extraHeaders:e.headers,discoveryDoc:r.doc??void 0}),u=c??a,d=s.some(e=>e.severity===`pass`&&e.label===`Challenge parseable`),f=!s.some(e=>e.severity===`fail`),p=(l??[]).filter(e=>e.method!==`stripe`).map(e=>e.request.methodDetails?.chainId).filter(e=>typeof e==`number`),m=p.some(UR),h=p.some(e=>!UR(e)),g=!d&&s.some(e=>e.label===`Not an MPP endpoint`),_=s.some(e=>e.severity===`pass`&&e.label===`WWW-Authenticate header present`),v=s.some(e=>e.severity===`fail`&&e.label===`Challenge parseable`);if(yield{phase:`challenge`,endpoint:i,results:s,isMpp:d,isTestnet:m,isMainnet:h,isNonMppPayment:g,isMalformedChallenge:!d&&_&&v,methods:l?.map(e=>e.method)??[]},d&&(yield{phase:`errorHandling`,endpoint:i,results:await _R(t,i,{body:u,challenge:l?.[0],extraHeaders:e.headers,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults,a=await jR(t,i,n,{body:u,query:e.query,extraHeaders:e.headers,yes:e.yes,silent:!r,interactive:e.interactive,...r&&{onResults:r}});yield{phase:`payment`,endpoint:i,results:a,succeeded:a.some(e=>e.severity===`pass`&&e.label===`Payment: successful`)}}}}async function BR(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of zR(e))switch(t.phase){case`discovery`:n=t.discovery;break;case`endpoint`:i={method:t.endpoint.method,path:t.endpoint.path,challenge:[],errorHandling:[],payment:[]},r.push(i);break;case`challenge`:i&&(i.challenge=t.results),t.isMpp&&(t.isTestnet&&(a=!0),t.isMainnet&&(o=!0));break;case`errorHandling`:i&&(i.errorHandling=t.results);break;case`payment`:i&&(i.payment=t.results)}let s={passed:0,failed:0,warnings:0,suggested:0,skipped:0};if(n)for(let e of n.checks)e.severity===`pass`?s.passed++:e.severity===`fail`?s.failed++:e.severity===`warn`?s.warnings++:e.severity===`suggested`?s.suggested++:e.severity===`skip`&&s.skipped++;for(let e of r)for(let t of[...e.challenge,...e.errorHandling,...e.payment])t.severity===`pass`?s.passed++:t.severity===`fail`?s.failed++:t.severity===`warn`?s.warnings++:t.severity===`suggested`?s.suggested++:t.severity===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=VR(r,n,{sawTestnet:a,sawMainnet:o});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function VR(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(yR);let a=n.sawMainnet,o=n.sawTestnet,s=i.some(e=>e.label.includes(`[stripe]`)&&e.label.includes(`livemode`));return a&&!o?r.push(`Validate your testnet server to test without real funds (Tempo wallets are automatically provisioned).`):o&&!a&&r.push(`Validate your mainnet server to confirm real payments work end-to-end.`),s&&r.push(`Validate your testmode Stripe server to test card payments end-to-end (auto-pays with test card).`),r}const HR=Object.values(Ze);function UR(e){return HR.find(t=>t.id===e)?.testnet===!0}async function WR(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await XL(e));let s=new URL(e).origin,c;t.discoveryPath?c=[new URL(t.discoveryPath,e+`/`).href.replace(/\/openapi\.json$/i,``)]:(c=[e,s,`${s}/api`],c=[...new Set(c)]);let l,u=[];for(let e of c)if(l=await YL(e),`error`in l)u.push(`${e}/openapi.json: ${l.error}`);else break;if(!l||`error`in l)n.push({label:`Document found`,detail:u.join(`; `),hint:`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,severity:`fail`});else{a=!0,n.push({label:`Document found and parseable`,severity:`pass`});let e=PE(l.doc),t=e.filter(e=>e.severity===`error`),r=e.filter(e=>e.severity===`warning`);if(t.length>0){n.push({label:`Valid OpenAPI structure`,detail:`${t.length} error(s)`,severity:`fail`});for(let e of t)n.push({label:e.message,detail:e.path,severity:`fail`})}else o=!0,n.push({label:`Valid OpenAPI structure`,severity:`pass`});for(let e of r)n.push({label:e.message,detail:e.path,severity:`warn`});i=l.doc}if(t.endpoint){let e=KL(t.endpoint);e&&r.push(e)}else if(i){r=ZL(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=GL(t.amount)?BigInt(t.amount):e,i=GL(n.amount)?BigInt(n.amount):e;return r<i?-1:+(r>i)}),r.length>0?n.push({label:`Paid endpoints found`,detail:`${r.length} endpoint(s)`,severity:`pass`}):n.push({label:`Paid endpoints found`,detail:`No endpoints with x-payment-info`,severity:`warn`})}return{found:a,valid:o,endpoints:r,checks:n,doc:i}}Nx(),qk();const GR=pb(`validate`,{description:`Validate an MPP server implementation end-to-end`,args:p.object({url:p.string().describe(`Base URL of the MPP server to validate`)}),options:p.object({endpoint:p.string().optional().describe(`Endpoint to test (METHOD:path). Skips discovery.`),body:p.string().optional().describe(`Request body. With --endpoint, used directly. In discovery mode, JSON with / keys is a per-path mapping.`),query:p.array(p.string()).optional().describe(`Query parameter (key=value, repeatable)`),header:p.array(p.string()).optional().describe(`Request header (key:value, repeatable)`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity level`),yes:p.boolean().default(!1).describe(`Auto-approve mainnet payments`),outputJson:p.boolean().default(!1).describe(`Output results as JSON (auto-enabled in known agent environments)`)}),alias:{endpoint:`e`,header:`H`,verbose:`v`,yes:`y`,outputJson:`j`},async run(e){if(e.options.outputJson||Ok()){let t=await BR({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!1});console.log(JSON.stringify(t,null,2));let n=t.endpoints.length===0&&!e.options.endpoint;(t.summary.failed>0||!t.discovery.found||n)&&process.exit(1);return}let t=e.args.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``);console.log(`\n${X.bold(`mppx validate`)} ${X.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,suggested:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of zR({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!!process.stdin.isTTY,onPaymentResults:e=>BL(e,n)}))switch(t.phase){case`discovery`:if(zL(`Discovery (/openapi.json)`),BL(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=yR.split(`
264
- `);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,zL(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),BL(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),BL(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}KR(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function KR(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function qR(e){return YR(e)?e.offers:[e]}function JR(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=XR(t.amount)??XR(i.amount)??null,o=XR(t.currency)??XR(i.currency),s=XR(e.description)??XR(t.description),c={amount:a,...o?{currency:o}:{},...s?{description:s}:{},intent:n,method:r},l=new Set([`amount`,`currency`,`description`,`methodDetails`]);for(let[e,n]of Object.entries(t))!l.has(e)&&n!==void 0&&(c[e]=n);return c}function YR(e){return`offers`in e&&!(`_canonicalRequest`in e)}function XR(e){return typeof e==`string`?e:void 0}var ZR=F((()=>{})),QR=rt({generate:()=>$R,generateProxy:()=>ez});function $R(e,t){let n=e.methods,r=new Map,i={};for(let e of n)r.set(`${e.name}/${e.intent}`,e),i[e.intent]=(i[e.intent]??0)+1;for(let e of n)i[e.intent]===1&&r.set(e.intent,e);let a=t.routes.map(e=>nz(e,r));return tz({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function ez(e){let t=e.routes.map(t=>({...t,path:rz(e.basePath,t.path)}));return tz({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function tz(e){let t={};for(let n of e.routes){let e=n.method.toLowerCase(),r={responses:{...n.payment?{402:{description:`Payment Required`}}:{},200:{description:`Successful response`}}};n.payment&&(r[`x-payment-info`]=DE.parse(n.payment)),n.summary&&(r.summary=n.summary),n.requestBody&&(r.requestBody=n.requestBody),t[n.path]||(t[n.path]={}),t[n.path][e]=r}let n={info:e.info,openapi:`3.1.0`,paths:t};return e.serviceInfo&&(n[`x-service-info`]=e.serviceInfo),n}function nz(e,t){if(`handler`in e){let t=e.handler._internal;if(!t)throw Error(`Route ${e.method.toUpperCase()} ${e.path} is missing discovery metadata`);return{method:e.method,path:e.path,payment:{offers:qR(t).map(JR)},...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}let n=t.get(e.intent);if(!n)throw Error(`Unknown intent "${e.intent}" for route ${e.method.toUpperCase()} ${e.path}. Available: ${[...t.keys()].join(`, `)}`);let{description:r,...i}=e.options,a={_canonicalRequest:Hx(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:JR(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function rz(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var iz=F((()=>{Wx(),NE(),ZR()}));Nx(),CS(),$T(),rT(),gw(),kw(),Mw(),Bx(),fk(),Dw(),tC(),ZC(),sA(),qk();const az=`0.17.5`,oz=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),sz=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),cz=p.object({message:p.string(),path:p.string(),severity:p.string()}),lz=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),uz=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function dz(e){return e.format===`json`&&e.formatExplicit}function fz(e,t,n){if(dz(e))return e.ok(t);n()}async function pz(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function mz(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function hz(e){return typeof e==`string`?e:void 0}function gz(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function _z(e){let t=gz(e);return{...hz(e.description)?{description:hz(e.description)}:{},id:hz(e.id)??hz(e.name)??`unknown`,...hz(e.name)?{name:hz(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...hz(e.status)?{status:hz(e.status)}:{},...hz(e.serviceUrl)||hz(e.url)?{url:hz(e.serviceUrl)??hz(e.url)}:{}}}function vz(e){return{...hz(e.description)?{description:hz(e.description)}:{},method:hz(e.method)??`GET`,path:hz(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function yz(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=hz(t.amount),r=hz(t.currency),i=hz(t.method),a=hz(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function bz(e){return e.request.currency??e.request.asset}function xz(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=bz(e);return typeof t==`string`&&t.toLowerCase()===n})}async function Sz(e,t,n={}){let r=()=>hw().getChallenges(e),i=()=>Ow().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}function Cz(e){return Aw({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function wz(e,t){if(!$S(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:iS(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[NC]:ww({accepts:[OC(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function Tz(e){let{host:t,hostname:n,protocol:r}=new URL(e);return r===`https:`||!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function Ez(e,t,n,r){let i=t,a=Tz(i),o={...n,redirect:`manual`,headers:cT(n.headers)};a.host&&kz(o.headers,a.host);for(let t=0;t<=20;t++){let n=await e(a.url,o),s=n.headers.get(`location`);if(!r||!s||![301,302,303,307,308].includes(n.status))return{init:o,logicalUrl:i,response:n,target:a};if(t===20)throw TypeError(`Too many redirects`);await n.body?.cancel().catch(()=>{});let c=new URL(s,i),l=new URL(i),u=cT(o.headers);if(c.origin!==l.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];let d=(o.method??(o.body?`POST`:`GET`)).toUpperCase(),f=n.status===303&&d!==`GET`&&d!==`HEAD`||(n.status===301||n.status===302)&&d===`POST`;if(f)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];i=c.href,a=Tz(i),a.host&&kz(u,a.host);let p={...o};f&&(delete p.body,p.method=`GET`),o={...p,headers:u,redirect:`manual`}}throw TypeError(`Too many redirects`)}function Dz(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&Oz(i),Tz(i.href)}function Oz(e){throw new I({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function kz(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function Az(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function jz(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new I({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new I({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function Mz(e,t){let n=t.toLowerCase();return e.find(e=>{let t=hz(e.id)?.toLowerCase(),r=hz(e.name)?.toLowerCase();return t===n||r===n})}const Nz=pb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:az,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (disables payment retries)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await oI(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=lA(),i={"User-Agent":e.options.userAgent??`mppx/${az}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=rI(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure??!1,u=l?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,d=Tz(o),f=d.url;d.host&&(i.Host=d.host);try{let r=Dk(e.options.methodOpt),a=wI(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&bk(o,s,t);let p=await Ez(u,o,s,e.options.location??!1),m=p.response;if(l&&m.status===402)return e.error({code:`INSECURE_PAYMENT`,message:`Payment requires verified TLS. Install a trusted certificate and omit --insecure.`,exitCode:2});if(m.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&m.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${m.status}`,exitCode:22});xk(m,c),await pz(m);return}let h=m.url?new URL(m.url):void 0,g=d.host!==void 0&&h?.hostname===`127.0.0.1`,_=await Sz(m,e.options.protocol,{ignoreX402ResponseUrl:g});if(_.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let v=xz(_,e.options.currency);if(e.options.currency&&v.length===0){let t=_.map(bz).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let y=iI(n?.config)?.length?v:await _F(v,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),b=nI(y,n?.config);if(!b){let t=y.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:x,plugin:S,method:C}=b,w=$S(x),T=w?void 0:Dz(o,d,p.logicalUrl);if(!w)try{$w(x,new URL(p.logicalUrl||o),void 0)}catch(t){return e.error({code:`UNTRUSTED_PROOF_REALM`,message:t.message,exitCode:1})}let E=wz(x,m),ee=x.request.currency??``,D=x.request.decimals??6,O,k;S&&(k=await S.setup({challenge:x,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),ee=k.tokenSymbol,D=k.tokenDecimals,O=k.explorerUrl);let te=!e.options.silent&&e.options.confirm,ne=new Set;{xk(m,x.method===`tempo`&&x.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(x))e.has(n)||r===void 0||t.push([n,wk(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:ee,tokenDecimals:D,explorerUrl:O},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(x.request))e.has(n)||i===void 0||t.push([n,Sk(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=x.request.methodDetails;if(!e)return[];let t=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if(n===`memo`&&typeof i==`string`){let e=Ck(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,Sk(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)ne.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||te){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
265
+ `]:[],s=o.length,l=!0);for(let e of a){let n=kD(e);n?.type===`payment-receipt`&&!t&&(t=n.data)}},d=i.body.pipeThrough(new TransformStream({transform(e,t){u(a.decode(e,{stream:!0}),!1),t.enqueue(e)},flush(){u(a.decode(),!0)}})),f=new Response(d,{headers:i.headers,status:i.status,statusText:i.statusText});return Object.defineProperty(f,"url",{value:i.url}),f},receipt:()=>t}}async function*UR(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await JR(t,e);yield{phase:`discovery`,discovery:r,results:r.checks};for(let i of r.endpoints){yield{phase:`endpoint`,endpoint:i};let a,o=!1;e.endpoint?a=e.body:(a=ZL(e.body,i.path),!a&&r.doc&&(a=nR(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await dR(t,i,n,{body:a,bodyIsAutogenerated:o,query:e.query,extraHeaders:e.headers,discoveryDoc:r.doc??void 0}),u=c??a,d=s.some(e=>e.severity===`pass`&&e.label===`Challenge parseable`),f=!s.some(e=>e.severity===`fail`),p=(l??[]).filter(e=>e.method!==`stripe`).map(e=>e.request.methodDetails?.chainId).filter(e=>typeof e==`number`),m=p.some(qR),h=p.some(e=>!qR(e)),g=!d&&s.some(e=>e.label===`Not an MPP endpoint`),_=s.some(e=>e.severity===`pass`&&e.label===`WWW-Authenticate header present`),v=s.some(e=>e.severity===`fail`&&e.label===`Challenge parseable`);if(yield{phase:`challenge`,endpoint:i,results:s,isMpp:d,isTestnet:m,isMainnet:h,isNonMppPayment:g,isMalformedChallenge:!d&&_&&v,methods:l?.map(e=>e.method)??[]},d&&(yield{phase:`errorHandling`,endpoint:i,results:await xR(t,i,{body:u,challenge:l?.[0],extraHeaders:e.headers,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults,a=await FR(t,i,n,{body:u,query:e.query,extraHeaders:e.headers,yes:e.yes,silent:!r,interactive:e.interactive,...r&&{onResults:r}});yield{phase:`payment`,endpoint:i,results:a,succeeded:a.some(e=>e.severity===`pass`&&e.label===`Payment: successful`)}}}}async function WR(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of UR(e))switch(t.phase){case`discovery`:n=t.discovery;break;case`endpoint`:i={method:t.endpoint.method,path:t.endpoint.path,challenge:[],errorHandling:[],payment:[]},r.push(i);break;case`challenge`:i&&(i.challenge=t.results),t.isMpp&&(t.isTestnet&&(a=!0),t.isMainnet&&(o=!0));break;case`errorHandling`:i&&(i.errorHandling=t.results);break;case`payment`:i&&(i.payment=t.results)}let s={passed:0,failed:0,warnings:0,suggested:0,skipped:0};if(n)for(let e of n.checks)e.severity===`pass`?s.passed++:e.severity===`fail`?s.failed++:e.severity===`warn`?s.warnings++:e.severity===`suggested`?s.suggested++:e.severity===`skip`&&s.skipped++;for(let e of r)for(let t of[...e.challenge,...e.errorHandling,...e.payment])t.severity===`pass`?s.passed++:t.severity===`fail`?s.failed++:t.severity===`warn`?s.warnings++:t.severity===`suggested`?s.suggested++:t.severity===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=GR(r,n,{sawTestnet:a,sawMainnet:o});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function GR(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(CR);let a=n.sawMainnet,o=n.sawTestnet,s=i.some(e=>e.label.includes(`[stripe]`)&&e.label.includes(`livemode`));return a&&!o?r.push(`Validate your testnet server to test without real funds (Tempo wallets are automatically provisioned).`):o&&!a&&r.push(`Validate your mainnet server to confirm real payments work end-to-end.`),s&&r.push(`Validate your testmode Stripe server to test card payments end-to-end (auto-pays with test card).`),r}const KR=Object.values(Ze);function qR(e){return KR.find(t=>t.id===e)?.testnet===!0}async function JR(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await eR(e));let s=new URL(e).origin,c;t.discoveryPath?c=[new URL(t.discoveryPath,e+`/`).href.replace(/\/openapi\.json$/i,``)]:(c=[e,s,`${s}/api`],c=[...new Set(c)]);let l,u=[];for(let e of c)if(l=await $L(e),`error`in l)u.push(`${e}/openapi.json: ${l.error}`);else break;if(!l||`error`in l)n.push({label:`Document found`,detail:u.join(`; `),hint:`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,severity:`fail`});else{a=!0,n.push({label:`Document found and parseable`,severity:`pass`});let e=PE(l.doc),t=e.filter(e=>e.severity===`error`),r=e.filter(e=>e.severity===`warning`);if(t.length>0){n.push({label:`Valid OpenAPI structure`,detail:`${t.length} error(s)`,severity:`fail`});for(let e of t)n.push({label:e.message,detail:e.path,severity:`fail`})}else o=!0,n.push({label:`Valid OpenAPI structure`,severity:`pass`});for(let e of r)n.push({label:e.message,detail:e.path,severity:`warn`});i=l.doc}if(t.endpoint){let e=XL(t.endpoint);e&&r.push(e)}else if(i){r=tR(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=YL(t.amount)?BigInt(t.amount):e,i=YL(n.amount)?BigInt(n.amount):e;return r<i?-1:+(r>i)}),r.length>0?n.push({label:`Paid endpoints found`,detail:`${r.length} endpoint(s)`,severity:`pass`}):n.push({label:`Paid endpoints found`,detail:`No endpoints with x-payment-info`,severity:`warn`})}return{found:a,valid:o,endpoints:r,checks:n,doc:i}}Nx(),qk();const YR=pb(`validate`,{description:`Validate an MPP server implementation end-to-end`,args:p.object({url:p.string().describe(`Base URL of the MPP server to validate`)}),options:p.object({endpoint:p.string().optional().describe(`Endpoint to test (METHOD:path). Skips discovery.`),body:p.string().optional().describe(`Request body. With --endpoint, used directly. In discovery mode, JSON with / keys is a per-path mapping.`),query:p.array(p.string()).optional().describe(`Query parameter (key=value, repeatable)`),header:p.array(p.string()).optional().describe(`Request header (key:value, repeatable)`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity level`),yes:p.boolean().default(!1).describe(`Auto-approve mainnet payments`),outputJson:p.boolean().default(!1).describe(`Output results as JSON (auto-enabled in known agent environments)`)}),alias:{endpoint:`e`,header:`H`,verbose:`v`,yes:`y`,outputJson:`j`},async run(e){if(e.options.outputJson||Ok()){let t=await WR({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!1});console.log(JSON.stringify(t,null,2));let n=t.endpoints.length===0&&!e.options.endpoint;(t.summary.failed>0||!t.discovery.found||n)&&process.exit(1);return}let t=e.args.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``);console.log(`\n${X.bold(`mppx validate`)} ${X.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,suggested:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of UR({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!!process.stdin.isTTY,onPaymentResults:e=>WL(e,n)}))switch(t.phase){case`discovery`:if(UL(`Discovery (/openapi.json)`),WL(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=CR.split(`
266
+ `);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,UL(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),WL(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),WL(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}XR(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function XR(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function ZR(e){return $R(e)?e.offers:[e]}function QR(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=ez(t.amount)??ez(i.amount)??null,o=ez(t.currency)??ez(i.currency),s=ez(e.description)??ez(t.description),c={amount:a,...o?{currency:o}:{},...s?{description:s}:{},intent:n,method:r},l=new Set([`amount`,`currency`,`description`,`methodDetails`]);for(let[e,n]of Object.entries(t))!l.has(e)&&n!==void 0&&(c[e]=n);return c}function $R(e){return`offers`in e&&!(`_canonicalRequest`in e)}function ez(e){return typeof e==`string`?e:void 0}var tz=F((()=>{})),nz=rt({generate:()=>rz,generateProxy:()=>iz});function rz(e,t){let n=e.methods,r=new Map,i={};for(let e of n)r.set(`${e.name}/${e.intent}`,e),i[e.intent]=(i[e.intent]??0)+1;for(let e of n)i[e.intent]===1&&r.set(e.intent,e);let a=t.routes.map(e=>oz(e,r));return az({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function iz(e){let t=e.routes.map(t=>({...t,path:sz(e.basePath,t.path)}));return az({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function az(e){let t={};for(let n of e.routes){let e=n.method.toLowerCase(),r={responses:{...n.payment?{402:{description:`Payment Required`}}:{},200:{description:`Successful response`}}};n.payment&&(r[`x-payment-info`]=DE.parse(n.payment)),n.summary&&(r.summary=n.summary),n.requestBody&&(r.requestBody=n.requestBody),t[n.path]||(t[n.path]={}),t[n.path][e]=r}let n={info:e.info,openapi:`3.1.0`,paths:t};return e.serviceInfo&&(n[`x-service-info`]=e.serviceInfo),n}function oz(e,t){if(`handler`in e){let t=e.handler._internal;if(!t)throw Error(`Route ${e.method.toUpperCase()} ${e.path} is missing discovery metadata`);return{method:e.method,path:e.path,payment:{offers:ZR(t).map(QR)},...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}let n=t.get(e.intent);if(!n)throw Error(`Unknown intent "${e.intent}" for route ${e.method.toUpperCase()} ${e.path}. Available: ${[...t.keys()].join(`, `)}`);let{description:r,...i}=e.options,a={_canonicalRequest:Hx(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:QR(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function sz(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var cz=F((()=>{Wx(),NE(),tz()}));Nx(),CS(),$T(),rT(),gw(),kw(),Mw(),Bx(),fk(),Dw(),tC(),ZC(),sA(),qk();const lz=`0.17.6`,uz=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),dz=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),fz=p.object({message:p.string(),path:p.string(),severity:p.string()}),pz=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),mz=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function hz(e){return e.format===`json`&&e.formatExplicit}function gz(e,t,n){if(hz(e))return e.ok(t);n()}async function _z(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function vz(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function yz(e){return typeof e==`string`?e:void 0}function bz(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function xz(e){let t=bz(e);return{...yz(e.description)?{description:yz(e.description)}:{},id:yz(e.id)??yz(e.name)??`unknown`,...yz(e.name)?{name:yz(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...yz(e.status)?{status:yz(e.status)}:{},...yz(e.serviceUrl)||yz(e.url)?{url:yz(e.serviceUrl)??yz(e.url)}:{}}}function Sz(e){return{...yz(e.description)?{description:yz(e.description)}:{},method:yz(e.method)??`GET`,path:yz(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function Cz(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=yz(t.amount),r=yz(t.currency),i=yz(t.method),a=yz(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function wz(e){return e.request.currency??e.request.asset}function Tz(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=wz(e);return typeof t==`string`&&t.toLowerCase()===n})}async function Ez(e,t,n={}){let r=()=>hw().getChallenges(e),i=()=>Ow().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}function Dz(e){return Aw({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function Oz(e,t){if(!$S(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:iS(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[NC]:ww({accepts:[OC(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function kz(e){let{host:t,hostname:n,protocol:r}=new URL(e);return r===`https:`||!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function Az(e,t,n,r){let i=t,a=kz(i),o={...n,redirect:`manual`,headers:cT(n.headers)};a.host&&Nz(o.headers,a.host);for(let t=0;t<=20;t++){let n=await e(a.url,o),s=n.headers.get(`location`);if(!r||!s||![301,302,303,307,308].includes(n.status))return{init:o,logicalUrl:i,response:n,target:a};if(t===20)throw TypeError(`Too many redirects`);await n.body?.cancel().catch(()=>{});let c=new URL(s,i),l=new URL(i),u=cT(o.headers);if(c.origin!==l.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];let d=(o.method??(o.body?`POST`:`GET`)).toUpperCase(),f=n.status===303&&d!==`GET`&&d!==`HEAD`||(n.status===301||n.status===302)&&d===`POST`;if(f)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];i=c.href,a=kz(i),a.host&&Nz(u,a.host);let p={...o};f&&(delete p.body,p.method=`GET`),o={...p,headers:u,redirect:`manual`}}throw TypeError(`Too many redirects`)}function jz(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&Mz(i),kz(i.href)}function Mz(e){throw new I({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function Nz(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function Pz(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function Fz(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new I({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new I({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function Iz(e,t){let n=t.toLowerCase();return e.find(e=>{let t=yz(e.id)?.toLowerCase(),r=yz(e.name)?.toLowerCase();return t===n||r===n})}const Lz=pb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:lz,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (disables payment retries)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await oI(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=lA(),i={"User-Agent":e.options.userAgent??`mppx/${lz}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=rI(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure??!1,u=l?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,d=kz(o),f=d.url;d.host&&(i.Host=d.host);try{let r=Dk(e.options.methodOpt),a=wI(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&bk(o,s,t);let p=await Az(u,o,s,e.options.location??!1),m=p.response;if(l&&m.status===402)return e.error({code:`INSECURE_PAYMENT`,message:`Payment requires verified TLS. Install a trusted certificate and omit --insecure.`,exitCode:2});if(m.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&m.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${m.status}`,exitCode:22});xk(m,c),await _z(m);return}let h=m.url?new URL(m.url):void 0,g=d.host!==void 0&&h?.hostname===`127.0.0.1`,_=await Ez(m,e.options.protocol,{ignoreX402ResponseUrl:g});if(_.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let v=Tz(_,e.options.currency);if(e.options.currency&&v.length===0){let t=_.map(wz).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let y=iI(n?.config)?.length?v:await _F(v,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),b=nI(y,n?.config);if(!b){let t=y.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:x,plugin:S,method:C}=b,w=$S(x),T=w?void 0:jz(o,d,p.logicalUrl);if(!w)try{$w(x,new URL(p.logicalUrl||o),void 0)}catch(t){return e.error({code:`UNTRUSTED_PROOF_REALM`,message:t.message,exitCode:1})}let E=Oz(x,m),ee=x.request.currency??``,D=x.request.decimals??6,O,k;S&&(k=await S.setup({challenge:x,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),ee=k.tokenSymbol,D=k.tokenDecimals,O=k.explorerUrl);let te=!e.options.silent&&e.options.confirm,ne=new Set;{xk(m,x.method===`tempo`&&x.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(x))e.has(n)||r===void 0||t.push([n,wk(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:ee,tokenDecimals:D,explorerUrl:O},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(x.request))e.has(n)||i===void 0||t.push([n,Sk(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=x.request.methodDetails;if(!e)return[];let t=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if(n===`memo`&&typeof i==`string`){let e=Ck(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,Sk(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)ne.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||te){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
265
267
  `);t(` ${X.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${l}${e}\n`)}}}if(te&&(t(`
266
268
  `),!await jk(`Proceed with ${x.intent}?`,!0))){t(`Aborted.
267
- `);return}}let j=process.env.MPPX_PRIVATE_KEY?.trim()||!kk(eA(e.options.account));if(OO(x)&&j&&!C){try{await TL({challenge:x,challengeResponse:E,credentialContext:await eI(x,n?.config.extensions,k?.credentialContext),endpoint:p.logicalUrl,fetch:u,fetchInput:T.url,init:{...p.init,redirect:`manual`},info:t,methodOptions:r,options:{account:e.options.account,fail:e.options.fail,include:e.options.include,network:e.options.network,rpcUrl:e.options.rpcUrl,session:e.options.session,silent:e.options.silent,verbose:e.options.verbose},registry:a})}catch(e){return mL(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:C&&OO(x)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let re=C&&OO(x)?void 0:await eI(x,n?.config.extensions,k?.credentialContext),M,ie;if(C&&OO(x)){let e=E;M=await tE({methods:[C],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await eI(e,n?.config.extensions,k?.credentialContext);return cI(x,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return u(t,n)}}).fetch(T.url,{...p.init,context:re,redirect:`manual`})}else{if(k?.createCredential)ie=await k.createCredential(E,re);else if(k)ie=await tE({methods:k.methods,polyfill:!1,transport:Cz(x)}).createCredential(E,re);else if(C)ie=await tE({methods:[C],polyfill:!1,transport:Cz(x)}).createCredential(E,re);else throw Error(`unreachable`);let n=w?PC:vS(x),r={...cT(p.init.headers),[n]:ie},i=w?Tz((Az(x)??m.url)||o):T;w&&kz(r,i.host),S?.prepareCredentialRequest?.({challenge:x,credential:ie,headers:r});let a={...p.init,redirect:`manual`,headers:r};e.options.verbose>=2&&bk(i.url,a,t),M=await u(i.url,a)}if(e.options.fail&&M.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${M.status}`,exitCode:22});if(M.status===402){let n=await M.text();t(`${X.bold(X.red(`Payment Rejected`))}\n`);try{let e=JSON.parse(n),r=[];for(let[t,n]of Object.entries(e))n!==void 0&&r.push([t,Tk(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(xk(M,c),!(ie&&await S?.handleResponse?.({challenge:x,credential:ie,response:M,fetchUrl:f,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:te,confirm:jk,tokenSymbol:ee,tokenDecimals:D,explorerUrl:O,shownKeys:ne}))){let n=M.headers.get(q.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(A.toString(n));t(`\n${X.bold(X.green(`Payment Receipt`))}\n`);let r=[],i=e.channelId,a=e.reference,o=i&&a&&i===a,s=new Set([`acceptedCumulative`,`spent`]);for(let[t,n]of Object.entries(e)){if(n===void 0||ne.has(t)||t===`reference`&&o)continue;let e=S?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${Mk(BigInt(n),ee,D)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&O?r.push([t,Ek(`${O}/tx/${n}`,n)]):r.push([t,String(n)]):r.push([t,e])}r.sort(([e],[t])=>e.localeCompare(t));let c=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(c))} ${n}\n`);t(`
268
- `)}catch{}await pz(M)}}catch(t){if(t instanceof I)throw t;let n=t instanceof Error?t.cause:void 0,r=n instanceof Error?n:void 0;if(r&&`code`in r){let t=r.code;return t===`ENOTFOUND`?e.error({code:`DNS_ERROR`,message:`Could not resolve host "${s}". Check the URL and try again.`,exitCode:6}):t===`ECONNREFUSED`?e.error({code:`CONNECTION_REFUSED`,message:`Connection refused by "${s}". Is the server running?`,retryable:!0,exitCode:7}):t===`ECONNRESET`?e.error({code:`CONNECTION_RESET`,message:`Connection to "${s}" was reset.`,retryable:!0,exitCode:56}):t===`ETIMEDOUT`?e.error({code:`CONNECTION_TIMEOUT`,message:`Connection to "${s}" timed out.`,retryable:!0,exitCode:28}):t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?e.error({code:`TLS_ERROR`,message:`TLS certificate error for "${s}". Use --insecure to skip verification.`,exitCode:60}):e.error({code:`REQUEST_FAILED`,message:`Request to "${s}" failed: ${r.message}`})}{let n=t instanceof Error?t.message:String(t);return e.error({code:`REQUEST_FAILED`,message:r?`Request failed: ${n} (Cause: ${r.message})`:`Request failed: ${n}`})}}}}),Pz=pb(`account`,{description:`Manage accounts (create, default, delete, export, fund, list, view)`}).command(`create`,{description:`Create new account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({address:p.string(),name:p.string()}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=dz(e),n=e.options.account;if(!n){if((await tA().list()).length===0)n=`main`;else{if(t)return e.error({code:`ACCOUNT_REQUIRED`,message:`Account name is required in structured mode.`,exitCode:2});let r=await Ak(`Account name`);if(!r)return;n=r}}let r=tA(n);for(;await r.get();){if(t)return e.error({code:`ACCOUNT_EXISTS`,message:`Account "${n}" already exists.`,exitCode:1});process.stderr.write(`${X.dim(`Account "${n}" already exists.`)}\n\n`);let i=await Ak(`Enter different name`);if(!i)return;n=i,r=tA(n)}let i=ye(),a=xe(i);await r.set(i),(await tA().list()).length===1&&$k().set(n);let o=P.blockExplorers?.default?.url,s=o?Ek(`${o}/address/${a.address}`,a.address):a.address,c=Pk(e.options),l=Nk(e.options.rpcUrl,{network:c});return Fk({network:c,rpcUrl:l}).then(e=>M({chain:e,transport:de(l)})).then(e=>import(`viem/tempo`).then(({Actions:t})=>t.faucet.fund(e,{account:a}).catch(()=>{}))),fz(e,{address:a.address,name:n},()=>{console.log(`Account "${n}" saved to keychain.`),console.log(X.dim(`Address ${s}`)),console.log(X.dim(`Fund testnet tokens: mppx account fund --account ${n} --network testnet`))})}}).command(`default`,{description:`Set default account`,options:p.object({account:p.string().describe(`Account name`)}),output:p.object({name:p.string()}),alias:{account:`a`},async run(e){let t=e.options.account;return kk(t)?RF(t)?($k().set(t),fz(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69}):await tA(t).get()?($k().set(t),fz(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69})}}).command(`delete`,{description:`Delete account`,options:p.object({account:p.string().describe(`Account name`),yes:p.boolean().optional().describe(`DANGER!! Skip confirmation prompts`)}),output:p.object({defaultAccount:p.string().optional(),name:p.string()}),alias:{account:`a`},async run(e){let t=tA(e.options.account),n=await t.get();if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${e.options.account}" not found.`,exitCode:69});let r=xe(n),i=await Bk(r.address,{includeTestnet:!1});if(!e.options.yes){if(dz(e))return e.error({code:`CONFIRMATION_REQUIRED`,message:`Pass --yes to delete an account in structured mode.`,exitCode:2});let t=P.blockExplorers?.default?.url,n=t?Ek(`${t}/address/${r.address}`,r.address):r.address;process.stderr.write(X.dim(`Delete account "${e.options.account}"\n`)),process.stderr.write(X.dim(` Address ${n}\n`));for(let e=0;e<i.length;e++)process.stderr.write(X.dim(` ${e===0?`Balance`:` `} ${i[e]}\n`));if(process.stderr.write(X.dim(`This action cannot be undone
269
+ `);return}}let j=process.env.MPPX_PRIVATE_KEY?.trim()||!kk(eA(e.options.account));if(OO(x)&&j&&!C){try{await TL({challenge:x,challengeResponse:E,credentialContext:await eI(x,n?.config.extensions,k?.credentialContext),endpoint:p.logicalUrl,fetch:u,fetchInput:T.url,init:{...p.init,redirect:`manual`},info:t,methodOptions:r,options:{account:e.options.account,fail:e.options.fail,include:e.options.include,network:e.options.network,rpcUrl:e.options.rpcUrl,session:e.options.session,silent:e.options.silent,verbose:e.options.verbose},registry:a})}catch(e){return mL(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:C&&OO(x)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let re=C&&OO(x)?void 0:await eI(x,n?.config.extensions,k?.credentialContext),M,ie;if(C&&OO(x)){let e=E;M=await tE({methods:[C],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await eI(e,n?.config.extensions,k?.credentialContext);return cI(x,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return u(t,n)}}).fetch(T.url,{...p.init,context:re,redirect:`manual`})}else{if(k?.createCredential)ie=await k.createCredential(E,re);else if(k)ie=await tE({methods:k.methods,polyfill:!1,transport:Dz(x)}).createCredential(E,re);else if(C)ie=await tE({methods:[C],polyfill:!1,transport:Dz(x)}).createCredential(E,re);else throw Error(`unreachable`);let n=w?PC:vS(x),r={...cT(p.init.headers),[n]:ie},i=w?kz((Pz(x)??m.url)||o):T;w&&Nz(r,i.host),S?.prepareCredentialRequest?.({challenge:x,credential:ie,headers:r});let a={...p.init,redirect:`manual`,headers:r};e.options.verbose>=2&&bk(i.url,a,t),M=await u(i.url,a)}if(e.options.fail&&M.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${M.status}`,exitCode:22});if(M.status===402){let n=await M.text();t(`${X.bold(X.red(`Payment Rejected`))}\n`);try{let e=JSON.parse(n),r=[];for(let[t,n]of Object.entries(e))n!==void 0&&r.push([t,Tk(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(xk(M,c),!(ie&&await S?.handleResponse?.({challenge:x,credential:ie,response:M,fetchUrl:f,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:te,confirm:jk,tokenSymbol:ee,tokenDecimals:D,explorerUrl:O,shownKeys:ne}))){let n=M.headers.get(q.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(A.toString(n));t(`\n${X.bold(X.green(`Payment Receipt`))}\n`);let r=[],i=e.channelId,a=e.reference,o=i&&a&&i===a,s=new Set([`acceptedCumulative`,`spent`]);for(let[t,n]of Object.entries(e)){if(n===void 0||ne.has(t)||t===`reference`&&o)continue;let e=S?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${Mk(BigInt(n),ee,D)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&O?r.push([t,Ek(`${O}/tx/${n}`,n)]):r.push([t,String(n)]):r.push([t,e])}r.sort(([e],[t])=>e.localeCompare(t));let c=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(c))} ${n}\n`);t(`
270
+ `)}catch{}await _z(M)}}catch(t){if(t instanceof I)throw t;let n=t instanceof Error?t.cause:void 0,r=n instanceof Error?n:void 0;if(r&&`code`in r){let t=r.code;return t===`ENOTFOUND`?e.error({code:`DNS_ERROR`,message:`Could not resolve host "${s}". Check the URL and try again.`,exitCode:6}):t===`ECONNREFUSED`?e.error({code:`CONNECTION_REFUSED`,message:`Connection refused by "${s}". Is the server running?`,retryable:!0,exitCode:7}):t===`ECONNRESET`?e.error({code:`CONNECTION_RESET`,message:`Connection to "${s}" was reset.`,retryable:!0,exitCode:56}):t===`ETIMEDOUT`?e.error({code:`CONNECTION_TIMEOUT`,message:`Connection to "${s}" timed out.`,retryable:!0,exitCode:28}):t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?e.error({code:`TLS_ERROR`,message:`TLS certificate error for "${s}". Use --insecure to skip verification.`,exitCode:60}):e.error({code:`REQUEST_FAILED`,message:`Request to "${s}" failed: ${r.message}`})}{let n=t instanceof Error?t.message:String(t);return e.error({code:`REQUEST_FAILED`,message:r?`Request failed: ${n} (Cause: ${r.message})`:`Request failed: ${n}`})}}}}),Rz=pb(`account`,{description:`Manage accounts (create, default, delete, export, fund, list, view)`}).command(`create`,{description:`Create new account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({address:p.string(),name:p.string()}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=hz(e),n=e.options.account;if(!n){if((await tA().list()).length===0)n=`main`;else{if(t)return e.error({code:`ACCOUNT_REQUIRED`,message:`Account name is required in structured mode.`,exitCode:2});let r=await Ak(`Account name`);if(!r)return;n=r}}let r=tA(n);for(;await r.get();){if(t)return e.error({code:`ACCOUNT_EXISTS`,message:`Account "${n}" already exists.`,exitCode:1});process.stderr.write(`${X.dim(`Account "${n}" already exists.`)}\n\n`);let i=await Ak(`Enter different name`);if(!i)return;n=i,r=tA(n)}let i=ye(),a=xe(i);await r.set(i),(await tA().list()).length===1&&$k().set(n);let o=P.blockExplorers?.default?.url,s=o?Ek(`${o}/address/${a.address}`,a.address):a.address,c=Pk(e.options),l=Nk(e.options.rpcUrl,{network:c});return Fk({network:c,rpcUrl:l}).then(e=>M({chain:e,transport:de(l)})).then(e=>import(`viem/tempo`).then(({Actions:t})=>t.faucet.fund(e,{account:a}).catch(()=>{}))),gz(e,{address:a.address,name:n},()=>{console.log(`Account "${n}" saved to keychain.`),console.log(X.dim(`Address ${s}`)),console.log(X.dim(`Fund testnet tokens: mppx account fund --account ${n} --network testnet`))})}}).command(`default`,{description:`Set default account`,options:p.object({account:p.string().describe(`Account name`)}),output:p.object({name:p.string()}),alias:{account:`a`},async run(e){let t=e.options.account;return kk(t)?RF(t)?($k().set(t),gz(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69}):await tA(t).get()?($k().set(t),gz(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69})}}).command(`delete`,{description:`Delete account`,options:p.object({account:p.string().describe(`Account name`),yes:p.boolean().optional().describe(`DANGER!! Skip confirmation prompts`)}),output:p.object({defaultAccount:p.string().optional(),name:p.string()}),alias:{account:`a`},async run(e){let t=tA(e.options.account),n=await t.get();if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${e.options.account}" not found.`,exitCode:69});let r=xe(n),i=await Bk(r.address,{includeTestnet:!1});if(!e.options.yes){if(hz(e))return e.error({code:`CONFIRMATION_REQUIRED`,message:`Pass --yes to delete an account in structured mode.`,exitCode:2});let t=P.blockExplorers?.default?.url,n=t?Ek(`${t}/address/${r.address}`,r.address):r.address;process.stderr.write(X.dim(`Delete account "${e.options.account}"\n`)),process.stderr.write(X.dim(` Address ${n}\n`));for(let e=0;e<i.length;e++)process.stderr.write(X.dim(` ${e===0?`Balance`:` `} ${i[e]}\n`));if(process.stderr.write(X.dim(`This action cannot be undone
269
271
 
270
- `)),!await jk(`Confirm delete?`)){console.log(`Canceled`);return}}await t.delete();let a=$k().get(),o;if(a===e.options.account){let e=await tA().list();e.length>0?(o=e[0],$k().set(o)):$k().clear()}return fz(e,{defaultAccount:o,name:e.options.account},()=>{o&&console.log(`Default account set to "${o}"`),console.log(`Account "${e.options.account}" deleted`)})}}).command(`fund`,{description:`Fund account with testnet tokens`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({account:p.string(),chain:p.string(),transactions:p.array(p.string())}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=dz(e),n=eA(e.options.account),r=await tA(n).get();if(!r)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${n}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let i=xe(r),a=Pk(e.options),o=Nk(e.options.rpcUrl,{network:a}),s=await Fk({network:a,rpcUrl:o}),c=M({chain:s,transport:de(o)});t||console.log(`Funding "${n}" on ${Ik(s)}`);try{let{Actions:r}=await import(`viem/tempo`),a=await r.faucet.fund(c,{account:i}),o=s.blockExplorers?.default?.url;if(!t)for(let e of a){let t=o?Ek(`${o}/tx/${e}`,X.gray(e)):e;console.log(` ${t}`)}let{waitForTransactionReceipt:l}=await import(`viem/actions`);return await Promise.all(a.map(e=>l(c,{hash:e}))),fz(e,{account:n,chain:Ik(s),transactions:[...a]},()=>{console.log(`Funded successfully`)})}catch(n){let r=n instanceof Error?n.message:String(n);return t?e.error({code:`FUNDING_FAILED`,message:r,exitCode:1}):e.error({code:`FUNDING_FAILED`,message:`Funding failed: ${r}`,exitCode:1})}}}).command(`list`,{description:`List all accounts`,output:p.object({accounts:p.array(oz)}),async run(e){let t=$k().get(),n=(await tA().list()).sort(),r=[];for(let e of n){let t=await tA(e).get();t&&r.push({name:e,address:xe(t).address})}let i=LF();for(let e=0;e<i.length;e++){let t=i[e],n=e===0?`tempo:default`:`tempo:${e}`;t.wallet_address&&r.push({name:n,address:t.wallet_address,source:`tempo wallet`})}if(r.length===0)return fz(e,{accounts:[]},()=>{console.log(`No accounts found.`)});let a=P.blockExplorers?.default?.url,o=Math.max(...r.map(e=>e.name.length+ +(e.name===t)));return fz(e,{accounts:r.map(e=>({...e,...e.name===t?{isDefault:!0}:void 0}))},()=>{for(let e of r){let n=e.name===t,r=n?`${e.name}${X.dim(`*`)}`:e.name,i=e.name.length+ +!!n,s=a?Ek(`${a}/address/${e.address}`,e.address):e.address,c=e.source?` ${X.dim(`(${e.source})`)}`:``;console.log(`${r}${` `.repeat(o-i+2)}${X.dim(s)}${c}`)}})}}).command(`export`,{description:`Export the private key for a local account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`)}),output:p.object({privateKey:p.string()}),alias:{account:`a`},async run(e){let t=eA(e.options.account);if(kk(t))return e.error({code:`UNSUPPORTED_ACCOUNT`,message:`Account "${t}" is managed by Tempo wallet and does not expose a private key via mppx.`,exitCode:2});let n=await tA(t).get();return n?fz(e,{privateKey:n},()=>{console.log(n)}):e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}}).command(`view`,{description:`View account address`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:sz,alias:{account:`a`,rpcUrl:`r`},async run(e){let t=eA(e.options.account);if(kk(t)){let n=RF(t);if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69});let r=n.wallet_address,i=Nk(e.options.rpcUrl,{network:e.options.network}),a=await Fk({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?Ek(`${o}/address/${r}`,r):r,c=await Bk(r,a&&i?{chain:a,rpcUrl:i}:void 0);return fz(e,{address:r,balances:c,name:t,type:`${n.wallet_type} (tempo wallet)`},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`),console.log(`${X.dim(`Type`)} ${n.wallet_type} ${X.dim(`(tempo wallet)`)}`)})}let n=await tA(t).get();if(!n)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let r=xe(n),i=Nk(e.options.rpcUrl,{network:e.options.network}),a=await Fk({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?Ek(`${o}/address/${r.address}`,r.address):r.address,c=await Bk(r.address,a&&i?{chain:a,rpcUrl:i}:void 0);return fz(e,{address:r.address,balances:c,name:t},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`)})}}),Fz=pb(`sign`,{description:`Sign a payment challenge and output the Authorization header`,usage:[{suffix:`--challenge <value> [options]`},{prefix:`echo <challenge> |`,suffix:`[options]`}],options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),challenge:p.string().optional().describe(`WWW-Authenticate challenge value`),config:p.string().optional().describe(`Path to config file`),dryRun:p.boolean().optional().describe(`Validate and parse the challenge without signing`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`)}),output:p.object({authorization:p.string()}),alias:{account:`a`,challenge:`C`,config:`c`,methodOpt:`M`,rpcUrl:`r`},async run(e){let t=e.options.challenge||(mz()?await new Promise((e,t)=>{let n=``;process.stdin.setEncoding(`utf-8`),process.stdin.on(`data`,e=>{n+=e}),process.stdin.on(`end`,()=>e(n.trim())),process.stdin.on(`error`,t)}):void 0);if(!t)return e.error({code:`NO_CHALLENGE`,message:`No challenge provided. Use --challenge or pipe via stdin.`,exitCode:2});let n;try{n=gS(t)}catch(t){return e.error({code:`INVALID_CHALLENGE`,message:`Failed to parse challenge: ${t instanceof Error?t.message:t}`,exitCode:2})}if(e.options.dryRun){process.stderr.write(`Challenge is valid.
271
- `);return}let r=await oI(e.options.config),i=nI(n,r?.config);if(!i){let t=n.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:a,plugin:o,method:s}=i,c=Dk(e.options.methodOpt),l=iS(a),u=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:l}}),d;o&&(d=await o.setup({challenge:a,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:c}));let f=await eI(a,r?.config.extensions,d?.credentialContext),p;if(d)p=d.createCredential?await d.createCredential(u,f):await tE({methods:d.methods,polyfill:!1}).createCredential(u,f);else if(s)p=await tE({methods:[s],polyfill:!1}).createCredential(u,f);else return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method: ${a.method}/${a.intent}. Add it to mppx.config.ts using defineConfig().`,exitCode:2});return fz(e,{authorization:p},()=>{console.log(p)})}}),Iz=pb(`init`,{description:`Create an mppx.config.ts file in the current directory`,options:p.object({force:p.boolean().optional().describe(`Overwrite existing config file`)}),output:p.object({file:p.string()}),alias:{force:`f`},async run(e){let n=process.cwd(),r=`mppx.config${(()=>{if(t.existsSync(c.join(n,`tsconfig.json`)))return`.ts`;try{if(JSON.parse(t.readFileSync(c.join(n,`package.json`),`utf-8`)).type===`module`)return`.mjs`}catch{}return`.js`})()}`,i=c.join(n,r);return t.existsSync(i)&&!e.options.force?e.error({code:`CONFIG_EXISTS`,message:`${r} already exists. Use --force to overwrite.`,exitCode:1}):(t.writeFileSync(i,`import { defineConfig } from 'mppx/cli'
272
+ `)),!await jk(`Confirm delete?`)){console.log(`Canceled`);return}}await t.delete();let a=$k().get(),o;if(a===e.options.account){let e=await tA().list();e.length>0?(o=e[0],$k().set(o)):$k().clear()}return gz(e,{defaultAccount:o,name:e.options.account},()=>{o&&console.log(`Default account set to "${o}"`),console.log(`Account "${e.options.account}" deleted`)})}}).command(`fund`,{description:`Fund account with testnet tokens`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({account:p.string(),chain:p.string(),transactions:p.array(p.string())}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=hz(e),n=eA(e.options.account),r=await tA(n).get();if(!r)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${n}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let i=xe(r),a=Pk(e.options),o=Nk(e.options.rpcUrl,{network:a}),s=await Fk({network:a,rpcUrl:o}),c=M({chain:s,transport:de(o)});t||console.log(`Funding "${n}" on ${Ik(s)}`);try{let{Actions:r}=await import(`viem/tempo`),a=await r.faucet.fund(c,{account:i}),o=s.blockExplorers?.default?.url;if(!t)for(let e of a){let t=o?Ek(`${o}/tx/${e}`,X.gray(e)):e;console.log(` ${t}`)}let{waitForTransactionReceipt:l}=await import(`viem/actions`);return await Promise.all(a.map(e=>l(c,{hash:e}))),gz(e,{account:n,chain:Ik(s),transactions:[...a]},()=>{console.log(`Funded successfully`)})}catch(n){let r=n instanceof Error?n.message:String(n);return t?e.error({code:`FUNDING_FAILED`,message:r,exitCode:1}):e.error({code:`FUNDING_FAILED`,message:`Funding failed: ${r}`,exitCode:1})}}}).command(`list`,{description:`List all accounts`,output:p.object({accounts:p.array(uz)}),async run(e){let t=$k().get(),n=(await tA().list()).sort(),r=[];for(let e of n){let t=await tA(e).get();t&&r.push({name:e,address:xe(t).address})}let i=LF();for(let e=0;e<i.length;e++){let t=i[e],n=e===0?`tempo:default`:`tempo:${e}`;t.wallet_address&&r.push({name:n,address:t.wallet_address,source:`tempo wallet`})}if(r.length===0)return gz(e,{accounts:[]},()=>{console.log(`No accounts found.`)});let a=P.blockExplorers?.default?.url,o=Math.max(...r.map(e=>e.name.length+ +(e.name===t)));return gz(e,{accounts:r.map(e=>({...e,...e.name===t?{isDefault:!0}:void 0}))},()=>{for(let e of r){let n=e.name===t,r=n?`${e.name}${X.dim(`*`)}`:e.name,i=e.name.length+ +!!n,s=a?Ek(`${a}/address/${e.address}`,e.address):e.address,c=e.source?` ${X.dim(`(${e.source})`)}`:``;console.log(`${r}${` `.repeat(o-i+2)}${X.dim(s)}${c}`)}})}}).command(`export`,{description:`Export the private key for a local account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`)}),output:p.object({privateKey:p.string()}),alias:{account:`a`},async run(e){let t=eA(e.options.account);if(kk(t))return e.error({code:`UNSUPPORTED_ACCOUNT`,message:`Account "${t}" is managed by Tempo wallet and does not expose a private key via mppx.`,exitCode:2});let n=await tA(t).get();return n?gz(e,{privateKey:n},()=>{console.log(n)}):e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}}).command(`view`,{description:`View account address`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:dz,alias:{account:`a`,rpcUrl:`r`},async run(e){let t=eA(e.options.account);if(kk(t)){let n=RF(t);if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69});let r=n.wallet_address,i=Nk(e.options.rpcUrl,{network:e.options.network}),a=await Fk({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?Ek(`${o}/address/${r}`,r):r,c=await Bk(r,a&&i?{chain:a,rpcUrl:i}:void 0);return gz(e,{address:r,balances:c,name:t,type:`${n.wallet_type} (tempo wallet)`},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`),console.log(`${X.dim(`Type`)} ${n.wallet_type} ${X.dim(`(tempo wallet)`)}`)})}let n=await tA(t).get();if(!n)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let r=xe(n),i=Nk(e.options.rpcUrl,{network:e.options.network}),a=await Fk({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?Ek(`${o}/address/${r.address}`,r.address):r.address,c=await Bk(r.address,a&&i?{chain:a,rpcUrl:i}:void 0);return gz(e,{address:r.address,balances:c,name:t},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`)})}}),zz=pb(`sign`,{description:`Sign a payment challenge and output the Authorization header`,usage:[{suffix:`--challenge <value> [options]`},{prefix:`echo <challenge> |`,suffix:`[options]`}],options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),challenge:p.string().optional().describe(`WWW-Authenticate challenge value`),config:p.string().optional().describe(`Path to config file`),dryRun:p.boolean().optional().describe(`Validate and parse the challenge without signing`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`)}),output:p.object({authorization:p.string()}),alias:{account:`a`,challenge:`C`,config:`c`,methodOpt:`M`,rpcUrl:`r`},async run(e){let t=e.options.challenge||(vz()?await new Promise((e,t)=>{let n=``;process.stdin.setEncoding(`utf-8`),process.stdin.on(`data`,e=>{n+=e}),process.stdin.on(`end`,()=>e(n.trim())),process.stdin.on(`error`,t)}):void 0);if(!t)return e.error({code:`NO_CHALLENGE`,message:`No challenge provided. Use --challenge or pipe via stdin.`,exitCode:2});let n;try{n=gS(t)}catch(t){return e.error({code:`INVALID_CHALLENGE`,message:`Failed to parse challenge: ${t instanceof Error?t.message:t}`,exitCode:2})}if(e.options.dryRun){process.stderr.write(`Challenge is valid.
273
+ `);return}let r=await oI(e.options.config),i=nI(n,r?.config);if(!i){let t=n.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:a,plugin:o,method:s}=i,c=Dk(e.options.methodOpt),l=iS(a),u=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:l}}),d;o&&(d=await o.setup({challenge:a,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:c}));let f=await eI(a,r?.config.extensions,d?.credentialContext),p;if(d)p=d.createCredential?await d.createCredential(u,f):await tE({methods:d.methods,polyfill:!1}).createCredential(u,f);else if(s)p=await tE({methods:[s],polyfill:!1}).createCredential(u,f);else return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method: ${a.method}/${a.intent}. Add it to mppx.config.ts using defineConfig().`,exitCode:2});return gz(e,{authorization:p},()=>{console.log(p)})}}),Bz=pb(`init`,{description:`Create an mppx.config.ts file in the current directory`,options:p.object({force:p.boolean().optional().describe(`Overwrite existing config file`)}),output:p.object({file:p.string()}),alias:{force:`f`},async run(e){let n=process.cwd(),r=`mppx.config${(()=>{if(t.existsSync(c.join(n,`tsconfig.json`)))return`.ts`;try{if(JSON.parse(t.readFileSync(c.join(n,`package.json`),`utf-8`)).type===`module`)return`.mjs`}catch{}return`.js`})()}`,i=c.join(n,r);return t.existsSync(i)&&!e.options.force?e.error({code:`CONFIG_EXISTS`,message:`${r} already exists. Use --force to overwrite.`,exitCode:1}):(t.writeFileSync(i,`import { defineConfig } from 'mppx/cli'
272
274
 
273
275
  export default defineConfig({
274
276
  methods: [],
275
277
  plugins: [],
276
278
  })
277
- `),fz(e,{file:i},()=>{console.log(`Created ${r}`)}))}}),Lz=pb(`services`,{description:`Browse the MPP services registry`}).command(`list`,{description:`List registered MPP services`,options:p.object({query:p.string().optional().describe(`Filter by id, name, category, tag, or description`)}),output:p.object({services:p.array(lz)}),alias:{query:`q`},async run(e){let t=e.options.query?.toLowerCase(),n=await jz(),r=(t?n.filter(e=>[e.id,e.name,e.description,...Array.isArray(e.categories)?e.categories:[],...Array.isArray(e.tags)?e.tags:[]].filter(e=>typeof e==`string`).some(e=>e.toLowerCase().includes(t))):n).map(_z).sort((e,t)=>e.id.localeCompare(t.id));return fz(e,{services:r},()=>{if(r.length===0){console.log(`No services found.`);return}let e=Math.max(...r.map(e=>e.id.length)),t=Math.max(...r.map(e=>String(e.paidEndpoints).length));for(let n of r){let r=n.name&&n.name!==n.id?` ${n.name}`:``,i=n.url?` ${X.dim(n.url)}`:``;console.log(`${n.id.padEnd(e)} ${String(n.paidEndpoints).padStart(t)} paid${r}${i}`)}})}}).command(`show`,{description:`Show one registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({service:p.record(p.string(),p.unknown())}),async run(e){let t=Mz(await jz(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=_z(t),r=gz(t);return fz(e,{service:t},()=>{console.log(`${n.name??n.id} ${X.dim(`(${n.id})`)}`),n.description&&console.log(n.description),n.url&&console.log(`${X.dim(`URL`)} ${Ek(n.url,n.url)}`),n.status&&console.log(`${X.dim(`Status`)} ${n.status}`),console.log(`${X.dim(`Endpoints`)} ${r.length} (${n.paidEndpoints} paid)`);let e=t.docs,i=e&&hz(e.homepage);i&&console.log(`${X.dim(`Docs`)} ${Ek(i,i)}`)})}}).command(`endpoints`,{description:`List endpoints for a registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({endpoints:p.array(uz),service:lz}),async run(e){let t=Mz(await jz(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=_z(t),r=gz(t).map(vz);return fz(e,{endpoints:r,service:n},()=>{if(r.length===0){console.log(`No endpoints found for ${n.id}.`);return}let e=Math.max(...r.map(e=>e.method.length)),t=Math.max(...r.map(e=>e.path.length));for(let n of r){let r=yz(n.payment),i=n.description?` ${X.dim(n.description)}`:``;console.log(`${n.method.padEnd(e)} ${n.path.padEnd(t)} ${r}${i}`)}})}}),Rz=pb(`discover`,{description:`Discovery tooling`}).command(`generate`,{description:`Generate a static OpenAPI discovery document from a module`,args:p.object({module:p.string().describe(`Path to a module that default-exports a discovery config`)}),options:p.object({output:p.string().optional().describe(`Write output to a file instead of stdout`)}),output:p.record(p.string(),p.unknown()),alias:{output:`o`},async run(e){let n=c.resolve(e.args.module);if(!t.existsSync(n))return e.error({code:`MODULE_NOT_FOUND`,message:`Module not found: ${n}`,exitCode:1});let r;try{r=await import(n)}catch(t){return e.error({code:`MODULE_IMPORT_FAILED`,message:`Failed to import module: ${t.message}`,exitCode:1})}let i=r.default??r,a;if(typeof i.openapi==`string`)a=i;else{let{generate:t}=await Promise.resolve().then(()=>(iz(),QR)),n=i.mppx;if(!n)return e.error({code:`INVALID_MODULE`,message:"Module must default-export an OpenAPI document (with `openapi` key) or an object with `mppx` (server instance) and `routes`.",exitCode:1});a=t(n,i)}let o=JSON.stringify(a,null,2);if(e.options.output){let n=c.resolve(e.options.output);return t.writeFileSync(n,`${o}\n`),process.stderr.write(`Wrote ${n}\n`),fz(e,a,()=>{})}return fz(e,a,()=>{console.log(o)})}}).command(`validate`,{description:`Validate an OpenAPI discovery document from a file or URL`,args:p.object({input:p.string().describe(`Path or URL to a discovery document`)}),output:p.object({errorCount:p.number(),issues:p.array(cz),valid:p.boolean(),warningCount:p.number()}),async run(e){let n=e.args.input,r;if(/^https?:\/\//.test(n)){let t=new AbortController,i=setTimeout(()=>t.abort(),3e4),a;try{a=await globalThis.fetch(n,{signal:t.signal})}catch(t){clearTimeout(i);let n=t instanceof DOMException&&t.name===`AbortError`?`Request timed out after 30s`:t.message;return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: ${n}`,exitCode:1})}if(clearTimeout(i),!a.ok)return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: HTTP ${a.status}`,exitCode:1});let o=10485760,s=a.headers.get(`content-length`);if(s&&Number(s)>o||(r=await a.text(),r.length>o))return e.error({code:`DISCOVERY_TOO_LARGE`,message:`Discovery document exceeds 10 MB limit`,exitCode:1})}else{let i=c.resolve(n);if(!t.existsSync(i))return e.error({code:`DISCOVERY_NOT_FOUND`,message:`Discovery document not found: ${i}`,exitCode:1});r=t.readFileSync(i,`utf-8`)}let i;try{i=JSON.parse(r)}catch(t){return e.error({code:`DISCOVERY_INVALID_JSON`,message:`Invalid discovery JSON: ${t.message}`,exitCode:1})}let a=PE(i);if(!dz(e))for(let e of a)console.log(`[${e.severity}] ${e.path}: ${e.message}`);let o=a.filter(e=>e.severity===`error`).length,s=a.filter(e=>e.severity===`warning`).length;return o>0?e.error({code:`DISCOVERY_INVALID`,message:`Discovery document has ${o} error(s) and ${s} warning(s).`,exitCode:1}):fz(e,{errorCount:o,issues:a,valid:!0,warningCount:s},()=>{console.log(s>0?`Discovery document is valid with ${s} warning(s).`:`Discovery document is valid.`)})}}),zz=p.object({address:p.string(),id:p.string(),livemode:p.boolean(),network:p.string(),supportedTokens:p.array(p.object({contractAddress:p.string(),currency:p.string()}))}),Bz=pb(`stripe`,{description:`Stripe machine payments tooling`}).command(`address`,{description:`Create a Stripe crypto deposit address and print its public address`,usage:[{suffix:`[--network tempo|base|solana] [--env [path]] [--secret-key <key>] [options]`}],options:p.object({customer:p.string().optional().describe(`Scope the address to a Stripe customer (cus_...); it then only accepts their funds`),env:p.string().optional().describe(`Write <NETWORK>_DEPOSIT_ADDRESS to this env file instead of printing (default path: .env)`),live:p.boolean().optional().describe(`Use the Stripe CLI's live mode key instead of its test mode key`),network:p.enum([`tempo`,`base`,`solana`]).default(`tempo`).describe(`Network to create the address on`),projectName:p.string().optional().describe(`Stripe CLI project to read the key from (env: STRIPE_PROJECT_NAME, default: default)`),secretKey:p.string().optional().describe(`Stripe secret key (sk_...); else STRIPE_SECRET_KEY, else the Stripe CLI's login`),stripeAccount:p.string().optional().describe(`Connected account to create the address for (acct_...)`)}),output:zz,alias:{network:`n`},async run(e){let{customer:t,env:n,live:r,network:i,projectName:a,secretKey:o,stripeAccount:s}=e.options;if(n&&t)return e.error({code:`INVALID_OPTIONS`,message:`--env can't be combined with --customer: that address only accepts the customer's funds.`,exitCode:2});let c=DL({live:r,projectName:a,secretKey:o});if(!c)return e.error({code:`MISSING_STRIPE_SECRET_KEY`,message:`No Stripe key found. Pass --secret-key <sk_...>, set STRIPE_SECRET_KEY, or run \`stripe login\` so mppx can read the Stripe CLI's ${r?`live`:`test`} mode key.`,exitCode:2});let l=new URLSearchParams({network:i});t&&l.set(`customer`,t);let u=await globalThis.fetch(new URL(`/v1/crypto/deposit_addresses`,process.env.MPPX_STRIPE_API_URL??`https://api.stripe.com`),{method:`POST`,headers:{Authorization:`Bearer ${c.key}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":FE,...s?{"Stripe-Account":s}:{}},body:l}),d=await u.json().catch(()=>({}));if(!u.ok||!d.address){let t=d.error?.code&&/^[a-z_]+$/.test(d.error.code)?`, ${d.error.code}`:``,n=`HTTP ${u.status}${t}`,r=u.status===401||u.status===403,i=c.source===`stripe-cli`?`the Stripe CLI's login`:c.source===`flag`?`--secret-key`:`STRIPE_SECRET_KEY`,a=r&&c.key.startsWith(`rk_`)?`Stripe refused the restricted key (rk_...) from ${i} for crypto deposit addresses (${n}). Pass a secret key with --secret-key <sk_...> or STRIPE_SECRET_KEY.`:r&&c.source===`stripe-cli`?`Stripe refused the key from the Stripe CLI's login (${n}). Run \`stripe login\` again, or pass --secret-key <sk_...>.`:`Stripe could not create a deposit address (${n}).`;return e.error({code:`STRIPE_REQUEST_FAILED`,message:a,exitCode:1})}let f={address:d.address,id:d.id??``,livemode:d.livemode??!1,network:d.network??i,supportedTokens:(d.supported_tokens??[]).map(e=>({contractAddress:e.token_contract_address,currency:e.token_currency}))};if(n){let t=`${i.toUpperCase()}_DEPOSIT_ADDRESS`;return NL(n,t,f.address),console.error(`Wrote ${t} to ${n}`),fz(e,f,()=>{})}return fz(e,f,()=>console.log(f.address))}});Nz.command(Pz),Nz.command(Rz),Nz.command(Iz),Nz.command(Lz),Nz.command(_L),Nz.command(Fz),Nz.command(Bz),Nz.command(GR);const Vz=Nz.serve.bind(Nz);Nz.serve=(e=process.argv.slice(2),t)=>Vz(PL(e),t);export{Nz as default,Dz as resolveMppCredentialTarget};
279
+ `),gz(e,{file:i},()=>{console.log(`Created ${r}`)}))}}),Vz=pb(`services`,{description:`Browse the MPP services registry`}).command(`list`,{description:`List registered MPP services`,options:p.object({query:p.string().optional().describe(`Filter by id, name, category, tag, or description`)}),output:p.object({services:p.array(pz)}),alias:{query:`q`},async run(e){let t=e.options.query?.toLowerCase(),n=await Fz(),r=(t?n.filter(e=>[e.id,e.name,e.description,...Array.isArray(e.categories)?e.categories:[],...Array.isArray(e.tags)?e.tags:[]].filter(e=>typeof e==`string`).some(e=>e.toLowerCase().includes(t))):n).map(xz).sort((e,t)=>e.id.localeCompare(t.id));return gz(e,{services:r},()=>{if(r.length===0){console.log(`No services found.`);return}let e=Math.max(...r.map(e=>e.id.length)),t=Math.max(...r.map(e=>String(e.paidEndpoints).length));for(let n of r){let r=n.name&&n.name!==n.id?` ${n.name}`:``,i=n.url?` ${X.dim(n.url)}`:``;console.log(`${n.id.padEnd(e)} ${String(n.paidEndpoints).padStart(t)} paid${r}${i}`)}})}}).command(`show`,{description:`Show one registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({service:p.record(p.string(),p.unknown())}),async run(e){let t=Iz(await Fz(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=xz(t),r=bz(t);return gz(e,{service:t},()=>{console.log(`${n.name??n.id} ${X.dim(`(${n.id})`)}`),n.description&&console.log(n.description),n.url&&console.log(`${X.dim(`URL`)} ${Ek(n.url,n.url)}`),n.status&&console.log(`${X.dim(`Status`)} ${n.status}`),console.log(`${X.dim(`Endpoints`)} ${r.length} (${n.paidEndpoints} paid)`);let e=t.docs,i=e&&yz(e.homepage);i&&console.log(`${X.dim(`Docs`)} ${Ek(i,i)}`)})}}).command(`endpoints`,{description:`List endpoints for a registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({endpoints:p.array(mz),service:pz}),async run(e){let t=Iz(await Fz(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=xz(t),r=bz(t).map(Sz);return gz(e,{endpoints:r,service:n},()=>{if(r.length===0){console.log(`No endpoints found for ${n.id}.`);return}let e=Math.max(...r.map(e=>e.method.length)),t=Math.max(...r.map(e=>e.path.length));for(let n of r){let r=Cz(n.payment),i=n.description?` ${X.dim(n.description)}`:``;console.log(`${n.method.padEnd(e)} ${n.path.padEnd(t)} ${r}${i}`)}})}}),Hz=pb(`discover`,{description:`Discovery tooling`}).command(`generate`,{description:`Generate a static OpenAPI discovery document from a module`,args:p.object({module:p.string().describe(`Path to a module that default-exports a discovery config`)}),options:p.object({output:p.string().optional().describe(`Write output to a file instead of stdout`)}),output:p.record(p.string(),p.unknown()),alias:{output:`o`},async run(e){let n=c.resolve(e.args.module);if(!t.existsSync(n))return e.error({code:`MODULE_NOT_FOUND`,message:`Module not found: ${n}`,exitCode:1});let r;try{r=await import(n)}catch(t){return e.error({code:`MODULE_IMPORT_FAILED`,message:`Failed to import module: ${t.message}`,exitCode:1})}let i=r.default??r,a;if(typeof i.openapi==`string`)a=i;else{let{generate:t}=await Promise.resolve().then(()=>(cz(),nz)),n=i.mppx;if(!n)return e.error({code:`INVALID_MODULE`,message:"Module must default-export an OpenAPI document (with `openapi` key) or an object with `mppx` (server instance) and `routes`.",exitCode:1});a=t(n,i)}let o=JSON.stringify(a,null,2);if(e.options.output){let n=c.resolve(e.options.output);return t.writeFileSync(n,`${o}\n`),process.stderr.write(`Wrote ${n}\n`),gz(e,a,()=>{})}return gz(e,a,()=>{console.log(o)})}}).command(`validate`,{description:`Validate an OpenAPI discovery document from a file or URL`,args:p.object({input:p.string().describe(`Path or URL to a discovery document`)}),output:p.object({errorCount:p.number(),issues:p.array(fz),valid:p.boolean(),warningCount:p.number()}),async run(e){let n=e.args.input,r;if(/^https?:\/\//.test(n)){let t=new AbortController,i=setTimeout(()=>t.abort(),3e4),a;try{a=await globalThis.fetch(n,{signal:t.signal})}catch(t){clearTimeout(i);let n=t instanceof DOMException&&t.name===`AbortError`?`Request timed out after 30s`:t.message;return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: ${n}`,exitCode:1})}if(clearTimeout(i),!a.ok)return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: HTTP ${a.status}`,exitCode:1});let o=10485760,s=a.headers.get(`content-length`);if(s&&Number(s)>o||(r=await a.text(),r.length>o))return e.error({code:`DISCOVERY_TOO_LARGE`,message:`Discovery document exceeds 10 MB limit`,exitCode:1})}else{let i=c.resolve(n);if(!t.existsSync(i))return e.error({code:`DISCOVERY_NOT_FOUND`,message:`Discovery document not found: ${i}`,exitCode:1});r=t.readFileSync(i,`utf-8`)}let i;try{i=JSON.parse(r)}catch(t){return e.error({code:`DISCOVERY_INVALID_JSON`,message:`Invalid discovery JSON: ${t.message}`,exitCode:1})}let a=PE(i);if(!hz(e))for(let e of a)console.log(`[${e.severity}] ${e.path}: ${e.message}`);let o=a.filter(e=>e.severity===`error`).length,s=a.filter(e=>e.severity===`warning`).length;return o>0?e.error({code:`DISCOVERY_INVALID`,message:`Discovery document has ${o} error(s) and ${s} warning(s).`,exitCode:1}):gz(e,{errorCount:o,issues:a,valid:!0,warningCount:s},()=>{console.log(s>0?`Discovery document is valid with ${s} warning(s).`:`Discovery document is valid.`)})}}),Uz=p.object({address:p.string(),id:p.string(),livemode:p.boolean(),network:p.string(),supportedTokens:p.array(p.object({contractAddress:p.string(),currency:p.string()}))}),Wz=pb(`stripe`,{description:`Stripe machine payments tooling`}).command(`address`,{description:`Create a Stripe crypto deposit address and print its public address`,usage:[{suffix:`[--network tempo|base|solana] [--env [path]] [--secret-key <key>] [options]`}],options:p.object({customer:p.string().optional().describe(`Scope the address to a Stripe customer (cus_...); it then only accepts their funds`),env:p.string().optional().describe(`Write <NETWORK>_DEPOSIT_ADDRESS to this env file instead of printing (default path: .env)`),live:p.boolean().optional().describe(`Use the Stripe CLI's live mode key instead of its test mode key`),network:p.enum([`tempo`,`base`,`solana`]).default(`tempo`).describe(`Network to create the address on`),projectName:p.string().optional().describe(`Stripe CLI project to read the key from (env: STRIPE_PROJECT_NAME, default: default)`),secretKey:p.string().optional().describe(`Stripe secret key (sk_...); else STRIPE_SECRET_KEY, else the Stripe CLI's login`),stripeAccount:p.string().optional().describe(`Connected account to create the address for (acct_...)`)}),output:Uz,alias:{network:`n`},async run(e){let{customer:t,env:n,live:r,network:i,projectName:a,secretKey:o,stripeAccount:s}=e.options;if(n&&t)return e.error({code:`INVALID_OPTIONS`,message:`--env can't be combined with --customer: that address only accepts the customer's funds.`,exitCode:2});let c=DL({live:r,projectName:a,secretKey:o});if(!c)return e.error({code:`MISSING_STRIPE_SECRET_KEY`,message:`No Stripe key found. Pass --secret-key <sk_...>, set STRIPE_SECRET_KEY, or run \`stripe login\` so mppx can read the Stripe CLI's ${r?`live`:`test`} mode key.`,exitCode:2});let l=new URLSearchParams({network:i});t&&l.set(`customer`,t);let u=await globalThis.fetch(new URL(`/v1/crypto/deposit_addresses`,process.env.MPPX_STRIPE_API_URL??`https://api.stripe.com`),{method:`POST`,headers:{Authorization:`Bearer ${c.key}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":FE,...s?{"Stripe-Account":s}:{}},body:l}),d=await u.json().catch(()=>({}));if(!u.ok||!d.address){let t=d.error?.code&&/^[a-z_]+$/.test(d.error.code)?`, ${d.error.code}`:``,n=`HTTP ${u.status}${t}`,r=u.status===401||u.status===403,i=c.source===`stripe-cli`?`the Stripe CLI's login`:c.source===`flag`?`--secret-key`:`STRIPE_SECRET_KEY`,a=r&&c.key.startsWith(`rk_`)?`Stripe refused the restricted key (rk_...) from ${i} for crypto deposit addresses (${n}). Pass a secret key with --secret-key <sk_...> or STRIPE_SECRET_KEY.`:r&&c.source===`stripe-cli`?`Stripe refused the key from the Stripe CLI's login (${n}). Run \`stripe login\` again, or pass --secret-key <sk_...>.`:`Stripe could not create a deposit address (${n}).`;return e.error({code:`STRIPE_REQUEST_FAILED`,message:a,exitCode:1})}if(!NL(i,d.address))return e.error({code:`STRIPE_INVALID_ADDRESS`,message:`Stripe returned a deposit address that isn't a valid ${i} address.`,exitCode:1});let f={address:d.address,id:d.id??``,livemode:d.livemode??!1,network:d.network??i,supportedTokens:(d.supported_tokens??[]).map(e=>({contractAddress:e.token_contract_address,currency:e.token_currency}))};if(n){let t=`${i.toUpperCase()}_DEPOSIT_ADDRESS`;return FL(n,t,f.address),console.error(`Wrote ${t} to ${n}`),gz(e,f,()=>{})}return gz(e,f,()=>console.log(f.address))}});Lz.command(Rz),Lz.command(Hz),Lz.command(Bz),Lz.command(Vz),Lz.command(_L),Lz.command(zz),Lz.command(Wz),Lz.command(YR);const Gz=Lz.serve.bind(Lz);Lz.serve=(e=process.argv.slice(2),t)=>Gz(RL(e),t);export{Lz as default,jz as resolveMppCredentialTarget};