mppx 0.19.1 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/cli/cli.js +2 -2
- package/dist/extensions/identity/erc8004/Constants.d.ts +20 -0
- package/dist/extensions/identity/erc8004/Constants.js +20 -0
- package/dist/extensions/identity/erc8004/Types.d.ts +11 -0
- package/dist/extensions/identity/erc8004/Types.js +2 -0
- package/dist/extensions/identity/erc8004/client/index.d.ts +33 -0
- package/dist/extensions/identity/erc8004/client/index.js +33 -0
- package/dist/extensions/identity/erc8004/index.d.ts +5 -0
- package/dist/extensions/identity/erc8004/index.js +4 -0
- package/dist/extensions/identity/erc8004/internal/Agent.d.ts +21 -0
- package/dist/extensions/identity/erc8004/internal/Agent.js +24 -0
- package/dist/extensions/identity/erc8004/server/index.d.ts +44 -0
- package/dist/extensions/identity/erc8004/server/index.js +178 -0
- package/dist/extensions/identity/index.d.ts +2 -0
- package/dist/extensions/identity/index.js +2 -0
- package/dist/identity/Headers.d.ts +1 -1
- package/dist/identity/Headers.js +2 -0
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/proxy/Proxy.js +47 -9
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/session/server/CredentialVerification.d.ts +2 -0
- package/dist/tempo/session/server/CredentialVerification.js +44 -0
- package/dist/tempo/session/server/MeteredStream.d.ts +2 -0
- package/dist/tempo/session/server/MeteredStream.js +11 -0
- package/dist/tempo/session/server/Sse.js +9 -4
- package/package.json +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# mppx
|
|
2
2
|
|
|
3
|
+
## 0.20.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- e2d81d0: Required manual charges before billable per-item stream generation; billable automatic SSE proxy sessions now require request pricing. Session replay retains payment verification, and opening credentials bind their source to the signed transaction payer.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- d8292be: Added `mppx/extensions/identity/erc8004`: an ERC-8004 agent identity provider. The client prover signs each request with the agent's wallet, and the server's verifier and payment check require that the wallet the Identity Registry names (on Tempo mainnet by default) signed the request or signed the transaction or proof of a `tempo` charge (transaction hashes, sessions, Zones and other methods need the signature). The proxy and cross-origin redirects drop its `Agent-Id` and `Agent-Signature` headers.
|
|
12
|
+
|
|
3
13
|
## 0.19.1
|
|
4
14
|
|
|
5
15
|
### Patch Changes
|
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 UC=I((()=>{}));function WC(e){let{extensions:t,resource:n,...r}=e;return iw.parse(r)}var GC,KC,qC,JC,YC,XC,ZC,QC,$C,ew,tw,nw,rw,iw,aw,ow,sw,cw,lw,uw,dw,fw,pw=I((()=>{oS(),GC=`charge`,KC=[`exact`],qC=`eip155:`,JC=`x402:`,YC=`PAYMENT-REQUIRED`,XC=`PAYMENT-SIGNATURE`,ZC=`PAYMENT-RESPONSE`,QC=J.string().check(J.minLength(1)),$C=J.number().check(J.refine(e=>e>0,`Must be positive`)),ew=J.string().check(J.regex(/^\d+$/,`Invalid atomic amount`)),tw=tS(),nw=J.string().check(J.regex(RegExp(`^${qC}\\d+$`),`Invalid EVM CAIP-2 network`)),rw=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:QC}),J.discriminatedUnion(`type`,[J.object({name:QC,type:J.literal(`eip3009`),version:QC}),J.object({name:J.optional(J.string()),type:J.literal(`permit2`),version:J.optional(J.string())})]),iw=J.object({amount:ew,asset:QC,extra:J.optional(J.record(J.string(),J.unknown())),maxTimeoutSeconds:$C,network:nw,payTo:QC,scheme:J.enum(KC)}),aw=J.object({info:J.record(J.string(),J.unknown()),schema:J.record(J.string(),J.unknown())}),ow=J.record(J.string(),aw),sw=J.object({accepts:J.array(iw).check(J.minLength(1)),error:J.optional(J.string()),extensions:J.optional(ow),resource:rw,x402Version:J.literal(2)}),cw=J.object({authorization:J.object({from:tw,nonce:nS(),to:tw,validAfter:ew,validBefore:ew,value:ew}),signature:iS()}),lw=J.object({permit2Authorization:J.object({deadline:ew,from:tw,nonce:ew,permitted:J.object({amount:ew,token:tw}),spender:tw,witness:J.object({to:tw,validAfter:ew})}),signature:iS()}),uw=J.union([cw,lw]),dw=J.object({accepted:iw,extensions:J.optional(ow),payload:uw,resource:J.optional(rw),x402Version:J.literal(2)}),J.object({extensions:J.optional(ow),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())}),fw=J.object({amount:J.optional(ew),errorMessage:J.optional(J.string()),errorReason:J.optional(J.string()),extensions:J.optional(ow),extra:J.optional(J.record(J.string(),J.unknown())),network:QC,payer:J.optional(J.string()),success:J.boolean(),transaction:J.string()})}));function mw(e,t,n){let r=new Headers(e.headers);for(let e of hw)e===q.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}var hw,gw=I((()=>{Wx(),pw(),hw=[q.authorization,YC,ZC,XC]}));function _w(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 vw(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 yw(e){let t=_w(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 bw(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 xw(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=ES.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 Sw(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:xw(e.error.data):xw(e.result?._meta?.[BC])}function Cw(e,t){return!e||e.id!==t?[]:Sw(e)?.challenges??[]}async function ww(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=HC(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=bw(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>Ow)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function Tw(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 bw(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>Ow)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function Ew(e){let t=kw.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>Ow)){if(t.includes(`application/json`))return Tw(e);if(t.includes(`text/event-stream`))return ww(e)}})();return kw.set(e,n),n}function Dw(){return{getChallenges(e,t){let n=yw(t);return e.status===402||n===void 0?[]:Ew(e).then(e=>Cw(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=zS(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,[zC]:r}}})}}}}var Ow,kw,Aw=I((()=>{DS(),JS(),UC(),VC(),gw(),Ow=1048576,kw=new WeakMap}));function jw(){return{getChallenges(e){let t=e.headers.get(q.wwwAuthenticate);return e.status!==402||!t||!gS(t)?[]:vS(e)},setCredential(e,t,n){return mw(e,n?.challenge?SS(n.challenge):q.authorization,t)}}}var Mw=I((()=>{DS(),Wx(),gw()}));function Nw(e){return{encode(t){return re.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(re.toString(t)))}catch{throw new Pw}}}}var Pw,Fw=I((()=>{Pw=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}}}));function Iw(e){try{let t=JSON.parse(re.toString(e));return Hw(t)}catch{throw new Pw}}var Lw,Rw,zw,Bw,Vw,Hw,Uw=I((()=>{Fw(),pw(),Lw=Nw(sw),Rw=Nw(dw),zw=Nw(fw),Bw=Lw.encode,Lw.decode,Vw=Rw.encode,Rw.decode,zw.encode,zw.decode,Hw=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Pw;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Pw;let n=rw.parse(t.resource),r=t.extensions===void 0?void 0:ow.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}}}));function Ww(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(YC);if(!t)return[];let n=Iw(t);return n.accepts.flatMap((e,t)=>{let r=iw.safeParse(e);if(!r.success)return[];let i=r.data;return mC(sS({id:`${JC}${t}`,intent:GC,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return mw(e,XC,t)}}}var Gw=I((()=>{DS(),Uw(),_C(),pw(),gw()}));function Kw(e){return e}function qw(){let e=[jw(),Ww(),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 Kw({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 Jw=I((()=>{Aw(),Mw(),gw(),Gw()}));function Yw(e,t){return $w.set(e,t),e}function Xw(e){return $w.has(e)}function Zw(e,t){return Promise.resolve($w.get(e)?.(t))}function Qw(e){return $w.get(e)}var $w,eT=I((()=>{$w=new WeakMap}));function tT(e,t){return uT.set(e,t),e}function nT(e){uT.delete(e)}function rT(e,t,n){uT.has(e)&&dT.set(t,n)}function iT(e){return dT.get(e)}function aT(e,t){return Promise.resolve(uT.get(e)?.(t)??t.response)}function oT(e,t){return pT.set(e,t),e}function sT(e,t){try{return pT.get(e)?.(t)}catch{return}}function cT(e,t){fT.set(e,t)}function lT(e){return fT.get(e)??dT.get(e)?.origin}var uT,dT,fT,pT,mT=I((()=>{uT=new WeakMap,dT=new WeakMap,fT=new WeakMap,pT=new WeakMap}));function hT(e,t,n){if(!_T(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&&vT(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 gT(e,t){if(!(!_T(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 _T(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function vT(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}var yT=I((()=>{}));async function bT(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},dE);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>uE){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(fE,`true`);let s=new Response(new Blob(n).slice(0,uE),{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 xT(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 ST(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=lE,methods:a,onChallenge:o,orderChallenges:s,transport:c=qw(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&KT(e.fetch)),d=e.eventDispatcher??TT(),f=t??yC(a),p=qT(r),m=async(e,t,n)=>u?u.send(p,new Request(e,t),n):{response:await p(e,t),headers:[]},h=async(e,t,r)=>{let g=GT(e,t?.headers),_=g.has(q.acceptPayment),v=QT(g,f),y=UT(e,t,g),b=HT(e,t,g,v.header,_,n),x=await m(JT(b.input),b.init),S=x.response,C=x.headers,w=WT(b.init,await y);if(t?.[cE]||vw(w)||!await c.isPaymentRequired(S,w))return S;let T=t?.context,{context:ee,orderChallenges:te,...ne}=w??{},E,D,re,O,ie;try{for(let n=0;n<i;n++){D=await c.getChallenges(S,w);let i=(await $T(CC(D,a,v.entries,T),te??s))[0];if(!i){if(await xT(O,{challenges:D,response:S,status:`rejected`}),n>0)return S;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;E=f,re=i.method,E.expires&&LS(E.expires,E.id),await u?.challenge(S,{challenge:f},rE(b.input).href);let g=await aE(S,b.input,b.input,ne);hT(f,()=>rE(g),l);let _=O,y=cS(f),x=_?.method===i.method&&_?.key===y,ee=!1;if(_){let e=await xT(_,{challenges:D,response:S,status:x?`pending`:`rejected`});ee=x&&!e}O=ee?_:void 0;let k=AT(async n=>{if(n===void 0&&ee&&_)return _.promise;ee&&_&&(await xT(_,{status:`rejected`}),O=void 0),YT(e,t)?.throwIfAborted();let r=n??T;if(!Xw(i.method))return ZT(f,i.method,r);let a={origin:rE(g).origin,prepare:()=>Zw(i.method,{challenge:f,context:r,fetch:u?aC(p,u,{challenge:f}):p,input:g,signal:YT(e,t)})},o=a.prepare().then(()=>ZT(f,i.method,r,a));return O={context:r,attempt:a,key:n===void 0?y:void 0,method:i.method,promise:o},o}),ae=await d.emit(`challenge.received`,jT({challenge:f,challenges:D,createCredential:k,init:t,input:e,method:i.method,response:S}))??(o?await o(E,{createCredential:k}):void 0)??await k(),A=O;A&&await A.promise.catch(()=>void 0)!==ae&&(await xT(A,{status:`rejected`}),O=void 0);let oe=O?O.context:T;XT(ae),await d.emit(`credential.created`,MT({challenge:f,credential:ae,init:t,input:e,method:i.method,response:S}));let se=e=>new MS({cause:e,challenge:f,credential:ae,transactionHash:sT(i.method,ae)});try{({response:S}=await m(g,{...c.setCredential({...ne,headers:b.headers},ae,{challenge:f}),redirect:`manual`},{challenge:f,headers:C}))}catch(e){throw ie=se(e),e}let ce=await c.isPaymentRequired(S,w);if(ce||(await xT(A,{response:S,status:S.status>=300&&S.status<400?`pending`:S.ok?`accepted`:`rejected`}),O=void 0),S.ok&&ET(d,`payment.response`)&&await d.emit(`payment.response`,NT({challenge:f,credential:ae,init:t,input:e,method:i.method,response:S})),!ce){if(S.status>=500&&ET(d,`payment.failed`)){try{S=await bT(S)}catch(e){throw ie=se(e),S=new Response(null,{headers:S.headers,status:S.status,statusText:S.statusText}),e}await d.emit(`payment.failed`,PT({challenge:f,challenges:D,error:se(),init:t,input:e,method:i.method,response:S}))}return S.ok?aT(i.method,{context:oe,challenge:f,credential:ae,fetch:p,headers:b.headers,input:g,...r?{refetch:()=>h(JT(b.input),t,!1)}:{},response:S,signal:YT(e,t)}):S}}D=void 0;try{D=await c.getChallenges(S,w)}catch{}return await xT(O,{challenges:D,response:S,status:`rejected`}),S}catch(n){throw await xT(O,{challenges:D,response:S,status:`rejected`}),await d.emit(`payment.failed`,PT({challenge:E,challenges:D,error:ie??n,init:t,input:e,method:re,response:S})),n}},g=(e,t)=>h(e,t,!0);return g[oE]=p,u&&(g[sE]=u),g}function CT(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);pE||=globalThis.fetch,globalThis.fetch=ST({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??(nE()?`same-origin`:`always`),fetch:qT(globalThis.fetch)})}function wT(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 TT(){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 kT(e[`*`],t,n),r}case`credential.created`:await OT(e[`credential.created`],n),await kT(e[`*`],t,n);return;case`payment.failed`:await OT(e[`payment.failed`],n),await kT(e[`*`],t,n);return;case`payment.response`:await OT(e[`payment.response`],n),await kT(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 mE.set(t,t=>e[t].size>0||e[`*`].size>0),t}function ET(e,t){return mE.get(e)?.(t)??!0}async function DT(e,t){try{return await e(t)}catch{return}}async function OT(e,t){for(let n of e)try{await n(t)}catch{}}async function kT(e,t,n){await OT(e,Object.freeze({name:t,payload:n}))}function AT(e){let t;return n=>(t??=e(n),t)}function jT(e){return Object.freeze({challenge:zT(e.challenge),challenges:e.challenges.map(e=>zT(e)),createCredential:e.createCredential,init:FT(e.init),input:IT(e.input),method:LT(e.method),response:RT(e.response)})}function MT(e){return Object.freeze({challenge:zT(e.challenge),credential:e.credential,init:FT(e.init),input:IT(e.input),method:LT(e.method),...e.response===void 0?{}:{response:RT(e.response)}})}function NT(e){return Object.freeze({challenge:zT(e.challenge),credential:e.credential,init:FT(e.init),input:IT(e.input),method:LT(e.method),response:RT(e.response)})}function PT(e){return Object.freeze({...e.challenge?{challenge:zT(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>zT(e))}:{},error:e.error,init:FT(e.init),input:IT(e.input),...e.method?{method:LT(e.method)}:{},...e.response===void 0?{}:{response:RT(e.response)}})}function FT(e){if(e)return VT({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function IT(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function LT(e){return VT(Object.assign({},e))}function RT(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 zT(e)}function zT(e){try{return BT(structuredClone(e))}catch{return VT(e)}}function BT(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))BT(t);return e}function VT(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function HT(e,t,n,r,i,a){let o=!!r&&!i&&eE(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 UT(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 WT(e,t){return t===void 0?e:{...e,body:t}}function GT(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function KT(e){return e[sE]}function qT(e){let t=e;for(;t[oE];)t=t[oE];return t}function JT(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function YT(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function XT(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 ZT(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&&cT(a,r.origin),r&&rT(t,a,r),t.createCredential(a)}function QT(e,t){let n=e.get(q.acceptPayment);if(!n)return t;try{return{...t,entries:bC(n),header:n}}catch{return t}}async function $T(e,t){return t?t(e):e}function eE(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=rE(e);return t===`same-origin`?!nE()||n.origin===globalThis.location.origin:t.origins.some(e=>tE(n,e))}function tE(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 nE(){return globalThis.location!==void 0}function rE(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,nE()?globalThis.location.href:void 0)}function iE(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 aE(e,t,n,r){if(iE(t,r),!e.url)return t;let i=new URL(e.url),a=rE(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 oE,sE,cE,lE,uE,dE,fE,pE,mE,hE=I((()=>{DS(),Wx(),IS(),RS(),pC(),RC(),Jw(),eT(),mT(),yT(),Aw(),oE=Symbol.for(`mppx.fetch.wrapper`),sE=Symbol.for(`mppx.fetch.identity`),cE=Symbol.for(`mppx.fetch.skipPayment`),lE=3,uE=65536,dE=2e3,fE=`Mppx-Body-Truncated`,mE=new WeakMap}));Lx(),hE();const gE=Object.freeze([`dpop`,`identity-attestation`,`identity-presentation`,`poppy-session`,`tempo-id-token`]);Object.freeze([`privatetoken`,`identity-presentation`]),Object.freeze([`identity-attestation-required`,`identity-required`]),Wx(),RS(),pC(),RC(),eT(),mT(),yT(),Jw();const _E=new WeakMap;function vE(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=qw(),trustedTempoProofRealms:c}=e;if(`attestation`in e)throw TypeError("Mppx client `attestation` was replaced by `identity: [prover]`.");let l=qT(e.fetch??globalThis.fetch),u=t?tC(t):e.fetch&&KT(e.fetch),d=e.methods.flat(),f=yC(d,e.paymentPreferences),p=TT(),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=ST(h);a&&CT(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=ME(e),a=await s.getChallenges(e,t?.request),o=Object.freeze(a.map(e=>NE(e))),l=IE(f.entries,t?.acceptPayment),u,m;try{let f=CC(a,d,l,n);f.length===0&&n===void 0&&(f=CC(a,d,l,LC));let h=(await LE(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&&LS(u.expires,u.id);let _=zE(e);_?hT(u,_,c):s.name===`mcp`&&gT(u,c&&Object.values(c));let v=u,y=m,b=DE(async e=>{try{v.expires&&LS(v.expires,v.id);let t=DE(t=>RE(v,y,t??e,_?.origin)),n=await p.emit(`challenge.received`,OE({challenge:v,challenges:a,createCredential:t,method:y,response:r}))??await t();return XT(n),await p.emit(`credential.created`,kE({challenge:v,credential:n,method:y,response:r})),n}catch(e){throw await p.emit(`payment.failed`,AE({challenge:v,challenges:a,error:e,method:y,response:r})),e}}),x=Object.freeze({challenge:v,challenges:o,createCredential:b,method:jE(y),setCredential(e,t){return XT(t),s.setCredential(e,t,{challenge:g})}});return _E.set(x,y),x}catch(e){throw await p.emit(`payment.failed`,AE({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 SE({acceptPayment:f.header,acceptPaymentPolicy:o,fetch:l,init:t,input:e,maxRedirects:r,identity:u}),p=CE(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});hT(m.challenge,new URL(d.replayRequest.url),c);let h=_E.get(m)??m.method,g=DE(async e=>(await u?.challenge(d.response,{challenge:m.challenge},d.replayRequest.url),Xw(h)&&await Zw(h,{challenge:m.challenge,context:e,fetch:u?aC(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(CE(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,headers:d.identityHeaders});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 yE=new Set([301,302,303,307,308]),bE=[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`,`transfer-encoding`],xE=[`authorization`,`cookie`,`cookie2`,`host`,`payment-authorization`,`payment-signature`,`proxy-authorization`,`x-payment`];async function SE(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 Set([...xE,...gE,...i?.headers??[]]),l=new Request(o,{...a,redirect:`manual`}),u=l.headers.has(q.acceptPayment),d=await wE(l,a?.body),f=[];for(;;){l=TE(l,t,u,n);let{request:e,response:a,headers:o}=await(async()=>{if(i)return i.send(r,l.clone());let e=l.clone();return{request:e,response:await r(e),headers:[]}})();if(a.type===`opaqueredirect`||a.status===0)throw Error(`prepareRequest requires a runtime that exposes manual redirect responses.`);if(!yE.has(a.status))return{body:d,identityHeaders:o,replayRequest:l,request:e,response:a,redirects:Object.freeze(f)};let p=a.headers.get(`location`);if(!p)return{body:d,identityHeaders:o,replayRequest:l,request:e,response:a,redirects:Object.freeze(f)};if(f.length>=s)throw await a.body?.cancel(),Error(`Payment request exceeded ${s} redirects.`);let m=new URL(l.url),h=new URL(p,m);if(m.protocol===`https:`&&h.protocol!==`https:`)throw await a.body?.cancel(),Error(`Payment request refused HTTPS downgrade redirect to ${h.href}`);let g=new Headers(l.headers),_=l.method;if((a.status===301||a.status===302)&&_===`POST`||a.status===303&&_!==`GET`&&_!==`HEAD`){_=`GET`,d=void 0;for(let e of bE)g.delete(e)}if(m.origin!==h.origin)for(let e of[...g.keys()]){let t=g.get(e)??``;(c.has(e)||t.startsWith(`Payment `))&&g.delete(e)}f.push(Object.freeze({from:m.href,status:a.status,to:h.href})),await a.body?.cancel(),l=new Request(h,EE(l,g,_,d))}}function CE(e,t){return EE(e,new Headers(e.headers),e.method,t)}async function wE(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 TE(e,t,n,r){if(n)return e;let i=new Headers(e.headers);return i.delete(q.acceptPayment),t&&eE(e,r)&&i.set(q.acceptPayment,t),new Request(e,{headers:i})}function EE(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 DE(e){let t;return n=>(t??=e(n),t)}function OE(e){return Object.freeze({challenge:NE(e.challenge),challenges:e.challenges.map(e=>NE(e)),createCredential:e.createCredential,method:jE(e.method),response:ME(e.response)})}function kE(e){return Object.freeze({challenge:NE(e.challenge),credential:e.credential,method:jE(e.method),response:ME(e.response)})}function AE(e){return Object.freeze({...e.challenge?{challenge:NE(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>NE(e))}:{},error:e.error,...e.method?{method:jE(e.method)}:{},response:ME(e.response)})}function jE(e){return FE(Object.assign({},e))}function ME(e){return e instanceof Response?e.body===null?e.clone():new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText}):NE(e)}function NE(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 PE(t)}catch{return FE(e)}}function PE(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))PE(t);return e}function FE(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function IE(e,t){return t?typeof t==`string`?bC(t):t:e}async function LE(e,t){return t?t(e):e}async function RE(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&&cT(a,r),t.createCredential(a)}function zE(e){if(typeof Response<`u`&&e instanceof Response&&e.url)return new URL(e.url)}function BE(){return J.string().check(J.regex(VE,`Invalid URI or path`))}var VE,HE,UE,WE,GE,KE,qE,JE,YE,XE=I((()=>{oS(),VE=/^([a-zA-Z][a-zA-Z\d+.-]*:\/\/\S+|\/\S*)$/,HE=new Set([`amount`,`currency`,`description`,`intent`,`method`]),UE=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())}),WE=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(UE).check(J.minLength(1)))}).check(J.refine(e=>e.offers===void 0||Object.keys(e).every(e=>e===`offers`||!HE.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`&&(HE.has(n)||r!==void 0)&&(t[n]=r);return{offers:[t]}})),GE=J.looseObject({apiReference:J.optional(BE()),homepage:J.optional(BE()),llms:J.optional(BE())}),KE=J.looseObject({categories:J.optional(J.array(J.string())),docs:J.optional(GE)}),qE=J.looseObject({"x-payment-info":J.optional(WE),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(qE),get:J.optional(qE),head:J.optional(qE),options:J.optional(qE),patch:J.optional(qE),post:J.optional(qE),put:J.optional(qE),trace:J.optional(qE)}),YE=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))})}));XE();function ZE(e){let t=[],n=YE.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=WE.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 QE=`2026-07-29.preview`;function $E(e){return e}function eD(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}var tD=I((()=>{}));function nD(e,t){return Je.resolve(e).toLowerCase()===Je.resolve(t).toLowerCase()}var rD=I((()=>{}));function iD(e){return Number.isInteger(e)&&e>0&&e<_D}function aD(e,t){return iD(t)?e===!0||(e?.includes(t)??!1):!1}function oD(e){return Ve.zonePortal(e)}function sD(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 cD(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 lD(e){return ie.keccak256(D.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function uD(e,t){let{blockNumber:n,sender:r,transactionHash:i}=t,a=t=>je(e,{abi:Re.zoneOutbox,address:Ve.zoneOutbox,blockNumber:t,functionName:`lastFallbackNonce`}),[o,s]=await Promise.all([a(n-1n),a(n)]);if(s<=o)throw Error(`Zone withdrawal transaction ${i} did not request a withdrawal from the outbox.`);if(s-o>mD)throw Error(`Zone withdrawal transaction ${i} has ${s-o} candidate sender tags, more than ${mD}.`);let c=[];for(let e=o+1n;e<=s;e++)c.push(lD({fallbackNonce:e,sender:r,transactionHash:i}));return c}async function dD(e,t){let{senderTags:n,timeoutMs:r=fD}=t;if(!Number.isFinite(r)||r<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);if(n.length===0)throw Error(`Zone settlement needs at least one sender tag.`);let i=await Oe(e,{cacheTime:0}),a=i>pD?i-pD:0n,o=Date.now()+r;for(;;){if(a<=i){let[r]=await ke(e,{address:t.portal,event:gD,args:{senderTag:[...n],...t.to?{to:t.to}:{}},fromBlock:a,toBlock:i});if(r?.transactionHash&&r.args.senderTag)return{hash:r.transactionHash,senderTag:r.args.senderTag};a=i+1n}if(Date.now()+hD>o)throw Error(`Zone withdrawal ${n.join(` or `)} did not settle on Tempo within ${r}ms.`);await new Promise(e=>setTimeout(e,hD)),i=await Oe(e,{cacheTime:0})}}var fD,pD,mD,hD,gD,_D,vD=I((()=>{fD=6e4,pD=7200n,mD=64n,hD=500,gD=de({abi:Re.zonePortal,name:`WithdrawalProcessed`}),_D=4217e5}));function yD(e){return J.refine(e=>{let{amount:t,decimals:n}=e;return P(t,n)>0n},e)}function bD(e){let{periodCount:t,periodUnit:n}=e;try{let e=wD[n];return e!==void 0&&BigInt(t)*e<=CD}catch{return!1}}var xD,SD,CD,wD,TD,ED,DD,OD,kD,AD,jD,MD,ND,PD=I((()=>{Wx(),tD(),oS(),vD(),xD=[`push`,`pull`],SD=J.object({amount:Xx(),memo:J.optional(nS()),recipient:J.pipe(J.string(),J.transform(e=>e))}),CD=(1n<<64n)-1n,wD={dev_second:1n,day:86400n,week:604800n},TD=J.pipe(tS(),J.transform(e=>e.toLowerCase())),ED=J.object({accessKeyAddress:TD,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)))}),DD=J.object({accessKey:J.optional(ED),chainId:J.optional(J.number())}),OD=Qx(`subscriptionExpires must be a valid date`).check(J.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),kD=J.enum([`dev_second`,`day`,`week`]),AD=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)<=CD}catch{return!1}},`periodCount exceeds uint64`)),jD=$E({name:`tempo`,intent:`charge`,schema:{credential:{payload:J.discriminatedUnion(`type`,[J.object({hash:nS(),type:J.literal(`hash`)}),J.object({signature:iS(),type:J.literal(`transaction`)}),J.object({signature:iS(),type:J.literal(`proof`)}),J.object({hash:nS(),senderTag:nS(),type:J.literal(`zone`),zoneId:J.number().check(J.refine(iD,`Invalid Zone ID`))})])},request:J.pipe(J.object({machineTokenEnabled:J.optional(J.boolean()),amount:Xx(),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(SD).check(J.minLength(1),J.maxLength(10))),supportedModes:J.optional(J.array(J.enum(xD)).check(J.minLength(1))),zones:J.optional(J.union([J.literal(!0),J.array(J.number().check(J.refine(iD,`Invalid Zone ID`))).check(J.minLength(1))]))}).check(J.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=P(e,t),i=n.reduce((e,n)=>e+P(n.amount,t),0n);return n.every(e=>P(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:P(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:P(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),MD=$E({name:`tempo`,intent:`session`,schema:{credential:{payload:J.discriminatedUnion(`action`,[J.object({action:J.literal(`open`),authorizedSigner:J.optional(J.string()),channelId:nS(),cumulativeAmount:Xx(),descriptor:J.optional(J.custom()),signature:iS(),transaction:iS(),type:J.literal(`transaction`)}),J.object({action:J.literal(`topUp`),additionalDeposit:Xx(),channelId:nS(),descriptor:J.optional(J.custom()),transaction:iS(),type:J.literal(`transaction`)}),J.object({action:J.literal(`voucher`),channelId:nS(),cumulativeAmount:Xx(),descriptor:J.optional(J.custom()),signature:iS()}),J.object({action:J.literal(`close`),channelId:nS(),closeSignature:iS(),cumulativeAmount:Xx(),descriptor:J.optional(J.custom()),signature:iS()})])},request:J.pipe(J.object({amount:Xx(),chainId:J.optional(J.number()),channelId:J.optional(nS()),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(tS()),minVoucherDelta:J.optional(Xx()),operator:J.optional(tS()),recipient:J.optional(J.string()),sessionProtocol:J.optional(J.enum([Ux.v2,Ux.v1])),sessionSnapshot:J.optional(J.custom()),suggestedDeposit:J.optional(Xx()),unitType:J.string()}).check(J.refine(({amount:e,decimals:t})=>P(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:P(e,r).toString(),...d?{suggestedDeposit:P(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:P(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&&{[Hx.sessionProtocol]:l},...u!==void 0&&{[Hx.sessionSnapshot]:u}}})))}}),ND=$E({name:`tempo`,intent:`subscription`,schema:{credential:{payload:J.object({signature:iS(),type:J.literal(`keyAuthorization`)})},request:J.pipe(J.object({amount:Xx(),accessKey:J.optional(ED),chainId:J.optional(J.number()),currency:TD,decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:J.optional(DD),periodCount:AD,periodUnit:kD,recipient:TD,subscriptionExpires:OD}).check(yD(`Subscription amount must be greater than 0`),J.refine(bD,`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:P(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}})}));function FD(e){return e>=0n&&e<=eO}function ID(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return FD(t)?t:void 0}function LD(e){return RD(e),e}function RD(e){if(!FD(e))throw Error(`Value ${e} is outside uint96 bounds.`)}function zD(e){return typeof e==`object`&&!!e}function BD(e){return typeof e==`string`&&tO.has(e)}function VD(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!BD(t.action))}function HD(e,t=`No session credential context available.`){if(!VD(e))throw Error(t);return e}function UD(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function WD(e){return zD(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function GD(e){return zD(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 KD(e){let t=re.toString(e),n=JSON.parse(t);if(!GD(n))throw Error(`Invalid session receipt.`);return n}function qD(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function JD(e){let t=`message`,n=[];for(let r of e.split(`
|
|
229
|
+
`))throw Error(`Credential header value contains illegal newline characters`)}async function ZT(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&&cT(a,r.origin),r&&rT(t,a,r),t.createCredential(a)}function QT(e,t){let n=e.get(q.acceptPayment);if(!n)return t;try{return{...t,entries:bC(n),header:n}}catch{return t}}async function $T(e,t){return t?t(e):e}function eE(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=rE(e);return t===`same-origin`?!nE()||n.origin===globalThis.location.origin:t.origins.some(e=>tE(n,e))}function tE(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 nE(){return globalThis.location!==void 0}function rE(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,nE()?globalThis.location.href:void 0)}function iE(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 aE(e,t,n,r){if(iE(t,r),!e.url)return t;let i=new URL(e.url),a=rE(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 oE,sE,cE,lE,uE,dE,fE,pE,mE,hE=I((()=>{DS(),Wx(),IS(),RS(),pC(),RC(),Jw(),eT(),mT(),yT(),Aw(),oE=Symbol.for(`mppx.fetch.wrapper`),sE=Symbol.for(`mppx.fetch.identity`),cE=Symbol.for(`mppx.fetch.skipPayment`),lE=3,uE=65536,dE=2e3,fE=`Mppx-Body-Truncated`,mE=new WeakMap}));Lx(),hE();const gE=Object.freeze([`agent-id`,`agent-signature`,`dpop`,`identity-attestation`,`identity-presentation`,`poppy-session`,`tempo-id-token`]);Object.freeze([`privatetoken`,`identity-presentation`]),Object.freeze([`identity-attestation-required`,`identity-required`]),Wx(),RS(),pC(),RC(),eT(),mT(),yT(),Jw();const _E=new WeakMap;function vE(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=qw(),trustedTempoProofRealms:c}=e;if(`attestation`in e)throw TypeError("Mppx client `attestation` was replaced by `identity: [prover]`.");let l=qT(e.fetch??globalThis.fetch),u=t?tC(t):e.fetch&&KT(e.fetch),d=e.methods.flat(),f=yC(d,e.paymentPreferences),p=TT(),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=ST(h);a&&CT(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=ME(e),a=await s.getChallenges(e,t?.request),o=Object.freeze(a.map(e=>NE(e))),l=IE(f.entries,t?.acceptPayment),u,m;try{let f=CC(a,d,l,n);f.length===0&&n===void 0&&(f=CC(a,d,l,LC));let h=(await LE(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&&LS(u.expires,u.id);let _=zE(e);_?hT(u,_,c):s.name===`mcp`&&gT(u,c&&Object.values(c));let v=u,y=m,b=DE(async e=>{try{v.expires&&LS(v.expires,v.id);let t=DE(t=>RE(v,y,t??e,_?.origin)),n=await p.emit(`challenge.received`,OE({challenge:v,challenges:a,createCredential:t,method:y,response:r}))??await t();return XT(n),await p.emit(`credential.created`,kE({challenge:v,credential:n,method:y,response:r})),n}catch(e){throw await p.emit(`payment.failed`,AE({challenge:v,challenges:a,error:e,method:y,response:r})),e}}),x=Object.freeze({challenge:v,challenges:o,createCredential:b,method:jE(y),setCredential(e,t){return XT(t),s.setCredential(e,t,{challenge:g})}});return _E.set(x,y),x}catch(e){throw await p.emit(`payment.failed`,AE({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 SE({acceptPayment:f.header,acceptPaymentPolicy:o,fetch:l,init:t,input:e,maxRedirects:r,identity:u}),p=CE(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});hT(m.challenge,new URL(d.replayRequest.url),c);let h=_E.get(m)??m.method,g=DE(async e=>(await u?.challenge(d.response,{challenge:m.challenge},d.replayRequest.url),Xw(h)&&await Zw(h,{challenge:m.challenge,context:e,fetch:u?aC(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(CE(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,headers:d.identityHeaders});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 yE=new Set([301,302,303,307,308]),bE=[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`,`transfer-encoding`],xE=[`authorization`,`cookie`,`cookie2`,`host`,`payment-authorization`,`payment-signature`,`proxy-authorization`,`x-payment`];async function SE(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 Set([...xE,...gE,...i?.headers??[]]),l=new Request(o,{...a,redirect:`manual`}),u=l.headers.has(q.acceptPayment),d=await wE(l,a?.body),f=[];for(;;){l=TE(l,t,u,n);let{request:e,response:a,headers:o}=await(async()=>{if(i)return i.send(r,l.clone());let e=l.clone();return{request:e,response:await r(e),headers:[]}})();if(a.type===`opaqueredirect`||a.status===0)throw Error(`prepareRequest requires a runtime that exposes manual redirect responses.`);if(!yE.has(a.status))return{body:d,identityHeaders:o,replayRequest:l,request:e,response:a,redirects:Object.freeze(f)};let p=a.headers.get(`location`);if(!p)return{body:d,identityHeaders:o,replayRequest:l,request:e,response:a,redirects:Object.freeze(f)};if(f.length>=s)throw await a.body?.cancel(),Error(`Payment request exceeded ${s} redirects.`);let m=new URL(l.url),h=new URL(p,m);if(m.protocol===`https:`&&h.protocol!==`https:`)throw await a.body?.cancel(),Error(`Payment request refused HTTPS downgrade redirect to ${h.href}`);let g=new Headers(l.headers),_=l.method;if((a.status===301||a.status===302)&&_===`POST`||a.status===303&&_!==`GET`&&_!==`HEAD`){_=`GET`,d=void 0;for(let e of bE)g.delete(e)}if(m.origin!==h.origin)for(let e of[...g.keys()]){let t=g.get(e)??``;(c.has(e)||t.startsWith(`Payment `))&&g.delete(e)}f.push(Object.freeze({from:m.href,status:a.status,to:h.href})),await a.body?.cancel(),l=new Request(h,EE(l,g,_,d))}}function CE(e,t){return EE(e,new Headers(e.headers),e.method,t)}async function wE(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 TE(e,t,n,r){if(n)return e;let i=new Headers(e.headers);return i.delete(q.acceptPayment),t&&eE(e,r)&&i.set(q.acceptPayment,t),new Request(e,{headers:i})}function EE(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 DE(e){let t;return n=>(t??=e(n),t)}function OE(e){return Object.freeze({challenge:NE(e.challenge),challenges:e.challenges.map(e=>NE(e)),createCredential:e.createCredential,method:jE(e.method),response:ME(e.response)})}function kE(e){return Object.freeze({challenge:NE(e.challenge),credential:e.credential,method:jE(e.method),response:ME(e.response)})}function AE(e){return Object.freeze({...e.challenge?{challenge:NE(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>NE(e))}:{},error:e.error,...e.method?{method:jE(e.method)}:{},response:ME(e.response)})}function jE(e){return FE(Object.assign({},e))}function ME(e){return e instanceof Response?e.body===null?e.clone():new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText}):NE(e)}function NE(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 PE(t)}catch{return FE(e)}}function PE(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))PE(t);return e}function FE(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function IE(e,t){return t?typeof t==`string`?bC(t):t:e}async function LE(e,t){return t?t(e):e}async function RE(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&&cT(a,r),t.createCredential(a)}function zE(e){if(typeof Response<`u`&&e instanceof Response&&e.url)return new URL(e.url)}function BE(){return J.string().check(J.regex(VE,`Invalid URI or path`))}var VE,HE,UE,WE,GE,KE,qE,JE,YE,XE=I((()=>{oS(),VE=/^([a-zA-Z][a-zA-Z\d+.-]*:\/\/\S+|\/\S*)$/,HE=new Set([`amount`,`currency`,`description`,`intent`,`method`]),UE=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())}),WE=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(UE).check(J.minLength(1)))}).check(J.refine(e=>e.offers===void 0||Object.keys(e).every(e=>e===`offers`||!HE.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`&&(HE.has(n)||r!==void 0)&&(t[n]=r);return{offers:[t]}})),GE=J.looseObject({apiReference:J.optional(BE()),homepage:J.optional(BE()),llms:J.optional(BE())}),KE=J.looseObject({categories:J.optional(J.array(J.string())),docs:J.optional(GE)}),qE=J.looseObject({"x-payment-info":J.optional(WE),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(qE),get:J.optional(qE),head:J.optional(qE),options:J.optional(qE),patch:J.optional(qE),post:J.optional(qE),put:J.optional(qE),trace:J.optional(qE)}),YE=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))})}));XE();function ZE(e){let t=[],n=YE.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=WE.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 QE=`2026-07-29.preview`;function $E(e){return e}function eD(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}var tD=I((()=>{}));function nD(e,t){return Je.resolve(e).toLowerCase()===Je.resolve(t).toLowerCase()}var rD=I((()=>{}));function iD(e){return Number.isInteger(e)&&e>0&&e<_D}function aD(e,t){return iD(t)?e===!0||(e?.includes(t)??!1):!1}function oD(e){return Ve.zonePortal(e)}function sD(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 cD(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 lD(e){return ie.keccak256(D.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function uD(e,t){let{blockNumber:n,sender:r,transactionHash:i}=t,a=t=>je(e,{abi:Re.zoneOutbox,address:Ve.zoneOutbox,blockNumber:t,functionName:`lastFallbackNonce`}),[o,s]=await Promise.all([a(n-1n),a(n)]);if(s<=o)throw Error(`Zone withdrawal transaction ${i} did not request a withdrawal from the outbox.`);if(s-o>mD)throw Error(`Zone withdrawal transaction ${i} has ${s-o} candidate sender tags, more than ${mD}.`);let c=[];for(let e=o+1n;e<=s;e++)c.push(lD({fallbackNonce:e,sender:r,transactionHash:i}));return c}async function dD(e,t){let{senderTags:n,timeoutMs:r=fD}=t;if(!Number.isFinite(r)||r<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);if(n.length===0)throw Error(`Zone settlement needs at least one sender tag.`);let i=await Oe(e,{cacheTime:0}),a=i>pD?i-pD:0n,o=Date.now()+r;for(;;){if(a<=i){let[r]=await ke(e,{address:t.portal,event:gD,args:{senderTag:[...n],...t.to?{to:t.to}:{}},fromBlock:a,toBlock:i});if(r?.transactionHash&&r.args.senderTag)return{hash:r.transactionHash,senderTag:r.args.senderTag};a=i+1n}if(Date.now()+hD>o)throw Error(`Zone withdrawal ${n.join(` or `)} did not settle on Tempo within ${r}ms.`);await new Promise(e=>setTimeout(e,hD)),i=await Oe(e,{cacheTime:0})}}var fD,pD,mD,hD,gD,_D,vD=I((()=>{fD=6e4,pD=7200n,mD=64n,hD=500,gD=de({abi:Re.zonePortal,name:`WithdrawalProcessed`}),_D=4217e5}));function yD(e){return J.refine(e=>{let{amount:t,decimals:n}=e;return P(t,n)>0n},e)}function bD(e){let{periodCount:t,periodUnit:n}=e;try{let e=wD[n];return e!==void 0&&BigInt(t)*e<=CD}catch{return!1}}var xD,SD,CD,wD,TD,ED,DD,OD,kD,AD,jD,MD,ND,PD=I((()=>{Wx(),tD(),oS(),vD(),xD=[`push`,`pull`],SD=J.object({amount:Xx(),memo:J.optional(nS()),recipient:J.pipe(J.string(),J.transform(e=>e))}),CD=(1n<<64n)-1n,wD={dev_second:1n,day:86400n,week:604800n},TD=J.pipe(tS(),J.transform(e=>e.toLowerCase())),ED=J.object({accessKeyAddress:TD,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)))}),DD=J.object({accessKey:J.optional(ED),chainId:J.optional(J.number())}),OD=Qx(`subscriptionExpires must be a valid date`).check(J.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),kD=J.enum([`dev_second`,`day`,`week`]),AD=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)<=CD}catch{return!1}},`periodCount exceeds uint64`)),jD=$E({name:`tempo`,intent:`charge`,schema:{credential:{payload:J.discriminatedUnion(`type`,[J.object({hash:nS(),type:J.literal(`hash`)}),J.object({signature:iS(),type:J.literal(`transaction`)}),J.object({signature:iS(),type:J.literal(`proof`)}),J.object({hash:nS(),senderTag:nS(),type:J.literal(`zone`),zoneId:J.number().check(J.refine(iD,`Invalid Zone ID`))})])},request:J.pipe(J.object({machineTokenEnabled:J.optional(J.boolean()),amount:Xx(),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(SD).check(J.minLength(1),J.maxLength(10))),supportedModes:J.optional(J.array(J.enum(xD)).check(J.minLength(1))),zones:J.optional(J.union([J.literal(!0),J.array(J.number().check(J.refine(iD,`Invalid Zone ID`))).check(J.minLength(1))]))}).check(J.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=P(e,t),i=n.reduce((e,n)=>e+P(n.amount,t),0n);return n.every(e=>P(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:P(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:P(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),MD=$E({name:`tempo`,intent:`session`,schema:{credential:{payload:J.discriminatedUnion(`action`,[J.object({action:J.literal(`open`),authorizedSigner:J.optional(J.string()),channelId:nS(),cumulativeAmount:Xx(),descriptor:J.optional(J.custom()),signature:iS(),transaction:iS(),type:J.literal(`transaction`)}),J.object({action:J.literal(`topUp`),additionalDeposit:Xx(),channelId:nS(),descriptor:J.optional(J.custom()),transaction:iS(),type:J.literal(`transaction`)}),J.object({action:J.literal(`voucher`),channelId:nS(),cumulativeAmount:Xx(),descriptor:J.optional(J.custom()),signature:iS()}),J.object({action:J.literal(`close`),channelId:nS(),closeSignature:iS(),cumulativeAmount:Xx(),descriptor:J.optional(J.custom()),signature:iS()})])},request:J.pipe(J.object({amount:Xx(),chainId:J.optional(J.number()),channelId:J.optional(nS()),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(tS()),minVoucherDelta:J.optional(Xx()),operator:J.optional(tS()),recipient:J.optional(J.string()),sessionProtocol:J.optional(J.enum([Ux.v2,Ux.v1])),sessionSnapshot:J.optional(J.custom()),suggestedDeposit:J.optional(Xx()),unitType:J.string()}).check(J.refine(({amount:e,decimals:t})=>P(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:P(e,r).toString(),...d?{suggestedDeposit:P(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:P(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&&{[Hx.sessionProtocol]:l},...u!==void 0&&{[Hx.sessionSnapshot]:u}}})))}}),ND=$E({name:`tempo`,intent:`subscription`,schema:{credential:{payload:J.object({signature:iS(),type:J.literal(`keyAuthorization`)})},request:J.pipe(J.object({amount:Xx(),accessKey:J.optional(ED),chainId:J.optional(J.number()),currency:TD,decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:J.optional(DD),periodCount:AD,periodUnit:kD,recipient:TD,subscriptionExpires:OD}).check(yD(`Subscription amount must be greater than 0`),J.refine(bD,`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:P(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}})}));function FD(e){return e>=0n&&e<=eO}function ID(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return FD(t)?t:void 0}function LD(e){return RD(e),e}function RD(e){if(!FD(e))throw Error(`Value ${e} is outside uint96 bounds.`)}function zD(e){return typeof e==`object`&&!!e}function BD(e){return typeof e==`string`&&tO.has(e)}function VD(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!BD(t.action))}function HD(e,t=`No session credential context available.`){if(!VD(e))throw Error(t);return e}function UD(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function WD(e){return zD(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function GD(e){return zD(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 KD(e){let t=re.toString(e),n=JSON.parse(t);if(!GD(n))throw Error(`Invalid session receipt.`);return n}function qD(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function JD(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=YD(r);return WD(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=YD(r);return GD(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function YD(e){try{return JSON.parse(e)}catch{return null}}function XD(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function ZD(){return JSON.stringify({mpp:`payment-close-request`})}function QD(e){let t=$D(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`&&GD(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`&&WD(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&GD(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function $D(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}var eO,tO,nO,rO=I((()=>{eO=(1n<<96n)-1n,tO=new Set([`open`,`topUp`,`voucher`,`close`]),nO=`0x4d50500000000000000000000000000000000000`}));function iO(e){return dO.encode(e)}function aO(e){return dO.decode(e)}var oO,sO,cO,lO,uO,dO,fO=I((()=>{Fw(),oS(),oO=J.custom(e=>typeof e==`string`&&pe(e,{strict:!1})),sO=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),cO=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),lO=J.object({authorizedSigner:oO,expiringNonceHash:sO,operator:oO,payee:oO,payer:oO,salt:sO,token:oO}),uO=J.object({acceptedCumulative:J.string(),chainId:J.number(),channelId:sO,closeRequestedAt:J.optional(J.string()),deposit:J.string(),descriptor:lO,escrow:oO,highestVoucher:J.optional(J.object({channelId:sO,cumulativeAmount:J.string(),signature:cO})),requiredCumulative:J.string(),settled:J.string(),spent:J.string(),units:J.optional(J.number())}),dO=Nw(uO)}));function pO(e){return{status:`active`,...e}}function mO(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?yO(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?yO(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:_O(e.challengeId,t.snapshot),effects:[]}:yO(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?yO(e,t):{state:jO({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:vO(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:yO(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?yO(e,t):{state:PO(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?gO({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):yO(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:yO(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?yO(e,t):{state:vO(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}]}:yO(e,t);case`settled`:return e.status===`settling`?{state:vO(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:yO(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:yO(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:yO(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?yO(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`?yO(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function hO(e,t){let n=mO(e.state,t);return e.state=n.state,n}function gO(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 _O(e,t){return pO({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function vO(e,t,n,r){return pO({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function yO(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function bO(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function xO(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`);bO({cumulativeAmount:i,maxVoucherCumulative:n}),bO({cumulativeAmount:a,maxVoucherCumulative:n})}function SO(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;xO({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function CO(e,t){return typeof e==`bigint`?e:P(e,t)}function wO(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(EO(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 TO(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;bO({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 EO(e,t){bO({cumulativeAmount:e,maxVoucherCumulative:t??null})}function DO(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 OO(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function kO(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!FD(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>OO({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function AO(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=ID(r),s=ID(a.spent);return o===void 0||s===void 0||!FD(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function jO(e){return pO({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 MO(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:BO}}function NO(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=SO({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&hO(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function PO(e,t){return pO({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function FO(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=ID(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 IO(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 mO(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function LO(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 RO(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 zO(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(ZD()),e.waitForCloseReady()))(),a=BigInt(i.spent);kO({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=>AO({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(XD(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}var BO,VO=I((()=>{rO(),fO(),BO={status:`idle`}}));function HO(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=Dk.CLOSED,r=null}if(a.type===`open`&&(i=Dk.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 UO(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function WO(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=CO(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 GO(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:PO(s,u)}:i?{channel:u,state:jO({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function KO(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=UO(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:LD(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function qO(e){return e.method===Bx.tempo&&e.intent===Vx.session}function JO(e){return qO(e)&&Rx(e.request.methodDetails,Hx.sessionProtocol)===Ux.v2}function YO(e){return Rx(e.request.methodDetails,Hx.sessionSnapshot)}function XO(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return mw({...t,redirect:`manual`,headers:{...wT(i),...wT(t?.headers)}},SS(r),n)}function ZO(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 QO(e){try{let t=typeof location>`u`?void 0:location.href,n=ZO(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function $O(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function ek(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 tk(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 nk({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 Ak&&(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?KD(i):void 0}async function nk(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(QO(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:Ek(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new Ak(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=vS(n).find(JO);return r?t(r):n}async function rk(e){let t=ik({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,XO(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(q.paymentReceipt)&&await l(),u}function ik(e){let t=vS(e.response).find(JO);if(!t)return;let n=YO(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function ak(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=ZO(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?QO(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:Ek(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=vS(o).find(JO);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await ek(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=KD(s);if(!c.txHash||!k.validate(c.txHash,{strict:!0})||k.size(c.txHash)!==32||!AO({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 ok(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...wT(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!qD(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),sk(e,c,{onReceipt:r,signal:o},n,s.headers)}function sk(e,t,n,r,i){if(!qD(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return ck({onNeedVoucher:t=>pk({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*ck(e){for await(let t of lk(e))t.data!==void 0&&(yield t.data)}async function*lk(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=uk(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=JD(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 uk(e,t){for(let n=0;n<e.length;n++){let r=dk(e,n,t);if(!r)continue;let i=dk(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function dk(e,t,n){return e[t]===`
|
|
@@ -263,7 +263,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
263
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(`
|
|
264
264
|
`)?[`
|
|
265
265
|
`]:[],s=o.length,l=!0);for(let e of a){let n=JD(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*Ez(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await jz(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=PR(e.body,i.path),!a&&r.doc&&(a=zR(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await JR(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(Az),h=p.some(e=>!Az(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 iz(t,i,{body:u,challenge:l?.[0],extraHeaders:e.headers,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults,a=await vz(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 Dz(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of Ez(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=Oz(r,n,{sawTestnet:a,sawMainnet:o});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function Oz(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(oz);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 kz=Object.values(et);function Az(e){return kz.find(t=>t.id===e)?.testnet===!0}async function jz(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await LR(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 IR(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=ZE(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=NR(t.endpoint);e&&r.push(e)}else if(i){r=RR(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=MR(t.amount)?BigInt(t.amount):e,i=MR(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}}Lx(),pA();const Mz=_b(`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||Jk()){let t=await Dz({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 Ez({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=>DR(e,n)}))switch(t.phase){case`discovery`:if(ER(`Discovery (/openapi.json)`),DR(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=oz.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++,ER(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),DR(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`)),DR(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}Nz(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function Nz(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 Pz(e){return Iz(e)?e.offers:[e]}function Fz(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=Lz(t.amount)??Lz(i.amount)??null,o=Lz(t.currency)??Lz(i.currency),s=Lz(e.description)??Lz(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 Iz(e){return`offers`in e&&!(`_canonicalRequest`in e)}function Lz(e){return typeof e==`string`?e:void 0}var Rz=I((()=>{})),zz=ot({generate:()=>Bz,generateProxy:()=>Vz});function Bz(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=>Uz(e,r));return Hz({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function Vz(e){let t=e.routes.map(t=>({...t,path:Wz(e.basePath,t.path)}));return Hz({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function Hz(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`]=WE.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 Uz(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:Pz(t).map(Fz)},...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:Kx(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:Fz(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function Wz(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var Gz=I((()=>{Jx(),XE(),Rz()}));Lx(),DS(),hE(),yT(),Mw(),Gw(),Jw(),Wx(),jk(),Uw(),_C(),pw(),DA(),pA();const Kz=`0.19.1`,qz=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),Jz=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),Yz=p.object({message:p.string(),path:p.string(),severity:p.string()}),Xz=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),Zz=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function Qz(e){return e.format===`json`&&e.formatExplicit}function $z(e,t,n){if(Qz(e))return e.ok(t);n()}async function eB(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 tB(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function nB(e){return typeof e==`string`?e:void 0}function rB(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function iB(e){let t=rB(e);return{...nB(e.description)?{description:nB(e.description)}:{},id:nB(e.id)??nB(e.name)??`unknown`,...nB(e.name)?{name:nB(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...nB(e.status)?{status:nB(e.status)}:{},...nB(e.serviceUrl)||nB(e.url)?{url:nB(e.serviceUrl)??nB(e.url)}:{}}}function aB(e){return{...nB(e.description)?{description:nB(e.description)}:{},method:nB(e.method)??`GET`,path:nB(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function oB(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=nB(t.amount),r=nB(t.currency),i=nB(t.method),a=nB(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function sB(e){return e.request.currency??e.request.asset}function cB(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=sB(e);return typeof t==`string`&&t.toLowerCase()===n})}async function lB(e,t,n={}){let r=()=>jw().getChallenges(e),i=()=>Ww().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 uB(e){return Kw({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function dB(e,t){if(!hC(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:cS(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[YC]:Bw({accepts:[WC(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function fB(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 pB(e,t,n,r){let i=t,a=fB(i),o={...n,redirect:`manual`,headers:wT(n.headers)};a.host&&gB(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=wT(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=fB(i),a.host&&gB(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 mB(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&hB(i),fB(i.href)}function hB(e){throw new L({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function gB(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function _B(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function vB(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new L({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 L({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function yB(e,t){let n=t.toLowerCase();return e.find(e=>{let t=nB(e.id)?.toLowerCase(),r=nB(e.name)?.toLowerCase();return t===n||r===n})}const bB=_b(`mppx`,{mcp:{tools:{discovery:`direct`}},version:Kz,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 UI(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=kA(),i={"User-Agent":e.options.userAgent??`mppx/${Kz}${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=BI(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=fB(o),f=d.url;d.host&&(i.Host=d.host);try{let r=qk(e.options.methodOpt),a=sL(),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 pB(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});Vk(m,c),await eB(m);return}let h=m.url?new URL(m.url):void 0,g=d.host!==void 0&&h?.hostname===`127.0.0.1`,_=await lB(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=cB(_,e.options.currency);if(e.options.currency&&v.length===0){let t=_.map(sB).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=VI(n?.config)?.length?v:await eI(v,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),b=zI(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=hC(x),T=w?void 0:mB(o,d,p.logicalUrl);if(!w)try{hT(x,new URL(p.logicalUrl||o),void 0)}catch(t){return e.error({code:`UNTRUSTED_PROOF_REALM`,message:t.message,exitCode:1})}let ee=dB(x,m),te=x.request.currency??``,ne=x.request.decimals??6,E,D;S&&(D=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}),te=D.tokenSymbol,ne=D.tokenDecimals,E=D.explorerUrl);let O=!e.options.silent&&e.options.confirm,ie=new Set;{Vk(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:te,tokenDecimals:ne,explorerUrl:E},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,Hk(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=Uk(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,Hk(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)ie.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||O){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(`
|
|
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++,ER(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),DR(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`)),DR(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}Nz(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function Nz(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 Pz(e){return Iz(e)?e.offers:[e]}function Fz(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=Lz(t.amount)??Lz(i.amount)??null,o=Lz(t.currency)??Lz(i.currency),s=Lz(e.description)??Lz(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 Iz(e){return`offers`in e&&!(`_canonicalRequest`in e)}function Lz(e){return typeof e==`string`?e:void 0}var Rz=I((()=>{})),zz=ot({generate:()=>Bz,generateProxy:()=>Vz});function Bz(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=>Uz(e,r));return Hz({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function Vz(e){let t=e.routes.map(t=>({...t,path:Wz(e.basePath,t.path)}));return Hz({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function Hz(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`]=WE.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 Uz(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:Pz(t).map(Fz)},...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:Kx(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:Fz(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function Wz(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var Gz=I((()=>{Jx(),XE(),Rz()}));Lx(),DS(),hE(),yT(),Mw(),Gw(),Jw(),Wx(),jk(),Uw(),_C(),pw(),DA(),pA();const Kz=`0.20.0`,qz=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),Jz=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),Yz=p.object({message:p.string(),path:p.string(),severity:p.string()}),Xz=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),Zz=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function Qz(e){return e.format===`json`&&e.formatExplicit}function $z(e,t,n){if(Qz(e))return e.ok(t);n()}async function eB(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 tB(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function nB(e){return typeof e==`string`?e:void 0}function rB(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function iB(e){let t=rB(e);return{...nB(e.description)?{description:nB(e.description)}:{},id:nB(e.id)??nB(e.name)??`unknown`,...nB(e.name)?{name:nB(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...nB(e.status)?{status:nB(e.status)}:{},...nB(e.serviceUrl)||nB(e.url)?{url:nB(e.serviceUrl)??nB(e.url)}:{}}}function aB(e){return{...nB(e.description)?{description:nB(e.description)}:{},method:nB(e.method)??`GET`,path:nB(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function oB(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=nB(t.amount),r=nB(t.currency),i=nB(t.method),a=nB(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function sB(e){return e.request.currency??e.request.asset}function cB(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=sB(e);return typeof t==`string`&&t.toLowerCase()===n})}async function lB(e,t,n={}){let r=()=>jw().getChallenges(e),i=()=>Ww().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 uB(e){return Kw({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function dB(e,t){if(!hC(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:cS(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[YC]:Bw({accepts:[WC(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function fB(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 pB(e,t,n,r){let i=t,a=fB(i),o={...n,redirect:`manual`,headers:wT(n.headers)};a.host&&gB(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=wT(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=fB(i),a.host&&gB(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 mB(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&hB(i),fB(i.href)}function hB(e){throw new L({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function gB(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function _B(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function vB(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new L({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 L({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function yB(e,t){let n=t.toLowerCase();return e.find(e=>{let t=nB(e.id)?.toLowerCase(),r=nB(e.name)?.toLowerCase();return t===n||r===n})}const bB=_b(`mppx`,{mcp:{tools:{discovery:`direct`}},version:Kz,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 UI(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=kA(),i={"User-Agent":e.options.userAgent??`mppx/${Kz}${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=BI(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=fB(o),f=d.url;d.host&&(i.Host=d.host);try{let r=qk(e.options.methodOpt),a=sL(),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 pB(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});Vk(m,c),await eB(m);return}let h=m.url?new URL(m.url):void 0,g=d.host!==void 0&&h?.hostname===`127.0.0.1`,_=await lB(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=cB(_,e.options.currency);if(e.options.currency&&v.length===0){let t=_.map(sB).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=VI(n?.config)?.length?v:await eI(v,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),b=zI(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=hC(x),T=w?void 0:mB(o,d,p.logicalUrl);if(!w)try{hT(x,new URL(p.logicalUrl||o),void 0)}catch(t){return e.error({code:`UNTRUSTED_PROOF_REALM`,message:t.message,exitCode:1})}let ee=dB(x,m),te=x.request.currency??``,ne=x.request.decimals??6,E,D;S&&(D=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}),te=D.tokenSymbol,ne=D.tokenDecimals,E=D.explorerUrl);let O=!e.options.silent&&e.options.confirm,ie=new Set;{Vk(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:te,tokenDecimals:ne,explorerUrl:E},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,Hk(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=Uk(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,Hk(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)ie.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||O){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(`
|
|
267
267
|
`);t(` ${X.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${l}${e}\n`)}}}if(O&&(t(`
|
|
268
268
|
`),!await Zk(`Proceed with ${x.intent}?`,!0))){t(`Aborted.
|
|
269
269
|
`);return}}let k=process.env.MPPX_PRIVATE_KEY?.trim()||!Yk(bA(e.options.account));if(qO(x)&&k&&!C){try{await cR({challenge:x,challengeResponse:ee,credentialContext:await LI(x,n?.config.extensions,D?.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 ZL(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:C&&qO(x)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let ae=C&&qO(x)?void 0:await LI(x,n?.config.extensions,D?.credentialContext),A,oe;if(C&&qO(x)){let e=ee;A=await vE({methods:[C],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await LI(e,n?.config.extensions,D?.credentialContext);return GI(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:ae,redirect:`manual`})}else{if(D?.createCredential)oe=await D.createCredential(ee,ae);else if(D)oe=await vE({methods:D.methods,polyfill:!1,transport:uB(x)}).createCredential(ee,ae);else if(C)oe=await vE({methods:[C],polyfill:!1,transport:uB(x)}).createCredential(ee,ae);else throw Error(`unreachable`);let n=w?XC:SS(x),r={...wT(p.init.headers),[n]:oe},i=w?fB((_B(x)??m.url)||o):T;w&&gB(r,i.host),S?.prepareCredentialRequest?.({challenge:x,credential:oe,headers:r});let a={...p.init,redirect:`manual`,headers:r};e.options.verbose>=2&&Bk(i.url,a,t),A=await u(i.url,a)}if(e.options.fail&&A.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${A.status}`,exitCode:22});if(A.status===402){let n=await A.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,Gk(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(Vk(A,c),!(oe&&await S?.handleResponse?.({challenge:x,credential:oe,response:A,fetchUrl:f,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:O,confirm:Zk,tokenSymbol:te,tokenDecimals:ne,explorerUrl:E,shownKeys:ie}))){let n=A.headers.get(q.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(re.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||ie.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(`(${Qk(BigInt(n),te,ne)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&E?r.push([t,Kk(`${E}/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(`
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** ERC-8004 values used by the agent identity provider. */
|
|
2
|
+
export declare const Constants: {
|
|
3
|
+
/** Identity type advertised in a 402's `Identity-Required` header. */
|
|
4
|
+
readonly type: 'erc8004';
|
|
5
|
+
/** Chain the default registry is on: Tempo mainnet. */
|
|
6
|
+
readonly chainId: 4217;
|
|
7
|
+
/** The ERC-8004 Identity Registry, at the same address on every chain that deploys it. */
|
|
8
|
+
readonly identityRegistry: '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432';
|
|
9
|
+
/** Default RPC for Tempo mainnet. */
|
|
10
|
+
readonly rpcUrl: 'https://rpc.tempo.xyz';
|
|
11
|
+
/** Carries the agent's ID: `eip155:<chainId>:<registry>:<agentId>`. */
|
|
12
|
+
readonly idHeader: 'Agent-Id';
|
|
13
|
+
/** Carries `<created>.<nonce>.<signature>`: the agent wallet's signature of the request. */
|
|
14
|
+
readonly signatureHeader: 'Agent-Signature';
|
|
15
|
+
/** How long, in seconds, a request signature stays valid. */
|
|
16
|
+
readonly maxAge: 300;
|
|
17
|
+
/** Allowed clock skew, in seconds. */
|
|
18
|
+
readonly clockTolerance: 60;
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=Constants.d.ts.map
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** ERC-8004 values used by the agent identity provider. */
|
|
2
|
+
export const Constants = {
|
|
3
|
+
/** Identity type advertised in a 402's `Identity-Required` header. */
|
|
4
|
+
type: 'erc8004',
|
|
5
|
+
/** Chain the default registry is on: Tempo mainnet. */
|
|
6
|
+
chainId: 4217,
|
|
7
|
+
/** The ERC-8004 Identity Registry, at the same address on every chain that deploys it. */
|
|
8
|
+
identityRegistry: '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432',
|
|
9
|
+
/** Default RPC for Tempo mainnet. */
|
|
10
|
+
rpcUrl: 'https://rpc.tempo.xyz',
|
|
11
|
+
/** Carries the agent's ID: `eip155:<chainId>:<registry>:<agentId>`. */
|
|
12
|
+
idHeader: 'Agent-Id',
|
|
13
|
+
/** Carries `<created>.<nonce>.<signature>`: the agent wallet's signature of the request. */
|
|
14
|
+
signatureHeader: 'Agent-Signature',
|
|
15
|
+
/** How long, in seconds, a request signature stays valid. */
|
|
16
|
+
maxAge: 300,
|
|
17
|
+
/** Allowed clock skew, in seconds. */
|
|
18
|
+
clockTolerance: 60,
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=Constants.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Address } from 'viem';
|
|
2
|
+
/** An ERC-8004 agent whose wallet signed the request or paid. */
|
|
3
|
+
export type Agent = {
|
|
4
|
+
/** The agent's global ID: `eip155:<chainId>:<registry>:<agentId>`. */
|
|
5
|
+
readonly id: string;
|
|
6
|
+
/** The agent's token ID in the Identity Registry. */
|
|
7
|
+
readonly agentId: bigint;
|
|
8
|
+
/** The agent's wallet, from the registry's `getAgentWallet`, checksummed. */
|
|
9
|
+
readonly wallet: Address;
|
|
10
|
+
};
|
|
11
|
+
//# sourceMappingURL=Types.d.ts.map
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Address, Hex } from 'viem';
|
|
2
|
+
import type * as Identity from '../../../../identity/Types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Creates a prover that signs each request as an ERC-8004 agent, with the agent's wallet.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```ts
|
|
8
|
+
* const mppx = Mppx.create({
|
|
9
|
+
* identity: [Erc8004.Client.prover({ account, agentId: 42n, scope: ['https://api.example'] })],
|
|
10
|
+
* methods: [tempo({ account })],
|
|
11
|
+
* })
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export declare function prover(config: prover.Config): Identity.Prover;
|
|
15
|
+
export declare namespace prover {
|
|
16
|
+
type Config = {
|
|
17
|
+
/** The agent's wallet, such as a viem `privateKeyToAccount` account. It also pays. */
|
|
18
|
+
readonly account: {
|
|
19
|
+
readonly signMessage: (parameters: {
|
|
20
|
+
message: string;
|
|
21
|
+
}) => Promise<Hex>;
|
|
22
|
+
};
|
|
23
|
+
/** The agent's token ID in the Identity Registry. */
|
|
24
|
+
readonly agentId: bigint | number;
|
|
25
|
+
/** Origins that receive the agent's signature, or `'*'` for any origin. */
|
|
26
|
+
readonly scope: Identity.Prover['scope'];
|
|
27
|
+
/** The registry's chain. @default 4217 (Tempo mainnet) */
|
|
28
|
+
readonly chainId?: number | undefined;
|
|
29
|
+
/** The Identity Registry. @default '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432' */
|
|
30
|
+
readonly registry?: Address | undefined;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { Constants } from '../Constants.js';
|
|
2
|
+
import * as Agent from '../internal/Agent.js';
|
|
3
|
+
/**
|
|
4
|
+
* Creates a prover that signs each request as an ERC-8004 agent, with the agent's wallet.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```ts
|
|
8
|
+
* const mppx = Mppx.create({
|
|
9
|
+
* identity: [Erc8004.Client.prover({ account, agentId: 42n, scope: ['https://api.example'] })],
|
|
10
|
+
* methods: [tempo({ account })],
|
|
11
|
+
* })
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export function prover(config) {
|
|
15
|
+
const id = Agent.format({
|
|
16
|
+
agentId: BigInt(config.agentId),
|
|
17
|
+
chainId: config.chainId ?? Constants.chainId,
|
|
18
|
+
registry: config.registry ?? Constants.identityRegistry,
|
|
19
|
+
});
|
|
20
|
+
return {
|
|
21
|
+
scope: config.scope,
|
|
22
|
+
async prove(request, { created, nonce }) {
|
|
23
|
+
const signature = await config.account.signMessage({
|
|
24
|
+
message: Agent.message({ created, id, nonce, request }),
|
|
25
|
+
});
|
|
26
|
+
const headers = new Headers(request.headers);
|
|
27
|
+
headers.set(Constants.idHeader, id);
|
|
28
|
+
headers.set(Constants.signatureHeader, `${created}.${nonce}.${signature}`);
|
|
29
|
+
return new Request(request, { headers });
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type Address } from 'viem';
|
|
2
|
+
/** Formats an agent's global ID: `eip155:<chainId>:<registry>:<agentId>`. */
|
|
3
|
+
export declare function format(agent: {
|
|
4
|
+
chainId: number;
|
|
5
|
+
registry: Address;
|
|
6
|
+
agentId: bigint;
|
|
7
|
+
}): string;
|
|
8
|
+
/** Parses an agent's global ID, or returns `undefined` when it is malformed. */
|
|
9
|
+
export declare function parse(value: string): {
|
|
10
|
+
chainId: number;
|
|
11
|
+
registry: `0x${string}`;
|
|
12
|
+
agentId: bigint;
|
|
13
|
+
} | undefined;
|
|
14
|
+
/** The message an agent's wallet signs (EIP-191) for one request attempt. */
|
|
15
|
+
export declare function message(parameters: {
|
|
16
|
+
id: string;
|
|
17
|
+
request: Request;
|
|
18
|
+
created: number;
|
|
19
|
+
nonce: string;
|
|
20
|
+
}): string;
|
|
21
|
+
//# sourceMappingURL=Agent.d.ts.map
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { getAddress, isAddress } from 'viem';
|
|
2
|
+
/** Formats an agent's global ID: `eip155:<chainId>:<registry>:<agentId>`. */
|
|
3
|
+
export function format(agent) {
|
|
4
|
+
return `eip155:${agent.chainId}:${getAddress(agent.registry)}:${agent.agentId}`;
|
|
5
|
+
}
|
|
6
|
+
/** Parses an agent's global ID, or returns `undefined` when it is malformed. */
|
|
7
|
+
export function parse(value) {
|
|
8
|
+
const [, chainId, registry, agentId] = /^eip155:(\d{1,15}):(0x[0-9a-fA-F]{40}):(\d{1,78})$/.exec(value) ?? [];
|
|
9
|
+
if (!chainId || !registry || !agentId || !isAddress(registry, { strict: false }))
|
|
10
|
+
return undefined;
|
|
11
|
+
return { chainId: Number(chainId), registry: getAddress(registry), agentId: BigInt(agentId) };
|
|
12
|
+
}
|
|
13
|
+
/** The message an agent's wallet signs (EIP-191) for one request attempt. */
|
|
14
|
+
export function message(parameters) {
|
|
15
|
+
const url = new URL(parameters.request.url);
|
|
16
|
+
return [
|
|
17
|
+
'mppx:erc8004',
|
|
18
|
+
parameters.id,
|
|
19
|
+
`${parameters.request.method} ${url.origin}${url.pathname}${url.search}`,
|
|
20
|
+
parameters.created,
|
|
21
|
+
parameters.nonce,
|
|
22
|
+
].join('\n');
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=Agent.js.map
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type Address, type Client } from 'viem';
|
|
2
|
+
import type * as Identity from '../../../../identity/Types.js';
|
|
3
|
+
import * as Store from '../../../../Store.js';
|
|
4
|
+
import type * as Types from '../Types.js';
|
|
5
|
+
/**
|
|
6
|
+
* Creates an ERC-8004 agent verifier for one API.
|
|
7
|
+
*
|
|
8
|
+
* - `verifier` requires a request signed by the agent's wallet, as the Identity Registry's
|
|
9
|
+
* `getAgentWallet` names it: an EOA signature, or ERC-1271 for a contract or configurable account.
|
|
10
|
+
* - `paymentCheck` accepts a `tempo` charge the agent's wallet signed (a transaction or proof), so
|
|
11
|
+
* the payment itself proves the agent. For anything else (no Credential, transaction hashes,
|
|
12
|
+
* sessions, Zones, other methods) it requires the signature.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* const agents = Erc8004.Server.create({ store })
|
|
17
|
+
* mppx.charge({ amount: '0.01', identity: { request: [agents.verifier], payment: agents.paymentCheck } })
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export declare function create(config?: create.Config): Erc8004;
|
|
21
|
+
export declare namespace create {
|
|
22
|
+
type Config = {
|
|
23
|
+
/** Decides whether a verified agent may call the API, such as by its ID or reputation. */
|
|
24
|
+
readonly allow?: ((agent: Types.Agent) => boolean | Promise<boolean>) | undefined;
|
|
25
|
+
/** The registry's chain. Payments must settle on it too. @default 4217 (Tempo mainnet) */
|
|
26
|
+
readonly chainId?: number | undefined;
|
|
27
|
+
/** A viem client for the registry's chain. @default an HTTP client for `rpcUrl` */
|
|
28
|
+
readonly client?: Client | undefined;
|
|
29
|
+
/** The Identity Registry. @default '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432' */
|
|
30
|
+
readonly registry?: Address | undefined;
|
|
31
|
+
/** RPC URL of the registry's chain. @default 'https://rpc.tempo.xyz' */
|
|
32
|
+
readonly rpcUrl?: string | undefined;
|
|
33
|
+
/** Accepts each request signature once. Without it, a signature can be replayed for six minutes. */
|
|
34
|
+
readonly store?: Store.AtomicStore | undefined;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** An ERC-8004 agent verifier from {@link create}. */
|
|
38
|
+
export type Erc8004 = {
|
|
39
|
+
/** A request-stage verifier: requires a request signed by the agent's wallet, before any 402. */
|
|
40
|
+
readonly verifier: Identity.Verifier<Types.Agent>;
|
|
41
|
+
/** A payment check: requires that the agent's wallet paid. */
|
|
42
|
+
readonly paymentCheck: Identity.PaymentCheck<Types.Agent>;
|
|
43
|
+
};
|
|
44
|
+
//# sourceMappingURL=index.d.ts.map
|