mppx 0.9.1 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +7 -0
  3. package/dist/cli/cli.d.ts +1 -0
  4. package/dist/cli/cli.js +36 -36
  5. package/dist/cli/internal.js +2 -2
  6. package/dist/cli/plugins/evm.js +2 -0
  7. package/dist/cli/plugins/index.d.ts +1 -0
  8. package/dist/cli/plugins/index.js +3 -3
  9. package/dist/cli/plugins/x402.d.ts +3 -0
  10. package/dist/cli/plugins/x402.js +61 -0
  11. package/dist/middlewares/internal/mppx.js +17 -3
  12. package/dist/stripe/Methods.d.ts +20 -2
  13. package/dist/stripe/client/Charge.d.ts +20 -2
  14. package/dist/stripe/client/Methods.d.ts +20 -2
  15. package/dist/stripe/internal/constants.d.ts +4 -0
  16. package/dist/stripe/internal/constants.js +2 -0
  17. package/dist/stripe/internal/payment-intent.d.ts +10 -1
  18. package/dist/stripe/internal/payment-intent.js +8 -1
  19. package/dist/stripe/internal/types.d.ts +4 -0
  20. package/dist/stripe/server/Charge.d.ts +20 -2
  21. package/dist/stripe/server/Charge.js +27 -11
  22. package/dist/stripe/server/Methods.d.ts +6 -0
  23. package/dist/stripe/server/Methods.js +19 -2
  24. package/dist/stripe/server/internal/hosted-fee-payer.d.ts +10 -0
  25. package/dist/stripe/server/internal/hosted-fee-payer.js +54 -0
  26. package/dist/stripe/server/internal/html.gen.d.ts +1 -1
  27. package/dist/stripe/server/internal/html.gen.js +1 -1
  28. package/dist/stripe/server/internal/record-payment.d.ts +3 -1
  29. package/dist/stripe/server/internal/record-payment.js +33 -5
  30. package/dist/tempo/internal/account.d.ts +1 -0
  31. package/dist/tempo/internal/remote-fee-payer.d.ts +2 -0
  32. package/dist/tempo/server/internal/html.gen.d.ts +1 -1
  33. package/dist/tempo/server/internal/html.gen.js +1 -1
  34. package/dist/viem/Client.js +1 -0
  35. package/package.json +1 -1
package/dist/cli/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import*as e from"node:fs";import t,{existsSync as n,mkdirSync as r,readFileSync as i,writeFileSync as a}from"node:fs";import{createRequire as o}from"node:module";import*as s from"node:path";import c,{dirname as l,join as u}from"node:path";import{z as d,z as f}from"zod";import*as p from"node:child_process";import{execFile as m}from"node:child_process";import{createHash as h,randomUUID as g}from"node:crypto";import*as _ from"node:util";import*as v from"node:zlib";import*as y from"node:os";import b,{homedir as x}from"node:os";import*as S from"node:fs/promises";import C from"node:fs/promises";import{PassThrough as w}from"node:stream";import{fileURLToPath as T,pathToFileURL as ee}from"node:url";import*as E from"zod/v4";import{AbiParameters as D,Base64 as O,Bytes as k,Hash as A,Hex as j,Json as te,Signature as M}from"ox";import{createClient as ne,createTransport as re,custom as ie,encodeFunctionData as ae,erc20Abi as oe,formatUnits as se,getAbiItem as N,getAddress as ce,hashTypedData as le,http as ue,isAddress as de,isAddressEqual as fe,parseUnits as P}from"viem";import{generatePrivateKey as pe,parseAccount as me,privateKeyToAccount as he}from"viem/accounts";import{tempo as ge,tempoModerato as _e}from"viem/tempo/chains";import{z as ve}from"zod/mini";import{createParser as ye}from"eventsource-parser";import*as be from"node:readline";import{prepareTransactionRequest as F,readContract as xe,sendCallsSync as Se,sendTransactionSync as Ce,signTransaction as we,signTypedData as Te,waitForTransactionReceipt as Ee}from"viem/actions";import{Abis as De,Account as Oe,Actions as ke,Addresses as Ae,TokenId as je,Transaction as Me,withFeePayer as Ne}from"viem/tempo";import*as Pe from"viem/chains";import{tempo as Fe}from"viem/chains";import{Channel as Ie,KeyAuthorization as Le,SignatureEnvelope as Re,TempoAddress as ze,TxEnvelopeTempo as Be}from"ox/tempo";import{defineToken as Ve}from"viem/tokens";var He=Object.defineProperty,Ue=Object.getOwnPropertyDescriptor,We=Object.getOwnPropertyNames,Ge=Object.prototype.hasOwnProperty,I=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},Ke=(e,t)=>{let n={};for(var r in e)He(n,r,{get:e[r],enumerable:!0});return t||He(n,Symbol.toStringTag,{value:`Module`}),n},qe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=We(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ge.call(e,s)&&s!==n&&He(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ue(t,s))||r.enumerable});return e},Je=(e,t,n)=>(qe(e,t,`default`),n&&qe(n,t,`default`));function Ye(){let t=process.env.npm_config_user_agent??``,n=process.env.npm_execpath??``,r=(()=>{if(!process.argv[1])return``;try{return e.realpathSync(process.argv[1])}catch{return process.argv[1]}})();return t.includes(`pnpm`)?`pnpm`:t.includes(`bun`)?`bun`:t.startsWith(`npm/`)?`npm`:n.includes(`pnpm`)?`pnpm`:n.includes(`bun`)?`bun`:n.includes(`npm`)?`npm`:r.includes(`/.pnpm/`)||r.includes(`\\.pnpm\\`)?`pnpm`:r.includes(`/.bun/`)||r.includes(`\\bun\\`)?`bun`:`npm`}function Xe(){let e=Ye();return e===`pnpm`?`pnpx`:e===`bun`?`bunx`:`npx`}function Ze(e){let t=Ye();return t===`pnpm`?{args:[`add`,`--global`,`${e}@latest`],command:`pnpm`}:t===`bun`?{args:[`add`,`--global`,`${e}@latest`],command:`bun`}:{args:[`install`,`--global`,`${e}@latest`],command:`npm`}}var Qe=I((()=>{}));function $e(e,t={}){if(ht())return;let n=rt(e,t);if(!n?.check||!n.current)return;let r=lt(n.key),i=ut(r),a=Date.now(),o=Math.max(0,t.interval??gt);if((!i||a-i.checkedAt>=o)&&ft(r,a,i?.latest,t.binary),!(!i?.latest||!nt(i.latest,n.current)))return{current:n.current,latest:i.latest,name:n.name}}async function et(e,t={}){let n=rt(e,t);if(!n?.check||!n.current)return;let r=await n.check({current:n.current,name:e,...n.package?{package:n.package}:void 0});!r||!st(r)||dt(lt(n.key),{checkedAt:Date.now(),latest:r})}async function tt(e,t={}){let n=rt(e,t);if(!n?.install)throw Error(`No update installer is configured for '${e}'.`);let r=ut(lt(n.key));return await n.install({...n.current?{current:n.current}:void 0,...r?.latest?{latest:r.latest}:void 0,name:e,...n.package?{package:n.package}:void 0}),{...n.command?{command:n.command}:void 0,...n.deferred?{deferred:!0}:void 0,name:n.name}}function nt(e,t){let n=st(e),r=st(t);if(!n||!r)return!1;for(let e of[`major`,`minor`,`patch`]){if(n[e]>r[e])return!0;if(n[e]<r[e])return!1}let i=n.prerelease,a=r.prerelease;if(i.length===0)return a.length>0;if(a.length===0)return!1;let o=Math.max(i.length,a.length);for(let e=0;e<o;e++){let t=i[e],n=a[e];if(t===void 0)return!1;if(n===void 0)return!0;if(t!==n)return typeof t==`bigint`&&typeof n==`string`?!1:typeof t==`string`&&typeof n==`bigint`||t>n}return!1}function rt(e,t){let n=it(e),r=t.package??n?.name;if(r&&!ct(r))return;let i=t.version??n?.version,a=r?Ze(r):void 0,o=t.check??(r?()=>ot(r):void 0),s=t.install??(a?()=>mt(a.command,a.args):void 0);if(!(!o&&!s))return{...o?{check:o}:void 0,...a&&!t.install?{command:`${a.command} ${a.args.join(` `)}`}:void 0,...i?{current:i}:void 0,...t.deferred?{deferred:!0}:void 0,...s?{install:s}:void 0,key:r??e,name:r??e,...r?{package:r}:void 0}}function it(t){let n=(()=>{if(process.argv[1])try{return e.realpathSync(process.argv[1])}catch{return}})();if(!n)return;let r=s.dirname(n);for(;;){try{let n=JSON.parse(e.readFileSync(s.join(r,`package.json`),`utf8`));if(typeof n.name==`string`&&typeof n.version==`string`&&at(n,t))return{name:n.name,version:n.version}}catch{}let n=s.dirname(r);if(n===r)return;r=n}}function at(e,t){return e.name===t||typeof e.bin==`object`&&e.bin!==null&&t in e.bin?!0:typeof e.bin!=`string`||typeof e.name!=`string`?!1:e.name.split(`/`).pop()===t}async function ot(e){let t=process.env.npm_config_registry||`https://registry.npmjs.org`,n=t.endsWith(`/`)?t:`${t}/`,r=await fetch(new URL(encodeURIComponent(e),n),{headers:{accept:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`},signal:AbortSignal.timeout(1e4)});if(!r.ok)return;let i=(await r.json())[`dist-tags`]?.latest;return typeof i==`string`?i:void 0}function st(e){let t=e.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);if(!t)return;let n=[];for(let e of t[4]?.split(`.`)??[]){if(!/^\d+$/.test(e)){n.push(e);continue}if(e.length>1&&e.startsWith(`0`))return;n.push(BigInt(e))}return{major:BigInt(t[1]),minor:BigInt(t[2]),patch:BigInt(t[3]),prerelease:n}}function ct(e){return/^(?:@[A-Za-z0-9][A-Za-z0-9._~-]*\/)?[A-Za-z0-9][A-Za-z0-9._~-]*$/.test(e)}function lt(e){let t=process.env.XDG_CACHE_HOME||s.join(y.homedir(),`.cache`);return s.join(t,`incur`,`updates`,`${encodeURIComponent(e)}.json`)}function ut(t){try{let n=JSON.parse(e.readFileSync(t,`utf8`));return typeof n.checkedAt!=`number`||n.latest!==void 0&&typeof n.latest!=`string`?void 0:n}catch{return}}function dt(t,n){e.mkdirSync(s.dirname(t),{recursive:!0}),e.writeFileSync(t,JSON.stringify(n)+`
1
+ import*as e from"node:fs";import t,{existsSync as n,mkdirSync as r,readFileSync as i,writeFileSync as a}from"node:fs";import{createRequire as o}from"node:module";import*as s from"node:path";import c,{dirname as l,join as u}from"node:path";import{z as d,z as f}from"zod";import*as p from"node:child_process";import{execFile as m}from"node:child_process";import{createHash as h,randomUUID as g}from"node:crypto";import*as _ from"node:util";import*as v from"node:zlib";import*as y from"node:os";import b,{homedir as x}from"node:os";import*as S from"node:fs/promises";import C from"node:fs/promises";import{PassThrough as w}from"node:stream";import{fileURLToPath as T,pathToFileURL as ee}from"node:url";import*as E from"zod/v4";import{AbiParameters as D,Base64 as O,Bytes as k,Hash as te,Hex as A,Json as ne,Signature as j}from"ox";import{createClient as M,createTransport as re,custom as ie,encodeFunctionData as ae,erc20Abi as oe,formatUnits as se,getAbiItem as N,getAddress as ce,hashTypedData as le,http as ue,isAddress as de,isAddressEqual as fe,parseUnits as P}from"viem";import{generatePrivateKey as pe,parseAccount as me,privateKeyToAccount as he}from"viem/accounts";import{tempo as ge,tempoModerato as _e}from"viem/tempo/chains";import{z as ve}from"zod/mini";import{createParser as ye}from"eventsource-parser";import*as be from"node:readline";import{prepareTransactionRequest as F,readContract as xe,sendCallsSync as Se,sendTransactionSync as Ce,signTransaction as we,signTypedData as Te,waitForTransactionReceipt as Ee}from"viem/actions";import{Abis as De,Account as Oe,Actions as ke,Addresses as Ae,TokenId as je,Transaction as Me,withFeePayer as Ne}from"viem/tempo";import*as Pe from"viem/chains";import{tempo as Fe}from"viem/chains";import{Channel as Ie,KeyAuthorization as Le,SignatureEnvelope as Re,TempoAddress as ze,TxEnvelopeTempo as Be}from"ox/tempo";import{defineToken as Ve}from"viem/tokens";var He=Object.defineProperty,Ue=Object.getOwnPropertyDescriptor,We=Object.getOwnPropertyNames,Ge=Object.prototype.hasOwnProperty,I=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},Ke=(e,t)=>{let n={};for(var r in e)He(n,r,{get:e[r],enumerable:!0});return t||He(n,Symbol.toStringTag,{value:`Module`}),n},qe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=We(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ge.call(e,s)&&s!==n&&He(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ue(t,s))||r.enumerable});return e},Je=(e,t,n)=>(qe(e,t,`default`),n&&qe(n,t,`default`));function Ye(){let t=process.env.npm_config_user_agent??``,n=process.env.npm_execpath??``,r=(()=>{if(!process.argv[1])return``;try{return e.realpathSync(process.argv[1])}catch{return process.argv[1]}})();return t.includes(`pnpm`)?`pnpm`:t.includes(`bun`)?`bun`:t.startsWith(`npm/`)?`npm`:n.includes(`pnpm`)?`pnpm`:n.includes(`bun`)?`bun`:n.includes(`npm`)?`npm`:r.includes(`/.pnpm/`)||r.includes(`\\.pnpm\\`)?`pnpm`:r.includes(`/.bun/`)||r.includes(`\\bun\\`)?`bun`:`npm`}function Xe(){let e=Ye();return e===`pnpm`?`pnpx`:e===`bun`?`bunx`:`npx`}function Ze(e){let t=Ye();return t===`pnpm`?{args:[`add`,`--global`,`${e}@latest`],command:`pnpm`}:t===`bun`?{args:[`add`,`--global`,`${e}@latest`],command:`bun`}:{args:[`install`,`--global`,`${e}@latest`],command:`npm`}}var Qe=I((()=>{}));function $e(e,t={}){if(ht())return;let n=rt(e,t);if(!n?.check||!n.current)return;let r=lt(n.key),i=ut(r),a=Date.now(),o=Math.max(0,t.interval??gt);if((!i||a-i.checkedAt>=o)&&ft(r,a,i?.latest,t.binary),!(!i?.latest||!nt(i.latest,n.current)))return{current:n.current,latest:i.latest,name:n.name}}async function et(e,t={}){let n=rt(e,t);if(!n?.check||!n.current)return;let r=await n.check({current:n.current,name:e,...n.package?{package:n.package}:void 0});!r||!st(r)||dt(lt(n.key),{checkedAt:Date.now(),latest:r})}async function tt(e,t={}){let n=rt(e,t);if(!n?.install)throw Error(`No update installer is configured for '${e}'.`);let r=ut(lt(n.key));return await n.install({...n.current?{current:n.current}:void 0,...r?.latest?{latest:r.latest}:void 0,name:e,...n.package?{package:n.package}:void 0}),{...n.command?{command:n.command}:void 0,...n.deferred?{deferred:!0}:void 0,name:n.name}}function nt(e,t){let n=st(e),r=st(t);if(!n||!r)return!1;for(let e of[`major`,`minor`,`patch`]){if(n[e]>r[e])return!0;if(n[e]<r[e])return!1}let i=n.prerelease,a=r.prerelease;if(i.length===0)return a.length>0;if(a.length===0)return!1;let o=Math.max(i.length,a.length);for(let e=0;e<o;e++){let t=i[e],n=a[e];if(t===void 0)return!1;if(n===void 0)return!0;if(t!==n)return typeof t==`bigint`&&typeof n==`string`?!1:typeof t==`string`&&typeof n==`bigint`||t>n}return!1}function rt(e,t){let n=it(e),r=t.package??n?.name;if(r&&!ct(r))return;let i=t.version??n?.version,a=r?Ze(r):void 0,o=t.check??(r?()=>ot(r):void 0),s=t.install??(a?()=>mt(a.command,a.args):void 0);if(!(!o&&!s))return{...o?{check:o}:void 0,...a&&!t.install?{command:`${a.command} ${a.args.join(` `)}`}:void 0,...i?{current:i}:void 0,...t.deferred?{deferred:!0}:void 0,...s?{install:s}:void 0,key:r??e,name:r??e,...r?{package:r}:void 0}}function it(t){let n=(()=>{if(process.argv[1])try{return e.realpathSync(process.argv[1])}catch{return}})();if(!n)return;let r=s.dirname(n);for(;;){try{let n=JSON.parse(e.readFileSync(s.join(r,`package.json`),`utf8`));if(typeof n.name==`string`&&typeof n.version==`string`&&at(n,t))return{name:n.name,version:n.version}}catch{}let n=s.dirname(r);if(n===r)return;r=n}}function at(e,t){return e.name===t||typeof e.bin==`object`&&e.bin!==null&&t in e.bin?!0:typeof e.bin!=`string`||typeof e.name!=`string`?!1:e.name.split(`/`).pop()===t}async function ot(e){let t=process.env.npm_config_registry||`https://registry.npmjs.org`,n=t.endsWith(`/`)?t:`${t}/`,r=await fetch(new URL(encodeURIComponent(e),n),{headers:{accept:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`},signal:AbortSignal.timeout(1e4)});if(!r.ok)return;let i=(await r.json())[`dist-tags`]?.latest;return typeof i==`string`?i:void 0}function st(e){let t=e.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);if(!t)return;let n=[];for(let e of t[4]?.split(`.`)??[]){if(!/^\d+$/.test(e)){n.push(e);continue}if(e.length>1&&e.startsWith(`0`))return;n.push(BigInt(e))}return{major:BigInt(t[1]),minor:BigInt(t[2]),patch:BigInt(t[3]),prerelease:n}}function ct(e){return/^(?:@[A-Za-z0-9][A-Za-z0-9._~-]*\/)?[A-Za-z0-9][A-Za-z0-9._~-]*$/.test(e)}function lt(e){let t=process.env.XDG_CACHE_HOME||s.join(y.homedir(),`.cache`);return s.join(t,`incur`,`updates`,`${encodeURIComponent(e)}.json`)}function ut(t){try{let n=JSON.parse(e.readFileSync(t,`utf8`));return typeof n.checkedAt!=`number`||n.latest!==void 0&&typeof n.latest!=`string`?void 0:n}catch{return}}function dt(t,n){e.mkdirSync(s.dirname(t),{recursive:!0}),e.writeFileSync(t,JSON.stringify(n)+`
2
2
  `)}function ft(e,t,n,r){let i=pt(r);if(i)try{dt(e,{checkedAt:t,...n?{latest:n}:void 0});let r=p.spawn(i.command,i.args,{detached:!0,stdio:`ignore`});r.once(`error`,()=>{}),r.unref()}catch{}}function pt(t){if(t)return{args:[_t],command:process.execPath};let n=process.argv[1];if(n){if(n.startsWith(`/$bunfs/`))return{args:[_t],command:process.execPath};try{if(e.realpathSync(n)===e.realpathSync(process.execPath))return{args:[_t],command:process.execPath}}catch{}return{args:[...process.execArgv,n,_t],command:process.execPath}}}function mt(e,t){return new Promise((n,r)=>{p.execFile(e,t,(e,t,i)=>{if(!e)return n();r(Error(i.trim()||t.trim()||e.message))})})}function ht(){return process.env.NO_UPDATE_NOTIFIER||process.env.npm_config_update_notifier===`false`?!0:!!(process.env.CI&&process.env.CI!==`false`)}var gt,_t,vt=I((()=>{Qe(),gt=864e5,_t=`--incur-update-check`}));async function yt(e=process.argv.slice(2)){if(e[0]!==`--incur-binary-apply`)return process.platform===`win32`&&jt&&Mt&&Nt&&await Tt(process.execPath),!1;if(process.platform!==`win32`)throw Error(`${At} is only supported on Windows.`);if(e.length!==2||!e[1])throw Error(`Invalid ${At} arguments.`);let t=Number(e[1]);if(!Number.isSafeInteger(t)||t<=0)throw Error(`Invalid ${At} arguments.`);return await bt(t),!0}async function bt(t){let n=xt(process.execPath,t),r=!1;try{await St(t),await e.promises.rename(n.target,n.backup),r=!0,await e.promises.rename(n.staged,n.target)}catch(t){let i=t,a=`The installed executable remains at '${n.target}'.`;if(r)try{await e.promises.rename(n.backup,n.target),r=!1,a=`The previous executable was restored to '${n.target}'.`}catch(t){try{await e.promises.copyFile(n.backup,n.target,e.constants.COPYFILE_EXCL),a=`The previous executable was copied back to '${n.target}', and its backup remains at '${n.backup}'.`}catch(e){i=Error(`Binary update failed and '${n.target}' could not be restored. The previous executable remains at '${n.backup}': ${Ot(e)}`,{cause:t})}}throw await Et(n,i,a),i}await Dt(n.backup),await Dt(n.error),await Dt(n.staged),await Dt(n.helper)}function xt(e,t){let n=s.resolve(e),r=n.match(/^(.*)\.incur-handoff-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.exe$/i);if(!r?.[1]||!r[2])throw Error(`Invalid binary update handoff path.`);let i=r[1],a=i.toLowerCase().endsWith(`.exe`)?`.exe`:``;return{backup:`${i}.incur-backup-${r[2]}${a}`,error:`${i}.incur-error-${r[2]}.txt`,helper:n,parent:t,staged:`${i}.incur-new-${r[2]}${a}`,target:i}}async function St(e){let t=Date.now()+kt;for(;Ct(e);){if(Date.now()>=t)throw Error(`Timed out waiting for update process ${e} to exit.`);await wt(100)}}function Ct(e){try{return process.kill(e,0),!0}catch(e){return e.code!==`ESRCH`}}function wt(e){return new Promise(t=>setTimeout(t,e))}async function Tt(t){let n=s.dirname(t),r=`${s.basename(t)}.incur-handoff-`;try{let t=await e.promises.readdir(n);await Promise.all(t.filter(e=>e.startsWith(r)&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.exe$/i.test(e.slice(r.length))).map(e=>Dt(s.join(n,e))))}catch{}}async function Et(t,n,r){let i=[`Binary update failed: ${Ot(n)}`,`Recovery: ${r}`,`Downloaded candidate: ${t.staged}`,`Previous executable backup: ${t.backup}`].join(`
3
3
  `);try{await e.promises.writeFile(t.error,`${i}\n`,{flag:`wx`,mode:384})}catch{}}async function Dt(t){try{await e.promises.unlink(t)}catch{}}function Ot(e){return e instanceof Error?e.message:String(e)}var kt,At,jt,Mt,Nt,Pt=I((()=>{kt=6e4,_.promisify(v.gunzip),At=`--incur-binary-apply`,jt=typeof __INCUR_BINARY_NAME__==`string`&&__INCUR_BINARY_NAME__?__INCUR_BINARY_NAME__:void 0,Mt=typeof __INCUR_BINARY_TARGET__==`string`&&__INCUR_BINARY_TARGET__?__INCUR_BINARY_TARGET__:void 0,Nt=typeof __INCUR_BINARY_VERSION__==`string`&&__INCUR_BINARY_VERSION__?__INCUR_BINARY_VERSION__:void 0}));function*Ft(e,t={}){if(!e)return;let n=It(t);for(let t of e.split(Gt))t&&(yield{segment:t,tokenCount:Lt(t,n)})}function It(e){return{defaultCharsPerToken:e.defaultCharsPerToken??Kt,languageConfigs:e.languageConfigs??Yt}}function Lt(e,{languageConfigs:t,defaultCharsPerToken:n}){if(Wt.whitespace.test(e))return+!!Wt.structuredWhitespace.test(e);let r=Rt(e,t);return r===void 0?Wt.cjk.test(e)?Bt(e):Wt.numeric.test(e)?Math.ceil(e.length/3):e.length<=qt?1:Wt.punctuation.test(e)?Math.ceil(e.length/2):Math.ceil(e.length/n):Math.ceil(zt(e)/r)}function Rt(e,t){for(let n of t)if(e.search(n.pattern)!==-1)return n.averageCharsPerToken}function zt(e){return Array.from(e).length}function Bt(e){let t=0,n=0;for(let r of e){let e=r.codePointAt(0);e>=12352&&e<=12543?t++:n++}return n+Math.ceil(t/Jt)}function Vt(e,t={}){if(!e)return 0;let n=0;for(let r of Ft(e,t))n+=r.tokenCount;return n}function Ht(e,t=0,n,r={}){if(!e)return``;let i=Ft(e,r),a=0;if(t<0||n!==void 0&&n<0){let e=Array.from(i);for(let{tokenCount:t}of e)a+=t;i=e}let o=t<0?Math.max(0,a+t):Math.max(0,t),s=n===void 0?1/0:n<0?Math.max(0,a+n):n;if(o>=s)return``;let c=[],l=0;for(let{segment:e,tokenCount:t}of i){if(l>=s)break;let n=Ut(e,l,t,o,s);n&&c.push(n),l+=t}return c.join(``)}function Ut(e,t,n,r,i){if(n===0)return t>=r&&t<i?e:``;let a=t+n;if(t>=i||a<=r)return``;let o=Math.max(0,r-t),s=Math.min(n,i-t);if(o===0&&s===n)return e;let c=Math.floor(o/n*e.length),l=Math.ceil(s/n*e.length);return e.slice(c,l)}var Wt,Gt,Kt,qt,Jt,Yt,Xt=I((()=>{Wt={whitespace:/^\s+$/,structuredWhitespace:/\n\s/,cjk:/[\u4E00-\u9FFF\u3400-\u4DBF\u3000-\u30FF\uFF00-\uFFEF\u2E80-\u2EFF\u31C0-\u31EF\u3200-\u32FF\u3300-\u33FF\uAC00-\uD7AF\u1100-\u11FF\u3130-\u318F\uA960-\uA97F\uD7B0-\uD7FF]/,numeric:/^\d+$/,punctuation:/[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_"-]/},Gt=RegExp(`(\\s+|${Wt.punctuation.source}+)`),Kt=6,qt=3,Jt=1.35,Yt=[{pattern:/[äöüßẞ]/i,averageCharsPerToken:2.6},{pattern:/[éèêëàâîïôûùüÿçœæáíóúñ]/i,averageCharsPerToken:3},{pattern:/[ąćęłńóśźżěščřžýůúďťň]/i,averageCharsPerToken:2.5},{pattern:/[\u0430-\u044F\u0451]/i,averageCharsPerToken:4},{pattern:/[\u03AC-\u03CE]/i,averageCharsPerToken:2.75},{pattern:/^\p{Extended_Pictographic}[\p{Extended_Pictographic}\p{Emoji_Component}]*$/u,averageCharsPerToken:.75}]}));function Zt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qt(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function $t(e,t){let n=e.length,r=t.length,i=Array.from({length:r+1},(e,t)=>t);for(let a=1;a<=n;a++){let n=i[0];i[0]=a;for(let o=1;o<=r;o++){let r=i[o];i[o]=e[a-1]===t[o-1]?n:1+Math.min(n,i[o],i[o-1]),n=r}}return i[r]}function en(e,t){let n=e.length<=4?2:Math.floor(e.length/2),r=e.toLowerCase(),i=Array.isArray(t)?t:[...t],a,o=1/0;for(let e of i){let t=e.toLowerCase(),i=$t(r,t),s;if(t.startsWith(r)&&t!==r)s=i;else if(t.includes(r))s=100+i;else if(i<=n)s=200+i;else continue;s<o&&(o=s,a=e)}return a}var tn=I((()=>{}));function nn(e,t){switch(e){case`bash`:return fn(t);case`zsh`:return pn(t);case`fish`:return mn(t);case`nushell`:return hn(t)}}function rn(e,t,n,r,i){let a=n[r]??``,o={commands:e,leaf:t};for(let e=0;e<r;e++){let t=n[e];if(t.startsWith(`-`))continue;let r=o.commands.get(t);if(r&&(r._alias&&r.target&&(r=o.commands.get(r.target)),r)){if(r._group&&r.commands)o={commands:r.commands,leaf:r.root};else{o={commands:new Map,leaf:r};break}}}let s=[];if(a.startsWith(`-`)){let e=o.leaf;if(e?.options){let t=e.options.shape;for(let e of Object.keys(t)){let n=`--${Qt(e)}`;n.startsWith(a)&&s.push({value:n,description:un(t[e])})}if(e.alias)for(let[n,r]of Object.entries(e.alias)){let e=`-${r}`;if(e.startsWith(a)){let r=un(t[n]);s.push({value:e,description:r})}}}if(i){let e=i.schema.shape;for(let t of Object.keys(e)){let n=`--${Qt(t)}`;n.startsWith(a)&&!s.some(e=>e.value===n)&&s.push({value:n,description:un(e[t])})}if(i.alias)for(let[t,n]of Object.entries(i.alias)){let r=`-${n}`;if(r.startsWith(a)&&!s.some(e=>e.value===r)){let n=un(e[t]);s.push({value:r,description:n})}}}return s}if(r>0){let e=n[r-1],t=o.leaf;if(e.startsWith(`-`)){if(t?.options){let n=on(e,t);if(n){let e=cn(n,t.options);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!sn(n,t.options))return s}}if(i){let t=on(e,{options:i.schema,alias:i.alias});if(t){let e=cn(t,i.schema);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!sn(t,i.schema))return s}}}}for(let[e,t]of o.commands)t._alias||e.startsWith(a)&&s.push({value:e,description:t.description,...t._group?{noSpace:!0}:void 0});return s}function an(e,t){switch(e){case`bash`:return t.map(e=>e.noSpace?`${e.value}\x01`:e.value).join(`\v`);case`zsh`:return t.map(e=>{let t=e.value.replaceAll(`:`,`\\:`);return e.description?`${t}:${e.description}`:t}).join(`
4
4
  `);case`fish`:return t.map(e=>e.description?`${e.value}\t${e.description}`:e.value).join(`
@@ -170,14 +170,14 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
170
170
  `)}},{name:`mcp`,description:`Register as MCP server`,subcommands:[Wl({name:`add`,description:`Register as MCP server`,alias:{command:`c`},options:d.object({agent:d.string().optional().describe(`Target a specific agent (e.g. claude-code, cursor)`),command:d.string().optional().describe(`Override the command agents will run (e.g. "pnpm my-cli --mcp")`),noGlobal:d.boolean().optional().describe(`Install to project instead of globally`)})}),Wl({name:`doctor`,description:`Validate MCP server startup and tool listing`})]},{name:`skills`,aliases:[`skill`],description:`Sync skill files to agents`,subcommands:[Wl({name:`add`,description:`Sync skill files to agents`,options:d.object({depth:d.number().optional().describe(`Grouping depth for skill files (default: 1)`),noGlobal:d.boolean().optional().describe(`Install to project instead of globally`)})}),Wl({name:`list`,aliases:[`ls`],description:`List skills`})]}]}));function Zl(e,t={}){let{aliases:n,configFlag:r,description:i,globals:a,version:o,commands:s=[],root:c=!1}=t,l=[],u=o?`${e}@${o}`:e;if(l.push(i?`${u} \u2014 ${i}`:u),l.push(``),l.push(`Usage: ${e} <command>`),n?.length&&l.push(`Aliases: ${n.join(`, `)}`),s.length>0){l.push(``),l.push(`Commands:`);let e=Math.max(...s.map(e=>e.name.length));for(let t of s)if(t.description){let n=` `.repeat(e-t.name.length);l.push(` ${t.name}${n} ${t.description}`)}else l.push(` ${t.name}`)}return l.push(...cu(c,r,a)),l.join(`
171
171
  `)}function Ql(e,t={}){let{alias:n,aliases:r,configFlag:i,description:a,globals:o,version:s,args:c,env:l,envSource:u,hint:d,root:f=!1,options:p,examples:m}=t,h=[],g=s?`${e}@${s}`:e;h.push(a?`${g} \u2014 ${a}`:g),h.push(``);let{usage:_}=t;if(_&&_.length>0){let t=_.map(t=>{let n=[];if(t.prefix&&n.push(t.prefix),n.push(e),t.args)for(let e of Object.keys(t.args))n.push(`<${e}>`);if(t.options)for(let e of Object.keys(t.options))n.push(`--${e} <${e}>`);return t.suffix&&n.push(t.suffix),n.join(` `)}),n=` `.repeat(7);h.push(`Usage: ${t[0]}`);for(let e of t.slice(1))h.push(`${n}${e}`)}else{let n=$l(e,c),r=t.commands&&t.commands.length>0?` | <command>`:``;h.push(`Usage: ${n}${p?` [options]`:``}${r}`)}if(r?.length&&h.push(`Aliases: ${r.join(`, `)}`),c){let e=eu(c);if(e.length>0){h.push(``),h.push(`Arguments:`);let t=Math.max(...e.map(e=>e.name.length));for(let n of e)h.push(` ${n.name}${` `.repeat(t-n.name.length)} ${n.description}`)}}if(p){let e=nu(p,n);if(e.length>0){h.push(``),h.push(`Options:`);let t=Math.max(...e.map(e=>e.flag.length));for(let n of e){let e=` `.repeat(t-n.flag.length),r=n.deprecated?`[deprecated] `:``,i=n.defaultValue===void 0?`${r}${n.description}`:`${r}${n.description} (default: ${n.defaultValue})`;h.push(` ${n.flag}${e} ${i}`)}}}if(m&&m.length>0){h.push(``),h.push(`Examples:`);let t=Math.max(...m.map(t=>(t.command?`${e} ${t.command}`:e).length));for(let n of m){let r=n.command?`${e} ${n.command}`:e;n.description?h.push(` ${r}${` `.repeat(t-r.length)} # ${n.description}`):h.push(` ${r}`)}}d&&(h.push(``),h.push(d));let{commands:v}=t;if(v&&v.length>0){h.push(``),h.push(`Commands:`);let e=Math.max(...v.map(e=>e.name.length));for(let t of v)if(t.description){let n=` `.repeat(e-t.name.length);h.push(` ${t.name}${n} ${t.description}`)}else h.push(` ${t.name}`)}if(t.hideGlobalOptions||h.push(...cu(f,i,o)),l){let e=tu(l);if(e.length>0){h.push(``),h.push(`Environment Variables:`);let t=Math.max(...e.map(e=>e.name.length));for(let n of e){let e=` `.repeat(t-n.name.length),r=[n.description],i=u??Rl();n.name in i&&r.push(`set: ${lu(i[n.name])}`),n.defaultValue!==void 0&&r.push(`default: ${n.defaultValue}`);let a=r.length>1?`${r[0]} (${r.slice(1).join(`, `)})`:r[0];h.push(` ${n.name}${e} ${a}`)}}}return h.join(`
172
172
  `)}function $l(e,t){if(!t)return e;let n=[e];for(let[e,r]of Object.entries(t.shape)){let t=ru(r),i=(t.includes(`|`)?t:e)+(t===`array`?`...`:``);n.push(r._zod.optout===`optional`?`[${i}]`:`<${i}>`)}return n.join(` `)}function eu(e){let t=[];for(let[n,r]of Object.entries(e.shape))t.push({name:n,description:r.description??``});return t}function tu(e){let t=[];for(let[n,r]of Object.entries(e.shape)){let e=ou(r);t.push({name:n,description:r.description??``,defaultValue:e})}return t}function nu(e,t){let n=[];for(let[r,i]of Object.entries(e.shape)){let e=ru(i),a=t?.[r],o=Qt(r),s=e===`boolean`?``:` <${e}>`,c=a?`--${o}, -${a}${s}`:`--${o}${s}`,l=ou(i);e===`boolean`&&l===!1&&(l=void 0);let u=su(i);n.push({flag:c,description:i.description??``,defaultValue:l,deprecated:u})}return n}function ru(e){if(iu(e))return`count`;let t=au(e);if(t instanceof d.ZodString)return`string`;if(t instanceof d.ZodNumber)return`number`;if(t instanceof d.ZodBoolean)return`boolean`;if(t instanceof d.ZodArray)return`array`;if(t instanceof d.ZodEnum)return Object.values(t._zod.def.entries).join(`|`);if(t instanceof d.ZodUnion){let e=t._zod?.def?.options;if(e?.every(e=>e instanceof d.ZodLiteral))return e.map(e=>String(e._zod.def.values[0])).join(`|`)}return`value`}function iu(e){let t=e;return typeof t?.meta==`function`&&t.meta()?.count===!0}function au(e){return e instanceof d.ZodOptional?au(e.unwrap()):e instanceof d.ZodDefault?au(e.removeDefault()):e instanceof d.ZodNullable?au(e.unwrap()):e}function ou(e){if(e instanceof d.ZodDefault){let t=e._def.defaultValue,n=typeof t==`function`?t():t;return Array.isArray(n)&&n.length===0?void 0:n}if(e instanceof d.ZodOptional)return ou(e.unwrap())}function su(e){return e?.meta?.()?.deprecated===!0||void 0}function cu(e=!1,t,n){let r=[];if(e){let e=Yl.flatMap(e=>{if(!e.subcommands)return[{name:e.name,desc:e.description}];if(e.subcommands.length===1)return[{name:`${e.name} ${e.subcommands[0].name}`,desc:e.subcommands[0].description}];let t=e.subcommands.map(e=>e.name).join(`, `);return[{name:e.name,desc:`${e.description} (${t})`}]}),t=Math.max(...e.map(e=>e.name.length));r.push(``,`Integrations:`,...e.map(e=>` ${e.name}${` `.repeat(t-e.name.length)} ${e.desc}`))}if(n){let e=nu(n.schema,n.alias);if(e.length>0){let t=Math.max(...e.map(e=>e.flag.length));r.push(``,`Custom Global Options:`,...e.map(e=>{let n=` `.repeat(t-e.flag.length),r=e.deprecated?`[deprecated] `:``,i=e.defaultValue===void 0?`${r}${e.description}`:`${r}${e.description} (default: ${e.defaultValue})`;return` ${e.flag}${n} ${i}`}))}}let i=[...t?[{flag:`--${t} <path>`,desc:`Load JSON option defaults from a file`}]:[],{flag:`--filter-output <keys>`,desc:`Filter output by key paths (e.g. foo,bar.baz,a[0,3])`},{flag:`--format <toon|json|yaml|md|jsonl>`,desc:`Output format`},{flag:`--help`,desc:`Show help`},{flag:`--llms, --llms-full`,desc:`Print LLM-readable manifest`},...e?[{flag:`--mcp`,desc:`Start as MCP stdio server`}]:[],...t?[{flag:`--no-${t}`,desc:`Disable JSON option defaults for this run`}]:[],{flag:`--schema`,desc:`Show JSON Schema for command`},{flag:`--token-count`,desc:`Print token count of output (instead of output)`},{flag:`--token-limit <n>`,desc:`Limit output to n tokens`},{flag:`--token-offset <n>`,desc:`Skip first n tokens of output`},{flag:`--full-output`,desc:`Show full output envelope`},...e?[{flag:`--update`,desc:`Update to latest version`}]:[],...e?[{flag:`--version`,desc:`Show version`}]:[]].sort((e,t)=>e.flag.localeCompare(t.flag)),a=Math.max(...i.map(e=>e.flag.length));return r.push(``,`Global Options:`,...i.map(e=>` ${e.flag}${` `.repeat(a-e.flag.length)} ${e.desc}`)),r}function lu(e){return e.length<=4?`****`:`****${e.slice(-4)}`}var uu=I((()=>{Xl(),tn(),zl()}));function du(e,t){if(!(!t||t.commands.length===0))return{description:t.description??(t.commands.length===1?`Suggested command:`:`Suggested commands:`),commands:t.commands.map(t=>pu(e,t))}}function fu(e){let t=[e.description];for(let n of e.commands)t.push(` ${n.command}${n.description?` - ${n.description}`:``}`);return t.join(`
173
- `)}function pu(e,t){if(typeof t==`string`)return{command:`${e} ${t}`};let n=`${t.command===e||t.command.startsWith(`${e} `)?``:`${e} `}${t.command}`;if(t.args)for(let[e,r]of Object.entries(t.args))n+=r===!0?` <${e}>`:` ${r}`;if(t.options)for(let[e,r]of Object.entries(t.options))n+=r===!0?` --${e} <${e}>`:` --${e} ${r}`;return{command:n,...t.description?{description:t.description}:void 0}}var mu=I((()=>{}));async function hu(e,t={}){let n=[],r=t.exclude?s.resolve(t.exclude):void 0;async function i(e,t){let a=await S.readdir(e,{withFileTypes:!0});a.sort((e,t)=>e.name.localeCompare(t.name));for(let o of a){if(o.name.startsWith(`.`)||o.name.startsWith(`_`))continue;let a=s.join(e,o.name);if(o.isDirectory()){vu(o.name,a),await i(a,[...t,o.name]);continue}if(!o.isFile()||a===r)continue;let c=yu.find(e=>o.name.endsWith(e));if(!c)continue;let l=o.name.slice(0,-c.length);if(!(l.endsWith(`.d`)||l.endsWith(`.test`)||l.endsWith(`.test-d`)||l.endsWith(`.spec`))){if(l===`index`){t.length>0&&n.push({file:a,segments:t});continue}vu(l,a),n.push({file:a,segments:[...t,l]})}}}await i(e,[]);let a=new Map;for(let e of n){let t=e.segments.join(` `),n=a.get(t);if(n)throw Error(`Duplicate filesystem command '${t}' from '${n}' and '${e.file}'.`);a.set(t,e.file)}return n}function gu(){return globalThis[Symbol.for(xu)]?.shift()}async function _u(e){return Promise.all(e.map(async({load:e,...t})=>({...t,command:await e()})))}function vu(e,t){if(!bu.test(e))throw Error(`Invalid filesystem command segment '${e}' from '${t}'. Use lowercase kebab-case names.`)}var yu,bu,xu,Su=I((()=>{yu=[`.cts`,`.cjs`,`.mts`,`.mjs`,`.ts`,`.js`],bu=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,xu=`incur.fs.manifests`}));function Cu(e){let t=d.toJSONSchema(e,{unrepresentable:`any`,override:e=>{let t=e.zodSchema._zod?.def?.type;(t===`bigint`||t===`date`)&&(e.jsonSchema.type=`string`)}});return delete t.$schema,t}var wu=I((()=>{}));function Tu(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!Tu(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Tu(e[r],t[r]))return!1;return!0}return e===t}var Eu=I((()=>{}));function Du(e){return encodeURI(Ou(e))}function Ou(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var ku=I((()=>{}));function Au(e,t=Object.create(null),n=Pu,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:Au(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(Nu[i])continue;let a=`${r}/${Du(i)}`,o=e[i];if(Array.isArray(o)){if(ju[i]){let e=o.length;for(let r=0;r<e;r++)Au(o[r],t,n,`${a}/${r}`)}}else if(Mu[i])for(let e in o)Au(o[e],t,n,`${a}/${Du(e)}`);else Au(o,t,n,a)}return t}var ju,Mu,Nu,Pu,Fu=I((()=>{ku(),ju={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Mu={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Nu={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},Pu=typeof self<`u`&&self.location&&self.location.origin!==`null`?new URL(self.location.origin+self.location.pathname+location.search):new URL(`https://github.com/cfworker`)}));function Iu(e){return e.test.bind(e)}function Lu(e){return e%4==0&&(e%100!=0||e%400==0)}function Ru(e){let t=e.match(Uu);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&Lu(n)?29:Wu[r])}function zu(e,t){let n=t.match(Gu);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}function Bu(e){let t=e.split(ad);return t.length==2&&Ru(t[0])&&zu(!0,t[1])}function Vu(e){return od.test(e)&&sd.test(e)}function Hu(e){if(cd.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}var Uu,Wu,Gu,Ku,qu,Ju,Yu,Xu,Zu,Qu,$u,ed,td,nd,rd,id,ad,od,sd,cd,ld=I((()=>{Uu=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Wu=[0,31,28,31,30,31,30,31,31,30,31,30,31],Gu=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Ku=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,qu=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Ju=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Yu=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Xu=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Zu=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Qu=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,$u=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,ed=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},td=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,nd=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,rd=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),id={date:Ru,time:zu.bind(void 0,!1),"date-time":Bu,duration:rd,uri:Vu,"uri-reference":Iu(qu),"uri-template":Iu(Ju),url:Iu(Yu),email:ed,hostname:Iu(Ku),ipv4:Iu(td),ipv6:Iu(nd),regex:Hu,uuid:Iu(Xu),"json-pointer":Iu(Zu),"json-pointer-uri-fragment":Iu(Qu),"relative-json-pointer":Iu($u)},ad=/t|\s/i,od=/\/|:/,sd=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,cd=/[^\\]\\Z/})),ud=I((()=>{}));function dd(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}var fd=I((()=>{}));function pd(e,t,n=`2019-09`,r=Au(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:C,else:w,format:T,properties:ee,patternProperties:E,additionalProperties:D,unevaluatedProperties:O,minProperties:k,maxProperties:A,propertyNames:j,dependentRequired:te,dependentSchemas:M,dependencies:ne,prefixItems:re,items:ie,additionalItems:ae,unevaluatedItems:oe,contains:se,minContains:N,maxContains:ce,minItems:le,maxItems:ue,uniqueItems:de,minimum:fe,maximum:P,exclusiveMinimum:pe,exclusiveMaximum:me,multipleOf:he,minLength:ge,maxLength:_e,pattern:ve,__absolute_ref__:ye,__absolute_recursive_ref__:be}=t,F=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[be]:a,u=`${s}/$recursiveRef`,d=pd(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||F.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[ye||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw ye&&ye!==d&&(e+=` Absolute URI "${ye}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
174
- - `)}`,Error(e)}let l=`${s}/$ref`,u=pd(e,t,n,r,i,a,o,l,c);if(u.valid||F.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:F.length===0,errors:F}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||F.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&F.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&F.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?Tu(e,h)||F.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&F.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>Tu(e,t))||F.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||F.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){let t=`${s}/not`;pd(e,v,n,r,i,a,o,t).valid&&F.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let xe=[];if(y!==void 0){let t=`${s}/anyOf`,l=F.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=pd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);F.push(...f.errors),u||=f.valid,f.valid&&xe.push(d)}u?F.length=l:F.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${s}/allOf`,l=F.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=pd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);F.push(...f.errors),u&&=f.valid,f.valid&&xe.push(d)}u?F.length=l:F.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(x!==void 0){let t=`${s}/oneOf`,l=F.length,u=x.filter((s,l)=>{let u=Object.create(c),d=pd(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return F.push(...d.errors),d.valid&&xe.push(u),d.valid}).length;u===1?F.length=l:F.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...xe),S!==void 0){let t=`${s}/if`;if(pd(e,S,n,r,i,a,o,t,c).valid){if(C!==void 0){let l=pd(e,C,n,r,i,a,o,`${s}/then`,c);l.valid||F.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(w!==void 0){let l=pd(e,w,n,r,i,a,o,`${s}/else`,c);l.valid||F.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||F.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(k!==void 0&&t.length<k&&F.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),A!==void 0&&t.length>A&&F.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${A} properties.`}),j!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${Du(s)}`,c=pd(s,j,n,r,i,a,e,t);c.valid||F.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(te!==void 0){let t=`${s}/dependantRequired`;for(let n in te)if(n in e){let r=te[n];for(let i of r)i in e||F.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(M!==void 0)for(let t in M){let l=`${s}/dependentSchemas`;if(t in e){let s=pd(e,M[t],n,r,i,a,o,`${l}/${Du(t)}`,c);s.valid||F.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(ne!==void 0){let t=`${s}/dependencies`;for(let s in ne)if(s in e){let c=ne[s];if(Array.isArray(c))for(let n of c)n in e||F.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=pd(e,c,n,r,i,a,o,`${t}/${Du(s)}`);l.valid||F.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(ee!==void 0){let t=`${s}/properties`;for(let s in ee){if(!(s in e))continue;let d=`${o}/${Du(s)}`,f=pd(e[s],ee[s],n,r,i,a,d,`${t}/${Du(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,F.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&E!==void 0){let t=`${s}/patternProperties`;for(let s in E){let d=new RegExp(s,`u`),f=E[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${Du(p)}`,h=pd(e[p],f,n,r,i,a,m,`${t}/${Du(s)}`);h.valid?c[p]=l[p]=!0:(u=i,F.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&D!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${Du(s)}`,f=pd(e[s],D,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,F.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&O!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${Du(s)}`,u=pd(e[s],O,n,r,i,a,l,t);u.valid?c[s]=!0:F.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){ue!==void 0&&e.length>ue&&F.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${ue}).`}),le!==void 0&&e.length<le&&F.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${le}).`});let t=e.length,l=0,u=!1;if(re!==void 0){let d=`${s}/prefixItems`,f=Math.min(re.length,t);for(;l<f;l++){let t=pd(e[l],re[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,F.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(ie!==void 0){let d=`${s}/items`;if(Array.isArray(ie)){let s=Math.min(ie.length,t);for(;l<s;l++){let t=pd(e[l],ie[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,F.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=pd(e[l],ie,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,F.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ae!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=pd(e[l],ae,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,F.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(se!==void 0){if(t===0&&N===void 0)F.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(N!==void 0&&t<N)F.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${N}).`});else{let l=`${s}/contains`,u=F.length,d=0;for(let s=0;s<t;s++){let t=pd(e[s],se,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):F.push(...t.errors)}d>=(N||0)&&(F.length=u),N===void 0&&ce===void 0&&d===0?F.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):N!==void 0&&d<N?F.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${N} items matching schema. Only ${d} items were found.`}):ce!==void 0&&d>ce&&F.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${ce} items matching schema. ${d} items were found.`})}}if(!u&&oe!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=pd(e[l],oe,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||F.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(de)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&Tu(r,t))&&(F.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(fe!==void 0&&(pe===!0&&e<=fe||e<fe)&&F.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${pe?`or equal to `:``} ${fe}.`}),P!==void 0&&(me===!0&&e>=P||e>P)&&F.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${me?`or equal to `:``} ${P}.`})):(fe!==void 0&&e<fe&&F.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${fe}.`}),P!==void 0&&e>P&&F.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${P}.`}),pe!==void 0&&e<=pe&&F.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${pe}.`}),me!==void 0&&e>=me&&F.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${me}.`})),he!==void 0){let t=e%he;Math.abs(0-t)>=1.1920929e-7&&Math.abs(he-t)>=1.1920929e-7&&F.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${he}.`})}}else if(u===`string`){let t=ge===void 0&&_e===void 0?0:dd(e);ge!==void 0&&t<ge&&F.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${ge}).`}),_e!==void 0&&t>_e&&F.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${_e}).`}),ve!==void 0&&!new RegExp(ve,`u`).test(e)&&F.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),T!==void 0&&id[T]&&!id[T](e)&&F.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${T}".`})}return{valid:F.length===0,errors:F}}var md=I((()=>{Eu(),Fu(),ld(),ku(),fd()})),hd,gd=I((()=>{Fu(),md(),hd=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Au(e)}validate(e){return pd(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Au(e,this.lookup)}}})),_d=I((()=>{Eu(),Fu(),ld(),ku(),ud(),fd(),md(),gd()}));function vd(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function yd({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}function bd(e){return e.title!==void 0&&e.title!==``?e.title:`annotations`in e&&e.annotations?.title?e.annotations.title:e.name}function xd(e){return dh[e]}function Sd(e){let t={};for(let n of e){let e=n.shape.method.value;t[e]=n}return t}function Cd(e){return fh[e]}function wd(e){return ph[e]}function Td(e){return zf.parse(e)}function Ed(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Dd(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}function Od(e,t){return E.safeParse(e,t)}function kd(e){return e===`completed`||e===`failed`||e===`cancelled`}function Ad(e){if(!e)return;let{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}=e;return{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}}function jd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Md(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=jd(a)&&jd(i)?{...a,...i}:i}return n}async function Nd(e){let t=[];for await(let n of e)t.push(n);return t}async function Pd(e){for await(let t of e)if(t.type===`result`)return t.result;else if(t.type===`error`)throw t.error;throw Error(`No result in stream.`)}function Fd(e){return zf.parse(JSON.parse(e))}function Id(e){return JSON.stringify(e)+`
173
+ `)}function pu(e,t){if(typeof t==`string`)return{command:`${e} ${t}`};let n=`${t.command===e||t.command.startsWith(`${e} `)?``:`${e} `}${t.command}`;if(t.args)for(let[e,r]of Object.entries(t.args))n+=r===!0?` <${e}>`:` ${r}`;if(t.options)for(let[e,r]of Object.entries(t.options))n+=r===!0?` --${e} <${e}>`:` --${e} ${r}`;return{command:n,...t.description?{description:t.description}:void 0}}var mu=I((()=>{}));async function hu(e,t={}){let n=[],r=t.exclude?s.resolve(t.exclude):void 0;async function i(e,t){let a=await S.readdir(e,{withFileTypes:!0});a.sort((e,t)=>e.name.localeCompare(t.name));for(let o of a){if(o.name.startsWith(`.`)||o.name.startsWith(`_`))continue;let a=s.join(e,o.name);if(o.isDirectory()){vu(o.name,a),await i(a,[...t,o.name]);continue}if(!o.isFile()||a===r)continue;let c=yu.find(e=>o.name.endsWith(e));if(!c)continue;let l=o.name.slice(0,-c.length);if(!(l.endsWith(`.d`)||l.endsWith(`.test`)||l.endsWith(`.test-d`)||l.endsWith(`.spec`))){if(l===`index`){t.length>0&&n.push({file:a,segments:t});continue}vu(l,a),n.push({file:a,segments:[...t,l]})}}}await i(e,[]);let a=new Map;for(let e of n){let t=e.segments.join(` `),n=a.get(t);if(n)throw Error(`Duplicate filesystem command '${t}' from '${n}' and '${e.file}'.`);a.set(t,e.file)}return n}function gu(){return globalThis[Symbol.for(xu)]?.shift()}async function _u(e){return Promise.all(e.map(async({load:e,...t})=>({...t,command:await e()})))}function vu(e,t){if(!bu.test(e))throw Error(`Invalid filesystem command segment '${e}' from '${t}'. Use lowercase kebab-case names.`)}var yu,bu,xu,Su=I((()=>{yu=[`.cts`,`.cjs`,`.mts`,`.mjs`,`.ts`,`.js`],bu=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,xu=`incur.fs.manifests`}));function Cu(e){let t=d.toJSONSchema(e,{unrepresentable:`any`,override:e=>{let t=e.zodSchema._zod?.def?.type;(t===`bigint`||t===`date`)&&(e.jsonSchema.type=`string`)}});return delete t.$schema,t}var wu=I((()=>{}));function Tu(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!Tu(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Tu(e[r],t[r]))return!1;return!0}return e===t}var Eu=I((()=>{}));function Du(e){return encodeURI(Ou(e))}function Ou(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var ku=I((()=>{}));function Au(e,t=Object.create(null),n=Pu,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:Au(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(Nu[i])continue;let a=`${r}/${Du(i)}`,o=e[i];if(Array.isArray(o)){if(ju[i]){let e=o.length;for(let r=0;r<e;r++)Au(o[r],t,n,`${a}/${r}`)}}else if(Mu[i])for(let e in o)Au(o[e],t,n,`${a}/${Du(e)}`);else Au(o,t,n,a)}return t}var ju,Mu,Nu,Pu,Fu=I((()=>{ku(),ju={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Mu={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Nu={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},Pu=typeof self<`u`&&self.location&&self.location.origin!==`null`?new URL(self.location.origin+self.location.pathname+location.search):new URL(`https://github.com/cfworker`)}));function Iu(e){return e.test.bind(e)}function Lu(e){return e%4==0&&(e%100!=0||e%400==0)}function Ru(e){let t=e.match(Uu);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&Lu(n)?29:Wu[r])}function zu(e,t){let n=t.match(Gu);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}function Bu(e){let t=e.split(ad);return t.length==2&&Ru(t[0])&&zu(!0,t[1])}function Vu(e){return od.test(e)&&sd.test(e)}function Hu(e){if(cd.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}var Uu,Wu,Gu,Ku,qu,Ju,Yu,Xu,Zu,Qu,$u,ed,td,nd,rd,id,ad,od,sd,cd,ld=I((()=>{Uu=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Wu=[0,31,28,31,30,31,30,31,31,30,31,30,31],Gu=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Ku=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,qu=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Ju=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Yu=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Xu=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Zu=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Qu=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,$u=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,ed=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},td=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,nd=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,rd=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),id={date:Ru,time:zu.bind(void 0,!1),"date-time":Bu,duration:rd,uri:Vu,"uri-reference":Iu(qu),"uri-template":Iu(Ju),url:Iu(Yu),email:ed,hostname:Iu(Ku),ipv4:Iu(td),ipv6:Iu(nd),regex:Hu,uuid:Iu(Xu),"json-pointer":Iu(Zu),"json-pointer-uri-fragment":Iu(Qu),"relative-json-pointer":Iu($u)},ad=/t|\s/i,od=/\/|:/,sd=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,cd=/[^\\]\\Z/})),ud=I((()=>{}));function dd(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}var fd=I((()=>{}));function pd(e,t,n=`2019-09`,r=Au(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:C,else:w,format:T,properties:ee,patternProperties:E,additionalProperties:D,unevaluatedProperties:O,minProperties:k,maxProperties:te,propertyNames:A,dependentRequired:ne,dependentSchemas:j,dependencies:M,prefixItems:re,items:ie,additionalItems:ae,unevaluatedItems:oe,contains:se,minContains:N,maxContains:ce,minItems:le,maxItems:ue,uniqueItems:de,minimum:fe,maximum:P,exclusiveMinimum:pe,exclusiveMaximum:me,multipleOf:he,minLength:ge,maxLength:_e,pattern:ve,__absolute_ref__:ye,__absolute_recursive_ref__:be}=t,F=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[be]:a,u=`${s}/$recursiveRef`,d=pd(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||F.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[ye||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw ye&&ye!==d&&(e+=` Absolute URI "${ye}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
174
+ - `)}`,Error(e)}let l=`${s}/$ref`,u=pd(e,t,n,r,i,a,o,l,c);if(u.valid||F.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:F.length===0,errors:F}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||F.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&F.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&F.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?Tu(e,h)||F.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&F.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>Tu(e,t))||F.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||F.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){let t=`${s}/not`;pd(e,v,n,r,i,a,o,t).valid&&F.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let xe=[];if(y!==void 0){let t=`${s}/anyOf`,l=F.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=pd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);F.push(...f.errors),u||=f.valid,f.valid&&xe.push(d)}u?F.length=l:F.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${s}/allOf`,l=F.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=pd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);F.push(...f.errors),u&&=f.valid,f.valid&&xe.push(d)}u?F.length=l:F.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(x!==void 0){let t=`${s}/oneOf`,l=F.length,u=x.filter((s,l)=>{let u=Object.create(c),d=pd(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return F.push(...d.errors),d.valid&&xe.push(u),d.valid}).length;u===1?F.length=l:F.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...xe),S!==void 0){let t=`${s}/if`;if(pd(e,S,n,r,i,a,o,t,c).valid){if(C!==void 0){let l=pd(e,C,n,r,i,a,o,`${s}/then`,c);l.valid||F.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(w!==void 0){let l=pd(e,w,n,r,i,a,o,`${s}/else`,c);l.valid||F.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||F.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(k!==void 0&&t.length<k&&F.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),te!==void 0&&t.length>te&&F.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${te} properties.`}),A!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${Du(s)}`,c=pd(s,A,n,r,i,a,e,t);c.valid||F.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(ne!==void 0){let t=`${s}/dependantRequired`;for(let n in ne)if(n in e){let r=ne[n];for(let i of r)i in e||F.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(j!==void 0)for(let t in j){let l=`${s}/dependentSchemas`;if(t in e){let s=pd(e,j[t],n,r,i,a,o,`${l}/${Du(t)}`,c);s.valid||F.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(M!==void 0){let t=`${s}/dependencies`;for(let s in M)if(s in e){let c=M[s];if(Array.isArray(c))for(let n of c)n in e||F.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=pd(e,c,n,r,i,a,o,`${t}/${Du(s)}`);l.valid||F.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(ee!==void 0){let t=`${s}/properties`;for(let s in ee){if(!(s in e))continue;let d=`${o}/${Du(s)}`,f=pd(e[s],ee[s],n,r,i,a,d,`${t}/${Du(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,F.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&E!==void 0){let t=`${s}/patternProperties`;for(let s in E){let d=new RegExp(s,`u`),f=E[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${Du(p)}`,h=pd(e[p],f,n,r,i,a,m,`${t}/${Du(s)}`);h.valid?c[p]=l[p]=!0:(u=i,F.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&D!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${Du(s)}`,f=pd(e[s],D,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,F.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&O!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${Du(s)}`,u=pd(e[s],O,n,r,i,a,l,t);u.valid?c[s]=!0:F.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){ue!==void 0&&e.length>ue&&F.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${ue}).`}),le!==void 0&&e.length<le&&F.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${le}).`});let t=e.length,l=0,u=!1;if(re!==void 0){let d=`${s}/prefixItems`,f=Math.min(re.length,t);for(;l<f;l++){let t=pd(e[l],re[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,F.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(ie!==void 0){let d=`${s}/items`;if(Array.isArray(ie)){let s=Math.min(ie.length,t);for(;l<s;l++){let t=pd(e[l],ie[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,F.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=pd(e[l],ie,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,F.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ae!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=pd(e[l],ae,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,F.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(se!==void 0){if(t===0&&N===void 0)F.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(N!==void 0&&t<N)F.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${N}).`});else{let l=`${s}/contains`,u=F.length,d=0;for(let s=0;s<t;s++){let t=pd(e[s],se,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):F.push(...t.errors)}d>=(N||0)&&(F.length=u),N===void 0&&ce===void 0&&d===0?F.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):N!==void 0&&d<N?F.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${N} items matching schema. Only ${d} items were found.`}):ce!==void 0&&d>ce&&F.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${ce} items matching schema. ${d} items were found.`})}}if(!u&&oe!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=pd(e[l],oe,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||F.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(de)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&Tu(r,t))&&(F.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(fe!==void 0&&(pe===!0&&e<=fe||e<fe)&&F.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${pe?`or equal to `:``} ${fe}.`}),P!==void 0&&(me===!0&&e>=P||e>P)&&F.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${me?`or equal to `:``} ${P}.`})):(fe!==void 0&&e<fe&&F.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${fe}.`}),P!==void 0&&e>P&&F.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${P}.`}),pe!==void 0&&e<=pe&&F.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${pe}.`}),me!==void 0&&e>=me&&F.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${me}.`})),he!==void 0){let t=e%he;Math.abs(0-t)>=1.1920929e-7&&Math.abs(he-t)>=1.1920929e-7&&F.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${he}.`})}}else if(u===`string`){let t=ge===void 0&&_e===void 0?0:dd(e);ge!==void 0&&t<ge&&F.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${ge}).`}),_e!==void 0&&t>_e&&F.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${_e}).`}),ve!==void 0&&!new RegExp(ve,`u`).test(e)&&F.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),T!==void 0&&id[T]&&!id[T](e)&&F.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${T}".`})}return{valid:F.length===0,errors:F}}var md=I((()=>{Eu(),Fu(),ld(),ku(),fd()})),hd,gd=I((()=>{Fu(),md(),hd=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Au(e)}validate(e){return pd(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Au(e,this.lookup)}}})),_d=I((()=>{Eu(),Fu(),ld(),ku(),ud(),fd(),md(),gd()}));function vd(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function yd({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}function bd(e){return e.title!==void 0&&e.title!==``?e.title:`annotations`in e&&e.annotations?.title?e.annotations.title:e.name}function xd(e){return dh[e]}function Sd(e){let t={};for(let n of e){let e=n.shape.method.value;t[e]=n}return t}function Cd(e){return fh[e]}function wd(e){return ph[e]}function Td(e){return zf.parse(e)}function Ed(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Dd(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}function Od(e,t){return E.safeParse(e,t)}function kd(e){return e===`completed`||e===`failed`||e===`cancelled`}function Ad(e){if(!e)return;let{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}=e;return{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}}function jd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Md(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=jd(a)&&jd(i)?{...a,...i}:i}return n}async function Nd(e){let t=[];for await(let n of e)t.push(n);return t}async function Pd(e){for await(let t of e)if(t.type===`result`)return t.result;else if(t.type===`error`)throw t.error;throw Error(`No result in stream.`)}function Fd(e){return zf.parse(JSON.parse(e))}function Id(e){return JSON.stringify(e)+`
175
175
  `}function Ld(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Eh.test(e)){let n=[...e].filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Rd(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function zd(e){let t=Ld(e);return Rd(e,t.warnings),t.isValid}function Bd(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Vd(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...Bd(t.headers),...Bd(r.headers)}:t.headers}):e}function Hd(e,t=`input`){let n=e[`~standard`].jsonSchema[t]({target:`draft-2020-12`});if(n.type!==void 0&&n.type!==`object`)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(n.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:`object`,...n}}function Ud(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function Wd(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>Ud(e)).join(`, `)}:{success:!0,data:n.value}}function Gd(e){let t=Hd(e,`input`),n=t.properties||{},r=t.required||[];return Object.entries(n).map(([e,t])=>({name:e,description:t?.description,required:r.includes(e)}))}function Kd(){let e=new qg.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Jg.default)(e),e}function qd(e,t){let n=t.getValidator(e);return{"~standard":{version:1,vendor:`mcp`,jsonSchema:{input:()=>e,output:()=>e},validate:e=>{let t=n(e);return t.valid?{value:t.data}:{issues:[{message:t.errorMessage}]}}}}}var Jd,Yd,Xd,Zd,Qd,$d,B,ef,tf,nf,rf,V,H,af,of,sf,cf,lf,uf,df,ff,pf,mf,hf,gf,_f,vf,yf,U,W,bf,xf,Sf,Cf,wf,Tf,Ef,Df,Of,kf,Af,jf,Mf,Nf,Pf,Ff,If,Lf,Rf,zf,Bf,Vf,Hf,Uf,Wf,Gf,Kf,qf,Jf,Yf,Xf,Zf,Qf,$f,ep,tp,np,rp,ip,ap,op,sp,cp,lp,up,dp,fp,pp,mp,hp,gp,_p,vp,yp,bp,xp,Sp,Cp,wp,Tp,Ep,Dp,Op,kp,Ap,jp,Mp,Np,Pp,Fp,Ip,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp,$p,em,tm,nm,rm,im,am,om,sm,cm,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Am,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Bm,Vm,Hm,Um,Wm,Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,$m,eh,th,nh,rh,ih,ah,oh,sh,ch,lh,uh,dh,fh,ph,mh,hh,gh,_h,vh,yh,bh,xh,Sh,Ch,wh,Th,Eh,Dh,Oh,kh,Ah,jh,Mh,Nh,G,K,Ph,Fh,Ih,Lh,Rh,zh,Bh,Vh,Hh,Uh,Wh,Gh,Kh,qh,Jh,Yh,Xh,Zh,Qh,$h,eg,tg,ng,rg,ig,ag,og,sg,cg,lg,ug,dg,fg,pg,mg,hg,gg,_g,vg,yg,bg,xg,Sg,Cg,wg,Tg,Eg,Dg,Og,kg,Ag,jg,Mg,Ng,Pg,Fg,Ig,Lg,Rg,zg,Bg,Vg,Hg,Ug,Wg,Gg,Kg,qg,Jg,Yg,Xg,Zg=I((()=>{_d(),Jd=Object.create,Yd=Object.defineProperty,Xd=Object.getOwnPropertyDescriptor,Zd=Object.getOwnPropertyNames,Qd=Object.getPrototypeOf,$d=Object.prototype.hasOwnProperty,B=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ef=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Zd(t),a=0,o=i.length,s;a<o;a++)s=i[a],!$d.call(e,s)&&s!==n&&Yd(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Xd(t,s))||r.enumerable});return e},tf=(e,t,n)=>(n=e==null?{}:Jd(Qd(e)),ef(t||!e||!e.__esModule?Yd(n,`default`,{value:e,enumerable:!0}):n,e)),nf=function(e){return e.InvalidRequest=`invalid_request`,e.InvalidClient=`invalid_client`,e.InvalidGrant=`invalid_grant`,e.UnauthorizedClient=`unauthorized_client`,e.UnsupportedGrantType=`unsupported_grant_type`,e.InvalidScope=`invalid_scope`,e.AccessDenied=`access_denied`,e.ServerError=`server_error`,e.TemporarilyUnavailable=`temporarily_unavailable`,e.UnsupportedResponseType=`unsupported_response_type`,e.UnsupportedTokenType=`unsupported_token_type`,e.InvalidToken=`invalid_token`,e.MethodNotAllowed=`method_not_allowed`,e.TooManyRequests=`too_many_requests`,e.InvalidClientMetadata=`invalid_client_metadata`,e.InsufficientScope=`insufficient_scope`,e.InvalidTarget=`invalid_target`,e}({}),rf=class e extends Error{constructor(e,t,n){super(t),this.code=e,this.errorUri=n,this.name=`OAuthError`}toResponseObject(){let e={error:this.code,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}},V=function(e){return e.NotConnected=`NOT_CONNECTED`,e.AlreadyConnected=`ALREADY_CONNECTED`,e.NotInitialized=`NOT_INITIALIZED`,e.CapabilityNotSupported=`CAPABILITY_NOT_SUPPORTED`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.ConnectionClosed=`CONNECTION_CLOSED`,e.SendFailed=`SEND_FAILED`,e.ClientHttpNotImplemented=`CLIENT_HTTP_NOT_IMPLEMENTED`,e.ClientHttpAuthentication=`CLIENT_HTTP_AUTHENTICATION`,e.ClientHttpForbidden=`CLIENT_HTTP_FORBIDDEN`,e.ClientHttpUnexpectedContent=`CLIENT_HTTP_UNEXPECTED_CONTENT`,e.ClientHttpFailedToOpenStream=`CLIENT_HTTP_FAILED_TO_OPEN_STREAM`,e.ClientHttpFailedToTerminateSession=`CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION`,e}({}),H=class extends Error{constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`SdkError`}},af=E.url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:E.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),E.NEVER}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),E.looseObject({resource:E.string().url(),authorization_servers:E.array(af).optional(),jwks_uri:E.string().url().optional(),scopes_supported:E.array(E.string()).optional(),bearer_methods_supported:E.array(E.string()).optional(),resource_signing_alg_values_supported:E.array(E.string()).optional(),resource_name:E.string().optional(),resource_documentation:E.string().optional(),resource_policy_uri:E.string().url().optional(),resource_tos_uri:E.string().url().optional(),tls_client_certificate_bound_access_tokens:E.boolean().optional(),authorization_details_types_supported:E.array(E.string()).optional(),dpop_signing_alg_values_supported:E.array(E.string()).optional(),dpop_bound_access_tokens_required:E.boolean().optional()}),of=E.looseObject({issuer:E.string(),authorization_endpoint:af,token_endpoint:af,registration_endpoint:af.optional(),scopes_supported:E.array(E.string()).optional(),response_types_supported:E.array(E.string()),response_modes_supported:E.array(E.string()).optional(),grant_types_supported:E.array(E.string()).optional(),token_endpoint_auth_methods_supported:E.array(E.string()).optional(),token_endpoint_auth_signing_alg_values_supported:E.array(E.string()).optional(),service_documentation:af.optional(),revocation_endpoint:af.optional(),revocation_endpoint_auth_methods_supported:E.array(E.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:E.array(E.string()).optional(),introspection_endpoint:E.string().optional(),introspection_endpoint_auth_methods_supported:E.array(E.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:E.array(E.string()).optional(),code_challenge_methods_supported:E.array(E.string()).optional(),client_id_metadata_document_supported:E.boolean().optional()}),sf=E.looseObject({issuer:E.string(),authorization_endpoint:af,token_endpoint:af,userinfo_endpoint:af.optional(),jwks_uri:af,registration_endpoint:af.optional(),scopes_supported:E.array(E.string()).optional(),response_types_supported:E.array(E.string()),response_modes_supported:E.array(E.string()).optional(),grant_types_supported:E.array(E.string()).optional(),acr_values_supported:E.array(E.string()).optional(),subject_types_supported:E.array(E.string()),id_token_signing_alg_values_supported:E.array(E.string()),id_token_encryption_alg_values_supported:E.array(E.string()).optional(),id_token_encryption_enc_values_supported:E.array(E.string()).optional(),userinfo_signing_alg_values_supported:E.array(E.string()).optional(),userinfo_encryption_alg_values_supported:E.array(E.string()).optional(),userinfo_encryption_enc_values_supported:E.array(E.string()).optional(),request_object_signing_alg_values_supported:E.array(E.string()).optional(),request_object_encryption_alg_values_supported:E.array(E.string()).optional(),request_object_encryption_enc_values_supported:E.array(E.string()).optional(),token_endpoint_auth_methods_supported:E.array(E.string()).optional(),token_endpoint_auth_signing_alg_values_supported:E.array(E.string()).optional(),display_values_supported:E.array(E.string()).optional(),claim_types_supported:E.array(E.string()).optional(),claims_supported:E.array(E.string()).optional(),service_documentation:E.string().optional(),claims_locales_supported:E.array(E.string()).optional(),ui_locales_supported:E.array(E.string()).optional(),claims_parameter_supported:E.boolean().optional(),request_parameter_supported:E.boolean().optional(),request_uri_parameter_supported:E.boolean().optional(),require_request_uri_registration:E.boolean().optional(),op_policy_uri:af.optional(),op_tos_uri:af.optional(),client_id_metadata_document_supported:E.boolean().optional()}),E.object({...sf.shape,...of.pick({code_challenge_methods_supported:!0}).shape}),E.object({access_token:E.string(),id_token:E.string().optional(),token_type:E.string(),expires_in:E.coerce.number().optional(),scope:E.string().optional(),refresh_token:E.string().optional()}).strip(),E.object({issued_token_type:E.literal(`urn:ietf:params:oauth:token-type:id-jag`),access_token:E.string(),token_type:E.string().optional(),expires_in:E.number().optional(),scope:E.string().optional()}).strip(),E.object({error:E.string(),error_description:E.string().optional(),error_uri:E.string().optional()}),cf=af.optional().or(E.literal(``).transform(()=>void 0)),lf=E.object({redirect_uris:E.array(af),token_endpoint_auth_method:E.string().optional(),grant_types:E.array(E.string()).optional(),response_types:E.array(E.string()).optional(),client_name:E.string().optional(),client_uri:af.optional(),logo_uri:cf,scope:E.string().optional(),contacts:E.array(E.string()).optional(),tos_uri:cf,policy_uri:E.string().optional(),jwks_uri:af.optional(),jwks:E.any().optional(),software_id:E.string().optional(),software_version:E.string().optional(),software_statement:E.string().optional()}).strip(),uf=E.object({client_id:E.string(),client_secret:E.string().optional(),client_id_issued_at:E.number().optional(),client_secret_expires_at:E.number().optional()}).strip(),lf.merge(uf),E.object({error:E.string(),error_description:E.string().optional()}).strip(),E.object({token:E.string(),token_type_hint:E.string().optional()}).strip(),df=`2025-11-25`,ff=`2025-03-26`,pf=[df,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],mf=`io.modelcontextprotocol/related-task`,hf=-32700,gf=-32600,_f=-32601,vf=-32602,yf=-32603,U=function(e){return e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.ResourceNotFound=-32002]=`ResourceNotFound`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`,e}({}),W=class e extends Error{constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`ProtocolError`}static fromError(t,n,r){if(t===U.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new bf(e.elicitations,n)}return new e(t,n,r)}},bf=class extends W{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(U.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},xf=E.lazy(()=>E.union([E.string(),E.number(),E.boolean(),E.null(),E.record(E.string(),xf),E.array(xf)])),Sf=E.record(E.string(),xf),E.array(xf),Cf=E.union([E.string(),E.number().int()]),wf=E.string(),E.looseObject({ttl:E.number().optional(),pollInterval:E.number().optional()}),Tf=E.object({ttl:E.number().optional()}),Ef=E.object({taskId:E.string()}),Df=E.looseObject({progressToken:Cf.optional(),[mf]:Ef.optional()}),Of=E.object({_meta:Df.optional()}),kf=Of.extend({task:Tf.optional()}),Af=E.object({method:E.string(),params:Of.loose().optional()}),jf=E.object({_meta:Df.optional()}),Mf=E.object({method:E.string(),params:jf.loose().optional()}),Nf=E.looseObject({_meta:Df.optional()}),Pf=E.union([E.string(),E.number().int()]),Ff=E.object({jsonrpc:E.literal(`2.0`),id:Pf,...Af.shape}).strict(),If=E.object({jsonrpc:E.literal(`2.0`),...Mf.shape}).strict(),Lf=E.object({jsonrpc:E.literal(`2.0`),id:Pf,result:Nf}).strict(),Rf=E.object({jsonrpc:E.literal(`2.0`),id:Pf.optional(),error:E.object({code:E.number().int(),message:E.string(),data:E.unknown().optional()})}).strict(),zf=E.union([Ff,If,Lf,Rf]),E.union([Lf,Rf]),Bf=Nf.strict(),Vf=jf.extend({requestId:Pf.optional(),reason:E.string().optional()}),Hf=Mf.extend({method:E.literal(`notifications/cancelled`),params:Vf}),Uf=E.object({src:E.string(),mimeType:E.string().optional(),sizes:E.array(E.string()).optional(),theme:E.enum([`light`,`dark`]).optional()}),Wf=E.object({icons:E.array(Uf).optional()}),Gf=E.object({name:E.string(),title:E.string().optional()}),Kf=Gf.extend({...Gf.shape,...Wf.shape,version:E.string(),websiteUrl:E.string().optional(),description:E.string().optional()}),qf=E.intersection(E.object({applyDefaults:E.boolean().optional()}),Sf),Jf=E.preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,E.intersection(E.object({form:qf.optional(),url:Sf.optional()}),Sf.optional())),Yf=E.looseObject({list:Sf.optional(),cancel:Sf.optional(),requests:E.looseObject({sampling:E.looseObject({createMessage:Sf.optional()}).optional(),elicitation:E.looseObject({create:Sf.optional()}).optional()}).optional()}),Xf=E.looseObject({list:Sf.optional(),cancel:Sf.optional(),requests:E.looseObject({tools:E.looseObject({call:Sf.optional()}).optional()}).optional()}),Zf=E.object({experimental:E.record(E.string(),Sf).optional(),sampling:E.object({context:Sf.optional(),tools:Sf.optional()}).optional(),elicitation:Jf.optional(),roots:E.object({listChanged:E.boolean().optional()}).optional(),tasks:Yf.optional(),extensions:E.record(E.string(),Sf).optional()}),Qf=Of.extend({protocolVersion:E.string(),capabilities:Zf,clientInfo:Kf}),$f=Af.extend({method:E.literal(`initialize`),params:Qf}),ep=E.object({experimental:E.record(E.string(),Sf).optional(),logging:Sf.optional(),completions:Sf.optional(),prompts:E.object({listChanged:E.boolean().optional()}).optional(),resources:E.object({subscribe:E.boolean().optional(),listChanged:E.boolean().optional()}).optional(),tools:E.object({listChanged:E.boolean().optional()}).optional(),tasks:Xf.optional(),extensions:E.record(E.string(),Sf).optional()}),tp=Nf.extend({protocolVersion:E.string(),capabilities:ep,serverInfo:Kf,instructions:E.string().optional()}),np=Mf.extend({method:E.literal(`notifications/initialized`),params:jf.optional()}),rp=Af.extend({method:E.literal(`ping`),params:Of.optional()}),ip=E.object({progress:E.number(),total:E.optional(E.number()),message:E.optional(E.string())}),ap=E.object({...jf.shape,...ip.shape,progressToken:Cf}),op=Mf.extend({method:E.literal(`notifications/progress`),params:ap}),sp=Of.extend({cursor:wf.optional()}),cp=Af.extend({params:sp.optional()}),lp=Nf.extend({nextCursor:wf.optional()}),up=E.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),dp=E.object({taskId:E.string(),status:up,ttl:E.union([E.number(),E.null()]),createdAt:E.string(),lastUpdatedAt:E.string(),pollInterval:E.optional(E.number()),statusMessage:E.optional(E.string())}),fp=Nf.extend({task:dp}),pp=jf.merge(dp),mp=Mf.extend({method:E.literal(`notifications/tasks/status`),params:pp}),hp=Af.extend({method:E.literal(`tasks/get`),params:Of.extend({taskId:E.string()})}),gp=Nf.merge(dp),_p=Af.extend({method:E.literal(`tasks/result`),params:Of.extend({taskId:E.string()})}),vp=Nf.loose(),yp=cp.extend({method:E.literal(`tasks/list`)}),bp=lp.extend({tasks:E.array(dp)}),xp=Af.extend({method:E.literal(`tasks/cancel`),params:Of.extend({taskId:E.string()})}),Sp=Nf.merge(dp),Cp=E.object({uri:E.string(),mimeType:E.optional(E.string()),_meta:E.record(E.string(),E.unknown()).optional()}),wp=Cp.extend({text:E.string()}),Tp=E.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Ep=Cp.extend({blob:Tp}),Dp=E.enum([`user`,`assistant`]),Op=E.object({audience:E.array(Dp).optional(),priority:E.number().min(0).max(1).optional(),lastModified:E.iso.datetime({offset:!0}).optional()}),kp=E.object({...Gf.shape,...Wf.shape,uri:E.string(),description:E.optional(E.string()),mimeType:E.optional(E.string()),size:E.optional(E.number()),annotations:Op.optional(),_meta:E.optional(E.looseObject({}))}),Ap=E.object({...Gf.shape,...Wf.shape,uriTemplate:E.string(),description:E.optional(E.string()),mimeType:E.optional(E.string()),annotations:Op.optional(),_meta:E.optional(E.looseObject({}))}),jp=cp.extend({method:E.literal(`resources/list`)}),Mp=lp.extend({resources:E.array(kp)}),Np=cp.extend({method:E.literal(`resources/templates/list`)}),Pp=lp.extend({resourceTemplates:E.array(Ap)}),Fp=Of.extend({uri:E.string()}),Ip=Fp,Lp=Af.extend({method:E.literal(`resources/read`),params:Ip}),Rp=Nf.extend({contents:E.array(E.union([wp,Ep]))}),zp=Mf.extend({method:E.literal(`notifications/resources/list_changed`),params:jf.optional()}),Bp=Fp,Vp=Af.extend({method:E.literal(`resources/subscribe`),params:Bp}),Hp=Fp,Up=Af.extend({method:E.literal(`resources/unsubscribe`),params:Hp}),Wp=jf.extend({uri:E.string()}),Gp=Mf.extend({method:E.literal(`notifications/resources/updated`),params:Wp}),Kp=E.object({name:E.string(),description:E.optional(E.string()),required:E.optional(E.boolean())}),qp=E.object({...Gf.shape,...Wf.shape,description:E.optional(E.string()),arguments:E.optional(E.array(Kp)),_meta:E.optional(E.looseObject({}))}),Jp=cp.extend({method:E.literal(`prompts/list`)}),Yp=lp.extend({prompts:E.array(qp)}),Xp=Of.extend({name:E.string(),arguments:E.record(E.string(),E.string()).optional()}),Zp=Af.extend({method:E.literal(`prompts/get`),params:Xp}),Qp=E.object({type:E.literal(`text`),text:E.string(),annotations:Op.optional(),_meta:E.record(E.string(),E.unknown()).optional()}),$p=E.object({type:E.literal(`image`),data:Tp,mimeType:E.string(),annotations:Op.optional(),_meta:E.record(E.string(),E.unknown()).optional()}),em=E.object({type:E.literal(`audio`),data:Tp,mimeType:E.string(),annotations:Op.optional(),_meta:E.record(E.string(),E.unknown()).optional()}),tm=E.object({type:E.literal(`tool_use`),name:E.string(),id:E.string(),input:E.record(E.string(),E.unknown()),_meta:E.record(E.string(),E.unknown()).optional()}),nm=E.object({type:E.literal(`resource`),resource:E.union([wp,Ep]),annotations:Op.optional(),_meta:E.record(E.string(),E.unknown()).optional()}),rm=kp.extend({type:E.literal(`resource_link`)}),im=E.union([Qp,$p,em,rm,nm]),am=E.object({role:Dp,content:im}),om=Nf.extend({description:E.string().optional(),messages:E.array(am)}),sm=Mf.extend({method:E.literal(`notifications/prompts/list_changed`),params:jf.optional()}),cm=E.object({title:E.string().optional(),readOnlyHint:E.boolean().optional(),destructiveHint:E.boolean().optional(),idempotentHint:E.boolean().optional(),openWorldHint:E.boolean().optional()}),lm=E.object({taskSupport:E.enum([`required`,`optional`,`forbidden`]).optional()}),um=E.object({...Gf.shape,...Wf.shape,description:E.string().optional(),inputSchema:E.object({type:E.literal(`object`),properties:E.record(E.string(),xf).optional(),required:E.array(E.string()).optional()}).catchall(E.unknown()),outputSchema:E.object({type:E.literal(`object`),properties:E.record(E.string(),xf).optional(),required:E.array(E.string()).optional()}).catchall(E.unknown()).optional(),annotations:cm.optional(),execution:lm.optional(),_meta:E.record(E.string(),E.unknown()).optional()}),dm=cp.extend({method:E.literal(`tools/list`)}),fm=lp.extend({tools:E.array(um)}),pm=Nf.extend({content:E.array(im).default([]),structuredContent:E.record(E.string(),E.unknown()).optional(),isError:E.boolean().optional()}),pm.or(Nf.extend({toolResult:E.unknown()})),mm=kf.extend({name:E.string(),arguments:E.record(E.string(),E.unknown()).optional()}),hm=Af.extend({method:E.literal(`tools/call`),params:mm}),gm=Mf.extend({method:E.literal(`notifications/tools/list_changed`),params:jf.optional()}),E.object({autoRefresh:E.boolean().default(!0),debounceMs:E.number().int().nonnegative().default(300)}),_m=E.enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),vm=Of.extend({level:_m}),ym=Af.extend({method:E.literal(`logging/setLevel`),params:vm}),bm=jf.extend({level:_m,logger:E.string().optional(),data:E.unknown()}),xm=Mf.extend({method:E.literal(`notifications/message`),params:bm}),Sm=E.object({name:E.string().optional()}),Cm=E.object({hints:E.array(Sm).optional(),costPriority:E.number().min(0).max(1).optional(),speedPriority:E.number().min(0).max(1).optional(),intelligencePriority:E.number().min(0).max(1).optional()}),wm=E.object({mode:E.enum([`auto`,`required`,`none`]).optional()}),Tm=E.object({type:E.literal(`tool_result`),toolUseId:E.string().describe(`The unique identifier for the corresponding tool call.`),content:E.array(im).default([]),structuredContent:E.object({}).loose().optional(),isError:E.boolean().optional(),_meta:E.record(E.string(),E.unknown()).optional()}),Em=E.discriminatedUnion(`type`,[Qp,$p,em]),Dm=E.discriminatedUnion(`type`,[Qp,$p,em,tm,Tm]),Om=E.object({role:Dp,content:E.union([Dm,E.array(Dm)]),_meta:E.record(E.string(),E.unknown()).optional()}),km=kf.extend({messages:E.array(Om),modelPreferences:Cm.optional(),systemPrompt:E.string().optional(),includeContext:E.enum([`none`,`thisServer`,`allServers`]).optional(),temperature:E.number().optional(),maxTokens:E.number().int(),stopSequences:E.array(E.string()).optional(),metadata:Sf.optional(),tools:E.array(um).optional(),toolChoice:wm.optional()}),Am=Af.extend({method:E.literal(`sampling/createMessage`),params:km}),jm=Nf.extend({model:E.string(),stopReason:E.optional(E.enum([`endTurn`,`stopSequence`,`maxTokens`]).or(E.string())),role:Dp,content:Em}),Mm=Nf.extend({model:E.string(),stopReason:E.optional(E.enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(E.string())),role:Dp,content:E.union([Dm,E.array(Dm)])}),Nm=E.object({type:E.literal(`boolean`),title:E.string().optional(),description:E.string().optional(),default:E.boolean().optional()}),Pm=E.object({type:E.literal(`string`),title:E.string().optional(),description:E.string().optional(),minLength:E.number().optional(),maxLength:E.number().optional(),format:E.enum([`email`,`uri`,`date`,`date-time`]).optional(),default:E.string().optional()}),Fm=E.object({type:E.enum([`number`,`integer`]),title:E.string().optional(),description:E.string().optional(),minimum:E.number().optional(),maximum:E.number().optional(),default:E.number().optional()}),Im=E.object({type:E.literal(`string`),title:E.string().optional(),description:E.string().optional(),enum:E.array(E.string()),default:E.string().optional()}),Lm=E.object({type:E.literal(`string`),title:E.string().optional(),description:E.string().optional(),oneOf:E.array(E.object({const:E.string(),title:E.string()})),default:E.string().optional()}),Rm=E.object({type:E.literal(`string`),title:E.string().optional(),description:E.string().optional(),enum:E.array(E.string()),enumNames:E.array(E.string()).optional(),default:E.string().optional()}),zm=E.union([Im,Lm]),Bm=E.object({type:E.literal(`array`),title:E.string().optional(),description:E.string().optional(),minItems:E.number().optional(),maxItems:E.number().optional(),items:E.object({type:E.literal(`string`),enum:E.array(E.string())}),default:E.array(E.string()).optional()}),Vm=E.object({type:E.literal(`array`),title:E.string().optional(),description:E.string().optional(),minItems:E.number().optional(),maxItems:E.number().optional(),items:E.object({anyOf:E.array(E.object({const:E.string(),title:E.string()}))}),default:E.array(E.string()).optional()}),Hm=E.union([Bm,Vm]),Um=E.union([Rm,zm,Hm]),Wm=E.union([Um,Nm,Pm,Fm]),Gm=kf.extend({mode:E.literal(`form`).optional(),message:E.string(),requestedSchema:E.object({type:E.literal(`object`),properties:E.record(E.string(),Wm),required:E.array(E.string()).optional()})}),Km=kf.extend({mode:E.literal(`url`),message:E.string(),elicitationId:E.string(),url:E.string().url()}),qm=E.union([Gm,Km]),Jm=Af.extend({method:E.literal(`elicitation/create`),params:qm}),Ym=jf.extend({elicitationId:E.string()}),Xm=Mf.extend({method:E.literal(`notifications/elicitation/complete`),params:Ym}),Zm=Nf.extend({action:E.enum([`accept`,`decline`,`cancel`]),content:E.preprocess(e=>e===null?void 0:e,E.record(E.string(),E.union([E.string(),E.number(),E.boolean(),E.array(E.string())])).optional())}),Qm=E.object({type:E.literal(`ref/resource`),uri:E.string()}),$m=E.object({type:E.literal(`ref/prompt`),name:E.string()}),eh=Of.extend({ref:E.union([$m,Qm]),argument:E.object({name:E.string(),value:E.string()}),context:E.object({arguments:E.record(E.string(),E.string()).optional()}).optional()}),th=Af.extend({method:E.literal(`completion/complete`),params:eh}),nh=Nf.extend({completion:E.looseObject({values:E.array(E.string()).max(100),total:E.optional(E.number().int()),hasMore:E.optional(E.boolean())})}),rh=E.object({uri:E.string().startsWith(`file://`),name:E.string().optional(),_meta:E.record(E.string(),E.unknown()).optional()}),ih=Af.extend({method:E.literal(`roots/list`),params:Of.optional()}),ah=Nf.extend({roots:E.array(rh)}),oh=Mf.extend({method:E.literal(`notifications/roots/list_changed`),params:jf.optional()}),sh=E.union([rp,$f,th,ym,Zp,Jp,jp,Np,Lp,Vp,Up,hm,dm,hp,_p,yp,xp]),ch=E.union([Hf,op,np,oh,mp]),E.union([Bf,jm,Mm,Zm,ah,gp,bp,fp]),lh=E.union([rp,Am,Jm,ih,hp,_p,yp,xp]),uh=E.union([Hf,op,xm,Gp,zp,gm,sm,mp,Xm]),E.union([Bf,tp,nh,om,Yp,Mp,Pp,Rp,pm,fm,gp,bp,fp]),dh={ping:Bf,initialize:tp,"completion/complete":nh,"logging/setLevel":Bf,"prompts/get":om,"prompts/list":Yp,"resources/list":Mp,"resources/templates/list":Pp,"resources/read":Rp,"resources/subscribe":Bf,"resources/unsubscribe":Bf,"tools/call":E.union([pm,fp]),"tools/list":fm,"sampling/createMessage":E.union([Mm,fp]),"elicitation/create":E.union([Zm,fp]),"roots/list":ah,"tasks/get":gp,"tasks/result":Nf,"tasks/list":bp,"tasks/cancel":Sp},fh=Sd([...sh.options,...lh.options]),ph=Sd([...ch.options,...uh.options]),mh=e=>Ff.safeParse(e).success,hh=e=>If.safeParse(e).success,gh=e=>Lf.safeParse(e).success,_h=e=>Rf.safeParse(e).success,vh=e=>kf.safeParse(e).success,yh=e=>$f.safeParse(e).success,bh=e=>np.safeParse(e).success,xh=class{_taskStore;_taskMessageQueue;_taskProgressTokens=new Map;_requestResolvers=new Map;_options;_host;constructor(e){this._options=e,this._taskStore=e.taskStore,this._taskMessageQueue=e.taskMessageQueue}bind(e){this._host=e,this._taskStore&&(e.registerHandler(`tasks/get`,async(e,t)=>{let n=e.params;return{...await this.handleGetTask(n.taskId,t.sessionId)}}),e.registerHandler(`tasks/result`,async(t,n)=>{let r=t.params;return await this.handleGetTaskPayload(r.taskId,n.sessionId,n.mcpReq.signal,async t=>{await e.sendOnResponseStream(t,n.mcpReq.id)})}),e.registerHandler(`tasks/list`,async(e,t)=>{let n=e.params;return await this.handleListTasks(n?.cursor,t.sessionId)}),e.registerHandler(`tasks/cancel`,async(e,t)=>{let n=e.params;return await this.handleCancelTask(n.taskId,t.sessionId)}))}get _requireHost(){if(!this._host)throw new W(U.InternalError,`TaskManager is not bound to a Protocol host — call bind() first`);return this._host}get taskStore(){return this._taskStore}get _requireTaskStore(){if(!this._taskStore)throw new W(U.InternalError,`TaskStore is not configured`);return this._taskStore}get taskMessageQueue(){return this._taskMessageQueue}async*requestStream(e,t,n){let r=this._requireHost,{task:i}=n??{};if(!i){try{yield{type:`result`,result:await r.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof Error?e:Error(String(e))}}return}let a;try{let i=await r.request(e,fp,n);if(i.task)a=i.task.taskId,yield{type:`taskCreated`,task:i.task};else throw new W(U.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:a},n);if(yield{type:`taskStatus`,task:e},kd(e.status)){switch(e.status){case`completed`:yield{type:`result`,result:await this.getTaskResult({taskId:a},t,n)};break;case`failed`:yield{type:`error`,error:new W(U.InternalError,`Task ${a} failed`)};break;case`cancelled`:yield{type:`error`,error:new W(U.InternalError,`Task ${a} was cancelled`)}}return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:a},t,n)};return}let r=e.pollInterval??this._options.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof Error?e:Error(String(e))}}}async getTask(e,t){return this._requireHost.request({method:`tasks/get`,params:e},gp,t)}async getTaskResult(e,t,n){return this._requireHost.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this._requireHost.request({method:`tasks/list`,params:e},bp,t)}async cancelTask(e,t){return this._requireHost.request({method:`tasks/cancel`,params:e},Sp,t)}async handleGetTask(e,t){let n=await this._requireTaskStore.getTask(e,t);if(!n)throw new W(U.InvalidParams,`Failed to retrieve task: Task not found`);return n}async handleGetTaskPayload(e,t,n,r){let i=async()=>{if(this._taskMessageQueue){let n;for(;n=await this._taskMessageQueue.dequeue(e,t);){if(n.type===`response`||n.type===`error`){let e=n.message,t=e.id,r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),n.type===`response`)r(e);else{let t=e;r(new W(t.error.code,t.error.message,t.error.data))}}else{let e=n.type===`response`?`Response`:`Error`;this._host?.reportError(Error(`${e} handler missing for request ${t}`))}continue}await r(n.message)}}let a=await this._requireTaskStore.getTask(e,t);if(!a)throw new W(U.InvalidParams,`Task not found: ${e}`);if(!kd(a.status))return await this._waitForTaskUpdate(a.pollInterval,n),await i();let o=await this._requireTaskStore.getTaskResult(e,t);return await this._clearTaskQueue(e),{...o,_meta:{...o._meta,[mf]:{taskId:e}}}};return await i()}async handleListTasks(e,t){try{let{tasks:n,nextCursor:r}=await this._requireTaskStore.listTasks(e,t);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new W(U.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}async handleCancelTask(e,t){try{let n=await this._requireTaskStore.getTask(e,t);if(!n)throw new W(U.InvalidParams,`Task not found: ${e}`);if(kd(n.status))throw new W(U.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._requireTaskStore.updateTaskStatus(e,`cancelled`,`Client cancelled task execution.`,t),await this._clearTaskQueue(e);let r=await this._requireTaskStore.getTask(e,t);if(!r)throw new W(U.InvalidParams,`Task not found after cancellation: ${e}`);return{_meta:{},...r}}catch(e){throw e instanceof W?e:new W(U.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}prepareOutboundRequest(e,t,n,r,i){let{task:a,relatedTask:o}=t??{};a&&(e.params={...e.params,task:a}),o&&(e.params={...e.params,_meta:{...e.params?._meta,[mf]:o}});let s=o?.taskId;return s?(this._requestResolvers.set(n,r),this._enqueueTaskMessage(s,{type:`request`,message:e,timestamp:Date.now()}).catch(e=>{i(e)}),!0):!1}extractInboundTaskContext(e,t){let n=(e.params?._meta)?.[mf]?.taskId,r=vh(e.params)?e.params.task:void 0,i;return this._taskStore&&(i={id:n,store:this.createRequestTaskStore(e,t),requestedTtl:r?.ttl}),!n&&!r&&!i?{}:{relatedTaskId:n,taskCreationParams:r,taskContext:i}}wrapSendNotification(e,t){return async n=>{await t(n,{relatedTask:{taskId:e}})}}wrapSendRequest(e,t,n){return async(r,i,a)=>{let o={...a};e&&!o.relatedTask&&(o.relatedTask={taskId:e});let s=o.relatedTask?.taskId??e;return s&&t&&await t.updateTaskStatus(s,`input_required`),await n(r,i,o)}}handleResponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);return n?(this._requestResolvers.delete(t),gh(e)?n(e):n(new W(e.error.code,e.error.message,e.error.data)),!0):!1}shouldPreserveProgressHandler(e,t){if(gh(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;if(typeof e.taskId==`string`)return this._taskProgressTokens.set(e.taskId,t),!0}}return!1}async routeNotification(e,t){let n=t?.relatedTask?.taskId;if(!n)return!1;let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta,[mf]:t.relatedTask}}};return await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()}),!0}async routeResponse(e,t,n){return!e||!this._taskMessageQueue?!1:(await(_h(t)?this._enqueueTaskMessage(e,{type:`error`,message:t,timestamp:Date.now()},n):this._enqueueTaskMessage(e,{type:`response`,message:t,timestamp:Date.now()},n)),!0)}createRequestTaskStore(e,t){let n=this._requireTaskStore,r=this._host;return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new W(U.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,i,a)=>{await n.storeTaskResult(e,i,a,t);let o=await n.getTask(e,t);if(o){let t=mp.parse({method:`notifications/tasks/status`,params:o});await r?.notification(t),kd(o.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,i,a)=>{let o=await n.getTask(e,t);if(!o)throw new W(U.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(kd(o.status))throw new W(U.InvalidParams,`Cannot update task "${e}" from terminal status "${o.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,i,a,t);let s=await n.getTask(e,t);if(s){let t=mp.parse({method:`notifications/tasks/status`,params:s});await r?.notification(t),kd(s.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}processInboundRequest(e,t){let n=this.extractInboundTaskContext(e,t.sessionId),r=n?.relatedTaskId,i=r?this.wrapSendNotification(r,t.sendNotification):e=>t.sendNotification(e),a=r?this.wrapSendRequest(r,n?.taskContext?.store,t.sendRequest):n?.taskContext?this.wrapSendRequest(``,n.taskContext.store,t.sendRequest):t.sendRequest,o=!!n?.taskCreationParams;return{taskContext:n?.taskContext,sendNotification:i,sendRequest:a,routeResponse:async e=>r?this.routeResponse(r,e,t.sessionId):!1,hasTaskCreationParams:o,validateInbound:o?()=>this._requireHost.assertTaskHandlerCapability(e.method):void 0}}processOutboundRequest(e,t,n,r,i){return this._requireHost.enforceStrictCapabilities&&t?.task&&this._requireHost.assertTaskCapability(e.method),{queued:this.prepareOutboundRequest(e,t,n,r,i)}}processInboundResponse(e,t){return this.handleResponse(e)?{consumed:!0,preserveProgress:!1}:{consumed:!1,preserveProgress:this.shouldPreserveProgressHandler(e,t)}}async processOutboundNotification(e,t){if(await this.routeNotification(e,t))return{queued:!0};let n={...e,jsonrpc:`2.0`};return t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta,[mf]:t.relatedTask}}}),{queued:!1,jsonrpcNotification:n}}onClose(){this._taskProgressTokens.clear(),this._requestResolvers.clear()}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);await this._taskMessageQueue.enqueue(e,t,n,this._options.maxTaskQueueSize)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&mh(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new W(U.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._host?.reportError(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=e??this._options.defaultTaskPollInterval??1e3;return new Promise((e,r)=>{if(t.aborted){r(new W(U.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new W(U.InvalidRequest,`Request cancelled`))},{once:!0})})}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._host?.removeProgressHandler(t),this._taskProgressTokens.delete(e))}},Sh=class extends xh{constructor(){super({})}processInboundRequest(e,t){let n=vh(e.params)&&!!e.params.task;return{taskContext:void 0,sendNotification:e=>t.sendNotification(e),sendRequest:t.sendRequest,routeResponse:async()=>!1,hasTaskCreationParams:n,validateInbound:n?()=>this._requireHost.assertTaskHandlerCapability(e.method):void 0}}async processOutboundNotification(e,t){return{queued:!1,jsonrpcNotification:{...e,jsonrpc:`2.0`}}}},Ch=6e4,wh=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_taskManager;_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??pf,this._taskManager=e?.tasks?new xh(e.tasks):new Sh,this._bindTaskManager(),this.setNotificationHandler(`notifications/cancelled`,e=>{this._oncancel(e)}),this.setNotificationHandler(`notifications/progress`,e=>{this._onprogress(e)}),this.setRequestHandler(`ping`,e=>({}))}get taskManager(){return this._taskManager}_bindTaskManager(){let e=this._taskManager,t={request:(e,t,n)=>this._requestWithSchema(e,t,n),notification:(e,t)=>this.notification(e,t),reportError:e=>this._onerror(e),removeProgressHandler:e=>this._progressHandlers.delete(e),registerHandler:(e,t)=>{let n=Cd(e);this._requestHandlers.set(e,(e,r)=>(n.parse(e),t(e,r)))},sendOnResponseStream:async(e,t)=>{await this._transport?.send(e,{relatedRequestId:t})},enforceStrictCapabilities:this._options?.enforceStrictCapabilities===!0,assertTaskCapability:e=>this.assertTaskCapability(e),assertTaskHandlerCapability:e=>this.assertTaskHandlerCapability(e)};e.bind(t)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new H(V.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),gh(e)||_h(e)?this._onresponse(e):mh(e)?this._onrequest(e,t):hh(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskManager.onClose(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new H(V.ConnectionClosed,`Connection closed`);this._transport=void 0;try{this.onclose?.()}finally{for(let t of e.values())t(n);for(let e of t.values())e.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i={sessionId:r?.sessionId,sendNotification:(t,n)=>this.notification(t,{...n,relatedRequestId:e.id}),sendRequest:(t,n,r)=>this._requestWithSchema(t,n,{...r,relatedRequestId:e.id})},a=this._taskManager.processInboundRequest(e,i),o=a.sendNotification,s=a.sendRequest,c=a.taskContext,l=a.routeResponse,u=[];if(a.validateInbound&&u.push(a.validateInbound),n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:U.MethodNotFound,message:`Method not found`}};l(t).then(e=>{e||r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))}).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`)));return}let d=new AbortController;this._requestHandlerAbortControllers.set(e.id,d);let f={sessionId:r?.sessionId,mcpReq:{id:e.id,method:e.method,_meta:e.params?._meta,signal:d.signal,send:(e,t)=>s(e,xd(e.method),t),notify:o},http:t?.authInfo?{authInfo:t.authInfo}:void 0,task:c},p=this.buildContext(f,t);Promise.resolve().then(()=>{for(let e of u)e()}).then(()=>n(e,p)).then(async t=>{if(d.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};await l(n)||await r?.send(n)},async t=>{if(d.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:U.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};await l(n)||await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===d&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._taskManager.processInboundResponse(e,t);if(n.consumed)return;let r=n.preserveProgress,i=this._responseHandlers.get(t);if(i===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),r||this._progressHandlers.delete(t),gh(e)?i(e):i(W.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t){let n=xd(e.method);return this._requestWithSchema(e,n,t)}_requestWithSchema(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}=n??{},o,s;return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++;s=d;let f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta,progressToken:d}});let p=e=>{this._progressHandlers.delete(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof H?e:new H(V.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Od(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),o=()=>p(n?.signal?.reason),n?.signal?.addEventListener(`abort`,o,{once:!0});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(new H(V.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))},g=!1;try{this._taskManager.processOutboundRequest(f,n,d,h,e=>{this._progressHandlers.delete(d),l(e)}).queued&&(g=!0)}catch(e){this._progressHandlers.delete(d),l(e);return}g||this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._progressHandlers.delete(d),l(e)})}).finally(()=>{o&&n?.signal?.removeEventListener(`abort`,o),s!==void 0&&(this._responseHandlers.delete(s),this._cleanupTimeout(s))})}async notification(e,t){if(!this._transport)throw new H(V.NotConnected,`Not connected`);this.assertNotificationCapability(e.method);let n=await this._taskManager.processOutboundNotification(e,t),r=n.queued,i=n.queued?void 0:n.jsonrpcNotification;if(!r){if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(e.method),this._transport&&this._transport?.send(i,t).catch(e=>this._onerror(e))});return}await this._transport.send(i,t)}}setRequestHandler(e,t){this.assertRequestHandlerCapability(e);let n=Cd(e);this._requestHandlers.set(e,(e,r)=>{let i=n.parse(e);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=wd(e);this._notificationHandlers.set(e,e=>{let r=n.parse(e);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}},Th=class{_buffer;append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){for(;this._buffer;){let e=this._buffer.indexOf(`
176
- `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);this._buffer=this._buffer.subarray(e+1);try{return Fd(t)}catch(e){if(e instanceof SyntaxError)continue;throw e}}return null}clear(){this._buffer=void 0}},Eh=/^[A-Za-z0-9._-]{1,128}$/,Dh=1e6,Oh=1e6,kh=1e4,Ah=1e6,jh=class e{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,n){if(e.length>t)throw Error(`${n} exceeds maximum length of ${t} characters (got ${e.length})`)}template;parts;get variableNames(){return this.parts.flatMap(e=>typeof e==`string`?[]:e.names)}constructor(t){e.validateLength(t,Dh,`Template`),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){let n=[],r=``,i=0,a=0;for(;i<t.length;)if(t[i]===`{`){r&&=(n.push(r),``);let o=t.indexOf(`}`,i);if(o===-1)throw Error(`Unclosed template expression`);if(a++,a>kh)throw Error(`Template contains too many expressions (max ${kh})`);let s=t.slice(i+1,o),c=this.getOperator(s),l=s.includes(`*`),u=this.getNames(s),d=u[0];for(let t of u)e.validateLength(t,Oh,`Variable name`);n.push({name:d,operator:c,names:u,exploded:l}),i=o+1}else r+=t[i],i++;return r&&n.push(r),n}getOperator(e){return[`+`,`#`,`.`,`/`,`?`,`&`].find(t=>e.startsWith(t))||``}getNames(e){let t=this.getOperator(e);return e.slice(t.length).split(`,`).map(e=>e.replace(`*`,``).trim()).filter(e=>e.length>0)}encodeValue(t,n){return e.validateLength(t,Oh,`Variable value`),n===`+`||n===`#`?encodeURI(t):encodeURIComponent(t)}expandPart(e,t){if(e.operator===`?`||e.operator===`&`){let n=e.names.map(n=>{let r=t[n];return r===void 0?``:`${n}=${Array.isArray(r)?r.map(t=>this.encodeValue(t,e.operator)).join(`,`):this.encodeValue(r.toString(),e.operator)}`}).filter(e=>e.length>0);return n.length===0?``:(e.operator===`?`?`?`:`&`)+n.join(`&`)}if(e.names.length>1){let n=e.names.map(e=>t[e]).filter(e=>e!==void 0);return n.length===0?``:n.map(e=>Array.isArray(e)?e[0]:e).join(`,`)}let n=t[e.name];if(n===void 0)return``;let r=(Array.isArray(n)?n:[n]).map(t=>this.encodeValue(t,e.operator));switch(e.operator){case``:return r.join(`,`);case`+`:return r.join(`,`);case`#`:return`#`+r.join(`,`);case`.`:return`.`+r.join(`.`);case`/`:return`/`+r.join(`/`);default:return r.join(`,`)}}expand(e){let t=``,n=!1;for(let r of this.parts){if(typeof r==`string`){t+=r;continue}let i=this.expandPart(r,e);i&&(t+=(r.operator===`?`||r.operator===`&`)&&n?i.replace(`?`,`&`):i,(r.operator===`?`||r.operator===`&`)&&(n=!0))}return t}escapeRegExp(e){return e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(t){let n=[];for(let n of t.names)e.validateLength(n,Oh,`Variable name`);if(t.operator===`?`||t.operator===`&`){for(let e=0;e<t.names.length;e++){let r=t.names[e],i=e===0?`\\`+t.operator:`&`;n.push({pattern:i+this.escapeRegExp(r)+`=([^&]+)`,name:r})}return n}let r,i=t.name;switch(t.operator){case``:r=t.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`;break;case`+`:case`#`:r=`(.+)`;break;case`.`:r=String.raw`\.([^/,]+)`;break;case`/`:r=`/`+(t.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`);break;default:r=`([^/]+)`}return n.push({pattern:r,name:i}),n}match(t){e.validateLength(t,Dh,`URI`);let n=`^`,r=[];for(let e of this.parts)if(typeof e==`string`)n+=this.escapeRegExp(e);else{let t=this.partToRegExp(e);for(let{pattern:i,name:a}of t)n+=i,r.push({name:a,exploded:e.exploded})}n+=`$`,e.validateLength(n,Ah,`Generated regex pattern`);let i=new RegExp(n),a=t.match(i);if(!a)return null;let o={};for(let[e,t]of r.entries()){let{name:n,exploded:r}=t,i=a[e+1],s=n.replace(`*`,``);o[s]=r&&i.includes(`,`)?i.split(`,`):i}return o}},Mh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),Nh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Mh();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),G=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=Mh(),n=Nh();var r=Mh();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=Nh();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=O(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=O(this.rhs,e,n),this}get names(){return D(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=O(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(k(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>E(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(A(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=O(this.condition,e,t),this}get names(){let e=super.names;return D(e,this.condition),this.else&&E(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=O(this.iteration,e,t),this}get names(){return E(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return D(D(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=O(this.iterable,e,t),this}get names(){return E(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&E(e,this.catch.names),this.finally&&E(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var ee=class extends m{render(e){return`finally`+super.render(e)}};ee.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
177
- `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new ee,this.code(n)),this._endBlockNode(T,ee)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function E(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function D(e,n){return n instanceof t._CodeOrName?E(e,n.names):e}function O(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function k(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function A(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ie(e)}`}e.not=A;let j=re(e.operators.AND);function te(...e){return e.reduce(j)}e.and=te;let M=re(e.operators.OR);function ne(...e){return e.reduce(M)}e.or=ne;function re(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ie(n)} ${e} ${ie(r)}`}function ie(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),K=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=G(),n=Mh();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),Ph=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),Fh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=G(),n=K(),r=Ph();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),Ih=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Fh(),n=G(),r=Ph(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),Lh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),Rh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),zh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=Lh(),n=Rh(),r=Fh(),i=G(),a=K();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
176
+ `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);this._buffer=this._buffer.subarray(e+1);try{return Fd(t)}catch(e){if(e instanceof SyntaxError)continue;throw e}}return null}clear(){this._buffer=void 0}},Eh=/^[A-Za-z0-9._-]{1,128}$/,Dh=1e6,Oh=1e6,kh=1e4,Ah=1e6,jh=class e{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,n){if(e.length>t)throw Error(`${n} exceeds maximum length of ${t} characters (got ${e.length})`)}template;parts;get variableNames(){return this.parts.flatMap(e=>typeof e==`string`?[]:e.names)}constructor(t){e.validateLength(t,Dh,`Template`),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){let n=[],r=``,i=0,a=0;for(;i<t.length;)if(t[i]===`{`){r&&=(n.push(r),``);let o=t.indexOf(`}`,i);if(o===-1)throw Error(`Unclosed template expression`);if(a++,a>kh)throw Error(`Template contains too many expressions (max ${kh})`);let s=t.slice(i+1,o),c=this.getOperator(s),l=s.includes(`*`),u=this.getNames(s),d=u[0];for(let t of u)e.validateLength(t,Oh,`Variable name`);n.push({name:d,operator:c,names:u,exploded:l}),i=o+1}else r+=t[i],i++;return r&&n.push(r),n}getOperator(e){return[`+`,`#`,`.`,`/`,`?`,`&`].find(t=>e.startsWith(t))||``}getNames(e){let t=this.getOperator(e);return e.slice(t.length).split(`,`).map(e=>e.replace(`*`,``).trim()).filter(e=>e.length>0)}encodeValue(t,n){return e.validateLength(t,Oh,`Variable value`),n===`+`||n===`#`?encodeURI(t):encodeURIComponent(t)}expandPart(e,t){if(e.operator===`?`||e.operator===`&`){let n=e.names.map(n=>{let r=t[n];return r===void 0?``:`${n}=${Array.isArray(r)?r.map(t=>this.encodeValue(t,e.operator)).join(`,`):this.encodeValue(r.toString(),e.operator)}`}).filter(e=>e.length>0);return n.length===0?``:(e.operator===`?`?`?`:`&`)+n.join(`&`)}if(e.names.length>1){let n=e.names.map(e=>t[e]).filter(e=>e!==void 0);return n.length===0?``:n.map(e=>Array.isArray(e)?e[0]:e).join(`,`)}let n=t[e.name];if(n===void 0)return``;let r=(Array.isArray(n)?n:[n]).map(t=>this.encodeValue(t,e.operator));switch(e.operator){case``:return r.join(`,`);case`+`:return r.join(`,`);case`#`:return`#`+r.join(`,`);case`.`:return`.`+r.join(`.`);case`/`:return`/`+r.join(`/`);default:return r.join(`,`)}}expand(e){let t=``,n=!1;for(let r of this.parts){if(typeof r==`string`){t+=r;continue}let i=this.expandPart(r,e);i&&(t+=(r.operator===`?`||r.operator===`&`)&&n?i.replace(`?`,`&`):i,(r.operator===`?`||r.operator===`&`)&&(n=!0))}return t}escapeRegExp(e){return e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(t){let n=[];for(let n of t.names)e.validateLength(n,Oh,`Variable name`);if(t.operator===`?`||t.operator===`&`){for(let e=0;e<t.names.length;e++){let r=t.names[e],i=e===0?`\\`+t.operator:`&`;n.push({pattern:i+this.escapeRegExp(r)+`=([^&]+)`,name:r})}return n}let r,i=t.name;switch(t.operator){case``:r=t.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`;break;case`+`:case`#`:r=`(.+)`;break;case`.`:r=String.raw`\.([^/,]+)`;break;case`/`:r=`/`+(t.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`);break;default:r=`([^/]+)`}return n.push({pattern:r,name:i}),n}match(t){e.validateLength(t,Dh,`URI`);let n=`^`,r=[];for(let e of this.parts)if(typeof e==`string`)n+=this.escapeRegExp(e);else{let t=this.partToRegExp(e);for(let{pattern:i,name:a}of t)n+=i,r.push({name:a,exploded:e.exploded})}n+=`$`,e.validateLength(n,Ah,`Generated regex pattern`);let i=new RegExp(n),a=t.match(i);if(!a)return null;let o={};for(let[e,t]of r.entries()){let{name:n,exploded:r}=t,i=a[e+1],s=n.replace(`*`,``);o[s]=r&&i.includes(`,`)?i.split(`,`):i}return o}},Mh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),Nh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Mh();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),G=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=Mh(),n=Nh();var r=Mh();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=Nh();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=O(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=O(this.rhs,e,n),this}get names(){return D(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=O(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(k(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>E(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(te(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=O(this.condition,e,t),this}get names(){let e=super.names;return D(e,this.condition),this.else&&E(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=O(this.iteration,e,t),this}get names(){return E(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return D(D(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=O(this.iterable,e,t),this}get names(){return E(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&E(e,this.catch.names),this.finally&&E(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var ee=class extends m{render(e){return`finally`+super.render(e)}};ee.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
177
+ `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new ee,this.code(n)),this._endBlockNode(T,ee)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function E(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function D(e,n){return n instanceof t._CodeOrName?E(e,n.names):e}function O(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function k(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function te(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ie(e)}`}e.not=te;let A=re(e.operators.AND);function ne(...e){return e.reduce(A)}e.and=ne;let j=re(e.operators.OR);function M(...e){return e.reduce(j)}e.or=M;function re(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ie(n)} ${e} ${ie(r)}`}function ie(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),K=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=G(),n=Mh();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),Ph=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),Fh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=G(),n=K(),r=Ph();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),Ih=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Fh(),n=G(),r=Ph(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),Lh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),Rh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),zh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=Lh(),n=Rh(),r=Fh(),i=G(),a=K();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
178
178
  || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
179
179
  || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(c,null);return;case`array`:r.elseIf((0,i._)`${s} === "string" || ${s} === "number"
180
- || ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Bh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=G(),n=K();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),Vh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=G(),n=K(),r=Ph(),i=K();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),Hh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=G(),n=Ph(),r=Vh(),i=Fh();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Uh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=G(),n=K();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),Wh=B(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),Gh=B(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),Kh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=K(),n=Wh(),r=Gh(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),qh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Ih(),n=zh(),r=Rh(),i=zh(),a=Bh(),o=Hh(),s=Uh(),c=G(),l=Ph(),u=Kh(),d=K(),f=Fh();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&k(e),E(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),A(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&k(e),D(e),O(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),ee(e)}function T(e,t){if(e.opts.jtd)return te(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);te(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function ee(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function E(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function D(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function O(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function k({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function A(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&j(e),t.return((0,c._)`${l.default.errors} === 0`))}function j({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function te(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>ue(e,`$ref`,h.all.$ref.definition));return}p.jtd||ne(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),M(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):M(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function M(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&ue(e,n.keyword,n.definition,t.type)})}function ne(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(re(e,t),e.opts.allowUnionTypes||ie(e,t),ae(e,e.dataTypes))}function re(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{se(e.dataTypes,t)||ce(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),N(e,t)}}function ie(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ce(e,`use allowUnionTypes to allow union type keyword`)}function ae(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>oe(t,e))&&ce(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function oe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function se(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function N(e,t){let n=[];for(let r of e.dataTypes)se(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ce(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var le=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,P(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=le;function ue(e,t,n,r){let i=new le(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let de=/^\/(?:[^~]|~0|~1)*$/,fe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function P(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!de.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=fe.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=P})),Jh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),Yh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Kh();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),Xh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=G(),n=Jh(),r=Ph(),i=Kh(),a=K(),o=qh();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),Zh=B(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),Qh=B(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function i(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let a=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function s(e,t,n){if(e.length){let r=i(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function c(e){let t=0,n={error:!1,address:``,zone:``},r=[],a=[],c=!1,l=!1,u=s;for(let i=0;i<e.length;i++){let s=e[i];if(s!==`[`&&s!==`]`){if(s===`:`){if(c===!0&&(l=!0),!u(a,r,n))break;if(++t>7){n.error=!0;break}i>0&&e[i-1]===`:`&&(c=!0),r.push(`:`);continue}if(s===`%`){if(!u(a,r,n))break;u=o}else{a.push(s);continue}}}return a.length&&(u===o?n.zone=a.join(``):l?r.push(a.join(``)):r.push(i(a))),n.address=r.join(``),n}function l(e){if(u(e,`:`)<2)return{host:e,isIPV6:!1};let t=c(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function u(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function d(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}function f(e,t){let n=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function p(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let t=l(n);n=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:a,recomposeAuthority:p,normalizeComponentEncoding:f,removeDotSegments:d,isIPv4:r,isUUID:n,normalizeIPv6:l,stringArrayToHexStripped:i}})),$h=B(((e,t)=>{let{isUUID:n}=Qh(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),eg=B(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=Qh(),{SCHEMES:c,getSchemeHandler:l}=$h();function u(e,t){return typeof e==`string`?e=m(g(e,t),t):typeof e==`object`&&(e=g(m(e,t),t)),e}function d(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=f(g(e,r),g(t,r),r,!0);return r.skipEscape=!0,m(i,r)}function f(e,t,n,i){let a={};return i||(e=g(m(e,n),n),t=g(m(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function p(e,t,n){return typeof e==`string`?(e=unescape(e),e=m(a(g(e,n),!0),{...n,skipEscape:!0})):typeof e==`object`&&(e=m(a(e,!0),{...n,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=m(a(g(t,n),!0),{...n,skipEscape:!0})):typeof t==`object`&&(t=m(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function m(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},a=Object.assign({},t),o=[],s=l(a.scheme||n.scheme);s&&s.serialize&&s.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),a.reference!==`suffix`&&n.scheme&&o.push(n.scheme,`:`);let c=i(n);if(c!==void 0&&(a.reference!==`suffix`&&o.push(`//`),o.push(c),n.path&&n.path[0]!==`/`&&o.push(`/`)),n.path!==void 0){let e=n.path;!a.absolutePath&&(!s||!s.absolutePath)&&(e=r(e)),c===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),o.push(e)}return n.query!==void 0&&o.push(`?`,n.query),n.fragment!==void 0&&o.push(`#`,n.fragment),o.join(``)}let h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let c=e.match(h);if(c){if(i.scheme=c[1],i.userinfo=c[3],i.host=c[4],i.port=parseInt(c[5],10),i.path=c[6]||``,i.query=c[7],i.fragment=c[8],isNaN(i.port)&&(i.port=c[5]),i.host){if(o(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),a=e.isIPV6}else a=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let t=l(r.scheme||i.scheme);if(!r.unicodeSupport&&(!t||!t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&a===!1&&s(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=unescape(i.host))),i.path&&=escape(unescape(i.path)),i.fragment&&=encodeURI(decodeURIComponent(i.fragment))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return i}let _={SCHEMES:c,normalize:u,resolve:d,resolveComponent:f,equal:p,serialize:m,parse:g};t.exports=_,t.exports.default=_,t.exports.fastUri=_})),tg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=eg();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),ng=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=qh();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=G();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});let r=Jh(),i=Yh(),a=Lh(),o=Xh(),s=G(),c=Kh(),l=zh(),u=K(),d=Zh(),f=tg(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=E(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(O.call(this,n,t),!t)return(0,u.eachItem)(n,e=>k.call(this,e)),this;j.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>k.call(this,e,r):e=>r.type.forEach(t=>k.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=M(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let ee={log(){},warn(){},error(){}};function E(e){if(e===!1)return ee;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let D=/^[a-z_$][a-z0-9_$:-]*$/i;function O(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!D.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function k(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?A.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function A(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function j(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=M(t)),e.validateSchema=this.compile(t,!0))}let te={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function M(e){return{anyOf:[e,te]}}})),rg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),ig=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=Yh(),n=Vh(),r=G(),i=Ph(),a=Xh(),o=K(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);if(h instanceof a.SchemaEnv)return _(h);return v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}}if(l.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}}e.callRef=l,e.default=s})),ag=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rg(),n=ig();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),og=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),sg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),cg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),lg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=K(),r=cg();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),ug=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Vh(),n=K(),r=G();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),dg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),fg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Vh(),n=G(),r=K();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),pg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),mg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Wh();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),hg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=zh(),n=G(),r=K(),i=mg();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),gg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=K(),r=mg();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),_g=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=K(),r=mg();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),vg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=og(),n=sg(),r=lg(),i=ug(),a=dg(),o=fg(),s=pg(),c=hg(),l=gg(),u=_g();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),yg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=G(),n=K(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),bg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=G(),n=K(),r=Vh(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),xg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=bg();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Sg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=K(),r=Vh(),i=yg();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),Cg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=K();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),wg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=G(),n=K(),r=Vh();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
180
+ || ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Bh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=G(),n=K();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),Vh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=G(),n=K(),r=Ph(),i=K();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),Hh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=G(),n=Ph(),r=Vh(),i=Fh();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Uh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=G(),n=K();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),Wh=B(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),Gh=B(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),Kh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=K(),n=Wh(),r=Gh(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),qh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Ih(),n=zh(),r=Rh(),i=zh(),a=Bh(),o=Hh(),s=Uh(),c=G(),l=Ph(),u=Kh(),d=K(),f=Fh();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&k(e),E(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),te(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&k(e),D(e),O(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),ee(e)}function T(e,t){if(e.opts.jtd)return ne(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);ne(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function ee(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function E(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function D(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function O(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function k({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function te(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&A(e),t.return((0,c._)`${l.default.errors} === 0`))}function A({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function ne(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>ue(e,`$ref`,h.all.$ref.definition));return}p.jtd||M(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),j(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):j(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function j(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&ue(e,n.keyword,n.definition,t.type)})}function M(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(re(e,t),e.opts.allowUnionTypes||ie(e,t),ae(e,e.dataTypes))}function re(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{se(e.dataTypes,t)||ce(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),N(e,t)}}function ie(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ce(e,`use allowUnionTypes to allow union type keyword`)}function ae(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>oe(t,e))&&ce(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function oe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function se(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function N(e,t){let n=[];for(let r of e.dataTypes)se(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ce(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var le=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,P(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=le;function ue(e,t,n,r){let i=new le(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let de=/^\/(?:[^~]|~0|~1)*$/,fe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function P(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!de.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=fe.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=P})),Jh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),Yh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Kh();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),Xh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=G(),n=Jh(),r=Ph(),i=Kh(),a=K(),o=qh();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),Zh=B(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),Qh=B(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function i(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let a=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function s(e,t,n){if(e.length){let r=i(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function c(e){let t=0,n={error:!1,address:``,zone:``},r=[],a=[],c=!1,l=!1,u=s;for(let i=0;i<e.length;i++){let s=e[i];if(s!==`[`&&s!==`]`){if(s===`:`){if(c===!0&&(l=!0),!u(a,r,n))break;if(++t>7){n.error=!0;break}i>0&&e[i-1]===`:`&&(c=!0),r.push(`:`);continue}if(s===`%`){if(!u(a,r,n))break;u=o}else{a.push(s);continue}}}return a.length&&(u===o?n.zone=a.join(``):l?r.push(a.join(``)):r.push(i(a))),n.address=r.join(``),n}function l(e){if(u(e,`:`)<2)return{host:e,isIPV6:!1};let t=c(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function u(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function d(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}function f(e,t){let n=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function p(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let t=l(n);n=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:a,recomposeAuthority:p,normalizeComponentEncoding:f,removeDotSegments:d,isIPv4:r,isUUID:n,normalizeIPv6:l,stringArrayToHexStripped:i}})),$h=B(((e,t)=>{let{isUUID:n}=Qh(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),eg=B(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=Qh(),{SCHEMES:c,getSchemeHandler:l}=$h();function u(e,t){return typeof e==`string`?e=m(g(e,t),t):typeof e==`object`&&(e=g(m(e,t),t)),e}function d(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=f(g(e,r),g(t,r),r,!0);return r.skipEscape=!0,m(i,r)}function f(e,t,n,i){let a={};return i||(e=g(m(e,n),n),t=g(m(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function p(e,t,n){return typeof e==`string`?(e=unescape(e),e=m(a(g(e,n),!0),{...n,skipEscape:!0})):typeof e==`object`&&(e=m(a(e,!0),{...n,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=m(a(g(t,n),!0),{...n,skipEscape:!0})):typeof t==`object`&&(t=m(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function m(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},a=Object.assign({},t),o=[],s=l(a.scheme||n.scheme);s&&s.serialize&&s.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),a.reference!==`suffix`&&n.scheme&&o.push(n.scheme,`:`);let c=i(n);if(c!==void 0&&(a.reference!==`suffix`&&o.push(`//`),o.push(c),n.path&&n.path[0]!==`/`&&o.push(`/`)),n.path!==void 0){let e=n.path;!a.absolutePath&&(!s||!s.absolutePath)&&(e=r(e)),c===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),o.push(e)}return n.query!==void 0&&o.push(`?`,n.query),n.fragment!==void 0&&o.push(`#`,n.fragment),o.join(``)}let h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let c=e.match(h);if(c){if(i.scheme=c[1],i.userinfo=c[3],i.host=c[4],i.port=parseInt(c[5],10),i.path=c[6]||``,i.query=c[7],i.fragment=c[8],isNaN(i.port)&&(i.port=c[5]),i.host){if(o(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),a=e.isIPV6}else a=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let t=l(r.scheme||i.scheme);if(!r.unicodeSupport&&(!t||!t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&a===!1&&s(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=unescape(i.host))),i.path&&=escape(unescape(i.path)),i.fragment&&=encodeURI(decodeURIComponent(i.fragment))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return i}let _={SCHEMES:c,normalize:u,resolve:d,resolveComponent:f,equal:p,serialize:m,parse:g};t.exports=_,t.exports.default=_,t.exports.fastUri=_})),tg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=eg();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),ng=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=qh();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=G();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});let r=Jh(),i=Yh(),a=Lh(),o=Xh(),s=G(),c=Kh(),l=zh(),u=K(),d=Zh(),f=tg(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=E(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(O.call(this,n,t),!t)return(0,u.eachItem)(n,e=>k.call(this,e)),this;A.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>k.call(this,e,r):e=>r.type.forEach(t=>k.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=j(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let ee={log(){},warn(){},error(){}};function E(e){if(e===!1)return ee;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let D=/^[a-z_$][a-z0-9_$:-]*$/i;function O(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!D.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function k(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?te.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function te(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function A(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=j(t)),e.validateSchema=this.compile(t,!0))}let ne={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function j(e){return{anyOf:[e,ne]}}})),rg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),ig=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=Yh(),n=Vh(),r=G(),i=Ph(),a=Xh(),o=K(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);if(h instanceof a.SchemaEnv)return _(h);return v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}}if(l.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}}e.callRef=l,e.default=s})),ag=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rg(),n=ig();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),og=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),sg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),cg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),lg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=K(),r=cg();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),ug=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Vh(),n=K(),r=G();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),dg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),fg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Vh(),n=G(),r=K();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),pg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),mg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Wh();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),hg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=zh(),n=G(),r=K(),i=mg();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),gg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=K(),r=mg();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),_g=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=K(),r=mg();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),vg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=og(),n=sg(),r=lg(),i=ug(),a=dg(),o=fg(),s=pg(),c=hg(),l=gg(),u=_g();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),yg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=G(),n=K(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),bg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=G(),n=K(),r=Vh(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),xg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=bg();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Sg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=K(),r=Vh(),i=yg();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),Cg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=K();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),wg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=G(),n=K(),r=Vh();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
181
181
  missingProperty: ${i},
182
182
  depsCount: ${n},
183
183
  deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),Tg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=K();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),Eg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Vh(),n=G(),r=Ph(),i=K();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),Dg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qh(),n=Vh(),r=K(),i=Eg();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),Og=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Vh(),n=G(),r=K(),i=K();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),kg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=K();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),Ag=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Vh().validateUnion,error:{message:`must match a schema in anyOf`}}})),jg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=K();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),Mg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=K();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),Ng=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=K(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),Pg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=K();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),Fg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=yg(),n=xg(),r=bg(),i=Sg(),a=Cg(),o=wg(),s=Tg(),c=Eg(),l=Dg(),u=Og(),d=kg(),f=Ag(),p=jg(),m=Mg(),h=Ng(),g=Pg();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),Ig=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),Lg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Ig().default]})),Rg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),zg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ag(),n=vg(),r=Fg(),i=Lg(),a=Rg();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Bg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),Vg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Bg(),r=Xh(),i=Yh(),a=K();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),Hg=B(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),Ug=B(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=ng(),r=zg(),i=Vg(),a=Hg(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=qh();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=G();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=Jh();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=Yh();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Wg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:ee,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function ee(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Gg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=Ug(),n=G(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),Kg=B(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=Wg(),r=Gg(),i=G(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),qg=Ug(),Jg=tf(Kg(),1),Yg=class{_ajv;constructor(e){this._ajv=e??Kd()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},Xg=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft??`2020-12`}getValidator(e){let t=new hd(e,this.draft,this.shortcircuit);return e=>{let n=t.validate(e);return n.valid?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:n.errors.map(e=>`${e.instanceLocation}: ${e.error}`).join(`; `)}}}}}));function Qg(){throw Error(`StdioServerTransport is not supported in this environment. Use StreamableHTTPServerTransport instead.`)}var $g,e_=I((()=>{Zg(),$g={get stdin(){return Qg()},get stdout(){return Qg()}}})),t_=Ke({AjvJsonSchemaValidator:()=>Yg,CfWorkerJsonSchemaValidator:()=>Xg,DEFAULT_NEGOTIATED_PROTOCOL_VERSION:()=>ff,DEFAULT_REQUEST_TIMEOUT_MSEC:()=>Ch,ExperimentalMcpServerTasks:()=>b_,ExperimentalServerTasks:()=>x_,INTERNAL_ERROR:()=>yf,INVALID_PARAMS:()=>vf,INVALID_REQUEST:()=>gf,InMemoryTaskMessageQueue:()=>y_,InMemoryTaskStore:()=>v_,JSONRPC_VERSION:()=>`2.0`,LATEST_PROTOCOL_VERSION:()=>df,METHOD_NOT_FOUND:()=>_f,McpServer:()=>C_,OAuthError:()=>rf,OAuthErrorCode:()=>nf,PARSE_ERROR:()=>hf,ProtocolError:()=>W,ProtocolErrorCode:()=>U,RELATED_TASK_META_KEY:()=>mf,ReadBuffer:()=>Th,ResourceTemplate:()=>w_,SUPPORTED_PROTOCOL_VERSIONS:()=>pf,SdkError:()=>H,SdkErrorCode:()=>V,Server:()=>S_,StdioServerTransport:()=>D_,UriTemplate:()=>jh,UrlElicitationRequiredError:()=>bf,WebStandardStreamableHTTPServerTransport:()=>O_,assertClientRequestTaskCapability:()=>o_,assertCompleteRequestPrompt:()=>Ed,assertCompleteRequestResourceTemplate:()=>Dd,assertToolsCallTaskCapability:()=>a_,checkResourceAllowed:()=>yd,completable:()=>n_,createFetchWithInit:()=>Vd,deserializeMessage:()=>Fd,fromJsonSchema:()=>g_,getDisplayName:()=>bd,hostHeaderValidationResponse:()=>h_,isCompletable:()=>r_,isInitializeRequest:()=>yh,isInitializedNotification:()=>bh,isJSONRPCErrorResponse:()=>_h,isJSONRPCNotification:()=>hh,isJSONRPCRequest:()=>mh,isJSONRPCResultResponse:()=>gh,isTaskAugmentedRequestParams:()=>vh,isTerminal:()=>kd,localhostAllowedHostnames:()=>m_,parseJSONRPCMessage:()=>Td,resourceUrlFromServerUrl:()=>vd,serializeMessage:()=>Id,takeResult:()=>Pd,toArrayAsync:()=>Nd,validateHostHeader:()=>p_});function n_(e,t){return Object.defineProperty(e,__,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function r_(e){return!!e&&typeof e==`object`&&__ in e}function i_(e){return e[__]?.complete}function a_(e,t,n){if(!e)throw new H(V.CapabilityNotSupported,`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw new H(V.CapabilityNotSupported,`${n} does not support task creation for tools/call (required for ${t})`)}function o_(e,t,n){if(!e)throw new H(V.CapabilityNotSupported,`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw new H(V.CapabilityNotSupported,`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw new H(V.CapabilityNotSupported,`${n} does not support task creation for elicitation/create (required for ${t})`)}}function s_(e,t){if(`createTask`in t){let n=t;return async(t,r)=>{if(!r.task?.store)throw Error(`No task store provided.`);let i={...r,task:{store:r.task.store,requestedTtl:r.task?.requestedTtl}};return e?n.createTask(t,i):n.createTask(i)}}if(e){let e=t;return async(t,n)=>e(t,n)}let n=t;return async(e,t)=>n(t)}function c_(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await Wd(t,n);if(!a.success)throw new W(U.InvalidParams,`Invalid arguments for prompt ${e}: ${a.error}`);return r(a.data,i)}}{let e=n;return async(t,n)=>e(n)}}function l_(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}function u_(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function d_(e){return e?.type===`optional`}function f_(e){return d_(e)?e.def?.innerType??e:e}function p_(e,t){if(!e)return{ok:!1,errorCode:`missing_host`,message:`Missing Host header`};let n;try{n=new URL(`http://${e}`).hostname}catch{return{ok:!1,errorCode:`invalid_host_header`,message:`Invalid Host header: ${e}`,hostHeader:e}}return t.includes(n)?{ok:!0,hostname:n}:{ok:!1,errorCode:`invalid_host`,message:`Invalid Host: ${n}`,hostHeader:e,hostname:n}}function m_(){return[`localhost`,`127.0.0.1`,`[::1]`]}function h_(e,t){let n=p_(e.headers.get(`host`),t);if(!n.ok)return Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:n.message},id:null},{status:403,headers:{"Content-Type":`application/json`}})}function g_(e,t){return qd(e,t??(k_??=new Xg))}var __,v_,y_,b_,x_,S_,C_,w_,T_,E_,D_,O_,k_,A_=I((()=>{Zg(),e_(),__=Symbol.for(`mcp.completable`),v_=class{tasks=new Map;cleanupTimers=new Map;generateTaskId(){return crypto.randomUUID().replaceAll(`-`,``)}async createTask(e,t,n,r){let i=this.generateTaskId();if(this.tasks.has(i))throw Error(`Task with ID ${i} already exists`);let a=e.ttl??null,o=new Date().toISOString(),s={taskId:i,status:`working`,ttl:a,createdAt:o,lastUpdatedAt:o,pollInterval:e.pollInterval??1e3};if(this.tasks.set(i,{task:s,request:n,requestId:t,sessionId:r}),a){let e=setTimeout(()=>{this.tasks.delete(i),this.cleanupTimers.delete(i)},a);this.cleanupTimers.set(i,e)}return s}getStoredTask(e,t){let n=this.tasks.get(e);if(n&&(t===void 0||n.sessionId===void 0||n.sessionId===t))return n}async getTask(e,t){let n=this.getStoredTask(e,t);return n?{...n.task}:null}async storeTaskResult(e,t,n,r){let i=this.getStoredTask(e,r);if(!i)throw Error(`Task with ID ${e} not found`);if(kd(i.task.status))throw Error(`Cannot store result for task ${e} in terminal status '${i.task.status}'. Task results can only be stored once.`);if(i.result=n,i.task.status=t,i.task.lastUpdatedAt=new Date().toISOString(),i.task.ttl){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.tasks.delete(e),this.cleanupTimers.delete(e)},i.task.ttl);this.cleanupTimers.set(e,n)}}async getTaskResult(e,t){let n=this.getStoredTask(e,t);if(!n)throw Error(`Task with ID ${e} not found`);if(!n.result)throw Error(`Task ${e} has no result stored`);return n.result}async updateTaskStatus(e,t,n,r){let i=this.getStoredTask(e,r);if(!i)throw Error(`Task with ID ${e} not found`);if(kd(i.task.status))throw Error(`Cannot update task ${e} from terminal status '${i.task.status}' to '${t}'. Terminal states (completed, failed, cancelled) cannot transition to other states.`);if(i.task.status=t,n&&(i.task.statusMessage=n),i.task.lastUpdatedAt=new Date().toISOString(),kd(t)&&i.task.ttl){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.tasks.delete(e),this.cleanupTimers.delete(e)},i.task.ttl);this.cleanupTimers.set(e,n)}}async listTasks(e,t){let n=[...this.tasks.entries()].filter(([,e])=>t===void 0||e.sessionId===void 0||e.sessionId===t).map(([e])=>e),r=0;if(e){let t=n.indexOf(e);if(t===-1)throw Error(`Invalid cursor: ${e}`);r=t+1}let i=n.slice(r,r+10);return{tasks:i.map(e=>({...this.tasks.get(e).task})),nextCursor:r+10<n.length?i.at(-1):void 0}}cleanup(){for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear(),this.tasks.clear()}getAllTasks(){return[...this.tasks.values()].map(e=>({...e.task}))}},y_=class{queues=new Map;getQueueKey(e,t){return e}getQueue(e,t){let n=this.getQueueKey(e,t),r=this.queues.get(n);return r||(r=[],this.queues.set(n,r)),r}async enqueue(e,t,n,r){let i=this.getQueue(e,n);if(r!==void 0&&i.length>=r)throw Error(`Task message queue overflow: queue size (${i.length}) exceeds maximum (${r})`);i.push(t)}async dequeue(e,t){return this.getQueue(e,t).shift()}async dequeueAll(e,t){let n=this.getQueueKey(e,t),r=this.queues.get(n)??[];return this.queues.delete(n),r}},b_=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},x_=class{constructor(e){this._server=e}get _module(){return this._server.taskManager}requestStream(e,t){let n=xd(e.method);return this._module.requestStream(e,n,t)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new H(V.CapabilityNotSupported,`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages.at(-1),n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages.at(-2):void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw new H(V.CapabilityNotSupported,`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw new H(V.CapabilityNotSupported,`Client does not support form elicitation.`)}let i=r===`form`&&e.mode!==`form`?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},t)}async getTask(e,t){return this._module.getTask({taskId:e},t)}async getTaskResult(e,t){return this._module.getTaskResult({taskId:e},vp,t)}async listTasks(e,t){return this._module.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._module.cancelTask({taskId:e},t)}},S_=class extends wh{_clientCapabilities;_clientVersion;_capabilities;_instructions;_jsonSchemaValidator;_experimental;oninitialized;constructor(e,t){if(super({...t,tasks:Ad(t?.capabilities?.tasks)}),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Xg,t?.capabilities?.tasks){let{taskStore:e,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i,...a}=t.capabilities.tasks;this._capabilities.tasks=a}this.setRequestHandler(`initialize`,e=>this._oninitialize(e)),this.setNotificationHandler(`notifications/initialized`,()=>this.oninitialized?.()),this._capabilities.logging&&this._registerLoggingHandler()}_registerLoggingHandler(){this.setRequestHandler(`logging/setLevel`,async(e,t)=>{let n=t.sessionId||t.http?.req?.headers.get(`mcp-session-id`)||void 0,{level:r}=e.params,i=Od(_m,r);return i.success&&this._loggingLevels.set(n,i.data),{}})}buildContext(e,t){let n=e.http||t?.request||t?.closeSSEStream||t?.closeStandaloneSSEStream;return{...e,mcpReq:{...e.mcpReq,log:(e,t,n)=>this.sendLoggingMessage({level:e,data:t,logger:n}),elicitInput:(e,t)=>this.elicitInput(e,t),requestSampling:(e,t)=>this.createMessage(e,t)},http:n?{...e.http,req:t?.request,closeSSE:t?.closeSSEStream,closeStandaloneSSE:t?.closeStandaloneSSEStream}:void 0}}get experimental(){return this._experimental||={tasks:new x_(this)},this._experimental}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(_m.options.map((e,t)=>[e,t]));isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1};registerCapabilities(e){if(this.transport)throw new H(V.AlreadyConnected,`Cannot register capabilities after connecting to transport`);let t=!!this._capabilities.logging;this._capabilities=Md(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}setRequestHandler(e,t){return e===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=Od(hm,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new W(U.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=Od(fp,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new W(U.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=Od(pm,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new W(U.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw new H(V.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw new H(V.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw new H(V.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw new H(V.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw new H(V.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw new H(V.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw new H(V.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw new H(V.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case`completion/complete`:if(!this._capabilities.completions)throw new H(V.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw new H(V.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw new H(V.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw new H(V.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw new H(V.CapabilityNotSupported,`Server does not support tools (required for ${e})`)}}assertTaskCapability(e){o_(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){a_(this._capabilities?.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo;let n=this._supportedProtocolVersions.includes(t)?t:this._supportedProtocolVersions[0]??`2025-11-25`;return this.transport?.setProtocolVersion?.(n),{protocolVersion:n,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this._requestWithSchema({method:`ping`},Bf)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new H(V.CapabilityNotSupported,`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages.at(-1),n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages.at(-2):void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw new W(U.InvalidParams,`The last message must contain only tool_result content if any is present`);if(!o)throw new W(U.InvalidParams,`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new W(U.InvalidParams,`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this._requestWithSchema({method:`sampling/createMessage`,params:e},Mm,t):this._requestWithSchema({method:`sampling/createMessage`,params:e},jm,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw new H(V.CapabilityNotSupported,`Client does not support url elicitation.`);let n=e;return this._requestWithSchema({method:`elicitation/create`,params:n},Zm,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw new H(V.CapabilityNotSupported,`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this._requestWithSchema({method:`elicitation/create`,params:n},Zm,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new W(U.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof W?e:new W(U.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new H(V.CapabilityNotSupported,`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this._requestWithSchema({method:`roots/list`,params:e},ah,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}},C_=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_experimental;constructor(e,t){this.server=new S_(e,t)}get experimental(){return this._experimental||={tasks:new b_(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(`tools/list`),this.server.assertCanSetRequestHandler(`tools/call`),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler(`tools/list`,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?Hd(t.inputSchema,`input`):T_,annotations:t.annotations,execution:t.execution,_meta:t._meta};return t.outputSchema&&(n.outputSchema=Hd(t.outputSchema,`output`)),n})})),this.server.setRequestHandler(`tools/call`,async(e,t)=>{let n=this._registeredTools[e.params.name];if(!n)throw new W(U.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new W(U.InvalidParams,`Tool ${e.params.name} disabled`);try{let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new W(U.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new W(U.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof W&&e.code===U.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await Wd(e.inputSchema,t??{});if(!r.success)throw new W(U.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${r.error}`);return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new W(U.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await Wd(e.outputSchema,t.structuredContent);if(!r.success)throw new W(U.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${r.error}`)}async executeToolHandler(e,t,n){return e.executor(t,n)}async handleAutomaticTaskPolling(e,t,n){if(!n.task?.store)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=await e.executor(r,n),a=i.task.taskId,o=i.task,s=o.pollInterval??5e3;for(;o.status!==`completed`&&o.status!==`failed`&&o.status!==`cancelled`;){await new Promise(e=>setTimeout(e,s));let e=await n.task.store.getTask(a);if(!e)throw new W(U.InternalError,`Task ${a} not found during polling`);o=e}return await n.task.store.getTaskResult(a)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(`completion/complete`),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(`completion/complete`,async e=>{switch(e.params.ref.type){case`ref/prompt`:return Ed(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Dd(e),this.handleResourceCompletion(e,e.params.ref);default:throw new W(U.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new W(U.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new W(U.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return E_;let r=f_(u_(n.argsSchema)?.[e.params.argument.name]);if(!r_(r))return E_;let i=i_(r);return i?l_(await i(e.params.argument.value,e.params.context)):E_}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return E_;throw new W(U.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?l_(await r(e.params.argument.value,e.params.context)):E_}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(`resources/list`),this.server.assertCanSetRequestHandler(`resources/templates/list`),this.server.assertCanSetRequestHandler(`resources/read`),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler(`resources/list`,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(`resources/templates/list`,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(`resources/read`,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new W(U.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new W(U.ResourceNotFound,`Resource ${n} not found`)}),!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(`prompts/list`),this.server.assertCanSetRequestHandler(`prompts/get`),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler(`prompts/list`,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Gd(t.argsSchema):void 0,_meta:t._meta}))})),this.server.setRequestHandler(`prompts/get`,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new W(U.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new W(U.InvalidParams,`Prompt ${e.params.name} disabled`);return n.handler(e.params.arguments,t)}),!0)}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i,a){let o=r,s=i,c={title:t,description:n,argsSchema:r,_meta:a,handler:c_(e,r,i),enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=c)),t.title!==void 0&&(c.title=t.title),t.description!==void 0&&(c.description=t.description),t._meta!==void 0&&(c._meta=t._meta);let n=!1;t.argsSchema!==void 0&&(c.argsSchema=t.argsSchema,o=t.argsSchema,n=!0),t.callback!==void 0&&(s=t.callback,n=!0),n&&(c.handler=c_(e,o,s)),t.enabled!==void 0&&(c.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=c,r){let e=u_(r);e&&Object.values(e).some(e=>r_(f_(e)))&&this.setCompletionRequestHandler()}return c}_createRegisteredTool(e,t,n,r,i,a,o,s,c){zd(e);let l=c,u={title:t,description:n,inputSchema:r,outputSchema:i,annotations:a,execution:o,_meta:s,handler:c,executor:s_(r,c),enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&zd(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=u)),t.title!==void 0&&(u.title=t.title),t.description!==void 0&&(u.description=t.description);let n=!1;t.paramsSchema!==void 0&&(u.inputSchema=t.paramsSchema,n=!0),t.callback!==void 0&&(u.handler=t.callback,l=t.callback,n=!0),n&&(u.executor=s_(u.inputSchema,l)),t.outputSchema!==void 0&&(u.outputSchema=t.outputSchema),t.annotations!==void 0&&(u.annotations=t.annotations),t._meta!==void 0&&(u._meta=t._meta),t.enabled!==void 0&&(u.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a,_meta:o}=t,s=this._createRegisteredPrompt(e,r,i,a,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},w_=class{_uriTemplate;constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new jh(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},T_={type:`object`,properties:{}},E_={completion:{values:[],hasMore:!1}},D_=class{_readBuffer=new Th;_started=!1;_closed=!1;constructor(e=$g.stdin,t=$g.stdout){this._stdin=e,this._stdout=t}onclose;onerror;onmessage;_ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()};_onerror=e=>{this.onerror?.(e)};_onstdouterror=e=>{this.onerror?.(e),this.close().catch(()=>{})};async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror),this._stdout.on(`error`,this._onstdouterror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._closed||(this._closed=!0,this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdout.off(`error`,this._onstdouterror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.())}send(e){return this._closed?Promise.reject(Error(`StdioServerTransport is closed`)):new Promise((t,n)=>{let r=Id(e),i=!1,a=e=>{i||(i=!0,this._stdout.off(`error`,a),this._stdout.off(`drain`,o),n(e))},o=()=>{i||(i=!0,this._stdout.off(`error`,a),this._stdout.off(`drain`,o),t())};if(this._stdout.once(`error`,a),this._stdout.write(r)){if(i)return;i=!0,this._stdout.off(`error`,a),t()}else i||this._stdout.once(`drain`,o)})}},O_=class{sessionIdGenerator;_started=!1;_streamMapping=new Map;_requestToStreamMapping=new Map;_requestResponseMap=new Map;_initialized=!1;_enableJsonResponse=!1;_standaloneSseStreamId=`_GET_stream`;_eventStore;_onsessioninitialized;_onsessionclosed;_allowedHosts;_allowedOrigins;_enableDnsRebindingProtection;_retryInterval;_supportedProtocolVersions;sessionId;onclose;onerror;onmessage;constructor(e={}){this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval,this._supportedProtocolVersions=e.supportedProtocolVersions??pf}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}setSupportedProtocolVersions(e){this._supportedProtocolVersions=e}createJsonErrorResponse(e,t,n,r){let i={code:t,message:n};return r?.data!==void 0&&(i.data=r.data),Response.json({jsonrpc:`2.0`,error:i,id:null},{status:e,headers:{"Content-Type":`application/json`,...r?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,n,r){if(!this._eventStore||r<`2025-11-25`)return;let i=await this._eventStore.storeEvent(n,{}),a=`id: ${i}\ndata: \n\n`;this._retryInterval!==void 0&&(a=`id: ${i}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(a))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),o={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(o[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),new Response(a,{headers:o})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let n={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(n[`mcp-session-id`]=this.sessionId);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{}}),o=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(i,r,t,e))try{i.close()}catch{}}});return this._streamMapping.set(o,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(o);try{i.close()}catch{}}}),new Response(a,{headers:n})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,n,r){try{let i=`event: message
@@ -206,13 +206,13 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
206
206
  `).filter(e=>e.includes(`✓`)||e.includes(`✔`)).map(e=>e.replace(/[│┃|]/g,``).replace(/.*[✓✔]\s*/,``).replace(/:.*/,``).trim()).filter(Boolean))}return(i.length===0||i.includes(`amp`))&&wy(e,r)&&o.push(`Amp`),{command:r,agents:o}}function wy(e,t){let o=u(x(),`.config`,`amp`,`settings.json`),s={};if(n(o))try{s=JSON.parse(i(o,`utf-8`))}catch{return!1}let[c,...d]=Ay(t);if(!c)return!1;let f=s[`amp.mcpServers`]??{};f[e]={command:c,args:d},s[`amp.mcpServers`]=f;let p=l(o);return n(p)||r(p,{recursive:!0}),a(o,JSON.stringify(s,null,2)+`
207
207
  `),!0}function Ty(e,t){return Dy(e)?`${e} --mcp`:`${t} ${ky(e)} --mcp`}function Ey(){let e=(process.argv[1]?.replace(/\\/g,`/`))?.match(/^(.+)\/node_modules\/(.+)$/);return e?{root:e[1],entry:e[2]}:null}function Dy(e){let t=process.argv[1];if(!t)return!1;let n=Ey();if(n)return!n.entry.startsWith(`.bin/`)&&!Oy(n.root,e);let r=t.replace(/\\/g,`/`).split(`/`).pop();return r===e||r===`${e}.cmd`||r===`${e}.ps1`}function Oy(e,t){try{let n=JSON.parse(i(u(e,`package.json`),`utf-8`));return[n.dependencies,n.devDependencies,n.optionalDependencies,n.peerDependencies].some(e=>t in(e??{}))}catch{return!1}}function ky(e){let t=Ey();if(!t)return e;try{let n=JSON.parse(i(u(t.root,`package.json`),`utf-8`)).dependencies??{},r=n[e];if(!r||Object.keys(n).length!==1)return e;if(/^https?:\/\//.test(r)||r.startsWith(`file:`))return r;if(/^\d/.test(r))return`${e}@${r}`}catch{}return e}function Ay(e){let t=[],n=``,r=null;for(let i=0;i<e.length;i++){let a=e[i];r?a===r?r=null:n+=a:a===`"`||a===`'`?r=a:a===` `?(n&&t.push(n),n=``):n+=a}return n&&t.push(n),t}function jy(e,t){return new Promise((n,r)=>{m(e,t,(e,t,i)=>{if(e){let n=i?.trim()||t?.trim()||e.message;r(Error(n))}else n({stdout:t,stderr:i})})})}var My=I((()=>{Qe()}));function Ny(){return Uy.filter(e=>e.detect())}function Py(t,n={}){let r=n.global!==!1,i=n.cwd||process.cwd(),a=r?q:i,o=s.join(a,`.agents`,`skills`),c=n.agents??Ny(),l=[],u=[];for(let n of Iy(t)){let t=s.join(o,n.name);Ry(t),e.mkdirSync(t,{recursive:!0}),n.root?e.copyFileSync(s.join(n.dir,`SKILL.md`),s.join(t,`SKILL.md`)):e.cpSync(n.dir,t,{recursive:!0}),l.push(t);for(let a of c){if(a.universal)continue;let o=r?a.globalSkillsDir:s.join(i,a.projectSkillsDir),c=s.join(o,n.name);if(zy(c)!==zy(t))try{Ry(c),e.mkdirSync(s.dirname(c),{recursive:!0});let n=zy(s.dirname(c)),r=zy(t),i=s.relative(n,r);e.symlinkSync(i,c),u.push({agent:a.name,path:c,mode:`symlink`})}catch{try{e.cpSync(t,c,{recursive:!0}),u.push({agent:a.name,path:c,mode:`copy`})}catch{}}}}return{paths:l,agents:u}}function Fy(e,t={}){let n=t.global!==!1,r=t.cwd||process.cwd(),i=n?q:r;Ry(s.join(i,`.agents`,`skills`,e));for(let t of Ny()){if(t.universal)continue;let i=n?t.globalSkillsDir:s.join(r,t.projectSkillsDir);Ry(s.join(i,e))}}function Iy(t){let n=[];function r(t){let i;try{i=e.readdirSync(t,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let i=s.join(t,a.name),o=s.join(i,`SKILL.md`);if(e.existsSync(o)){let t=e.readFileSync(o,`utf8`).match(/^name:\s*(.+)$/m);n.push({name:Ly(t?.[1]??a.name),dir:i})}r(i)}}r(t);let i=s.join(t,`SKILL.md`);if(e.existsSync(i)){let r=Ly(e.readFileSync(i,`utf8`).match(/^name:\s*(.+)$/m)?.[1]??`skill`);n.some(e=>e.name===r)||n.push({name:r,dir:t,root:!0})}return n}function Ly(e){return e.trim().replace(/[/\\]/g,`-`).replace(/\.\./g,``).slice(0,255)}function Ry(t){try{e.lstatSync(t).isSymbolicLink()?e.unlinkSync(t):e.rmSync(t,{recursive:!0,force:!0})}catch{}}function zy(t){try{return e.realpathSync(t)}catch{let n=s.dirname(t);if(n===t)return t;try{return s.join(e.realpathSync(n),s.relative(n,t))}catch{return t}}}var q,By,Vy,Hy,Uy,Wy=I((()=>{q=y.homedir(),By=process.env.XDG_CONFIG_HOME||s.join(q,`.config`),Vy=process.env.CLAUDE_CONFIG_DIR?.trim()||s.join(q,`.claude`),Hy=process.env.CODEX_HOME?.trim()||s.join(q,`.codex`),Uy=[{name:`Amp`,globalSkillsDir:s.join(By,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>e.existsSync(s.join(By,`amp`))},{name:`Cline`,globalSkillsDir:s.join(q,`.agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>e.existsSync(s.join(q,`.cline`))},{name:`Codex`,globalSkillsDir:s.join(Hy,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>e.existsSync(Hy)},{name:`Cursor`,globalSkillsDir:s.join(q,`.cursor`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>e.existsSync(s.join(q,`.cursor`))},{name:`Gemini CLI`,globalSkillsDir:s.join(q,`.gemini`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>e.existsSync(s.join(q,`.gemini`))},{name:`GitHub Copilot`,globalSkillsDir:s.join(q,`.copilot`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>e.existsSync(s.join(q,`.copilot`))},{name:`Kimi CLI`,globalSkillsDir:s.join(By,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>e.existsSync(s.join(q,`.kimi`))},{name:`OpenCode`,globalSkillsDir:s.join(By,`opencode`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>e.existsSync(s.join(By,`opencode`))},{name:`Claude Code`,globalSkillsDir:s.join(Vy,`skills`),projectSkillsDir:`.claude/skills`,universal:!1,detect:()=>e.existsSync(Vy)},{name:`Windsurf`,globalSkillsDir:s.join(q,`.codeium`,`windsurf`,`skills`),projectSkillsDir:`.windsurf/skills`,universal:!1,detect:()=>e.existsSync(s.join(q,`.codeium`,`windsurf`))},{name:`Continue`,globalSkillsDir:s.join(q,`.continue`,`skills`),projectSkillsDir:`.continue/skills`,universal:!1,detect:()=>e.existsSync(s.join(q,`.continue`))},{name:`Roo`,globalSkillsDir:s.join(q,`.roo`,`skills`),projectSkillsDir:`.roo/skills`,universal:!1,detect:()=>e.existsSync(s.join(q,`.roo`))},{name:`Kilo`,globalSkillsDir:s.join(q,`.kilocode`,`skills`),projectSkillsDir:`.kilocode/skills`,universal:!1,detect:()=>e.existsSync(s.join(q,`.kilocode`))},{name:`Goose`,globalSkillsDir:s.join(By,`goose`,`skills`),projectSkillsDir:`.goose/skills`,universal:!1,detect:()=>e.existsSync(s.join(By,`goose`))},{name:`Augment`,globalSkillsDir:s.join(q,`.augment`,`skills`),projectSkillsDir:`.augment/skills`,universal:!1,detect:()=>e.existsSync(s.join(q,`.augment`))},{name:`Trae`,globalSkillsDir:s.join(q,`.trae`,`skills`),projectSkillsDir:`.trae/skills`,universal:!1,detect:()=>e.existsSync(s.join(q,`.trae`))},{name:`Junie`,globalSkillsDir:s.join(q,`.junie`,`skills`),projectSkillsDir:`.junie/skills`,universal:!1,detect:()=>e.existsSync(s.join(q,`.junie`))},{name:`Crush`,globalSkillsDir:s.join(By,`crush`,`skills`),projectSkillsDir:`.crush/skills`,universal:!1,detect:()=>e.existsSync(s.join(By,`crush`))},{name:`Kiro CLI`,globalSkillsDir:s.join(q,`.kiro`,`skills`),projectSkillsDir:`.kiro/skills`,universal:!1,detect:()=>e.existsSync(s.join(q,`.kiro`))},{name:`Qwen Code`,globalSkillsDir:s.join(q,`.qwen`,`skills`),projectSkillsDir:`.qwen/skills`,universal:!1,detect:()=>e.existsSync(s.join(q,`.qwen`))},{name:`OpenHands`,globalSkillsDir:s.join(q,`.openhands`,`skills`),projectSkillsDir:`.openhands/skills`,universal:!1,detect:()=>e.existsSync(s.join(q,`.openhands`))}]}));async function Gy(e,t,n={}){let{depth:r=1,description:i,global:a=!0}=n,o=n.cwd??(a?Jy():process.cwd());await ul();let s=new Map;i&&s.set(e,i);let l=hy(e,$b(t,[],s,n.rootCommand),r,s),u=await C.mkdtemp(c.join(b.tmpdir(),`incur-skills-${e}-`));try{let r=[];for(let t of l){let n=t.dir?c.join(u,t.dir,`SKILL.md`):c.join(u,`SKILL.md`);await C.mkdir(c.dirname(n),{recursive:!0}),await C.writeFile(n,`${t.content}\n`);let i=ix(t.content);r.push({name:i.name??(t.dir||e),description:i.description})}if(n.include)for(let t of n.include){let n=t===`_root`?`SKILL.md`:c.join(t,`SKILL.md`);for await(let i of C.glob(n,{cwd:o}))try{let n=await C.readFile(c.resolve(o,i),`utf8`),a=ix(n),s=t===`_root`?a.name??e:c.basename(c.dirname(i)),l=c.join(u,s,`SKILL.md`);await C.mkdir(c.dirname(l),{recursive:!0}),await C.writeFile(l,n),r.some(e=>e.name===s)||r.push({name:s,description:a.description,external:!0})}catch{}}let{paths:i,agents:s}=Py(u,{global:a,cwd:o}),d=new Set(i.map(e=>c.basename(e))),f=Zy(e);if(f?.skills)for(let e of f.skills)d.has(e)||Fy(e,{global:a,cwd:o});return Xy(e,vy($b(t,[],new Map,n.rootCommand)),[...d],[...i,...s.map(e=>e.path)]),{skills:r.sort((e,t)=>e.name.localeCompare(t.name)),paths:i,agents:s}}finally{await C.rm(u,{recursive:!0,force:!0})}}async function Ky(e,t,n={}){let{depth:r=1,description:i}=n,a=n.cwd??process.cwd();await ul();let o=new Map;i&&o.set(e,i);let s=hy(e,$b(t,[],o,n.rootCommand),r,o),l=[],u=Qy(e,{cwd:a});for(let t of s){let n=ix(t.content),r=n.name??(t.dir||e);l.push({name:r,description:n.description,installed:u.has(r)})}if(n.include)for(let t of n.include){let n=t===`_root`?`SKILL.md`:c.join(t,`SKILL.md`);for await(let r of C.glob(n,{cwd:a}))try{let n=ix(await C.readFile(c.resolve(a,r),`utf8`)),i=t===`_root`?n.name??e:c.basename(c.dirname(r));l.some(e=>e.name===i)||l.push({name:i,description:n.description,installed:u.has(i)})}catch{}}return l.sort((e,t)=>e.name.localeCompare(t.name))}function qy(e,t={}){return Qy(e,t).size>0}function Jy(){let e=process.argv[1];if(!e)return process.cwd();let n=c.dirname((()=>{try{return t.realpathSync(e)}catch{return process.execPath}})()),r=c.parse(n).root;for(;n!==r;){try{return t.accessSync(c.join(n,`package.json`)),n}catch{}n=c.dirname(n)}return process.cwd()}function Yy(e){let t=process.env.XDG_DATA_HOME||c.join(b.homedir(),`.local`,`share`);return c.join(t,`incur`,`${e}.json`)}function Xy(e,n,r,i){let a=Yy(e),o=c.dirname(a);t.existsSync(o)||t.mkdirSync(o,{recursive:!0}),t.writeFileSync(a,JSON.stringify({hash:n,skills:r,paths:i,at:new Date().toISOString()})+`
208
208
  `)}function Zy(e){try{return JSON.parse(t.readFileSync(Yy(e),`utf-8`))}catch{return}}function Qy(e,t={}){let n=Zy(e);if(!n?.skills?.length)return new Set;if(n.paths?.length){let e=n.paths.filter(e=>$y(e)).map(e=>c.basename(e));return new Set(e)}let r=t.cwd??process.cwd(),i=[c.join(b.homedir(),`.agents`,`skills`),c.join(r,`.agents`,`skills`)],a=n.skills.filter(e=>i.some(t=>$y(c.join(t,e))));return new Set(a)}function $y(e){return t.existsSync(c.join(e,`SKILL.md`))}function eb(e){return Zy(e)?.hash}var tb=I((()=>{xx(),Wy(),pl(),Sy()}));function nb(e,t){let n=typeof e==`string`?e:e.name,r=typeof e==`string`?t??{}:e,i=r.version??Nt,a=`run`in r?r:void 0,o=`fetch`in r&&r.fetch!==void 0?r.fetch:void 0,s=o===void 0?void 0:Fb(o),c=o===void 0?void 0:Ib(o),l=new Map,u=[],d=[],f=ib(r.mcp?.name??n,i??`0.0.0`,{instructions:r.mcp?.instructions,stateless:r.mcp?.stateless,title:r.mcp?.title,tools:r.mcp?.tools});r.openapi&&s&&d.push((async()=>{let e=await wv(await Sv(r.openapi,{baseUrl:c}),s,{config:r.openapiConfig});for(let[t,n]of e)l.set(t,n)})());let p={name:n,description:r.description,env:r.env,vars:r.vars,command(e,t){if(typeof e==`string`){if(Pb(t))return d.push((async()=>{let n=$v(await Qv(t.mcp)),r={_group:!0,description:t.description,commands:n,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0};Vb(e,r,vx.get(p)),l.set(e,r)})()),p;if(t&&`fetch`in t&&Nb(t.fetch)){let n=Fb(t.fetch);return t.openapi?(d.push((async()=>{let r=await wv(await Sv(t.openapi,{baseUrl:Ib(t.fetch)}),n,{basePath:t.basePath,config:t.openapiConfig}),i={_group:!0,description:t.description,commands:r,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0,...t.mcp===!1?{mcp:!1}:void 0};Vb(e,i,vx.get(p)),l.set(e,i)})()),p):(l.set(e,{_fetch:!0,basePath:t.basePath,description:t.description,fetch:n,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0}),p)}if(Vb(e,t,vx.get(p)),l.set(e,t),t.aliases)for(let n of t.aliases)l.set(n,{_alias:!0,target:e});return p}let n=mx.get(e),r=e,i=dx.get(r),a=_x.get(r),o=px.get(r),s=fx.get(r),c=n&&i.size===0?n:{_group:!0,description:r.description,commands:i,...n?{root:n}:void 0,...a?{outputPolicy:a}:void 0,...o?.length?{middlewares:o}:void 0};if(s?.length?d.push(Promise.all(s).then(()=>{Vb(r.name,c,vx.get(p))})):Vb(r.name,c,vx.get(p)),l.set(r.name,c),n){let t=yx.get(e);if(t)for(let n of t)l.set(n,{_alias:!0,target:e.name})}return p},async fetch(e){d.length>0&&await Promise.all(d);let t=vx.get(p);return sb(n,l,e,{description:r.description,envSchema:r.env,globals:t,mcpHandler:f,middlewares:u,name:n,rootCommand:a,vars:r.vars,version:i})},fs(e){let t=gu();return d.push((async()=>{let n=t?await _u(t):await kb(await Ob(e));for(let e of n){if(!Ab(e.command))throw Error(`Expected the default export from '${e.file}' to be created with \`Cli.command()\`.`);jb(l,e.segments,e.command,e.file,vx.get(p))}})()),p},async serve(e=process.argv.slice(2),t={}){if(await yt(e))return;d.length>0&&await Promise.all(d);let o=vx.get(p);return rb(n,l,e,{...t,aliases:r.aliases,banner:r.banner,config:r.config,description:r.description,envSchema:r.env,format:r.format,globals:o,mcp:r.mcp,middlewares:u,outputPolicy:r.outputPolicy,rootCommand:a,rootFetch:s,sync:r.sync,update:r.update,vars:r.vars,version:i})},use(e){return u.push(e),p}};if(a&&mx.set(p,a),a&&r.aliases&&yx.set(p,r.aliases),r.options&&hx.set(p,r.options),r.config!==void 0&&gx.set(p,!0),r.outputPolicy&&_x.set(p,r.outputPolicy),r.globals){vx.set(p,{schema:r.globals,alias:r.globalAlias});let e=[`verbose`,`format`,`json`,`llms`,`llmsFull`,`mcp`,`help`,`incurBinaryApply`,`incurUpdateCheck`,`update`,`version`,`schema`,`filterOutput`,`tokenLimit`,`tokenOffset`,`tokenCount`,...r.config?.flag?[r.config.flag,`no${r.config.flag[0].toUpperCase()}${r.config.flag.slice(1)}`]:[]],t=Object.keys(r.globals.shape);for(let n of t)if(e.includes(n))throw Error(`Global option '${n}' conflicts with a built-in flag. Choose a different name.`);let n=new Set([`h`]);if(r.globalAlias){for(let[e,t]of Object.entries(r.globalAlias))if(n.has(t))throw Error(`Global alias '-${t}' for '${e}' conflicts with a built-in short flag. Choose a different alias.`)}}return px.set(p,u),dx.set(p,l),fx.set(p,d),p}async function rb(e,t,n,r={}){let i=r.stdout??(e=>process.stdout.write(e)),a=r.exit??(e=>process.exit(e)),o=process.stdout.isTTY===!0,s=o,c=r.config!==void 0,l=r.config?.flag,u=sx(e,r.aliases);function d(e){i(e.endsWith(`
209
- `)?e:`${e}\n`)}async function f(){if(!r.banner||w)return;let e=typeof r.banner==`function`?{render:r.banner,mode:`all`}:r.banner,t=e.mode??`all`;if(t===`all`||t===(s?`human`:`agent`))try{let t=await e.render();t&&d(t)}catch{}}let p;try{p=fb(n,{configFlag:l})}catch(e){let t=e instanceof Error?e.message:String(e);d(s?Hb({code:`UNKNOWN`,message:t}):ml({code:`UNKNOWN`,message:t},`toon`)),a(1);return}let{fullOutput:m,format:h,formatExplicit:g,filterOutput:_,tokenLimit:v,tokenOffset:y,tokenCount:b,llms:x,llmsFull:S,mcp:C,help:w,update:T,updateCheck:ee,version:E,schema:D,configPath:O,configDisabled:k,rest:A}=p;s=o&&!g;let j={...typeof r.update==`object`?r.update:void 0,binary:Mt!==void 0,version:r.version},te={},M=A;function ne(e){if(!r.globals)return!0;try{let t=Ll(A,r.globals.schema,r.globals.alias,{validate:e});return e&&(te=t.parsed),M=t.rest,!0}catch(e){let t=e instanceof Error?e.message:String(e);return d(s?Hb({code:`UNKNOWN`,message:t}):ml({code:`UNKNOWN`,message:t},`toon`)),a(1),!1}}if(!ne(!1))return;if(h===`yaml`&&await ul(),ee){if(r.update!==!1)try{await et(e,j)}catch{}return}if(T&&!w){try{let t=await tt(e,j);if(s){let e=[t.deferred?`✓ Update staged for ${t.name}`:`✓ Updated ${t.name}`];t.command&&e.push(` ${t.command}`),t.deferred&&e.push(` Installation will finish after this process exits.`),d(e.join(`
209
+ `)?e:`${e}\n`)}async function f(){if(!r.banner||w)return;let e=typeof r.banner==`function`?{render:r.banner,mode:`all`}:r.banner,t=e.mode??`all`;if(t===`all`||t===(s?`human`:`agent`))try{let t=await e.render();t&&d(t)}catch{}}let p;try{p=fb(n,{configFlag:l})}catch(e){let t=e instanceof Error?e.message:String(e);d(s?Hb({code:`UNKNOWN`,message:t}):ml({code:`UNKNOWN`,message:t},`toon`)),a(1);return}let{fullOutput:m,format:h,formatExplicit:g,filterOutput:_,tokenLimit:v,tokenOffset:y,tokenCount:b,llms:x,llmsFull:S,mcp:C,help:w,update:T,updateCheck:ee,version:E,schema:D,configPath:O,configDisabled:k,rest:te}=p;s=o&&!g;let A={...typeof r.update==`object`?r.update:void 0,binary:Mt!==void 0,version:r.version},ne={},j=te;function M(e){if(!r.globals)return!0;try{let t=Ll(te,r.globals.schema,r.globals.alias,{validate:e});return e&&(ne=t.parsed),j=t.rest,!0}catch(e){let t=e instanceof Error?e.message:String(e);return d(s?Hb({code:`UNKNOWN`,message:t}):ml({code:`UNKNOWN`,message:t},`toon`)),a(1),!1}}if(!M(!1))return;if(h===`yaml`&&await ul(),ee){if(r.update!==!1)try{await et(e,A)}catch{}return}if(T&&!w){try{let t=await tt(e,A);if(s){let e=[t.deferred?`✓ Update staged for ${t.name}`:`✓ Updated ${t.name}`];t.command&&e.push(` ${t.command}`),t.deferred&&e.push(` Installation will finish after this process exits.`),d(e.join(`
210
210
  `))}else d(ml(t,h))}catch(e){let t={code:`UPDATE_FAILED`,message:e instanceof Error?e.message:String(e)};d(s?Hb(t):ml(t,h)),a(1)}return}if(C){await j_(r.mcp?.name??e,r.version??`0.0.0`,t,{middlewares:r.middlewares,env:r.envSchema,vars:r.vars,version:r.version,...r.mcp?.instructions?{instructions:r.mcp.instructions}:void 0,...r.mcp?.title?{title:r.mcp.title}:void 0,...r.mcp?.tools?{tools:r.mcp.tools}:void 0});return}let re=process.env.COMPLETE;if(re){let a=n.indexOf(`--`),o=a===-1?n:n.slice(a+1);if(o.length===0)i([e,...r.aliases??[]].map(e=>nn(re,e)).join(`
211
- `));else{let e=Number(process.env._COMPLETE_INDEX??o.length-1),n=rn(t,r.rootCommand,o,e,r.globals?{schema:r.globals.schema,alias:r.globals.alias}:void 0),a=o[e]??``,s=o.slice(0,e).filter(e=>!e.startsWith(`-`));if(s.length<=1)for(let e of Yl)e.name.startsWith(a)&&!n.some(t=>t.value===e.name)&&n.push({value:e.name,description:e.description,...e.subcommands?{noSpace:!0}:void 0});else if(s.length===2){let e=s[s.length-1],t=Gl(e);if(t?.subcommands)for(let e of t.subcommands)for(let t of[e.name,...e.aliases??[]])t.startsWith(a)&&!n.some(e=>e.value===t)&&n.push({value:t,description:e.description})}let c=an(re,n);c&&i(c)}return}let ie;if(!x&&!S&&!D&&!w&&!T&&!ee&&!E){let n=yb(M,e,`skills`)!==-1,i=yb(M,e,`mcp`)!==-1;if(!n&&!i){let n=eb(e);n&&qy(e,{cwd:r.sync?.cwd})&&vy($b(t,[],new Map,r.rootCommand))!==n&&(ie={description:`Skills are out of date:`,commands:[{command:process.env.npm_config_user_agent||process.env.npm_execpath?`${Xe()} ${ky(e)} skills add`:`${u} skills add`,description:`sync outdated skills`}]})}}if(x||S){let n=t,i=[],a=r.description,o=r.rootCommand;for(let e of M){let t=n.get(e);if(!t)break;let r=Bb(n,t);if(Lb(r))n=r.commands,a=r.description,o=r.root,i.push(e);else{n=new Map([[e,r]]),o=void 0;break}}i.length===0&&(o=r.rootCommand);let s=i.length>0?[]:i;if(S){if(!g||h===`md`){let t=new Map,r=$b(n,s,t,o);d(my(i.length>0?`${e} ${i.join(` `)}`:e,r,t));return}d(ml(Xb(n,i,r.globals?.schema,o),h));return}if(!g||h===`md`){let t=$b(n,s,new Map,o);d(fy(i.length>0?`${e} ${i.join(` `)}`:e,t,a));return}d(ml(Jb(n,i,r.globals?.schema,o),h));return}let ae=yb(M,e,`completions`);if(ae!==-1){let t=M[ae+1];if(w||!t){let t=Gl(`completions`);d(Ql(`${e} completions`,{args:t.args,description:t.description,hideGlobalOptions:!0,hint:t.hint?.(e)}));return}if(!Jl.includes(t)){d(Hb({code:`INVALID_SHELL`,message:`Unknown shell '${t}'. Supported: ${Jl.join(`, `)}`})),a(1);return}d([e,...r.aliases??[]].map(e=>nn(t,e)).join(`
212
- `));return}let oe=yb(M,e,`skills`);if(oe!==-1){let o=Gl(`skills`),c=M[oe+1],l=c?Kl(o,c):void 0;if(c&&!l){let t=en(c,o.subcommands?.flatMap(e=>[e.name,...e.aliases??[]])??[]),r=`'${c}' is not a command for '${e} skills'.${t?` Did you mean '${t}'?`:``}`,i=[];if(t){let r=n.map(e=>e===c?t:e);i.push({command:`${e} ${r.join(` `)}`})}i.push({command:`${e} skills --help`,description:`see all available commands`});let l={description:i.length===1?`Suggested command:`:`Suggested commands:`,commands:i};s?(d(Hb({code:`COMMAND_NOT_FOUND`,message:r})),d(Ub(l))):d(ml({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(bb(e,o));return}if(l?.name===`list`){if(w){d(xb(e,o,`list`));return}try{let n=await Ky(e,t,{cwd:r.sync?.cwd,depth:r.sync?.depth??1,description:r.description,include:r.sync?.include,rootCommand:r.rootCommand});if(n.length===0){d(`No skills found.`);return}let i=[],a=Math.max(...n.map(e=>e.name.length));for(let e of n){let t=e.installed?`✓`:`✗`,n=e.description?`${` `.repeat(a-e.name.length)} ${e.description}`:``;i.push(` ${t} ${e.name}${n}`)}let o=n.filter(e=>e.installed).length;i.push(``),i.push(`${n.length} skill${n.length===1?``:`s`} (${o} installed)`),d(i.join(`
213
- `))}catch(e){d(ml({code:`LIST_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(w){d(xb(e,o,`add`));return}let u=M.slice(oe+2),f=u.indexOf(`--depth`),p=u.find(e=>e.startsWith(`--depth=`)),_=f===-1?p?Number(p.split(`=`)[1]):r.sync?.depth??1:Number(u[f+1]),v=!u.includes(`--no-global`)&&void 0;try{i(`Syncing...`);let n=await Gy(e,t,{cwd:r.sync?.cwd,depth:_,description:r.description,global:v,include:r.sync?.include,rootCommand:r.rootCommand});i(`\r\x1B[K`);let a=[],o=e=>e.name,s=Math.max(...n.skills.map(e=>o(e).length));for(let e of n.skills){let t=o(e),n=e.description?`${` `.repeat(s-t.length)} ${e.description}`:``;a.push(` ✓ ${t}${n}`)}a.push(``),a.push(`${n.skills.length} skill${n.skills.length===1?``:`s`} synced`);let c=r.sync?.body;c&&(a.push(``),a.push(c));let l=r.sync?.suggestions;if(l&&l.length>0){a.push(``),a.push(`Your agent can now use ${e}. Try asking:`);for(let e of l)a.push(` "${e}"`)}if(a.push(``),a.push(`Run \`${e} --help\` to see the full command reference.`),d(a.join(`
214
- `)),m||g){let e={skills:n.paths};c&&(e.body=c),m&&n.agents.length>0&&(e.agents=n.agents),d(ml(e,g?h:`toon`))}}catch(e){d(ml({code:`SYNC_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}let se=yb(M,e,`mcp`);if(se!==-1){let o=Gl(`mcp`),c=M[se+1],l=c?Kl(o,c):void 0;if(c&&!l){let t=en(c,o.subcommands?.flatMap(e=>[e.name,...e.aliases??[]])??[]),r=`'${c}' is not a command for '${e} mcp'.${t?` Did you mean '${t}'?`:``}`,i=[];if(t){let r=n.map(e=>e===c?t:e);i.push({command:`${e} ${r.join(` `)}`})}i.push({command:`${e} mcp --help`,description:`see all available commands`});let l={description:i.length===1?`Suggested command:`:`Suggested commands:`,commands:i};s?(d(Hb({code:`COMMAND_NOT_FOUND`,message:r})),d(Ub(l))):d(ml({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(bb(e,o));return}if(w){d(xb(e,o,l.name));return}if(l.name===`doctor`){let n=await Sb(e,t,r);d(ml(n,g?h:`toon`)),n.ok||a(1);return}let u=M.slice(se+2),f=!u.includes(`--no-global`),p=r.mcp?.command,_=[...r.mcp?.agents??[]];for(let e=0;e<u.length;e++)(u[e]===`--command`||u[e]===`-c`)&&u[e+1]?p=u[++e]:u[e]===`--agent`&&u[e+1]&&_.push(u[++e]);try{let t=r.mcp?.name??e;i(`Registering MCP server...`);let n=await Cy(t,{...t===e?void 0:{cli:e},command:p,global:f,agents:_});i(`\r\x1B[K`);let a=[];a.push(`✓ Registered ${t} as MCP server`),n.agents.length>0&&a.push(` Agents: ${n.agents.join(`, `)}`),a.push(``),a.push(`Agents can now use ${t} tools.`);let o=r.sync?.suggestions;if(o&&o.length>0){a.push(``),a.push(`Try asking:`);for(let e of o)a.push(` "${e}"`)}d(a.join(`
215
- `)),(m||g)&&d(ml({name:t,command:n.command,agents:n.agents},g?h:`toon`))}catch(e){d(ml({code:`MCP_ADD_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(E&&!w&&r.version){d(r.version);return}if(M.length===0){if(r.rootCommand&&s&&r.rootCommand.args&&Gb(r.rootCommand.args)){let n=r.rootCommand;await f(),d(Ql(e,{alias:n.alias,aliases:r.aliases,configFlag:l,description:n.description??r.description,globals:r.globals,version:r.version,args:n.args,env:n.env,envSource:r.env,hint:n.hint,options:n.options,examples:rx(n.examples),usage:n.usage,commands:t.size>0?vb(t):void 0,root:!0}));return}if(!(r.rootCommand||r.rootFetch)){await f(),d(Zl(e,{aliases:r.aliases,configFlag:l,description:r.description,globals:r.globals,version:r.version,commands:vb(t),root:!0}));return}}let N=M.length===0&&r.rootCommand?{command:r.rootCommand,path:e,rest:[]}:M.length===0&&r.rootFetch?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:[]}:db(t,M);if(w&&`fetchGateway`in N){let n=N.path===e?e:`${e} ${N.path}`;N.path===e&&t.size>0?d(Zl(e,{aliases:r.aliases,configFlag:l,description:r.description,version:r.version,commands:vb(t),root:!0})):d(Db(n,N.fetchGateway.description));return}if(w){if(`help`in N||`error`in N){let n=`help`in N?`${e} ${N.path}`:e,i=`help`in N?N.description:r.description,a=`help`in N?N.commands:t,o=n===e;if(o&&r.rootCommand&&a.size>0){let t=r.rootCommand;d(Ql(e,{alias:t.alias,aliases:r.aliases,configFlag:l,description:t.description??r.description,globals:r.globals,version:r.version,args:t.args,env:t.env,envSource:r.env,hint:t.hint,options:t.options,examples:rx(t.examples),usage:t.usage,commands:vb(a),root:!0}))}else d(Zl(n,{aliases:o?r.aliases:void 0,configFlag:l,description:i,globals:r.globals,version:o?r.version:void 0,commands:vb(a),root:o}))}else if(`command`in N){let n=N.command,i=N.path===e,a=i?e:`${e} ${N.path}`,o=`commands`in N&&N.commands&&N.commands.size>0?vb(N.commands):i&&r.rootCommand&&t.size>0?vb(t):void 0;d(Ql(a,{alias:n.alias,aliases:i?r.aliases:n.aliases,configFlag:l,description:n.description,globals:r.globals,version:i?r.version:void 0,args:n.args,env:n.env,envSource:r.env,hint:n.hint,options:n.options,examples:rx(n.examples),usage:n.usage,commands:o,root:i}))}return}if(D){if(`help`in N){d(Zl(`${e} ${N.path}`,{configFlag:l,description:N.description,globals:r.globals,commands:vb(N.commands)}));return}if(`error`in N){let t=N.path?`${e} ${N.path}`:e,n=en(N.error,N.commands.keys()),r=n?` Did you mean '${n}'?`:``;d(`Error: '${N.error}' is not a command for '${t}'.${r}`),a(1);return}if(`fetchGateway`in N){d(`--schema is not supported for fetch commands.`),a(1);return}let t=N.command,n=g?h:`toon`,i={};t.args&&(i.args=Cu(t.args)),t.env&&(i.env=Cu(t.env)),t.options&&(i.options=Cu(t.options)),t.output&&(i.output=Cu(t.output)),r.globals?.schema&&(i.globals=Cu(r.globals.schema)),d(ml(i,n));return}if(`help`in N){d(Zl(`${e} ${N.path}`,{configFlag:l,description:N.description,globals:r.globals,commands:vb(N.commands)}));return}let ce;if(s&&r.update!==!1){let t=$e(e,j);t&&(ce={description:`Update available for ${t.name}:`,commands:[{command:`${u} --update`,description:`upgrade from ${t.current} to ${t.latest}`}]})}let le=Wb(ie,ce),ue=performance.now(),de=`command`in N&&N.command.format,fe=g?h:de||r.format||`toon`;fe===`yaml`&&await ul();let P=`error`in N&&!N.path&&(()=>{let e=[...N.commands.keys()];for(let t of Yl)e.push(t.name);return en(N.error,e)!==void 0})(),pe=`error`in N&&r.rootFetch&&!N.path&&!P?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:M}:`error`in N&&r.rootCommand&&!N.path&&!P?{command:r.rootCommand,path:e,rest:M}:N,me=`outputPolicy`in N&&N.outputPolicy||r.outputPolicy,he=!(s&&!g&&me===`agent-only`),ge=_?An(_):void 0;function _e(e){if(v==null&&y==null)return{text:e,truncated:!1};let t=Vt(e),n=y??0,r=v==null?t:n+v;if(n===0&&r>=t)return{text:e,truncated:!1};let i=Ht(e,n,r),a=Math.min(r,t),o=a<t?a:void 0;return{text:`${i}\n[truncated: showing tokens ${n}–${a} of ${t}]`,truncated:!0,nextOffset:o}}function ve(e){if(ge&&e.ok&&e.data!=null&&(e={...e,data:jn(e.data,ge)}),le){let t=e.meta.cta;e={...e,meta:{...e.meta,cta:t?{description:t.description,commands:[...t.commands,...le.commands]}:le}}}if(b){let t=e.ok?e.data:e.error,n=t==null?``:ml(t,fe);return d(String(Vt(n)))}let t=e.meta.cta;if(s&&!m){e.ok&&e.data!=null&&he?d(_e(ml(e.data,fe)).text):e.ok||d(Hb(e.error)),t&&d(Ub(t));return}if(m){if(v!=null||y!=null){let t=_e(e.ok&&e.data!=null?ml(e.data,fe):e.ok?``:ml(e.error,fe));if(t.truncated){let n=e.ok?{ok:!0,data:t.text}:{ok:!1,error:t.text},r={...e.meta};return t.nextOffset!=null&&(r.nextOffset=t.nextOffset),n.meta=r,d(ml(n,fe))}}return d(ml(e,fe))}let n=e.ok?e.data:e.error,r=ml(n,fe);if(!t){r&&d(_e(r).text);return}d(_e(ml(typeof n==`object`&&n?{...n,cta:t}:{data:n,cta:t},fe)).text)}if(`error`in pe){let t=pe.path?`${e} ${pe.path} --help`:`${e} --help`,r=pe.path?`${e} ${pe.path}`:e,i=`commands`in pe?[...pe.commands.keys()]:[];if(!pe.path)for(let e of Yl)i.push(e.name);let o=en(pe.error,i),c=o?` Did you mean '${o}'?`:``,l=`'${pe.error}' is not a command for '${r}'.${c}`,u=[];if(o){let t=n.map(e=>e===pe.error?o:e);u.push({command:`${e} ${t.join(` `)}`})}u.push({command:t,description:`see all available commands`});let f={description:u.length===1?`Suggested command:`:`Suggested commands:`,commands:u};if(s&&!m){d(Hb({code:`COMMAND_NOT_FOUND`,message:l})),d(Ub(le?{...f,commands:[...f.commands,...le.commands]}:f)),a(1);return}ve({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:l},meta:{command:pe.error,cta:f,duration:`${Math.round(performance.now()-ue)}ms`}}),a(1);return}if(`fetchGateway`in pe){if(!ne(!0))return;let{fetchGateway:t,path:n,rest:i}=pe,o=[...r.middlewares??[],...pe.middlewares??[]],c=async()=>{let r=Sn(i);t.basePath&&(r.path=t.basePath+r.path);let o=Cn(r),c=await t.fetch(o);if(wn(c)){await qb(Tn(c),{name:e,path:n,start:ue,format:fe,formatExplicit:g,human:s,renderOutput:he,fullOutput:m,truncate:_e,write:ve,writeln:d,exit:a});return}let l=await En(c);l.ok?ve({ok:!0,data:l.data,meta:{command:n,duration:`${Math.round(performance.now()-ue)}ms`}}):(ve({ok:!1,error:{code:`HTTP_${l.status}`,message:typeof l.data==`object`&&l.data!==null&&`message`in l.data?String(l.data.message):typeof l.data==`string`?l.data:`HTTP ${l.status}`},meta:{command:n,duration:`${Math.round(performance.now()-ue)}ms`}}),a(1))};try{let t=r.envSchema?Pl(r.envSchema,r.env??process.env):{};if(o.length>0){let i=r.vars?r.vars.parse({}):{},l={agent:!s,command:n,displayName:u,env:t,error:e=>({[bx]:`error`,...e}),format:fe,formatExplicit:g,globals:te,name:e,set(e,t){i[e]=t},var:i,version:r.version},d=e=>{if(!Kb(e)||e[bx]!==`error`)return;let t=e,r=du(u,t.cta);ve({ok:!1,error:{code:t.code,message:t.message,...t.retryable===void 0?void 0:{retryable:t.retryable}},meta:{command:n,duration:`${Math.round(performance.now()-ue)}ms`,...r?{cta:r}:void 0}}),a(t.exitCode??1)};await o.reduceRight((e,t)=>async()=>{d(await t(l,e))},c)()}else await c()}catch(e){ve({ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:n,duration:`${Math.round(performance.now()-ue)}ms`}}),a(e instanceof L?e.exitCode??1:1)}return}let{command:ye,path:be,rest:F}=pe;if(!ne(!0))return;let xe=[...r.middlewares??[],...`middlewares`in N?N.middlewares??[]:[],...ye.middleware??[]];s&&ox(F,ye.options,ye.alias);let Se;if(c)try{Se=await pb(e,be,{configDisabled:k,configPath:O,files:r.config?.files,loader:r.config?.loader})}catch(e){ve({ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:be,duration:`${Math.round(performance.now()-ue)}ms`}}),a(e instanceof L?e.exitCode??1:1);return}let Ce=await Bl(ye,{agent:!s,argv:F,defaults:Se,displayName:u,env:r.envSchema,envSource:r.env,format:fe,formatExplicit:g,globals:te,inputOptions:{},middlewares:xe,name:e,path:be,vars:r.vars,version:r.version}),we=`${Math.round(performance.now()-ue)}ms`;if(`stream`in Ce){await qb(Ce.stream,{name:u,path:be,start:ue,format:fe,formatExplicit:g,human:s,renderOutput:he,fullOutput:m,truncate:_e,write:ve,writeln:d,exit:a});return}if(Ce.ok){let e=du(u,Ce.cta);ve({ok:!0,data:Ce.data,meta:{command:be,duration:we,...e?{cta:e}:void 0}})}else{let e=du(u,Ce.cta);if(s&&!g&&Ce.error.fieldErrors){d(lb(u,be,ye,new yn({message:Ce.error.message,fieldErrors:Ce.error.fieldErrors}),r.env,l)),a(1);return}ve({ok:!1,error:{code:Ce.error.code,message:Ce.error.message,...Ce.error.retryable===void 0?void 0:{retryable:Ce.error.retryable},...Ce.error.fieldErrors?{fieldErrors:Ce.error.fieldErrors}:void 0},meta:{command:be,duration:we,...e?{cta:e}:void 0}}),a(Ce.exitCode??1)}}function ib(e,t,n={}){let r;async function i(r,i,a){let{fromJsonSchema:o,McpServer:s,WebStandardStreamableHTTPServerTransport:c}=await Promise.resolve().then(()=>(A_(),t_)),l=new s({name:e,...n.title?{title:n.title}:void 0,version:t},n.instructions?{instructions:n.instructions}:void 0);F_(l,r,{env:i?.env,fromJsonSchema:o,middlewares:i?.middlewares,name:e,request:e=>e?.http?.req,sendNotification:e=>l.server.notification(e),tools:n.tools,vars:i?.vars,version:t});let u=new c(a?{enableJsonResponse:!0}:{sessionIdGenerator:()=>crypto.randomUUID(),enableJsonResponse:!0});return await l.connect(u),{server:l,transport:u}}return async(e,t,a)=>{let o=n.stateless??!0;if(o&&e.method!==`POST`)return new Response(null,{status:405,headers:{Allow:`POST`}});if(!o)return r??=i(t,a,!1).catch(e=>{throw r=void 0,e}),(await r).transport.handleRequest(e);let s=()=>e.signal.reason??new DOMException(`This operation was aborted`,`AbortError`);if(e.signal.aborted)throw s();let{server:c,transport:l}=await i(t,a,!0),u,d=()=>u??=c.close(),f,p=new Promise((e,t)=>{f=t}),m=!1,h=()=>{m||(m=!0,f(s()),d())};e.signal.addEventListener(`abort`,h,{once:!0}),e.signal.aborted&&h();try{return e.signal.aborted?await p:await Promise.race([l.handleRequest(e),p])}finally{e.signal.removeEventListener(`abort`,h),await d()}}}function ab(e){return e.length===1?e[0]===`openapi.json`||e[0]===`openapi.yml`||e[0]===`openapi.yaml`:e[0]===`.well-known`&&e[1]===`openapi.json`&&e.length===2}function ob(e,t,n){let r={name:e,description:n.description};return dx.set(r,t),n.rootCommand&&mx.set(r,n.rootCommand),sv(r,{title:e,...n.version?{version:n.version}:void 0,...n.description?{description:n.description}:void 0})}async function sb(e,t,n,r={}){let i=performance.now(),a=new URL(n.url),o=a.pathname.split(`/`).filter(Boolean);if(n.method===`GET`&&ab(o)){let n=ob(e,t,r),i=o[0]===`openapi.yml`||o[0]===`openapi.yaml`;return new Response(i?(await ul()).stringify(n):JSON.stringify(n),{status:200,headers:{"content-type":i?`application/yaml`:`application/json`,"cache-control":`public, max-age=300`}})}if(o[0]===`mcp`&&o.length===1&&r.mcpHandler)return r.mcpHandler(n,t,{middlewares:r.middlewares,env:r.envSchema,vars:r.vars});if(o[0]===`.well-known`&&o[1]===`skills`&&o.length>=3&&n.method===`GET`){await ul();let n=new Map,i=$b(t,[],n,r.rootCommand);if(o[2]===`index.json`&&o.length===3){let t=hy(e,i,1,n).map(t=>{let n=t.content.match(/^---\n([\s\S]*?)\n---/),r=n?dl().parse(n[1]):{};return{name:t.dir||e,description:r.description??``,files:[`SKILL.md`]}});return new Response(JSON.stringify({skills:t}),{status:200,headers:{"content-type":`application/json`,"cache-control":`public, max-age=300`}})}if(o.length===4&&o[3]===`SKILL.md`){let t=o[2],r=hy(e,i,1,n).find(n=>(n.dir||e)===t);return r?new Response(r.content,{status:200,headers:{"content-type":`text/markdown`,"cache-control":`public, max-age=300`}}):new Response(`Not Found`,{status:404})}return new Response(`Not Found`,{status:404})}let s={};if(n.method===`GET`)for(let[e,t]of a.searchParams)s[e]=t;else try{(n.headers.get(`content-type`)??``).includes(`application/json`)&&(s=await n.json())}catch{}function c(e,t){return new Response(Mr(e),{status:t,headers:{"content-type":`application/json`}})}if(o.length===0)return r.rootCommand?cb(e,r.rootCommand,[],s,n,i,r):c({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:`No root command defined.`},meta:{command:`/`,duration:`${Math.round(performance.now()-i)}ms`}},404);let l=db(t,o);if(`error`in l){let t=l.path?`${e} ${l.path}`:e,n=en(l.error,l.commands.keys()),r=n?` Did you mean '${n}'?`:``;return c({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:`'${l.error}' is not a command for '${t}'.${r}`},meta:{command:l.error,duration:`${Math.round(performance.now()-i)}ms`}},404)}if(`help`in l)return c({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:`'${l.path}' is a command group. Specify a subcommand.`},meta:{command:l.path,duration:`${Math.round(performance.now()-i)}ms`}},404);if(`fetchGateway`in l)return l.fetchGateway.fetch(n);let{command:u,path:d,rest:f}=l,p=`middlewares`in l?l.middlewares:[];return cb(d,u,f,s,n,i,{...r,groupMiddlewares:p})}async function cb(e,t,n,r,i,a,o){function s(e,t){return new Response(Mr(e),{status:t,headers:{"content-type":`application/json`}})}let c=[...o.middlewares??[],...o.groupMiddlewares??[],...t.middleware??[]],l={},u=r;if(o.globals){let t=new Set(Object.keys(o.globals.schema.shape)),n={};u={};for(let[e,i]of Object.entries(r))t.has(e)?n[e]=i:u[e]=i;try{l=o.globals.schema.parse(n)}catch(t){return s({ok:!1,error:{code:`VALIDATION_ERROR`,message:(t?.issues??t?.error?.issues??[]).map(e=>e.message).join(`; `)||`Validation failed`},meta:{command:e,duration:`${Math.round(performance.now()-a)}ms`}},400)}}let d=await Bl(t,{agent:!0,argv:n,env:o.envSchema,format:`json`,formatExplicit:!0,globals:l,inputOptions:u,middlewares:c,name:o.name??e,parseMode:`split`,path:e,request:i,vars:o.vars,version:o.version}),f=`${Math.round(performance.now()-a)}ms`;if(`stream`in d){let t=d.stream,n=new TextEncoder,r=t=>({command:e,duration:`${Math.round(performance.now()-a)}ms`,...t?{cta:t}:void 0}),i=t=>({type:`error`,ok:!1,error:{code:t.code,message:t.message,...t.retryable===void 0?void 0:{retryable:t.retryable}},meta:r(du(o.name??e,t.cta))}),s=new ReadableStream({async cancel(){await t.return(void 0)},async pull(a){try{let{value:s,done:c}=await t.next();if(c){if(Kb(s)&&s[bx]===`error`){a.enqueue(n.encode(Mr(i(s))+`
211
+ `));else{let e=Number(process.env._COMPLETE_INDEX??o.length-1),n=rn(t,r.rootCommand,o,e,r.globals?{schema:r.globals.schema,alias:r.globals.alias}:void 0),a=o[e]??``,s=o.slice(0,e).filter(e=>!e.startsWith(`-`));if(s.length<=1)for(let e of Yl)e.name.startsWith(a)&&!n.some(t=>t.value===e.name)&&n.push({value:e.name,description:e.description,...e.subcommands?{noSpace:!0}:void 0});else if(s.length===2){let e=s[s.length-1],t=Gl(e);if(t?.subcommands)for(let e of t.subcommands)for(let t of[e.name,...e.aliases??[]])t.startsWith(a)&&!n.some(e=>e.value===t)&&n.push({value:t,description:e.description})}let c=an(re,n);c&&i(c)}return}let ie;if(!x&&!S&&!D&&!w&&!T&&!ee&&!E){let n=yb(j,e,`skills`)!==-1,i=yb(j,e,`mcp`)!==-1;if(!n&&!i){let n=eb(e);n&&qy(e,{cwd:r.sync?.cwd})&&vy($b(t,[],new Map,r.rootCommand))!==n&&(ie={description:`Skills are out of date:`,commands:[{command:process.env.npm_config_user_agent||process.env.npm_execpath?`${Xe()} ${ky(e)} skills add`:`${u} skills add`,description:`sync outdated skills`}]})}}if(x||S){let n=t,i=[],a=r.description,o=r.rootCommand;for(let e of j){let t=n.get(e);if(!t)break;let r=Bb(n,t);if(Lb(r))n=r.commands,a=r.description,o=r.root,i.push(e);else{n=new Map([[e,r]]),o=void 0;break}}i.length===0&&(o=r.rootCommand);let s=i.length>0?[]:i;if(S){if(!g||h===`md`){let t=new Map,r=$b(n,s,t,o);d(my(i.length>0?`${e} ${i.join(` `)}`:e,r,t));return}d(ml(Xb(n,i,r.globals?.schema,o),h));return}if(!g||h===`md`){let t=$b(n,s,new Map,o);d(fy(i.length>0?`${e} ${i.join(` `)}`:e,t,a));return}d(ml(Jb(n,i,r.globals?.schema,o),h));return}let ae=yb(j,e,`completions`);if(ae!==-1){let t=j[ae+1];if(w||!t){let t=Gl(`completions`);d(Ql(`${e} completions`,{args:t.args,description:t.description,hideGlobalOptions:!0,hint:t.hint?.(e)}));return}if(!Jl.includes(t)){d(Hb({code:`INVALID_SHELL`,message:`Unknown shell '${t}'. Supported: ${Jl.join(`, `)}`})),a(1);return}d([e,...r.aliases??[]].map(e=>nn(t,e)).join(`
212
+ `));return}let oe=yb(j,e,`skills`);if(oe!==-1){let o=Gl(`skills`),c=j[oe+1],l=c?Kl(o,c):void 0;if(c&&!l){let t=en(c,o.subcommands?.flatMap(e=>[e.name,...e.aliases??[]])??[]),r=`'${c}' is not a command for '${e} skills'.${t?` Did you mean '${t}'?`:``}`,i=[];if(t){let r=n.map(e=>e===c?t:e);i.push({command:`${e} ${r.join(` `)}`})}i.push({command:`${e} skills --help`,description:`see all available commands`});let l={description:i.length===1?`Suggested command:`:`Suggested commands:`,commands:i};s?(d(Hb({code:`COMMAND_NOT_FOUND`,message:r})),d(Ub(l))):d(ml({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(bb(e,o));return}if(l?.name===`list`){if(w){d(xb(e,o,`list`));return}try{let n=await Ky(e,t,{cwd:r.sync?.cwd,depth:r.sync?.depth??1,description:r.description,include:r.sync?.include,rootCommand:r.rootCommand});if(n.length===0){d(`No skills found.`);return}let i=[],a=Math.max(...n.map(e=>e.name.length));for(let e of n){let t=e.installed?`✓`:`✗`,n=e.description?`${` `.repeat(a-e.name.length)} ${e.description}`:``;i.push(` ${t} ${e.name}${n}`)}let o=n.filter(e=>e.installed).length;i.push(``),i.push(`${n.length} skill${n.length===1?``:`s`} (${o} installed)`),d(i.join(`
213
+ `))}catch(e){d(ml({code:`LIST_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(w){d(xb(e,o,`add`));return}let u=j.slice(oe+2),f=u.indexOf(`--depth`),p=u.find(e=>e.startsWith(`--depth=`)),_=f===-1?p?Number(p.split(`=`)[1]):r.sync?.depth??1:Number(u[f+1]),v=!u.includes(`--no-global`)&&void 0;try{i(`Syncing...`);let n=await Gy(e,t,{cwd:r.sync?.cwd,depth:_,description:r.description,global:v,include:r.sync?.include,rootCommand:r.rootCommand});i(`\r\x1B[K`);let a=[],o=e=>e.name,s=Math.max(...n.skills.map(e=>o(e).length));for(let e of n.skills){let t=o(e),n=e.description?`${` `.repeat(s-t.length)} ${e.description}`:``;a.push(` ✓ ${t}${n}`)}a.push(``),a.push(`${n.skills.length} skill${n.skills.length===1?``:`s`} synced`);let c=r.sync?.body;c&&(a.push(``),a.push(c));let l=r.sync?.suggestions;if(l&&l.length>0){a.push(``),a.push(`Your agent can now use ${e}. Try asking:`);for(let e of l)a.push(` "${e}"`)}if(a.push(``),a.push(`Run \`${e} --help\` to see the full command reference.`),d(a.join(`
214
+ `)),m||g){let e={skills:n.paths};c&&(e.body=c),m&&n.agents.length>0&&(e.agents=n.agents),d(ml(e,g?h:`toon`))}}catch(e){d(ml({code:`SYNC_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}let se=yb(j,e,`mcp`);if(se!==-1){let o=Gl(`mcp`),c=j[se+1],l=c?Kl(o,c):void 0;if(c&&!l){let t=en(c,o.subcommands?.flatMap(e=>[e.name,...e.aliases??[]])??[]),r=`'${c}' is not a command for '${e} mcp'.${t?` Did you mean '${t}'?`:``}`,i=[];if(t){let r=n.map(e=>e===c?t:e);i.push({command:`${e} ${r.join(` `)}`})}i.push({command:`${e} mcp --help`,description:`see all available commands`});let l={description:i.length===1?`Suggested command:`:`Suggested commands:`,commands:i};s?(d(Hb({code:`COMMAND_NOT_FOUND`,message:r})),d(Ub(l))):d(ml({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(bb(e,o));return}if(w){d(xb(e,o,l.name));return}if(l.name===`doctor`){let n=await Sb(e,t,r);d(ml(n,g?h:`toon`)),n.ok||a(1);return}let u=j.slice(se+2),f=!u.includes(`--no-global`),p=r.mcp?.command,_=[...r.mcp?.agents??[]];for(let e=0;e<u.length;e++)(u[e]===`--command`||u[e]===`-c`)&&u[e+1]?p=u[++e]:u[e]===`--agent`&&u[e+1]&&_.push(u[++e]);try{let t=r.mcp?.name??e;i(`Registering MCP server...`);let n=await Cy(t,{...t===e?void 0:{cli:e},command:p,global:f,agents:_});i(`\r\x1B[K`);let a=[];a.push(`✓ Registered ${t} as MCP server`),n.agents.length>0&&a.push(` Agents: ${n.agents.join(`, `)}`),a.push(``),a.push(`Agents can now use ${t} tools.`);let o=r.sync?.suggestions;if(o&&o.length>0){a.push(``),a.push(`Try asking:`);for(let e of o)a.push(` "${e}"`)}d(a.join(`
215
+ `)),(m||g)&&d(ml({name:t,command:n.command,agents:n.agents},g?h:`toon`))}catch(e){d(ml({code:`MCP_ADD_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(E&&!w&&r.version){d(r.version);return}if(j.length===0){if(r.rootCommand&&s&&r.rootCommand.args&&Gb(r.rootCommand.args)){let n=r.rootCommand;await f(),d(Ql(e,{alias:n.alias,aliases:r.aliases,configFlag:l,description:n.description??r.description,globals:r.globals,version:r.version,args:n.args,env:n.env,envSource:r.env,hint:n.hint,options:n.options,examples:rx(n.examples),usage:n.usage,commands:t.size>0?vb(t):void 0,root:!0}));return}if(!(r.rootCommand||r.rootFetch)){await f(),d(Zl(e,{aliases:r.aliases,configFlag:l,description:r.description,globals:r.globals,version:r.version,commands:vb(t),root:!0}));return}}let N=j.length===0&&r.rootCommand?{command:r.rootCommand,path:e,rest:[]}:j.length===0&&r.rootFetch?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:[]}:db(t,j);if(w&&`fetchGateway`in N){let n=N.path===e?e:`${e} ${N.path}`;N.path===e&&t.size>0?d(Zl(e,{aliases:r.aliases,configFlag:l,description:r.description,version:r.version,commands:vb(t),root:!0})):d(Db(n,N.fetchGateway.description));return}if(w){if(`help`in N||`error`in N){let n=`help`in N?`${e} ${N.path}`:e,i=`help`in N?N.description:r.description,a=`help`in N?N.commands:t,o=n===e;if(o&&r.rootCommand&&a.size>0){let t=r.rootCommand;d(Ql(e,{alias:t.alias,aliases:r.aliases,configFlag:l,description:t.description??r.description,globals:r.globals,version:r.version,args:t.args,env:t.env,envSource:r.env,hint:t.hint,options:t.options,examples:rx(t.examples),usage:t.usage,commands:vb(a),root:!0}))}else d(Zl(n,{aliases:o?r.aliases:void 0,configFlag:l,description:i,globals:r.globals,version:o?r.version:void 0,commands:vb(a),root:o}))}else if(`command`in N){let n=N.command,i=N.path===e,a=i?e:`${e} ${N.path}`,o=`commands`in N&&N.commands&&N.commands.size>0?vb(N.commands):i&&r.rootCommand&&t.size>0?vb(t):void 0;d(Ql(a,{alias:n.alias,aliases:i?r.aliases:n.aliases,configFlag:l,description:n.description,globals:r.globals,version:i?r.version:void 0,args:n.args,env:n.env,envSource:r.env,hint:n.hint,options:n.options,examples:rx(n.examples),usage:n.usage,commands:o,root:i}))}return}if(D){if(`help`in N){d(Zl(`${e} ${N.path}`,{configFlag:l,description:N.description,globals:r.globals,commands:vb(N.commands)}));return}if(`error`in N){let t=N.path?`${e} ${N.path}`:e,n=en(N.error,N.commands.keys()),r=n?` Did you mean '${n}'?`:``;d(`Error: '${N.error}' is not a command for '${t}'.${r}`),a(1);return}if(`fetchGateway`in N){d(`--schema is not supported for fetch commands.`),a(1);return}let t=N.command,n=g?h:`toon`,i={};t.args&&(i.args=Cu(t.args)),t.env&&(i.env=Cu(t.env)),t.options&&(i.options=Cu(t.options)),t.output&&(i.output=Cu(t.output)),r.globals?.schema&&(i.globals=Cu(r.globals.schema)),d(ml(i,n));return}if(`help`in N){d(Zl(`${e} ${N.path}`,{configFlag:l,description:N.description,globals:r.globals,commands:vb(N.commands)}));return}let ce;if(s&&r.update!==!1){let t=$e(e,A);t&&(ce={description:`Update available for ${t.name}:`,commands:[{command:`${u} --update`,description:`upgrade from ${t.current} to ${t.latest}`}]})}let le=Wb(ie,ce),ue=performance.now(),de=`command`in N&&N.command.format,fe=g?h:de||r.format||`toon`;fe===`yaml`&&await ul();let P=`error`in N&&!N.path&&(()=>{let e=[...N.commands.keys()];for(let t of Yl)e.push(t.name);return en(N.error,e)!==void 0})(),pe=`error`in N&&r.rootFetch&&!N.path&&!P?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:j}:`error`in N&&r.rootCommand&&!N.path&&!P?{command:r.rootCommand,path:e,rest:j}:N,me=`outputPolicy`in N&&N.outputPolicy||r.outputPolicy,he=!(s&&!g&&me===`agent-only`),ge=_?An(_):void 0;function _e(e){if(v==null&&y==null)return{text:e,truncated:!1};let t=Vt(e),n=y??0,r=v==null?t:n+v;if(n===0&&r>=t)return{text:e,truncated:!1};let i=Ht(e,n,r),a=Math.min(r,t),o=a<t?a:void 0;return{text:`${i}\n[truncated: showing tokens ${n}–${a} of ${t}]`,truncated:!0,nextOffset:o}}function ve(e){if(ge&&e.ok&&e.data!=null&&(e={...e,data:jn(e.data,ge)}),le){let t=e.meta.cta;e={...e,meta:{...e.meta,cta:t?{description:t.description,commands:[...t.commands,...le.commands]}:le}}}if(b){let t=e.ok?e.data:e.error,n=t==null?``:ml(t,fe);return d(String(Vt(n)))}let t=e.meta.cta;if(s&&!m){e.ok&&e.data!=null&&he?d(_e(ml(e.data,fe)).text):e.ok||d(Hb(e.error)),t&&d(Ub(t));return}if(m){if(v!=null||y!=null){let t=_e(e.ok&&e.data!=null?ml(e.data,fe):e.ok?``:ml(e.error,fe));if(t.truncated){let n=e.ok?{ok:!0,data:t.text}:{ok:!1,error:t.text},r={...e.meta};return t.nextOffset!=null&&(r.nextOffset=t.nextOffset),n.meta=r,d(ml(n,fe))}}return d(ml(e,fe))}let n=e.ok?e.data:e.error,r=ml(n,fe);if(!t){r&&d(_e(r).text);return}d(_e(ml(typeof n==`object`&&n?{...n,cta:t}:{data:n,cta:t},fe)).text)}if(`error`in pe){let t=pe.path?`${e} ${pe.path} --help`:`${e} --help`,r=pe.path?`${e} ${pe.path}`:e,i=`commands`in pe?[...pe.commands.keys()]:[];if(!pe.path)for(let e of Yl)i.push(e.name);let o=en(pe.error,i),c=o?` Did you mean '${o}'?`:``,l=`'${pe.error}' is not a command for '${r}'.${c}`,u=[];if(o){let t=n.map(e=>e===pe.error?o:e);u.push({command:`${e} ${t.join(` `)}`})}u.push({command:t,description:`see all available commands`});let f={description:u.length===1?`Suggested command:`:`Suggested commands:`,commands:u};if(s&&!m){d(Hb({code:`COMMAND_NOT_FOUND`,message:l})),d(Ub(le?{...f,commands:[...f.commands,...le.commands]}:f)),a(1);return}ve({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:l},meta:{command:pe.error,cta:f,duration:`${Math.round(performance.now()-ue)}ms`}}),a(1);return}if(`fetchGateway`in pe){if(!M(!0))return;let{fetchGateway:t,path:n,rest:i}=pe,o=[...r.middlewares??[],...pe.middlewares??[]],c=async()=>{let r=Sn(i);t.basePath&&(r.path=t.basePath+r.path);let o=Cn(r),c=await t.fetch(o);if(wn(c)){await qb(Tn(c),{name:e,path:n,start:ue,format:fe,formatExplicit:g,human:s,renderOutput:he,fullOutput:m,truncate:_e,write:ve,writeln:d,exit:a});return}let l=await En(c);l.ok?ve({ok:!0,data:l.data,meta:{command:n,duration:`${Math.round(performance.now()-ue)}ms`}}):(ve({ok:!1,error:{code:`HTTP_${l.status}`,message:typeof l.data==`object`&&l.data!==null&&`message`in l.data?String(l.data.message):typeof l.data==`string`?l.data:`HTTP ${l.status}`},meta:{command:n,duration:`${Math.round(performance.now()-ue)}ms`}}),a(1))};try{let t=r.envSchema?Pl(r.envSchema,r.env??process.env):{};if(o.length>0){let i=r.vars?r.vars.parse({}):{},l={agent:!s,command:n,displayName:u,env:t,error:e=>({[bx]:`error`,...e}),format:fe,formatExplicit:g,globals:ne,name:e,set(e,t){i[e]=t},var:i,version:r.version},d=e=>{if(!Kb(e)||e[bx]!==`error`)return;let t=e,r=du(u,t.cta);ve({ok:!1,error:{code:t.code,message:t.message,...t.retryable===void 0?void 0:{retryable:t.retryable}},meta:{command:n,duration:`${Math.round(performance.now()-ue)}ms`,...r?{cta:r}:void 0}}),a(t.exitCode??1)};await o.reduceRight((e,t)=>async()=>{d(await t(l,e))},c)()}else await c()}catch(e){ve({ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:n,duration:`${Math.round(performance.now()-ue)}ms`}}),a(e instanceof L?e.exitCode??1:1)}return}let{command:ye,path:be,rest:F}=pe;if(!M(!0))return;let xe=[...r.middlewares??[],...`middlewares`in N?N.middlewares??[]:[],...ye.middleware??[]];s&&ox(F,ye.options,ye.alias);let Se;if(c)try{Se=await pb(e,be,{configDisabled:k,configPath:O,files:r.config?.files,loader:r.config?.loader})}catch(e){ve({ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:be,duration:`${Math.round(performance.now()-ue)}ms`}}),a(e instanceof L?e.exitCode??1:1);return}let Ce=await Bl(ye,{agent:!s,argv:F,defaults:Se,displayName:u,env:r.envSchema,envSource:r.env,format:fe,formatExplicit:g,globals:ne,inputOptions:{},middlewares:xe,name:e,path:be,vars:r.vars,version:r.version}),we=`${Math.round(performance.now()-ue)}ms`;if(`stream`in Ce){await qb(Ce.stream,{name:u,path:be,start:ue,format:fe,formatExplicit:g,human:s,renderOutput:he,fullOutput:m,truncate:_e,write:ve,writeln:d,exit:a});return}if(Ce.ok){let e=du(u,Ce.cta);ve({ok:!0,data:Ce.data,meta:{command:be,duration:we,...e?{cta:e}:void 0}})}else{let e=du(u,Ce.cta);if(s&&!g&&Ce.error.fieldErrors){d(lb(u,be,ye,new yn({message:Ce.error.message,fieldErrors:Ce.error.fieldErrors}),r.env,l)),a(1);return}ve({ok:!1,error:{code:Ce.error.code,message:Ce.error.message,...Ce.error.retryable===void 0?void 0:{retryable:Ce.error.retryable},...Ce.error.fieldErrors?{fieldErrors:Ce.error.fieldErrors}:void 0},meta:{command:be,duration:we,...e?{cta:e}:void 0}}),a(Ce.exitCode??1)}}function ib(e,t,n={}){let r;async function i(r,i,a){let{fromJsonSchema:o,McpServer:s,WebStandardStreamableHTTPServerTransport:c}=await Promise.resolve().then(()=>(A_(),t_)),l=new s({name:e,...n.title?{title:n.title}:void 0,version:t},n.instructions?{instructions:n.instructions}:void 0);F_(l,r,{env:i?.env,fromJsonSchema:o,middlewares:i?.middlewares,name:e,request:e=>e?.http?.req,sendNotification:e=>l.server.notification(e),tools:n.tools,vars:i?.vars,version:t});let u=new c(a?{enableJsonResponse:!0}:{sessionIdGenerator:()=>crypto.randomUUID(),enableJsonResponse:!0});return await l.connect(u),{server:l,transport:u}}return async(e,t,a)=>{let o=n.stateless??!0;if(o&&e.method!==`POST`)return new Response(null,{status:405,headers:{Allow:`POST`}});if(!o)return r??=i(t,a,!1).catch(e=>{throw r=void 0,e}),(await r).transport.handleRequest(e);let s=()=>e.signal.reason??new DOMException(`This operation was aborted`,`AbortError`);if(e.signal.aborted)throw s();let{server:c,transport:l}=await i(t,a,!0),u,d=()=>u??=c.close(),f,p=new Promise((e,t)=>{f=t}),m=!1,h=()=>{m||(m=!0,f(s()),d())};e.signal.addEventListener(`abort`,h,{once:!0}),e.signal.aborted&&h();try{return e.signal.aborted?await p:await Promise.race([l.handleRequest(e),p])}finally{e.signal.removeEventListener(`abort`,h),await d()}}}function ab(e){return e.length===1?e[0]===`openapi.json`||e[0]===`openapi.yml`||e[0]===`openapi.yaml`:e[0]===`.well-known`&&e[1]===`openapi.json`&&e.length===2}function ob(e,t,n){let r={name:e,description:n.description};return dx.set(r,t),n.rootCommand&&mx.set(r,n.rootCommand),sv(r,{title:e,...n.version?{version:n.version}:void 0,...n.description?{description:n.description}:void 0})}async function sb(e,t,n,r={}){let i=performance.now(),a=new URL(n.url),o=a.pathname.split(`/`).filter(Boolean);if(n.method===`GET`&&ab(o)){let n=ob(e,t,r),i=o[0]===`openapi.yml`||o[0]===`openapi.yaml`;return new Response(i?(await ul()).stringify(n):JSON.stringify(n),{status:200,headers:{"content-type":i?`application/yaml`:`application/json`,"cache-control":`public, max-age=300`}})}if(o[0]===`mcp`&&o.length===1&&r.mcpHandler)return r.mcpHandler(n,t,{middlewares:r.middlewares,env:r.envSchema,vars:r.vars});if(o[0]===`.well-known`&&o[1]===`skills`&&o.length>=3&&n.method===`GET`){await ul();let n=new Map,i=$b(t,[],n,r.rootCommand);if(o[2]===`index.json`&&o.length===3){let t=hy(e,i,1,n).map(t=>{let n=t.content.match(/^---\n([\s\S]*?)\n---/),r=n?dl().parse(n[1]):{};return{name:t.dir||e,description:r.description??``,files:[`SKILL.md`]}});return new Response(JSON.stringify({skills:t}),{status:200,headers:{"content-type":`application/json`,"cache-control":`public, max-age=300`}})}if(o.length===4&&o[3]===`SKILL.md`){let t=o[2],r=hy(e,i,1,n).find(n=>(n.dir||e)===t);return r?new Response(r.content,{status:200,headers:{"content-type":`text/markdown`,"cache-control":`public, max-age=300`}}):new Response(`Not Found`,{status:404})}return new Response(`Not Found`,{status:404})}let s={};if(n.method===`GET`)for(let[e,t]of a.searchParams)s[e]=t;else try{(n.headers.get(`content-type`)??``).includes(`application/json`)&&(s=await n.json())}catch{}function c(e,t){return new Response(Mr(e),{status:t,headers:{"content-type":`application/json`}})}if(o.length===0)return r.rootCommand?cb(e,r.rootCommand,[],s,n,i,r):c({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:`No root command defined.`},meta:{command:`/`,duration:`${Math.round(performance.now()-i)}ms`}},404);let l=db(t,o);if(`error`in l){let t=l.path?`${e} ${l.path}`:e,n=en(l.error,l.commands.keys()),r=n?` Did you mean '${n}'?`:``;return c({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:`'${l.error}' is not a command for '${t}'.${r}`},meta:{command:l.error,duration:`${Math.round(performance.now()-i)}ms`}},404)}if(`help`in l)return c({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:`'${l.path}' is a command group. Specify a subcommand.`},meta:{command:l.path,duration:`${Math.round(performance.now()-i)}ms`}},404);if(`fetchGateway`in l)return l.fetchGateway.fetch(n);let{command:u,path:d,rest:f}=l,p=`middlewares`in l?l.middlewares:[];return cb(d,u,f,s,n,i,{...r,groupMiddlewares:p})}async function cb(e,t,n,r,i,a,o){function s(e,t){return new Response(Mr(e),{status:t,headers:{"content-type":`application/json`}})}let c=[...o.middlewares??[],...o.groupMiddlewares??[],...t.middleware??[]],l={},u=r;if(o.globals){let t=new Set(Object.keys(o.globals.schema.shape)),n={};u={};for(let[e,i]of Object.entries(r))t.has(e)?n[e]=i:u[e]=i;try{l=o.globals.schema.parse(n)}catch(t){return s({ok:!1,error:{code:`VALIDATION_ERROR`,message:(t?.issues??t?.error?.issues??[]).map(e=>e.message).join(`; `)||`Validation failed`},meta:{command:e,duration:`${Math.round(performance.now()-a)}ms`}},400)}}let d=await Bl(t,{agent:!0,argv:n,env:o.envSchema,format:`json`,formatExplicit:!0,globals:l,inputOptions:u,middlewares:c,name:o.name??e,parseMode:`split`,path:e,request:i,vars:o.vars,version:o.version}),f=`${Math.round(performance.now()-a)}ms`;if(`stream`in d){let t=d.stream,n=new TextEncoder,r=t=>({command:e,duration:`${Math.round(performance.now()-a)}ms`,...t?{cta:t}:void 0}),i=t=>({type:`error`,ok:!1,error:{code:t.code,message:t.message,...t.retryable===void 0?void 0:{retryable:t.retryable}},meta:r(du(o.name??e,t.cta))}),s=new ReadableStream({async cancel(){await t.return(void 0)},async pull(a){try{let{value:s,done:c}=await t.next();if(c){if(Kb(s)&&s[bx]===`error`){a.enqueue(n.encode(Mr(i(s))+`
216
216
  `)),a.close();return}let t=Kb(s)&&s[bx]===`ok`?du(o.name??e,s.cta):void 0;a.enqueue(n.encode(Mr({type:`done`,ok:!0,meta:r(t)})+`
217
217
  `)),a.close();return}if(Kb(s)&&s[bx]===`error`){a.enqueue(n.encode(Mr(i(s))+`
218
218
  `)),await t.return(void 0),a.close();return}a.enqueue(n.encode(Mr({type:`chunk`,data:s})+`
@@ -220,41 +220,41 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
220
220
  `)),a.close()}}});return new Response(s,{status:200,headers:{"content-type":`application/x-ndjson`}})}if(!d.ok){let t=du(o.name??e,d.cta);return s({ok:!1,error:{code:d.error.code,message:d.error.message,...d.error.retryable===void 0?void 0:{retryable:d.error.retryable},...d.error.fieldErrors?{fieldErrors:d.error.fieldErrors}:void 0},meta:{command:e,duration:f,...t?{cta:t}:void 0}},d.error.code===`VALIDATION_ERROR`?400:500)}let p=du(o.name??e,d.cta);return s({ok:!0,data:d.data,meta:{command:e,duration:f,...p?{cta:p}:void 0}},200)}function lb(e,t,n,r,i,a){let o=[];for(let e of r.fieldErrors){let t=(()=>{let t=ub(n,e.path);return e.missing?`Error: missing required ${t.kind} ${t.label}`:t.kind===`environment variable`?`Error: invalid value for environment variable ${t.label}: ${e.message}`:`Error: invalid value for ${t.label}: ${e.message}`})();o.push(t)}return o.push(`See below for usage.`),o.push(``),o.push(Ql(t===e?e:`${e} ${t}`,{alias:n.alias,configFlag:a,description:n.description,args:n.args,env:n.env,envSource:i,hint:n.hint,options:n.options,examples:rx(n.examples),usage:n.usage})),o.join(`
221
221
  `)}function ub(e,t){let[n,...r]=t.split(`.`);if(!n)return{kind:`argument`,label:`input`};if(e.options?.shape[n]){let e=r.length>0?`.${r.join(`.`)}`:``;return{kind:`option`,label:`--${Qt(n)}${e}`}}return e.env?.shape[n]?{kind:`environment variable`,label:`${n}${r.length>0?`.${r.join(`.`)}`:``}`}:{kind:`argument`,label:`<${t}>`}}function db(e,t){let[n,...r]=t;if(!n||!e.has(n))return{error:n??`(none)`,path:``,commands:e,rest:r};let i=Bb(e,e.get(n)),a=[n],o=r,s,c=[];if(Rb(i)){let e=i.outputPolicy??s;return{fetchGateway:i,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}for(;Lb(i);){i.outputPolicy&&(s=i.outputPolicy),i.middlewares&&c.push(...i.middlewares);let e=o[0];if(!e&&i.root){let e=i.root.outputPolicy??s;return{command:i.root,commands:i.commands,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}if(!e)return{help:!0,path:a.join(` `),description:i.description,commands:i.commands};let t=i.commands.get(e);if(!t){if(i.root&&!en(e,i.commands.keys())){let e=i.root.outputPolicy??s;return{command:i.root,commands:i.commands,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}return{error:e,path:a.join(` `),commands:i.commands,rest:o.slice(1)}}let n=Bb(i.commands,t);if(a.push(e),o=o.slice(1),i=n,Rb(i)){let e=i.outputPolicy??s;return{fetchGateway:i,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}}let l=i.outputPolicy??s;return{command:i,middlewares:c,path:a.join(` `),rest:o,...l?{outputPolicy:l}:void 0}}function fb(e,t={}){let n=!1,r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=!1,d=`toon`,f=!1,p,m=!1,h,g,_,v=!1,y=[],b=t.configFlag?`--${t.configFlag}`:void 0,x=t.configFlag?`--${t.configFlag}=`:void 0,S=t.configFlag?`--no-${t.configFlag}`:void 0;for(let t=0;t<e.length;t++){let C=e[t];if(C===`--full-output`)n=!0;else if(C===`--llms`)r=!0;else if(C===`--llms-full`)i=!0;else if(C===`--mcp`)a=!0;else if(C===`--help`||C===`-h`)o=!0;else if(C===`--update`)s=!0;else if(C===`--incur-update-check`)c=!0;else if(C===`--version`&&(e[t+1]===void 0||e[t+1].startsWith(`-`)))l=!0;else if(C===`--schema`)u=!0;else if(C===`--json`)d=`json`,f=!0;else if(C===`--format`&&e[t+1]){if(!ux.has(e[t+1]))throw new bn({message:`Invalid format: "${e[t+1]}". Expected one of: ${[...ux].join(`, `)}`});d=e[t+1],f=!0,t++}else if(b&&C===b){let n=e[t+1];if(n===void 0)throw new bn({message:`Missing value for flag: ${b}`});p=n,m=!1,t++}else if(x&&C.startsWith(x)){let e=C.slice(x.length);if(e.length===0)throw new bn({message:`Missing value for flag: ${b}`});p=e,m=!1}else if(S&&C===S)p=void 0,m=!0;else if(C===`--filter-output`&&e[t+1])h=e[t+1],t++;else if(C===`--token-limit`&&e[t+1]){let n=Number(e[t+1]);if(!Number.isFinite(n)||e[t+1].trim()===``)throw new bn({message:`Invalid value for --token-limit: "${e[t+1]}"`});g=n,t++}else if(C===`--token-offset`&&e[t+1]){let n=Number(e[t+1]);if(!Number.isFinite(n)||e[t+1].trim()===``)throw new bn({message:`Invalid value for --token-offset: "${e[t+1]}"`});_=n,t++}else C===`--token-count`?v=!0:y.push(C)}return{fullOutput:n,format:d,formatExplicit:f,configPath:p,configDisabled:m,filterOutput:h,tokenLimit:g,tokenOffset:_,tokenCount:v,llms:r,llmsFull:i,mcp:a,help:o,update:s,updateCheck:c,version:l,schema:u,rest:y}}async function pb(e,t,n={}){if(n.configDisabled)return;let{loader:r}=n,i;i=n.configPath?mb(n.configPath):await hb(n.files??[`${e}.json`]);let a;if(r){let e=await r(i);if(e===void 0)return;if(!Zt(e))throw new bn({message:`Config loader must return a plain object or undefined`});a=e}else{if(!i)return;let e=await gb(i,!!n.configPath);if(!e)return;a=e}return _b(a,e,t)}function mb(e){return e.startsWith(`~/`)||e===`~`?s.join(y.homedir(),e.slice(1)):s.resolve(process.cwd(),e)}async function hb(e){for(let t of e){let e=mb(t);try{return await S.access(e,S.constants.R_OK),e}catch{}}}async function gb(e,t){let n;try{n=await S.readFile(e,`utf8`)}catch(n){if(n.code===`ENOENT`){if(t)throw new bn({message:`Config file not found: ${e}`});return}throw n}let r;try{r=JSON.parse(n)}catch(t){throw new bn({message:`Invalid JSON config file: ${e}`,cause:t instanceof Error?t:void 0})}if(!Zt(r))throw new bn({message:`Invalid config file: expected a top-level object in ${e}`});return r}function _b(e,t,n){let r=n===t?[]:n.split(` `),i=e;for(let e of r){if(!Zt(i))return;let t=i.commands;if(!Zt(t)||(i=t[e],i===void 0))return}if(!Zt(i))throw new bn({message:`Invalid config section for '${n}': expected an object`});let a=i.options;if(a!==void 0){if(!Zt(a))throw new bn({message:`Invalid config 'options' for '${n}': expected an object`});return Object.keys(a).length>0?a:void 0}}function vb(e){let t=[];for(let[n,r]of e)zb(r)||t.push({name:n,description:r.description});return t.sort((e,t)=>e.name.localeCompare(t.name))}function yb(e,t,n){return Gl(e[0])?.name===n?0:e[0]===t&&Gl(e[1])?.name===n?1:-1}function bb(e,t){return Zl(`${e} ${t.name}`,{aliases:t.aliases,description:t.description,commands:t.subcommands?.map(e=>({name:e.name,description:e.description}))})}function xb(e,t,n){let r=Kl(t,n);return Ql(`${e} ${t.name} ${n}`,{alias:r?.alias,aliases:r?.aliases,description:r?.description,hideGlobalOptions:!0,options:r?.options})}async function Sb(e,t,n){let r=[],i=[],a=new w,o=new w,s=[];o.on(`data`,e=>s.push(e.toString()));let c,l=j_(n.mcp?.name??e,n.version??`0.0.0`,t,{input:a,output:o,middlewares:n.middlewares,env:n.envSchema,vars:n.vars,version:n.version,...n.mcp?.instructions?{instructions:n.mcp.instructions}:void 0,...n.mcp?.title?{title:n.mcp.title}:void 0,tools:{...n.mcp?.tools,discovery:`direct`}}).catch(e=>{c=e}),u=!1;if(l.finally(()=>{u=!0}),a.write(`${Mr({jsonrpc:`2.0`,id:1,method:`initialize`,params:{protocolVersion:`2024-11-05`,capabilities:{},clientInfo:{name:`incur-doctor`,version:`1.0.0`}}})}\n`),a.write(`${Mr({jsonrpc:`2.0`,id:2,method:`tools/list`,params:{}})}\n`),await Cb(s,()=>u),a.end(),await l,c)return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_SERVER_FAILED`,message:Tb(c)}]};let d;try{d=wb(s)}catch(e){return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_RESPONSE_PARSE_FAILED`,message:Tb(e)}]}}let f=d.find(e=>e.id===1);f?f.error&&i.push({code:`MCP_INITIALIZE_FAILED`,message:Eb(f.error)}):i.push({code:`MCP_INITIALIZE_MISSING`,message:`Missing initialize response.`});let p=d.find(e=>e.id===2),m=[];return p?p.error?i.push({code:`MCP_TOOLS_LIST_FAILED`,message:Eb(p.error)}):!Zt(p.result)||!Array.isArray(p.result.tools)?i.push({code:`MCP_TOOLS_LIST_INVALID`,message:`tools/list did not return a tools array.`}):m=p.result.tools.filter(Zt).map(e=>({name:typeof e.name==`string`?e.name:``,...typeof e.description==`string`?{description:e.description}:void 0})).filter(e=>e.name):i.push({code:`MCP_TOOLS_LIST_MISSING`,message:`Missing tools/list response.`}),i.length===0&&m.length===0&&r.push(`No MCP tools exposed.`),{ok:i.length===0,toolCount:m.length,tools:m,warnings:r,errors:i}}async function Cb(e,t){let n=Date.now();for(;!t()&&(e.join(``).match(/\n/g)?.length??0)<2;){if(Date.now()-n>=1e3)return;await new Promise(e=>setTimeout(e,5))}}function wb(e){let t=[];for(let n of e.join(``).split(/\r?\n/)){let e=n.trim();if(!e)continue;let r=JSON.parse(e);if(!Zt(r))throw Error(`Expected JSON-RPC response object.`);t.push(r)}return t}function Tb(e){return e instanceof Error?e.message:String(e)}function Eb(e){return Zt(e)&&typeof e.message==`string`?e.message:Mr(e)}function Db(e,t){let n=[];return t?n.push(`${e} — ${t}`):n.push(e),n.push(``),n.push(`Usage: ${e} <path> [options]`),n.push(``),n.push(`Path segments are joined into the request URL path.`),n.push(``),n.push(`Options:`),n.push(` -X, --method <METHOD> HTTP method (default: GET, POST if body present)`),n.push(` -H, --header "Key: Val" Set a request header (repeatable)`),n.push(` -d, --data <json> Request body (implies POST)`),n.push(` --body <json> Request body (implies POST)`),n.push(` --<key> <value> Query string parameter`),n.join(`
222
222
  `)}async function Ob(e){if(e)return{directory:T(e)};let t=process.argv[1];if(!t)throw Error("Could not infer the filesystem command directory without an executed entrypoint. Pass a directory URL to `fs()`.");let n=s.resolve(t);try{let e=await S.realpath(n);return{directory:s.dirname(e),exclude:e}}catch(e){if(e.code!==`ENOENT`)throw e;return{directory:s.dirname(n),exclude:n}}}async function kb(e){let t=await hu(e.directory,{exclude:e.exclude});return Promise.all(t.map(async e=>({...e,command:(await import(ee(e.file).href)).default})))}function Ab(e){return typeof e==`object`&&!!e&&e[lx]===!0}function jb(e,t,n,r,i){let a=e;for(let[e,o]of t.entries()){let s=e===t.length-1,c=a.get(o);if(s){if(!c)a.set(o,n);else if(Lb(c)&&!c.root)c.root=n,c.description??=n.description;else throw Mb(t,r);Vb(t.join(` `),n,i);for(let e of n.aliases??[]){if(a.has(e))throw Mb([...t.slice(0,-1),e],r);a.set(e,{_alias:!0,target:o})}return}if(!c){let e={_group:!0,commands:new Map};a.set(o,e),a=e.commands;continue}if(zb(c)||Rb(c))throw Mb(t,r);if(Lb(c)){a=c.commands;continue}let l={_group:!0,commands:new Map,description:c.description,root:c};a.set(o,l),a=l.commands}}function Mb(e,t){return Error(`Filesystem command '${e.join(` `)}' from '${t}' conflicts with an existing command or alias.`)}function Nb(e){if(typeof e==`function`)return!0;if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.fetch==`function`&&t.url instanceof URL}function Pb(e){if(typeof e!=`object`||!e||!(`mcp`in e))return!1;let t=e.mcp;return typeof t==`string`||t instanceof URL||typeof t==`object`&&!!t&&`url`in t}function Fb(e){return typeof e==`function`?e:e.fetch}function Ib(e){return typeof e==`function`?void 0:e.url}function Lb(e){return`_group`in e}function Rb(e){return`_fetch`in e}function zb(e){return`_alias`in e}function Bb(e,t){return zb(t)?e.get(t.target):t}function Vb(e,t,n){if(!(!n||Rb(t)||zb(t))){if(Lb(t)){t.root&&Vb(e,t.root,n);for(let[r,i]of t.commands)Vb(`${e} ${r}`,i,n);return}if(t.options){let r=Object.keys(n.schema.shape),i=Object.keys(t.options.shape);for(let t of i)if(r.includes(t))throw Error(`Command '${e}' option '${t}' conflicts with a global option. Choose a different name.`)}if(n.alias&&t.alias){let r=new Set(Object.values(n.alias));for(let[n,i]of Object.entries(t.alias))if(i&&r.has(i))throw Error(`Command '${e}' alias '-${i}' for '${n}' conflicts with a global alias. Choose a different alias.`)}}}function Hb(e){let t=`${e.code===`UNKNOWN`||e.code===`COMMAND_NOT_FOUND`?`Error`:`Error (${e.code})`}: ${e.message}`;if(e.fieldErrors)for(let n of e.fieldErrors)t+=`\n ${n.path}: ${n.message}`;return t}function Ub(e){let t=[``,e.description],n=Math.max(...e.commands.map(e=>e.command.length));for(let r of e.commands){let e=r.description?` ${``.padEnd(n-r.command.length)}# ${r.description}`:``;t.push(` ${r.command}${e}`)}return t.join(`
223
- `)}function Wb(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return{description:t[0].description,commands:t.flatMap(e=>e.commands)}}function Gb(e){return Object.values(e.shape).some(e=>e._zod.optout!==`optional`)}function Kb(e){return typeof e==`object`&&!!e&&bx in e}async function qb(e,t){let n=t.format===`jsonl`;if(n||!t.formatExplicit&&t.format===`toon`)try{let r;for(;;){let{value:i,done:a}=await e.next();if(a){r=i;break}if(Kb(i)){let e=i;if(e[bx]===`error`){n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}}})):t.writeln(Hb({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}}n?t.writeln(Mr({type:`chunk`,data:i})):t.renderOutput&&t.writeln(t.truncate(ml(i,t.format)).text)}if(Kb(r)&&r[bx]===`error`){let e=r;n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}}})):t.writeln(Hb({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}let i=Kb(r)&&r[bx]===`ok`?du(t.name,r.cta):void 0;n?t.writeln(JSON.stringify({type:`done`,ok:!0,meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`,...i?{cta:i}:void 0}})):i&&t.writeln(Ub(i))}catch(e){n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof L?{retryable:e.retryable}:void 0}})):t.writeln(Hb({code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)})),t.exit(e instanceof L?e.exitCode??1:1)}else{let n=[];try{let r;for(;;){let{value:i,done:a}=await e.next();if(a){r=i;break}if(Kb(i)){let e=i;if(e[bx]===`error`){t.write({ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e.exitCode??1);return}}n.push(i)}if(Kb(r)&&r[bx]===`error`){let e=r;t.write({ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e.exitCode??1);return}let i=Kb(r)&&r[bx]===`ok`?du(t.name,r.cta):void 0;t.write({ok:!0,data:n,meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`,...i?{cta:i}:void 0}})}catch(e){t.write({ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof L?{retryable:e.retryable}:void 0},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e instanceof L?e.exitCode??1:1)}}}function Jb(e,t=[],n,r){let i=Yb(e,t);return r&&t.length>0&&i.push({name:t.join(` `),...r.description?{description:r.description}:void 0}),{version:`incur.v1`,commands:i.sort((e,t)=>e.name.localeCompare(t.name)),...n?{globals:Cu(n)}:void 0}}function Yb(e,t){let n=[];for(let[r,i]of e){if(zb(i))continue;let e=[...t,r];if(Lb(i)){if(i.root){let t={name:e.join(` `)};i.root.description&&(t.description=i.root.description),n.push(t)}n.push(...Yb(i.commands,e))}else{let t={name:e.join(` `)};Rb(i),i.description&&(t.description=i.description),n.push(t)}}return n}function Xb(e,t=[],n,r){let i=Zb(e,t);return r&&t.length>0&&i.push(Qb(t,r)),{version:`incur.v1`,commands:i.sort((e,t)=>e.name.localeCompare(t.name)),...n?{globals:Cu(n)}:void 0}}function Zb(e,t){let n=[];for(let[r,i]of e){if(zb(i))continue;let e=[...t,r];if(Rb(i)){let t={name:e.join(` `)};i.description&&(t.description=i.description),n.push(t)}else Lb(i)?(i.root&&n.push(Qb(e,i.root)),n.push(...Zb(i.commands,e))):n.push(Qb(e,i))}return n}function Qb(e,t){let n={name:e.join(` `)};t.description&&(n.description=t.description);let r=ax(t.args,t.env,t.options),i=t.output?Cu(t.output):void 0;(r||i)&&(n.schema={},r?.args&&(n.schema.args=r.args),r?.env&&(n.schema.env=r.env),r?.options&&(n.schema.options=r.options),i&&(n.schema.output=i));let a=rx(t.examples);if(a){let t=e.join(` `);n.examples=a.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function $b(e,t,n,r){let i=[];if(r){let e={};r.description&&(e.description=r.description),r.args&&(e.args=r.args),r.env&&(e.env=r.env),r.hint&&(e.hint=r.hint),tx(r)&&(e.hint=nx(e.hint)),r.options&&(e.options=r.options),r.output&&(e.output=r.output);let t=rx(r.examples);t&&(e.examples=t),i.push(e)}for(let[r,a]of e){if(zb(a))continue;let e=[...t,r];if(Rb(a)){let t={name:e.join(` `)};a.description&&(t.description=a.description),t.hint=`Fetch gateway. Pass path segments and curl-style flags (-X, -H, -d, --key value).`,i.push(t)}else Lb(a)?(a.description&&n.set(e.join(` `),a.description),a.root&&i.push(ex(e,a.root)),i.push(...$b(a.commands,e,n))):i.push(ex(e,a))}return i.sort((e,t)=>(e.name??``).localeCompare(t.name??``))}function ex(e,t){let n={name:e.join(` `)};t.description&&(n.description=t.description),t.args&&(n.args=t.args),t.env&&(n.env=t.env),t.hint&&(n.hint=t.hint),tx(t)&&(n.hint=nx(n.hint)),t.options&&(n.options=t.options),t.output&&(n.output=t.output);let r=rx(t.examples);if(r){let t=e.join(` `);n.examples=r.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function tx(e){return e.destructive===!0||e.mcp!==!1&&e.mcp?.annotations?.destructiveHint===!0}function nx(e){return e?e.includes(cx)?e:`${e} ${cx}`:cx}function rx(e){if(!(!e||e.length===0))return e.map(e=>{let t=[];if(e.args)for(let n of Object.values(e.args))t.push(String(n));if(e.options)for(let[n,r]of Object.entries(e.options))t.push(`--${n} ${r}`);let n={command:t.join(` `)};return e.description&&(n.description=e.description),n})}function ix(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return{};let n=dl().parse(t[1]);return!n||typeof n!=`object`?{}:n}function ax(e,t,n){if(!e&&!t&&!n)return;let r={};return e&&(r.args=Cu(e)),t&&(r.env=Cu(t)),n&&(r.options=Cu(n)),r}function ox(e,t,n){if(!t)return;let r=t.shape,i=new Set,a=new Map;for(let e of Object.keys(r))if(r[e]?.meta?.()?.deprecated){let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);i.add(t),n?.[e]&&a.set(n[e],t)}if(i.size!==0){for(let t of e)if(t.startsWith(`--`)){let e=t.split(`=`)[0].slice(2),n=!i.has(e)&&e.startsWith(`no-`)?e.slice(3):e;i.has(n)&&process.stderr.write(`Warning: --${n} is deprecated\n`)}else if(t.startsWith(`-`)&&t.length>=2)for(let e of t.slice(1))a.has(e)&&process.stderr.write(`Warning: --${a.get(e)} is deprecated\n`)}}function sx(e,t){let n=process.argv[1];if(!n)return e;let r=s.basename(n);return r===e?e:t?.includes(r)?r:e}var cx,lx,ux,dx,fx,px,mx,hx,gx,_x,vx,yx,bx,xx=I((()=>{Xt(),Pt(),gn(),xn(),kn(),Nn(),Sl(),uu(),Xl(),mu(),Su(),tn(),Pr(),Qe(),vt(),pl(),nv(),dy(),Zv(),zl(),wu(),Sy(),My(),tb(),cx=`Confirm with the user before executing this destructive command.`,lx=Symbol.for(`incur.fileCommand`),ux=new Set([`toon`,`json`,`yaml`,`md`,`jsonl`]),dx=new WeakMap,fx=new WeakMap,px=new WeakMap,mx=new WeakMap,hx=new WeakMap,gx=new WeakMap,_x=new WeakMap,vx=new WeakMap,yx=new WeakMap,bx=Symbol.for(`incur.sentinel`)})),Sx=I((()=>{Pt(),xx(),gn(),xn(),Sl(),uu(),nv(),kn(),Zv(),zl(),wu(),Sy(),pl(),My(),tb()}));function Cx(e,t){if(!(!e||typeof e!=`object`))return e[t]}var J,wx,Tx,Ex,Dx,Ox,kx=I((()=>{J={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},wx={payment:`Payment`},Tx={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Ex={charge:`charge`,session:`session`,subscription:`subscription`},Dx={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},Ox={v1:`v1`,v2:`v2`}}));function Ax(e){let t=O.toString(e);return JSON.parse(t)}function jx(e,t){return e.schema.request.parse(t)}function Mx(e){let t=te.canonicalize(e);return O.fromString(t,{pad:!1,url:!0})}var Nx=I((()=>{})),Y=Ke({address:()=>Bx,amount:()=>Fx,datetime:()=>Ix,datetimeInput:()=>Lx,hash:()=>Vx,period:()=>Hx,signature:()=>Ux,toDate:()=>Rx,toDatetimeString:()=>zx,unwrapOptional:()=>Wx});import*as Px from"zod/mini";Je(Y,Px);function Fx(){return ve.string().check(ve.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function Ix(){return ve.string().check(ve.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function Lx(e=`Invalid ISO 8601 datetime`){return ve.pipe(ve.union([Ix(),ve.custom(e=>e instanceof Date)]),ve.transform(Rx)).check(ve.refine(e=>Number.isFinite(e.getTime()),e))}function Rx(e){return e instanceof Date?e:new Date(e)}function zx(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function Bx(){return ve.string().check(ve.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function Vx(){return ve.string().check(ve.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function Hx(){return ve.string().check(ve.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function Ux(){return ve.string().check(ve.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function Wx(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}var Gx=I((()=>{}));function Kx(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=sS(o)?void 0:o,f=e.expires?zx(e.expires):void 0,p=e.opaque??(i===void 0?void 0:Mx(i)),m=u?cS({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return uS.parse({id:m,realm:c,method:a,intent:s,request:l,...n&&{description:n},...r&&{digest:r},...f&&{expires:f},...d!==void 0&&{header:d},...i!==void 0&&{meta:i},...p!==void 0&&{opaque:p}})}function qx(e){let t=[Jx(`id`,e.id),Jx(`realm`,e.realm),Jx(`method`,e.method),Jx(`intent`,e.intent),Jx(`request`,Mx(e.request))];e.description!==void 0&&t.push(Jx(`description`,e.description)),e.digest!==void 0&&t.push(Jx(`digest`,e.digest)),e.expires!==void 0&&t.push(Jx(`expires`,e.expires));let n=e.header;return n!==void 0&&!sS(n)&&t.push(Jx(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(Jx(`opaque`,Mx(e.meta))):t.push(Jx(`opaque`,e.opaque)),`${wx.payment} ${t.join(`, `)}`}function Jx(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function Yx(e,t){let n=Xx(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=Zx(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>lS)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return Kx({...a,request:Ax(r),...i&&{opaque:i}},t)}function Xx(e){let t=wx.payment,[n]=tS(e,t);if(n===void 0)return null;let r=n+t.length;for(;r<e.length&&/\s/.test(e[r]??``);)r++;return e.slice(r)}function Zx(e){let t=Object.create(null),n=0;for(;n<e.length;){for(;n<e.length&&/[\s,]/.test(e[n]??``);)n++;if(n>=e.length)break;let r=n;for(;n<e.length&&/[A-Za-z0-9_-]/.test(e[n]??``);)n++;let i=e.slice(r,n).toLowerCase();if(!i)throw Error(`Malformed auth-param.`);for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]!==`=`)break;for(n++;n<e.length&&/\s/.test(e[n]??``);)n++;let[a,o]=Qx(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function Qx(e,t){if(e[t]===`"`)return $x(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function $x(e,t){let n=t,r=!1,i=t,a;for(;n<e.length;){let o=e[n];if(n++,r){a??=[];let t=o===`u`?e.slice(n,n+4):void 0;t&&/^[0-9A-Fa-f]{4}$/.test(t)?(a.push(String.fromCharCode(Number.parseInt(t,16))),n+=4):a.push(o),i=n,r=!1;continue}if(o===`\\`){a??=[],a.push(e.slice(i,n-1)),i=n,r=!0;continue}if(o===`"`)return[a?[...a,e.slice(i,n-1)].join(``):e.slice(t,n-1),n]}throw Error(`Unterminated quoted-string.`)}function eS(e,t,n){if(e.slice(t,t+n.length).toLowerCase()!==n.toLowerCase())return!1;let r=e[t+n.length];return!!(r&&/\s/.test(r))}function tS(e,t){let n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(!eS(e,a,t))continue;let s=a-1;for(;s>=0&&/\s/.test(e[s]??``);)s--;s>=0&&e[s]!==`,`||n.push(a)}return n}function nS(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return rS(e.headers,t)}function rS(e,t){let n=e.get(J.wwwAuthenticate);if(!n)throw Error(`Missing ${J.wwwAuthenticate} header.`);return iS(n,t)}function iS(e,t){let n=tS(e,wx.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return Yx(e.slice(r,a).replace(/,\s*$/,``),t)})}function aS(e){let t=[e.realm,e.method,e.intent,Mx(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!sS(n)&&t.push(n),t.push(e.opaque??(e.meta?Mx(e.meta):``)),t.join(`|`)}function oS(e){return e.header??J.authorization}function sS(e){return e?.toLowerCase()===J.authorization.toLowerCase()}function cS(e,t){let n=aS(e),r=k.fromString(t.secretKey),i=k.fromString(n),a=A.hmac256(r,i,{as:`Bytes`});return O.fromBytes(a,{url:!0,pad:!1})}var lS,uS,dS=I((()=>{kx(),Nx(),Gx(),lS=16384,uS=Y.object({description:Y.optional(Y.string()),digest:Y.optional(Y.string().check(Y.regex(/^sha-256=/,`Invalid digest format`))),expires:Y.optional(Ix()),header:Y.optional(Y.string().check(Y.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:Y.string().check(Y.minLength(1)),intent:Y.string(),method:Y.string(),meta:Y.optional(Y.record(Y.string(),Y.string())),opaque:Y.optional(Y.string()),realm:Y.string(),request:Y.record(Y.string(),Y.unknown())})})),fS,pS,X,mS,hS=I((()=>{fS=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...e&&{challengeId:e}}}},pS=class extends fS{name=`InvalidChallengeError`;title=`Invalid Challenge`;status=402;type=`https://paymentauth.org/problems/invalid-challenge`;constructor(e={}){let{id:t,reason:n}=e,r=t?` "${t}"`:``,i=n?`: ${n}`:``;super(`Challenge${r} is invalid${i}.`)}},X=class extends fS{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,reason:n}=e;super(n?`Payment verification failed: ${n}.`:`Payment verification failed.`,{details:t})}},mS=class extends fS{name=`PaymentExpiredError`;title=`Payment Expired`;type=`https://paymentauth.org/problems/payment-expired`;constructor(e={}){let{expires:t}=e;super(t?`Payment expired at ${t}.`:`Payment has expired.`)}}}));function gS(e,t){if(!e)throw new pS({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new pS({...t&&{id:t},reason:`malformed expires timestamp`});if(new Date(e)<new Date)throw new mS({expires:e})}var _S=I((()=>{hS()}));function vS(e){return Object.defineProperty(e,bS,{value:!0}),e}function yS(e){return!!e?.[bS]}var bS,xS=I((()=>{bS=Symbol.for(`mppx.x402.challenge`)}));function SS(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=OS(n)}return t}function CS(e,t){let n=SS(e),r=FS(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[OS(e)]??1,index:t}));return{definition:r,entries:i,header:TS(i),keys:n}}function wS(e){let t=e.split(/\s*,\s*/).map(e=>e.trim()).filter(Boolean);if(t.length===0)throw Error(`Accept-Payment header is empty.`);return t.map((e,t)=>NS(e,t))}function TS(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${zS(n)}`}).join(`, `)}function ES(e,t,n){let r=DS(e,t,n)[0];if(r)return{challenge:r.challenge,method:r.method}}function DS(e,t,n){let r=new Map;for(let e of t){let t=OS(e),n=r.get(t);n?n.push(e):r.set(t,[e])}return e.flatMap((e,t)=>{let i=r.get(OS(e));if(!i)return[];let a=kS(e,n);return!a||a.q<=0?[]:i.filter(t=>t.canHandleChallenge?.({challenge:e})??!0).map(n=>({challenge:e,index:t,match:a,method:n}))}).sort((e,t)=>MS(e.challenge)-MS(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function OS(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function kS(e,t){let n;for(let r of t){if(!AS(e,r))continue;let t={...r,specificity:jS(r)};(!n||t.specificity>n.specificity||t.specificity===n.specificity&&t.q>n.q||t.specificity===n.specificity&&t.q===n.q&&t.index<n.index)&&(n=t)}return n}function AS(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function jS(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function MS(e){return+!!yS(e)}function NS(e,t){let n=/^(?<method>[^/;\s]+|\*)\s*\/\s*(?<intent>[^/;\s]+|\*)(?<params>(?:\s*;\s*.+)?)$/u.exec(e),r=n?.groups?.method,i=n?.groups?.intent;if(!r||!i)throw Error(`Invalid Accept-Payment entry: ${e}`);BS(r,`method`),BS(i,`intent`);let a=1;for(let t of PS(n.groups?.params)){if(!t)continue;let n=/^(?<name>[A-Za-z0-9_-]+)\s*=\s*(?<value>\S+)$/u.exec(t),r=n?.groups?.name,i=n?.groups?.value;if(!r||!i)throw Error(`Invalid Accept-Payment parameter: ${t}`);r===`q`&&(a=LS(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function PS(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function FS(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>OS(e))),a={};for(let[e,t]of Object.entries(r??{})){if(!i.has(e))throw Error(`Unknown payment preference "${e}". Available: ${[...i].join(`, `)}`);a[e]=IS(t,`payment preference "${e}"`)}return a}function IS(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return RS(e,t)}function LS(e,t){if(!/^0(?:\.\d{0,3})?$|^1(?:\.0{0,3})?$/.test(e))throw Error(`Invalid q-value for ${t}. Expected an HTTP qvalue.`);return RS(Number(e),t)}function RS(e,t){if(e<0||e>1)throw Error(`Invalid q-value for ${t}. Expected a value between 0 and 1.`);let n=Math.round(e*1e3);if(Math.abs(e*1e3-n)>1e-9)throw Error(`Invalid q-value for ${t}. Expected at most 3 decimal places.`);return n/1e3}function zS(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function BS(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}var VS=I((()=>{xS()}));function HS(e){let t=e.match(RegExp(`^${wx.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new qS;try{let e=O.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=US(r);return{challenge:uS.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Ax(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new JS}}function US(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!WS(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:Mx(e)}}function WS(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function GS(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function KS(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:Mx(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:Mx(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=O.fromString(s,{pad:!1,url:!0});return`${wx.payment} ${c}`}var qS,JS,YS=I((()=>{dS(),kx(),Nx(),qS=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},JS=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}}})),XS,ZS,QS=I((()=>{XS=`org.paymentauth/credential`,ZS=`org.paymentauth/payment-required`}));function $S(e){let{extensions:t,resource:n,...r}=e;return pC.parse(r)}var eC,tC,nC,rC,iC,aC,oC,sC,cC,lC,uC,dC,fC,pC,mC,hC,gC,_C,vC,yC,bC,xC,SC=I((()=>{Gx(),eC=`charge`,tC=[`exact`],nC=`eip155:`,rC=`x402:`,iC=`PAYMENT-REQUIRED`,aC=`PAYMENT-SIGNATURE`,oC=`PAYMENT-RESPONSE`,sC=Y.string().check(Y.minLength(1)),cC=Y.number().check(Y.refine(e=>e>0,`Must be positive`)),lC=Y.string().check(Y.regex(/^\d+$/,`Invalid atomic amount`)),uC=Bx(),dC=Y.string().check(Y.regex(RegExp(`^${nC}\\d+$`),`Invalid EVM CAIP-2 network`)),fC=Y.object({description:Y.optional(Y.string()),iconUrl:Y.optional(Y.string()),mimeType:Y.optional(Y.string()),serviceName:Y.optional(Y.string()),tags:Y.optional(Y.array(Y.string())),url:sC}),Y.discriminatedUnion(`type`,[Y.object({name:sC,type:Y.literal(`eip3009`),version:sC}),Y.object({name:Y.optional(Y.string()),type:Y.literal(`permit2`),version:Y.optional(Y.string())})]),pC=Y.object({amount:lC,asset:sC,extra:Y.optional(Y.record(Y.string(),Y.unknown())),maxTimeoutSeconds:cC,network:dC,payTo:sC,scheme:Y.enum(tC)}),mC=Y.object({info:Y.record(Y.string(),Y.unknown()),schema:Y.record(Y.string(),Y.unknown())}),hC=Y.record(Y.string(),mC),gC=Y.object({accepts:Y.array(pC).check(Y.minLength(1)),error:Y.optional(Y.string()),extensions:Y.optional(hC),resource:fC,x402Version:Y.literal(2)}),_C=Y.object({authorization:Y.object({from:uC,nonce:Vx(),to:uC,validAfter:lC,validBefore:lC,value:lC}),signature:Ux()}),vC=Y.object({permit2Authorization:Y.object({deadline:lC,from:uC,nonce:lC,permitted:Y.object({amount:lC,token:uC}),spender:uC,witness:Y.object({to:uC,validAfter:lC})}),signature:Ux()}),yC=Y.union([_C,vC]),bC=Y.object({accepted:pC,extensions:Y.optional(hC),payload:yC,resource:Y.optional(fC),x402Version:Y.literal(2)}),Y.object({extensions:Y.optional(hC),extra:Y.optional(Y.record(Y.string(),Y.unknown())),invalidMessage:Y.optional(Y.string()),invalidReason:Y.optional(Y.string()),isValid:Y.boolean(),payer:Y.optional(Y.string())}),xC=Y.object({amount:Y.optional(lC),errorMessage:Y.optional(Y.string()),errorReason:Y.optional(Y.string()),extensions:Y.optional(hC),extra:Y.optional(Y.record(Y.string(),Y.unknown())),network:sC,payer:Y.optional(Y.string()),success:Y.boolean(),transaction:Y.string()})}));function CC(e,t,n){let r=new Headers(e.headers);for(let e of wC)e===J.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}var wC,TC=I((()=>{kx(),SC(),wC=[J.authorization,iC,oC,aC]}));function EC(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 DC(e){let t=EC(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 OC(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 kC(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=uS.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 AC(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:kC(e.error.data):kC(e.result?._meta?.[ZS])}function jC(e,t){return!e||e.id!==t?[]:AC(e)?.challenges??[]}async function MC(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=!1,i,a=ye({onEvent(e){if(!(r||!e.data)&&(r=!0,!(e.event&&e.event!==`message`)))try{i=OC(JSON.parse(e.data))}catch{}}});try{for(;;){if(r)return i;let{done:e,value:o}=await t.read();if(e)return a.feed(n.decode()),a.reset({consume:!0}),i;a.feed(n.decode(o,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}function NC(e){let t=FC.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(t.includes(`application/json`))return e.clone().json().then(OC).catch(()=>void 0);if(t.includes(`text/event-stream`))return MC(e)})();return FC.set(e,n),n}function PC(){return{getChallenges(e,t){let n=DC(t);return e.status===402||n===void 0?[]:NC(e).then(e=>jC(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=HS(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,[XS]:r}}})}}}}var FC,IC=I((()=>{dS(),YS(),QS(),TC(),FC=new WeakMap}));function LC(){return{getChallenges(e){return e.status!==402||!e.headers.has(J.wwwAuthenticate)?[]:nS(e)},setCredential(e,t,n){return CC(e,n?.challenge?oS(n.challenge):J.authorization,t)}}}var RC=I((()=>{dS(),kx(),TC()}));function zC(e){return{encode(t){return O.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(O.toString(t)))}catch{throw new BC}}}}var BC,VC=I((()=>{BC=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}}}));function HC(e){try{let t=JSON.parse(O.toString(e));return qC(t)}catch{throw new BC}}var UC,WC,GC,KC,qC,JC=I((()=>{VC(),SC(),UC=zC(gC),WC=zC(bC),GC=zC(xC),UC.encode,UC.decode,KC=WC.encode,WC.decode,GC.encode,GC.decode,qC=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new BC;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new BC;let n=fC.parse(t.resource),r=t.extensions===void 0?void 0:hC.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}}}));function YC(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(iC);if(!t)return[];let n=HC(t);if(e.url&&n.resource.url!==e.url)throw Error(`x402 payment-required resource does not match response URL.`);return n.accepts.flatMap((e,t)=>{let r=pC.safeParse(e);if(!r.success)return[];let i=r.data;return vS(Kx({id:`${rC}${t}`,intent:eC,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return CC(e,aC,t)}}}var XC=I((()=>{dS(),JC(),xS(),SC(),TC()}));function ZC(e){return e}function QC(){let e=[LC(),YC(),PC()],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 ZC({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 $C=I((()=>{IC(),RC(),TC(),XC()}));function ew(e,t){return rw.set(e,t),e}function tw(e){return rw.has(e)}function nw(e,t){return Promise.resolve(rw.get(e)?.(t))}var rw,iw=I((()=>{rw=new WeakMap}));function aw(e,t){return uw.set(e,t),e}function ow(e){uw.delete(e)}function sw(e,t,n){uw.has(e)&&dw.set(t,n)}function cw(e){return dw.get(e)}function lw(e,t){return Promise.resolve(uw.get(e)?.(t)??t.response)}var uw,dw,fw=I((()=>{uw=new WeakMap,dw=new WeakMap}));async function pw(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 mw(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=Zw,methods:a,onChallenge:o,orderChallenges:s,transport:c=QC()}=e,l=e.eventDispatcher??_w(),u=t??CS(a),d=Rw(r),f=async(e,t,r)=>{let p=Lw(e,t?.headers),m=p.has(J.acceptPayment),h=Uw(p,u),g=Fw(e,t,p),_=Pw(e,t,p,h.header,m,n),v=await d(zw(_.input),_.init),y=Iw(_.init,await g);if(!await c.isPaymentRequired(v,y))return v;let b=t?.context,{context:x,orderChallenges:S,...C}=y??{},w,T,ee,E;try{for(let n=0;n<i;n++){T=await c.getChallenges(v,y);let i=(await Ww(DS(T,a,h.entries),S??s))[0];if(!i){if(await pw(E,{challenges:T,response:v,status:`rejected`}),n>0)return v;throw Error(`No method found for challenges: ${T.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let u=i.challenge;w=u,ee=i.method,w.expires&&gS(w.expires,w.id);let p=Yw(v,_.input,_.input),m=E,g=qx(u),x=m?.method===i.method&&m?.key===g,D=!1;if(m){let e=await pw(m,{challenges:T,response:v,status:x?`pending`:`rejected`});D=x&&!e}E=D?m:void 0;let O=Sw(async e=>{if(e===void 0&&D&&m)return m.promise;D&&m&&(await pw(m,{status:`rejected`}),E=void 0);let t=e??b;if(!tw(i.method))return Hw(u,i.method,t);let n={prepare:()=>nw(i.method,{challenge:u,context:t,fetch:d,input:p})},r=n.prepare().then(()=>Hw(u,i.method,t,n));return E={attempt:n,key:e===void 0?g:void 0,method:i.method,promise:r},r}),k=await l.emit(`challenge.received`,Cw({challenge:u,challenges:T,createCredential:O,init:t,input:e,method:i.method,response:v}))??(o?await o(w,{createCredential:O}):void 0)??await O(),A=E;A&&await A.promise.catch(()=>void 0)!==k&&(await pw(A,{status:`rejected`}),E=void 0),Vw(k),await l.emit(`credential.created`,ww({challenge:u,credential:k,init:t,input:e,method:i.method,response:v})),v=await d(p,c.setCredential({...C,headers:_.headers},k,{challenge:u}));let j=await c.isPaymentRequired(v,y);if(j||(await pw(A,{response:v,status:v.ok?`accepted`:`rejected`}),E=void 0),v.ok&&vw(l,`payment.response`)&&await l.emit(`payment.response`,Tw({challenge:u,credential:k,init:t,input:e,method:i.method,response:v})),!j)return v.ok?lw(i.method,{challenge:u,credential:k,fetch:d,headers:_.headers,input:p,...r?{refetch:()=>f(zw(_.input),t,!1)}:{},response:v,signal:Bw(e,t)}):v}T=void 0;try{T=await c.getChallenges(v,y)}catch{}return await pw(E,{challenges:T,response:v,status:`rejected`}),v}catch(n){throw await pw(E,{challenges:T,response:v,status:`rejected`}),await l.emit(`payment.failed`,Ew({challenge:w,challenges:T,error:n,init:t,input:e,method:ee,response:v})),n}},p=(e,t)=>f(e,t,!0);return p[Xw]=d,p}function hw(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);Qw||=globalThis.fetch,globalThis.fetch=mw({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??(qw()?`same-origin`:`always`),fetch:globalThis.fetch})}function gw(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 _w(){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 yw(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await xw(e[`*`],t,n),r}case`credential.created`:await bw(e[`credential.created`],n),await xw(e[`*`],t,n);return;case`payment.failed`:await bw(e[`payment.failed`],n),await xw(e[`*`],t,n);return;case`payment.response`:await bw(e[`payment.response`],n),await xw(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 $w.set(t,t=>e[t].size>0||e[`*`].size>0),t}function vw(e,t){return $w.get(e)?.(t)??!0}async function yw(e,t){try{return await e(t)}catch{return}}async function bw(e,t){for(let n of e)try{await n(t)}catch{}}async function xw(e,t,n){await bw(e,Object.freeze({name:t,payload:n}))}function Sw(e){let t;return n=>(t??=e(n),t)}function Cw(e){return Object.freeze({challenge:jw(e.challenge),challenges:e.challenges.map(e=>jw(e)),createCredential:e.createCredential,init:Dw(e.init),input:Ow(e.input),method:kw(e.method),response:Aw(e.response)})}function ww(e){return Object.freeze({challenge:jw(e.challenge),credential:e.credential,init:Dw(e.init),input:Ow(e.input),method:kw(e.method),...e.response===void 0?{}:{response:Aw(e.response)}})}function Tw(e){return Object.freeze({challenge:jw(e.challenge),credential:e.credential,init:Dw(e.init),input:Ow(e.input),method:kw(e.method),response:Aw(e.response)})}function Ew(e){return Object.freeze({...e.challenge?{challenge:jw(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>jw(e))}:{},error:e.error,init:Dw(e.init),input:Ow(e.input),...e.method?{method:kw(e.method)}:{},...e.response===void 0?{}:{response:Aw(e.response)}})}function Dw(e){if(e)return Nw({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function Ow(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function kw(e){return Nw(Object.assign({},e))}function Aw(e){return e instanceof Response?e.clone():jw(e)}function jw(e){try{return Mw(structuredClone(e))}catch{return Nw(e)}}function Mw(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Mw(t);return e}function Nw(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function Pw(e,t,n,r,i,a){let o=!!r&&!i&&Gw(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(J.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function Fw(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 Iw(e,t){return t===void 0?e:{...e,body:t}}function Lw(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function Rw(e){let t=e;for(;t[Xw];)t=t[Xw];return t}function zw(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Bw(e,t){return t?.signal??(e instanceof Request?e.signal:void 0)}function Vw(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
224
- `))throw Error(`Credential header value contains illegal newline characters`)}async function Hw(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&&sw(t,a,r),t.createCredential(a)}function Uw(e,t){let n=e.get(J.acceptPayment);if(!n)return t;try{return{...t,entries:wS(n),header:n}}catch{return t}}async function Ww(e,t){return t?t(e):e}function Gw(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=Jw(e);return t===`same-origin`?!qw()||n.origin===globalThis.location.origin:t.origins.some(e=>Kw(n,e))}function Kw(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 qw(){return globalThis.location!==void 0}function Jw(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,qw()?globalThis.location.href:void 0)}function Yw(e,t,n){if(!e.url)return t;let r=new URL(e.url),i=Jw(n);if(r.origin!==i.origin)throw Error(`Refusing to send payment credential across redirect from ${i.origin} to ${r.origin}`);return e.url}var Xw,Zw,Qw,$w,eT=I((()=>{dS(),kx(),_S(),VS(),$C(),iw(),fw(),Xw=Symbol.for(`mppx.fetch.wrapper`),Zw=3,$w=new WeakMap}));Sx(),eT();function tT(){let e=new Uint8Array(64);return crypto.getRandomValues(e),Object.freeze({created:Math.floor(Date.now()/1e3),nonce:O.fromBytes(e,{pad:!1,url:!0})})}function nT(...e){return{protocol:`composed`,async sign(t,n=tT()){for(let r of e)t=await r.sign(t,n);return t}}}function rT(e,t){return async(n,r)=>e(await t.sign(new Request(n,r)))}_S(),VS(),$C();function iT(e){let{attestation:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=QC()}=e,c=e.fetch??globalThis.fetch,l=t?aT(c,t):c,u=e.methods.flat(),d=CS(u,e.paymentPreferences),f=_w(),p=r,m={acceptPayment:d,acceptPaymentPolicy:o,...(e.fetch||t)&&{fetch:l},eventDispatcher:f,...n!==void 0&&{maxPaymentRetries:n},...p&&{onChallenge:p},...i&&{orderChallenges:i},methods:u,transport:s},h=mw(m);a&&hw(m);function g(e){return f.on(`challenge.received`,e)}function _(e){return f.on(`credential.created`,e)}function v(e){return f.on(`payment.failed`,e)}function y(e){return f.on(`payment.response`,e)}async function b(e,t){let n=dT(e),r=await s.getChallenges(e,t?.request),a=Object.freeze(r.map(e=>fT(e))),o=hT(d.entries,t?.acceptPayment),c,l;try{let e=(await gT(DS(r,u,o),t?.orderChallenges??i))[0];if(!e)throw Error(`No method found for challenges: ${r.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${u.map(e=>`${e.name}.${e.intent}`).join(`, `)}`);let d=e.challenge;c=a[e.index],l=e.method,c.expires&&gS(c.expires,c.id);let p=c,m=l,h=oT(async e=>{try{p.expires&&gS(p.expires,p.id);let t=oT(t=>_T(p,m,t??e)),i=await f.emit(`challenge.received`,sT({challenge:p,challenges:r,createCredential:t,method:m,response:n}))??await t();return Vw(i),await f.emit(`credential.created`,cT({challenge:p,credential:i,method:m,response:n})),i}catch(e){throw await f.emit(`payment.failed`,lT({challenge:p,challenges:r,error:e,method:m,response:n})),e}});return Object.freeze({challenge:p,challenges:a,createCredential:h,method:uT(m),setCredential(e,t){return Vw(t),s.setCredential(e,t,{challenge:d})}})}catch(e){throw await f.emit(`payment.failed`,lT({challenge:c,challenges:r,error:e,method:l,response:n})),e}}return{fetch:h,rawFetch:c,methods:u,transport:s,on:f.on,onChallengeReceived:g,onCredentialCreated:_,onPaymentFailed:v,onPaymentResponse:y,preparePayment:b,async createCredential(e,t,n){return(await b(e,n)).createCredential(t)}}}function aT(e,t){let n=Object.values(t);if(n.length===0)throw TypeError(`Mppx client attestation must configure at least one signer.`);return rT(e,nT(...n))}function oT(e){let t;return n=>(t??=e(n),t)}function sT(e){return Object.freeze({challenge:fT(e.challenge),challenges:e.challenges.map(e=>fT(e)),createCredential:e.createCredential,method:uT(e.method),response:dT(e.response)})}function cT(e){return Object.freeze({challenge:fT(e.challenge),credential:e.credential,method:uT(e.method),response:dT(e.response)})}function lT(e){return Object.freeze({...e.challenge?{challenge:fT(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>fT(e))}:{},error:e.error,...e.method?{method:uT(e.method)}:{},response:dT(e.response)})}function uT(e){return mT(Object.assign({},e))}function dT(e){if(e instanceof Response)try{return e.clone()}catch{return new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText})}return fT(e)}function fT(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 pT(t)}catch{return mT(e)}}function pT(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))pT(t);return e}function mT(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function hT(e,t){return t?typeof t==`string`?wS(t):t:e}async function gT(e,t){return t?t(e):e}async function _T(e,t,n){let r=t.context&&n!==void 0?t.context.parse(n):void 0;return t.createCredential(r===void 0?{challenge:e}:{challenge:e,context:r})}function vT(){return Y.string().check(Y.regex(yT,`Invalid URI or path`))}var yT,bT,xT,ST,CT,wT,TT,ET,DT,OT=I((()=>{Gx(),yT=/^([a-zA-Z][a-zA-Z\d+.-]*:\/\/\S+|\/\S*)$/,bT=new Set([`amount`,`currency`,`description`,`intent`,`method`]),xT=Y.looseObject({amount:Y.optional(Y.union([Y.null(),Y.string().check(Y.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:Y.optional(Y.string()),description:Y.optional(Y.string()),intent:Y.optional(Y.string()),method:Y.optional(Y.string())}),ST=Y.pipe(Y.looseObject({amount:Y.optional(Y.union([Y.null(),Y.string().check(Y.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:Y.optional(Y.string()),description:Y.optional(Y.string()),intent:Y.optional(Y.string()),method:Y.optional(Y.string()),offers:Y.optional(Y.array(xT).check(Y.minLength(1)))}).check(Y.refine(e=>e.offers===void 0||Object.keys(e).every(e=>e===`offers`||!bT.has(e)),`Cannot mix offers with flat payment info fields`)),Y.transform(e=>{if(e.offers)return{offers:e.offers};let t={};for(let[n,r]of Object.entries(e))n!==`offers`&&(bT.has(n)||r!==void 0)&&(t[n]=r);return{offers:[t]}})),CT=Y.looseObject({apiReference:Y.optional(vT()),homepage:Y.optional(vT()),llms:Y.optional(vT())}),wT=Y.looseObject({categories:Y.optional(Y.array(Y.string())),docs:Y.optional(CT)}),TT=Y.looseObject({"x-payment-info":Y.optional(ST),requestBody:Y.optional(Y.unknown()),responses:Y.optional(Y.record(Y.string(),Y.unknown())),summary:Y.optional(Y.string())}),ET=Y.looseObject({delete:Y.optional(TT),get:Y.optional(TT),head:Y.optional(TT),options:Y.optional(TT),patch:Y.optional(TT),post:Y.optional(TT),put:Y.optional(TT),trace:Y.optional(TT)}),DT=Y.looseObject({openapi:Y.string(),info:Y.looseObject({title:Y.string(),version:Y.string()}),"x-service-info":Y.optional(wT),paths:Y.optional(Y.record(Y.string(),ET))})}));OT();function kT(e){let t=[],n=DT.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=ST.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}function AT(e){return e}function jT(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}var MT=I((()=>{}));function NT(e){return Y.refine(e=>{let{amount:t,decimals:n}=e;return P(t,n)>0n},e)}function PT(e){let{periodCount:t,periodUnit:n}=e;try{let e=RT[n];return e!==void 0&&BigInt(t)*e<=LT}catch{return!1}}var FT,IT,LT,RT,zT,BT,VT,HT,UT,WT,GT,KT,qT,JT=I((()=>{kx(),MT(),Gx(),FT=[`push`,`pull`],IT=Y.object({amount:Fx(),memo:Y.optional(Vx()),recipient:Y.pipe(Y.string(),Y.transform(e=>e))}),LT=(1n<<64n)-1n,RT={dev_second:1n,day:86400n,week:604800n},zT=Y.pipe(Bx(),Y.transform(e=>e.toLowerCase())),BT=Y.object({accessKeyAddress:zT,keyType:Y.enum([`p256`,`secp256k1`,`webAuthn`])}),VT=Y.object({accessKey:Y.optional(BT),chainId:Y.optional(Y.number())}),HT=Lx(`subscriptionExpires must be a valid date`).check(Y.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),UT=Y.enum([`dev_second`,`day`,`week`]),WT=Y.pipe(Y.union([Y.string(),Y.bigint(),Y.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),Y.transform(e=>e.toString())).check(Y.regex(/^[1-9]\d*$/,`Invalid periodCount`),Y.refine(e=>{try{return BigInt(e)<=LT}catch{return!1}},`periodCount exceeds uint64`)),GT=AT({name:`tempo`,intent:`charge`,schema:{credential:{payload:Y.discriminatedUnion(`type`,[Y.object({hash:Vx(),type:Y.literal(`hash`)}),Y.object({signature:Ux(),type:Y.literal(`transaction`)}),Y.object({signature:Ux(),type:Y.literal(`proof`)})])},request:Y.pipe(Y.object({amount:Fx(),chainId:Y.optional(Y.number()),currency:Y.string(),decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),feePayer:Y.optional(Y.pipe(Y.union([Y.boolean(),Y.custom()]),Y.transform(e=>typeof e==`object`||e))),memo:Y.optional(Vx()),recipient:Y.optional(Y.string()),splits:Y.optional(Y.array(IT).check(Y.minLength(1),Y.maxLength(10))),supportedModes:Y.optional(Y.array(Y.enum(FT)).check(Y.minLength(1)))}).check(Y.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`)),Y.transform(({amount:e,chainId:t,decimals:n,feePayer:r,memo:i,splits:a,supportedModes:o,...s})=>({...s,amount:P(e,n).toString(),...t!==void 0||r!==void 0||i!==void 0||a!==void 0||o!==void 0?{methodDetails:{...t!==void 0&&{chainId:t},...r!==void 0&&{feePayer:r},...i!==void 0&&{memo:i},...a!==void 0&&{splits:a.map(e=>({...e,amount:P(e.amount,n).toString()}))},...o!==void 0&&{supportedModes:o}}}:{}})))}}),KT=AT({name:`tempo`,intent:`session`,schema:{credential:{payload:Y.discriminatedUnion(`action`,[Y.object({action:Y.literal(`open`),authorizedSigner:Y.optional(Y.string()),channelId:Vx(),cumulativeAmount:Fx(),descriptor:Y.optional(Y.custom()),signature:Ux(),transaction:Ux(),type:Y.literal(`transaction`)}),Y.object({action:Y.literal(`topUp`),additionalDeposit:Fx(),channelId:Vx(),descriptor:Y.optional(Y.custom()),transaction:Ux(),type:Y.literal(`transaction`)}),Y.object({action:Y.literal(`voucher`),channelId:Vx(),cumulativeAmount:Fx(),descriptor:Y.optional(Y.custom()),signature:Ux()}),Y.object({action:Y.literal(`close`),channelId:Vx(),cumulativeAmount:Fx(),descriptor:Y.optional(Y.custom()),signature:Ux()})])},request:Y.pipe(Y.object({amount:Fx(),chainId:Y.optional(Y.number()),channelId:Y.optional(Vx()),currency:Y.string(),decimals:Y.number(),escrowContract:Y.optional(Y.string()),feePayer:Y.optional(Y.pipe(Y.union([Y.boolean(),Y.custom()]),Y.transform(e=>typeof e==`object`||e))),feeToken:Y.optional(Bx()),minVoucherDelta:Y.optional(Fx()),operator:Y.optional(Bx()),recipient:Y.optional(Y.string()),sessionProtocol:Y.optional(Y.enum([Ox.v2,Ox.v1])),sessionSnapshot:Y.optional(Y.custom()),suggestedDeposit:Y.optional(Fx()),unitType:Y.string()}).check(Y.refine(({amount:e,decimals:t})=>P(e,t)>0n,`Session amount must be greater than 0`)),Y.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&&{[Dx.sessionProtocol]:l},...u!==void 0&&{[Dx.sessionSnapshot]:u}}})))}}),qT=AT({name:`tempo`,intent:`subscription`,schema:{credential:{payload:Y.object({signature:Ux(),type:Y.literal(`keyAuthorization`)})},request:Y.pipe(Y.object({amount:Fx(),accessKey:Y.optional(BT),chainId:Y.optional(Y.number()),currency:zT,decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),methodDetails:Y.optional(VT),periodCount:WT,periodUnit:UT,recipient:zT,subscriptionExpires:HT}).check(NT(`Subscription amount must be greater than 0`),Y.refine(PT,`Subscription period exceeds uint64`)),Y.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 YT(e){return e>=0n&&e<=mE}function XT(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return YT(t)?t:void 0}function ZT(e){return QT(e),e}function QT(e){if(!YT(e))throw Error(`Value ${e} is outside uint96 bounds.`)}function $T(e){return typeof e==`object`&&!!e}function eE(e){return typeof e==`string`&&hE.has(e)}function tE(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!eE(t.action))}function nE(e,t=`No session credential context available.`){if(!tE(e))throw Error(t);return e}function rE(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function iE(e){return $T(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function aE(e){return $T(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 oE(e){let t=O.toString(e),n=JSON.parse(t);if(!aE(n))throw Error(`Invalid session receipt.`);return n}function sE(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function cE(e){let t=`message`,n=[];for(let r of e.split(`
223
+ `)}function Wb(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return{description:t[0].description,commands:t.flatMap(e=>e.commands)}}function Gb(e){return Object.values(e.shape).some(e=>e._zod.optout!==`optional`)}function Kb(e){return typeof e==`object`&&!!e&&bx in e}async function qb(e,t){let n=t.format===`jsonl`;if(n||!t.formatExplicit&&t.format===`toon`)try{let r;for(;;){let{value:i,done:a}=await e.next();if(a){r=i;break}if(Kb(i)){let e=i;if(e[bx]===`error`){n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}}})):t.writeln(Hb({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}}n?t.writeln(Mr({type:`chunk`,data:i})):t.renderOutput&&t.writeln(t.truncate(ml(i,t.format)).text)}if(Kb(r)&&r[bx]===`error`){let e=r;n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}}})):t.writeln(Hb({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}let i=Kb(r)&&r[bx]===`ok`?du(t.name,r.cta):void 0;n?t.writeln(JSON.stringify({type:`done`,ok:!0,meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`,...i?{cta:i}:void 0}})):i&&t.writeln(Ub(i))}catch(e){n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof L?{retryable:e.retryable}:void 0}})):t.writeln(Hb({code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)})),t.exit(e instanceof L?e.exitCode??1:1)}else{let n=[];try{let r;for(;;){let{value:i,done:a}=await e.next();if(a){r=i;break}if(Kb(i)){let e=i;if(e[bx]===`error`){t.write({ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e.exitCode??1);return}}n.push(i)}if(Kb(r)&&r[bx]===`error`){let e=r;t.write({ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e.exitCode??1);return}let i=Kb(r)&&r[bx]===`ok`?du(t.name,r.cta):void 0;t.write({ok:!0,data:n,meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`,...i?{cta:i}:void 0}})}catch(e){t.write({ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof L?{retryable:e.retryable}:void 0},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e instanceof L?e.exitCode??1:1)}}}function Jb(e,t=[],n,r){let i=Yb(e,t);return r&&t.length>0&&i.push({name:t.join(` `),...r.description?{description:r.description}:void 0}),{version:`incur.v1`,commands:i.sort((e,t)=>e.name.localeCompare(t.name)),...n?{globals:Cu(n)}:void 0}}function Yb(e,t){let n=[];for(let[r,i]of e){if(zb(i))continue;let e=[...t,r];if(Lb(i)){if(i.root){let t={name:e.join(` `)};i.root.description&&(t.description=i.root.description),n.push(t)}n.push(...Yb(i.commands,e))}else{let t={name:e.join(` `)};Rb(i),i.description&&(t.description=i.description),n.push(t)}}return n}function Xb(e,t=[],n,r){let i=Zb(e,t);return r&&t.length>0&&i.push(Qb(t,r)),{version:`incur.v1`,commands:i.sort((e,t)=>e.name.localeCompare(t.name)),...n?{globals:Cu(n)}:void 0}}function Zb(e,t){let n=[];for(let[r,i]of e){if(zb(i))continue;let e=[...t,r];if(Rb(i)){let t={name:e.join(` `)};i.description&&(t.description=i.description),n.push(t)}else Lb(i)?(i.root&&n.push(Qb(e,i.root)),n.push(...Zb(i.commands,e))):n.push(Qb(e,i))}return n}function Qb(e,t){let n={name:e.join(` `)};t.description&&(n.description=t.description);let r=ax(t.args,t.env,t.options),i=t.output?Cu(t.output):void 0;(r||i)&&(n.schema={},r?.args&&(n.schema.args=r.args),r?.env&&(n.schema.env=r.env),r?.options&&(n.schema.options=r.options),i&&(n.schema.output=i));let a=rx(t.examples);if(a){let t=e.join(` `);n.examples=a.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function $b(e,t,n,r){let i=[];if(r){let e={};r.description&&(e.description=r.description),r.args&&(e.args=r.args),r.env&&(e.env=r.env),r.hint&&(e.hint=r.hint),tx(r)&&(e.hint=nx(e.hint)),r.options&&(e.options=r.options),r.output&&(e.output=r.output);let t=rx(r.examples);t&&(e.examples=t),i.push(e)}for(let[r,a]of e){if(zb(a))continue;let e=[...t,r];if(Rb(a)){let t={name:e.join(` `)};a.description&&(t.description=a.description),t.hint=`Fetch gateway. Pass path segments and curl-style flags (-X, -H, -d, --key value).`,i.push(t)}else Lb(a)?(a.description&&n.set(e.join(` `),a.description),a.root&&i.push(ex(e,a.root)),i.push(...$b(a.commands,e,n))):i.push(ex(e,a))}return i.sort((e,t)=>(e.name??``).localeCompare(t.name??``))}function ex(e,t){let n={name:e.join(` `)};t.description&&(n.description=t.description),t.args&&(n.args=t.args),t.env&&(n.env=t.env),t.hint&&(n.hint=t.hint),tx(t)&&(n.hint=nx(n.hint)),t.options&&(n.options=t.options),t.output&&(n.output=t.output);let r=rx(t.examples);if(r){let t=e.join(` `);n.examples=r.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function tx(e){return e.destructive===!0||e.mcp!==!1&&e.mcp?.annotations?.destructiveHint===!0}function nx(e){return e?e.includes(cx)?e:`${e} ${cx}`:cx}function rx(e){if(!(!e||e.length===0))return e.map(e=>{let t=[];if(e.args)for(let n of Object.values(e.args))t.push(String(n));if(e.options)for(let[n,r]of Object.entries(e.options))t.push(`--${n} ${r}`);let n={command:t.join(` `)};return e.description&&(n.description=e.description),n})}function ix(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return{};let n=dl().parse(t[1]);return!n||typeof n!=`object`?{}:n}function ax(e,t,n){if(!e&&!t&&!n)return;let r={};return e&&(r.args=Cu(e)),t&&(r.env=Cu(t)),n&&(r.options=Cu(n)),r}function ox(e,t,n){if(!t)return;let r=t.shape,i=new Set,a=new Map;for(let e of Object.keys(r))if(r[e]?.meta?.()?.deprecated){let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);i.add(t),n?.[e]&&a.set(n[e],t)}if(i.size!==0){for(let t of e)if(t.startsWith(`--`)){let e=t.split(`=`)[0].slice(2),n=!i.has(e)&&e.startsWith(`no-`)?e.slice(3):e;i.has(n)&&process.stderr.write(`Warning: --${n} is deprecated\n`)}else if(t.startsWith(`-`)&&t.length>=2)for(let e of t.slice(1))a.has(e)&&process.stderr.write(`Warning: --${a.get(e)} is deprecated\n`)}}function sx(e,t){let n=process.argv[1];if(!n)return e;let r=s.basename(n);return r===e?e:t?.includes(r)?r:e}var cx,lx,ux,dx,fx,px,mx,hx,gx,_x,vx,yx,bx,xx=I((()=>{Xt(),Pt(),gn(),xn(),kn(),Nn(),Sl(),uu(),Xl(),mu(),Su(),tn(),Pr(),Qe(),vt(),pl(),nv(),dy(),Zv(),zl(),wu(),Sy(),My(),tb(),cx=`Confirm with the user before executing this destructive command.`,lx=Symbol.for(`incur.fileCommand`),ux=new Set([`toon`,`json`,`yaml`,`md`,`jsonl`]),dx=new WeakMap,fx=new WeakMap,px=new WeakMap,mx=new WeakMap,hx=new WeakMap,gx=new WeakMap,_x=new WeakMap,vx=new WeakMap,yx=new WeakMap,bx=Symbol.for(`incur.sentinel`)})),Sx=I((()=>{Pt(),xx(),gn(),xn(),Sl(),uu(),nv(),kn(),Zv(),zl(),wu(),Sy(),pl(),My(),tb()}));function Cx(e,t){if(!(!e||typeof e!=`object`))return e[t]}var J,wx,Tx,Ex,Dx,Ox,kx=I((()=>{J={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},wx={payment:`Payment`},Tx={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Ex={charge:`charge`,session:`session`,subscription:`subscription`},Dx={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},Ox={v1:`v1`,v2:`v2`}}));function Ax(e){let t=O.toString(e);return JSON.parse(t)}function jx(e,t){return e.schema.request.parse(t)}function Mx(e){let t=ne.canonicalize(e);return O.fromString(t,{pad:!1,url:!0})}var Nx=I((()=>{})),Y=Ke({address:()=>Bx,amount:()=>Fx,datetime:()=>Ix,datetimeInput:()=>Lx,hash:()=>Vx,period:()=>Hx,signature:()=>Ux,toDate:()=>Rx,toDatetimeString:()=>zx,unwrapOptional:()=>Wx});import*as Px from"zod/mini";Je(Y,Px);function Fx(){return ve.string().check(ve.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function Ix(){return ve.string().check(ve.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function Lx(e=`Invalid ISO 8601 datetime`){return ve.pipe(ve.union([Ix(),ve.custom(e=>e instanceof Date)]),ve.transform(Rx)).check(ve.refine(e=>Number.isFinite(e.getTime()),e))}function Rx(e){return e instanceof Date?e:new Date(e)}function zx(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function Bx(){return ve.string().check(ve.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function Vx(){return ve.string().check(ve.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function Hx(){return ve.string().check(ve.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function Ux(){return ve.string().check(ve.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function Wx(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}var Gx=I((()=>{}));function Kx(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=sS(o)?void 0:o,f=e.expires?zx(e.expires):void 0,p=e.opaque??(i===void 0?void 0:Mx(i)),m=u?cS({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return uS.parse({id:m,realm:c,method:a,intent:s,request:l,...n&&{description:n},...r&&{digest:r},...f&&{expires:f},...d!==void 0&&{header:d},...i!==void 0&&{meta:i},...p!==void 0&&{opaque:p}})}function qx(e){let t=[Jx(`id`,e.id),Jx(`realm`,e.realm),Jx(`method`,e.method),Jx(`intent`,e.intent),Jx(`request`,Mx(e.request))];e.description!==void 0&&t.push(Jx(`description`,e.description)),e.digest!==void 0&&t.push(Jx(`digest`,e.digest)),e.expires!==void 0&&t.push(Jx(`expires`,e.expires));let n=e.header;return n!==void 0&&!sS(n)&&t.push(Jx(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(Jx(`opaque`,Mx(e.meta))):t.push(Jx(`opaque`,e.opaque)),`${wx.payment} ${t.join(`, `)}`}function Jx(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function Yx(e,t){let n=Xx(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=Zx(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>lS)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return Kx({...a,request:Ax(r),...i&&{opaque:i}},t)}function Xx(e){let t=wx.payment,[n]=tS(e,t);if(n===void 0)return null;let r=n+t.length;for(;r<e.length&&/\s/.test(e[r]??``);)r++;return e.slice(r)}function Zx(e){let t=Object.create(null),n=0;for(;n<e.length;){for(;n<e.length&&/[\s,]/.test(e[n]??``);)n++;if(n>=e.length)break;let r=n;for(;n<e.length&&/[A-Za-z0-9_-]/.test(e[n]??``);)n++;let i=e.slice(r,n).toLowerCase();if(!i)throw Error(`Malformed auth-param.`);for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]!==`=`)break;for(n++;n<e.length&&/\s/.test(e[n]??``);)n++;let[a,o]=Qx(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function Qx(e,t){if(e[t]===`"`)return $x(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function $x(e,t){let n=t,r=!1,i=t,a;for(;n<e.length;){let o=e[n];if(n++,r){a??=[];let t=o===`u`?e.slice(n,n+4):void 0;t&&/^[0-9A-Fa-f]{4}$/.test(t)?(a.push(String.fromCharCode(Number.parseInt(t,16))),n+=4):a.push(o),i=n,r=!1;continue}if(o===`\\`){a??=[],a.push(e.slice(i,n-1)),i=n,r=!0;continue}if(o===`"`)return[a?[...a,e.slice(i,n-1)].join(``):e.slice(t,n-1),n]}throw Error(`Unterminated quoted-string.`)}function eS(e,t,n){if(e.slice(t,t+n.length).toLowerCase()!==n.toLowerCase())return!1;let r=e[t+n.length];return!!(r&&/\s/.test(r))}function tS(e,t){let n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(!eS(e,a,t))continue;let s=a-1;for(;s>=0&&/\s/.test(e[s]??``);)s--;s>=0&&e[s]!==`,`||n.push(a)}return n}function nS(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return rS(e.headers,t)}function rS(e,t){let n=e.get(J.wwwAuthenticate);if(!n)throw Error(`Missing ${J.wwwAuthenticate} header.`);return iS(n,t)}function iS(e,t){let n=tS(e,wx.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return Yx(e.slice(r,a).replace(/,\s*$/,``),t)})}function aS(e){let t=[e.realm,e.method,e.intent,Mx(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!sS(n)&&t.push(n),t.push(e.opaque??(e.meta?Mx(e.meta):``)),t.join(`|`)}function oS(e){return e.header??J.authorization}function sS(e){return e?.toLowerCase()===J.authorization.toLowerCase()}function cS(e,t){let n=aS(e),r=k.fromString(t.secretKey),i=k.fromString(n),a=te.hmac256(r,i,{as:`Bytes`});return O.fromBytes(a,{url:!0,pad:!1})}var lS,uS,dS=I((()=>{kx(),Nx(),Gx(),lS=16384,uS=Y.object({description:Y.optional(Y.string()),digest:Y.optional(Y.string().check(Y.regex(/^sha-256=/,`Invalid digest format`))),expires:Y.optional(Ix()),header:Y.optional(Y.string().check(Y.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:Y.string().check(Y.minLength(1)),intent:Y.string(),method:Y.string(),meta:Y.optional(Y.record(Y.string(),Y.string())),opaque:Y.optional(Y.string()),realm:Y.string(),request:Y.record(Y.string(),Y.unknown())})})),fS,pS,X,mS,hS=I((()=>{fS=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...e&&{challengeId:e}}}},pS=class extends fS{name=`InvalidChallengeError`;title=`Invalid Challenge`;status=402;type=`https://paymentauth.org/problems/invalid-challenge`;constructor(e={}){let{id:t,reason:n}=e,r=t?` "${t}"`:``,i=n?`: ${n}`:``;super(`Challenge${r} is invalid${i}.`)}},X=class extends fS{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,reason:n}=e;super(n?`Payment verification failed: ${n}.`:`Payment verification failed.`,{details:t})}},mS=class extends fS{name=`PaymentExpiredError`;title=`Payment Expired`;type=`https://paymentauth.org/problems/payment-expired`;constructor(e={}){let{expires:t}=e;super(t?`Payment expired at ${t}.`:`Payment has expired.`)}}}));function gS(e,t){if(!e)throw new pS({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new pS({...t&&{id:t},reason:`malformed expires timestamp`});if(new Date(e)<new Date)throw new mS({expires:e})}var _S=I((()=>{hS()}));function vS(e){return Object.defineProperty(e,bS,{value:!0}),e}function yS(e){return!!e?.[bS]}var bS,xS=I((()=>{bS=Symbol.for(`mppx.x402.challenge`)}));function SS(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=OS(n)}return t}function CS(e,t){let n=SS(e),r=FS(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[OS(e)]??1,index:t}));return{definition:r,entries:i,header:TS(i),keys:n}}function wS(e){let t=e.split(/\s*,\s*/).map(e=>e.trim()).filter(Boolean);if(t.length===0)throw Error(`Accept-Payment header is empty.`);return t.map((e,t)=>NS(e,t))}function TS(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${zS(n)}`}).join(`, `)}function ES(e,t,n){let r=DS(e,t,n)[0];if(r)return{challenge:r.challenge,method:r.method}}function DS(e,t,n){let r=new Map;for(let e of t){let t=OS(e),n=r.get(t);n?n.push(e):r.set(t,[e])}return e.flatMap((e,t)=>{let i=r.get(OS(e));if(!i)return[];let a=kS(e,n);return!a||a.q<=0?[]:i.filter(t=>t.canHandleChallenge?.({challenge:e})??!0).map(n=>({challenge:e,index:t,match:a,method:n}))}).sort((e,t)=>MS(e.challenge)-MS(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function OS(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function kS(e,t){let n;for(let r of t){if(!AS(e,r))continue;let t={...r,specificity:jS(r)};(!n||t.specificity>n.specificity||t.specificity===n.specificity&&t.q>n.q||t.specificity===n.specificity&&t.q===n.q&&t.index<n.index)&&(n=t)}return n}function AS(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function jS(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function MS(e){return+!!yS(e)}function NS(e,t){let n=/^(?<method>[^/;\s]+|\*)\s*\/\s*(?<intent>[^/;\s]+|\*)(?<params>(?:\s*;\s*.+)?)$/u.exec(e),r=n?.groups?.method,i=n?.groups?.intent;if(!r||!i)throw Error(`Invalid Accept-Payment entry: ${e}`);BS(r,`method`),BS(i,`intent`);let a=1;for(let t of PS(n.groups?.params)){if(!t)continue;let n=/^(?<name>[A-Za-z0-9_-]+)\s*=\s*(?<value>\S+)$/u.exec(t),r=n?.groups?.name,i=n?.groups?.value;if(!r||!i)throw Error(`Invalid Accept-Payment parameter: ${t}`);r===`q`&&(a=LS(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function PS(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function FS(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>OS(e))),a={};for(let[e,t]of Object.entries(r??{})){if(!i.has(e))throw Error(`Unknown payment preference "${e}". Available: ${[...i].join(`, `)}`);a[e]=IS(t,`payment preference "${e}"`)}return a}function IS(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return RS(e,t)}function LS(e,t){if(!/^0(?:\.\d{0,3})?$|^1(?:\.0{0,3})?$/.test(e))throw Error(`Invalid q-value for ${t}. Expected an HTTP qvalue.`);return RS(Number(e),t)}function RS(e,t){if(e<0||e>1)throw Error(`Invalid q-value for ${t}. Expected a value between 0 and 1.`);let n=Math.round(e*1e3);if(Math.abs(e*1e3-n)>1e-9)throw Error(`Invalid q-value for ${t}. Expected at most 3 decimal places.`);return n/1e3}function zS(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function BS(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}var VS=I((()=>{xS()}));function HS(e){let t=e.match(RegExp(`^${wx.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new qS;try{let e=O.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=US(r);return{challenge:uS.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Ax(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new JS}}function US(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!WS(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:Mx(e)}}function WS(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function GS(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function KS(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:Mx(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:Mx(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=O.fromString(s,{pad:!1,url:!0});return`${wx.payment} ${c}`}var qS,JS,YS=I((()=>{dS(),kx(),Nx(),qS=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},JS=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}}})),XS,ZS,QS=I((()=>{XS=`org.paymentauth/credential`,ZS=`org.paymentauth/payment-required`}));function $S(e){let{extensions:t,resource:n,...r}=e;return pC.parse(r)}var eC,tC,nC,rC,iC,aC,oC,sC,cC,lC,uC,dC,fC,pC,mC,hC,gC,_C,vC,yC,bC,xC,SC=I((()=>{Gx(),eC=`charge`,tC=[`exact`],nC=`eip155:`,rC=`x402:`,iC=`PAYMENT-REQUIRED`,aC=`PAYMENT-SIGNATURE`,oC=`PAYMENT-RESPONSE`,sC=Y.string().check(Y.minLength(1)),cC=Y.number().check(Y.refine(e=>e>0,`Must be positive`)),lC=Y.string().check(Y.regex(/^\d+$/,`Invalid atomic amount`)),uC=Bx(),dC=Y.string().check(Y.regex(RegExp(`^${nC}\\d+$`),`Invalid EVM CAIP-2 network`)),fC=Y.object({description:Y.optional(Y.string()),iconUrl:Y.optional(Y.string()),mimeType:Y.optional(Y.string()),serviceName:Y.optional(Y.string()),tags:Y.optional(Y.array(Y.string())),url:sC}),Y.discriminatedUnion(`type`,[Y.object({name:sC,type:Y.literal(`eip3009`),version:sC}),Y.object({name:Y.optional(Y.string()),type:Y.literal(`permit2`),version:Y.optional(Y.string())})]),pC=Y.object({amount:lC,asset:sC,extra:Y.optional(Y.record(Y.string(),Y.unknown())),maxTimeoutSeconds:cC,network:dC,payTo:sC,scheme:Y.enum(tC)}),mC=Y.object({info:Y.record(Y.string(),Y.unknown()),schema:Y.record(Y.string(),Y.unknown())}),hC=Y.record(Y.string(),mC),gC=Y.object({accepts:Y.array(pC).check(Y.minLength(1)),error:Y.optional(Y.string()),extensions:Y.optional(hC),resource:fC,x402Version:Y.literal(2)}),_C=Y.object({authorization:Y.object({from:uC,nonce:Vx(),to:uC,validAfter:lC,validBefore:lC,value:lC}),signature:Ux()}),vC=Y.object({permit2Authorization:Y.object({deadline:lC,from:uC,nonce:lC,permitted:Y.object({amount:lC,token:uC}),spender:uC,witness:Y.object({to:uC,validAfter:lC})}),signature:Ux()}),yC=Y.union([_C,vC]),bC=Y.object({accepted:pC,extensions:Y.optional(hC),payload:yC,resource:Y.optional(fC),x402Version:Y.literal(2)}),Y.object({extensions:Y.optional(hC),extra:Y.optional(Y.record(Y.string(),Y.unknown())),invalidMessage:Y.optional(Y.string()),invalidReason:Y.optional(Y.string()),isValid:Y.boolean(),payer:Y.optional(Y.string())}),xC=Y.object({amount:Y.optional(lC),errorMessage:Y.optional(Y.string()),errorReason:Y.optional(Y.string()),extensions:Y.optional(hC),extra:Y.optional(Y.record(Y.string(),Y.unknown())),network:sC,payer:Y.optional(Y.string()),success:Y.boolean(),transaction:Y.string()})}));function CC(e,t,n){let r=new Headers(e.headers);for(let e of wC)e===J.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}var wC,TC=I((()=>{kx(),SC(),wC=[J.authorization,iC,oC,aC]}));function EC(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 DC(e){let t=EC(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 OC(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 kC(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=uS.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 AC(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:kC(e.error.data):kC(e.result?._meta?.[ZS])}function jC(e,t){return!e||e.id!==t?[]:AC(e)?.challenges??[]}async function MC(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=!1,i,a=ye({onEvent(e){if(!(r||!e.data)&&(r=!0,!(e.event&&e.event!==`message`)))try{i=OC(JSON.parse(e.data))}catch{}}});try{for(;;){if(r)return i;let{done:e,value:o}=await t.read();if(e)return a.feed(n.decode()),a.reset({consume:!0}),i;a.feed(n.decode(o,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}function NC(e){let t=FC.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(t.includes(`application/json`))return e.clone().json().then(OC).catch(()=>void 0);if(t.includes(`text/event-stream`))return MC(e)})();return FC.set(e,n),n}function PC(){return{getChallenges(e,t){let n=DC(t);return e.status===402||n===void 0?[]:NC(e).then(e=>jC(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=HS(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,[XS]:r}}})}}}}var FC,IC=I((()=>{dS(),YS(),QS(),TC(),FC=new WeakMap}));function LC(){return{getChallenges(e){return e.status!==402||!e.headers.has(J.wwwAuthenticate)?[]:nS(e)},setCredential(e,t,n){return CC(e,n?.challenge?oS(n.challenge):J.authorization,t)}}}var RC=I((()=>{dS(),kx(),TC()}));function zC(e){return{encode(t){return O.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(O.toString(t)))}catch{throw new BC}}}}var BC,VC=I((()=>{BC=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}}}));function HC(e){try{let t=JSON.parse(O.toString(e));return JC(t)}catch{throw new BC}}var UC,WC,GC,KC,qC,JC,YC=I((()=>{VC(),SC(),UC=zC(gC),WC=zC(bC),GC=zC(xC),KC=UC.encode,UC.decode,qC=WC.encode,WC.decode,GC.encode,GC.decode,JC=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new BC;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new BC;let n=fC.parse(t.resource),r=t.extensions===void 0?void 0:hC.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}}}));function XC(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(iC);if(!t)return[];let n=HC(t);if(e.url&&n.resource.url!==e.url)throw Error(`x402 payment-required resource does not match response URL.`);return n.accepts.flatMap((e,t)=>{let r=pC.safeParse(e);if(!r.success)return[];let i=r.data;return vS(Kx({id:`${rC}${t}`,intent:eC,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return CC(e,aC,t)}}}var ZC=I((()=>{dS(),YC(),xS(),SC(),TC()}));function QC(e){return e}function $C(){let e=[LC(),XC(),PC()],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 QC({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 ew=I((()=>{IC(),RC(),TC(),ZC()}));function tw(e,t){return iw.set(e,t),e}function nw(e){return iw.has(e)}function rw(e,t){return Promise.resolve(iw.get(e)?.(t))}var iw,aw=I((()=>{iw=new WeakMap}));function ow(e,t){return dw.set(e,t),e}function sw(e){dw.delete(e)}function cw(e,t,n){dw.has(e)&&fw.set(t,n)}function lw(e){return fw.get(e)}function uw(e,t){return Promise.resolve(dw.get(e)?.(t)??t.response)}var dw,fw,pw=I((()=>{dw=new WeakMap,fw=new WeakMap}));async function mw(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 hw(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=Qw,methods:a,onChallenge:o,orderChallenges:s,transport:c=$C()}=e,l=e.eventDispatcher??vw(),u=t??CS(a),d=zw(r),f=async(e,t,r)=>{let p=Rw(e,t?.headers),m=p.has(J.acceptPayment),h=Ww(p,u),g=Iw(e,t,p),_=Fw(e,t,p,h.header,m,n),v=await d(Bw(_.input),_.init),y=Lw(_.init,await g);if(!await c.isPaymentRequired(v,y))return v;let b=t?.context,{context:x,orderChallenges:S,...C}=y??{},w,T,ee,E;try{for(let n=0;n<i;n++){T=await c.getChallenges(v,y);let i=(await Gw(DS(T,a,h.entries),S??s))[0];if(!i){if(await mw(E,{challenges:T,response:v,status:`rejected`}),n>0)return v;throw Error(`No method found for challenges: ${T.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let u=i.challenge;w=u,ee=i.method,w.expires&&gS(w.expires,w.id);let p=Xw(v,_.input,_.input),m=E,g=qx(u),x=m?.method===i.method&&m?.key===g,D=!1;if(m){let e=await mw(m,{challenges:T,response:v,status:x?`pending`:`rejected`});D=x&&!e}E=D?m:void 0;let O=Cw(async e=>{if(e===void 0&&D&&m)return m.promise;D&&m&&(await mw(m,{status:`rejected`}),E=void 0);let t=e??b;if(!nw(i.method))return Uw(u,i.method,t);let n={prepare:()=>rw(i.method,{challenge:u,context:t,fetch:d,input:p})},r=n.prepare().then(()=>Uw(u,i.method,t,n));return E={attempt:n,key:e===void 0?g:void 0,method:i.method,promise:r},r}),k=await l.emit(`challenge.received`,ww({challenge:u,challenges:T,createCredential:O,init:t,input:e,method:i.method,response:v}))??(o?await o(w,{createCredential:O}):void 0)??await O(),te=E;te&&await te.promise.catch(()=>void 0)!==k&&(await mw(te,{status:`rejected`}),E=void 0),Hw(k),await l.emit(`credential.created`,Tw({challenge:u,credential:k,init:t,input:e,method:i.method,response:v})),v=await d(p,c.setCredential({...C,headers:_.headers},k,{challenge:u}));let A=await c.isPaymentRequired(v,y);if(A||(await mw(te,{response:v,status:v.ok?`accepted`:`rejected`}),E=void 0),v.ok&&yw(l,`payment.response`)&&await l.emit(`payment.response`,Ew({challenge:u,credential:k,init:t,input:e,method:i.method,response:v})),!A)return v.ok?uw(i.method,{challenge:u,credential:k,fetch:d,headers:_.headers,input:p,...r?{refetch:()=>f(Bw(_.input),t,!1)}:{},response:v,signal:Vw(e,t)}):v}T=void 0;try{T=await c.getChallenges(v,y)}catch{}return await mw(E,{challenges:T,response:v,status:`rejected`}),v}catch(n){throw await mw(E,{challenges:T,response:v,status:`rejected`}),await l.emit(`payment.failed`,Dw({challenge:w,challenges:T,error:n,init:t,input:e,method:ee,response:v})),n}},p=(e,t)=>f(e,t,!0);return p[Zw]=d,p}function gw(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);$w||=globalThis.fetch,globalThis.fetch=hw({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??(Jw()?`same-origin`:`always`),fetch:globalThis.fetch})}function _w(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 vw(){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 bw(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await Sw(e[`*`],t,n),r}case`credential.created`:await xw(e[`credential.created`],n),await Sw(e[`*`],t,n);return;case`payment.failed`:await xw(e[`payment.failed`],n),await Sw(e[`*`],t,n);return;case`payment.response`:await xw(e[`payment.response`],n),await Sw(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 eT.set(t,t=>e[t].size>0||e[`*`].size>0),t}function yw(e,t){return eT.get(e)?.(t)??!0}async function bw(e,t){try{return await e(t)}catch{return}}async function xw(e,t){for(let n of e)try{await n(t)}catch{}}async function Sw(e,t,n){await xw(e,Object.freeze({name:t,payload:n}))}function Cw(e){let t;return n=>(t??=e(n),t)}function ww(e){return Object.freeze({challenge:Mw(e.challenge),challenges:e.challenges.map(e=>Mw(e)),createCredential:e.createCredential,init:Ow(e.init),input:kw(e.input),method:Aw(e.method),response:jw(e.response)})}function Tw(e){return Object.freeze({challenge:Mw(e.challenge),credential:e.credential,init:Ow(e.init),input:kw(e.input),method:Aw(e.method),...e.response===void 0?{}:{response:jw(e.response)}})}function Ew(e){return Object.freeze({challenge:Mw(e.challenge),credential:e.credential,init:Ow(e.init),input:kw(e.input),method:Aw(e.method),response:jw(e.response)})}function Dw(e){return Object.freeze({...e.challenge?{challenge:Mw(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>Mw(e))}:{},error:e.error,init:Ow(e.init),input:kw(e.input),...e.method?{method:Aw(e.method)}:{},...e.response===void 0?{}:{response:jw(e.response)}})}function Ow(e){if(e)return Pw({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function kw(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function Aw(e){return Pw(Object.assign({},e))}function jw(e){return e instanceof Response?e.clone():Mw(e)}function Mw(e){try{return Nw(structuredClone(e))}catch{return Pw(e)}}function Nw(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Nw(t);return e}function Pw(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function Fw(e,t,n,r,i,a){let o=!!r&&!i&&Kw(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(J.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function Iw(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 Lw(e,t){return t===void 0?e:{...e,body:t}}function Rw(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function zw(e){let t=e;for(;t[Zw];)t=t[Zw];return t}function Bw(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Vw(e,t){return t?.signal??(e instanceof Request?e.signal:void 0)}function Hw(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
224
+ `))throw Error(`Credential header value contains illegal newline characters`)}async function Uw(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&&cw(t,a,r),t.createCredential(a)}function Ww(e,t){let n=e.get(J.acceptPayment);if(!n)return t;try{return{...t,entries:wS(n),header:n}}catch{return t}}async function Gw(e,t){return t?t(e):e}function Kw(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=Yw(e);return t===`same-origin`?!Jw()||n.origin===globalThis.location.origin:t.origins.some(e=>qw(n,e))}function qw(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 Jw(){return globalThis.location!==void 0}function Yw(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,Jw()?globalThis.location.href:void 0)}function Xw(e,t,n){if(!e.url)return t;let r=new URL(e.url),i=Yw(n);if(r.origin!==i.origin)throw Error(`Refusing to send payment credential across redirect from ${i.origin} to ${r.origin}`);return e.url}var Zw,Qw,$w,eT,tT=I((()=>{dS(),kx(),_S(),VS(),ew(),aw(),pw(),Zw=Symbol.for(`mppx.fetch.wrapper`),Qw=3,eT=new WeakMap}));Sx(),tT();function nT(){let e=new Uint8Array(64);return crypto.getRandomValues(e),Object.freeze({created:Math.floor(Date.now()/1e3),nonce:O.fromBytes(e,{pad:!1,url:!0})})}function rT(...e){return{protocol:`composed`,async sign(t,n=nT()){for(let r of e)t=await r.sign(t,n);return t}}}function iT(e,t){return async(n,r)=>e(await t.sign(new Request(n,r)))}_S(),VS(),ew();function aT(e){let{attestation:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=$C()}=e,c=e.fetch??globalThis.fetch,l=t?oT(c,t):c,u=e.methods.flat(),d=CS(u,e.paymentPreferences),f=vw(),p=r,m={acceptPayment:d,acceptPaymentPolicy:o,...(e.fetch||t)&&{fetch:l},eventDispatcher:f,...n!==void 0&&{maxPaymentRetries:n},...p&&{onChallenge:p},...i&&{orderChallenges:i},methods:u,transport:s},h=hw(m);a&&gw(m);function g(e){return f.on(`challenge.received`,e)}function _(e){return f.on(`credential.created`,e)}function v(e){return f.on(`payment.failed`,e)}function y(e){return f.on(`payment.response`,e)}async function b(e,t){let n=fT(e),r=await s.getChallenges(e,t?.request),a=Object.freeze(r.map(e=>pT(e))),o=gT(d.entries,t?.acceptPayment),c,l;try{let e=(await _T(DS(r,u,o),t?.orderChallenges??i))[0];if(!e)throw Error(`No method found for challenges: ${r.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${u.map(e=>`${e.name}.${e.intent}`).join(`, `)}`);let d=e.challenge;c=a[e.index],l=e.method,c.expires&&gS(c.expires,c.id);let p=c,m=l,h=sT(async e=>{try{p.expires&&gS(p.expires,p.id);let t=sT(t=>vT(p,m,t??e)),i=await f.emit(`challenge.received`,cT({challenge:p,challenges:r,createCredential:t,method:m,response:n}))??await t();return Hw(i),await f.emit(`credential.created`,lT({challenge:p,credential:i,method:m,response:n})),i}catch(e){throw await f.emit(`payment.failed`,uT({challenge:p,challenges:r,error:e,method:m,response:n})),e}});return Object.freeze({challenge:p,challenges:a,createCredential:h,method:dT(m),setCredential(e,t){return Hw(t),s.setCredential(e,t,{challenge:d})}})}catch(e){throw await f.emit(`payment.failed`,uT({challenge:c,challenges:r,error:e,method:l,response:n})),e}}return{fetch:h,rawFetch:c,methods:u,transport:s,on:f.on,onChallengeReceived:g,onCredentialCreated:_,onPaymentFailed:v,onPaymentResponse:y,preparePayment:b,async createCredential(e,t,n){return(await b(e,n)).createCredential(t)}}}function oT(e,t){let n=Object.values(t);if(n.length===0)throw TypeError(`Mppx client attestation must configure at least one signer.`);return iT(e,rT(...n))}function sT(e){let t;return n=>(t??=e(n),t)}function cT(e){return Object.freeze({challenge:pT(e.challenge),challenges:e.challenges.map(e=>pT(e)),createCredential:e.createCredential,method:dT(e.method),response:fT(e.response)})}function lT(e){return Object.freeze({challenge:pT(e.challenge),credential:e.credential,method:dT(e.method),response:fT(e.response)})}function uT(e){return Object.freeze({...e.challenge?{challenge:pT(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>pT(e))}:{},error:e.error,...e.method?{method:dT(e.method)}:{},response:fT(e.response)})}function dT(e){return hT(Object.assign({},e))}function fT(e){if(e instanceof Response)try{return e.clone()}catch{return new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText})}return pT(e)}function pT(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 mT(t)}catch{return hT(e)}}function mT(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))mT(t);return e}function hT(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function gT(e,t){return t?typeof t==`string`?wS(t):t:e}async function _T(e,t){return t?t(e):e}async function vT(e,t,n){let r=t.context&&n!==void 0?t.context.parse(n):void 0;return t.createCredential(r===void 0?{challenge:e}:{challenge:e,context:r})}function yT(){return Y.string().check(Y.regex(bT,`Invalid URI or path`))}var bT,xT,ST,CT,wT,TT,ET,DT,OT,kT=I((()=>{Gx(),bT=/^([a-zA-Z][a-zA-Z\d+.-]*:\/\/\S+|\/\S*)$/,xT=new Set([`amount`,`currency`,`description`,`intent`,`method`]),ST=Y.looseObject({amount:Y.optional(Y.union([Y.null(),Y.string().check(Y.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:Y.optional(Y.string()),description:Y.optional(Y.string()),intent:Y.optional(Y.string()),method:Y.optional(Y.string())}),CT=Y.pipe(Y.looseObject({amount:Y.optional(Y.union([Y.null(),Y.string().check(Y.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:Y.optional(Y.string()),description:Y.optional(Y.string()),intent:Y.optional(Y.string()),method:Y.optional(Y.string()),offers:Y.optional(Y.array(ST).check(Y.minLength(1)))}).check(Y.refine(e=>e.offers===void 0||Object.keys(e).every(e=>e===`offers`||!xT.has(e)),`Cannot mix offers with flat payment info fields`)),Y.transform(e=>{if(e.offers)return{offers:e.offers};let t={};for(let[n,r]of Object.entries(e))n!==`offers`&&(xT.has(n)||r!==void 0)&&(t[n]=r);return{offers:[t]}})),wT=Y.looseObject({apiReference:Y.optional(yT()),homepage:Y.optional(yT()),llms:Y.optional(yT())}),TT=Y.looseObject({categories:Y.optional(Y.array(Y.string())),docs:Y.optional(wT)}),ET=Y.looseObject({"x-payment-info":Y.optional(CT),requestBody:Y.optional(Y.unknown()),responses:Y.optional(Y.record(Y.string(),Y.unknown())),summary:Y.optional(Y.string())}),DT=Y.looseObject({delete:Y.optional(ET),get:Y.optional(ET),head:Y.optional(ET),options:Y.optional(ET),patch:Y.optional(ET),post:Y.optional(ET),put:Y.optional(ET),trace:Y.optional(ET)}),OT=Y.looseObject({openapi:Y.string(),info:Y.looseObject({title:Y.string(),version:Y.string()}),"x-service-info":Y.optional(TT),paths:Y.optional(Y.record(Y.string(),DT))})}));kT();function AT(e){let t=[],n=OT.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=CT.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}function jT(e){return e}function MT(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}var NT=I((()=>{}));function PT(e){return Y.refine(e=>{let{amount:t,decimals:n}=e;return P(t,n)>0n},e)}function FT(e){let{periodCount:t,periodUnit:n}=e;try{let e=zT[n];return e!==void 0&&BigInt(t)*e<=RT}catch{return!1}}var IT,LT,RT,zT,BT,VT,HT,UT,WT,GT,KT,qT,JT,YT=I((()=>{kx(),NT(),Gx(),IT=[`push`,`pull`],LT=Y.object({amount:Fx(),memo:Y.optional(Vx()),recipient:Y.pipe(Y.string(),Y.transform(e=>e))}),RT=(1n<<64n)-1n,zT={dev_second:1n,day:86400n,week:604800n},BT=Y.pipe(Bx(),Y.transform(e=>e.toLowerCase())),VT=Y.object({accessKeyAddress:BT,keyType:Y.enum([`p256`,`secp256k1`,`webAuthn`])}),HT=Y.object({accessKey:Y.optional(VT),chainId:Y.optional(Y.number())}),UT=Lx(`subscriptionExpires must be a valid date`).check(Y.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),WT=Y.enum([`dev_second`,`day`,`week`]),GT=Y.pipe(Y.union([Y.string(),Y.bigint(),Y.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),Y.transform(e=>e.toString())).check(Y.regex(/^[1-9]\d*$/,`Invalid periodCount`),Y.refine(e=>{try{return BigInt(e)<=RT}catch{return!1}},`periodCount exceeds uint64`)),KT=jT({name:`tempo`,intent:`charge`,schema:{credential:{payload:Y.discriminatedUnion(`type`,[Y.object({hash:Vx(),type:Y.literal(`hash`)}),Y.object({signature:Ux(),type:Y.literal(`transaction`)}),Y.object({signature:Ux(),type:Y.literal(`proof`)})])},request:Y.pipe(Y.object({amount:Fx(),chainId:Y.optional(Y.number()),currency:Y.string(),decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),feePayer:Y.optional(Y.pipe(Y.union([Y.boolean(),Y.custom()]),Y.transform(e=>typeof e==`object`||e))),memo:Y.optional(Vx()),recipient:Y.optional(Y.string()),splits:Y.optional(Y.array(LT).check(Y.minLength(1),Y.maxLength(10))),supportedModes:Y.optional(Y.array(Y.enum(IT)).check(Y.minLength(1)))}).check(Y.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`)),Y.transform(({amount:e,chainId:t,decimals:n,feePayer:r,memo:i,splits:a,supportedModes:o,...s})=>({...s,amount:P(e,n).toString(),...t!==void 0||r!==void 0||i!==void 0||a!==void 0||o!==void 0?{methodDetails:{...t!==void 0&&{chainId:t},...r!==void 0&&{feePayer:r},...i!==void 0&&{memo:i},...a!==void 0&&{splits:a.map(e=>({...e,amount:P(e.amount,n).toString()}))},...o!==void 0&&{supportedModes:o}}}:{}})))}}),qT=jT({name:`tempo`,intent:`session`,schema:{credential:{payload:Y.discriminatedUnion(`action`,[Y.object({action:Y.literal(`open`),authorizedSigner:Y.optional(Y.string()),channelId:Vx(),cumulativeAmount:Fx(),descriptor:Y.optional(Y.custom()),signature:Ux(),transaction:Ux(),type:Y.literal(`transaction`)}),Y.object({action:Y.literal(`topUp`),additionalDeposit:Fx(),channelId:Vx(),descriptor:Y.optional(Y.custom()),transaction:Ux(),type:Y.literal(`transaction`)}),Y.object({action:Y.literal(`voucher`),channelId:Vx(),cumulativeAmount:Fx(),descriptor:Y.optional(Y.custom()),signature:Ux()}),Y.object({action:Y.literal(`close`),channelId:Vx(),cumulativeAmount:Fx(),descriptor:Y.optional(Y.custom()),signature:Ux()})])},request:Y.pipe(Y.object({amount:Fx(),chainId:Y.optional(Y.number()),channelId:Y.optional(Vx()),currency:Y.string(),decimals:Y.number(),escrowContract:Y.optional(Y.string()),feePayer:Y.optional(Y.pipe(Y.union([Y.boolean(),Y.custom()]),Y.transform(e=>typeof e==`object`||e))),feeToken:Y.optional(Bx()),minVoucherDelta:Y.optional(Fx()),operator:Y.optional(Bx()),recipient:Y.optional(Y.string()),sessionProtocol:Y.optional(Y.enum([Ox.v2,Ox.v1])),sessionSnapshot:Y.optional(Y.custom()),suggestedDeposit:Y.optional(Fx()),unitType:Y.string()}).check(Y.refine(({amount:e,decimals:t})=>P(e,t)>0n,`Session amount must be greater than 0`)),Y.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&&{[Dx.sessionProtocol]:l},...u!==void 0&&{[Dx.sessionSnapshot]:u}}})))}}),JT=jT({name:`tempo`,intent:`subscription`,schema:{credential:{payload:Y.object({signature:Ux(),type:Y.literal(`keyAuthorization`)})},request:Y.pipe(Y.object({amount:Fx(),accessKey:Y.optional(VT),chainId:Y.optional(Y.number()),currency:BT,decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),methodDetails:Y.optional(HT),periodCount:GT,periodUnit:WT,recipient:BT,subscriptionExpires:UT}).check(PT(`Subscription amount must be greater than 0`),Y.refine(FT,`Subscription period exceeds uint64`)),Y.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 XT(e){return e>=0n&&e<=hE}function ZT(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return XT(t)?t:void 0}function QT(e){return $T(e),e}function $T(e){if(!XT(e))throw Error(`Value ${e} is outside uint96 bounds.`)}function eE(e){return typeof e==`object`&&!!e}function tE(e){return typeof e==`string`&&gE.has(e)}function nE(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!tE(t.action))}function rE(e,t=`No session credential context available.`){if(!nE(e))throw Error(t);return e}function iE(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function aE(e){return eE(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function oE(e){return eE(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 sE(e){let t=O.toString(e),n=JSON.parse(t);if(!oE(n))throw Error(`Invalid session receipt.`);return n}function cE(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function lE(e){let t=`message`,n=[];for(let r of e.split(`
225
225
  `))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(`
226
- `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=lE(r);return iE(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=lE(r);return aE(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function lE(e){try{return JSON.parse(e)}catch{return null}}function uE(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function dE(){return JSON.stringify({mpp:`payment-close-request`})}function fE(e){let t=pE(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`&&aE(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`&&iE(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&aE(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function pE(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}var mE,hE,gE,_E=I((()=>{mE=(1n<<96n)-1n,hE=new Set([`open`,`topUp`,`voucher`,`close`]),gE=`0x4d50500000000000000000000000000000000000`}));function vE(e){return TE.encode(e)}function yE(e){return TE.decode(e)}var bE,xE,SE,CE,wE,TE,EE=I((()=>{VC(),Gx(),bE=Y.custom(e=>typeof e==`string`&&de(e,{strict:!1})),xE=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),SE=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),CE=Y.object({authorizedSigner:bE,expiringNonceHash:xE,operator:bE,payee:bE,payer:bE,salt:xE,token:bE}),wE=Y.object({acceptedCumulative:Y.string(),chainId:Y.number(),channelId:xE,closeRequestedAt:Y.optional(Y.string()),deposit:Y.string(),descriptor:CE,escrow:bE,highestVoucher:Y.optional(Y.object({channelId:xE,cumulativeAmount:Y.string(),signature:SE})),requiredCumulative:Y.string(),settled:Y.string(),spent:Y.string(),units:Y.optional(Y.number())}),TE=zC(wE)}));function DE(e){return{status:`active`,...e}}function OE(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?NE(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?NE(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:jE(e.challengeId,t.snapshot),effects:[]}:NE(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?NE(e,t):{state:GE({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:ME(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:NE(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?NE(e,t):{state:JE(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?AE({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):NE(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:NE(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?NE(e,t):{state:ME(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}]}:NE(e,t);case`settled`:return e.status===`settling`?{state:ME(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:NE(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:NE(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:NE(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?NE(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`?NE(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function kE(e,t){let n=OE(e.state,t);return e.state=n.state,n}function AE(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 jE(e,t){return DE({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function ME(e,t,n,r){return DE({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function NE(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function PE(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function FE(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`);PE({cumulativeAmount:i,maxVoucherCumulative:n}),PE({cumulativeAmount:a,maxVoucherCumulative:n})}function IE(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;FE({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function LE(e,t){return typeof e==`bigint`?e:P(e,t)}function RE(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(BE(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 zE(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;PE({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 BE(e,t){PE({cumulativeAmount:e,maxVoucherCumulative:t??null})}function VE(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 HE(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function UE(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!YT(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>HE({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function WE(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=XT(r),s=XT(a.spent);return o===void 0||s===void 0||!YT(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function GE(e){return DE({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 KE(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:eD}}function qE(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=IE({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&kE(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function JE(e,t){return DE({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function YE(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=XT(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 XE(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 OE(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function ZE(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 QE(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 $E(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(dE()),e.waitForCloseReady()))(),a=BigInt(i.spent);UE({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=>WE({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(uE(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}var eD,tD=I((()=>{_E(),EE(),eD={status:`idle`}}));function nD(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=zD.CLOSED,r=null}if(a.type===`open`&&(i=zD.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 rD(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function iD(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=LE(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 aD(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:JE(s,u)}:i?{channel:u,state:GE({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function oD(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=rD(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:ZT(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function sD(e){return e.method===Tx.tempo&&e.intent===Ex.session}function cD(e){return sD(e)&&Cx(e.request.methodDetails,Dx.sessionProtocol)===Ox.v2}function lD(e){return Cx(e.request.methodDetails,Dx.sessionSnapshot)}function uD(e,t,n){let r=e instanceof Request?e.headers:void 0;return{...t,headers:{...gw(r),...gw(t?.headers),[J.authorization]:n}}}function dD(e){try{let t=typeof location>`u`?void 0:location.href,n=e instanceof Request?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function fD(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function pD(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 mD(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);let r=await hD({challenge:e.challenge,context:{action:`topUp`,channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,input:e.input});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(J.paymentReceipt);return i?oE(i):void 0}async function hD(e){let t=async t=>e.fetch(dD(e.input),{method:`POST`,headers:{[J.authorization]:await e.createSessionCredential(t,e.context)}}),n=await t(e.challenge);if(n.status!==402)return n;let r=nS(n).find(cD);return r?t(r):n}async function gD(e){let t=_D({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,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a});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,uD(e.input,e.init,t))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(J.paymentReceipt)&&await l(),u}function _D(e){let t=nS(e.response).find(cD);if(!t)return;let n=lD(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function vD(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=async(r,i=!1)=>{t=r,n=(i?e.resolveSignedCloseAmount?.(r):void 0)??e.signedCloseAmount;let a=await e.createSessionCredential(r,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(e.lastUrl,{method:`POST`,headers:{[J.authorization]:a}})},i=await r(e.target.challenge);if(i.status===402){let t=nS(i).find(cD);t&&(e.setChallenge?.(t),i=await r(t,!0))}if(!i.ok){let e=await pD(i),t=i.headers.get(J.wwwAuthenticate)??``;throw Error(`Close request failed with status ${i.status}${e?`: ${e}`:``}${t?` [${J.wwwAuthenticate}: ${t}]`:``}`)}let a=i.headers.get(J.paymentReceipt);if(!a)return;let o=oE(a);if(!o.txHash||!j.validate(o.txHash,{strict:!0})||j.size(o.txHash)!==32||!WE({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:e.getMinimumSpent?.()??0n,receipt:o}))throw Error(`Session close response included a mismatched payment receipt.`);return o}async function yD(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o={...a,headers:{...gw(a.headers),Accept:`text/event-stream`},...i?{signal:i}:{}},s=await n.doFetch(e,o);return!sE(s)&&n.getChannel()?.opened&&(s=await n.doFetch(e,o)),bD(e,s,{onReceipt:r,signal:i},n)}function bD(e,t,n,r){if(!sE(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let i=r.getChallenge();return xD({onNeedVoucher:t=>ED({challenge:i,driver:r,input:e},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*xD(e){for await(let t of SD(e))t.data!==void 0&&(yield t.data)}async function*SD(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=CD(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=cE(i.replace(/\r\n|\r/g,`
227
- `));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);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 CD(e,t){for(let n=0;n<e.length;n++){let r=wD(e,n,t);if(!r)continue;let i=wD(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function wD(e,t,n){return e[t]===`
226
+ `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=uE(r);return aE(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=uE(r);return oE(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function uE(e){try{return JSON.parse(e)}catch{return null}}function dE(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function fE(){return JSON.stringify({mpp:`payment-close-request`})}function pE(e){let t=mE(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`&&oE(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`&&aE(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&oE(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function mE(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}var hE,gE,_E,vE=I((()=>{hE=(1n<<96n)-1n,gE=new Set([`open`,`topUp`,`voucher`,`close`]),_E=`0x4d50500000000000000000000000000000000000`}));function yE(e){return EE.encode(e)}function bE(e){return EE.decode(e)}var xE,SE,CE,wE,TE,EE,DE=I((()=>{VC(),Gx(),xE=Y.custom(e=>typeof e==`string`&&de(e,{strict:!1})),SE=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),CE=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),wE=Y.object({authorizedSigner:xE,expiringNonceHash:SE,operator:xE,payee:xE,payer:xE,salt:SE,token:xE}),TE=Y.object({acceptedCumulative:Y.string(),chainId:Y.number(),channelId:SE,closeRequestedAt:Y.optional(Y.string()),deposit:Y.string(),descriptor:wE,escrow:xE,highestVoucher:Y.optional(Y.object({channelId:SE,cumulativeAmount:Y.string(),signature:CE})),requiredCumulative:Y.string(),settled:Y.string(),spent:Y.string(),units:Y.optional(Y.number())}),EE=zC(TE)}));function OE(e){return{status:`active`,...e}}function kE(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?PE(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?PE(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:ME(e.challengeId,t.snapshot),effects:[]}:PE(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?PE(e,t):{state:KE({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:NE(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:PE(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?PE(e,t):{state:YE(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?jE({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):PE(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:PE(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?PE(e,t):{state:NE(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}]}:PE(e,t);case`settled`:return e.status===`settling`?{state:NE(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:PE(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:PE(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:PE(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?PE(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`?PE(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function AE(e,t){let n=kE(e.state,t);return e.state=n.state,n}function jE(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 ME(e,t){return OE({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function NE(e,t,n,r){return OE({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function PE(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function FE(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function IE(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`);FE({cumulativeAmount:i,maxVoucherCumulative:n}),FE({cumulativeAmount:a,maxVoucherCumulative:n})}function LE(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;IE({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function RE(e,t){return typeof e==`bigint`?e:P(e,t)}function zE(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(VE(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 BE(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;FE({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 VE(e,t){FE({cumulativeAmount:e,maxVoucherCumulative:t??null})}function HE(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 UE(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function WE(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!XT(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>UE({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function GE(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=ZT(r),s=ZT(a.spent);return o===void 0||s===void 0||!XT(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function KE(e){return OE({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 qE(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:tD}}function JE(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=LE({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&AE(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function YE(e,t){return OE({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function XE(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=ZT(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 ZE(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 kE(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function QE(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 $E(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 eD(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(fE()),e.waitForCloseReady()))(),a=BigInt(i.spent);WE({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=>GE({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(dE(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}var tD,nD=I((()=>{vE(),DE(),tD={status:`idle`}}));function rD(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=BD.CLOSED,r=null}if(a.type===`open`&&(i=BD.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 iD(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function aD(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=RE(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 oD(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:YE(s,u)}:i?{channel:u,state:KE({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function sD(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=iD(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:QT(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function cD(e){return e.method===Tx.tempo&&e.intent===Ex.session}function lD(e){return cD(e)&&Cx(e.request.methodDetails,Dx.sessionProtocol)===Ox.v2}function uD(e){return Cx(e.request.methodDetails,Dx.sessionSnapshot)}function dD(e,t,n){let r=e instanceof Request?e.headers:void 0;return{...t,headers:{..._w(r),..._w(t?.headers),[J.authorization]:n}}}function fD(e){try{let t=typeof location>`u`?void 0:location.href,n=e instanceof Request?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function pD(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function mD(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 hD(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);let r=await gD({challenge:e.challenge,context:{action:`topUp`,channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,input:e.input});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(J.paymentReceipt);return i?sE(i):void 0}async function gD(e){let t=async t=>e.fetch(fD(e.input),{method:`POST`,headers:{[J.authorization]:await e.createSessionCredential(t,e.context)}}),n=await t(e.challenge);if(n.status!==402)return n;let r=nS(n).find(lD);return r?t(r):n}async function _D(e){let t=vD({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,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a});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,dD(e.input,e.init,t))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(J.paymentReceipt)&&await l(),u}function vD(e){let t=nS(e.response).find(lD);if(!t)return;let n=uD(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function yD(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=async(r,i=!1)=>{t=r,n=(i?e.resolveSignedCloseAmount?.(r):void 0)??e.signedCloseAmount;let a=await e.createSessionCredential(r,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(e.lastUrl,{method:`POST`,headers:{[J.authorization]:a}})},i=await r(e.target.challenge);if(i.status===402){let t=nS(i).find(lD);t&&(e.setChallenge?.(t),i=await r(t,!0))}if(!i.ok){let e=await mD(i),t=i.headers.get(J.wwwAuthenticate)??``;throw Error(`Close request failed with status ${i.status}${e?`: ${e}`:``}${t?` [${J.wwwAuthenticate}: ${t}]`:``}`)}let a=i.headers.get(J.paymentReceipt);if(!a)return;let o=sE(a);if(!o.txHash||!A.validate(o.txHash,{strict:!0})||A.size(o.txHash)!==32||!GE({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:e.getMinimumSpent?.()??0n,receipt:o}))throw Error(`Session close response included a mismatched payment receipt.`);return o}async function bD(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o={...a,headers:{..._w(a.headers),Accept:`text/event-stream`},...i?{signal:i}:{}},s=await n.doFetch(e,o);return!cE(s)&&n.getChannel()?.opened&&(s=await n.doFetch(e,o)),xD(e,s,{onReceipt:r,signal:i},n)}function xD(e,t,n,r){if(!cE(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let i=r.getChallenge();return SD({onNeedVoucher:t=>DD({challenge:i,driver:r,input:e},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*SD(e){for await(let t of CD(e))t.data!==void 0&&(yield t.data)}async function*CD(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=wD(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=lE(i.replace(/\r\n|\r/g,`
227
+ `));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);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 wD(e,t){for(let n=0;n<e.length;n++){let r=TD(e,n,t);if(!r)continue;let i=TD(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function TD(e,t,n){return e[t]===`
228
228
  `?1:e[t]===`\r`?e[t+1]===`
229
- `?2:t+1===e.length&&!n?0:1:0}function TD(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=SD({...e,signal:t.signal}),i=new TextEncoder,a=new Headers(e.response.headers);a.delete(`content-length`);let o=()=>e.signal?.removeEventListener(`abort`,n),s=new Response(new ReadableStream({async pull(e){try{let t=await r.next();if(t.done)return o(),e.close();e.enqueue(i.encode(t.value.raw))}catch(e){throw o(),e}},async cancel(){o(),t.abort(),await r.return(void 0)}}),{headers:a,status:e.response.status,statusText:e.response.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{configurable:!0,get:()=>e.response[t]});return s}async function ED(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await oD({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,input:e.input,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await hD({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,input:e.input});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function DD(e){let t=new URL(e.input.toString()),n=fD(t);e.onProbeUrl?.(n);let r=await e.fetch(n,{...e.probeInit,...e.signal?{signal:e.signal}:{}});if(r.status!==402)throw Error(`Expected a 402 payment challenge from ${n}, received ${r.status} instead.`);let i=nS(r).find(cD);if(!i)throw Error(`No payment challenge received from HTTP endpoint for this WebSocket URL. The server may not require payment or did not advertise a challenge.`);return{challenge:i,httpUrl:n,wsUrl:t}}async function OD(e){let t=await DD(e);return{...t,credential:await e.createSessionCredential(t.challenge,{})}}function kD(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:HS(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:rE(t)}}function AD(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function jD(e){if(!AD(e))return`received mismatched payment-close-ready frame`;let t=XT(e.receipt.spent);if(t===void 0)return`received invalid payment-close-ready spend`;if(t>e.cumulativeAmount)return`received payment-close-ready beyond local voucher state`}function MD(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!AD(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!WE({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function ND(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=new i(a,r?.protocols),s=kD({challenge:t,credential:n,socket:o});e.setSocketSession(s);let c=nD(o),l=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(o.readyState===zD.CONNECTING||o.readyState===zD.OPEN)&&o.close(BD,t)};return o.addEventListener(`close`,t=>{s.socket=null,s.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),c.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),o.addEventListener(`error`,()=>{c.emit(`error`,{type:`error`})}),o.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await FD({driver:e,failSocketFlow:l,managedEmit:c.emit,message:n,rawSocket:o,socketState:s})}),r?.signal?.addEventListener(`abort`,()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),o.close()},{once:!0}),await PD(o,c.emit,a),o.send(uE(n)),await e.waitForReceipt(),c.socket}function PD(e,t,n){return new Promise((r,i)=>{let a=()=>{e.removeEventListener(`error`,o),t(`open`,{type:`open`}),r()},o=()=>{e.removeEventListener(`open`,a),i(Error(`WebSocket connection to ${n} failed to open.`))};e.addEventListener(`open`,a,{once:!0}),e.addEventListener(`error`,o,{once:!0})})}async function FD(e){let t=fE(e.message);if(!t){e.managedEmit(`message`,{data:e.message,type:`message`});return}switch(t.mpp){case`authorization`:return;case`message`:e.socketState.deliveredChunks+=1n,e.managedEmit(`message`,{data:t.data,type:`message`});return;case`payment-close-ready`:ID(e,t.data);return;case`payment-error`:e.driver.rejectReceipt(Error(t.message)),e.driver.rejectCloseReady(Error(t.message));return;case`payment-need-voucher`:await LD(e,t.data);return;case`payment-receipt`:RD(e,t.data);return}}function ID(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=jD({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,cumulativeAmount:n,receipt:t});if(r){e.failSocketFlow(r);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleCloseReady(t),e.managedEmit(`close`,{code:1e3,reason:`stream complete`,type:`close`,wasClean:!0})}async function LD(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+VD&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await oD({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:n,event:t,expectedChannelId:e.socketState.channelId,getChannel:e.driver.getChannel,input:e.driver.httpUrl,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status===`ignored`){e.failSocketFlow(r.reason===`channel-mismatch`?`received mismatched payment-need-voucher frame`:`cannot create voucher: no active channel`);return}let i=await e.driver.createSessionCredential(n,r.context);e.rawSocket.send(uE(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function RD(e,t){let n=MD({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}var zD,BD,VD,HD=I((()=>{dS(),eT(),kx(),YS(),_E(),tD(),zD={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},BD=3008,VD=5e3})),UD,WD,GD,KD,qD,JD=I((()=>{UD={mainnet:4217,testnet:42431},WD={usdc:`0x20C000000000000000000000b9537d11c60E8b50`,pathUsd:`0x20c0000000000000000000000000000000000000`},GD={[UD.mainnet]:WD.usdc,[UD.testnet]:WD.pathUsd},KD={[UD.mainnet]:`0x33b901018174DDabE4841042ab76ba85D4e24f25`,[UD.testnet]:`0xe1c4d3dce17bc111181ddf716f75bae49e61a336`},qD={[UD.mainnet]:`https://rpc.tempo.xyz`,[UD.testnet]:`https://rpc.moderato.tempo.xyz`}})),YD=Ke({chainName:()=>dO,confirm:()=>oO,decodeMemo:()=>$D,fetchBalanceLines:()=>hO,fetchTokenInfo:()=>mO,fmtBalance:()=>sO,fmtChallengeValue:()=>eO,fmtRequestValue:()=>QD,isAgentEnvironment:()=>rO,isTempoAccount:()=>iO,isTestnet:()=>pO,link:()=>tO,mainnetTokens:()=>bO,networkRpcUrls:()=>_O,parseMethodOpts:()=>nO,pathUsd:()=>vO,pc:()=>Z,printRequestHeaders:()=>XD,printResponseHeaders:()=>ZD,prompt:()=>aO,resolveChain:()=>uO,resolveFundingNetwork:()=>lO,resolveRpcUrl:()=>cO,testnetTokens:()=>xO,usdc:()=>yO});function XD(e,t,n){let{pathname:r,host:i}=new URL(e);n(`> ${(t.method??`GET`).toUpperCase()} ${r} HTTP/1.1\n`),n(`> Host: ${i}\n`);for(let[e,r]of Object.entries(t.headers??{}))n(`> ${e}: ${r}\n`);n(`>
230
- `)}function ZD(e,t){if(!t.include&&t.verbose<2||t.silent)return;let n=`HTTP/1.1 ${e.status} ${e.statusText}`,r=t.verbose>=2?process.stderr:process.stdout,i=t.verbose>=2?`< `:``;r.write(`${i}${n}\n`);for(let[t,n]of e.headers)r.write(`${i}${t}: ${n}\n`);r.write(t.verbose>=2?`<
229
+ `?2:t+1===e.length&&!n?0:1:0}function ED(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=CD({...e,signal:t.signal}),i=new TextEncoder,a=new Headers(e.response.headers);a.delete(`content-length`);let o=()=>e.signal?.removeEventListener(`abort`,n),s=new Response(new ReadableStream({async pull(e){try{let t=await r.next();if(t.done)return o(),e.close();e.enqueue(i.encode(t.value.raw))}catch(e){throw o(),e}},async cancel(){o(),t.abort(),await r.return(void 0)}}),{headers:a,status:e.response.status,statusText:e.response.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{configurable:!0,get:()=>e.response[t]});return s}async function DD(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await sD({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,input:e.input,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await gD({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,input:e.input});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function OD(e){let t=new URL(e.input.toString()),n=pD(t);e.onProbeUrl?.(n);let r=await e.fetch(n,{...e.probeInit,...e.signal?{signal:e.signal}:{}});if(r.status!==402)throw Error(`Expected a 402 payment challenge from ${n}, received ${r.status} instead.`);let i=nS(r).find(lD);if(!i)throw Error(`No payment challenge received from HTTP endpoint for this WebSocket URL. The server may not require payment or did not advertise a challenge.`);return{challenge:i,httpUrl:n,wsUrl:t}}async function kD(e){let t=await OD(e);return{...t,credential:await e.createSessionCredential(t.challenge,{})}}function AD(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:HS(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:iE(t)}}function jD(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function MD(e){if(!jD(e))return`received mismatched payment-close-ready frame`;let t=ZT(e.receipt.spent);if(t===void 0)return`received invalid payment-close-ready spend`;if(t>e.cumulativeAmount)return`received payment-close-ready beyond local voucher state`}function ND(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!jD(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!GE({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function PD(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=new i(a,r?.protocols),s=AD({challenge:t,credential:n,socket:o});e.setSocketSession(s);let c=rD(o),l=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(o.readyState===BD.CONNECTING||o.readyState===BD.OPEN)&&o.close(VD,t)};return o.addEventListener(`close`,t=>{s.socket=null,s.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),c.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),o.addEventListener(`error`,()=>{c.emit(`error`,{type:`error`})}),o.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await ID({driver:e,failSocketFlow:l,managedEmit:c.emit,message:n,rawSocket:o,socketState:s})}),r?.signal?.addEventListener(`abort`,()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),o.close()},{once:!0}),await FD(o,c.emit,a),o.send(dE(n)),await e.waitForReceipt(),c.socket}function FD(e,t,n){return new Promise((r,i)=>{let a=()=>{e.removeEventListener(`error`,o),t(`open`,{type:`open`}),r()},o=()=>{e.removeEventListener(`open`,a),i(Error(`WebSocket connection to ${n} failed to open.`))};e.addEventListener(`open`,a,{once:!0}),e.addEventListener(`error`,o,{once:!0})})}async function ID(e){let t=pE(e.message);if(!t){e.managedEmit(`message`,{data:e.message,type:`message`});return}switch(t.mpp){case`authorization`:return;case`message`:e.socketState.deliveredChunks+=1n,e.managedEmit(`message`,{data:t.data,type:`message`});return;case`payment-close-ready`:LD(e,t.data);return;case`payment-error`:e.driver.rejectReceipt(Error(t.message)),e.driver.rejectCloseReady(Error(t.message));return;case`payment-need-voucher`:await RD(e,t.data);return;case`payment-receipt`:zD(e,t.data);return}}function LD(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=MD({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,cumulativeAmount:n,receipt:t});if(r){e.failSocketFlow(r);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleCloseReady(t),e.managedEmit(`close`,{code:1e3,reason:`stream complete`,type:`close`,wasClean:!0})}async function RD(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+HD&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await sD({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:n,event:t,expectedChannelId:e.socketState.channelId,getChannel:e.driver.getChannel,input:e.driver.httpUrl,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status===`ignored`){e.failSocketFlow(r.reason===`channel-mismatch`?`received mismatched payment-need-voucher frame`:`cannot create voucher: no active channel`);return}let i=await e.driver.createSessionCredential(n,r.context);e.rawSocket.send(dE(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function zD(e,t){let n=ND({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}var BD,VD,HD,UD=I((()=>{dS(),tT(),kx(),YS(),vE(),nD(),BD={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},VD=3008,HD=5e3})),WD,GD,KD,qD,JD,YD=I((()=>{WD={mainnet:4217,testnet:42431},GD={usdc:`0x20C000000000000000000000b9537d11c60E8b50`,pathUsd:`0x20c0000000000000000000000000000000000000`},KD={[WD.mainnet]:GD.usdc,[WD.testnet]:GD.pathUsd},qD={[WD.mainnet]:`0x33b901018174DDabE4841042ab76ba85D4e24f25`,[WD.testnet]:`0xe1c4d3dce17bc111181ddf716f75bae49e61a336`},JD={[WD.mainnet]:`https://rpc.tempo.xyz`,[WD.testnet]:`https://rpc.moderato.tempo.xyz`}})),XD=Ke({chainName:()=>fO,confirm:()=>sO,decodeMemo:()=>eO,fetchBalanceLines:()=>gO,fetchTokenInfo:()=>hO,fmtBalance:()=>cO,fmtChallengeValue:()=>tO,fmtRequestValue:()=>$D,isAgentEnvironment:()=>iO,isTempoAccount:()=>aO,isTestnet:()=>mO,link:()=>nO,mainnetTokens:()=>xO,networkRpcUrls:()=>vO,parseMethodOpts:()=>rO,pathUsd:()=>yO,pc:()=>Z,printRequestHeaders:()=>ZD,printResponseHeaders:()=>QD,prompt:()=>oO,resolveChain:()=>dO,resolveFundingNetwork:()=>uO,resolveRpcUrl:()=>lO,testnetTokens:()=>SO,usdc:()=>bO});function ZD(e,t,n){let{pathname:r,host:i}=new URL(e);n(`> ${(t.method??`GET`).toUpperCase()} ${r} HTTP/1.1\n`),n(`> Host: ${i}\n`);for(let[e,r]of Object.entries(t.headers??{}))n(`> ${e}: ${r}\n`);n(`>
230
+ `)}function QD(e,t){if(!t.include&&t.verbose<2||t.silent)return;let n=`HTTP/1.1 ${e.status} ${e.statusText}`,r=t.verbose>=2?process.stderr:process.stdout,i=t.verbose>=2?`< `:``;r.write(`${i}${n}\n`);for(let[t,n]of e.headers)r.write(`${i}${t}: ${n}\n`);r.write(t.verbose>=2?`<
231
231
  `:`
232
- `)}function QD(e,t,n){if(gO.has(e)&&typeof t==`string`)return`${t} ${Z.dim(`(${sO(BigInt(t),n.tokenSymbol,n.tokenDecimals)})`)}`;if(e===`chainId`&&typeof t==`number`){let e=dO({id:t,name:``});return e?`${t} ${Z.dim(`(${e})`)}`:String(t)}return typeof t==`string`&&/^0x[0-9a-fA-F]{40}$/.test(t)?n.explorerUrl?tO(`${n.explorerUrl}/address/${t}`,t):t:typeof t==`string`&&/^https?:\/\//.test(t)?Z.link(t,t):String(t)}function $D(e){try{let t=e.replace(/^0x0*/,``);if(!t)return;let n=Uint8Array.from(t.match(/.{1,2}/g).map(e=>Number.parseInt(e,16))),r=new TextDecoder().decode(n);return/^[\x20-\x7e]+$/.test(r)?r:void 0}catch{return}}function eO(e,t){if(e===`realm`&&typeof t==`string`)try{let e=new URL(t.includes(`://`)?t:`https://${t}`);return Z.link(e.href,t)}catch{}return String(t)}function tO(e,t){return Z.link(e,t)}function nO(e){if(!e)return{};let t=Array.isArray(e)?e:[e],n={};for(let e of t){let t=e.indexOf(`=`);if(t===-1)throw Error(`Invalid method option format: ${e} (expected key=value)`);n[e.slice(0,t)]=e.slice(t+1)}return n}function rO(e=process.env){if(e.CLAUDECODE)return!0;for(let[t,n]of Object.entries(e))if(n&&(t===`CODEX`||t.startsWith(`CODEX_`)))return!0;return!1}function iO(e){return e.startsWith(`tempo:`)}function aO(e){let t=be.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.on(`close`,()=>n(void 0)),t.question(`${Z.bold(`▸ ${e}:`)} `,e=>{t.close(),n(e.trim()||void 0)})})}function oO(e,t=!1){let n=be.createInterface({input:process.stdin,output:process.stderr});return new Promise(r=>{let i=t?`(Y/n)`:`(y/N)`;n.question(`${Z.bold(`▸ ${e}`)} ${Z.dim(i)} `,e=>{n.close();let i=e.trim().toLowerCase();r(i===``?t:i===`y`)})})}function sO(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?Z.dim(Z.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):Z.dim(t);return`${a?`${o}.${a}`:o} ${s}`}function cO(e,t={}){return e??(t.network?_O[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}function lO(e={}){if(e.network)return e.network;if(!e.rpcUrl&&!(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()))return`testnet`}async function uO(e={}){let t=cO(e.rpcUrl,{network:e.network});if(!t)return ge;let{getChainId:n}=await import(`viem/actions`),r=await n(ne({transport:ue(t)})),i=Object.values(await import(`viem/tempo/chains`)).filter(e=>typeof e==`object`&&!!e&&`id`in e&&e.id===r),a=i.find(e=>`serializers`in e&&e.serializers)??i[0];if(!a)throw Error(`Unknown chain ID ${r} from RPC ${t}`);return a}function dO(e){return{[ge.id]:`mainnet`,[_e.id]:`testnet`}[e.id]??e.name}function fO(e){return typeof e==`bigint`?e:e.amount}function pO(e){return e.id!==ge.id}async function mO(e,t,n){let{Actions:r}=await import(`viem/tempo`),[i,a]=await Promise.all([r.token.getBalance(e,{account:n,token:t}).then(fO).catch(()=>0n),r.token.getMetadata(e,{token:t}).catch(()=>({symbol:t}))]);return{balance:i,symbol:{"0x20c0000000000000000000000000000000000000":`PathUSD`,"0x20C000000000000000000000b9537d11c60E8b50":`USDC`}[t]??a.symbol,decimals:`decimals`in a&&typeof a.decimals==`number`?a.decimals:6,token:t}}async function hO(e,t){if(t?.chain){let n=ne({chain:t.chain,transport:ue(t.rpcUrl)}),r=t.chain.blockExplorers?.default?.url,i=Z.dim(`(${dO(t.chain)})`);return pO(t.chain)?(await Promise.all(xO.map(t=>mO(n,t,e)))).filter(e=>e.balance>0n).map(e=>`${sO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`):(await Promise.all(bO.map(t=>mO(n,t,e)))).map(e=>`${sO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`)}let n=ne({chain:ge,transport:ue(cO())}),r=ge.blockExplorers?.default?.url,i=(await Promise.all(bO.map(t=>mO(n,t,e)))).map(e=>sO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token}));if(t?.includeTestnet!==!1){let t=ne({chain:_e,transport:ue()}),n=_e.blockExplorers?.default?.url,r=await Promise.all(xO.map(n=>mO(t,n,e)));for(let e of r)e.balance>0n&&i.push(`${sO(e.balance,e.symbol,e.decimals,{explorerUrl:n,token:e.token})} ${Z.dim(`(testnet)`)}`)}return i}var Z,gO,_O,vO,yO,bO,xO,SO=I((()=>{JD(),Z=(()=>{let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes(`--no-color`))&&(!!n.FORCE_COLOR||t.includes(`--color`)||(e.stdout||{}).isTTY&&n.TERM!==`dumb`||!!n.CI),i=(e,t,n,r)=>{let i=``,a=0,o=r;do i+=e.substring(a,o)+n,a=o+t.length,o=e.indexOf(t,a);while(~o);return i+e.substring(a)},a=r?(e,t,n=e)=>r=>{let a=`${r}`,o=a.indexOf(t,e.length);return~o?e+i(a,t,n,o)+t:e+a+t}:()=>String;return{isColorSupported:r,reset:a(`\x1B[0m`,`\x1B[0m`),bold:a(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:a(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:a(`\x1B[3m`,`\x1B[23m`),underline:a(`\x1B[4m`,`\x1B[24m`),inverse:a(`\x1B[7m`,`\x1B[27m`),hidden:a(`\x1B[8m`,`\x1B[28m`),strikethrough:a(`\x1B[9m`,`\x1B[29m`),black:a(`\x1B[30m`,`\x1B[39m`),red:a(`\x1B[31m`,`\x1B[39m`),green:a(`\x1B[32m`,`\x1B[39m`),yellow:a(`\x1B[33m`,`\x1B[39m`),blue:a(`\x1B[34m`,`\x1B[39m`),magenta:a(`\x1B[35m`,`\x1B[39m`),cyan:a(`\x1B[36m`,`\x1B[39m`),white:a(`\x1B[37m`,`\x1B[39m`),gray:a(`\x1B[90m`,`\x1B[39m`),bgBlack:a(`\x1B[40m`,`\x1B[49m`),bgRed:a(`\x1B[41m`,`\x1B[49m`),bgGreen:a(`\x1B[42m`,`\x1B[49m`),bgYellow:a(`\x1B[43m`,`\x1B[49m`),bgBlue:a(`\x1B[44m`,`\x1B[49m`),bgMagenta:a(`\x1B[45m`,`\x1B[49m`),bgCyan:a(`\x1B[46m`,`\x1B[49m`),bgWhite:a(`\x1B[47m`,`\x1B[49m`),blackBright:a(`\x1B[90m`,`\x1B[39m`),redBright:a(`\x1B[91m`,`\x1B[39m`),greenBright:a(`\x1B[92m`,`\x1B[39m`),yellowBright:a(`\x1B[93m`,`\x1B[39m`),blueBright:a(`\x1B[94m`,`\x1B[39m`),magentaBright:a(`\x1B[95m`,`\x1B[39m`),cyanBright:a(`\x1B[96m`,`\x1B[39m`),whiteBright:a(`\x1B[97m`,`\x1B[39m`),bgBlackBright:a(`\x1B[100m`,`\x1B[49m`),bgRedBright:a(`\x1B[101m`,`\x1B[49m`),bgGreenBright:a(`\x1B[102m`,`\x1B[49m`),bgYellowBright:a(`\x1B[103m`,`\x1B[49m`),bgBlueBright:a(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:a(`\x1B[105m`,`\x1B[49m`),bgCyanBright:a(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:a(`\x1B[107m`,`\x1B[49m`),link(e,t,n){return r?`\x1b]8;;${e}\x07${n?t:Z.underline(t)}\x1b]8;;\x07`:t}}})(),gO=new Set([`amount`,`suggestedDeposit`,`minVoucherDelta`]),_O={mainnet:qD[UD.mainnet],testnet:qD[UD.testnet]},vO=`0x20c0000000000000000000000000000000000000`,yO=`0x20C000000000000000000000b9537d11c60E8b50`,bO=[vO,yO],xO=[`0x20c0000000000000000000000000000000000000`,`0x20c0000000000000000000000000000000000001`,`0x20c0000000000000000000000000000000000002`,`0x20c0000000000000000000000000000000000003`]}));function CO(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:FO}function wO(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function TO(e){return new L({code:`KEYCHAIN_UNAVAILABLE`,message:`Linux keyring requires secret-tool. Install libsecret-tools.`,hint:`On Debian/Ubuntu, run: sudo apt install libsecret-tools gnome-keyring dbus-x11`,exitCode:69,cause:e})}function EO(e){if(e&&wO(e,`secret-tool`))throw TO(e)}function DO(e,t){return new Promise(n=>{p.execFile(e,t,{timeout:CO()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function OO(){let t=s.join(process.env.XDG_CONFIG_HOME||s.join(y.homedir(),`.config`),`mppx`,`default`);return{get(){try{return e.readFileSync(t,`utf-8`).trim()||`main`}catch{return`main`}},set(n){e.mkdirSync(s.dirname(t),{recursive:!0}),e.writeFileSync(t,n,`utf-8`)},clear(){try{e.unlinkSync(t)}catch{}}}}function kO(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:OO().get())}function AO(e=`main`){let t=PO;return{async list(){let e=y.platform();if(e===`darwin`){let{stdout:e,error:n}=await DO(`security`,[`dump-keychain`]);if(n)return[];let r=[],i=e.split(`keychain:`);for(let e of i){let n=e.match(/"svce"<blob>="([^"]*)"/),i=e.match(/"acct"<blob>="([^"]*)"/);n?.[1]===t&&i?.[1]&&r.push(i[1])}return r}if(e===`linux`){let{stdout:e,stderr:n,error:r}=await DO(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(EO(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=y.platform();if(n===`darwin`){let{stdout:n,error:r}=await DO(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await DO(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return EO(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=y.platform();if(r===`darwin`){await DO(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await DO(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=p.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),CO());return r.stdin?.write(n),r.stdin?.end(),new Promise((e,t)=>{r.on(`close`,n=>{clearTimeout(i),n===0?e():t(Error(`secret-tool exited with code ${n}`))}),r.on(`error`,e=>{clearTimeout(i),t(wO(e,`secret-tool`)?TO(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=y.platform();if(n===`darwin`){await DO(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await DO(`secret-tool`,[`clear`,`service`,t,`account`,e]);EO(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function jO(e){let{privateKeyToAccount:t}=await import(`viem/accounts`),n=process.env.MPPX_PRIVATE_KEY?.trim();if(n)return{account:t(n),source:`environment`};let r=kO(e),i=await AO(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function MO(e){let t=kO(e);if(!process.env.MPPX_PRIVATE_KEY?.trim()&&iO(t))throw new L({code:`UNSUPPORTED_ACCOUNT`,message:`Persistent sessions require an mppx account or MPPX_PRIVATE_KEY.`,exitCode:2});return jO(e).catch(e=>{throw new L({code:`ACCOUNT_NOT_FOUND`,message:e instanceof Error?e.message:`No account found.`,exitCode:69,...e instanceof Error&&{cause:e}})})}async function NO(e){return(await jO(e)).account}var PO,FO,IO=I((()=>{SO(),PO=`mppx`,FO=1e4}));const LO=Symbol(`mppx.x402.asset`);function RO(e){return{[LO]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function zO(e,t){let n=e(t.chainId);return RO({address:n.address,decimals:n.decimals,network:YO(t.chainId),transfer:ZO(t.transfer,n)})}const BO={USDC:RO({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},VO={USDC:RO({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},HO={USDC:RO({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:RO({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},UO={USDC:RO({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function WO(e){return typeof e!=`object`||!e?!1:e[LO]===!0}function GO(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function KO(e){return typeof e==`string`}function qO(e,t){if(WO(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(GO(e)){let n=e.addresses[XO(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function JO(e,t,n){let r=qO(e,n);return r?ce(r.address)===ce(t):!1}function YO(e){return`eip155:${e}`}function XO(e){return Number(e.slice(7))}function ZO(e,t){if(e.type!==`eip3009`)return e;if(e.name)return{...e,name:e.name};if(!t.name)throw Error(`EIP-3009 token assets require a token name.`);return{...e,name:t.name}}var QO=Ke({base:()=>BO,baseSepolia:()=>VO,celo:()=>HO,celoSepolia:()=>UO,define:()=>RO,fromToken:()=>zO,isAsset:()=>WO,isRawAddress:()=>KO,isToken:()=>GO,matches:()=>JO,resolve:()=>qO,toChainId:()=>XO,toNetwork:()=>YO}),$O=Ke({base:()=>ek,baseSepolia:()=>tk,celo:()=>nk,celoSepolia:()=>rk});const ek=8453,tk=84532,nk=42220,rk=11142220;Nx();function ik(e){let t=[Mx(e.accepted),Mx(e.resource),Mx(e.extensions)].join(`|`);return A.sha256(k.fromString(t),{as:`Hex`})}JC(),SC();async function ak(e){let t=e.context?.account??e.config.account;if(!t.signTypedData)throw Error(`x402 exact requires a typed-data signer.`);let n=e.challenge.request,r=$S(n);if(lk(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?dk(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} signing is not implemented yet.`);let o=r.extra?.name,s=r.extra?.version;if(typeof o!=`string`||typeof s!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let c=Math.floor(Date.now()/1e3),l={from:ce(t.address),nonce:i?.mppx?ik({accepted:r,extensions:i,resource:n.resource}):pk(),to:ce(r.payTo),validAfter:(c-600).toString(),validBefore:(c+r.maxTimeoutSeconds).toString(),value:r.amount},u=await t.signTypedData({domain:{chainId:ck(r.network),name:o,verifyingContract:ce(r.asset),version:s},message:{...l,value:BigInt(l.value),validAfter:BigInt(l.validAfter),validBefore:BigInt(l.validBefore)},primaryType:`TransferWithAuthorization`,types:sk});return KC({accepted:r,...i?{extensions:i}:{},payload:{authorization:l,signature:u},...n.resource?{resource:n.resource}:{},x402Version:2})}function ok(e){let t=e.challenge.request,n;try{n=$S(t),lk(e.config,n)}catch{return!1}if(!t.resource||(n.extra?.assetTransferMethod??`eip3009`)!==`eip3009`)return!1;let r=n.extra?.name,i=n.extra?.version;return typeof r==`string`&&typeof i==`string`}const sk={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function ck(e){return Number(e.slice(nC.length))}function lk(e,t){let n=ck(t.network);if(e.networks&&!e.networks.includes(n))throw Error(`x402 exact chain ID is not allowed: ${n}.`);let r=e.currencies??e.assets;if(r?.some(e=>KO(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=ce(t.asset);if(!r.some(n=>JO(n,e,t.network)))throw Error(`x402 exact currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`x402 exact amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=uk(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>P(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function uk(e,t){let n=e.currencies??e.assets,r=ce(t.asset),i=n?.find(e=>JO(e,r,t.network)),a=i?qO(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function dk(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:fk()}}}:e}function fk(){return mk().slice(2)}function pk(){return mk()}function mk(){let e=globalThis.crypto;if(!e?.getRandomValues)throw Error(`x402 exact requires crypto randomness.`);let t=e.getRandomValues(new Uint8Array(32));return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}Gx();const hk=[`authorization`],gk=Y.string().check(Y.regex(/^\d+$/,`Invalid atomic amount`));Y.object({name:Y.string().check(Y.minLength(1)),version:Y.string().check(Y.minLength(1))});const _k=Y.object({chainId:Y.number(),credentialTypes:Y.optional(Y.array(Y.enum(hk)).check(Y.minLength(1))),decimals:Y.optional(Y.number()),permit2Address:Y.optional(Bx()),splits:Y.optional(Y.array(Y.object({amount:gk,recipient:Bx()})))});Y.object({amount:gk,currency:Bx(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),methodDetails:_k,recipient:Bx()});const vk=Y.object({amount:Fx(),chainId:Y.number(),currency:Bx(),credentialTypes:Y.optional(Y.array(Y.enum(hk)).check(Y.minLength(1))),decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),permit2Address:Y.optional(Bx()),recipient:Bx(),splits:Y.optional(Y.array(Y.object({amount:gk,recipient:Bx()})))}),yk=Y.object({from:Bx(),nonce:Vx(),signature:Ux(),to:Bx(),type:Y.literal(`authorization`),validAfter:gk,validBefore:gk,value:gk}),bk={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function xk(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function Sk(e){return A.keccak256(k.fromString(`${e.id}${e.realm}`),{as:`Hex`})}function Ck(e){return`eip155:${e}`}function wk(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}MT(),Gx();const Tk=AT({name:`evm`,intent:`charge`,schema:{credential:{payload:yk},request:Y.pipe(vk,Y.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...c})=>({...c,amount:P(e,i).toString(),currency:ce(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:ce(a)}:{},...s?{splits:s}:{}},recipient:ce(o)})))}});YS(),MT(),xS(),Gx();function Ek(e){return jT(Tk,{canHandleChallenge({challenge:t}){return!Dk(t)||ok({challenge:t,config:e})},context:Y.object({account:Y.optional(Y.custom())}),async createCredential({challenge:t,context:n}){if(Dk(t))return ak({challenge:t,config:e,context:n});let r=n?.account??e.account;if(!r.signTypedData)throw Error(`EVM authorization requires a typed-data signer.`);let i=t.request;if(Ok(e,i),!i.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(i.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`);let a=kk(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return KS(GS({challenge:t,payload:{from:ce(r.address),nonce:Sk(t),signature:await r.signTypedData({domain:xk({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:ce(r.address),nonce:Sk(t),to:ce(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:bk}),to:ce(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:wk({address:ce(r.address),chainId:i.methodDetails.chainId})}))}})}function Dk(e){return yS(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function Ok(e,t){let n=t.methodDetails.chainId,r=Ck(n);if(e.networks&&!e.networks.includes(n))throw Error(`EVM chain ID is not allowed: ${n}.`);let i=e.currencies??e.assets;if(i?.some(e=>KO(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=ce(t.currency);if(!i.some(t=>JO(t,e,r)))throw Error(`EVM currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`EVM charge amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=Ak(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>P(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function kk(e,t){let n=e.currencies??e.assets,r=ce(t.currency),i=Ck(t.methodDetails.chainId),a=n?.find(e=>JO(e,r,i)),o=a?qO(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;throw Error(`EVM authorization requires token name and version.`)}function Ak(e,t){let n=e.currencies??e.assets,r=ce(t.currency),i=Ck(t.methodDetails.chainId),a=n?.find(e=>JO(e,r,i)),o=a?qO(a,i):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function jk(e){return[jk.charge(e)]}(function(e){e.charge=Ek,e.assets=QO,e.chains=$O})(jk||={});function Mk(e){return e}var Nk=I((()=>{}));IO(),Nk();function Pk(){return Mk({method:`evm`,async setup({challenge:e}){let t=e.request,n=t.methodDetails,r=n?.chainId,i=r?Fk(r):void 0,a=t.currency,o=await NO(),s=[...Object.values(BO),...Object.values(VO),...Object.values(HO),...Object.values(UO)],c=a??``;if(i&&a)try{let e=ne({chain:i,transport:ue()}),t=await xe(e,{address:a,abi:oe,functionName:`symbol`});t&&(c=t)}catch{}return{tokenSymbol:c,tokenDecimals:n?.decimals??6,explorerUrl:i?.blockExplorers?.default?.url,methods:[...jk({account:o,currencies:s})]}}})}function Fk(e){return Object.values(Pe).find(t=>t.id===e)}Gx();const Ik=Y.object({metadata:Y.record(Y.string(),Y.string())});MT(),Gx();const Lk=AT({name:`stripe`,intent:`charge`,schema:{credential:{payload:Y.object({externalId:Y.optional(Y.string()),spt:Y.string()})},request:Y.pipe(Y.object({amount:Fx(),currency:Y.string(),decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),metadata:Y.optional(Y.record(Y.string(),Y.string())),networkId:Y.string(),paymentIntentOptions:Y.optional(Ik),paymentMethodTypes:Y.array(Y.string()).check(Y.minLength(1)),recipient:Y.optional(Y.string())}),Y.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:P(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});YS(),MT(),Gx();function Rk(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return jT(Lk,{context:Y.object({paymentMethod:Y.optional(Y.string())}),async createCredential({challenge:e,context:a}){let o=a?.paymentMethod??i;if(!o)throw Error(`paymentMethod is required (pass via context or parameters)`);let s=e.request.amount,c=e.request.currency,l=typeof e.request.externalId==`string`?e.request.externalId:void 0,u=e.request.methodDetails?.networkId;if(!u)throw Error(`networkId is required in challenge.methodDetails`);let d=e.request.methodDetails?.metadata;if(d?.externalId)throw Error(`methodDetails.metadata.externalId is reserved; use credential externalId instead`);let f=e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,p=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:f,metadata:d,networkId:u,paymentMethod:o}),m=l??r;return KS({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function zk(e){return[Rk(e)]}(function(e){e.charge=Rk})(zk||={}),Sx(),SO(),Nk();function Bk(){return Mk({method:`stripe`,supports(e){return e.method===`stripe`&&e.intent===`charge`},async setup({challenge:e,methodOpts:t}){let n=e.request,r=n.currency,i=Hk(f.object({paymentMethod:f.string(),secretKey:f.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new L({code:`MISSING_ENV`,message:`MPPX_STRIPE_SECRET_KEY environment variable is required for Stripe payments.`,exitCode:2});return{tokenSymbol:r?.toUpperCase()??``,tokenDecimals:n.decimals??2,methods:[zk.charge({paymentMethod:i.paymentMethod,createToken:async({paymentMethod:e,amount:t,currency:n,networkId:r,expiresAt:i,metadata:o})=>{let s=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()}),c=Vk(a),l=process.env.MPPX_STRIPE_SPT_URL?process.env.MPPX_STRIPE_SPT_URL:c?`https://api.stripe.com/v1/test_helpers/shared_payment/granted_tokens`:`https://api.stripe.com/v1/shared_payment/issued_tokens`;if(r){let e=c?`seller_details[network_id]`:`seller_details[network_business_profile]`;s.set(e,r)}if(o)for(let[e,t]of Object.entries(o))s.set(`metadata[${e}]`,t);let u={Authorization:`Basic ${btoa(`${a}:`)}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":`2026-07-29.preview`},d=await globalThis.fetch(l,{method:`POST`,headers:u,body:s});if(!d.ok){let a=await d.json();if(c&&(o||r)&&a.error.message.includes(`Received unknown parameter`)){let r=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()});if(d=await globalThis.fetch(l,{method:`POST`,headers:u,body:r}),!d.ok){let e=await d.json();throw new L({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${e.error.message}`,exitCode:77})}}else throw new L({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${a.error.message}`,exitCode:77})}let{id:f}=await d.json();return f}})]}},formatReceiptField(e,t){if(e===`reference`&&typeof t==`string`&&t.startsWith(`pi_`)){let e=process.env.MPPX_STRIPE_SECRET_KEY,n=`https://dashboard.stripe.com${e!==void 0&&Vk(e)?`/test`:``}/payments/${t}`;return Z.link(n,t,!0)}}})}function Vk(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function Hk(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function Uk(e={}){let{account:t}=e;return(e,{account:n}={})=>{let r=n??t;if(!r){if(!e.account)throw Error("No `account` provided. Pass `account` to parameters or context.");return e.account}return me(r)}}var Wk=I((()=>{}));function Gk(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}var Kk=I((()=>{}));function qk(e,t={}){return ue(e.url,{fetchOptions:{headers:Gk(e)},...t})}function Jk(e){let{chain:t,getClient:n,remoteFeePayer:r,rpcUrl:i}=e;return n?!t?.serializers&&!r?n:async e=>{let i=await n(e),a=i;if(r&&i.transport.key!==`feePayer`){let e=i.request.bind(i),t=Ne(ie({request:t=>e(t)},{retryCount:0}),qk(r,{retryCount:i.transport.retryCount}))({account:i.account,chain:i.chain,pollingInterval:i.pollingInterval,retryCount:0}),n=re({...t.config,retryCount:0},t.value);a=Object.assign({},i,{request:n.request,transport:{...n.config,...n.value}})}return!t?.serializers||a.chain?.serializers?.transaction?a:Object.assign({},a,{chain:{...t,...a.chain,formatters:a.chain?.formatters??t.formatters,prepareTransactionRequest:a.chain?.prepareTransactionRequest??t.prepareTransactionRequest,serializers:a.chain?.serializers?.transaction?a.chain.serializers:t.serializers}})}:({chainId:e})=>{if(!i)throw Error("No `rpcUrl` provided.");let n=e||Number(Object.keys(i)[0]),a=i[n];if(!a)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let o=r?Ne(ue(a),qk(r)):ue(a);return ne({chain:Yk[n]??{...t,id:n},transport:o})}}var Yk,Xk=I((()=>{Kk(),Yk={[ge.id]:ge,[_e.id]:_e}}));function Zk(e){let t=A.keccak256(k.fromString(e),{as:`Hex`});return j.toBytes(j.slice(t,0,10))}function Qk(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(j.toBytes(eA),0),i[4]=tA,i.set(Zk(t),5),n&&i.set(Zk(n),15),i.set($k(r),25),j.fromBytes(i)}function $k(e){let t=A.keccak256(k.fromString(e),{as:`Hex`});return j.toBytes(j.slice(t,0,7))}var eA,tA,nA=I((()=>{eA=j.slice(A.keccak256(k.fromString(`mpp`),{as:`Hex`}),0,4),tA=1}));function rA(e,t){return ze.resolve(e).toLowerCase()===ze.resolve(t).toLowerCase()}var iA=I((()=>{}));async function aA(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t,s=a.filter(e=>!rA(e,i)),c=await Promise.allSettled([xe(e,ke.token.getBalance.call(e,{account:n,token:i})),...s.map(t=>xe(e,ke.token.getBalance.call(e,{account:n,token:t})))]),l=c[0];if(!(l.status===`fulfilled`&&l.value>=r)){for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let a=n.value;if(a<=0n)continue;let l=s[t];try{let t=await ke.dex.getBuyQuote(e,{tokenIn:l,tokenOut:i,amountOut:r});if(a>=t){let n=t+t*BigInt(Math.round(o*100))/sA;return[ke.token.approve.call(e,{amount:n,spender:Ae.stablecoinDex,token:l}),ke.dex.buy.call({tokenIn:l,tokenOut:i,amountOut:r,maxAmountIn:n})]}}catch{}}throw new lA({currency:i})}}function oA(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...t.filter(t=>!e.tokenIn.some(e=>rA(e,t)))]:t,slippage:e.slippage??1}:!1}var sA,cA,lA,uA=I((()=>{iA(),JD(),sA=10000n,cA=[WD.pathUsd,WD.usdc],lA=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}}}));function dA(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:e.amount,memo:e.memo,recipient:e.recipient}))]}var fA=I((()=>{}));function pA(e,t,n){t&&(n&&!n.some(e=>rA(e,t))||e.some(e=>rA(e,t))||e.push(t))}async function mA(e,t,n){try{return(await ke.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function hA(e){let t=e.chain?.feeToken;if(t)return je.toAddress(t);let n=e.chain?.id;return n?GD[n]:void 0}function gA(e){let t=[];return pA(t,WD.pathUsd),pA(t,GD[e]),t}async function _A(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])pA(o,e,n);if(pA(o,await ke.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),pA(o,hA(i),n),!a)for(let e of r??[])pA(o,e,n);for(let e of o)if(await mA(i,t,e))return e;return o[0]}var vA=I((()=>{iA(),JD()}));function yA(e){return{name:`MPP`,version:`3`,chainId:e}}function bA(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function xA(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:yA(n),types:wA,primaryType:CA,message:bA({account:t,challengeId:r,realm:i})}}function SA(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}var CA,wA,TA=I((()=>{CA=`Proof`,wA={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]}})),EA,DA=I((()=>{EA=Ve({addresses:{4217:`0x20c000000000000000000000f37de3740ADec032`,42431:`0x20c000000000000000000000f37de3740ADec032`},currency:`USD`,decimals:6,name:`MACH`,symbol:`MACH`})}));function OA(e={}){let{clientId:t}=e,n=Jk({chain:ge,getClient:e.getClient,rpcUrl:qD}),r=Uk({account:e.account});return jT(GT,{context:kA,async createCredential({challenge:i,context:a}){let o=i.request.methodDetails?.chainId;if(e.expectedChainId!==void 0&&o!==void 0&&o!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${o}.`);let s=o??e.expectedChainId,c=await n({chainId:s}),l=s??c.chain?.id;if(l===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:u}=i,{amount:d,methodDetails:f}=u,p=f?.supportedModes??[`pull`,`push`],m=r(c,a);if(BigInt(d)===0n)return KS({challenge:i,payload:{signature:await Te(c,{account:m,...xA({account:m.address,chainId:l,challengeId:i.id,realm:i.realm})}),type:`proof`},source:SA({address:m.address,chainId:l})});let h=u.currency;if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase())),n=f?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}let g=f?.memo?f.memo:Qk({challengeId:i.id,clientId:t,serverId:i.realm}),_=dA({amount:d,methodDetails:{...f,memo:g},recipient:u.recipient}).map(e=>ke.token.transfer.call(c,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:h})),v=oA(a?.autoSwap??e.autoSwap,cA),y=await e.resolveAccount?.({account:m,chainId:l,operation:{kind:`executeCalls`,...v?{}:{calls:_}}})??m,b=(()=>{let t=a?.mode??e.mode;if(t){if(!p.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=y.type===`json-rpc`?`push`:`pull`;return p.includes(n)?n:p[0]})(),x=[...(v?await aA(c,{account:y.address,amountOut:BigInt(d),tokenOut:h,tokenIn:v.tokenIn,slippage:v.slippage}):void 0)??[],..._],S=EA.addresses[l],C=gA(l),w=S&&fe(h,S)?await _A({account:y.address,allowedTokens:C,candidateTokens:C,client:c,prioritizeCandidates:!0}):void 0,T=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!i.expires)return e;let t=Math.floor(new Date(i.expires).getTime()/1e3);return Math.min(e,t)})();if(b===`push`){let{receipts:e}=y.type===`local`?{receipts:[await Ce(c,{account:y,calls:x,...w?{feeToken:w}:{},nonceKey:`expiring`,validBefore:T})]}:await Se(c,{account:y,...w?{capabilities:{feeToken:w}}:{},calls:x,experimental_fallback:x.length===1,forceAtomic:x.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return KS({challenge:i,payload:{hash:t,type:`hash`},source:SA({address:y.address,chainId:l})})}let ee=await F(c,{account:y,calls:x,...w?{feeToken:w}:{},nonceKey:`expiring`,validBefore:T});if(ee.gas=(ee.gas??0n)+5000n,f?.feePayer){let e=ee;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return KS({challenge:i,payload:{signature:await we(c,ee),type:`transaction`},source:SA({address:y.address,chainId:l})})}})}var kA,AA=I((()=>{YS(),MT(),Wk(),Xk(),Gx(),nA(),uA(),fA(),JD(),vA(),TA(),JT(),DA(),kA=Y.object({account:Y.optional(Y.custom()),autoSwap:Y.optional(Y.custom()),mode:Y.optional(Y.enum(FT))})}));function jA(e){return`accessKeyAddress`in e}function MA(e){return jA(e)?e.accessKeyAddress:e.address}var NA=I((()=>{}));function PA(e,t){return{name:HA,version:UA,chainId:t,verifyingContract:e}}function FA(e){return{channelId:e.channelId,cumulativeAmount:e.cumulativeAmount}}function IA(e,t,n){return le({domain:PA(e,t),types:WA,primaryType:`Voucher`,message:FA(n)})}async function LA(e,t,n,r,i){return Te(e,{account:t,domain:PA(r,i),types:WA,primaryType:`Voucher`,message:FA(n)})}function RA(e){let t=Re.from(e);if(t.type===`keychain`){if(t.inner.type!==`secp256k1`)throw Error(`Session vouchers only unwrap secp256k1 keychain signatures; pass a direct voucherSigner for other key types.`);return M.toHex(t.inner.signature)}return Re.serialize(t)}function zA(e){return e.type===`keychain`?!1:e.type===`secp256k1`||GA}function BA(e){if(!zA(e))throw Error(`Session vouchers only support secp256k1 signatures until TIP-1020 voucher verification is enabled.`)}async function VA(e,t,n,r,i,a){let o=a??t,s=MA(o),c=IA(r,i,n),l=RA(jA(o)?await o.sign({hash:c,raw:!0}):await LA(e,o,n,r,i)),u=Re.from(l);if(BA(u),!Re.verify(u,{address:s,payload:c}))throw Error(`voucher signature does not match voucher signer`);return l}var HA,UA,WA,GA,KA=I((()=>{NA(),HA=`Tempo Stream Channel`,UA=`1`,WA={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint128`}]},GA=!1}));function qA(e){let t=D.encode(D.from([`address payer`,`address payee`,`address token`,`bytes32 salt`,`address authorizedSigner`,`address escrowContract`,`uint256 chainId`]),[e.payer,e.payee,e.token,e.salt,e.authorizedSigner,e.escrowContract,BigInt(e.chainId)]);return A.keccak256(t)}var JA=I((()=>{})),YA,XA=I((()=>{YA=[{type:`function`,name:`CLOSE_GRACE_PERIOD`,inputs:[],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`VOUCHER_TYPEHASH`,inputs:[],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`channels`,inputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:`finalized`,type:`bool`,internalType:`bool`},{name:`closeRequestedAt`,type:`uint64`,internalType:`uint64`},{name:`payer`,type:`address`,internalType:`address`},{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`authorizedSigner`,type:`address`,internalType:`address`},{name:`deposit`,type:`uint128`,internalType:`uint128`},{name:`settled`,type:`uint128`,internalType:`uint128`}],stateMutability:`view`},{type:`function`,name:`close`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`},{name:`cumulativeAmount`,type:`uint128`,internalType:`uint128`},{name:`signature`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`computeChannelId`,inputs:[{name:`payer`,type:`address`,internalType:`address`},{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`salt`,type:`bytes32`,internalType:`bytes32`},{name:`authorizedSigner`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`domainSeparator`,inputs:[],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`eip712Domain`,inputs:[],outputs:[{name:`fields`,type:`bytes1`,internalType:`bytes1`},{name:`name`,type:`string`,internalType:`string`},{name:`version`,type:`string`,internalType:`string`},{name:`chainId`,type:`uint256`,internalType:`uint256`},{name:`verifyingContract`,type:`address`,internalType:`address`},{name:`salt`,type:`bytes32`,internalType:`bytes32`},{name:`extensions`,type:`uint256[]`,internalType:`uint256[]`}],stateMutability:`view`},{type:`function`,name:`getChannel`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`tuple`,internalType:`struct TempoStreamChannel.Channel`,components:[{name:`finalized`,type:`bool`,internalType:`bool`},{name:`closeRequestedAt`,type:`uint64`,internalType:`uint64`},{name:`payer`,type:`address`,internalType:`address`},{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`authorizedSigner`,type:`address`,internalType:`address`},{name:`deposit`,type:`uint128`,internalType:`uint128`},{name:`settled`,type:`uint128`,internalType:`uint128`}]}],stateMutability:`view`},{type:`function`,name:`getChannelsBatch`,inputs:[{name:`channelIds`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[{name:`channelStates`,type:`tuple[]`,internalType:`struct TempoStreamChannel.Channel[]`,components:[{name:`finalized`,type:`bool`,internalType:`bool`},{name:`closeRequestedAt`,type:`uint64`,internalType:`uint64`},{name:`payer`,type:`address`,internalType:`address`},{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`authorizedSigner`,type:`address`,internalType:`address`},{name:`deposit`,type:`uint128`,internalType:`uint128`},{name:`settled`,type:`uint128`,internalType:`uint128`}]}],stateMutability:`view`},{type:`function`,name:`getVoucherDigest`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`},{name:`cumulativeAmount`,type:`uint128`,internalType:`uint128`}],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`open`,inputs:[{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`deposit`,type:`uint128`,internalType:`uint128`},{name:`salt`,type:`bytes32`,internalType:`bytes32`},{name:`authorizedSigner`,type:`address`,internalType:`address`}],outputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`}],stateMutability:`nonpayable`},{type:`function`,name:`requestClose`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`settle`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`},{name:`cumulativeAmount`,type:`uint128`,internalType:`uint128`},{name:`signature`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`topUp`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`},{name:`additionalDeposit`,type:`uint256`,internalType:`uint256`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`withdraw`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`}],outputs:[],stateMutability:`nonpayable`},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`settledToPayee`,type:`uint256`,indexed:!1,internalType:`uint256`},{name:`refundedToPayer`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`ChannelExpired`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`}],anonymous:!1},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`token`,type:`address`,indexed:!1,internalType:`address`},{name:`authorizedSigner`,type:`address`,indexed:!1,internalType:`address`},{name:`salt`,type:`bytes32`,indexed:!1,internalType:`bytes32`},{name:`deposit`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`}],anonymous:!1},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`closeGraceEnd`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`cumulativeAmount`,type:`uint256`,indexed:!1,internalType:`uint256`},{name:`deltaPaid`,type:`uint256`,indexed:!1,internalType:`uint256`},{name:`newSettled`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`additionalDeposit`,type:`uint256`,indexed:!1,internalType:`uint256`},{name:`newDeposit`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`error`,name:`AmountExceedsDeposit`,inputs:[]},{type:`error`,name:`AmountNotIncreasing`,inputs:[]},{type:`error`,name:`ChannelAlreadyExists`,inputs:[]},{type:`error`,name:`ChannelFinalized`,inputs:[]},{type:`error`,name:`ChannelNotFound`,inputs:[]},{type:`error`,name:`CloseNotReady`,inputs:[]},{type:`error`,name:`DepositOverflow`,inputs:[]},{type:`error`,name:`InvalidPayee`,inputs:[]},{type:`error`,name:`InvalidSignature`,inputs:[]},{type:`error`,name:`NotPayee`,inputs:[]},{type:`error`,name:`NotPayer`,inputs:[]},{type:`error`,name:`TransferFailed`,inputs:[]}]}));async function ZA(e,t,n){return xe(e,{address:t,abi:YA,functionName:`getChannel`,args:[n]})}var QA=I((()=>{XA(),N({abi:YA,name:`open`}),N({abi:YA,name:`topUp`})}));function $A(e,t){return t??e}function ej(e,t,n,r=!1){let i=e.request.methodDetails?.escrowContract,a=n??KD[t];if(!a&&!(r&&i))throw Error("No trusted `escrowContract` available. Provide it in client parameters or use a supported chain.");if(i&&a&&i.toLowerCase()!==a.toLowerCase()&&(!r||n!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&(!a||i.toLowerCase()!==a.toLowerCase())?i:a}function tj(e,t,n,r){return KS({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}async function nj(e,t,n,r,i,a,o){let s=$A(t,o),c=await VA(e,t,{channelId:n,cumulativeAmount:r},i,a,s);return{action:`voucher`,channelId:n,cumulativeAmount:r.toString(),signature:c}}async function rj(e,t,n){let{escrowContract:r,payee:i,currency:a,deposit:o,initialAmount:s,chainId:c,feePayer:l}=n,u=$A(t,n.voucherSigner),d=MA(u),f=j.random(32),p=qA({authorizedSigner:d,chainId:c,escrowContract:r,payee:i,payer:t.address,salt:f,token:a}),m=ae({abi:De.tip20,functionName:`approve`,args:[r,o]}),h=ae({abi:YA,functionName:`open`,args:[i,a,o,f,d]}),g=Math.floor(Date.now()/1e3)+25,_=await F(e,{account:t,calls:[{to:a,data:m},{to:r,data:h}],feeToken:a,nonceKey:`expiring`,validBefore:g});_.gas=(_.gas??0n)+5000n,l&&(_.feePayer=!0);let v=await we(e,_),y=await VA(e,t,{channelId:p,cumulativeAmount:s},r,c,u);return{entry:{authorizedSigner:d,channelId:p,salt:f,cumulativeAmount:s,escrowContract:r,chainId:c,opened:!0},payload:{action:`open`,type:`transaction`,channelId:p,transaction:v,authorizedSigner:d,cumulativeAmount:s.toString(),signature:y}}}async function ij(e,t,n,r){try{let i=await ZA(e,t,n);if(i.deposit>0n&&!i.finalized)return{authorizedSigner:BigInt(i.authorizedSigner)===0n?i.payer:i.authorizedSigner,channelId:n,salt:`0x`,cumulativeAmount:i.settled,escrowContract:t,chainId:r,opened:!0}}catch{}}var aj=I((()=>{YS(),NA(),JD(),QA(),JA(),KA()}));function oj(e={}){let{allowCustomEscrow:t=!1,decimals:n=6}=e,r=Jk({chain:ge,getClient:e.getClient,rpcUrl:qD}),i=Uk({account:e.account}),a=e.maxDeposit===void 0?void 0:P(e.maxDeposit,n),o=new Map,s=new Map,c=new Map;function l(t){e.onChannelUpdate?.(t)}function u(e,t,n){return`${e.toLowerCase()}:${t.toLowerCase()}:${n.toLowerCase()}`}function d(n,r,i){if(i){let e=o.get(i);if(e)return ej(n,r,e)}return ej(n,r,e.escrowContract,t)}async function f(t,i,f){let p=t.request.methodDetails,m=p?.chainId??0,h=await r({chainId:m}),g=d(t,m),_=t.request.recipient,v=t.request.currency,y=BigInt(t.request.amount),b=t.request.suggestedDeposit,x=b?BigInt(b):void 0,S=(()=>{if(f?.depositRaw)return BigInt(f.depositRaw);if(e.deposit!==void 0)return P(e.deposit,n);if(x!==void 0&&a!==void 0)return x<a?x:a;if(a!==void 0)return a;if(x!==void 0)return x;throw Error("No deposit amount available. Set `deposit`, `maxDeposit`, or ensure the server challenge includes `suggestedDeposit`.")})(),C=e.voucherSigner??i,w=u(_,v,g),T=s.get(w);if(!T){let e=f?.channelId??p?.channelId;if(e){let t=await ij(h,g,e,m);if(t){let e=f?.cumulativeAmountRaw?BigInt(f.cumulativeAmountRaw):f?.cumulativeAmount?P(f.cumulativeAmount,n):void 0;e!==void 0&&(t.cumulativeAmount=e),s.set(w,t),c.set(t.channelId,w),o.set(t.channelId,g),T=t,l(T)}else if(f?.channelId)throw Error(`Channel ${f.channelId} cannot be reused (closed or not found on-chain).`)}}T?.opened&&T.authorizedSigner.toLowerCase()!==MA(C).toLowerCase()&&(T=void 0);let ee;if(T?.opened)T.cumulativeAmount+=y,ee=await nj(h,i,T.channelId,T.cumulativeAmount,g,m,C),l(T);else{let e=await rj(h,i,{voucherSigner:C,escrowContract:g,payee:_,currency:v,deposit:S,initialAmount:y,chainId:m,feePayer:p?.feePayer});s.set(w,e.entry),c.set(e.entry.channelId,w),o.set(e.entry.channelId,g),ee=e.payload,l(e.entry)}return tj(t,ee,m,i)}async function p(t,i,a){let u=t.request.methodDetails?.chainId??0,f=await r({chainId:u}),p=a.action,{channelId:m,transaction:h}=a,g=e.voucherSigner??i,_=m,v=a.cumulativeAmountRaw?BigInt(a.cumulativeAmountRaw):a.cumulativeAmount?P(a.cumulativeAmount,n):void 0,y=a.additionalDepositRaw?BigInt(a.additionalDepositRaw):a.additionalDeposit?P(a.additionalDeposit,n):void 0,b=d(t,u,_);o.set(_,b);let x;switch(p){case`open`:{if(!h)throw Error(`transaction required for open action`);if(v===void 0)throw Error(`cumulativeAmount required for open action`);let e=await VA(f,i,{channelId:_,cumulativeAmount:v},b,u,g);x={action:`open`,type:`transaction`,channelId:_,transaction:h,authorizedSigner:MA(g),cumulativeAmount:v.toString(),signature:e};break}case`topUp`:if(!h)throw Error(`transaction required for topUp action`);if(y===void 0)throw Error(`additionalDeposit required for topUp action`);x={action:`topUp`,type:`transaction`,channelId:_,transaction:h,additionalDeposit:y.toString()};break;case`voucher`:{if(v===void 0)throw Error(`cumulativeAmount required for voucher action`);x=await nj(f,i,_,v,b,u,g);let e=c.get(_);if(e){let t=s.get(e);t&&(t.cumulativeAmount=t.cumulativeAmount>v?t.cumulativeAmount:v,l(t))}break}case`close`:{if(v===void 0)throw Error(`cumulativeAmount required for close action`);let e=await VA(f,i,{channelId:_,cumulativeAmount:v},b,u,g);x={action:`close`,channelId:_,cumulativeAmount:v.toString(),signature:e};let t=c.get(_);if(t){let e=s.get(t);e&&(e.opened=!1,e.cumulativeAmount=e.cumulativeAmount>v?e.cumulativeAmount:v,l(e))}break}}return tj(t,x,u,i)}return jT(KT,{canHandleChallenge({challenge:e}){let t=Cx(e.request.methodDetails,Dx.sessionProtocol);return t===void 0||t===Ox.v1},context:sj,async createCredential({challenge:t,context:n}){let o=t.request.methodDetails?.chainId??0,s=await r({chainId:o}),c=i(s,n);if(!n?.action&&(e.deposit!==void 0||a!==void 0))return f(t,c,n);if(n?.action)return p(t,c,n);throw Error("No `action` in context and no `deposit` or `maxDeposit` configured. Either provide context with action/channelId/cumulativeAmount, or configure `deposit`/`maxDeposit` for auto-management.")}})}var sj,cj=I((()=>{kx(),MT(),Wk(),Xk(),Gx(),NA(),JD(),JT(),KA(),aj(),sj=Y.object({account:Y.optional(Y.custom()),action:Y.optional(Y.enum([`open`,`topUp`,`voucher`,`close`])),channelId:Y.optional(Y.string()),cumulativeAmount:Y.optional(Fx()),cumulativeAmountRaw:Y.optional(Y.string()),transaction:Y.optional(Y.string()),additionalDeposit:Y.optional(Fx()),additionalDepositRaw:Y.optional(Y.string()),depositRaw:Y.optional(Y.string())})}));function lj(e){let t=e.allowCustomEscrow??!1,n=e.fetch??globalThis.fetch,r=e.webSocket??globalThis.WebSocket,i=e.maxDeposit===void 0?null:P(e.maxDeposit,e.decimals??6),a=null,o=null,s=null,c=0n,l=0n,u=null,d=null,f=null,p=null,m=null,h=null,g=null,_=0n,v=0n,y=oj({account:e.account,allowCustomEscrow:t,voucherSigner:e.voucherSigner,getClient:e.client?()=>e.client:e.getClient,escrowContract:e.escrowContract,decimals:e.decimals,maxDeposit:e.maxDeposit,onChannelUpdate(e){e.channelId!==a?.channelId&&(c=0n,l=0n),a=e}}),b=mw({fetch:n,methods:[y],onChallenge:async(e,t)=>{o=e},orderChallenges:e.orderChallenges});function x(e){if(!e||e.channelId!==a?.channelId)return;S(e);let t=BigInt(e.acceptedCumulative),n=BigInt(e.spent);c=c>t?c:t,l=l>n?l:n}function S(e){if(!a||e.channelId!==a.channelId)return;let t=BigInt(e.acceptedCumulative),n=BigInt(e.spent);if(n>t)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(t>a.cumulativeAmount)throw Error(`receipt accepted cumulative exceeds local voucher state`);if(n>a.cumulativeAmount)throw Error(`receipt spent exceeds local voucher state`);k(t),k(n)}function C(e=()=>!0){if(g)throw Error(`receipt wait already in progress`);return new Promise((t,n)=>{g={predicate:e,resolve:t,reject:n}})}function w(){if(p)return Promise.resolve(p);if(m)throw Error(`close-ready wait already in progress`);return new Promise((e,t)=>{m={resolve:e,reject:t}})}function T(e){if(!g||!g.predicate(e))return;let t=g;g=null,t.resolve(e)}function ee(e){if(p=e,!m)return;let t=m;m=null,t.resolve(e)}function E(e){if(!g)return;let t=g;g=null,t.reject(e)}function D(e){if(!m)return;let t=m;m=null,t.reject(e)}function O(e,t){if(p&&p.challengeId===e.id&&p.channelId===t)return p.spent;let n=a?.channelId===t?a.cumulativeAmount:0n;if(v>0n){let e=_*v,t=l>e?l:e;return(t>n?n:t).toString()}return(l>c?l:c).toString()}function k(e){if(i!==null&&!(e<=i))throw Error(`requested voucher amount ${e} exceeds local maxDeposit ${i}`)}function A(e){let t=e.headers.get(J.paymentReceipt),n=t?oE(t):null;return x(n),Object.assign(e,{receipt:n,challenge:o,channelId:a?.channelId??null,cumulative:a?.cumulativeAmount??0n})}async function j(e,t){return s=e,A(await b(e,t))}function te(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)},s=(e,a)=>{if(e===`close`){if(n)return;n=!0,i=dj.CLOSED,r=null}if(e===`open`&&(i=dj.OPEN),e===`message`&&r){r.push(a);return}let o=`on${e}`,s=c[o];typeof s==`function`&&s(a);let l=t.get(e);if(l)for(let e of Array.from(l))typeof e.value==`function`?e.value(a):e.value.handleEvent(a),e.once&&l.delete(e)},c={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,_onmessage:null,get onmessage(){return c._onmessage},set onmessage(e){if(c._onmessage=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:c}}return{get channelId(){return a?.channelId},get cumulative(){return a?.cumulativeAmount??0n},get opened(){return a?.opened??!1},async open(e){if(a?.opened)return;if(!o)throw Error(`No challenge available. Make a request first to receive a 402 challenge, or pass a challenge via .fetch()/.sse().`);let t=e?.deposit,r=await y.createCredential({challenge:o,context:{...t!==void 0&&{depositRaw:t.toString()}}});if(!s)throw Error(`No URL available — call fetch() or sse() before open().`);let i=await n(s,{method:`POST`,headers:{[J.authorization]:r}});if(!i.ok){let e=await i.text().catch(()=>``),t=i.headers.get(J.wwwAuthenticate)??``;throw Error(`Open request failed with status ${i.status}${e?`: ${e}`:``}${t?` [${J.wwwAuthenticate}: ${t}]`:``}`)}},fetch:j,async sse(e,t){let{onReceipt:r,signal:i,...s}=t??{},c=await j(e,{...s,headers:{...gw(s.headers),Accept:`text/event-stream`},...i?{signal:i}:{}}),l=o;if(!c.body)throw Error(`Response has no body.`);let u=c.body.getReader(),d=new TextDecoder;async function*f(){let t=``;try{for(;!i?.aborted;){let{done:i,value:o}=await u.read();if(i)break;t+=d.decode(o,{stream:!0});let s=t.split(`
232
+ `)}function $D(e,t,n){if(_O.has(e)&&typeof t==`string`)return`${t} ${Z.dim(`(${cO(BigInt(t),n.tokenSymbol,n.tokenDecimals)})`)}`;if(e===`chainId`&&typeof t==`number`){let e=fO({id:t,name:``});return e?`${t} ${Z.dim(`(${e})`)}`:String(t)}return typeof t==`string`&&/^0x[0-9a-fA-F]{40}$/.test(t)?n.explorerUrl?nO(`${n.explorerUrl}/address/${t}`,t):t:typeof t==`string`&&/^https?:\/\//.test(t)?Z.link(t,t):String(t)}function eO(e){try{let t=e.replace(/^0x0*/,``);if(!t)return;let n=Uint8Array.from(t.match(/.{1,2}/g).map(e=>Number.parseInt(e,16))),r=new TextDecoder().decode(n);return/^[\x20-\x7e]+$/.test(r)?r:void 0}catch{return}}function tO(e,t){if(e===`realm`&&typeof t==`string`)try{let e=new URL(t.includes(`://`)?t:`https://${t}`);return Z.link(e.href,t)}catch{}return String(t)}function nO(e,t){return Z.link(e,t)}function rO(e){if(!e)return{};let t=Array.isArray(e)?e:[e],n={};for(let e of t){let t=e.indexOf(`=`);if(t===-1)throw Error(`Invalid method option format: ${e} (expected key=value)`);n[e.slice(0,t)]=e.slice(t+1)}return n}function iO(e=process.env){if(e.CLAUDECODE)return!0;for(let[t,n]of Object.entries(e))if(n&&(t===`CODEX`||t.startsWith(`CODEX_`)))return!0;return!1}function aO(e){return e.startsWith(`tempo:`)}function oO(e){let t=be.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.on(`close`,()=>n(void 0)),t.question(`${Z.bold(`▸ ${e}:`)} `,e=>{t.close(),n(e.trim()||void 0)})})}function sO(e,t=!1){let n=be.createInterface({input:process.stdin,output:process.stderr});return new Promise(r=>{let i=t?`(Y/n)`:`(y/N)`;n.question(`${Z.bold(`▸ ${e}`)} ${Z.dim(i)} `,e=>{n.close();let i=e.trim().toLowerCase();r(i===``?t:i===`y`)})})}function cO(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?Z.dim(Z.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):Z.dim(t);return`${a?`${o}.${a}`:o} ${s}`}function lO(e,t={}){return e??(t.network?vO[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}function uO(e={}){if(e.network)return e.network;if(!e.rpcUrl&&!(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()))return`testnet`}async function dO(e={}){let t=lO(e.rpcUrl,{network:e.network});if(!t)return ge;let{getChainId:n}=await import(`viem/actions`),r=await n(M({transport:ue(t)})),i=Object.values(await import(`viem/tempo/chains`)).filter(e=>typeof e==`object`&&!!e&&`id`in e&&e.id===r),a=i.find(e=>`serializers`in e&&e.serializers)??i[0];if(!a)throw Error(`Unknown chain ID ${r} from RPC ${t}`);return a}function fO(e){return{[ge.id]:`mainnet`,[_e.id]:`testnet`}[e.id]??e.name}function pO(e){return typeof e==`bigint`?e:e.amount}function mO(e){return e.id!==ge.id}async function hO(e,t,n){let{Actions:r}=await import(`viem/tempo`),[i,a]=await Promise.all([r.token.getBalance(e,{account:n,token:t}).then(pO).catch(()=>0n),r.token.getMetadata(e,{token:t}).catch(()=>({symbol:t}))]);return{balance:i,symbol:{"0x20c0000000000000000000000000000000000000":`PathUSD`,"0x20C000000000000000000000b9537d11c60E8b50":`USDC`}[t]??a.symbol,decimals:`decimals`in a&&typeof a.decimals==`number`?a.decimals:6,token:t}}async function gO(e,t){if(t?.chain){let n=M({chain:t.chain,transport:ue(t.rpcUrl)}),r=t.chain.blockExplorers?.default?.url,i=Z.dim(`(${fO(t.chain)})`);return mO(t.chain)?(await Promise.all(SO.map(t=>hO(n,t,e)))).filter(e=>e.balance>0n).map(e=>`${cO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`):(await Promise.all(xO.map(t=>hO(n,t,e)))).map(e=>`${cO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`)}let n=M({chain:ge,transport:ue(lO())}),r=ge.blockExplorers?.default?.url,i=(await Promise.all(xO.map(t=>hO(n,t,e)))).map(e=>cO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token}));if(t?.includeTestnet!==!1){let t=M({chain:_e,transport:ue()}),n=_e.blockExplorers?.default?.url,r=await Promise.all(SO.map(n=>hO(t,n,e)));for(let e of r)e.balance>0n&&i.push(`${cO(e.balance,e.symbol,e.decimals,{explorerUrl:n,token:e.token})} ${Z.dim(`(testnet)`)}`)}return i}var Z,_O,vO,yO,bO,xO,SO,CO=I((()=>{YD(),Z=(()=>{let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes(`--no-color`))&&(!!n.FORCE_COLOR||t.includes(`--color`)||(e.stdout||{}).isTTY&&n.TERM!==`dumb`||!!n.CI),i=(e,t,n,r)=>{let i=``,a=0,o=r;do i+=e.substring(a,o)+n,a=o+t.length,o=e.indexOf(t,a);while(~o);return i+e.substring(a)},a=r?(e,t,n=e)=>r=>{let a=`${r}`,o=a.indexOf(t,e.length);return~o?e+i(a,t,n,o)+t:e+a+t}:()=>String;return{isColorSupported:r,reset:a(`\x1B[0m`,`\x1B[0m`),bold:a(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:a(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:a(`\x1B[3m`,`\x1B[23m`),underline:a(`\x1B[4m`,`\x1B[24m`),inverse:a(`\x1B[7m`,`\x1B[27m`),hidden:a(`\x1B[8m`,`\x1B[28m`),strikethrough:a(`\x1B[9m`,`\x1B[29m`),black:a(`\x1B[30m`,`\x1B[39m`),red:a(`\x1B[31m`,`\x1B[39m`),green:a(`\x1B[32m`,`\x1B[39m`),yellow:a(`\x1B[33m`,`\x1B[39m`),blue:a(`\x1B[34m`,`\x1B[39m`),magenta:a(`\x1B[35m`,`\x1B[39m`),cyan:a(`\x1B[36m`,`\x1B[39m`),white:a(`\x1B[37m`,`\x1B[39m`),gray:a(`\x1B[90m`,`\x1B[39m`),bgBlack:a(`\x1B[40m`,`\x1B[49m`),bgRed:a(`\x1B[41m`,`\x1B[49m`),bgGreen:a(`\x1B[42m`,`\x1B[49m`),bgYellow:a(`\x1B[43m`,`\x1B[49m`),bgBlue:a(`\x1B[44m`,`\x1B[49m`),bgMagenta:a(`\x1B[45m`,`\x1B[49m`),bgCyan:a(`\x1B[46m`,`\x1B[49m`),bgWhite:a(`\x1B[47m`,`\x1B[49m`),blackBright:a(`\x1B[90m`,`\x1B[39m`),redBright:a(`\x1B[91m`,`\x1B[39m`),greenBright:a(`\x1B[92m`,`\x1B[39m`),yellowBright:a(`\x1B[93m`,`\x1B[39m`),blueBright:a(`\x1B[94m`,`\x1B[39m`),magentaBright:a(`\x1B[95m`,`\x1B[39m`),cyanBright:a(`\x1B[96m`,`\x1B[39m`),whiteBright:a(`\x1B[97m`,`\x1B[39m`),bgBlackBright:a(`\x1B[100m`,`\x1B[49m`),bgRedBright:a(`\x1B[101m`,`\x1B[49m`),bgGreenBright:a(`\x1B[102m`,`\x1B[49m`),bgYellowBright:a(`\x1B[103m`,`\x1B[49m`),bgBlueBright:a(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:a(`\x1B[105m`,`\x1B[49m`),bgCyanBright:a(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:a(`\x1B[107m`,`\x1B[49m`),link(e,t,n){return r?`\x1b]8;;${e}\x07${n?t:Z.underline(t)}\x1b]8;;\x07`:t}}})(),_O=new Set([`amount`,`suggestedDeposit`,`minVoucherDelta`]),vO={mainnet:JD[WD.mainnet],testnet:JD[WD.testnet]},yO=`0x20c0000000000000000000000000000000000000`,bO=`0x20C000000000000000000000b9537d11c60E8b50`,xO=[yO,bO],SO=[`0x20c0000000000000000000000000000000000000`,`0x20c0000000000000000000000000000000000001`,`0x20c0000000000000000000000000000000000002`,`0x20c0000000000000000000000000000000000003`]}));function wO(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:IO}function TO(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function EO(e){return new L({code:`KEYCHAIN_UNAVAILABLE`,message:`Linux keyring requires secret-tool. Install libsecret-tools.`,hint:`On Debian/Ubuntu, run: sudo apt install libsecret-tools gnome-keyring dbus-x11`,exitCode:69,cause:e})}function DO(e){if(e&&TO(e,`secret-tool`))throw EO(e)}function OO(e,t){return new Promise(n=>{p.execFile(e,t,{timeout:wO()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function kO(){let t=s.join(process.env.XDG_CONFIG_HOME||s.join(y.homedir(),`.config`),`mppx`,`default`);return{get(){try{return e.readFileSync(t,`utf-8`).trim()||`main`}catch{return`main`}},set(n){e.mkdirSync(s.dirname(t),{recursive:!0}),e.writeFileSync(t,n,`utf-8`)},clear(){try{e.unlinkSync(t)}catch{}}}}function AO(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:kO().get())}function jO(e=`main`){let t=FO;return{async list(){let e=y.platform();if(e===`darwin`){let{stdout:e,error:n}=await OO(`security`,[`dump-keychain`]);if(n)return[];let r=[],i=e.split(`keychain:`);for(let e of i){let n=e.match(/"svce"<blob>="([^"]*)"/),i=e.match(/"acct"<blob>="([^"]*)"/);n?.[1]===t&&i?.[1]&&r.push(i[1])}return r}if(e===`linux`){let{stdout:e,stderr:n,error:r}=await OO(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(DO(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=y.platform();if(n===`darwin`){let{stdout:n,error:r}=await OO(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await OO(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return DO(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=y.platform();if(r===`darwin`){await OO(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await OO(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=p.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),wO());return r.stdin?.write(n),r.stdin?.end(),new Promise((e,t)=>{r.on(`close`,n=>{clearTimeout(i),n===0?e():t(Error(`secret-tool exited with code ${n}`))}),r.on(`error`,e=>{clearTimeout(i),t(TO(e,`secret-tool`)?EO(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=y.platform();if(n===`darwin`){await OO(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await OO(`secret-tool`,[`clear`,`service`,t,`account`,e]);DO(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function MO(e){let{privateKeyToAccount:t}=await import(`viem/accounts`),n=process.env.MPPX_PRIVATE_KEY?.trim();if(n)return{account:t(n),source:`environment`};let r=AO(e),i=await jO(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function NO(e){let t=AO(e);if(!process.env.MPPX_PRIVATE_KEY?.trim()&&aO(t))throw new L({code:`UNSUPPORTED_ACCOUNT`,message:`Persistent sessions require an mppx account or MPPX_PRIVATE_KEY.`,exitCode:2});return MO(e).catch(e=>{throw new L({code:`ACCOUNT_NOT_FOUND`,message:e instanceof Error?e.message:`No account found.`,exitCode:69,...e instanceof Error&&{cause:e}})})}async function PO(e){return(await MO(e)).account}var FO,IO,LO=I((()=>{CO(),FO=`mppx`,IO=1e4}));const RO=Symbol(`mppx.x402.asset`);function zO(e){return{[RO]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function BO(e,t){let n=e(t.chainId);return zO({address:n.address,decimals:n.decimals,network:XO(t.chainId),transfer:QO(t.transfer,n)})}const VO={USDC:zO({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},HO={USDC:zO({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},UO={USDC:zO({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:zO({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},WO={USDC:zO({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function GO(e){return typeof e!=`object`||!e?!1:e[RO]===!0}function KO(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function qO(e){return typeof e==`string`}function JO(e,t){if(GO(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(KO(e)){let n=e.addresses[ZO(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function YO(e,t,n){let r=JO(e,n);return r?ce(r.address)===ce(t):!1}function XO(e){return`eip155:${e}`}function ZO(e){return Number(e.slice(7))}function QO(e,t){if(e.type!==`eip3009`)return e;if(e.name)return{...e,name:e.name};if(!t.name)throw Error(`EIP-3009 token assets require a token name.`);return{...e,name:t.name}}var $O=Ke({base:()=>VO,baseSepolia:()=>HO,celo:()=>UO,celoSepolia:()=>WO,define:()=>zO,fromToken:()=>BO,isAsset:()=>GO,isRawAddress:()=>qO,isToken:()=>KO,matches:()=>YO,resolve:()=>JO,toChainId:()=>ZO,toNetwork:()=>XO}),ek=Ke({base:()=>tk,baseSepolia:()=>nk,celo:()=>rk,celoSepolia:()=>ik});const tk=8453,nk=84532,rk=42220,ik=11142220;Nx();function ak(e){let t=[Mx(e.accepted),Mx(e.resource),Mx(e.extensions)].join(`|`);return te.sha256(k.fromString(t),{as:`Hex`})}YC(),SC();async function ok(e){let t=e.context?.account??e.config.account;if(!t.signTypedData)throw Error(`x402 exact requires a typed-data signer.`);let n=e.challenge.request,r=$S(n);if(uk(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?fk(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} signing is not implemented yet.`);let o=r.extra?.name,s=r.extra?.version;if(typeof o!=`string`||typeof s!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let c=Math.floor(Date.now()/1e3),l={from:ce(t.address),nonce:i?.mppx?ak({accepted:r,extensions:i,resource:n.resource}):mk(),to:ce(r.payTo),validAfter:(c-600).toString(),validBefore:(c+r.maxTimeoutSeconds).toString(),value:r.amount},u=await t.signTypedData({domain:{chainId:lk(r.network),name:o,verifyingContract:ce(r.asset),version:s},message:{...l,value:BigInt(l.value),validAfter:BigInt(l.validAfter),validBefore:BigInt(l.validBefore)},primaryType:`TransferWithAuthorization`,types:ck});return qC({accepted:r,...i?{extensions:i}:{},payload:{authorization:l,signature:u},...n.resource?{resource:n.resource}:{},x402Version:2})}function sk(e){let t=e.challenge.request,n;try{n=$S(t),uk(e.config,n)}catch{return!1}if(!t.resource||(n.extra?.assetTransferMethod??`eip3009`)!==`eip3009`)return!1;let r=n.extra?.name,i=n.extra?.version;return typeof r==`string`&&typeof i==`string`}const ck={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function lk(e){return Number(e.slice(nC.length))}function uk(e,t){let n=lk(t.network);if(e.networks&&!e.networks.includes(n))throw Error(`x402 exact chain ID is not allowed: ${n}.`);let r=e.currencies??e.assets;if(r?.some(e=>qO(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=ce(t.asset);if(!r.some(n=>YO(n,e,t.network)))throw Error(`x402 exact currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`x402 exact amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=dk(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>P(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function dk(e,t){let n=e.currencies??e.assets,r=ce(t.asset),i=n?.find(e=>YO(e,r,t.network)),a=i?JO(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function fk(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:pk()}}}:e}function pk(){return hk().slice(2)}function mk(){return hk()}function hk(){let e=globalThis.crypto;if(!e?.getRandomValues)throw Error(`x402 exact requires crypto randomness.`);let t=e.getRandomValues(new Uint8Array(32));return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}Gx();const gk=[`authorization`],_k=Y.string().check(Y.regex(/^\d+$/,`Invalid atomic amount`));Y.object({name:Y.string().check(Y.minLength(1)),version:Y.string().check(Y.minLength(1))});const vk=Y.object({chainId:Y.number(),credentialTypes:Y.optional(Y.array(Y.enum(gk)).check(Y.minLength(1))),decimals:Y.optional(Y.number()),permit2Address:Y.optional(Bx()),splits:Y.optional(Y.array(Y.object({amount:_k,recipient:Bx()})))});Y.object({amount:_k,currency:Bx(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),methodDetails:vk,recipient:Bx()});const yk=Y.object({amount:Fx(),chainId:Y.number(),currency:Bx(),credentialTypes:Y.optional(Y.array(Y.enum(gk)).check(Y.minLength(1))),decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),permit2Address:Y.optional(Bx()),recipient:Bx(),splits:Y.optional(Y.array(Y.object({amount:_k,recipient:Bx()})))}),bk=Y.object({from:Bx(),nonce:Vx(),signature:Ux(),to:Bx(),type:Y.literal(`authorization`),validAfter:_k,validBefore:_k,value:_k}),xk={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function Sk(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function Ck(e){return te.keccak256(k.fromString(`${e.id}${e.realm}`),{as:`Hex`})}function wk(e){return`eip155:${e}`}function Tk(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}NT(),Gx();const Ek=jT({name:`evm`,intent:`charge`,schema:{credential:{payload:bk},request:Y.pipe(yk,Y.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...c})=>({...c,amount:P(e,i).toString(),currency:ce(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:ce(a)}:{},...s?{splits:s}:{}},recipient:ce(o)})))}});YS(),NT(),xS(),Gx();function Dk(e){return MT(Ek,{canHandleChallenge({challenge:t}){return!Ok(t)||sk({challenge:t,config:e})},context:Y.object({account:Y.optional(Y.custom())}),async createCredential({challenge:t,context:n}){if(Ok(t))return ok({challenge:t,config:e,context:n});let r=n?.account??e.account;if(!r.signTypedData)throw Error(`EVM authorization requires a typed-data signer.`);let i=t.request;if(kk(e,i),!i.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(i.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`);let a=Ak(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return KS(GS({challenge:t,payload:{from:ce(r.address),nonce:Ck(t),signature:await r.signTypedData({domain:Sk({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:ce(r.address),nonce:Ck(t),to:ce(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:xk}),to:ce(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:Tk({address:ce(r.address),chainId:i.methodDetails.chainId})}))}})}function Ok(e){return yS(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function kk(e,t){let n=t.methodDetails.chainId,r=wk(n);if(e.networks&&!e.networks.includes(n))throw Error(`EVM chain ID is not allowed: ${n}.`);let i=e.currencies??e.assets;if(i?.some(e=>qO(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=ce(t.currency);if(!i.some(t=>YO(t,e,r)))throw Error(`EVM currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`EVM charge amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=jk(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>P(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function Ak(e,t){let n=e.currencies??e.assets,r=ce(t.currency),i=wk(t.methodDetails.chainId),a=n?.find(e=>YO(e,r,i)),o=a?JO(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;throw Error(`EVM authorization requires token name and version.`)}function jk(e,t){let n=e.currencies??e.assets,r=ce(t.currency),i=wk(t.methodDetails.chainId),a=n?.find(e=>YO(e,r,i)),o=a?JO(a,i):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function Mk(e){return[Mk.charge(e)]}(function(e){e.charge=Dk,e.assets=$O,e.chains=ek})(Mk||={});function Nk(e){return e}var Pk=I((()=>{}));xS(),LO(),Pk();function Fk(){return Nk({method:`evm`,supports:e=>e.method===`evm`&&!yS(e),async setup({challenge:e}){let t=e.request,n=t.methodDetails,r=n?.chainId,i=r?Ik(r):void 0,a=t.currency,o=await PO(),s=[...Object.values(VO),...Object.values(HO),...Object.values(UO),...Object.values(WO)],c=a??``;if(i&&a)try{let e=M({chain:i,transport:ue()}),t=await xe(e,{address:a,abi:oe,functionName:`symbol`});t&&(c=t)}catch{}return{tokenSymbol:c,tokenDecimals:n?.decimals??6,explorerUrl:i?.blockExplorers?.default?.url,methods:[...Mk({account:o,currencies:s})]}}})}function Ik(e){return Object.values(Pe).find(t=>t.id===e)}Gx();const Lk=Y.object({customer:Y.optional(Y.string().check(Y.minLength(1))),hooks:Y.optional(Y.object({inputs:Y.object({tax:Y.object({calculation:Y.string().check(Y.minLength(1))})})})),metadata:Y.optional(Y.record(Y.string(),Y.string())),receipt_email:Y.optional(Y.string().check(Y.minLength(1)))});NT(),Gx();const Rk=jT({name:`stripe`,intent:`charge`,schema:{credential:{payload:Y.object({externalId:Y.optional(Y.string()),spt:Y.string()})},request:Y.pipe(Y.object({amount:Fx(),currency:Y.string(),decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),metadata:Y.optional(Y.record(Y.string(),Y.string())),networkId:Y.string(),paymentIntentOptions:Y.optional(Lk),paymentMethodTypes:Y.array(Y.string()).check(Y.minLength(1)),recipient:Y.optional(Y.string())}),Y.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:P(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});YS(),NT(),Gx();function zk(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return MT(Rk,{context:Y.object({paymentMethod:Y.optional(Y.string())}),async createCredential({challenge:e,context:a}){let o=a?.paymentMethod??i;if(!o)throw Error(`paymentMethod is required (pass via context or parameters)`);let s=e.request.amount,c=e.request.currency,l=typeof e.request.externalId==`string`?e.request.externalId:void 0,u=e.request.methodDetails?.networkId;if(!u)throw Error(`networkId is required in challenge.methodDetails`);let d=e.request.methodDetails?.metadata;if(d?.externalId)throw Error(`methodDetails.metadata.externalId is reserved; use credential externalId instead`);let f=e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,p=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:f,metadata:d,networkId:u,paymentMethod:o}),m=l??r;return KS({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function Bk(e){return[zk(e)]}(function(e){e.charge=zk})(Bk||={}),Sx(),CO(),Pk();function Vk(){return Nk({method:`stripe`,supports(e){return e.method===`stripe`&&e.intent===`charge`},async setup({challenge:e,methodOpts:t}){let n=e.request,r=n.currency,i=Uk(f.object({paymentMethod:f.string(),secretKey:f.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new L({code:`MISSING_ENV`,message:`MPPX_STRIPE_SECRET_KEY environment variable is required for Stripe payments.`,exitCode:2});return{tokenSymbol:r?.toUpperCase()??``,tokenDecimals:n.decimals??2,methods:[Bk.charge({paymentMethod:i.paymentMethod,createToken:async({paymentMethod:e,amount:t,currency:n,networkId:r,expiresAt:i,metadata:o})=>{let s=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()}),c=Hk(a),l=process.env.MPPX_STRIPE_SPT_URL?process.env.MPPX_STRIPE_SPT_URL:c?`https://api.stripe.com/v1/test_helpers/shared_payment/granted_tokens`:`https://api.stripe.com/v1/shared_payment/issued_tokens`;if(r){let e=c?`seller_details[network_id]`:`seller_details[network_business_profile]`;s.set(e,r)}if(o)for(let[e,t]of Object.entries(o))s.set(`metadata[${e}]`,t);let u={Authorization:`Basic ${btoa(`${a}:`)}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":`2026-07-29.preview`},d=await globalThis.fetch(l,{method:`POST`,headers:u,body:s});if(!d.ok){let a=await d.json();if(c&&(o||r)&&a.error.message.includes(`Received unknown parameter`)){let r=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()});if(d=await globalThis.fetch(l,{method:`POST`,headers:u,body:r}),!d.ok){let e=await d.json();throw new L({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${e.error.message}`,exitCode:77})}}else throw new L({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${a.error.message}`,exitCode:77})}let{id:f}=await d.json();return f}})]}},formatReceiptField(e,t){if(e===`reference`&&typeof t==`string`&&t.startsWith(`pi_`)){let e=process.env.MPPX_STRIPE_SECRET_KEY,n=`https://dashboard.stripe.com${e!==void 0&&Hk(e)?`/test`:``}/payments/${t}`;return Z.link(n,t,!0)}}})}function Hk(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function Uk(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function Wk(e={}){let{account:t}=e;return(e,{account:n}={})=>{let r=n??t;if(!r){if(!e.account)throw Error("No `account` provided. Pass `account` to parameters or context.");return e.account}return me(r)}}var Gk=I((()=>{}));function Kk(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}var qk=I((()=>{}));function Jk(e,t={}){return ue(e.url,{fetchFn:e.fetch,fetchOptions:{headers:Kk(e)},...t})}function Yk(e){let{chain:t,getClient:n,remoteFeePayer:r,rpcUrl:i}=e;return n?!t?.serializers&&!r?n:async e=>{let i=await n(e),a=i;if(r&&i.transport.key!==`feePayer`){let e=i.request.bind(i),t=Ne(ie({request:t=>e(t)},{retryCount:0}),Jk(r,{retryCount:i.transport.retryCount}))({account:i.account,chain:i.chain,pollingInterval:i.pollingInterval,retryCount:0}),n=re({...t.config,retryCount:0},t.value);a=Object.assign({},i,{request:n.request,transport:{...n.config,...n.value}})}return!t?.serializers||a.chain?.serializers?.transaction?a:Object.assign({},a,{chain:{...t,...a.chain,formatters:a.chain?.formatters??t.formatters,prepareTransactionRequest:a.chain?.prepareTransactionRequest??t.prepareTransactionRequest,serializers:a.chain?.serializers?.transaction?a.chain.serializers:t.serializers}})}:({chainId:e})=>{if(!i)throw Error("No `rpcUrl` provided.");let n=e||Number(Object.keys(i)[0]),a=i[n];if(!a)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let o=r?Ne(ue(a),Jk(r)):ue(a);return M({chain:Xk[n]??{...t,id:n},transport:o})}}var Xk,Zk=I((()=>{qk(),Xk={[ge.id]:ge,[_e.id]:_e}}));function Qk(e){let t=te.keccak256(k.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,10))}function $k(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(A.toBytes(tA),0),i[4]=nA,i.set(Qk(t),5),n&&i.set(Qk(n),15),i.set(eA(r),25),A.fromBytes(i)}function eA(e){let t=te.keccak256(k.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,7))}var tA,nA,rA=I((()=>{tA=A.slice(te.keccak256(k.fromString(`mpp`),{as:`Hex`}),0,4),nA=1}));function iA(e,t){return ze.resolve(e).toLowerCase()===ze.resolve(t).toLowerCase()}var aA=I((()=>{}));async function oA(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t,s=a.filter(e=>!iA(e,i)),c=await Promise.allSettled([xe(e,ke.token.getBalance.call(e,{account:n,token:i})),...s.map(t=>xe(e,ke.token.getBalance.call(e,{account:n,token:t})))]),l=c[0];if(!(l.status===`fulfilled`&&l.value>=r)){for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let a=n.value;if(a<=0n)continue;let l=s[t];try{let t=await ke.dex.getBuyQuote(e,{tokenIn:l,tokenOut:i,amountOut:r});if(a>=t){let n=t+t*BigInt(Math.round(o*100))/cA;return[ke.token.approve.call(e,{amount:n,spender:Ae.stablecoinDex,token:l}),ke.dex.buy.call({tokenIn:l,tokenOut:i,amountOut:r,maxAmountIn:n})]}}catch{}}throw new uA({currency:i})}}function sA(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...t.filter(t=>!e.tokenIn.some(e=>iA(e,t)))]:t,slippage:e.slippage??1}:!1}var cA,lA,uA,dA=I((()=>{aA(),YD(),cA=10000n,lA=[GD.pathUsd,GD.usdc],uA=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}}}));function fA(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:e.amount,memo:e.memo,recipient:e.recipient}))]}var pA=I((()=>{}));function mA(e,t,n){t&&(n&&!n.some(e=>iA(e,t))||e.some(e=>iA(e,t))||e.push(t))}async function hA(e,t,n){try{return(await ke.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function gA(e){let t=e.chain?.feeToken;if(t)return je.toAddress(t);let n=e.chain?.id;return n?KD[n]:void 0}function _A(e){let t=[];return mA(t,GD.pathUsd),mA(t,KD[e]),t}async function vA(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])mA(o,e,n);if(mA(o,await ke.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),mA(o,gA(i),n),!a)for(let e of r??[])mA(o,e,n);for(let e of o)if(await hA(i,t,e))return e;return o[0]}var yA=I((()=>{aA(),YD()}));function bA(e){return{name:`MPP`,version:`3`,chainId:e}}function xA(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function SA(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:bA(n),types:TA,primaryType:wA,message:xA({account:t,challengeId:r,realm:i})}}function CA(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}var wA,TA,EA=I((()=>{wA=`Proof`,TA={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]}})),DA,OA=I((()=>{DA=Ve({addresses:{4217:`0x20c000000000000000000000f37de3740ADec032`,42431:`0x20c000000000000000000000f37de3740ADec032`},currency:`USD`,decimals:6,name:`MACH`,symbol:`MACH`})}));function kA(e={}){let{clientId:t}=e,n=Yk({chain:ge,getClient:e.getClient,rpcUrl:JD}),r=Wk({account:e.account});return MT(KT,{context:AA,async createCredential({challenge:i,context:a}){let o=i.request.methodDetails?.chainId;if(e.expectedChainId!==void 0&&o!==void 0&&o!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${o}.`);let s=o??e.expectedChainId,c=await n({chainId:s}),l=s??c.chain?.id;if(l===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:u}=i,{amount:d,methodDetails:f}=u,p=f?.supportedModes??[`pull`,`push`],m=r(c,a);if(BigInt(d)===0n)return KS({challenge:i,payload:{signature:await Te(c,{account:m,...SA({account:m.address,chainId:l,challengeId:i.id,realm:i.realm})}),type:`proof`},source:CA({address:m.address,chainId:l})});let h=u.currency;if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase())),n=f?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}let g=f?.memo?f.memo:$k({challengeId:i.id,clientId:t,serverId:i.realm}),_=fA({amount:d,methodDetails:{...f,memo:g},recipient:u.recipient}).map(e=>ke.token.transfer.call(c,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:h})),v=sA(a?.autoSwap??e.autoSwap,lA),y=await e.resolveAccount?.({account:m,chainId:l,operation:{kind:`executeCalls`,...v?{}:{calls:_}}})??m,b=(()=>{let t=a?.mode??e.mode;if(t){if(!p.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=y.type===`json-rpc`?`push`:`pull`;return p.includes(n)?n:p[0]})(),x=[...(v?await oA(c,{account:y.address,amountOut:BigInt(d),tokenOut:h,tokenIn:v.tokenIn,slippage:v.slippage}):void 0)??[],..._],S=DA.addresses[l],C=_A(l),w=S&&fe(h,S)?await vA({account:y.address,allowedTokens:C,candidateTokens:C,client:c,prioritizeCandidates:!0}):void 0,T=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!i.expires)return e;let t=Math.floor(new Date(i.expires).getTime()/1e3);return Math.min(e,t)})();if(b===`push`){let{receipts:e}=y.type===`local`?{receipts:[await Ce(c,{account:y,calls:x,...w?{feeToken:w}:{},nonceKey:`expiring`,validBefore:T})]}:await Se(c,{account:y,...w?{capabilities:{feeToken:w}}:{},calls:x,experimental_fallback:x.length===1,forceAtomic:x.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return KS({challenge:i,payload:{hash:t,type:`hash`},source:CA({address:y.address,chainId:l})})}let ee=await F(c,{account:y,calls:x,...w?{feeToken:w}:{},nonceKey:`expiring`,validBefore:T});if(ee.gas=(ee.gas??0n)+5000n,f?.feePayer){let e=ee;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return KS({challenge:i,payload:{signature:await we(c,ee),type:`transaction`},source:CA({address:y.address,chainId:l})})}})}var AA,jA=I((()=>{YS(),NT(),Gk(),Zk(),Gx(),rA(),dA(),pA(),YD(),yA(),EA(),YT(),OA(),AA=Y.object({account:Y.optional(Y.custom()),autoSwap:Y.optional(Y.custom()),mode:Y.optional(Y.enum(IT))})}));function MA(e){return`accessKeyAddress`in e}function NA(e){return MA(e)?e.accessKeyAddress:e.address}var PA=I((()=>{}));function FA(e,t){return{name:UA,version:WA,chainId:t,verifyingContract:e}}function IA(e){return{channelId:e.channelId,cumulativeAmount:e.cumulativeAmount}}function LA(e,t,n){return le({domain:FA(e,t),types:GA,primaryType:`Voucher`,message:IA(n)})}async function RA(e,t,n,r,i){return Te(e,{account:t,domain:FA(r,i),types:GA,primaryType:`Voucher`,message:IA(n)})}function zA(e){let t=Re.from(e);if(t.type===`keychain`){if(t.inner.type!==`secp256k1`)throw Error(`Session vouchers only unwrap secp256k1 keychain signatures; pass a direct voucherSigner for other key types.`);return j.toHex(t.inner.signature)}return Re.serialize(t)}function BA(e){return e.type===`keychain`?!1:e.type===`secp256k1`||KA}function VA(e){if(!BA(e))throw Error(`Session vouchers only support secp256k1 signatures until TIP-1020 voucher verification is enabled.`)}async function HA(e,t,n,r,i,a){let o=a??t,s=NA(o),c=LA(r,i,n),l=zA(MA(o)?await o.sign({hash:c,raw:!0}):await RA(e,o,n,r,i)),u=Re.from(l);if(VA(u),!Re.verify(u,{address:s,payload:c}))throw Error(`voucher signature does not match voucher signer`);return l}var UA,WA,GA,KA,qA=I((()=>{PA(),UA=`Tempo Stream Channel`,WA=`1`,GA={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint128`}]},KA=!1}));function JA(e){let t=D.encode(D.from([`address payer`,`address payee`,`address token`,`bytes32 salt`,`address authorizedSigner`,`address escrowContract`,`uint256 chainId`]),[e.payer,e.payee,e.token,e.salt,e.authorizedSigner,e.escrowContract,BigInt(e.chainId)]);return te.keccak256(t)}var YA=I((()=>{})),XA,ZA=I((()=>{XA=[{type:`function`,name:`CLOSE_GRACE_PERIOD`,inputs:[],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`VOUCHER_TYPEHASH`,inputs:[],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`channels`,inputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:`finalized`,type:`bool`,internalType:`bool`},{name:`closeRequestedAt`,type:`uint64`,internalType:`uint64`},{name:`payer`,type:`address`,internalType:`address`},{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`authorizedSigner`,type:`address`,internalType:`address`},{name:`deposit`,type:`uint128`,internalType:`uint128`},{name:`settled`,type:`uint128`,internalType:`uint128`}],stateMutability:`view`},{type:`function`,name:`close`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`},{name:`cumulativeAmount`,type:`uint128`,internalType:`uint128`},{name:`signature`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`computeChannelId`,inputs:[{name:`payer`,type:`address`,internalType:`address`},{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`salt`,type:`bytes32`,internalType:`bytes32`},{name:`authorizedSigner`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`domainSeparator`,inputs:[],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`eip712Domain`,inputs:[],outputs:[{name:`fields`,type:`bytes1`,internalType:`bytes1`},{name:`name`,type:`string`,internalType:`string`},{name:`version`,type:`string`,internalType:`string`},{name:`chainId`,type:`uint256`,internalType:`uint256`},{name:`verifyingContract`,type:`address`,internalType:`address`},{name:`salt`,type:`bytes32`,internalType:`bytes32`},{name:`extensions`,type:`uint256[]`,internalType:`uint256[]`}],stateMutability:`view`},{type:`function`,name:`getChannel`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`tuple`,internalType:`struct TempoStreamChannel.Channel`,components:[{name:`finalized`,type:`bool`,internalType:`bool`},{name:`closeRequestedAt`,type:`uint64`,internalType:`uint64`},{name:`payer`,type:`address`,internalType:`address`},{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`authorizedSigner`,type:`address`,internalType:`address`},{name:`deposit`,type:`uint128`,internalType:`uint128`},{name:`settled`,type:`uint128`,internalType:`uint128`}]}],stateMutability:`view`},{type:`function`,name:`getChannelsBatch`,inputs:[{name:`channelIds`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[{name:`channelStates`,type:`tuple[]`,internalType:`struct TempoStreamChannel.Channel[]`,components:[{name:`finalized`,type:`bool`,internalType:`bool`},{name:`closeRequestedAt`,type:`uint64`,internalType:`uint64`},{name:`payer`,type:`address`,internalType:`address`},{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`authorizedSigner`,type:`address`,internalType:`address`},{name:`deposit`,type:`uint128`,internalType:`uint128`},{name:`settled`,type:`uint128`,internalType:`uint128`}]}],stateMutability:`view`},{type:`function`,name:`getVoucherDigest`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`},{name:`cumulativeAmount`,type:`uint128`,internalType:`uint128`}],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`open`,inputs:[{name:`payee`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`deposit`,type:`uint128`,internalType:`uint128`},{name:`salt`,type:`bytes32`,internalType:`bytes32`},{name:`authorizedSigner`,type:`address`,internalType:`address`}],outputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`}],stateMutability:`nonpayable`},{type:`function`,name:`requestClose`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`settle`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`},{name:`cumulativeAmount`,type:`uint128`,internalType:`uint128`},{name:`signature`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`topUp`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`},{name:`additionalDeposit`,type:`uint256`,internalType:`uint256`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`withdraw`,inputs:[{name:`channelId`,type:`bytes32`,internalType:`bytes32`}],outputs:[],stateMutability:`nonpayable`},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`settledToPayee`,type:`uint256`,indexed:!1,internalType:`uint256`},{name:`refundedToPayer`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`ChannelExpired`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`}],anonymous:!1},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`token`,type:`address`,indexed:!1,internalType:`address`},{name:`authorizedSigner`,type:`address`,indexed:!1,internalType:`address`},{name:`salt`,type:`bytes32`,indexed:!1,internalType:`bytes32`},{name:`deposit`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`}],anonymous:!1},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`closeGraceEnd`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`cumulativeAmount`,type:`uint256`,indexed:!1,internalType:`uint256`},{name:`deltaPaid`,type:`uint256`,indexed:!1,internalType:`uint256`},{name:`newSettled`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`payer`,type:`address`,indexed:!0,internalType:`address`},{name:`payee`,type:`address`,indexed:!0,internalType:`address`},{name:`additionalDeposit`,type:`uint256`,indexed:!1,internalType:`uint256`},{name:`newDeposit`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`error`,name:`AmountExceedsDeposit`,inputs:[]},{type:`error`,name:`AmountNotIncreasing`,inputs:[]},{type:`error`,name:`ChannelAlreadyExists`,inputs:[]},{type:`error`,name:`ChannelFinalized`,inputs:[]},{type:`error`,name:`ChannelNotFound`,inputs:[]},{type:`error`,name:`CloseNotReady`,inputs:[]},{type:`error`,name:`DepositOverflow`,inputs:[]},{type:`error`,name:`InvalidPayee`,inputs:[]},{type:`error`,name:`InvalidSignature`,inputs:[]},{type:`error`,name:`NotPayee`,inputs:[]},{type:`error`,name:`NotPayer`,inputs:[]},{type:`error`,name:`TransferFailed`,inputs:[]}]}));async function QA(e,t,n){return xe(e,{address:t,abi:XA,functionName:`getChannel`,args:[n]})}var $A=I((()=>{ZA(),N({abi:XA,name:`open`}),N({abi:XA,name:`topUp`})}));function ej(e,t){return t??e}function tj(e,t,n,r=!1){let i=e.request.methodDetails?.escrowContract,a=n??qD[t];if(!a&&!(r&&i))throw Error("No trusted `escrowContract` available. Provide it in client parameters or use a supported chain.");if(i&&a&&i.toLowerCase()!==a.toLowerCase()&&(!r||n!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&(!a||i.toLowerCase()!==a.toLowerCase())?i:a}function nj(e,t,n,r){return KS({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}async function rj(e,t,n,r,i,a,o){let s=ej(t,o),c=await HA(e,t,{channelId:n,cumulativeAmount:r},i,a,s);return{action:`voucher`,channelId:n,cumulativeAmount:r.toString(),signature:c}}async function ij(e,t,n){let{escrowContract:r,payee:i,currency:a,deposit:o,initialAmount:s,chainId:c,feePayer:l}=n,u=ej(t,n.voucherSigner),d=NA(u),f=A.random(32),p=JA({authorizedSigner:d,chainId:c,escrowContract:r,payee:i,payer:t.address,salt:f,token:a}),m=ae({abi:De.tip20,functionName:`approve`,args:[r,o]}),h=ae({abi:XA,functionName:`open`,args:[i,a,o,f,d]}),g=Math.floor(Date.now()/1e3)+25,_=await F(e,{account:t,calls:[{to:a,data:m},{to:r,data:h}],feeToken:a,nonceKey:`expiring`,validBefore:g});_.gas=(_.gas??0n)+5000n,l&&(_.feePayer=!0);let v=await we(e,_),y=await HA(e,t,{channelId:p,cumulativeAmount:s},r,c,u);return{entry:{authorizedSigner:d,channelId:p,salt:f,cumulativeAmount:s,escrowContract:r,chainId:c,opened:!0},payload:{action:`open`,type:`transaction`,channelId:p,transaction:v,authorizedSigner:d,cumulativeAmount:s.toString(),signature:y}}}async function aj(e,t,n,r){try{let i=await QA(e,t,n);if(i.deposit>0n&&!i.finalized)return{authorizedSigner:BigInt(i.authorizedSigner)===0n?i.payer:i.authorizedSigner,channelId:n,salt:`0x`,cumulativeAmount:i.settled,escrowContract:t,chainId:r,opened:!0}}catch{}}var oj=I((()=>{YS(),PA(),YD(),$A(),YA(),qA()}));function sj(e={}){let{allowCustomEscrow:t=!1,decimals:n=6}=e,r=Yk({chain:ge,getClient:e.getClient,rpcUrl:JD}),i=Wk({account:e.account}),a=e.maxDeposit===void 0?void 0:P(e.maxDeposit,n),o=new Map,s=new Map,c=new Map;function l(t){e.onChannelUpdate?.(t)}function u(e,t,n){return`${e.toLowerCase()}:${t.toLowerCase()}:${n.toLowerCase()}`}function d(n,r,i){if(i){let e=o.get(i);if(e)return tj(n,r,e)}return tj(n,r,e.escrowContract,t)}async function f(t,i,f){let p=t.request.methodDetails,m=p?.chainId??0,h=await r({chainId:m}),g=d(t,m),_=t.request.recipient,v=t.request.currency,y=BigInt(t.request.amount),b=t.request.suggestedDeposit,x=b?BigInt(b):void 0,S=(()=>{if(f?.depositRaw)return BigInt(f.depositRaw);if(e.deposit!==void 0)return P(e.deposit,n);if(x!==void 0&&a!==void 0)return x<a?x:a;if(a!==void 0)return a;if(x!==void 0)return x;throw Error("No deposit amount available. Set `deposit`, `maxDeposit`, or ensure the server challenge includes `suggestedDeposit`.")})(),C=e.voucherSigner??i,w=u(_,v,g),T=s.get(w);if(!T){let e=f?.channelId??p?.channelId;if(e){let t=await aj(h,g,e,m);if(t){let e=f?.cumulativeAmountRaw?BigInt(f.cumulativeAmountRaw):f?.cumulativeAmount?P(f.cumulativeAmount,n):void 0;e!==void 0&&(t.cumulativeAmount=e),s.set(w,t),c.set(t.channelId,w),o.set(t.channelId,g),T=t,l(T)}else if(f?.channelId)throw Error(`Channel ${f.channelId} cannot be reused (closed or not found on-chain).`)}}T?.opened&&T.authorizedSigner.toLowerCase()!==NA(C).toLowerCase()&&(T=void 0);let ee;if(T?.opened)T.cumulativeAmount+=y,ee=await rj(h,i,T.channelId,T.cumulativeAmount,g,m,C),l(T);else{let e=await ij(h,i,{voucherSigner:C,escrowContract:g,payee:_,currency:v,deposit:S,initialAmount:y,chainId:m,feePayer:p?.feePayer});s.set(w,e.entry),c.set(e.entry.channelId,w),o.set(e.entry.channelId,g),ee=e.payload,l(e.entry)}return nj(t,ee,m,i)}async function p(t,i,a){let u=t.request.methodDetails?.chainId??0,f=await r({chainId:u}),p=a.action,{channelId:m,transaction:h}=a,g=e.voucherSigner??i,_=m,v=a.cumulativeAmountRaw?BigInt(a.cumulativeAmountRaw):a.cumulativeAmount?P(a.cumulativeAmount,n):void 0,y=a.additionalDepositRaw?BigInt(a.additionalDepositRaw):a.additionalDeposit?P(a.additionalDeposit,n):void 0,b=d(t,u,_);o.set(_,b);let x;switch(p){case`open`:{if(!h)throw Error(`transaction required for open action`);if(v===void 0)throw Error(`cumulativeAmount required for open action`);let e=await HA(f,i,{channelId:_,cumulativeAmount:v},b,u,g);x={action:`open`,type:`transaction`,channelId:_,transaction:h,authorizedSigner:NA(g),cumulativeAmount:v.toString(),signature:e};break}case`topUp`:if(!h)throw Error(`transaction required for topUp action`);if(y===void 0)throw Error(`additionalDeposit required for topUp action`);x={action:`topUp`,type:`transaction`,channelId:_,transaction:h,additionalDeposit:y.toString()};break;case`voucher`:{if(v===void 0)throw Error(`cumulativeAmount required for voucher action`);x=await rj(f,i,_,v,b,u,g);let e=c.get(_);if(e){let t=s.get(e);t&&(t.cumulativeAmount=t.cumulativeAmount>v?t.cumulativeAmount:v,l(t))}break}case`close`:{if(v===void 0)throw Error(`cumulativeAmount required for close action`);let e=await HA(f,i,{channelId:_,cumulativeAmount:v},b,u,g);x={action:`close`,channelId:_,cumulativeAmount:v.toString(),signature:e};let t=c.get(_);if(t){let e=s.get(t);e&&(e.opened=!1,e.cumulativeAmount=e.cumulativeAmount>v?e.cumulativeAmount:v,l(e))}break}}return nj(t,x,u,i)}return MT(qT,{canHandleChallenge({challenge:e}){let t=Cx(e.request.methodDetails,Dx.sessionProtocol);return t===void 0||t===Ox.v1},context:cj,async createCredential({challenge:t,context:n}){let o=t.request.methodDetails?.chainId??0,s=await r({chainId:o}),c=i(s,n);if(!n?.action&&(e.deposit!==void 0||a!==void 0))return f(t,c,n);if(n?.action)return p(t,c,n);throw Error("No `action` in context and no `deposit` or `maxDeposit` configured. Either provide context with action/channelId/cumulativeAmount, or configure `deposit`/`maxDeposit` for auto-management.")}})}var cj,lj=I((()=>{kx(),NT(),Gk(),Zk(),Gx(),PA(),YD(),YT(),qA(),oj(),cj=Y.object({account:Y.optional(Y.custom()),action:Y.optional(Y.enum([`open`,`topUp`,`voucher`,`close`])),channelId:Y.optional(Y.string()),cumulativeAmount:Y.optional(Fx()),cumulativeAmountRaw:Y.optional(Y.string()),transaction:Y.optional(Y.string()),additionalDeposit:Y.optional(Fx()),additionalDepositRaw:Y.optional(Y.string()),depositRaw:Y.optional(Y.string())})}));function uj(e){let t=e.allowCustomEscrow??!1,n=e.fetch??globalThis.fetch,r=e.webSocket??globalThis.WebSocket,i=e.maxDeposit===void 0?null:P(e.maxDeposit,e.decimals??6),a=null,o=null,s=null,c=0n,l=0n,u=null,d=null,f=null,p=null,m=null,h=null,g=null,_=0n,v=0n,y=sj({account:e.account,allowCustomEscrow:t,voucherSigner:e.voucherSigner,getClient:e.client?()=>e.client:e.getClient,escrowContract:e.escrowContract,decimals:e.decimals,maxDeposit:e.maxDeposit,onChannelUpdate(e){e.channelId!==a?.channelId&&(c=0n,l=0n),a=e}}),b=hw({fetch:n,methods:[y],onChallenge:async(e,t)=>{o=e},orderChallenges:e.orderChallenges});function x(e){if(!e||e.channelId!==a?.channelId)return;S(e);let t=BigInt(e.acceptedCumulative),n=BigInt(e.spent);c=c>t?c:t,l=l>n?l:n}function S(e){if(!a||e.channelId!==a.channelId)return;let t=BigInt(e.acceptedCumulative),n=BigInt(e.spent);if(n>t)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(t>a.cumulativeAmount)throw Error(`receipt accepted cumulative exceeds local voucher state`);if(n>a.cumulativeAmount)throw Error(`receipt spent exceeds local voucher state`);k(t),k(n)}function C(e=()=>!0){if(g)throw Error(`receipt wait already in progress`);return new Promise((t,n)=>{g={predicate:e,resolve:t,reject:n}})}function w(){if(p)return Promise.resolve(p);if(m)throw Error(`close-ready wait already in progress`);return new Promise((e,t)=>{m={resolve:e,reject:t}})}function T(e){if(!g||!g.predicate(e))return;let t=g;g=null,t.resolve(e)}function ee(e){if(p=e,!m)return;let t=m;m=null,t.resolve(e)}function E(e){if(!g)return;let t=g;g=null,t.reject(e)}function D(e){if(!m)return;let t=m;m=null,t.reject(e)}function O(e,t){if(p&&p.challengeId===e.id&&p.channelId===t)return p.spent;let n=a?.channelId===t?a.cumulativeAmount:0n;if(v>0n){let e=_*v,t=l>e?l:e;return(t>n?n:t).toString()}return(l>c?l:c).toString()}function k(e){if(i!==null&&!(e<=i))throw Error(`requested voucher amount ${e} exceeds local maxDeposit ${i}`)}function te(e){let t=e.headers.get(J.paymentReceipt),n=t?sE(t):null;return x(n),Object.assign(e,{receipt:n,challenge:o,channelId:a?.channelId??null,cumulative:a?.cumulativeAmount??0n})}async function A(e,t){return s=e,te(await b(e,t))}function ne(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)},s=(e,a)=>{if(e===`close`){if(n)return;n=!0,i=fj.CLOSED,r=null}if(e===`open`&&(i=fj.OPEN),e===`message`&&r){r.push(a);return}let o=`on${e}`,s=c[o];typeof s==`function`&&s(a);let l=t.get(e);if(l)for(let e of Array.from(l))typeof e.value==`function`?e.value(a):e.value.handleEvent(a),e.once&&l.delete(e)},c={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,_onmessage:null,get onmessage(){return c._onmessage},set onmessage(e){if(c._onmessage=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:c}}return{get channelId(){return a?.channelId},get cumulative(){return a?.cumulativeAmount??0n},get opened(){return a?.opened??!1},async open(e){if(a?.opened)return;if(!o)throw Error(`No challenge available. Make a request first to receive a 402 challenge, or pass a challenge via .fetch()/.sse().`);let t=e?.deposit,r=await y.createCredential({challenge:o,context:{...t!==void 0&&{depositRaw:t.toString()}}});if(!s)throw Error(`No URL available — call fetch() or sse() before open().`);let i=await n(s,{method:`POST`,headers:{[J.authorization]:r}});if(!i.ok){let e=await i.text().catch(()=>``),t=i.headers.get(J.wwwAuthenticate)??``;throw Error(`Open request failed with status ${i.status}${e?`: ${e}`:``}${t?` [${J.wwwAuthenticate}: ${t}]`:``}`)}},fetch:A,async sse(e,t){let{onReceipt:r,signal:i,...s}=t??{},c=await A(e,{...s,headers:{..._w(s.headers),Accept:`text/event-stream`},...i?{signal:i}:{}}),l=o;if(!c.body)throw Error(`Response has no body.`);let u=c.body.getReader(),d=new TextDecoder;async function*f(){let t=``;try{for(;!i?.aborted;){let{done:i,value:o}=await u.read();if(i)break;t+=d.decode(o,{stream:!0});let s=t.split(`
233
233
 
234
- `);t=s.pop();for(let t of s){if(!t.trim())continue;let i=cE(t);if(i)switch(i.type){case`message`:yield i.data;break;case`payment-need-voucher`:{if(!a||!l)break;let t=BigInt(i.data.requiredCumulative);k(t),a.cumulativeAmount=a.cumulativeAmount>t?a.cumulativeAmount:t;let r=await y.createCredential({challenge:l,context:{action:`voucher`,channelId:a.channelId,cumulativeAmountRaw:a.cumulativeAmount.toString()}}),o=await n(e,{method:`POST`,headers:{Accept:`text/event-stream`,[J.authorization]:r}});if(!o.ok)throw Error(`Voucher POST failed with status ${o.status}`);break}case`payment-receipt`:x(i.data),r?.(i.data)}}}}finally{u.releaseLock()}}return f()},async ws(t,i){if(!r)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let{onReceipt:c,protocols:l,signal:m}=i??{},g=new URL(t.toString()),b=new URL(g.toString());b.protocol===`ws:`&&(b.protocol=`http:`),b.protocol===`wss:`&&(b.protocol=`https:`),s=b.toString();let S=await n(b,m?{signal:m}:void 0);if(S.status!==402)throw Error(`Expected a 402 payment challenge from ${b}, received ${S.status} instead.`);let w=(await uj(DS(nS(S),[y],CS([y]).entries),i?.orderChallenges??e.orderChallenges))[0]?.challenge;if(!w)throw Error(`No payment challenge received from HTTP endpoint for this WebSocket URL. The server may not require payment or did not advertise a challenge.`);o=w;let O=await y.createCredential({challenge:w,context:{}});p=null,u=w,_=0n,v=BigInt(w.request.amount);let A=HS(O);d=A.payload.channelId;let j=new r(g,l);f=j;let M=te(j),ne=e=>{E(Error(e)),D(Error(e)),(j.readyState===dj.CONNECTING||j.readyState===dj.OPEN)&&j.close(fj,e)},re=e=>e.challengeId===w.id&&e.channelId===d,ie=new Promise((e,t)=>{let n=()=>{j.removeEventListener(`error`,r),M.emit(`open`,{type:`open`}),e()},r=()=>{j.removeEventListener(`open`,n),t(Error(`WebSocket connection to ${g} failed to open.`))};j.addEventListener(`open`,n,{once:!0}),j.addEventListener(`error`,r,{once:!0})});return j.addEventListener(`close`,e=>{f===j&&(f=null),u===w&&(u=null),d===A.payload.channelId&&(d=null),h=null,E(Error(`WebSocket closed before the payment flow completed.`)),D(Error(`WebSocket closed before the payment flow completed.`)),M.emit(`close`,{code:e.code??1e3,reason:e.reason??``,type:`close`,wasClean:!0})}),j.addEventListener(`error`,()=>{M.emit(`error`,{type:`error`})}),j.addEventListener(`message`,async e=>{let t=typeof e.data==`string`?e.data:void 0;if(!t)return;let n=fE(t);if(!n){M.emit(`message`,{data:t,type:`message`});return}switch(n.mpp){case`authorization`:break;case`message`:_+=1n,M.emit(`message`,{data:n.data,type:`message`});break;case`payment-close-ready`:if(!re(n.data)){ne(`received mismatched payment-close-ready frame`);break}if(BigInt(n.data.spent)>(a?.cumulativeAmount??0n)){ne(`received payment-close-ready beyond local voucher state`);break}x(n.data),c?.(n.data),ee(n.data),M.emit(`close`,{code:1e3,reason:`stream complete`,type:`close`});break;case`payment-error`:E(Error(n.message)),D(Error(n.message));break;case`payment-need-voucher`:{if(n.data.channelId!==d){ne(`received mismatched payment-need-voucher frame`);break}let e=BigInt(n.data.requiredCumulative);try{k(e)}catch(e){ne(e instanceof Error?e.message:`requested voucher amount exceeds local maxDeposit`);break}let t=(a?.cumulativeAmount??0n)>e?a?.cumulativeAmount??0n:e;a?.channelId===d&&(a.cumulativeAmount=t);let r=await y.createCredential({challenge:w,context:{action:`voucher`,channelId:d,cumulativeAmountRaw:t.toString()}});j.send(uE(r));break}case`payment-receipt`:if(!re(n.data)){ne(`received mismatched payment-receipt frame`);break}if(h!==null&&n.data.txHash&&(n.data.acceptedCumulative!==h||n.data.spent!==h)){ne(`received mismatched payment-close receipt frame`);break}x(n.data),c?.(n.data),T(n.data)}}),m&&m.addEventListener(`abort`,()=>{E(Error(`WebSocket payment flow aborted.`)),D(Error(`WebSocket payment flow aborted.`)),j.close()},{once:!0}),await ie,j.send(uE(O)),await C(),M.socket},async close(){let e=u??o,t=d??a?.channelId;if(!a?.opened)return;if(!e)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(!t)throw Error(`Cannot close session: no channel ID available. The session may not have been fully opened.`);if(f?.readyState===dj.OPEN){let n=p??await(async()=>(f.send(dE()),w()))(),r=BigInt(n.spent);if(r>(a.cumulativeAmount>l?a.cumulativeAmount:l))throw Error(`close-ready spent exceeds local voucher state`);let i=await y.createCredential({challenge:e,context:{action:`close`,channelId:t,cumulativeAmountRaw:r.toString()}}),o=r.toString();h=o;try{let n=C(n=>!!n.txHash&&n.challengeId===e.id&&n.channelId===t&&n.acceptedCumulative===o&&n.spent===o);f.send(uE(i));let r=await n;return f.close(),p=null,r}finally{h=null}}let r=await y.createCredential({challenge:e,context:{action:`close`,channelId:t,cumulativeAmountRaw:(()=>{let n=BigInt(O(e,t));if(n>a.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return k(n),n.toString()})()}});if(!s)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 i=await n(s,{method:`POST`,headers:{[J.authorization]:r}});if(!i.ok){let e=await i.text().catch(()=>``),t=(()=>{if(!e)return``;if(!i.headers.get(`Content-Type`)?.includes(`application/problem+json`))return e;try{return JSON.parse(e).detail??e}catch{return e}})(),n=i.headers.get(J.wwwAuthenticate)??``;throw Error(`Close request failed with status ${i.status}${t?`: ${t}`:``}${n?` [${J.wwwAuthenticate}: ${n}]`:``}`)}let c=i.headers.get(J.paymentReceipt);return c?oE(c):void 0}}}async function uj(e,t){let n=t;return n?n(e):e}var dj,fj,pj=I((()=>{dS(),eT(),kx(),YS(),VS(),_E(),cj(),dj={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},fj=3008})),mj=I((()=>{cj(),pj()}));function hj(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function gj(e){let t=D.encode(D.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return A.keccak256(t)}function _j(e){return Be.encodeForSigning(e)}function vj(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function yj(e,t){return A.keccak256(j.concat(_j(e),t.sender))}var bj=I((()=>{_E()})),xj,Sj,Cj,wj,Tj=I((()=>{xj=[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],Sj=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],Cj={name:`descriptor`,type:`tuple`,components:xj},wj=[{type:`function`,name:`CLOSE_GRACE_PERIOD`,stateMutability:`view`,inputs:[],outputs:[{type:`uint64`}]},{type:`function`,name:`VOUCHER_TYPEHASH`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`function`,name:`open`,stateMutability:`nonpayable`,inputs:[{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`deposit`,type:`uint96`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`}],outputs:[{name:`channelId`,type:`bytes32`}]},{type:`function`,name:`settle`,stateMutability:`nonpayable`,inputs:[Cj,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[Cj,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[Cj,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[Cj],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[Cj],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[Cj],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:xj},{name:`state`,type:`tuple`,components:Sj}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Sj}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Sj}]},{type:`function`,name:`computeChannelId`,stateMutability:`view`,inputs:[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`getVoucherDigest`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`domainSeparator`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`authorizedSigner`,type:`address`},{name:`salt`,type:`bytes32`},{name:`expiringNonceHash`,type:`bytes32`},{name:`deposit`,type:`uint96`}]},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`cumulativeAmount`,type:`uint96`},{name:`deltaPaid`,type:`uint96`},{name:`newSettled`,type:`uint96`}]},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`additionalDeposit`,type:`uint96`},{name:`newDeposit`,type:`uint96`}]},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`closeGraceEnd`,type:`uint256`}]},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`settledToPayee`,type:`uint96`},{name:`refundedToPayer`,type:`uint96`}]},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0}]}]}));function Ej(e,t){return{name:Nj,version:Pj,chainId:t,verifyingContract:e}}function Dj(e,t){return Ie.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function Oj(e,t,n){return e.toLowerCase()===Ie.address.toLowerCase()?Dj(t,n):le({domain:Ej(e,t),types:Fj,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function kj(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function Aj(e,t){return Oe.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function jj(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===Ie.address.toLowerCase())try{return await Aj(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return Te(e,{account:t,domain:Ej(r,i),types:Fj,primaryType:`Voucher`,message:n})})(),o=Re.from(a);if(!kj(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return Re.serialize(o)}function Mj(e,t,n,r){try{let i=Re.from(n.signature);if(!kj(i.type)||Re.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=Oj(e,t,n),o=Re.extractAddress({payload:a,signature:i});return Re.verify(i,{address:o,payload:a})&&rA(o,r)}catch{return!1}}var Nj,Pj,Fj,Ij=I((()=>{iA(),Nj=`TIP20 Channel Reserve`,Pj=`1`,Fj={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]}}));function Lj(e){return typeof e==`object`&&!!e}function Rj(e){return typeof e==`string`&&de(e,{strict:!1})?e:void 0}function zj(e){return Rj(e.accessKeyAddress)}function Bj(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(j.random(8))%e)}function Vj(e){return zj(e)??e.address}async function Hj(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return F(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function Uj(e,t){return await we(e,t)}function Wj(e,t,n=!1){let r=e.request.methodDetails,i=Lj(r)?Rj(r.escrowContract)??Rj(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!Kj(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!Kj(i,a)?i:a}function Gj(e,t,n,r){return KS({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function Kj(e,t){return e.toLowerCase()===t.toLowerCase()}async function qj(e,t,n,r,i,a=gE){let o=gj({...n,chainId:i,escrow:a}),s=ZT(r),c=await jj(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function Jj(e,t,n,r,i,a=gE){let o=await qj(e,t,n,r,i,a);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature}}async function Yj(e,t,n){let r=Vj(t),i=n.escrow??`0x4d50500000000000000000000000000000000000`,a=n.operator??`0x0000000000000000000000000000000000000000`,o=j.random(32),s=ZT(n.deposit),c=ZT(n.initialAmount),l=ae({abi:wj,functionName:`open`,args:[n.payee,a,n.token,s,o,r]}),u=await Uj(e,await Hj(e,{account:t,calls:[...n.prefixCalls??[],{to:i,data:l}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),d=Me.deserialize(u),f={authorizedSigner:r,expiringNonceHash:yj(vj({...n.feePayer?{feePayer:!0}:{},transaction:d}),{sender:t.address}),operator:a,payee:n.payee,payer:t.address,salt:o,token:n.token},p=gj({...f,chainId:n.chainId,escrow:i});return{action:`open`,type:`transaction`,channelId:p,transaction:u,signature:await jj(e,t,{channelId:p,cumulativeAmount:c},i,n.chainId),descriptor:f,cumulativeAmount:c.toString(),authorizedSigner:f.authorizedSigner}}async function Xj(e,t,n,r,i,a,o=gE,s=[],c=n.token){let l=gj({...n,chainId:i,escrow:o}),u=ZT(r);return{action:`topUp`,type:`transaction`,channelId:l,transaction:await Uj(e,await Hj(e,{account:t,calls:[...s,{to:o,data:ae({abi:wj,functionName:`topUp`,args:[n,u]})}],feePayer:a,feeToken:c,validAfter:Bj()})),descriptor:n,additionalDeposit:u.toString()}}var Zj=I((()=>{YS(),bj(),Tj(),_E(),Ij()}));function Qj(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function $j(e){return Qj({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function eM(){let e=new Map;return{get:t=>e.get(t),set(t){e.set($j(t),t)},delete(t){e.delete(t)}}}function tM(e){return{...e,cumulativeAmount:e.cumulativeAmount.toString(),deposit:e.deposit.toString()}}function nM(e){return{...e,cumulativeAmount:BigInt(e.cumulativeAmount),deposit:BigInt(e.deposit)}}var rM=I((()=>{}));function iM(e){if(e<0n||e>sM)throw new X({reason:`amount exceeds uint96 range`})}async function aM(e,t,n=gE,r){return oM(await xe(e,{address:n,abi:wj,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function oM(e){return iM(e.settled),iM(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}var sM,cM=I((()=>{hS(),Tj(),_E(),sM=2n**96n-1n}));function lM(e){return`cumulativeAmount`in e}function uM(e){if(lM(e))return BigInt(e.cumulativeAmount)}async function dM(e,t){t.opened?await e.store.set(t):await e.store.delete($j(t)),e.notifyUpdate(t)}async function fM(e,t,n){let r=uM(n);if(r===void 0)return;let i=await e.store.get(t);i&&i.channelId.toLowerCase()===n.channelId.toLowerCase()&&(i.cumulativeAmount=i.cumulativeAmount>r?i.cumulativeAmount:r,n.action===`close`&&(i.opened=!1),await dM(e,i))}function pM(e){return e?.action!==void 0}function mM(e){return pM(e)&&e.descriptor!==void 0}function hM(e,t,n){let r=n===`additionalDeposit`?e.additionalDepositRaw:e.cumulativeAmountRaw,i=n===`additionalDeposit`?e.additionalDeposit:e.cumulativeAmount;if(r)return BigInt(r);if(i)return P(i,t)}function gM(e,t,n,r){let i=hM(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function _M(e){return typeof e==`object`&&!!e}function vM(e){return typeof e==`string`&&de(e,{strict:!1})?e:void 0}function yM(e){let t=e.request.methodDetails;return _M(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:vM(t.escrowContract),escrow:vM(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:vM(t.feeToken),operator:vM(t.operator),sessionSnapshot:Cx(t,Dx.sessionSnapshot)}:{}}function bM(e,t){if(typeof e==`string`&&de(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function xM(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function SM(e){return typeof e==`string`?e:void 0}async function CM(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,getClient:i}=e,a=yM(n),o=await i({chainId:a.chainId}),s=a.chainId??o.chain?.id;if(!s)throw Error(`No chainId configured for TIP-1034 session challenge.`);let c=Wj(n,r,t),l=bM(n.request.recipient,`recipient`),u=bM(n.request.currency,`currency`);return{amount:xM(n.request.amount),challenge:n,chainId:s,client:o,escrow:c,feePayer:a.feePayer,feeToken:a.feeToken,key:Qj({payee:l,token:u,escrow:c,chainId:s}),operator:a.operator,payee:l,snapshot:a.sessionSnapshot,suggestedDepositRaw:SM(n.request.suggestedDeposit),token:u}}async function wM(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=aM}=e,o=gj({...r,chainId:i.chainId,escrow:i.escrow});TM({channelId:t,descriptor:r,expectedChannelId:o,payee:i.payee,payer:i.payer,authorizedSigner:i.authorizedSigner,token:i.token});let s=await a(n,o,i.escrow);if(s.deposit===0n)throw Error(`Channel ${o} cannot be reused (closed or not found on-chain).`);if(s.closeRequestedAt!==0)throw Error(`Channel ${o} cannot be reused (pending close request).`);return{channelId:o,state:s}}function TM(e){let{authorizedSigner:t,channelId:n,descriptor:r,expectedChannelId:i,payee:a,payer:o,token:s}=e;if(n&&n.toLowerCase()!==i.toLowerCase())throw Error(`context channelId does not match descriptor`);if(!Kj(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!Kj(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!Kj(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!Kj(hj(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function EM(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function DM(e){let{context:t,decimals:n,requestAmount:r,snapshot:i,settled:a}=e;if(i)return[BigInt(i.acceptedCumulative),BigInt(i.requiredCumulative),BigInt(i.spent)+r,a].reduce((e,t)=>t>e?t:e,0n);let o=hM(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function OM(e){let{account:t,client:n,readChannelState:r,snapshot:i}=e,a=i.highestVoucher;if(!a)throw Error(`session snapshot is missing its highest signed voucher`);if(a.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let o=BigInt(i.acceptedCumulative),s=BigInt(a.cumulativeAmount),c=BigInt(i.requiredCumulative),l=BigInt(i.deposit),u=BigInt(i.settled),d=BigInt(i.spent);if(s!==o)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(d>o)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(u>l)throw Error(`session snapshot settled amount exceeds deposit`);if(!Mj(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},hj(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await wM({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:Vj(t),token:i.descriptor.token},readChannelState:r}),p=[o,c,f.state.settled].reduce((e,t)=>t>e?t:e,0n);if(p>f.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:f.channelId,cumulativeAmount:p,deposit:f.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:d}}function kM(e,t){return Kj(e.address,t.payer)?Kj(Vj(e),hj(t)):!1}function AM(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(pM(r)){if(!mM(r))throw Error(`descriptor required for TIP-1034 session action`);return{type:`manual`,account:t,context:r,decimals:i,resolved:o}}if(!n&&r?.channelId&&!r.descriptor)throw Error(`descriptor required to reuse TIP-1034 channel`);let s=EM({context:r,snapshot:o.snapshot});return!n&&s&&kM(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&kM(t,n.descriptor)?{type:`voucher`,account:t,entry:n,maxDeposit:a,resolved:o}:{type:`open`,account:t,context:r,maxDeposit:a,resolved:o}}async function jM(e,t,n=!1){switch(e.type){case`open`:return NM(e,t,n);case`recover`:return PM(e,t);case`voucher`:return FM(e,t);case`manual`:return IM(e,t,n)}}async function MM(e,t){if(e)return await aA(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage})}async function NM(e,t,n){let{account:r,resolved:i}=e,a=RE({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await Yj(i.client,r,{chainId:i.chainId,deposit:a,escrow:i.escrow,feePayer:i.feePayer,feeToken:i.feeToken,initialAmount:i.amount,operator:i.operator,payee:i.payee,prefixCalls:await MM(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await dM(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function PM(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await wM({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:Vj(n),token:o.token}}),l=DM({context:r,decimals:i,requestAmount:o.amount,settled:c.state.settled,snapshot:o.snapshot});if(l>c.state.deposit)throw Error(`recovered voucher amount exceeds on-chain channel deposit`);BE(l,a);let u=await qj(o.client,n,s,l,o.chainId,o.escrow);return await dM(t,{channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function FM(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;BE(a,e.maxDeposit);let o=await qj(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await dM(t,r),o}async function IM(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=gj({...s,chainId:o.chainId,escrow:o.escrow});TM({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:Vj(r),token:o.token});let l=await LM({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await fM(t,o.key,l),l}async function LM(e,t){switch(e.context.action){case`open`:return RM(e);case`topUp`:return zM(e,t);case`voucher`:return BM(e);case`close`:return VM(e)}}async function RM(e){let{account:t,channelId:n,context:r,decimals:i,descriptor:a,resolved:o}=e;if(!r.transaction)throw Error(`transaction required for open action`);let s=gM(r,i,`cumulativeAmount`,`open`),c=await qj(o.client,t,a,s,o.chainId,o.escrow);return{action:`open`,type:`transaction`,channelId:n,transaction:r.transaction,signature:c.signature,descriptor:a,cumulativeAmount:s.toString(),authorizedSigner:a.authorizedSigner}}async function zM(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=gM(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:Xj(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await MM(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function BM(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return qj(a.client,t,i,gM(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function VM(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Jj(a.client,t,i,gM(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}var HM,UM,WM,GM=I((()=>{kx(),Gx(),uA(),cM(),bj(),Ij(),Zj(),rM(),tD(),HM=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),UM=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),WM=Y.object({account:Y.optional(Y.custom()),autoSwap:Y.optional(Y.custom()),action:Y.optional(Y.enum([`open`,`topUp`,`voucher`,`close`])),channelId:Y.optional(UM),cumulativeAmount:Y.optional(Fx()),cumulativeAmountRaw:Y.optional(Y.string()),transaction:Y.optional(HM),descriptor:Y.optional(Y.custom()),additionalDeposit:Y.optional(Fx()),additionalDepositRaw:Y.optional(Y.string()),depositRaw:Y.optional(Y.string())})}));async function KM(e,t){let n=XM.get(e)??new Map;XM.set(e,n);let r=n.get(t),i,a=new Promise(e=>{i=e});return n.set(t,a),await r,()=>{i(),n.get(t)===a&&n.delete(t)}}function qM(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function JM(e,t,n){try{let r=e.response?.headers.get(J.paymentReceipt);if(r){let e=oE(r);if(e.challengeId===t.id&&qM(n,e))return!0}}catch{}return e.challenges?.some(e=>cD(e)?qM(n,lD(e)):!1)??!1}function YM(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a=6,escrow:o,getClient:s,maxDeposit:c,topUpAmount:l,onChannelUpdate:u,resolveAccount:d}=e,f=Jk({chain:Fe,getClient:s,rpcUrl:qD}),p=Uk({account:t}),m=c===void 0?void 0:P(c,a),h=l===void 0?void 0:P(l,a),g=i??eM(),_={store:g,notifyUpdate:e=>u?.(e)},v=async(e,t,n)=>{let r=p(e.client,t),i=t?.action?t.descriptor:n?.descriptor??EM({context:t,snapshot:e.snapshot})?.descriptor;return await d?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:hj(i)}:{}}})??r},y=async(e,t,n)=>AM({account:await v(e,t,n),entry:n,context:t,decimals:a,maxDeposit:m,resolved:e}),b=jT(KT,{canHandleChallenge:({challenge:e})=>cD(e),context:WM,async createCredential(e){let{challenge:t,context:i}=e,a=await CM({allowCustomEscrow:n,challenge:t,escrowOverride:o,getClient:f}),s=cw(e),c=()=>{};try{let e=!pM(i)&&i?.descriptor===void 0;e&&(c=await KM(g,a.key),s&&(await g.get(a.key))?.opened&&await s.prepare());let n=await g.get(a.key),o=await y(a,i,n);if(!e&&s&&o.type===`open`){c=await KM(g,a.key);let e=await g.get(a.key);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await s.prepare(),n=await g.get(a.key)),o=await y(a,i,n))}let l,u=s&&o.type===`open`?{store:{get:e=>g.get(e),async set(e){l=e},delete:e=>g.delete(e)},notifyUpdate(){}}:_,d=await Gj(t,await jM(o,u,oA(i?.autoSwap??r,cA)),a.chainId,o.account);if(s&&l){let e=l;s.settle=async n=>{let r=n.status===`accepted`||JM(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await g.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await g.set(e),_.notifyUpdate(e))}return!0}finally{c()}}}else c();return d}catch(e){throw c(),e}}}),x=async({challenge:e,channel:t,deposit:n,fetch:r,input:i,requiredCumulative:a})=>{let o=t.deposit>n?t.deposit:n,s=zE({deposit:o,maxDeposit:m,requiredCumulative:a,suggestedDeposit:e.request.suggestedDeposit===void 0?void 0:BigInt(e.request.suggestedDeposit),topUpAmount:h});s>0n&&await mD({additionalDeposit:s,challenge:e,channel:t,channelId:t.channelId,createSessionCredential:(e,t)=>b.createCredential({challenge:e,context:t}),fetch:r,input:i});let c=o+s;if(c===t.deposit)return;let l=await g.get($j(t)),u=l?.channelId.toLowerCase()===t.channelId.toLowerCase()?l:t,d={...u,deposit:u.deposit>c?u.deposit:c};await g.set(d),_.notifyUpdate(d)};return ew(b,async({challenge:e,context:t,fetch:r,input:i})=>{if(!cD(e))return;let a=t===void 0?void 0:WM.parse(t);if(pM(a))return;let s=await CM({allowCustomEscrow:n,challenge:e,escrowOverride:o,getClient:f}),c=await g.get(s.key);if(!c?.opened)return;let l=s.snapshot?.channelId.toLowerCase()===c.channelId.toLowerCase()?s.snapshot:void 0,u=c.cumulativeAmount+rE(e),d=l?BigInt(l.requiredCumulative):u,p=d>u?d:u,m=l?BigInt(l.deposit):c.deposit,h=m>c.deposit?m:c.deposit;p<=h&&h===c.deposit||!kM(await v(s,a,c),c.descriptor)||await x({challenge:e,channel:c,deposit:h,fetch:r,input:i,requiredCumulative:p})}),aw(b,async({challenge:e,credential:t,fetch:r,headers:i,input:a,refetch:s,response:c,signal:l})=>{if(!cD(e))return c;if(!sE(c))return nE(HS(t).payload).action===`open`&&i.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await s?.()??c:c;let u=(await CM({allowCustomEscrow:n,challenge:e,escrowOverride:o,getClient:f})).key,d=await g.get(u),p={assertVoucherWithinLocalLimit:e=>BE(e,m),createSessionCredential:(e,t)=>b.createCredential({challenge:e,context:t}),fetch:r,getChannel:()=>d??null,async topUpIfNeeded({deposit:t,requiredCumulative:n}){d&&await x({challenge:e,channel:d,deposit:d.deposit>t?d.deposit:t,fetch:r,input:a,requiredCumulative:n})}};return TD({onNeedVoucher:t=>ED({challenge:e,driver:p,input:a},t),onReceipt(){},response:c,signal:l})})}var XM,ZM=I((()=>{iw(),fw(),kx(),YS(),MT(),Wk(),Xk(),uA(),JD(),JT(),bj(),_E(),Zj(),rM(),GM(),tD(),HD(),XM=new WeakMap}));function QM(e,t){eN.set(e,t)}function $M(e){let t=eN.get(e);if(!t)throw Error(`Session manager internals are unavailable.`);return t}var eN,tN=I((()=>{eN=new WeakMap}));function nN(e){let t=null;return{wait(n=()=>!0){if(t)throw Error(`${e} wait already in progress`);return new Promise((e,r)=>{t={predicate:n,resolve:e,reject:r}})},settle(e){if(!t||!t.predicate(e))return;let n=t;t=null,n.resolve(e)},reject(e){if(!t)return;let n=t;t=null,n.reject(e)}}}function rN(e){let t=nN(`close-ready`),n=nN(`receipt`);return{waitForReceipt(e){return n.wait(e)},waitForCloseReady(){let n=e.getSocketSession()?.closeReadyReceipt;return n?Promise.resolve(n):t.wait()},settleReceipt(e){n.settle(e)},settleCloseReady(n){let r=e.getSocketSession();r&&r.challenge.id===n.challengeId&&r.channelId===n.channelId&&(r.closeReadyReceipt=n),t.settle(n)},rejectReceipt(e){n.reject(e)},rejectCloseReady(e){t.reject(e)}}}var iN=I((()=>{}));function aN(e){return e.method===Tx.tempo&&e.intent===Ex.charge}function oN(e){if(!aN(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function sN(e,t,n){if(!n)return t;let r={...gw(e instanceof Request?e.headers:void 0),...gw(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===J.paymentSession.toLowerCase())?t:{...t,headers:{...r,[J.paymentSession]:n}}}function cN(e){let t=e.decimals??6,n=e.webSocket??globalThis.WebSocket;return{decimals:t,fetch:e.fetch??globalThis.fetch.bind(globalThis),maxVoucherCumulative:e.maxDeposit===void 0?null:P(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:P(e.topUpAmount,t),WebSocket:n}}function lN(e){let t=e.allowCustomEscrow??!1,n=cN(e),r=Jk({chain:Fe,getClient:e.client?()=>e.client:e.getClient,rpcUrl:qD}),i=Uk({account:e.account}),a=KE(),o=rN({getSocketSession:()=>a.socketSession}),s=e.channelStore??eM(),c=new Set,l;async function u(e){let t=await s.get(e);if(t?.opened&&!c.has(t.channelId))return t}let d={async get(e){let t=await u(e);return t&&l&&(l.seenExisting.add(e),!l.committed&&!l.created.has(e)&&(l.resumed??=t)),t},async set(e){let t=$j(e);e.opened&&c.delete(e.channelId),l?.trackCreates&&!l.seenExisting.has(t)&&l.created.set(t,e),await s.set(e)},delete:e=>s.delete(e)};async function f(e){let t=$j(e);c.add(e.channelId),l?.seenExisting.delete(t),l?.resumed===e&&(l.resumed=void 0),await Promise.resolve(s.delete(t)).catch(()=>void 0)}async function p(){let e=l;if(e?.created.size){for(let[t,n]of e.created)c.add(n.channelId),await Promise.resolve(s.delete(t)).catch(()=>void 0);e.created.clear(),await M(e.committed??e.previous)}}function m(e){let t=Cx(e.request.methodDetails,Dx.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=l;if(!n?.created.size||!a.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&a.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=ZE({channel:a.channel,spent:a.spent,state:a.state}),!0;return!1}function h(e){return kE(a,e)}function g(){let e=a.state.status===`active`?a.state:l?.committed?.state??l?.previous.state;return e?.status===`active`?e.units:0}function _(e){let t=l,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit||(t.resumed=void 0,t.committed=ZE({channel:a.channel,spent:a.spent,state:a.state}))}let v=YM({account:e.account,allowCustomEscrow:t,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,decimals:n.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:d,onChannelUpdate(e){e.channelId!==a.channel?.channelId&&(a.spent=0n),a.channel=e,a.lastChallenge&&h({type:`activated`,challengeId:a.lastChallenge.id,entry:e,spent:a.spent.toString(),units:g()}),_(e)}});ow(v);let y=OA({account:e.account,getClient:e.client?()=>e.client:e.getClient}),b=mw({fetch:n.fetch,methods:[v],onChallenge:async(e,t)=>{if(!sD(e))return;let n=l,r=n&&n.challengesReceived>0&&e.id===a.lastChallenge?.id,i=r&&qx(e)===qx(a.lastChallenge);n&&n.challengesReceived++,!i&&(m(e)||(n?.created.size?await p():r&&await M(n.committed??n.previous)),a.lastChallenge=e,h({type:`challengeReceived`,challengeId:e.id}))}});function x(e,t){return v.createCredential({challenge:e,context:t})}function S(e){qE({maxVoucherCumulative:n.maxVoucherCumulative,receipt:e,runtime:a})}function C(e=a.state.status===`active`?a.state.units:0){!a.channel||!a.lastChallenge||a.state.status!==`active`&&a.state.status!==`withdrawable`&&a.state.status!==`closeRequested`&&h({type:`activated`,challengeId:a.lastChallenge.id,entry:a.channel,spent:a.spent.toString(),units:e})}async function w(t){let n=t.headers.get(J.paymentSessionSnapshot);if(!n)return;let o=yE(n),s=await r({chainId:o.chainId}),c=i(s),{entry:l,spent:u}=await OM({account:await e.resolveAccount?.({account:c,chainId:o.chainId,operation:{authority:hj(o.descriptor),kind:`authorizePaymentChannel`}})??c,client:s,snapshot:o});return k(l.cumulativeAmount),await Promise.resolve(d.set(l)).catch(()=>void 0),a.channel=l,a.spent=u,l}async function T(t,r){if(!e.bootstrap||a.channel?.opened)return;let i=t instanceof Request?t.headers:void 0,{body:o,method:s,...c}=r??{},l=t instanceof Request?t.url:t,u={...c,method:`HEAD`,headers:{...gw(i),...gw(r?.headers),[J.acceptPayment]:`${Tx.tempo}/${Ex.charge}`}};try{let e=await n.fetch(l,u);if(e.status!==402)return await w(e);let t=nS(e).find(aN);if(!t||!oN(t))return;let r=await y.createCredential({challenge:t,context:{}}),i=await n.fetch(l,{...u,headers:{...gw(u.headers),[J.authorization]:r}});return i.ok?await w(i):void 0}catch{return}}function ee(e,t){let n=a.socketSession;return YE({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:a.channel?.channelId===t?a.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:a.spent,tickCost:n?.tickCost})}function E(e,t){let n=lD(t);if(!n)return;if(gj({...n.descriptor,chainId:n.chainId,escrow:n.escrow}).toLowerCase()!==n.channelId.toLowerCase())throw Error(`close snapshot descriptor does not match its channel ID`);if(n.channelId.toLowerCase()!==e.channelId.toLowerCase())throw Error(`close snapshot channel ID does not match local session`);if(n.chainId!==e.chainId||n.escrow.toLowerCase()!==e.escrow.toLowerCase())throw Error(`close snapshot payment scope does not match local session`);let r=BigInt(n.acceptedCumulative),i=BigInt(n.spent);if(r<0n||i<0n)throw Error(`close snapshot amounts must not be negative`);if(i>r)throw Error(`close snapshot spent exceeds accepted cumulative amount`);if(r>e.cumulativeAmount)throw Error(`close snapshot accepted cumulative exceeds local voucher state`);return{acceptedCumulative:r,spent:i}}function D(e,t){let n=E(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(a.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>a.spent&&(a.spent=i),n}function O(e,t=e.challenge,n=!1){let r=(n?D(e,t):E(e.channel,t))?.acceptedCumulative??ee(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return k(r),r.toString()}function k(e){PE({cumulativeAmount:e,maxVoucherCumulative:n.maxVoucherCumulative})}async function A(e){let{knownDeposit:t,...r}=e,i=await mD({...r,channel:a.channel,createSessionCredential:x,fetch:n.fetch});S(i);let o=aD({additionalDeposit:e.additionalDeposit,channel:a.channel,channelId:e.channelId,challengeId:a.lastChallenge?.id,currentState:a.state,knownDeposit:t,receipt:i,spent:a.spent});return o?.channel&&a.lastChallenge&&(await d.set(o.channel),h({type:`activated`,challengeId:a.lastChallenge.id,entry:o.channel,spent:a.spent.toString(),units:g()}),_(o.channel)),i}async function j(e){let t=a.channel?.channelId===e.channelId?a.channel.deposit:0n,r=t>e.deposit?t:e.deposit,i=zE({deposit:r,maxDeposit:n.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:n.topUpAmount});i!==0n&&await A({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:r})}async function te(e,t){let n=XE({channel:a.channel,channelId:e,challengeId:a.lastChallenge?.id,cumulativeAmount:t,spent:a.spent,state:a.state});n&&a.channel&&(h({type:`activated`,challengeId:n.challengeId,entry:a.channel,spent:n.spent,units:n.units}),await s.set(a.channel))}async function M(e){let t=QE(e,a.channel);a.channel=t.channel,a.spent=t.spent,a.state=t.state,a.channel?.opened&&await s.set(a.channel)}function ne(e){let t=e.headers.get(J.paymentReceipt),n=t?oE(t):null;return S(n),Object.assign(e,{receipt:n,challenge:a.lastChallenge,channelId:a.channel?.channelId??null,cumulative:a.channel?.cumulativeAmount??0n})}async function re(e,t){if(l)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a.lastUrl=e;let r=ZE({channel:a.channel,spent:a.spent,state:a.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:r,seenExisting:new Set,resumed:void 0,trackCreates:!1};l=i;try{await T(e,t),i.trackCreates=!0;let o=sN(e,t,a.channel?.opened?a.channel.channelId:void 0),s=!r.channel?.opened;async function c(){let n=i.resumed;return!s||!n?!1:(s=!1,await f(n),o=sN(e,t,void 0),!0)}for(;;){let t;try{t=await b(e,o)}catch(e){if(i.created.size?await p():await M(i.committed??r),await c())continue;throw e}let s=ne(t),l=!1;if(s.status===402){let t=await gD({input:e,init:o,response:s,createSessionCredential:x,fetch:n.fetch,getChannel:()=>a.channel,restoreCumulative:te,setChallenge(e){a.lastChallenge=e},topUpIfNeeded:j});t&&(l=!0,s=ne(t))}if(!l&&!s.ok&&!s.receipt){if(i.created.size?await p():await M(i.committed??r),await c())continue;return s}return s}}finally{l=void 0}}async function ie(e){let t=await vD({createSessionCredential:x,fetch:n.fetch,getMinimumSpent:()=>a.spent,lastUrl:a.lastUrl,resolveSignedCloseAmount:t=>O(e,t,!0),signedCloseAmount:O(e),setChallenge(e){a.lastChallenge=e},target:e});return t&&(C(),h({type:`closeStarted`}),h({type:`closed`,receipt:t})),t}let ae={createSessionCredential:x,doFetch:re,fetch:n.fetch,getChannel:()=>a.channel,getChallenge:()=>a.lastChallenge,assertVoucherWithinLocalLimit:k,acceptReceipt(e){S(e)},topUpIfNeeded:j},oe={get channelId(){return a.channel?.channelId},get cumulative(){return a.channel?.cumulativeAmount??0n},get opened(){return a.channel?.opened??!1},get state(){return a.state},fetch:re,async topUp(e){let t=iD({amount:e,assertVoucherWithinLocalLimit:k,channel:a.channel,decimals:n.decimals,lastChallenge:a.lastChallenge,lastUrl:a.lastUrl});return A({additionalDeposit:t.additionalDeposit,challenge:t.challenge,channelId:t.channelId,input:t.input})},async sse(e,t){return yD(e,t,ae)},async ws(e,t){if(!n.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let r=fD(e),i=t?.signal?{signal:t.signal}:void 0;await T(r,i);let s=a.channel?.opened?a.channel.channelId:void 0,{challenge:c,credential:l,httpUrl:u,wsUrl:d}=await OD({async createSessionCredential(e,t){return a.lastChallenge=e,await nw(v,{challenge:e,context:t,fetch:n.fetch,input:r}),x(e,t)},fetch:n.fetch,input:e,onProbeUrl(e){a.lastUrl=e.toString()},probeInit:sN(r,i,s),signal:t?.signal});return a.lastChallenge=c,ND({challenge:c,credential:l,httpUrl:u,WebSocket:n.WebSocket,wsUrl:d,options:t,createSessionCredential:x,getChannel:()=>a.channel,setSocketSession(e){a.socketSession=e},async refreshChallenge(){let e=await DD({fetch:n.fetch,input:u,probeInit:sN(u,i,a.channel?.opened?a.channel.channelId:void 0),signal:t?.signal});return a.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:k,acceptReceipt:S,rejectCloseReady:o.rejectCloseReady,rejectReceipt:o.rejectReceipt,settleCloseReady:o.settleCloseReady,settleReceipt:o.settleReceipt,topUpIfNeeded:j,waitForReceipt:o.waitForReceipt})},async close(){let e=a.socketSession,t=VE({channel:a.channel,currentSocket:e,lastChallenge:a.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===zD.OPEN){let r=await $E({activeSocket:n,createSessionCredential:x,currentSocket:e,spent:a.spent,target:t,waitForCloseReady:o.waitForCloseReady,waitForReceipt:o.waitForReceipt});return C(),h({type:`closeStarted`}),h({type:`closed`,receipt:r}),r}return ie(t)}};return QM(oe,{consumeSseResponse(e,t,n){return bD(e,t,n,ae)},rehydrate({channel:e,challenge:t,input:n,spent:r}){if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!sD(t))throw Error(`Cannot restore session: challenge is not tempo/session.`);if(r<0n)throw Error(`Cannot restore session: spent must not be negative.`);if(r>e.cumulativeAmount)throw Error(`Cannot restore session: spent exceeds local voucher state.`);k(e.cumulativeAmount);let i=E(e,t),o=i&&i.spent>r?i.spent:r;a.lastUrl=n,a.lastChallenge=t,a.channel=e,a.spent=o,h({type:`challengeReceived`,challengeId:t.id}),h({type:`activated`,challengeId:t.id,entry:e,spent:o.toString(),units:0})}}),oe}var uN=I((()=>{dS(),eT(),iw(),fw(),kx(),Wk(),Xk(),AA(),JD(),rM(),GM(),ZM(),bj(),_E(),EE(),tN(),iN(),tD(),HD(),(function(e){e.serializeSnapshot=vE,e.deserializeSnapshot=yE})(lN||={})}));function dN(e){return e instanceof Date?e:new Date(e)}function fN(e){let t=e.getTime();if(!Number.isFinite(t))throw new X({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new X({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new X({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function pN(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new X({reason:`periodCount is invalid`});let t=jN[e.periodUnit];if(t===void 0)throw new X({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>AN)throw new X({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new X({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function mN(e){let{challengeExpires:t,request:n}=e;pN(n);let r=fN(dN(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new X({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function hN(e){let t=DN(e.currency,`currency`),n=DN(e.recipient,`recipient`);return[{address:t,selector:kN,recipients:[n]}]}async function gN(e){let{accessKey:t,account:n,chainId:r,request:i}=e;if(typeof n.sign!=`function`)return;let a=vN({accessKey:t,chainId:r,request:i}),o=await n.sign({hash:Le.getSignPayload(a)}),s=Re.from(o);if(s.type===`keychain`||s.type===`multisig`)throw new X({reason:`keyAuthorization must use a primitive signature`});return Le.from(a,{signature:o})}function _N(e){let{accessKey:t,chainId:n,payload:r,request:i}=e;if(r.type!==`keyAuthorization`)throw new X({reason:`invalid keyAuthorization payload`});let a=yN(r.signature),o=bN(a);return xN({accessKey:t,authorization:a,chainId:n}),SN(a,i),wN(CN(a),i),TN(a.scopes,i),{authorization:a,source:{address:EN(a,o),chainId:n}}}function vN(e){let{accessKey:t,chainId:n,request:r}=e;return Le.from({address:DN(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(n),expiry:fN(dN(r.subscriptionExpires)),limits:[{token:DN(r.currency,`currency`),limit:BigInt(r.amount),period:pN(r)}],scopes:hN(r),type:t.keyType})}function yN(e){try{return Le.deserialize(e)}catch(e){throw e instanceof Le.InvalidSignatureTypeError?new X({reason:`keyAuthorization must use a primitive signature`}):new X({reason:`invalid keyAuthorization payload`})}}function bN(e){let t=e.signature;if(!t)throw new X({reason:`keyAuthorization must use a primitive signature`});return t}function xN(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new X({reason:`keyAuthorization chainId mismatch`});if(t){if(!fe(n.address,DN(t.accessKeyAddress,`accessKeyAddress`)))throw new X({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new X({reason:`keyAuthorization key type mismatch`})}}function SN(e,t){if(mN({request:t}),e.expiry!==fN(dN(t.subscriptionExpires)))throw new X({reason:`keyAuthorization expiry mismatch`})}function CN(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new X({reason:`keyAuthorization must contain exactly one token limit`});return t}function wN(e,t){if(!fe(e.token,DN(t.currency,`currency`)))throw new X({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new X({reason:`keyAuthorization amount mismatch`});if(e.period!==pN(t))throw new X({reason:`keyAuthorization period mismatch`})}function TN(e,t){if(!e||e.length!==1)throw new X({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=DN(t.currency,`currency`),r=DN(t.recipient,`recipient`),i=new Set;for(let t of e){if(!fe(t.address,n))throw new X({reason:`keyAuthorization call target mismatch`});let e=ON(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new X({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new X({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!fe(t.recipients[0],r))throw new X({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new X({reason:`keyAuthorization must allow transferWithMemo`})}function EN(e,t){let n=Le.getSignPayload(e);try{let e=Re.extractAddress({payload:n,signature:t});if(!Re.verify(t,{address:e,payload:n}))throw new X({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof X?e:new X({reason:`keyAuthorization signature is invalid`})}}function DN(e,t){if(!de(e))throw new X({reason:`${t} must be an address`});return e.toLowerCase()}function ON(e){return typeof e==`string`?e.toLowerCase():``}var kN,AN,jN,MN=I((()=>{hS(),kN=`0x95777d59`,AN=(1n<<64n)-1n,jN={dev_second:1n,day:86400n,week:604800n}}));function NN(e={}){let t=Jk({chain:ge,getClient:e.getClient,rpcUrl:qD}),n=Uk({account:e.account});return jT(qT,{context:IN,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??UD.testnet,o=await t({chainId:a}),s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");FN(r.request),await e.validateRequest?.(r.request);let l=await PN(o,{accessKey:c,account:s,chainId:a,request:r.request}),u=_N({accessKey:c,chainId:a,payload:{signature:Le.serialize(l),type:`keyAuthorization`},request:r.request});if(!fe(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return KS({challenge:r,payload:{signature:Le.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function PN(e,t){let{accessKey:n,account:r,chainId:i,request:a}=t,o=await gN({accessKey:n,account:r,chainId:i,request:a});if(o)return o;let s=await e.request({method:`wallet_authorizeAccessKey`,params:[{address:n.accessKeyAddress,expiry:fN(dN(a.subscriptionExpires)),keyType:n.keyType,limits:[{token:a.currency,limit:j.fromNumber(BigInt(a.amount)),period:pN(a)}],scopes:hN(a)}]});return Le.fromRpc(s.keyAuthorization)}function FN(e){pN(e),fN(dN(e.subscriptionExpires))}var IN,LN=I((()=>{YS(),MT(),Wk(),Xk(),Gx(),JD(),JT(),MN(),IN=Y.object({accessKey:Y.optional(Y.custom()),account:Y.optional(Y.custom())})}));function RN(e={}){return[OA(e),zN(e)]}var zN,BN,VN=I((()=>{mj(),ZM(),uN(),AA(),LN(),zN=Object.assign(YM,{manager:lN}),BN=Object.assign(lj,{method:oj}),(function(e){e.charge=OA,e.common=RN,e.session=zN,e.sessionLegacy=BN,e.subscription=NN})(RN||={})})),HN=I((()=>{AA(),VN(),mj(),LN(),ZM(),uN()})),UN=Ke({orderTempoChargeChallengesByBalance:()=>GN,readTempoKeystore:()=>dP,resolveTempoAccount:()=>fP,tempo:()=>KN});async function WN(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}async function GN(e,t){let n=[],r=[];for(let[t,i]of e.entries())$N(i)&&(n.push(t),r.push(i));if(r.length<2)return[...e];let i=await eP(t).catch(()=>void 0);if(!i)return[...e];let a=await Promise.all(r.map(async(e,t)=>({challenge:e,index:t,score:await tP(e,i)})));a.sort((e,t)=>bP.indexOf(e.score)-bP.indexOf(t.score)||e.index-t.index);let o=[...e];for(let[e,t]of n.entries())o[t]=a[e].challenge;return o}function KN(){let e;return Mk({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:t,options:n,methodOpts:r}){let i=kO(n.account),a=t.request,o=a.currency,s=QN(r),c=aP({autoSwap:s.autoSwap??n.autoSwap,payWith:s.payWith??n.payWith,slippage:s.slippage??n.slippage,tokenIn:s.tokenIn}),l=o??``,u=a.decimals??6,d,f,p,m=!1,h=process.env.MPPX_PRIVATE_KEY?.trim()||(iO(i)?void 0:await AO(i).get());if(!h&&iO(i)&&pP()){m=!0;let e=fP(i);if(e){let r=cO(n.rpcUrl,{network:n.network});p=ne({chain:await uO({network:n.network,rpcUrl:r}),transport:ue(r)}),rP({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let i=o?await mO(p,o,e.wallet_address).catch(()=>void 0):void 0;l=i?.symbol??o??``,u=i?.decimals??a.decimals??6}}else if(h)f=he(h);else{let e=hP();if(e){let t=await AO(e).get();t&&(f=he(t))}if(!f)throw n.account?new L({code:`ACCOUNT_NOT_FOUND`,message:`Account "${i}" not found.`,exitCode:69}):new L({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!m&&f){let e=cO(n.rpcUrl,{network:n.network});p=ne({chain:await uO({network:n.network,rpcUrl:e}),transport:ue(e)}),rP({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let r=o?await mO(p,o,f.address).catch(()=>void 0):void 0;l=r?.symbol??o??``,u=r?.decimals??a.decimals??6}if(m)return{tokenSymbol:l,tokenDecimals:u,explorerUrl:d,methods:[],async createCredential(e){let t=e.headers.get(`www-authenticate`);if(!t)throw Error(`No WWW-Authenticate header in 402 response.`);return mP(t)}};if(!f||!p)throw new L({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let g=RN({account:f,...s.allowCustomEscrow===void 0?{}:{allowCustomEscrow:s.allowCustomEscrow},getClient:()=>p,...c===void 0?{}:{autoSwap:c},maxDeposit:(()=>{if(t.intent!==`session`)return;let e=t.request.suggestedDeposit,n=(s.deposit===void 0?void 0:String(s.deposit))??e??(pO(p.chain)?`10`:void 0);if(!n)throw new L({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return n})()}),_=(()=>{if(!s.channel)return;let e=s.channel,t=sP(e);return{channelId:e,...t!==void 0&&{cumulativeAmountRaw:t.toString()}}})();return e={descriptor:void 0,async signVoucher({channelId:n,cumulativeAmount:r,escrowContract:i,chainId:a,action:o=`voucher`}){let s=e?.descriptor;if(!s)throw Error(`session descriptor not available`);return KS({challenge:t,payload:{action:o,channelId:n,descriptor:s,cumulativeAmount:r.toString(),signature:await jj(p,f,{channelId:n,cumulativeAmount:r},i,a)},source:`did:pkh:eip155:${a}:${f.address}`})},source:`did:pkh:eip155:${p.chain.id}:${f.address}`},{tokenSymbol:l,tokenDecimals:u,explorerUrl:d,methods:[...g],credentialContext:_}},prepareCredentialRequest({challenge:e,headers:t}){e.intent===`session`&&(t.Accept=`text/event-stream`)},async handleResponse(t){if(t.challenge.intent!==`session`||!e)return!1;let{challenge:n,credential:r,response:i,fetchUrl:a,fetchInit:o,verbose:s}=t,{silent:c,confirmEnabled:l,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,shownKeys:p}=t,m=c?e=>{}:e=>process.stderr.write(e),h=HS(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(e.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${Z.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
234
+ `);t=s.pop();for(let t of s){if(!t.trim())continue;let i=lE(t);if(i)switch(i.type){case`message`:yield i.data;break;case`payment-need-voucher`:{if(!a||!l)break;let t=BigInt(i.data.requiredCumulative);k(t),a.cumulativeAmount=a.cumulativeAmount>t?a.cumulativeAmount:t;let r=await y.createCredential({challenge:l,context:{action:`voucher`,channelId:a.channelId,cumulativeAmountRaw:a.cumulativeAmount.toString()}}),o=await n(e,{method:`POST`,headers:{Accept:`text/event-stream`,[J.authorization]:r}});if(!o.ok)throw Error(`Voucher POST failed with status ${o.status}`);break}case`payment-receipt`:x(i.data),r?.(i.data)}}}}finally{u.releaseLock()}}return f()},async ws(t,i){if(!r)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let{onReceipt:c,protocols:l,signal:m}=i??{},g=new URL(t.toString()),b=new URL(g.toString());b.protocol===`ws:`&&(b.protocol=`http:`),b.protocol===`wss:`&&(b.protocol=`https:`),s=b.toString();let S=await n(b,m?{signal:m}:void 0);if(S.status!==402)throw Error(`Expected a 402 payment challenge from ${b}, received ${S.status} instead.`);let w=(await dj(DS(nS(S),[y],CS([y]).entries),i?.orderChallenges??e.orderChallenges))[0]?.challenge;if(!w)throw Error(`No payment challenge received from HTTP endpoint for this WebSocket URL. The server may not require payment or did not advertise a challenge.`);o=w;let O=await y.createCredential({challenge:w,context:{}});p=null,u=w,_=0n,v=BigInt(w.request.amount);let te=HS(O);d=te.payload.channelId;let A=new r(g,l);f=A;let j=ne(A),M=e=>{E(Error(e)),D(Error(e)),(A.readyState===fj.CONNECTING||A.readyState===fj.OPEN)&&A.close(pj,e)},re=e=>e.challengeId===w.id&&e.channelId===d,ie=new Promise((e,t)=>{let n=()=>{A.removeEventListener(`error`,r),j.emit(`open`,{type:`open`}),e()},r=()=>{A.removeEventListener(`open`,n),t(Error(`WebSocket connection to ${g} failed to open.`))};A.addEventListener(`open`,n,{once:!0}),A.addEventListener(`error`,r,{once:!0})});return A.addEventListener(`close`,e=>{f===A&&(f=null),u===w&&(u=null),d===te.payload.channelId&&(d=null),h=null,E(Error(`WebSocket closed before the payment flow completed.`)),D(Error(`WebSocket closed before the payment flow completed.`)),j.emit(`close`,{code:e.code??1e3,reason:e.reason??``,type:`close`,wasClean:!0})}),A.addEventListener(`error`,()=>{j.emit(`error`,{type:`error`})}),A.addEventListener(`message`,async e=>{let t=typeof e.data==`string`?e.data:void 0;if(!t)return;let n=pE(t);if(!n){j.emit(`message`,{data:t,type:`message`});return}switch(n.mpp){case`authorization`:break;case`message`:_+=1n,j.emit(`message`,{data:n.data,type:`message`});break;case`payment-close-ready`:if(!re(n.data)){M(`received mismatched payment-close-ready frame`);break}if(BigInt(n.data.spent)>(a?.cumulativeAmount??0n)){M(`received payment-close-ready beyond local voucher state`);break}x(n.data),c?.(n.data),ee(n.data),j.emit(`close`,{code:1e3,reason:`stream complete`,type:`close`});break;case`payment-error`:E(Error(n.message)),D(Error(n.message));break;case`payment-need-voucher`:{if(n.data.channelId!==d){M(`received mismatched payment-need-voucher frame`);break}let e=BigInt(n.data.requiredCumulative);try{k(e)}catch(e){M(e instanceof Error?e.message:`requested voucher amount exceeds local maxDeposit`);break}let t=(a?.cumulativeAmount??0n)>e?a?.cumulativeAmount??0n:e;a?.channelId===d&&(a.cumulativeAmount=t);let r=await y.createCredential({challenge:w,context:{action:`voucher`,channelId:d,cumulativeAmountRaw:t.toString()}});A.send(dE(r));break}case`payment-receipt`:if(!re(n.data)){M(`received mismatched payment-receipt frame`);break}if(h!==null&&n.data.txHash&&(n.data.acceptedCumulative!==h||n.data.spent!==h)){M(`received mismatched payment-close receipt frame`);break}x(n.data),c?.(n.data),T(n.data)}}),m&&m.addEventListener(`abort`,()=>{E(Error(`WebSocket payment flow aborted.`)),D(Error(`WebSocket payment flow aborted.`)),A.close()},{once:!0}),await ie,A.send(dE(O)),await C(),j.socket},async close(){let e=u??o,t=d??a?.channelId;if(!a?.opened)return;if(!e)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(!t)throw Error(`Cannot close session: no channel ID available. The session may not have been fully opened.`);if(f?.readyState===fj.OPEN){let n=p??await(async()=>(f.send(fE()),w()))(),r=BigInt(n.spent);if(r>(a.cumulativeAmount>l?a.cumulativeAmount:l))throw Error(`close-ready spent exceeds local voucher state`);let i=await y.createCredential({challenge:e,context:{action:`close`,channelId:t,cumulativeAmountRaw:r.toString()}}),o=r.toString();h=o;try{let n=C(n=>!!n.txHash&&n.challengeId===e.id&&n.channelId===t&&n.acceptedCumulative===o&&n.spent===o);f.send(dE(i));let r=await n;return f.close(),p=null,r}finally{h=null}}let r=await y.createCredential({challenge:e,context:{action:`close`,channelId:t,cumulativeAmountRaw:(()=>{let n=BigInt(O(e,t));if(n>a.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return k(n),n.toString()})()}});if(!s)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 i=await n(s,{method:`POST`,headers:{[J.authorization]:r}});if(!i.ok){let e=await i.text().catch(()=>``),t=(()=>{if(!e)return``;if(!i.headers.get(`Content-Type`)?.includes(`application/problem+json`))return e;try{return JSON.parse(e).detail??e}catch{return e}})(),n=i.headers.get(J.wwwAuthenticate)??``;throw Error(`Close request failed with status ${i.status}${t?`: ${t}`:``}${n?` [${J.wwwAuthenticate}: ${n}]`:``}`)}let c=i.headers.get(J.paymentReceipt);return c?sE(c):void 0}}}async function dj(e,t){let n=t;return n?n(e):e}var fj,pj,mj=I((()=>{dS(),tT(),kx(),YS(),VS(),vE(),lj(),fj={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},pj=3008})),hj=I((()=>{lj(),mj()}));function gj(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function _j(e){let t=D.encode(D.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return te.keccak256(t)}function vj(e){return Be.encodeForSigning(e)}function yj(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function bj(e,t){return te.keccak256(A.concat(vj(e),t.sender))}var xj=I((()=>{vE()})),Sj,Cj,wj,Tj,Ej=I((()=>{Sj=[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],Cj=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],wj={name:`descriptor`,type:`tuple`,components:Sj},Tj=[{type:`function`,name:`CLOSE_GRACE_PERIOD`,stateMutability:`view`,inputs:[],outputs:[{type:`uint64`}]},{type:`function`,name:`VOUCHER_TYPEHASH`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`function`,name:`open`,stateMutability:`nonpayable`,inputs:[{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`deposit`,type:`uint96`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`}],outputs:[{name:`channelId`,type:`bytes32`}]},{type:`function`,name:`settle`,stateMutability:`nonpayable`,inputs:[wj,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[wj,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[wj,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[wj],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[wj],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[wj],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:Sj},{name:`state`,type:`tuple`,components:Cj}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Cj}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Cj}]},{type:`function`,name:`computeChannelId`,stateMutability:`view`,inputs:[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`getVoucherDigest`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`domainSeparator`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`authorizedSigner`,type:`address`},{name:`salt`,type:`bytes32`},{name:`expiringNonceHash`,type:`bytes32`},{name:`deposit`,type:`uint96`}]},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`cumulativeAmount`,type:`uint96`},{name:`deltaPaid`,type:`uint96`},{name:`newSettled`,type:`uint96`}]},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`additionalDeposit`,type:`uint96`},{name:`newDeposit`,type:`uint96`}]},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`closeGraceEnd`,type:`uint256`}]},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`settledToPayee`,type:`uint96`},{name:`refundedToPayer`,type:`uint96`}]},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0}]}]}));function Dj(e,t){return{name:Pj,version:Fj,chainId:t,verifyingContract:e}}function Oj(e,t){return Ie.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function kj(e,t,n){return e.toLowerCase()===Ie.address.toLowerCase()?Oj(t,n):le({domain:Dj(e,t),types:Ij,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function Aj(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function jj(e,t){return Oe.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function Mj(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===Ie.address.toLowerCase())try{return await jj(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return Te(e,{account:t,domain:Dj(r,i),types:Ij,primaryType:`Voucher`,message:n})})(),o=Re.from(a);if(!Aj(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return Re.serialize(o)}function Nj(e,t,n,r){try{let i=Re.from(n.signature);if(!Aj(i.type)||Re.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=kj(e,t,n),o=Re.extractAddress({payload:a,signature:i});return Re.verify(i,{address:o,payload:a})&&iA(o,r)}catch{return!1}}var Pj,Fj,Ij,Lj=I((()=>{aA(),Pj=`TIP20 Channel Reserve`,Fj=`1`,Ij={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]}}));function Rj(e){return typeof e==`object`&&!!e}function zj(e){return typeof e==`string`&&de(e,{strict:!1})?e:void 0}function Bj(e){return zj(e.accessKeyAddress)}function Vj(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(A.random(8))%e)}function Hj(e){return Bj(e)??e.address}async function Uj(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return F(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function Wj(e,t){return await we(e,t)}function Gj(e,t,n=!1){let r=e.request.methodDetails,i=Rj(r)?zj(r.escrowContract)??zj(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!qj(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!qj(i,a)?i:a}function Kj(e,t,n,r){return KS({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function qj(e,t){return e.toLowerCase()===t.toLowerCase()}async function Jj(e,t,n,r,i,a=_E){let o=_j({...n,chainId:i,escrow:a}),s=QT(r),c=await Mj(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function Yj(e,t,n,r,i,a=_E){let o=await Jj(e,t,n,r,i,a);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature}}async function Xj(e,t,n){let r=Hj(t),i=n.escrow??`0x4d50500000000000000000000000000000000000`,a=n.operator??`0x0000000000000000000000000000000000000000`,o=A.random(32),s=QT(n.deposit),c=QT(n.initialAmount),l=ae({abi:Tj,functionName:`open`,args:[n.payee,a,n.token,s,o,r]}),u=await Wj(e,await Uj(e,{account:t,calls:[...n.prefixCalls??[],{to:i,data:l}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),d=Me.deserialize(u),f={authorizedSigner:r,expiringNonceHash:bj(yj({...n.feePayer?{feePayer:!0}:{},transaction:d}),{sender:t.address}),operator:a,payee:n.payee,payer:t.address,salt:o,token:n.token},p=_j({...f,chainId:n.chainId,escrow:i});return{action:`open`,type:`transaction`,channelId:p,transaction:u,signature:await Mj(e,t,{channelId:p,cumulativeAmount:c},i,n.chainId),descriptor:f,cumulativeAmount:c.toString(),authorizedSigner:f.authorizedSigner}}async function Zj(e,t,n,r,i,a,o=_E,s=[],c=n.token){let l=_j({...n,chainId:i,escrow:o}),u=QT(r);return{action:`topUp`,type:`transaction`,channelId:l,transaction:await Wj(e,await Uj(e,{account:t,calls:[...s,{to:o,data:ae({abi:Tj,functionName:`topUp`,args:[n,u]})}],feePayer:a,feeToken:c,validAfter:Vj()})),descriptor:n,additionalDeposit:u.toString()}}var Qj=I((()=>{YS(),xj(),Ej(),vE(),Lj()}));function $j(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function eM(e){return $j({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function tM(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(eM(t),t)},delete(t){e.delete(t)}}}function nM(e){return{...e,cumulativeAmount:e.cumulativeAmount.toString(),deposit:e.deposit.toString()}}function rM(e){return{...e,cumulativeAmount:BigInt(e.cumulativeAmount),deposit:BigInt(e.deposit)}}var iM=I((()=>{}));function aM(e){if(e<0n||e>cM)throw new X({reason:`amount exceeds uint96 range`})}async function oM(e,t,n=_E,r){return sM(await xe(e,{address:n,abi:Tj,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function sM(e){return aM(e.settled),aM(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}var cM,lM=I((()=>{hS(),Ej(),vE(),cM=2n**96n-1n}));function uM(e){return`cumulativeAmount`in e}function dM(e){if(uM(e))return BigInt(e.cumulativeAmount)}async function fM(e,t){t.opened?await e.store.set(t):await e.store.delete(eM(t)),e.notifyUpdate(t)}async function pM(e,t,n){let r=dM(n);if(r===void 0)return;let i=await e.store.get(t);i&&i.channelId.toLowerCase()===n.channelId.toLowerCase()&&(i.cumulativeAmount=i.cumulativeAmount>r?i.cumulativeAmount:r,n.action===`close`&&(i.opened=!1),await fM(e,i))}function mM(e){return e?.action!==void 0}function hM(e){return mM(e)&&e.descriptor!==void 0}function gM(e,t,n){let r=n===`additionalDeposit`?e.additionalDepositRaw:e.cumulativeAmountRaw,i=n===`additionalDeposit`?e.additionalDeposit:e.cumulativeAmount;if(r)return BigInt(r);if(i)return P(i,t)}function _M(e,t,n,r){let i=gM(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function vM(e){return typeof e==`object`&&!!e}function yM(e){return typeof e==`string`&&de(e,{strict:!1})?e:void 0}function bM(e){let t=e.request.methodDetails;return vM(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:yM(t.escrowContract),escrow:yM(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:yM(t.feeToken),operator:yM(t.operator),sessionSnapshot:Cx(t,Dx.sessionSnapshot)}:{}}function xM(e,t){if(typeof e==`string`&&de(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function SM(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function CM(e){return typeof e==`string`?e:void 0}async function wM(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,getClient:i}=e,a=bM(n),o=await i({chainId:a.chainId}),s=a.chainId??o.chain?.id;if(!s)throw Error(`No chainId configured for TIP-1034 session challenge.`);let c=Gj(n,r,t),l=xM(n.request.recipient,`recipient`),u=xM(n.request.currency,`currency`);return{amount:SM(n.request.amount),challenge:n,chainId:s,client:o,escrow:c,feePayer:a.feePayer,feeToken:a.feeToken,key:$j({payee:l,token:u,escrow:c,chainId:s}),operator:a.operator,payee:l,snapshot:a.sessionSnapshot,suggestedDepositRaw:CM(n.request.suggestedDeposit),token:u}}async function TM(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=oM}=e,o=_j({...r,chainId:i.chainId,escrow:i.escrow});EM({channelId:t,descriptor:r,expectedChannelId:o,payee:i.payee,payer:i.payer,authorizedSigner:i.authorizedSigner,token:i.token});let s=await a(n,o,i.escrow);if(s.deposit===0n)throw Error(`Channel ${o} cannot be reused (closed or not found on-chain).`);if(s.closeRequestedAt!==0)throw Error(`Channel ${o} cannot be reused (pending close request).`);return{channelId:o,state:s}}function EM(e){let{authorizedSigner:t,channelId:n,descriptor:r,expectedChannelId:i,payee:a,payer:o,token:s}=e;if(n&&n.toLowerCase()!==i.toLowerCase())throw Error(`context channelId does not match descriptor`);if(!qj(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!qj(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!qj(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!qj(gj(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function DM(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function OM(e){let{context:t,decimals:n,requestAmount:r,snapshot:i,settled:a}=e;if(i)return[BigInt(i.acceptedCumulative),BigInt(i.requiredCumulative),BigInt(i.spent)+r,a].reduce((e,t)=>t>e?t:e,0n);let o=gM(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function kM(e){let{account:t,client:n,readChannelState:r,snapshot:i}=e,a=i.highestVoucher;if(!a)throw Error(`session snapshot is missing its highest signed voucher`);if(a.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let o=BigInt(i.acceptedCumulative),s=BigInt(a.cumulativeAmount),c=BigInt(i.requiredCumulative),l=BigInt(i.deposit),u=BigInt(i.settled),d=BigInt(i.spent);if(s!==o)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(d>o)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(u>l)throw Error(`session snapshot settled amount exceeds deposit`);if(!Nj(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},gj(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await TM({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:Hj(t),token:i.descriptor.token},readChannelState:r}),p=[o,c,f.state.settled].reduce((e,t)=>t>e?t:e,0n);if(p>f.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:f.channelId,cumulativeAmount:p,deposit:f.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:d}}function AM(e,t){return qj(e.address,t.payer)?qj(Hj(e),gj(t)):!1}function jM(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(mM(r)){if(!hM(r))throw Error(`descriptor required for TIP-1034 session action`);return{type:`manual`,account:t,context:r,decimals:i,resolved:o}}if(!n&&r?.channelId&&!r.descriptor)throw Error(`descriptor required to reuse TIP-1034 channel`);let s=DM({context:r,snapshot:o.snapshot});return!n&&s&&AM(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&AM(t,n.descriptor)?{type:`voucher`,account:t,entry:n,maxDeposit:a,resolved:o}:{type:`open`,account:t,context:r,maxDeposit:a,resolved:o}}async function MM(e,t,n=!1){switch(e.type){case`open`:return PM(e,t,n);case`recover`:return FM(e,t);case`voucher`:return IM(e,t);case`manual`:return LM(e,t,n)}}async function NM(e,t){if(e)return await oA(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage})}async function PM(e,t,n){let{account:r,resolved:i}=e,a=zE({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await Xj(i.client,r,{chainId:i.chainId,deposit:a,escrow:i.escrow,feePayer:i.feePayer,feeToken:i.feeToken,initialAmount:i.amount,operator:i.operator,payee:i.payee,prefixCalls:await NM(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await fM(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function FM(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await TM({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:Hj(n),token:o.token}}),l=OM({context:r,decimals:i,requestAmount:o.amount,settled:c.state.settled,snapshot:o.snapshot});if(l>c.state.deposit)throw Error(`recovered voucher amount exceeds on-chain channel deposit`);VE(l,a);let u=await Jj(o.client,n,s,l,o.chainId,o.escrow);return await fM(t,{channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function IM(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;VE(a,e.maxDeposit);let o=await Jj(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await fM(t,r),o}async function LM(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=_j({...s,chainId:o.chainId,escrow:o.escrow});EM({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:Hj(r),token:o.token});let l=await RM({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await pM(t,o.key,l),l}async function RM(e,t){switch(e.context.action){case`open`:return zM(e);case`topUp`:return BM(e,t);case`voucher`:return VM(e);case`close`:return HM(e)}}async function zM(e){let{account:t,channelId:n,context:r,decimals:i,descriptor:a,resolved:o}=e;if(!r.transaction)throw Error(`transaction required for open action`);let s=_M(r,i,`cumulativeAmount`,`open`),c=await Jj(o.client,t,a,s,o.chainId,o.escrow);return{action:`open`,type:`transaction`,channelId:n,transaction:r.transaction,signature:c.signature,descriptor:a,cumulativeAmount:s.toString(),authorizedSigner:a.authorizedSigner}}async function BM(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=_M(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:Zj(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await NM(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function VM(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Jj(a.client,t,i,_M(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function HM(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Yj(a.client,t,i,_M(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}var UM,WM,GM,KM=I((()=>{kx(),Gx(),dA(),lM(),xj(),Lj(),Qj(),iM(),nD(),UM=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),WM=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),GM=Y.object({account:Y.optional(Y.custom()),autoSwap:Y.optional(Y.custom()),action:Y.optional(Y.enum([`open`,`topUp`,`voucher`,`close`])),channelId:Y.optional(WM),cumulativeAmount:Y.optional(Fx()),cumulativeAmountRaw:Y.optional(Y.string()),transaction:Y.optional(UM),descriptor:Y.optional(Y.custom()),additionalDeposit:Y.optional(Fx()),additionalDepositRaw:Y.optional(Y.string()),depositRaw:Y.optional(Y.string())})}));async function qM(e,t){let n=ZM.get(e)??new Map;ZM.set(e,n);let r=n.get(t),i,a=new Promise(e=>{i=e});return n.set(t,a),await r,()=>{i(),n.get(t)===a&&n.delete(t)}}function JM(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function YM(e,t,n){try{let r=e.response?.headers.get(J.paymentReceipt);if(r){let e=sE(r);if(e.challengeId===t.id&&JM(n,e))return!0}}catch{}return e.challenges?.some(e=>lD(e)?JM(n,uD(e)):!1)??!1}function XM(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a=6,escrow:o,getClient:s,maxDeposit:c,topUpAmount:l,onChannelUpdate:u,resolveAccount:d}=e,f=Yk({chain:Fe,getClient:s,rpcUrl:JD}),p=Wk({account:t}),m=c===void 0?void 0:P(c,a),h=l===void 0?void 0:P(l,a),g=i??tM(),_={store:g,notifyUpdate:e=>u?.(e)},v=async(e,t,n)=>{let r=p(e.client,t),i=t?.action?t.descriptor:n?.descriptor??DM({context:t,snapshot:e.snapshot})?.descriptor;return await d?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:gj(i)}:{}}})??r},y=async(e,t,n)=>jM({account:await v(e,t,n),entry:n,context:t,decimals:a,maxDeposit:m,resolved:e}),b=MT(qT,{canHandleChallenge:({challenge:e})=>lD(e),context:GM,async createCredential(e){let{challenge:t,context:i}=e,a=await wM({allowCustomEscrow:n,challenge:t,escrowOverride:o,getClient:f}),s=lw(e),c=()=>{};try{let e=!mM(i)&&i?.descriptor===void 0;e&&(c=await qM(g,a.key),s&&(await g.get(a.key))?.opened&&await s.prepare());let n=await g.get(a.key),o=await y(a,i,n);if(!e&&s&&o.type===`open`){c=await qM(g,a.key);let e=await g.get(a.key);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await s.prepare(),n=await g.get(a.key)),o=await y(a,i,n))}let l,u=s&&o.type===`open`?{store:{get:e=>g.get(e),async set(e){l=e},delete:e=>g.delete(e)},notifyUpdate(){}}:_,d=await Kj(t,await MM(o,u,sA(i?.autoSwap??r,lA)),a.chainId,o.account);if(s&&l){let e=l;s.settle=async n=>{let r=n.status===`accepted`||YM(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await g.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await g.set(e),_.notifyUpdate(e))}return!0}finally{c()}}}else c();return d}catch(e){throw c(),e}}}),x=async({challenge:e,channel:t,deposit:n,fetch:r,input:i,requiredCumulative:a})=>{let o=t.deposit>n?t.deposit:n,s=BE({deposit:o,maxDeposit:m,requiredCumulative:a,suggestedDeposit:e.request.suggestedDeposit===void 0?void 0:BigInt(e.request.suggestedDeposit),topUpAmount:h});s>0n&&await hD({additionalDeposit:s,challenge:e,channel:t,channelId:t.channelId,createSessionCredential:(e,t)=>b.createCredential({challenge:e,context:t}),fetch:r,input:i});let c=o+s;if(c===t.deposit)return;let l=await g.get(eM(t)),u=l?.channelId.toLowerCase()===t.channelId.toLowerCase()?l:t,d={...u,deposit:u.deposit>c?u.deposit:c};await g.set(d),_.notifyUpdate(d)};return tw(b,async({challenge:e,context:t,fetch:r,input:i})=>{if(!lD(e))return;let a=t===void 0?void 0:GM.parse(t);if(mM(a))return;let s=await wM({allowCustomEscrow:n,challenge:e,escrowOverride:o,getClient:f}),c=await g.get(s.key);if(!c?.opened)return;let l=s.snapshot?.channelId.toLowerCase()===c.channelId.toLowerCase()?s.snapshot:void 0,u=c.cumulativeAmount+iE(e),d=l?BigInt(l.requiredCumulative):u,p=d>u?d:u,m=l?BigInt(l.deposit):c.deposit,h=m>c.deposit?m:c.deposit;p<=h&&h===c.deposit||!AM(await v(s,a,c),c.descriptor)||await x({challenge:e,channel:c,deposit:h,fetch:r,input:i,requiredCumulative:p})}),ow(b,async({challenge:e,credential:t,fetch:r,headers:i,input:a,refetch:s,response:c,signal:l})=>{if(!lD(e))return c;if(!cE(c))return rE(HS(t).payload).action===`open`&&i.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await s?.()??c:c;let u=(await wM({allowCustomEscrow:n,challenge:e,escrowOverride:o,getClient:f})).key,d=await g.get(u),p={assertVoucherWithinLocalLimit:e=>VE(e,m),createSessionCredential:(e,t)=>b.createCredential({challenge:e,context:t}),fetch:r,getChannel:()=>d??null,async topUpIfNeeded({deposit:t,requiredCumulative:n}){d&&await x({challenge:e,channel:d,deposit:d.deposit>t?d.deposit:t,fetch:r,input:a,requiredCumulative:n})}};return ED({onNeedVoucher:t=>DD({challenge:e,driver:p,input:a},t),onReceipt(){},response:c,signal:l})})}var ZM,QM=I((()=>{aw(),pw(),kx(),YS(),NT(),Gk(),Zk(),dA(),YD(),YT(),xj(),vE(),Qj(),iM(),KM(),nD(),UD(),ZM=new WeakMap}));function $M(e,t){tN.set(e,t)}function eN(e){let t=tN.get(e);if(!t)throw Error(`Session manager internals are unavailable.`);return t}var tN,nN=I((()=>{tN=new WeakMap}));function rN(e){let t=null;return{wait(n=()=>!0){if(t)throw Error(`${e} wait already in progress`);return new Promise((e,r)=>{t={predicate:n,resolve:e,reject:r}})},settle(e){if(!t||!t.predicate(e))return;let n=t;t=null,n.resolve(e)},reject(e){if(!t)return;let n=t;t=null,n.reject(e)}}}function iN(e){let t=rN(`close-ready`),n=rN(`receipt`);return{waitForReceipt(e){return n.wait(e)},waitForCloseReady(){let n=e.getSocketSession()?.closeReadyReceipt;return n?Promise.resolve(n):t.wait()},settleReceipt(e){n.settle(e)},settleCloseReady(n){let r=e.getSocketSession();r&&r.challenge.id===n.challengeId&&r.channelId===n.channelId&&(r.closeReadyReceipt=n),t.settle(n)},rejectReceipt(e){n.reject(e)},rejectCloseReady(e){t.reject(e)}}}var aN=I((()=>{}));function oN(e){return e.method===Tx.tempo&&e.intent===Ex.charge}function sN(e){if(!oN(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function cN(e,t,n){if(!n)return t;let r={..._w(e instanceof Request?e.headers:void 0),..._w(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===J.paymentSession.toLowerCase())?t:{...t,headers:{...r,[J.paymentSession]:n}}}function lN(e){let t=e.decimals??6,n=e.webSocket??globalThis.WebSocket;return{decimals:t,fetch:e.fetch??globalThis.fetch.bind(globalThis),maxVoucherCumulative:e.maxDeposit===void 0?null:P(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:P(e.topUpAmount,t),WebSocket:n}}function uN(e){let t=e.allowCustomEscrow??!1,n=lN(e),r=Yk({chain:Fe,getClient:e.client?()=>e.client:e.getClient,rpcUrl:JD}),i=Wk({account:e.account}),a=qE(),o=iN({getSocketSession:()=>a.socketSession}),s=e.channelStore??tM(),c=new Set,l;async function u(e){let t=await s.get(e);if(t?.opened&&!c.has(t.channelId))return t}let d={async get(e){let t=await u(e);return t&&l&&(l.seenExisting.add(e),!l.committed&&!l.created.has(e)&&(l.resumed??=t)),t},async set(e){let t=eM(e);e.opened&&c.delete(e.channelId),l?.trackCreates&&!l.seenExisting.has(t)&&l.created.set(t,e),await s.set(e)},delete:e=>s.delete(e)};async function f(e){let t=eM(e);c.add(e.channelId),l?.seenExisting.delete(t),l?.resumed===e&&(l.resumed=void 0),await Promise.resolve(s.delete(t)).catch(()=>void 0)}async function p(){let e=l;if(e?.created.size){for(let[t,n]of e.created)c.add(n.channelId),await Promise.resolve(s.delete(t)).catch(()=>void 0);e.created.clear(),await j(e.committed??e.previous)}}function m(e){let t=Cx(e.request.methodDetails,Dx.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=l;if(!n?.created.size||!a.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&a.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=QE({channel:a.channel,spent:a.spent,state:a.state}),!0;return!1}function h(e){return AE(a,e)}function g(){let e=a.state.status===`active`?a.state:l?.committed?.state??l?.previous.state;return e?.status===`active`?e.units:0}function _(e){let t=l,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit||(t.resumed=void 0,t.committed=QE({channel:a.channel,spent:a.spent,state:a.state}))}let v=XM({account:e.account,allowCustomEscrow:t,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,decimals:n.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:d,onChannelUpdate(e){e.channelId!==a.channel?.channelId&&(a.spent=0n),a.channel=e,a.lastChallenge&&h({type:`activated`,challengeId:a.lastChallenge.id,entry:e,spent:a.spent.toString(),units:g()}),_(e)}});sw(v);let y=kA({account:e.account,getClient:e.client?()=>e.client:e.getClient}),b=hw({fetch:n.fetch,methods:[v],onChallenge:async(e,t)=>{if(!cD(e))return;let n=l,r=n&&n.challengesReceived>0&&e.id===a.lastChallenge?.id,i=r&&qx(e)===qx(a.lastChallenge);n&&n.challengesReceived++,!i&&(m(e)||(n?.created.size?await p():r&&await j(n.committed??n.previous)),a.lastChallenge=e,h({type:`challengeReceived`,challengeId:e.id}))}});function x(e,t){return v.createCredential({challenge:e,context:t})}function S(e){JE({maxVoucherCumulative:n.maxVoucherCumulative,receipt:e,runtime:a})}function C(e=a.state.status===`active`?a.state.units:0){!a.channel||!a.lastChallenge||a.state.status!==`active`&&a.state.status!==`withdrawable`&&a.state.status!==`closeRequested`&&h({type:`activated`,challengeId:a.lastChallenge.id,entry:a.channel,spent:a.spent.toString(),units:e})}async function w(t){let n=t.headers.get(J.paymentSessionSnapshot);if(!n)return;let o=bE(n),s=await r({chainId:o.chainId}),c=i(s),{entry:l,spent:u}=await kM({account:await e.resolveAccount?.({account:c,chainId:o.chainId,operation:{authority:gj(o.descriptor),kind:`authorizePaymentChannel`}})??c,client:s,snapshot:o});return k(l.cumulativeAmount),await Promise.resolve(d.set(l)).catch(()=>void 0),a.channel=l,a.spent=u,l}async function T(t,r){if(!e.bootstrap||a.channel?.opened)return;let i=t instanceof Request?t.headers:void 0,{body:o,method:s,...c}=r??{},l=t instanceof Request?t.url:t,u={...c,method:`HEAD`,headers:{..._w(i),..._w(r?.headers),[J.acceptPayment]:`${Tx.tempo}/${Ex.charge}`}};try{let e=await n.fetch(l,u);if(e.status!==402)return await w(e);let t=nS(e).find(oN);if(!t||!sN(t))return;let r=await y.createCredential({challenge:t,context:{}}),i=await n.fetch(l,{...u,headers:{..._w(u.headers),[J.authorization]:r}});return i.ok?await w(i):void 0}catch{return}}function ee(e,t){let n=a.socketSession;return XE({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:a.channel?.channelId===t?a.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:a.spent,tickCost:n?.tickCost})}function E(e,t){let n=uD(t);if(!n)return;if(_j({...n.descriptor,chainId:n.chainId,escrow:n.escrow}).toLowerCase()!==n.channelId.toLowerCase())throw Error(`close snapshot descriptor does not match its channel ID`);if(n.channelId.toLowerCase()!==e.channelId.toLowerCase())throw Error(`close snapshot channel ID does not match local session`);if(n.chainId!==e.chainId||n.escrow.toLowerCase()!==e.escrow.toLowerCase())throw Error(`close snapshot payment scope does not match local session`);let r=BigInt(n.acceptedCumulative),i=BigInt(n.spent);if(r<0n||i<0n)throw Error(`close snapshot amounts must not be negative`);if(i>r)throw Error(`close snapshot spent exceeds accepted cumulative amount`);if(r>e.cumulativeAmount)throw Error(`close snapshot accepted cumulative exceeds local voucher state`);return{acceptedCumulative:r,spent:i}}function D(e,t){let n=E(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(a.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>a.spent&&(a.spent=i),n}function O(e,t=e.challenge,n=!1){let r=(n?D(e,t):E(e.channel,t))?.acceptedCumulative??ee(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return k(r),r.toString()}function k(e){FE({cumulativeAmount:e,maxVoucherCumulative:n.maxVoucherCumulative})}async function te(e){let{knownDeposit:t,...r}=e,i=await hD({...r,channel:a.channel,createSessionCredential:x,fetch:n.fetch});S(i);let o=oD({additionalDeposit:e.additionalDeposit,channel:a.channel,channelId:e.channelId,challengeId:a.lastChallenge?.id,currentState:a.state,knownDeposit:t,receipt:i,spent:a.spent});return o?.channel&&a.lastChallenge&&(await d.set(o.channel),h({type:`activated`,challengeId:a.lastChallenge.id,entry:o.channel,spent:a.spent.toString(),units:g()}),_(o.channel)),i}async function A(e){let t=a.channel?.channelId===e.channelId?a.channel.deposit:0n,r=t>e.deposit?t:e.deposit,i=BE({deposit:r,maxDeposit:n.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:n.topUpAmount});i!==0n&&await te({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:r})}async function ne(e,t){let n=ZE({channel:a.channel,channelId:e,challengeId:a.lastChallenge?.id,cumulativeAmount:t,spent:a.spent,state:a.state});n&&a.channel&&(h({type:`activated`,challengeId:n.challengeId,entry:a.channel,spent:n.spent,units:n.units}),await s.set(a.channel))}async function j(e){let t=$E(e,a.channel);a.channel=t.channel,a.spent=t.spent,a.state=t.state,a.channel?.opened&&await s.set(a.channel)}function M(e){let t=e.headers.get(J.paymentReceipt),n=t?sE(t):null;return S(n),Object.assign(e,{receipt:n,challenge:a.lastChallenge,channelId:a.channel?.channelId??null,cumulative:a.channel?.cumulativeAmount??0n})}async function re(e,t){if(l)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a.lastUrl=e;let r=QE({channel:a.channel,spent:a.spent,state:a.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:r,seenExisting:new Set,resumed:void 0,trackCreates:!1};l=i;try{await T(e,t),i.trackCreates=!0;let o=cN(e,t,a.channel?.opened?a.channel.channelId:void 0),s=!r.channel?.opened;async function c(){let n=i.resumed;return!s||!n?!1:(s=!1,await f(n),o=cN(e,t,void 0),!0)}for(;;){let t;try{t=await b(e,o)}catch(e){if(i.created.size?await p():await j(i.committed??r),await c())continue;throw e}let s=M(t),l=!1;if(s.status===402){let t=await _D({input:e,init:o,response:s,createSessionCredential:x,fetch:n.fetch,getChannel:()=>a.channel,restoreCumulative:ne,setChallenge(e){a.lastChallenge=e},topUpIfNeeded:A});t&&(l=!0,s=M(t))}if(!l&&!s.ok&&!s.receipt){if(i.created.size?await p():await j(i.committed??r),await c())continue;return s}return s}}finally{l=void 0}}async function ie(e){let t=await yD({createSessionCredential:x,fetch:n.fetch,getMinimumSpent:()=>a.spent,lastUrl:a.lastUrl,resolveSignedCloseAmount:t=>O(e,t,!0),signedCloseAmount:O(e),setChallenge(e){a.lastChallenge=e},target:e});return t&&(C(),h({type:`closeStarted`}),h({type:`closed`,receipt:t})),t}let ae={createSessionCredential:x,doFetch:re,fetch:n.fetch,getChannel:()=>a.channel,getChallenge:()=>a.lastChallenge,assertVoucherWithinLocalLimit:k,acceptReceipt(e){S(e)},topUpIfNeeded:A},oe={get channelId(){return a.channel?.channelId},get cumulative(){return a.channel?.cumulativeAmount??0n},get opened(){return a.channel?.opened??!1},get state(){return a.state},fetch:re,async topUp(e){let t=aD({amount:e,assertVoucherWithinLocalLimit:k,channel:a.channel,decimals:n.decimals,lastChallenge:a.lastChallenge,lastUrl:a.lastUrl});return te({additionalDeposit:t.additionalDeposit,challenge:t.challenge,channelId:t.channelId,input:t.input})},async sse(e,t){return bD(e,t,ae)},async ws(e,t){if(!n.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let r=pD(e),i=t?.signal?{signal:t.signal}:void 0;await T(r,i);let s=a.channel?.opened?a.channel.channelId:void 0,{challenge:c,credential:l,httpUrl:u,wsUrl:d}=await kD({async createSessionCredential(e,t){return a.lastChallenge=e,await rw(v,{challenge:e,context:t,fetch:n.fetch,input:r}),x(e,t)},fetch:n.fetch,input:e,onProbeUrl(e){a.lastUrl=e.toString()},probeInit:cN(r,i,s),signal:t?.signal});return a.lastChallenge=c,PD({challenge:c,credential:l,httpUrl:u,WebSocket:n.WebSocket,wsUrl:d,options:t,createSessionCredential:x,getChannel:()=>a.channel,setSocketSession(e){a.socketSession=e},async refreshChallenge(){let e=await OD({fetch:n.fetch,input:u,probeInit:cN(u,i,a.channel?.opened?a.channel.channelId:void 0),signal:t?.signal});return a.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:k,acceptReceipt:S,rejectCloseReady:o.rejectCloseReady,rejectReceipt:o.rejectReceipt,settleCloseReady:o.settleCloseReady,settleReceipt:o.settleReceipt,topUpIfNeeded:A,waitForReceipt:o.waitForReceipt})},async close(){let e=a.socketSession,t=HE({channel:a.channel,currentSocket:e,lastChallenge:a.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===BD.OPEN){let r=await eD({activeSocket:n,createSessionCredential:x,currentSocket:e,spent:a.spent,target:t,waitForCloseReady:o.waitForCloseReady,waitForReceipt:o.waitForReceipt});return C(),h({type:`closeStarted`}),h({type:`closed`,receipt:r}),r}return ie(t)}};return $M(oe,{consumeSseResponse(e,t,n){return xD(e,t,n,ae)},rehydrate({channel:e,challenge:t,input:n,spent:r}){if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!cD(t))throw Error(`Cannot restore session: challenge is not tempo/session.`);if(r<0n)throw Error(`Cannot restore session: spent must not be negative.`);if(r>e.cumulativeAmount)throw Error(`Cannot restore session: spent exceeds local voucher state.`);k(e.cumulativeAmount);let i=E(e,t),o=i&&i.spent>r?i.spent:r;a.lastUrl=n,a.lastChallenge=t,a.channel=e,a.spent=o,h({type:`challengeReceived`,challengeId:t.id}),h({type:`activated`,challengeId:t.id,entry:e,spent:o.toString(),units:0})}}),oe}var dN=I((()=>{dS(),tT(),aw(),pw(),kx(),Gk(),Zk(),jA(),YD(),iM(),KM(),QM(),xj(),vE(),DE(),nN(),aN(),nD(),UD(),(function(e){e.serializeSnapshot=yE,e.deserializeSnapshot=bE})(uN||={})}));function fN(e){return e instanceof Date?e:new Date(e)}function pN(e){let t=e.getTime();if(!Number.isFinite(t))throw new X({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new X({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new X({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function mN(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new X({reason:`periodCount is invalid`});let t=MN[e.periodUnit];if(t===void 0)throw new X({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>jN)throw new X({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new X({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function hN(e){let{challengeExpires:t,request:n}=e;mN(n);let r=pN(fN(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new X({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function gN(e){let t=ON(e.currency,`currency`),n=ON(e.recipient,`recipient`);return[{address:t,selector:AN,recipients:[n]}]}async function _N(e){let{accessKey:t,account:n,chainId:r,request:i}=e;if(typeof n.sign!=`function`)return;let a=yN({accessKey:t,chainId:r,request:i}),o=await n.sign({hash:Le.getSignPayload(a)}),s=Re.from(o);if(s.type===`keychain`||s.type===`multisig`)throw new X({reason:`keyAuthorization must use a primitive signature`});return Le.from(a,{signature:o})}function vN(e){let{accessKey:t,chainId:n,payload:r,request:i}=e;if(r.type!==`keyAuthorization`)throw new X({reason:`invalid keyAuthorization payload`});let a=bN(r.signature),o=xN(a);return SN({accessKey:t,authorization:a,chainId:n}),CN(a,i),TN(wN(a),i),EN(a.scopes,i),{authorization:a,source:{address:DN(a,o),chainId:n}}}function yN(e){let{accessKey:t,chainId:n,request:r}=e;return Le.from({address:ON(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(n),expiry:pN(fN(r.subscriptionExpires)),limits:[{token:ON(r.currency,`currency`),limit:BigInt(r.amount),period:mN(r)}],scopes:gN(r),type:t.keyType})}function bN(e){try{return Le.deserialize(e)}catch(e){throw e instanceof Le.InvalidSignatureTypeError?new X({reason:`keyAuthorization must use a primitive signature`}):new X({reason:`invalid keyAuthorization payload`})}}function xN(e){let t=e.signature;if(!t)throw new X({reason:`keyAuthorization must use a primitive signature`});return t}function SN(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new X({reason:`keyAuthorization chainId mismatch`});if(t){if(!fe(n.address,ON(t.accessKeyAddress,`accessKeyAddress`)))throw new X({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new X({reason:`keyAuthorization key type mismatch`})}}function CN(e,t){if(hN({request:t}),e.expiry!==pN(fN(t.subscriptionExpires)))throw new X({reason:`keyAuthorization expiry mismatch`})}function wN(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new X({reason:`keyAuthorization must contain exactly one token limit`});return t}function TN(e,t){if(!fe(e.token,ON(t.currency,`currency`)))throw new X({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new X({reason:`keyAuthorization amount mismatch`});if(e.period!==mN(t))throw new X({reason:`keyAuthorization period mismatch`})}function EN(e,t){if(!e||e.length!==1)throw new X({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=ON(t.currency,`currency`),r=ON(t.recipient,`recipient`),i=new Set;for(let t of e){if(!fe(t.address,n))throw new X({reason:`keyAuthorization call target mismatch`});let e=kN(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new X({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new X({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!fe(t.recipients[0],r))throw new X({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new X({reason:`keyAuthorization must allow transferWithMemo`})}function DN(e,t){let n=Le.getSignPayload(e);try{let e=Re.extractAddress({payload:n,signature:t});if(!Re.verify(t,{address:e,payload:n}))throw new X({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof X?e:new X({reason:`keyAuthorization signature is invalid`})}}function ON(e,t){if(!de(e))throw new X({reason:`${t} must be an address`});return e.toLowerCase()}function kN(e){return typeof e==`string`?e.toLowerCase():``}var AN,jN,MN,NN=I((()=>{hS(),AN=`0x95777d59`,jN=(1n<<64n)-1n,MN={dev_second:1n,day:86400n,week:604800n}}));function PN(e={}){let t=Yk({chain:ge,getClient:e.getClient,rpcUrl:JD}),n=Wk({account:e.account});return MT(JT,{context:LN,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??WD.testnet,o=await t({chainId:a}),s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");IN(r.request),await e.validateRequest?.(r.request);let l=await FN(o,{accessKey:c,account:s,chainId:a,request:r.request}),u=vN({accessKey:c,chainId:a,payload:{signature:Le.serialize(l),type:`keyAuthorization`},request:r.request});if(!fe(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return KS({challenge:r,payload:{signature:Le.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function FN(e,t){let{accessKey:n,account:r,chainId:i,request:a}=t,o=await _N({accessKey:n,account:r,chainId:i,request:a});if(o)return o;let s=await e.request({method:`wallet_authorizeAccessKey`,params:[{address:n.accessKeyAddress,expiry:pN(fN(a.subscriptionExpires)),keyType:n.keyType,limits:[{token:a.currency,limit:A.fromNumber(BigInt(a.amount)),period:mN(a)}],scopes:gN(a)}]});return Le.fromRpc(s.keyAuthorization)}function IN(e){mN(e),pN(fN(e.subscriptionExpires))}var LN,RN=I((()=>{YS(),NT(),Gk(),Zk(),Gx(),YD(),YT(),NN(),LN=Y.object({accessKey:Y.optional(Y.custom()),account:Y.optional(Y.custom())})}));function zN(e={}){return[kA(e),BN(e)]}var BN,VN,HN=I((()=>{hj(),QM(),dN(),jA(),RN(),BN=Object.assign(XM,{manager:uN}),VN=Object.assign(uj,{method:sj}),(function(e){e.charge=kA,e.common=zN,e.session=BN,e.sessionLegacy=VN,e.subscription=PN})(zN||={})})),UN=I((()=>{jA(),HN(),hj(),RN(),QM(),dN()})),WN=Ke({orderTempoChargeChallengesByBalance:()=>KN,readTempoKeystore:()=>fP,resolveTempoAccount:()=>pP,tempo:()=>qN});async function GN(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}async function KN(e,t){let n=[],r=[];for(let[t,i]of e.entries())eP(i)&&(n.push(t),r.push(i));if(r.length<2)return[...e];let i=await tP(t).catch(()=>void 0);if(!i)return[...e];let a=await Promise.all(r.map(async(e,t)=>({challenge:e,index:t,score:await nP(e,i)})));a.sort((e,t)=>xP.indexOf(e.score)-xP.indexOf(t.score)||e.index-t.index);let o=[...e];for(let[e,t]of n.entries())o[t]=a[e].challenge;return o}function qN(){let e;return Nk({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:t,options:n,methodOpts:r}){let i=AO(n.account),a=t.request,o=a.currency,s=$N(r),c=oP({autoSwap:s.autoSwap??n.autoSwap,payWith:s.payWith??n.payWith,slippage:s.slippage??n.slippage,tokenIn:s.tokenIn}),l=o??``,u=a.decimals??6,d,f,p,m=!1,h=process.env.MPPX_PRIVATE_KEY?.trim()||(aO(i)?void 0:await jO(i).get());if(!h&&aO(i)&&mP()){m=!0;let e=pP(i);if(e){let r=lO(n.rpcUrl,{network:n.network});p=M({chain:await dO({network:n.network,rpcUrl:r}),transport:ue(r)}),iP({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let i=o?await hO(p,o,e.wallet_address).catch(()=>void 0):void 0;l=i?.symbol??o??``,u=i?.decimals??a.decimals??6}}else if(h)f=he(h);else{let e=gP();if(e){let t=await jO(e).get();t&&(f=he(t))}if(!f)throw n.account?new L({code:`ACCOUNT_NOT_FOUND`,message:`Account "${i}" not found.`,exitCode:69}):new L({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!m&&f){let e=lO(n.rpcUrl,{network:n.network});p=M({chain:await dO({network:n.network,rpcUrl:e}),transport:ue(e)}),iP({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let r=o?await hO(p,o,f.address).catch(()=>void 0):void 0;l=r?.symbol??o??``,u=r?.decimals??a.decimals??6}if(m)return{tokenSymbol:l,tokenDecimals:u,explorerUrl:d,methods:[],async createCredential(e){let t=e.headers.get(`www-authenticate`);if(!t)throw Error(`No WWW-Authenticate header in 402 response.`);return hP(t)}};if(!f||!p)throw new L({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let g=zN({account:f,...s.allowCustomEscrow===void 0?{}:{allowCustomEscrow:s.allowCustomEscrow},getClient:()=>p,...c===void 0?{}:{autoSwap:c},maxDeposit:(()=>{if(t.intent!==`session`)return;let e=t.request.suggestedDeposit,n=(s.deposit===void 0?void 0:String(s.deposit))??e??(mO(p.chain)?`10`:void 0);if(!n)throw new L({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return n})()}),_=(()=>{if(!s.channel)return;let e=s.channel,t=cP(e);return{channelId:e,...t!==void 0&&{cumulativeAmountRaw:t.toString()}}})();return e={descriptor:void 0,async signVoucher({channelId:n,cumulativeAmount:r,escrowContract:i,chainId:a,action:o=`voucher`}){let s=e?.descriptor;if(!s)throw Error(`session descriptor not available`);return KS({challenge:t,payload:{action:o,channelId:n,descriptor:s,cumulativeAmount:r.toString(),signature:await Mj(p,f,{channelId:n,cumulativeAmount:r},i,a)},source:`did:pkh:eip155:${a}:${f.address}`})},source:`did:pkh:eip155:${p.chain.id}:${f.address}`},{tokenSymbol:l,tokenDecimals:u,explorerUrl:d,methods:[...g],credentialContext:_}},prepareCredentialRequest({challenge:e,headers:t}){e.intent===`session`&&(t.Accept=`text/event-stream`)},async handleResponse(t){if(t.challenge.intent!==`session`||!e)return!1;let{challenge:n,credential:r,response:i,fetchUrl:a,fetchInit:o,verbose:s}=t,{silent:c,confirmEnabled:l,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,shownKeys:p}=t,m=c?e=>{}:e=>process.stderr.write(e),h=HS(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(e.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${Z.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
235
235
  `}${Z.dim(`Channel opened ${h.payload.channelId}`)}${t}\n`)}else m(`${l?``:`
236
- `}${Z.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(J.paymentReceipt);if(w)try{let e=JSON.parse(O.toString(w));JN(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&cP(v,S),s>=1&&qN(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
237
- `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await YN(C,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:S,tickCost:x,fetchUrl:a,fetchInit:o,session:e,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await WN(C),v&&y&&b&&(l&&m(`
238
- `),l&&!await t.confirm(`Close channel?`,!0)?s>=1&&m(`${Z.dim(`Kept channel open.`)}\n`):await XN({channelId:v,cumulativeAmount:S,escrowContract:y,chainId:b,fetchUrl:a,fetchInit:o,session:e,info:m,verbose:s,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,confirmEnabled:l}))),!0},formatReceiptField(e,t){(e===`reference`||e===`txHash`)&&typeof t==`string`&&t.startsWith(`0x`)}})}function qN(e,t){t.info(`${t.prefix??``}${Z.bold(Z.green(`Payment Receipt`))}\n`);let n=[],r=e.channelId&&e.reference&&e.channelId===e.reference,i=new Set([`acceptedCumulative`,`spent`]);for(let[a,o]of Object.entries(e)){if(o===void 0||t.shownKeys.has(a)||a===`reference`&&r)continue;let e=t.handler.formatReceiptField?.(a,o);e===void 0?i.has(a)&&typeof o==`string`?n.push([a,`${o} ${Z.dim(`(${sO(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,tO(`${t.explorerUrl}/tx/${o}`,o)]):n.push([a,String(o)]):n.push([a,e])}n.sort(([e],[t])=>e.localeCompare(t));let a=Math.max(...n.map(([e])=>e.length));for(let[e,r]of n)t.info(` ${Z.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
239
- `)}function JN(e,t){if(typeof e.acceptedCumulative!=`string`)return;let n=BigInt(e.acceptedCumulative),r=typeof e.spent==`string`?BigInt(e.spent):0n;if(r>n)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(n>t)throw Error(`receipt accepted cumulative exceeds locally signed voucher amount`);if(r>t)throw Error(`receipt spent exceeds locally signed voucher amount`)}async function YN(e,t){let n=t.cumulativeAmount,r=e.body?.getReader();if(!r)throw Error(`No response body`);let i=new TextDecoder,a=``,o=``,s=t.verbose?await ZN():void 0,c=(()=>{if(!s||!Z.isColorSupported)return;let e=e=>Math.max(0,Math.min(255,Math.round(e))),t=.299*s.r+.587*s.g+.114*s.b<128?1:-1,n=n=>r=>`\x1b[48;2;${e(s.r+n*t)};${e(s.g+n*t)};${e(s.b+n*t)}m${r}\x1b[49m`;return[n(12),n(24)]})(),l=0,u=e=>{if(c){let t=c[l%c.length];process.stdout.write(e.replace(/[^\n]+/g,e=>t(e))),l++}else process.stdout.write(e)},d=async e=>{for(let r of e){if(r.startsWith(`event: `)){o=r.slice(7).trim();continue}if(!r.startsWith(`data: `)){r===``&&(o=``);continue}let e=r.slice(6);if(e.trim()!==`[DONE]`){if(o===`payment-need-voucher`&&t.channelId&&t.escrowContract&&t.chainId){try{let r=JSON.parse(e);if(r.channelId!==t.channelId)throw Error(`payment-need-voucher channelId does not match current session`);let i=BigInt(r.requiredCumulative);if(i>n+t.tickCost)throw Error(`payment-need-voucher exceeds next locally billable amount`);n=n>i?n:i;let a=await t.session.signVoucher({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId});await globalThis.fetch(t.fetchUrl,{method:`POST`,headers:{[J.authorization]:a}})}catch(e){t.info(Z.dim(Z.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{qN(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
236
+ `}${Z.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(J.paymentReceipt);if(w)try{let e=JSON.parse(O.toString(w));YN(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&lP(v,S),s>=1&&JN(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
237
+ `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await XN(C,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:S,tickCost:x,fetchUrl:a,fetchInit:o,session:e,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await GN(C),v&&y&&b&&(l&&m(`
238
+ `),l&&!await t.confirm(`Close channel?`,!0)?s>=1&&m(`${Z.dim(`Kept channel open.`)}\n`):await ZN({channelId:v,cumulativeAmount:S,escrowContract:y,chainId:b,fetchUrl:a,fetchInit:o,session:e,info:m,verbose:s,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,confirmEnabled:l}))),!0},formatReceiptField(e,t){(e===`reference`||e===`txHash`)&&typeof t==`string`&&t.startsWith(`0x`)}})}function JN(e,t){t.info(`${t.prefix??``}${Z.bold(Z.green(`Payment Receipt`))}\n`);let n=[],r=e.channelId&&e.reference&&e.channelId===e.reference,i=new Set([`acceptedCumulative`,`spent`]);for(let[a,o]of Object.entries(e)){if(o===void 0||t.shownKeys.has(a)||a===`reference`&&r)continue;let e=t.handler.formatReceiptField?.(a,o);e===void 0?i.has(a)&&typeof o==`string`?n.push([a,`${o} ${Z.dim(`(${cO(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,nO(`${t.explorerUrl}/tx/${o}`,o)]):n.push([a,String(o)]):n.push([a,e])}n.sort(([e],[t])=>e.localeCompare(t));let a=Math.max(...n.map(([e])=>e.length));for(let[e,r]of n)t.info(` ${Z.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
239
+ `)}function YN(e,t){if(typeof e.acceptedCumulative!=`string`)return;let n=BigInt(e.acceptedCumulative),r=typeof e.spent==`string`?BigInt(e.spent):0n;if(r>n)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(n>t)throw Error(`receipt accepted cumulative exceeds locally signed voucher amount`);if(r>t)throw Error(`receipt spent exceeds locally signed voucher amount`)}async function XN(e,t){let n=t.cumulativeAmount,r=e.body?.getReader();if(!r)throw Error(`No response body`);let i=new TextDecoder,a=``,o=``,s=t.verbose?await QN():void 0,c=(()=>{if(!s||!Z.isColorSupported)return;let e=e=>Math.max(0,Math.min(255,Math.round(e))),t=.299*s.r+.587*s.g+.114*s.b<128?1:-1,n=n=>r=>`\x1b[48;2;${e(s.r+n*t)};${e(s.g+n*t)};${e(s.b+n*t)}m${r}\x1b[49m`;return[n(12),n(24)]})(),l=0,u=e=>{if(c){let t=c[l%c.length];process.stdout.write(e.replace(/[^\n]+/g,e=>t(e))),l++}else process.stdout.write(e)},d=async e=>{for(let r of e){if(r.startsWith(`event: `)){o=r.slice(7).trim();continue}if(!r.startsWith(`data: `)){r===``&&(o=``);continue}let e=r.slice(6);if(e.trim()!==`[DONE]`){if(o===`payment-need-voucher`&&t.channelId&&t.escrowContract&&t.chainId){try{let r=JSON.parse(e);if(r.channelId!==t.channelId)throw Error(`payment-need-voucher channelId does not match current session`);let i=BigInt(r.requiredCumulative);if(i>n+t.tickCost)throw Error(`payment-need-voucher exceeds next locally billable amount`);n=n>i?n:i;let a=await t.session.signVoucher({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId});await globalThis.fetch(t.fetchUrl,{method:`POST`,headers:{[J.authorization]:a}})}catch(e){t.info(Z.dim(Z.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{JN(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
240
240
 
241
241
  `})}catch{}o=``;continue}if(e.length===0)u(`
242
242
  `);else try{let t=JSON.parse(e);u(t.token??t.choices?.[0]?.delta?.content??e)}catch{u(e)}o=``}}};for(;;){let{done:e,value:t}=await r.read();if(e)break;a+=i.decode(t,{stream:!0});let n=a.split(`
243
- `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await XN({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId,fetchUrl:t.fetchUrl,fetchInit:t.fetchInit,session:t.session,info:t.info,verbose:t.verbose,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,confirmEnabled:!1})}async function XN(e){let t=await e.session.signVoucher({channelId:e.channelId,cumulativeAmount:e.cumulativeAmount,escrowContract:e.escrowContract,chainId:e.chainId,action:`close`}),n=await globalThis.fetch(e.fetchUrl,{...e.fetchInit,headers:{...gw(e.fetchInit.headers),Authorization:t}});if(n.ok){if(lP(e.channelId),e.verbose>=1){let t=n.headers.get(J.paymentReceipt),r;if(t)try{let e=JSON.parse(O.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${Z.dim(tO(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${Z.dim(`Channel closed.`)} ${Z.dim(`Spent ${sO(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${Z.dim(Z.yellow(`Channel close failed`))} ${Z.dim(`(${n.status})`)}\n`),e.info(`${Z.dim(` channelId: ${e.channelId}`)}\n${Z.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${Z.dim(` escrowContract: ${e.escrowContract}`)}\n${Z.dim(` chainId: ${e.chainId}`)}\n${Z.dim(` response: ${t||`(empty)`}`)}\n`)}}function ZN(e=100){return!process.stdin.isTTY||!process.stdout.isTTY?Promise.resolve(void 0):new Promise(t=>{let n=process.stdin.isRaw,r=``,i=()=>{clearTimeout(a),process.stdin.removeListener(`data`,o),process.stdin.isTTY&&process.stdin.setRawMode(n??!1),process.stdin.pause()},a=setTimeout(()=>{i(),t(void 0)},e),o=e=>{r+=e.toString();let n=r.match(/\x1b\]11;rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!n)return;i();let a=e=>Number.parseInt(e.slice(0,2),16);t({r:a(n[1]),g:a(n[2]),b:a(n[3])})};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,o),process.stdout.write(`\x1B]11;?\x07`)})}function QN(e){return nP(vP,e,yP)}function $N(e){return e.method===`tempo`&&e.intent===`charge`}async function eP(e){let t=kO(e.options.account),n=process.env.MPPX_PRIVATE_KEY?.trim()||(iO(t)?void 0:await AO(t).get()),r;if(n)r=he(n).address;else if(iO(t)&&pP())r=fP(t)?.wallet_address;else{let e=hP();if(e){let t=await AO(e).get();t&&(r=he(t).address)}}if(!r)return;let i=cO(e.options.rpcUrl,{network:e.options.network}),a=ne({chain:await uO({network:e.options.network,rpcUrl:i}),transport:ue(i)});return{account:r,client:a}}async function tP(e,t){let n=e.request,r=n.currency,i=n.amount;if(typeof r!=`string`||typeof i!=`string`)return`unsupported`;let a=n.methodDetails?.chainId;if(a&&t.client.chain?.id&&a!==t.client.chain.id)return`unsupported`;let o=BigInt(i);if(o===0n)return`payable`;let s=await ke.token.getBalance(t.client,{account:t.account,token:r}).then(e=>e.amount).catch(()=>void 0);return s===void 0?`unknownBalance`:s>=o?`payable`:`insufficientBalance`}function nP(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function rP(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new L({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function iP(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function aP(e){let t=iP(e.tokenIn)??iP(e.payWith);if(!(!e.autoSwap&&!t&&e.slippage===void 0)){if(e.autoSwap===!1&&!t&&e.slippage===void 0)return!1;if(e.slippage!==void 0&&(!Number.isFinite(e.slippage)||e.slippage<0))throw Error(`Invalid CLI options (slippage: expected a non-negative number)`);return{...t?{tokenIn:t}:{},...e.slippage===void 0?{}:{slippage:e.slippage}}}}function oP(){return s.join(process.env.XDG_CONFIG_HOME||s.join(y.homedir(),`.config`),`mppx`,`channels`)}function sP(t){try{let n=e.readFileSync(s.join(oP(),t),`utf-8`).trim();return n?BigInt(n):void 0}catch{return}}function cP(t,n){let r=oP();e.mkdirSync(r,{recursive:!0}),e.writeFileSync(s.join(r,t),n.toString(),`utf-8`)}function lP(t){try{e.unlinkSync(s.join(oP(),t))}catch{}}function uP(){return y.platform()===`darwin`?s.join(y.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):s.join(process.env.XDG_DATA_HOME||s.join(y.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function dP(){try{let t=e.readFileSync(uP(),`utf-8`),n=[],r;for(let e of t.split(`
244
- `)){let t=e.trim();if(t===`[[keys]]`){r?.wallet_address&&n.push(r),r={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!r)continue;let i=t.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?r.wallet_type=o:a===`wallet_address`?r.wallet_address=o:a===`chain_id`&&(r.chain_id=Number.parseInt(o,10))}return r?.wallet_address&&n.push(r),n}catch{return[]}}function fP(e){let t=dP();if(t.length===0)return;let n=e.slice(6);if(n==="default"||n===``)return t[0];let r=Number.parseInt(n,10);if(!Number.isNaN(r)&&r>=0&&r<t.length)return t[r]}function pP(){if(xP!==void 0)return xP;try{p.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),xP=!0}catch{xP=!1}return xP}async function mP(e){return new Promise((t,n)=>{p.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function hP(){let e=OO();if(iO(e.get())&&!pP()&&y.platform()===`darwin`)try{let t=p.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===gP&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}var gP,_P,vP,yP,bP,xP,SP=I((()=>{Sx(),eT(),kx(),YS(),HN(),_E(),Ij(),IO(),SO(),Nk(),gP=`mppx`,_P=f.union([f.boolean(),f.literal(`true`).transform(()=>!0),f.literal(`false`).transform(()=>!1)]),vP=f.object({allowCustomEscrow:f.optional(_P),autoSwap:f.optional(_P),channel:f.optional(f.coerce.string()),deposit:f.optional(f.union([f.string(),f.number()])),payWith:f.optional(f.string()),slippage:f.optional(f.coerce.number()),tokenIn:f.optional(f.string())}),yP=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`],bP=[`payable`,`unknownBalance`,`insufficientBalance`,`unsupported`]}));VS(),SP();const CP=[KN(),Bk(),Pk()];function wP(e,t){let n=t?.plugins?.find(t=>OP(t,e));if(n)return{plugin:n};let r=CP.find(t=>OP(t,e));if(r)return{plugin:r};let i=DP(t)?.find(t=>t.name===e.method&&t.intent===e.intent);return i?{method:i}:{}}function TP(e,t){let n=DP(t);if(n?.length){let r=ES(e,n,CS(n,t?.paymentPreferences).entries);return r?{challenge:r.challenge,...wP(r.challenge,t)}:void 0}for(let n of e){let e=wP(n,t);if(e.plugin||e.method)return{challenge:n,...e}}}function EP(e){let t=DP(e);if(t?.length)return CS(t,e?.paymentPreferences).header}function DP(e){return Array.isArray(e?.methods)?e.methods.flat():void 0}function OP(e,t){return e.supports?e.supports(t):e.method===t.method}async function kP(e){let t=AP(e);if(!t)return;let n=await import(t);return{config:n.default??n,path:t}}function AP(t){if(t){let n=s.resolve(t);return e.existsSync(n)?n:void 0}let n=process.env.MPPX_CONFIG?.trim();if(n){let t=s.resolve(n);return e.existsSync(t)?t:void 0}}SP(),dS(),Zj(),tN(),uN(),HD();function jP(e){return e??globalThis.fetch.bind(globalThis)}function MP(e,t){let n=e.request.methodDetails?.chainId;if(n!==void 0&&n!==t.chainId)throw Error(`Close challenge changed the session chain.`);if(typeof e.request.recipient!=`string`||e.request.recipient.toLowerCase()!==t.descriptor.payee.toLowerCase())throw Error(`Close challenge changed the session payee.`);if(typeof e.request.currency!=`string`||e.request.currency.toLowerCase()!==t.descriptor.token.toLowerCase())throw Error(`Close challenge changed the session token.`);if(Wj(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Error(`Close challenge changed the session escrow.`);let r=lD(e);if(r&&r.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Close challenge changed the session channel.`)}async function NP(e){MP(e.challenge,e.channel);let t=jP(e.fetch),n,r=async(r,i)=>{n&&=(await e.onChallenge?.(n),void 0);let a=await t(r,i);if(a.status!==402)return a;let o=nS(a).find(sD);if(!o)throw Error(`Refreshed close response did not include tempo/session.`);return MP(o,e.channel),n=o,a},i=lN({...e.manager,bootstrap:!1,escrow:e.channel.escrow,fetch:r});$M(i).rehydrate(e);let a=await i.close();if(!a)throw Error(`Session close response did not include a payment receipt.`);return{manager:i,receipt:a}}dS(),Zj(),rM(),HD(),bj(),Gx();var PP=class extends Error{name=`SessionStateError`;code=`SESSION_STATE_INVALID`;file;constructor(e,t={}){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.file=t.file}},FP=class extends Error{name=`SessionBusyError`;code=`SESSION_BUSY`;exitCode=75;scope;owner;constructor(e,t){super(`Session scope is busy in process ${t.pid} on ${t.hostname}.`),this.scope=e,this.owner=t}};const IP=Y.object({channelId:Vx(),cumulativeAmount:Y.string(),deposit:Y.string(),descriptor:Y.object({payer:Bx(),payee:Bx(),operator:Bx(),token:Bx(),salt:Vx(),authorizedSigner:Bx(),expiringNonceHash:Vx()}),escrow:Bx(),chainId:Y.number(),opened:Y.boolean()}),LP=Y.object({name:Y.optional(Y.string()),address:Bx()}),RP=Y.object({method:Y.literal(`tempo`),intent:Y.literal(`session`),status:Y.literal(`success`),timestamp:Y.string(),reference:Y.string(),challengeId:Y.string(),channelId:Vx(),acceptedCumulative:Y.string(),spent:Y.string(),units:Y.optional(Y.number()),txHash:Y.optional(Vx())}),zP=Y.object({version:Y.literal(1),method:Y.literal(`tempo`),intent:Y.literal(`session`),status:Y.enum([`opening`,`open`,`closing`,`stale`]),channel:IP,account:LP,endpoint:Y.string(),challenge:uS,receipt:Y.optional(RP),spent:Y.string(),units:Y.number(),createdAt:Y.string(),updatedAt:Y.string()}),BP=Y.object({version:Y.literal(1),channelId:Vx()}),VP=Y.object({version:Y.literal(1),scope:Y.string(),hostname:Y.string(),pid:Y.number(),token:Y.string(),createdAt:Y.string()});function HP(e,t,n,r){let i=e.safeParse(t);if(!i.success)throw Q(n,r,i.error);return i.data}function UP(e){let t=$P(e);return[t.payer,t.payee,t.token,t.escrow,t.chainId].join(`:`)}function WP(e){return{payer:e.descriptor.payer,payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId}}function GP(e={}){let t=e.stateRoot??qP(),n={root:t,channels:s.join(t,`channels`),locks:s.join(t,`locks`),preferred:s.join(t,`preferred`)},r=e.hostname??y.hostname(),i=e.pid??process.pid,a=e.now??(()=>new Date),o=e.isProcessAlive??TF;async function c(){for(let e of[n.root,n.channels,n.locks,n.preferred])await S.mkdir(e,{recursive:!0,mode:448}),await S.chmod(e,448)}async function l(e){let t=ZP(e),r=JP(n,t),i=await gF(r);if(i===void 0)return;let a=sF(i,r);if(a.channel.channelId.toLowerCase()!==t)throw Q(r,`Session filename does not match its channel ID.`);return cF(a)}async function u(){let e;try{e=await S.readdir(n.channels,{withFileTypes:!0})}catch(e){if(DF(e,`ENOENT`))return[];throw Q(n.channels,`Unable to list managed sessions.`,e)}let t=[];for(let n of e){if(!n.isFile()||n.name.includes(`.tmp-`)||!n.name.endsWith(`.json`))continue;let e=n.name.slice(0,-5);ZP(e);let r=await l(e);r&&t.push(r)}return t.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}async function d(e){await c();let t=rF(e.channel),r=ZP(t.channelId),i=JP(n,r),o=await gF(i),s=o===void 0?void 0:sF(o,i);s&&lF(s,e,i);let l=aF(e.challenge,i);dF(l,t,i);let u=e.receipt?oF(e.receipt,t.channelId,i):void 0,d=s?nM(s.channel):void 0,f=hF(t.cumulativeAmount,d?.cumulativeAmount??0n),p=hF(e.spent??0n,u?BigInt(u.spent):0n,s?BigInt(s.spent):0n);if(p>f)throw Q(i,`Session spend exceeds the locally authorized cumulative amount.`);let m=iF(tM({...t,cumulativeAmount:f}),i),h=mF(s?.updatedAt,a(),i),g=pF(s?.receipt,u),_=nF(e.account,i),v=sF({version:1,method:`tempo`,intent:`session`,status:e.status,channel:m,account:{..._.name===void 0?s?.account.name===void 0?{}:{name:s.account.name}:{name:_.name},address:_.address},endpoint:tF(e.endpoint,i),challenge:l,...g!==void 0&&{receipt:g},spent:p.toString(),units:Math.max(s?.units??0,e.units??0,u?.units??0),createdAt:s?.createdAt??h,updatedAt:h},i);return await _F(i,v),cF(v)}async function f(e){let t=XP(n,e),r=await gF(t);if(r===void 0)return;let{channelId:i}=HP(BP,r,t,`Preferred session is invalid.`),a=await l(i);if(!a)throw Q(t,`Preferred session ${i} does not exist.`);return fF(a.channel,e,t),i}async function p(e,t){let r=ZP(t),i=await l(r),a=XP(n,e);if(!i)throw Q(a,`Session ${r} does not exist.`);fF(i.channel,e,a),await _F(a,{version:1,channelId:r})}async function m(e,t){let r=XP(n,e),i=t===void 0?void 0:ZP(t),a=await gF(r);if(a===void 0)return;let o=HP(BP,a,r,`Preferred session is invalid.`).channelId;i&&o.toLowerCase()!==i||await CF(r,`Unable to clear preferred session.`)}async function h(e){let t=ZP(e),r=await l(t);r&&(await m(WP(r.channel),t),await CF(JP(n,t),`Unable to remove session.`))}async function _(e){await c();let t=YP(n,e);for(let n=0;n<3;n++){let n={version:1,scope:e,hostname:r,pid:i,token:g(),createdAt:a().toISOString()};try{if(await vF(t,n),await xF(bF(t))){await SF(t,n);continue}return{async release(){await SF(t,n)}}}catch(e){if(!DF(e,`EEXIST`))throw e}let s=await gF(t);if(s===void 0)continue;let c=HP(VP,s,t,`Session lock is invalid.`);if(c.scope!==e)throw Q(t,`Session lock scope is invalid.`);if(c.hostname!==r||o(c.pid))throw new FP(e,c);await yF(t,c)}let s=await gF(t);throw s===void 0?Q(t,`Unable to acquire session lock.`):new FP(e,HP(VP,s,t,`Session lock is invalid.`))}async function v(e){return _(UP(e))}return{root:t,get:l,list:u,upsert:d,remove:h,getPreferred:f,setPreferred:p,clearPreferred:m,acquire:v}}function KP(e,t){let n=eF(t.scope),r=t.selection===`auto`||t.selection===`new`?void 0:ZP(t.selection);function i(e){if(e.toLowerCase()!==n)throw new PP(`Session manager requested an unexpected payment scope.`)}async function a(n=!0){if(t.selection===`new`&&!r)return;let i=r??await e.getPreferred(t.scope);if(!i)return;let a=await e.get(i);if(!a)throw new PP(`Session ${i} does not exist.`);if(fF(a.channel,t.scope),!(n&&(a.status!==`open`||!a.channel.opened)))return r=i,a}return{async get(e){return i(e),(await a())?.channel},async set(n){if(i($j(n)),fF(n,t.scope),r&&r.toLowerCase()!==n.channelId.toLowerCase())throw new PP(`Session manager selected ${r}, but attempted to store ${n.channelId}.`);r||t.onNewChannel?.(n);let a=await e.upsert({...t.context(),channel:n});r=a.channel.channelId,await e.setPreferred(t.scope,a.channel.channelId)},async delete(n){i(n);let o=await a(!1);if(!o)return;let s=t.context();await e.upsert({...o,...s,status:s.status===`closing`?`closing`:`stale`,channel:o.channel,spent:s.spent??o.spent,units:s.units??o.units}),s.status!==`closing`&&await e.clearPreferred(t.scope,o.channel.channelId),r=void 0}}}function qP(){let e=process.env.XDG_STATE_HOME||s.join(y.homedir(),`.local`,`state`);return s.join(e,`mppx`,`sessions`,`v1`)}function JP(e,t){return s.join(e.channels,`${t}.json`)}function YP(e,t){let n=h(`sha256`).update(t).digest(`hex`);return s.join(e.locks,`${n}.lock`)}function XP(e,t){let n=h(`sha256`).update(UP(t)).digest(`hex`);return s.join(e.preferred,`${n}.json`)}function ZP(e){return HP(Vx(),e,void 0,`Invalid session channel ID: ${e}.`).toLowerCase()}function QP(e,t,n){return HP(Bx(),e,n,`Invalid ${t}.`).toLowerCase()}function $P(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<0)throw new PP(`Invalid session chain ID.`);return{payer:QP(e.payer,`session payer`),payee:QP(e.payee,`session payee`),token:QP(e.token,`session token`),escrow:QP(e.escrow,`session escrow`),chainId:e.chainId}}function eF(e){let t=$P(e);return[t.payee,t.token,t.escrow,t.chainId].join(`:`)}function tF(e,t){if(typeof e!=`string`)throw Q(t,`Session endpoint is invalid.`);let n;try{n=new URL(e)}catch(e){throw Q(t,`Session endpoint is invalid.`,e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Q(t,`Session endpoint must use HTTP or HTTPS.`);if(n.username||n.password)throw Q(t,`Session endpoint must not contain credentials.`);let r=e.indexOf(`#`);return r===-1?e:e.slice(0,r)}function nF(e,t){return HP(LP,e,t,`Session account is invalid.`)}function rF(e){return nM(iF(tM(e)))}function iF(e,t){return HP(IP,e,t,`Stored session channel is invalid.`)}function aF(e,t){let n=uS.safeParse(e);if(!n.success||!sD(n.data))throw Q(t,`Stored session challenge is invalid.`);return n.data}function oF(e,t,n){let r=HP(RP,e,n,`Stored session receipt is invalid.`);if(r.channelId!==t.toLowerCase())throw Q(n,`Stored session receipt has a different channel ID.`);if(r.reference.toLowerCase()!==t.toLowerCase())throw Q(n,`Stored session receipt has a different reference.`);if(BigInt(r.spent)>BigInt(r.acceptedCumulative))throw Q(n,`Stored session receipt spend exceeds its accepted amount.`);return r}function sF(e,t){let n=HP(zP,e,t,`Stored session is invalid.`),{receipt:r,...i}=n,a=n.channel,o=n.account;if(o.address.toLowerCase()!==a.descriptor.payer.toLowerCase())throw Q(t,`Stored session account does not match the channel payer.`);let s=r?oF(r,a.channelId,t):void 0,c=n.spent,l=BigInt(a.cumulativeAmount);if(BigInt(c)>l)throw Q(t,`Stored session spend exceeds its cumulative authorization.`);if(s&&BigInt(s.acceptedCumulative)>l)throw Q(t,`Stored receipt exceeds the cumulative authorization.`);if(Date.parse(n.updatedAt)<Date.parse(n.createdAt))throw Q(t,`Stored session timestamps are not monotonic.`);let u=tF(n.endpoint,t);if(u!==n.endpoint)throw Q(t,`Stored session endpoint contains a fragment.`);let d=aF(n.challenge,t);return dF(d,nM(a),t),{...i,account:o,channel:a,endpoint:u,challenge:d,...s&&{receipt:s}}}function cF(e){return{version:1,status:e.status,channel:nM(e.channel),account:e.account,endpoint:e.endpoint,challenge:e.challenge,...e.receipt&&{receipt:e.receipt},spent:BigInt(e.spent),units:e.units,createdAt:e.createdAt,updatedAt:e.updatedAt}}function lF(e,t,n){let r=rF(t.channel),i=nF(t.account,n),a=nM(e.channel);if(JSON.stringify(uF(r))!==JSON.stringify(uF(a)))throw Q(n,`Session update changed immutable channel identity.`);if(i.address.toLowerCase()!==e.account.address.toLowerCase())throw Q(n,`Session update changed the payer account.`)}function uF(e){return{channelId:e.channelId.toLowerCase(),descriptor:Object.fromEntries(Object.entries(e.descriptor).map(([e,t])=>[e,typeof t==`string`?t.toLowerCase():t])),escrow:e.escrow.toLowerCase(),chainId:e.chainId}}function dF(e,t,n){if(gj({...t.descriptor,chainId:t.chainId,escrow:t.escrow}).toLowerCase()!==t.channelId.toLowerCase())throw Q(n,`Session channel ID does not match its descriptor.`);let r=QP(e.request.recipient,`challenge recipient`,n),i=QP(e.request.currency,`challenge currency`,n);if(r!==t.descriptor.payee.toLowerCase())throw Q(n,`Session challenge payee does not match the channel.`);if(i!==t.descriptor.token.toLowerCase())throw Q(n,`Session challenge token does not match the channel.`);if(Wj(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Q(n,`Session challenge escrow does not match the channel.`);if(EF(e.request.methodDetails)){let r=e.request.methodDetails;if(r.chainId!==void 0&&r.chainId!==t.chainId)throw Q(n,`Session challenge chain does not match the channel.`)}}function fF(e,t,n){let r=$P(t);if(e.descriptor.payer.toLowerCase()!==r.payer||e.descriptor.payee.toLowerCase()!==r.payee||e.descriptor.token.toLowerCase()!==r.token||e.escrow.toLowerCase()!==r.escrow||e.chainId!==r.chainId)throw Q(n,`Session channel does not match the selected payment scope.`)}function pF(e,t){return e?t&&Date.parse(t.timestamp)>=Date.parse(e.timestamp)?t:e:t}function mF(e,t,n){if(!Number.isFinite(t.getTime()))throw Q(n,`Session clock is invalid.`);let r=t.toISOString();return!e||Date.parse(r)>=Date.parse(e)?r:e}function hF(...e){return e.reduce((e,t)=>t>e?t:e,0n)}async function gF(e){let t;try{t=await S.readFile(e,`utf8`)}catch(t){if(DF(t,`ENOENT`))return;throw Q(e,`Unable to read session state.`,t)}try{return JSON.parse(t)}catch(t){throw Q(e,`Session state contains invalid JSON.`,t)}}async function _F(e,t){await S.mkdir(s.dirname(e),{recursive:!0,mode:448}),await S.chmod(s.dirname(e),448);let n=`${e}.tmp-${process.pid}-${g()}`,r;try{r=await S.open(n,`wx`,384),await r.writeFile(`${JSON.stringify(t,null,2)}\n`,`utf8`),await r.sync(),await r.close(),r=void 0,await S.rename(n,e),await S.chmod(e,384),await wF(s.dirname(e))}catch(t){throw await r?.close().catch(()=>void 0),await S.unlink(n).catch(()=>void 0),t instanceof PP?t:Q(e,`Unable to write session state.`,t)}}async function vF(e,t){let n;try{n=await S.open(e,`wx`,384),await n.writeFile(`${JSON.stringify(t)}\n`,`utf8`),await n.sync(),await n.close(),n=void 0,await wF(s.dirname(e))}catch(t){throw await n?.close().catch(()=>void 0),n&&await S.unlink(e).catch(()=>void 0),t}}async function yF(e,t){let n=bF(e);try{await S.link(e,n)}catch(t){if(DF(t,`EEXIST`)||DF(t,`ENOENT`))return;throw Q(e,`Unable to claim dead lock.`,t)}try{let r=await gF(n);if(r===void 0||HP(VP,r,n,`Session lock is invalid.`).token!==t.token)return;await CF(e,`Unable to reclaim dead lock.`)}finally{await CF(n,`Unable to release dead lock claim.`)}}function bF(e){return`${e}.reclaim`}async function xF(e){try{return await S.access(e),!0}catch(t){if(DF(t,`ENOENT`))return!1;throw Q(e,`Unable to inspect session lock.`,t)}}async function SF(e,t){let n=await gF(e);n!==void 0&&HP(VP,n,e,`Session lock is invalid.`).token===t.token&&await CF(e,`Unable to release session lock.`)}async function CF(e,t){try{await S.unlink(e),await wF(s.dirname(e))}catch(n){if(!DF(n,`ENOENT`))throw Q(e,t,n)}}async function wF(e){let t=await S.open(e,`r`);try{await t.sync()}finally{await t.close()}}function TF(e){try{return process.kill(e,0),!0}catch(e){if(DF(e,`ESRCH`))return!1;if(DF(e,`EPERM`))return!0;throw e}}function EF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function DF(e,t){return e instanceof Error&&`code`in e&&e.code===t}function Q(e,t,n){return new PP(t,{...n!==void 0&&{cause:n},file:e})}Sx(),eT(),GM(),cM(),bj(),IO(),SO();const OF=f.object({status:f.enum([`opening`,`open`,`closing`,`stale`]),channelId:f.string(),account:f.string().optional(),payer:f.string(),payee:f.string(),authorizedSigner:f.string(),token:f.string(),escrow:f.string(),chainId:f.number(),cumulativeAmount:f.string(),confirmedSpend:f.string(),deposit:f.string(),units:f.number(),resourceUrl:f.string(),createdAt:f.string(),updatedAt:f.string()}),kF=f.object({channelId:f.string(),status:f.enum([`closed`,`already-closed`]),spent:f.string(),txHash:f.string().optional()}),AF=f.object({closed:f.array(kF),failed:f.array(f.object({channelId:f.string(),message:f.string()}))});function jF(e){return e===`mainnet`?ge.id:_e.id}function MF(e){if(e===ge.id)return`mainnet`;if(e===_e.id)return`testnet`}function NF(e){let t={};for(let n of e??[]){let e=n.indexOf(`:`);if(e===-1)throw new L({code:`INVALID_HEADER`,message:`Invalid header format: ${n}`,exitCode:2});t[n.slice(0,e).trim()]=n.slice(e+1).trim()}return t}function PF(e){return{status:e.status,channelId:e.channel.channelId,...e.account.name&&{account:e.account.name},payer:e.channel.descriptor.payer,payee:e.channel.descriptor.payee,authorizedSigner:e.channel.descriptor.authorizedSigner,token:e.channel.descriptor.token,escrow:e.channel.escrow,chainId:e.channel.chainId,cumulativeAmount:e.channel.cumulativeAmount.toString(),confirmedSpend:e.spent.toString(),deposit:e.channel.deposit.toString(),units:e.units,resourceUrl:e.endpoint,createdAt:e.createdAt,updatedAt:e.updatedAt}}function FF(e,t){throw e instanceof L?e:e instanceof FP?new L({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e instanceof PP?new L({code:e.code,message:e.message,exitCode:65,cause:e}):new L({code:t,message:e instanceof Error?e.message:String(e),exitCode:75,...e instanceof Error&&{cause:e}})}async function IF(e,t){let n=await MO(t??e.account.name);if(!kM(n.account,e.channel.descriptor))throw new L({code:`SESSION_ACCOUNT_MISMATCH`,message:`Account ${n.account.address} cannot sign for session ${e.channel.channelId}.`,exitCode:2});return n}async function LF(e,t){if(t.network&&jF(t.network)!==e)throw new L({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, not ${t.network}.`,exitCode:2});let n=t.network??MF(e),r=cO(t.rpcUrl,{network:n}),i=await uO({network:n,rpcUrl:r});if(i.id!==e)throw new L({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, but RPC is chainId ${i.id}.`,exitCode:2});return ne({chain:i,transport:ue(r)})}const RF=nb(`sessions`,{description:`Manage persistent payment sessions (list, view, close)`}).command(`list`,{description:`List persistent payment sessions`,options:f.object({account:f.string().optional().describe(`Filter by account name`),network:f.enum([`mainnet`,`testnet`]).optional().describe(`Filter by Tempo network`)}),output:f.object({sessions:f.array(OF)}),alias:{account:`a`},async run(e){try{let t=(await GP().list()).filter(t=>!(e.options.account&&t.account.name!==e.options.account||e.options.network&&t.channel.chainId!==jF(e.options.network))).map(PF),n={sessions:t};if(e.format===`json`&&e.formatExplicit)return e.ok(n);t.length===0&&console.log(`No sessions.`);for(let[e,n]of t.entries())e>0&&console.log(``),zF(n);return}catch(e){return FF(e,`SESSION_LIST_FAILED`)}}}).command(`view`,{description:`View a persistent payment session`,args:f.object({channelId:f.string().describe(`Full session channel ID`)}),output:OF,async run(e){try{let t=await GP().get(e.args.channelId);if(!t)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${e.args.channelId} was not found.`,exitCode:2});let n=PF(t);if(e.format===`json`&&e.formatExplicit)return e.ok(n);zF(n);return}catch(e){return FF(e,`SESSION_VIEW_FAILED`)}}}).command(`close`,{description:`Cooperatively close persistent payment sessions`,usage:[{suffix:`<channel-id> [options]`},{suffix:`--all --yes [options]`}],args:f.object({channelId:f.string().optional().describe(`Full session channel ID`)}),options:f.object({account:f.string().optional().describe(`Account name`),all:f.boolean().optional().default(!1).describe(`Close every matching session`),header:f.array(f.string()).optional().describe(`Add close request header (repeatable)`),network:f.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:f.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`),url:f.string().optional().describe(`Override the stored resource URL`),yes:f.boolean().optional().default(!1).describe(`Confirm closing every session`)}),output:f.union([kF,AF]),alias:{account:`a`,header:`H`,rpcUrl:`r`},async run(e){if(e.options.all&&e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all, not both.`,exitCode:2});if(!e.options.all&&!e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all.`,exitCode:2});if(e.options.all&&!e.options.yes)return e.error({code:`CONFIRMATION_REQUIRED`,message:`Closing all sessions requires --yes.`,exitCode:2});if(e.options.all&&(e.options.header||e.options.rpcUrl||e.options.url))return e.error({code:`INVALID_SESSION_CLOSE`,message:`--header, --rpc-url, and --url only apply to a single session.`,exitCode:2});let t=GP();async function n(e,n={}){let r=await t.get(e);if(!r)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let i=WP(r.channel),a=await t.acquire(i);try{let r=await t.get(e);if(!r)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let a=await IF(r,n.account),o=await LF(r.channel.chainId,n);if(gj({...r.channel.descriptor,escrow:r.channel.escrow,chainId:r.channel.chainId}).toLowerCase()!==r.channel.channelId.toLowerCase())throw new L({code:`SESSION_STATE_INVALID`,message:`Stored descriptor does not derive the session channel ID.`,exitCode:65});if((await aM(o,r.channel.channelId,r.channel.escrow)).deposit===0n)return await t.remove(r.channel.channelId),{channelId:r.channel.channelId,status:`already-closed`,spent:r.spent.toString()};let s=tF(n.resourceUrl??r.endpoint),c={...a.source===`keychain`&&{name:a.accountName},address:a.account.address},l=(e=r.challenge)=>({status:`closing`,account:c,endpoint:s,challenge:e,...r.receipt&&{receipt:r.receipt},spent:r.spent,units:r.units}),u=await t.upsert({...l(),channel:r.channel}),d=NF(n.headers),f=u.challenge,p=await NP({channel:u.channel,challenge:u.challenge,fetch:async(e,t)=>globalThis.fetch(e,{...t,headers:{...d,...gw(t?.headers)}}),input:s,spent:u.spent,async onChallenge(e){f=e,await t.upsert({...l(e),channel:u.channel})},manager:{account:a.account,client:o,channelStore:KP(t,{scope:i,selection:u.channel.channelId,context:()=>l(f)})}});return await t.remove(u.channel.channelId),{channelId:u.channel.channelId,status:`closed`,spent:p.receipt.spent,txHash:p.receipt.txHash}}finally{await a.release()}}try{if(e.options.all){let r=(await t.list()).filter(t=>(!e.options.account||t.account.name===e.options.account)&&(!e.options.network||t.channel.chainId===jF(e.options.network))),i=[],a=[];for(let t of r)try{i.push(await n(t.channel.channelId,{account:e.options.account,network:e.options.network}))}catch(e){a.push({channelId:t.channel.channelId,message:e instanceof Error?e.message:String(e)})}let o={closed:i,failed:a};if(a.length>0){for(let e of a)process.stderr.write(`${e.channelId}: ${e.message}\n`);process.exitCode=1}if(e.format===`json`&&e.formatExplicit)return e.ok(o);for(let e of i)console.log(`${e.channelId} ${e.status} ${e.spent}`);for(let e of a)console.log(`${e.channelId} failed ${e.message}`);return}let r=await n(e.args.channelId,{account:e.options.account,headers:e.options.header,network:e.options.network,resourceUrl:e.options.url,rpcUrl:e.options.rpcUrl});if(e.format===`json`&&e.formatExplicit)return e.ok(r);console.log(`${r.channelId} ${r.status} ${r.spent}`),r.txHash&&console.log(` transaction ${r.txHash}`);return}catch(e){return FF(e,`SESSION_CLOSE_FAILED`)}}});function zF(e){console.log(e.channelId),console.log(` status ${e.status}`),console.log(` cumulative amount ${e.cumulativeAmount}`),console.log(` confirmed spend ${e.confirmedSpend}`),console.log(` deposit ${e.deposit}`),console.log(` chain ${e.chainId}`),console.log(` payer ${e.payer}`),console.log(` payee ${e.payee}`),console.log(` token ${e.token}`),console.log(` resource ${e.resourceUrl}`)}Sx(),GM(),tN(),uN(),_E(),IO(),SO();function BF(e,t){if(t&&e!==`auto`&&t.toLowerCase()!==e.toLowerCase())throw new L({code:`SESSION_SELECTION_CONFLICT`,message:`--session and -M channel= select different sessions.`,exitCode:2});let n=t??e;if(n===`auto`||n===`new`)return n;if(/^0x[0-9a-fA-F]{64}$/.test(n))return n.toLowerCase();throw new L({code:`INVALID_SESSION`,message:`Session must be auto, new, or a 32-byte channel ID.`,exitCode:2})}function VF(e){return typeof e.request.decimals==`number`?e.request.decimals:6}function HF(e){let t=e.allowCustomEscrow;if(t!==void 0){if(t===`true`)return!0;if(t===`false`)return!1;throw new L({code:`INVALID_ALLOW_CUSTOM_ESCROW`,message:`allowCustomEscrow must be true or false.`,exitCode:2})}}function UF(e,t,n){if(t.deposit!==void 0)return t.deposit;let r=e.request.suggestedDeposit;return typeof r==`string`?se(BigInt(r),VF(e)):n?`10`:void 0}function WF(e,t){if(!e)return;if(e.challengeId!==t.challenge.id)throw Error(`Session receipt challenge does not match the paid request.`);if(e.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Session receipt channel does not match the selected channel.`);let n=BigInt(e.acceptedCumulative),r=BigInt(e.spent);if(n>t.cumulative)throw Error(`Session receipt exceeds the local cumulative authorization.`);if(r>n)throw Error(`Session receipt spend exceeds its accepted authorization.`);return e}function GF(e,t){return e.channel.channelId.toLowerCase()===t.toLowerCase()}function KF(e){if(e.trim()!==`[DONE]`){if(e.length===0){process.stdout.write(`
245
- `);return}try{let t=JSON.parse(e);process.stdout.write(t.token??t.choices?.[0]?.delta?.content??e)}catch{process.stdout.write(e)}}}async function qF(e){let{options:t}=e,n=await MO(t.account),r=cO(t.rpcUrl,{network:t.network}),i=await uO({network:t.network,rpcUrl:r}),a=ne({chain:i,transport:ue(r)}),o=HF(e.methodOptions),s=await CM({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new L({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let c={payer:n.account.address,payee:s.payee,token:s.token,escrow:s.escrow,chainId:s.chainId},l=BF(t.session,e.methodOptions.channel),u=e.registry??GP(),d=await u.acquire(c).catch(e=>{throw e instanceof FP?new L({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=l===`auto`?await u.getPreferred(c):l===`new`?void 0:l,s=r?await u.get(r):void 0;if(r&&!s)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&l!==`auto`&&(s.status!==`open`||!s.channel.opened||UP(WP(s.channel))!==UP(c)||!kM(n.account,s.channel.descriptor)))throw new L({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let d=s?.status===`open`&&s.channel.opened?s:void 0,f=d?`open`:`opening`,p=e.challenge,m=d?.receipt,h=d?.spent??0n,g=d?.units??0,_=tF(e.endpoint),v={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},y=KP(u,{scope:c,selection:l,context:()=>({status:f,account:v,endpoint:_,challenge:p,...m&&{receipt:m},spent:h,units:g}),onNewChannel(){f=`opening`,m=void 0,h=0n,g=0}}),{signal:b,...x}=e.init,S={...x,...b&&{signal:b},onReceipt(e){m=e,h=h>BigInt(e.spent)?h:BigInt(e.spent),g=Math.max(g,e.units??0)}};if(e.challengeResponse.status!==402||e.challengeResponse.bodyUsed)throw Error(`Session manager requires an unconsumed 402 challenge response.`);let C=!0,w=lN({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:y,decimals:VF(e.challenge),maxDeposit:UF(e.challenge,e.methodOptions,pO(i)),fetch:async(t,n)=>C?(C=!1,e.challengeResponse):e.fetch(t,n)});d&&$M(w).rehydrate({channel:d.channel,challenge:e.challenge,input:e.fetchInput,spent:d.spent});let{onReceipt:T,...ee}=S,E=await w.fetch(e.fetchInput,ee);if(t.fail&&E.status>=400)throw new L({code:`HTTP_ERROR`,message:`HTTP error ${E.status}`,exitCode:22});if(E.status===402)throw new L({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});ZD(E,{include:!1,verbose:t.include?Math.max(t.verbose,2):t.verbose,silent:t.silent}),p=E.challenge??e.challenge;let D=w.channelId;if(!D)throw Error(`Session manager did not select a channel.`);if(m=WF(E.receipt,{challenge:p,channelId:D,cumulative:w.cumulative})??m,sE(E)){let t=$M(w).consumeSseResponse(e.fetchInput,E,{onReceipt:T,signal:e.init.signal??void 0});for await(let e of t)KF(e)}else process.stdout.write(Buffer.from(await E.arrayBuffer()));let O=await u.get(D);if(!O||!GF(O,D))throw Error(`Session ${D} was not persisted.`);if(m){let e=WF(m,{challenge:p,channelId:D,cumulative:w.cumulative});if(!e)throw Error(`Session receipt validation failed.`);m=e,h=h>BigInt(e.spent)?h:BigInt(e.spent),g=Math.max(g,e.units??0),f=`open`}await u.upsert({status:f,channel:O.channel,account:v,endpoint:_,challenge:p,...m&&{receipt:m},spent:h,units:g}),t.silent||(e.info(`Session retained ${D}\n`),e.info(`Close with: mppx sessions close ${D}\n`))}finally{await d.release()}}SO();function JF(e,t){return t?{label:e,detail:t,severity:`pass`}:{label:e,severity:`pass`}}function $(e,t,n){let r={label:e,severity:`fail`};return t&&(r.detail=t),n&&(r.hint=n),r}function YF(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function XF(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}const ZF={pass:Z.green(`✓`),fail:Z.red(`✗`),warn:Z.yellow(`⚠`),skip:Z.dim(`○`)};function QF(e){let t=ZF[e.severity],n=e.detail?`${e.label} (${e.detail})`:e.label;console.log(` ${t} ${n}`),e.hint&&e.severity!==`pass`&&console.log(Z.dim(` → ${e.hint}`))}function $F(e){console.log(`\n${Z.bold(e)}`)}function eI(e,t){for(let n of e)QF(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`skip`&&t.skipped++}async function tI(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{return await fetch(e,{...t,signal:r.signal})}finally{clearTimeout(i)}}function nI(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const rI=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function iI(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function aI(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function oI(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!rI.has(n))return null;let r=e.slice(t+1);if(!r)return null;let i=r.startsWith(`/`)?r:`/`+r;return{method:n.toUpperCase(),path:i}}function sI(e,t){if(e){try{let n=JSON.parse(e);if(n&&typeof n==`object`&&!Array.isArray(n)){let e=Object.keys(n);if(e.length>0&&e.every(e=>e.startsWith(`/`))){let e=n[t];return e===void 0?void 0:typeof e==`string`?e:JSON.stringify(e)}}}catch{}return e}}function cI(e){if(!e)return{};let t={};for(let n of e){let e=n.indexOf(`:`);e>0&&(t[n.slice(0,e).trim().toLowerCase()]=n.slice(e+1).trim())}return t}async function lI(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await tI(t,{});if(!e.ok)return{error:`HTTP ${e.status}`};let n=await e.text();return{doc:JSON.parse(n),raw:n}}catch(e){return e instanceof DOMException&&e.name===`AbortError`?{error:`Request timed out after 15s`}:e instanceof SyntaxError?{error:`Invalid JSON`}:{error:e.message}}}function uI(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=pI(i.parameters);for(let[a,o]of Object.entries(i)){if(!rI.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=mI(r,pI(i.parameters)),c=s.length>0?s:void 0;if(i[`x-payment-info`]){let n=i[`x-payment-info`];t.push({method:a.toUpperCase(),path:e,amount:n.amount,parameters:c})}else{let t=i.responses;t&&`402`in t&&n.push({method:a.toUpperCase(),path:e,parameters:c})}}}return t.length>0?t:n}function dI(e,t){let n=e.paths;if(!n)return;let r=n[t.path];if(!r)return;let i=r[t.method.toLowerCase()];if(!i?.requestBody)return;let a=i.requestBody.content?.[`application/json`];if(!a)return;if(a.example)return JSON.stringify(a.example);if(a.examples&&typeof a.examples==`object`){let e=Object.values(a.examples)[0];if(e?.value)return JSON.stringify(e.value)}let o=a.schema,s=new Set;if(o=gI(o,e,s),!o||o.type!==`object`)return;let c=_I(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function fI(e,t,n){let r=t.path;t.parameters&&(r=hI(r,t.parameters));let i=r.startsWith(`/`)?r.slice(1):r,a=new URL(i,e.replace(/\/?$/,`/`)).href;if(n){let e=new URL(a);for(let t of n){let[n,...r]=t.split(`=`);n&&e.searchParams.set(n,r.join(`=`))}a=e.href}return a}function pI(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;e.in===`path`&&typeof e.name==`string`&&t.push(e.schema&&typeof e.schema==`object`?{name:e.name,in:`path`,schema:e.schema,example:e.example}:{name:e.name,in:`path`,example:e.example})}return t}function mI(e,t){let n=[...e];for(let e of t){let t=n.findIndex(t=>t.name===e.name);t>=0?n[t]=e:n.push(e)}return n}function hI(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{let r=t.find(e=>e.name===n&&e.in===`path`);if(!r)return e;let i=r.example??r.schema?.example??r.schema?.default;return i===void 0?e:encodeURIComponent(String(i))})}function gI(e,t,n){if(!e||typeof e.$ref!=`string`)return e;if(n?.has(e.$ref))return;let r=e.$ref.replace(/^#\//,``).split(`/`),i=t;for(let e of r)if(i&&typeof i==`object`)i=i[e];else return;return i}function _I(e,t,n){let r=gI(e,t,n)??e;if(r.const!==void 0)return r.const;if(r.example!==void 0)return r.example;if(r.default!==void 0)return r.default;switch(r.type){case`string`:return r.enum&&Array.isArray(r.enum)?r.enum[0]:r.format===`email`?`test@example.com`:r.format===`uuid`?`00000000-0000-0000-0000-000000000000`:r.format===`uri`||r.format===`url`?`https://example.com`:r.format===`date`?`2026-01-01`:r.pattern===`^\\d{5}(?:-\\d{4})?$`?`10001`:r.pattern===`^[A-Z]{2}$`?`US`:`test`;case`number`:case`integer`:return r.minimum??1;case`boolean`:return!0;case`array`:return[];case`object`:{let e=r.properties;if(!e)return{};let i=r.required||[],a={};for(let r of i){let i=e[r];i&&(a[r]=_I(i,t,n))}return a}default:return null}}dS(),kx(),JC(),SO();const vI=Object.values(Pe);function yI(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&vI.find(e=>e.id===t.chainId)?.testnet===!0}async function bI(e,t,n,r){let i=[],a=fI(e,t,r?.query),o=cI(r?.extraHeaders),s;r?.body&&!r.bodyIsAutogenerated&&(s=r.body,o[`content-type`]||=`application/json`);let c;try{let e={method:t.method};Object.keys(o).length>0&&(e.headers=o),s&&(e.body=s),c=await tI(a,e)}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}if(!s&&(c.status===400||c.status===422)){let e=r?.body??(r?.discoveryDoc?dI(r.discoveryDoc,t):void 0);if(e){n&&console.log(Z.dim(` Retrying with body: ${e}`)),s=e,o[`content-type`]=`application/json`;try{c=await tI(a,{method:t.method,headers:o,body:s})}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}}}if(c.status!==402)return c.status===200?i.push(XF(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(XF(`Returns 402 without credentials`,`Got ${c.status} (endpoint requires auth before payment gate)`)):i.push($(`Returns 402 without credentials`,`Got ${c.status} instead`,c.status===400||c.status===422?`Server requires a valid request body before returning 402. Add a requestBody schema with examples to your OpenAPI doc, or use --body.`:`Endpoints that require payment must return HTTP 402 with a WWW-Authenticate: Payment header when no valid credential is provided.`)),{results:i};i.push(JF(`Returns 402 without credentials`));let l=c.headers.get(J.wwwAuthenticate),u=jI(c);if(!l)return u.length>0?(i.push(XF(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(XF(`Not an MPP endpoint`,`No WWW-Authenticate header (may be x402 or other protocol)`)),{results:i};if(u.length>0&&i.push(...u),!l.startsWith(`${wx.payment} `))return i.push(XF(`Not an MPP endpoint`,`WWW-Authenticate scheme is not Payment`)),{results:i};i.push(JF(`WWW-Authenticate header present`,`Payment scheme`));let d;try{d=nS(c)}catch(e){let t=e.message;i.push($(`Challenge parseable`,t,`The Payment challenge must include a request="<base64url>" parameter containing JSON-encoded payment details.`));let n=l.slice(l.indexOf(` `)+1);return i.push(YF(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0)return i.push($(`Challenge parseable`,`No Payment challenges found in header`)),{results:i};let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push(JF(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=new URL(e).hostname;xI(d,i),SI(d,i),CI(d,i),wI(d,p,i);let m=d.length>1;for(let e of d){let t=e.request;TI(e,t,i,m)}if(n)for(let e of d)console.log(Z.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function xI(e,t){let n=e.filter(e=>!e.id);n.length===0?t.push(JF(`Challenge has id`)):t.push($(`Challenge has id`,`${n.length} missing`,`Every challenge must include a unique id field.`))}function SI(e,t){let n=e.filter(e=>!e.realm);n.length===0?t.push(JF(`Challenge has realm`)):t.push($(`Challenge has realm`,`${n.length} missing`,`Set realm to your server's hostname.`))}function CI(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(YF(`Challenge has expiration`,`missing expires field`,`Add an expires field (ISO 8601) to prevent replay attacks.`));return}if(new Date(r.expires)<=n){t.push($(`Challenge expires in the future`,`Expired at ${r.expires}`,`The expires timestamp must be in the future.`));return}}let r=Math.min(...e.map(e=>new Date(e.expires).getTime()-n.getTime()));t.push(JF(`Challenge expires in the future`,`${Math.round(r/6e4)}m from now`))}function wI(e,t,n){let r=[...new Set(e.map(e=>e.realm??``))].filter(e=>e&&e!==t&&!t.endsWith(`.${e}`));r.length>0?n.push(YF(`Realm matches server hostname`,`realm="${r[0]}" vs host="${t}"`,`Set the realm to your production hostname (or base domain) in the challenge.`)):n.push(JF(`Realm matches server hostname`))}function TI(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===Tx.tempo?EI(t,i,n,e):e.method===Tx.stripe?DI(t,i,n):e.method===Tx.evm&&OI(e,t,i,n)}function EI(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if(iI(e.recipient)?n.push(JF(`${t}Valid recipient address`)):e.recipient===void 0&&a?n.push(JF(`${t}Uses splits (no single recipient)`)):e.recipient===void 0?n.push($(`${t}Valid recipient address`,`Missing recipient (and no splits defined)`,`Set request.recipient to a valid 0x address, or use methodDetails.splits for multiple recipients.`)):n.push($(`${t}Valid recipient address`,`Got: ${String(e.recipient)}`,`Set request.recipient to a valid 0x-prefixed 40-hex-char address.`)),iI(e.currency)){let e=yI(r)?`testnet`:`mainnet`;n.push(JF(`${t}Valid currency address`,e))}else n.push($(`${t}Valid currency address`,`Got: ${String(e.currency)}`,`Set request.currency to a valid token address.`));kI(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function DI(e,t,n){kI(e,t,n,`currency's smallest unit (e.g. "100" = $1.00 for USD)`);let r=e.currency;typeof r==`string`&&/^[a-z]{3}$/i.test(r)?n.push(JF(`${t}Valid currency code`,r.toUpperCase())):n.push($(`${t}Valid currency code`,r?`Got: ${r}`:`missing`,`Must be a three-letter ISO currency code (e.g. "usd").`));let i=e.methodDetails,a=i?.networkId;a?n.push(JF(`${t}Has networkId`,a.slice(0,20))):n.push($(`${t}Has networkId`,`Missing methodDetails.networkId`,`Set methodDetails.networkId to your Stripe Business Network profile ID.`));let o=i?.paymentMethodTypes;Array.isArray(o)&&o.length>0?n.push(JF(`${t}Has paymentMethodTypes`,o.join(`, `))):n.push($(`${t}Has paymentMethodTypes`,`Missing or empty`,`Set methodDetails.paymentMethodTypes to an array (e.g. ["card"]).`))}function OI(e,t,n,r){if(iI(t.recipient)?r.push(JF(`${n}Valid recipient address`)):r.push($(`${n}Valid recipient address`,`Got: ${String(t.recipient)}`,`Set request.recipient to a valid 0x-prefixed Ethereum address.`)),iI(t.currency)){let t=yI(e)?`testnet`:`mainnet`;r.push(JF(`${n}Valid currency address`,t))}else r.push($(`${n}Valid currency address`,`Got: ${String(t.currency)}`,`Set request.currency to a valid ERC-20 token contract address.`));kI(t,n,r,`token's smallest unit`);let i=t.methodDetails?.chainId;typeof i==`number`&&i>0?r.push(JF(`${n}Has chainId`,String(i))):r.push($(`${n}Has chainId`,`Missing methodDetails.chainId`,`Set methodDetails.chainId to the EVM chain ID.`))}function kI(e,t,n,r){aI(e.amount)?n.push(JF(`${t}Amount is valid integer string`)):e.amount===void 0||e.amount===null?n.push($(`${t}Amount is valid integer string`,`Missing amount`,`Set request.amount to a string of digits in the ${r}.`)):n.push($(`${t}Amount is valid integer string`,`Got: ${String(e.amount)}`,`request.amount must be a string of digits (no decimals, no prefix).`))}async function AI(e,t,n){let r=[],i=fI(e,t,n?.query),a={[J.authorization]:`${wx.payment} dGhpcyBpcyBnYXJiYWdl`},o;n?.body&&(o=n.body,a[`content-type`]=`application/json`);try{let e=await tI(i,{method:t.method,headers:a,body:o??null});e.status===402?(r.push(JF(`Malformed credential returns 402`,`not 500`)),e.headers.get(J.wwwAuthenticate)?.startsWith(`${wx.payment} `)?r.push(JF(`Error response includes fresh challenge`)):r.push(YF(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the Authorization header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(YF(`Malformed credential returns 402`,`Got ${e.status}`,`When the Authorization header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function jI(e){let t=[],n=e.headers.get(`payment-required`)??e.headers.get(`x-payment-required`);if(!n)return t;let r=e.headers.get(`payment-required`)?`PAYMENT-REQUIRED`:`X-Payment-Required`;try{let e=HC(n);t.push(JF(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(YF(`x402 payment challenge`,`${r} header present but failed schema validation`,`Ensure the PAYMENT-REQUIRED header contains a valid base64-encoded JSON payload matching the x402 schema.`))}return t}const MI=[`No discovery document found, endpoints could not be automatically found.`,`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,`The MPP SDKs can automatically expose this endpoint. See https://mpp.dev/sdk.`,``,`To test a specific endpoint: mppx validate <url> --endpoint POST:/your/path`].join(`
246
- `);Gx();const NI={method:Y.string(),reference:Y.string(),externalId:Y.optional(Y.string()),subscriptionId:Y.optional(Y.string()),status:Y.literal(`success`),timestamp:Ix()};Y.object(NI);const PI=Y.looseObject(NI);function FI(e){let t=O.toString(e);return II(JSON.parse(t))}function II(e){return PI.parse(e)}dS(),kx(),HN(),JD(),IO(),SO();async function LI(e,t,n){try{n||console.log(Z.dim(` Provisioning testnet wallet and funding via faucet...`));let t=pe(),r=he(t),i=ne({chain:_e,transport:ue()}),a=await ke.faucet.fund(i,{account:r});await Promise.all(a.map(e=>Ee(i,{hash:e}))),n||console.log(Z.dim(` Using wallet: ${r.address}`));let o=e.request.currency;if(typeof o==`string`)for(let e=0;e<10;e++){let e=await ke.token.getBalance(i,{account:r.address,token:o}).catch(()=>void 0);if(e&&e.amount>0n)break;await new Promise(e=>setTimeout(e,500))}return{methods:[...RN({account:r})]}}catch(e){t&&console.log(Z.dim(` Provisioning failed: ${e.message}`));return}}async function RI(){let e=kO(),{isTempoAccount:t}=await Promise.resolve().then(()=>(SO(),YD)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(SP(),UN));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await NO()).address}catch{return}}function zI(e){try{let{execSync:t}=p,n=t(`stripe config --list`,{encoding:`utf8`,timeout:5e3}).match(/test_mode_api_key\s*=\s*'([^']+)'/);if(n?.[1])return e&&console.log(Z.dim(` Using Stripe test key from stripe CLI`)),n[1]}catch{}}async function BI(e,t,n){let r=ne({chain:e,transport:ue()}),[i,a]=await Promise.all([xe(r,{address:t,abi:oe,functionName:`balanceOf`,args:[n]}),xe(r,{address:t,abi:oe,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,symbol:a??void 0}}function VI(e){return Object.values(Pe).find(t=>t.id===e)}function HI(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function UI(e){switch(e.method){case Tx.evm:return`no EVM payment plugin yet`;case`solana`:return`no Solana payment plugin yet`;default:return`no plugin for ${e.method}/${e.intent}`}}async function WI(e,t,n,r){let i=[],a=fI(e,t,r.query),o=cI(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await tI(a,{method:t.method,headers:o,body:s??null})}catch(e){return i.push($(`Payment: fetch challenge`,e.message)),i}if(c.status!==402)return i.push(XF(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=nS(c)}catch(e){return i.push($(`Payment: parse challenge`,e.message)),i}if(l.length===0)return i.push($(`Payment: parse challenge`,`No Payment challenges in response`)),i;let u=l.find(e=>{if(e.method!==Tx.tempo)return!1;let t=e.request.methodDetails;return typeof t?.chainId==`number`&&t.chainId!==UD.mainnet});if(u){let e=await LI(u,n,r.silent);if(e){let r=new Response(null,{status:402,headers:{[J.wwwAuthenticate]:qx(u)}});try{let c=await iT({methods:e.methods,polyfill:!1}).createCredential(r);i.push(JF(`Payment: submitted`,`ephemeral testnet wallet`)),await JI(i,a,t,c,o,s,n,_e)}catch(e){i.push($(`Payment: create credential`,e.message))}}else i.push($(`Payment: auto-provision wallet`,`Failed to create and fund testnet wallet`));r.onResults?.(i)}let d=await kP().catch(()=>void 0),f=r.interactive,p=process.env.MPPX_STRIPE_SECRET_KEY??zI(n),m=p?.startsWith(`sk_test_`)||p?.startsWith(`rk_test_`),h=new Set([Tx.tempo,Tx.evm,Tx.stripe]);for(let e of l){if(e===u||!h.has(e.method))continue;r.silent||console.log(``);let c=i.length,l=()=>{r.onResults&&i.length>c&&r.onResults(i.slice(c))},g=`Payment [${e.method}]`;try{switch(e.method){case Tx.tempo:case Tx.evm:await GI(e,g,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:d,isInteractive:f,options:r});break;case Tx.stripe:await KI(e,g,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:d,isInteractive:f,isStripeTestKey:m??!1,stripeKey:p,options:r})}}finally{l()}}return i}async function GI(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u}=n,d=e.request,f=d.methodDetails,p=aI(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,g;try{g=await RI()}catch{}if(!g){r.push(XF(t,`no wallet configured. Run "mppx account create" to create one.`));return}let _;if(e.method===Tx.tempo)_=ge;else if(e.method===Tx.evm){let e=f?.chainId;e&&(_=VI(e))}let v;if(p&&h&&_)try{let n;if(e.method===Tx.tempo){let e=await mO(ne({chain:ge,transport:ue()}),h,g);n=e.balance,v=e.symbol}else{let e=await BI(_,h,g);n=e.balance,v=e.symbol}if(n<p){let e=HI(p,m),i=HI(n,m),a=v??`tokens`;r.push(XF(t,`insufficient balance (have ${i}, need ${e} ${a} on ${_.name})`,`Fund wallet ${g} with at least ${e} ${a} on ${_.name}.`));return}}catch(e){c&&console.log(Z.dim(` Balance check skipped: ${e.message}`))}let y=p?HI(p,m):`unknown amount`,b=v??(h?.length===3?h.toUpperCase():``),x=_?.name,S=`${y}${b?` ${b}`:``}${x?` on ${x}`:``}`;if(u.silent||console.log(Z.dim(` Attempting payment with wallet ${g}`)),_?.testnet)u.silent||console.log(Z.dim(` Auto-approved: ${S} (testnet)`));else if(!u.yes&&!n.isInteractive){r.push(XF(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(Z.dim(` Auto-approved: ${S}`));else if(!await oO(` ${Z.yellow(`Pay`)} ${S}. Continue?`,!1)){r.push(XF(t,`declined`));return}let C=wP(e,l?.config),w=C.plugin,T=C.method;if(!w&&!T){r.push(XF(t,UI(e)));return}let ee,E;if(w)try{let t=await w.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});ee=t.methods,E=t.createCredential}catch(e){r.push(XF(t,e.message));return}else ee=[T];let D=await qI(e,ee,E,t,r);D&&(w?.prepareCredentialRequest?.({challenge:e,credential:D,headers:o}),await JI(r,i,a,D,o,s,c,_))}async function KI(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u,isStripeTestKey:d,stripeKey:f}=n,p=e.request,m=aI(p.amount)?BigInt(p.amount):void 0,h=p.decimals??2,g=p.currency,_=m?HI(m,h):`unknown amount`,v=g?.length===3?g.toUpperCase():``,y=`${_}${v?` ${v}`:``} via Stripe${d?` (testmode)`:``}`;if(d)u.silent||console.log(Z.dim(` Attempting: ${y}`));else if(!u.yes&&!n.isInteractive){r.push(XF(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(Z.dim(` Auto-approved: ${y}`));else if(!await oO(` ${Z.yellow(`Pay`)} ${y}. Continue?`,!1)){r.push(XF(t,`declined`));return}let b=wP(e,l?.config).plugin;if(!b){r.push(XF(t,`no Stripe plugin available`));return}let x,S;try{let t={paymentMethod:`pm_card_visa`};f&&(t.secretKey=f);let n=await b.setup({challenge:e,options:{},methodOpts:t});x=n.methods,S=n.createCredential}catch(e){r.push(XF(t,e.message));return}let C=await qI(e,x,S,t,r);if(C){if(b.prepareCredentialRequest?.({challenge:e,credential:C,headers:o}),d){let e=await tI(i,{method:a.method,headers:{...o,[J.authorization]:C},body:s??null},3e4);e.status>=200&&e.status<300?r.push(JF(`${t}: successful`,`HTTP ${e.status}`)):r.push(XF(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await JI(r,i,a,C,o,s,c,void 0)}}async function qI(e,t,n,r,i){let a=new Response(null,{status:402,headers:{[J.wwwAuthenticate]:qx(e)}});try{let e;return e=n?await n(a):await iT({methods:t,polyfill:!1}).createCredential(a),i.push(JF(`${r}: submitted`)),e}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(XF(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function JI(e,t,n,r,i,a,o,s){let c;try{c=await tI(t,{method:n.method,headers:{...i,[J.authorization]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}if(c.status===402){let t=await c.text().catch(()=>``),n=`Payment rejected`;try{let e=JSON.parse(t);n=e.detail??e.title??n}catch{}return e.push($(`Payment: accepted`,n,`The server rejected a valid credential. Check that your payment verification logic accepts the credential format and that the payment was processed on-chain.`)),e}if(c.status>=400&&c.status<500)e.push(YF(`Payment: post-payment response`,`Got ${c.status}`,`Payment succeeded but the endpoint returned a client error. The endpoint likely requires request body parameters. Use --body to provide them.`));else if(c.status>=500)return e.push($(`Payment: server response`,`Got ${c.status}`,`Payment was accepted but the server errored while generating the response. Check server logs for the underlying error.`)),e;else e.push(JF(`Payment: successful`,`HTTP ${c.status}`));let l=c.headers.get(J.paymentReceipt);if(!l)e.push($(`Payment-Receipt header present`,void 0,`After accepting payment, include a Payment-Receipt header with a base64url-encoded JSON object containing: method, reference, status ("success"), and timestamp (ISO 8601).`));else{e.push(JF(`Payment-Receipt header present`));try{let t=FI(l);if(e.push(JF(`Receipt parseable`)),t.status===`success`?e.push(JF(`Receipt status is "success"`)):e.push($(`Receipt status is "success"`,`Got: ${t.status}`)),t.reference){let n=/^0x[0-9a-fA-F]{64}$/.test(t.reference),r=t.reference.startsWith(`pi_`);n||r?e.push(JF(`Receipt reference valid`,t.reference.slice(0,20)+`...`)):e.push(YF(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(YF(`Receipt has reference`,`No reference field`));if(t.timestamp){let n=new Date(t.timestamp),r=Date.now()-n.getTime();r<6e4?e.push(JF(`Receipt timestamp recent`,`${Math.round(r/1e3)}s ago`)):e.push(YF(`Receipt timestamp recent`,`${Math.round(r/6e4)}m ago`))}o&&console.log(Z.dim(` Receipt: ${JSON.stringify(t,null,2)}`))}catch(t){e.push($(`Receipt parseable`,t.message))}}let u=c.headers.get(`content-type`)??``,d=await c.text().catch(()=>``);if(d.length>0)e.push(JF(`Response body non-empty`,`${u.split(`;`)[0]}, ${nI(d.length)}`));else{let t=[...c.headers.entries()].filter(([e])=>!e.startsWith(`x-`)&&![`content-type`,`content-length`,`date`,`server`,`connection`,`keep-alive`,`cache-control`,`vary`,`access-control-allow-origin`,`payment-receipt`,`payment-session`,`payment-session-snapshot`].includes(e.toLowerCase()));t.length>0?e.push(YF(`Response body empty -- data may be in headers only`,t.map(([e])=>e).join(`, `))):e.push(YF(`Response body empty`))}if(u?e.push(JF(`Content-Type header set`,u.split(`;`)[0])):e.push(YF(`Content-Type header set`)),l)try{let t=FI(l);if(t.reference&&/^0x[0-9a-fA-F]{64}$/.test(t.reference)){let n=s?.blockExplorers?.default?.url;if(n){let r=n.includes(`tempo`)?`receipt`:`tx`;e.push(JF(`On-chain transaction`,`${n}/${r}/${t.reference}`))}}}catch{}return e}async function*YI(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await eL(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=sI(e.body,i.path),!a&&r.doc&&(a=dI(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await bI(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=(l??[]).filter(e=>e.method!==`stripe`).map(e=>e.request.methodDetails?.chainId).filter(e=>typeof e==`number`),p=f.some($I),m=f.some(e=>!$I(e)),h=!d&&s.some(e=>e.label===`Not an MPP endpoint`),g=s.some(e=>e.severity===`pass`&&e.label===`WWW-Authenticate header present`),_=s.some(e=>e.severity===`fail`&&e.label===`Challenge parseable`);if(yield{phase:`challenge`,endpoint:i,results:s,isMpp:d,isTestnet:p,isMainnet:m,isNonMppPayment:h,isMalformedChallenge:!d&&g&&_,methods:l?.map(e=>e.method)??[]},d&&(yield{phase:`errorHandling`,endpoint:i,results:await AI(t,i,{body:u,query:e.query})},!e.skipPayment)){let r=e.onPaymentResults,a=await WI(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 XI(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of YI(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,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===`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===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=ZI(r,n,{sawTestnet:a,sawMainnet:o});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function ZI(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(MI);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 QI=Object.values(Pe);function $I(e){return QI.find(t=>t.id===e)?.testnet===!0}async function eL(e,t){let n=[],r=[],i=null,a=!1,o=!1,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 lI(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=kT(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=oI(t.endpoint);e&&r.push(e)}else if(i){r=uI(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=aI(t.amount)?BigInt(t.amount):e,i=aI(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}}Sx(),SO();const tL=nb(`validate`,{description:`Validate an MPP server implementation end-to-end`,args:f.object({url:f.string().describe(`Base URL of the MPP server to validate`)}),options:f.object({endpoint:f.string().optional().describe(`Endpoint to test (METHOD:path). Skips discovery.`),body:f.string().optional().describe(`Request body. With --endpoint, used directly. In discovery mode, JSON with / keys is a per-path mapping.`),query:f.array(f.string()).optional().describe(`Query parameter (key=value, repeatable)`),header:f.array(f.string()).optional().describe(`Request header (key:value, repeatable)`),verbose:f.number().default(0).meta({count:!0}).describe(`Verbosity level`),yes:f.boolean().default(!1).describe(`Auto-approve mainnet payments`),outputJson:f.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||rO()){let t=await XI({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${Z.bold(`mppx validate`)} ${Z.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of YI({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=>eI(e,n)}))switch(t.phase){case`discovery`:if($F(`Discovery (/openapi.json)`),eI(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=MI.split(`
247
- `);console.log(Z.yellow(` ${e}`));for(let e of t)console.log(e?Z.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(Z.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,$F(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(Z.dim(` Challenge`)),eI(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(Z.dim(` Error Handling`)),eI(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}nL(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function nL(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(Z.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(Z.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(Z.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(Z.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(Z.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(Z.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(Z.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(Z.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(Z.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(Z.green(`${e.passed} passed`)),e.failed>0&&r.push(Z.red(`${e.failed} failed`)),e.warnings>0&&r.push(Z.yellow(`${e.warnings} warning(s)`)),e.skipped>0&&r.push(Z.yellow(`${e.skipped} skipped`)),console.log(`${Z.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(Z.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(Z.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 rL(e){return aL(e)?e.offers:[e]}function iL(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=oL(t.amount)??oL(i.amount)??null,o=oL(t.currency)??oL(i.currency),s=oL(e.description)??oL(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 aL(e){return`offers`in e&&!(`_canonicalRequest`in e)}function oL(e){return typeof e==`string`?e:void 0}var sL=I((()=>{})),cL=Ke({generate:()=>lL,generateProxy:()=>uL});function lL(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=>fL(e,r));return dL({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function uL(e){let t=e.routes.map(t=>({...t,path:pL(e.basePath,t.path)}));return dL({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function dL(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`]=ST.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 fL(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:rL(t).map(iL)},...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:jx(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:iL(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function pL(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var mL=I((()=>{Nx(),OT(),sL()}));Sx(),dS(),eT(),kx(),HD(),IO(),SO();const hL=`0.9.1`,gL=f.object({address:f.string(),isDefault:f.boolean().optional(),name:f.string(),source:f.string().optional()}),_L=f.object({address:f.string(),balances:f.array(f.string()).optional(),name:f.string(),type:f.string().optional()}),vL=f.object({message:f.string(),path:f.string(),severity:f.string()}),yL=f.object({description:f.string().optional(),id:f.string(),name:f.string().optional(),paidEndpoints:f.number(),status:f.string().optional(),url:f.string().optional()}),bL=f.object({description:f.string().optional(),method:f.string(),path:f.string(),payment:f.unknown().optional()});function xL(e){return e.format===`json`&&e.formatExplicit}function SL(e,t,n){if(xL(e))return e.ok(t);n()}async function CL(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}function wL(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function TL(e){return typeof e==`string`?e:void 0}function EL(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function DL(e){let t=EL(e);return{...TL(e.description)?{description:TL(e.description)}:{},id:TL(e.id)??TL(e.name)??`unknown`,...TL(e.name)?{name:TL(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...TL(e.status)?{status:TL(e.status)}:{},...TL(e.serviceUrl)||TL(e.url)?{url:TL(e.serviceUrl)??TL(e.url)}:{}}}function OL(e){return{...TL(e.description)?{description:TL(e.description)}:{},method:TL(e.method)??`GET`,path:TL(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function kL(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=TL(t.amount),r=TL(t.currency),i=TL(t.method),a=TL(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function AL(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=e.request.currency;return typeof t==`string`&&t.toLowerCase()===n})}async function jL(){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 ML(e,t){let n=t.toLowerCase();return e.find(e=>{let t=TL(e.id)?.toLowerCase(),r=TL(e.name)?.toLowerCase();return t===n||r===n})}const NL=nb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:hL,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:f.object({url:f.string().describe(`URL to make request to`)}),options:f.object({account:f.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:f.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:f.string().optional().describe(`Path to config file`),confirm:f.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:f.string().optional().describe(`Payment currency/token address to select`),data:f.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:f.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:f.array(f.string()).optional().describe(`Add header (repeatable)`),include:f.boolean().optional().describe(`Include response headers in output`),insecure:f.boolean().optional().describe(`Skip TLS certificate verification (true for localhost/.local)`),jsonBody:f.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:f.boolean().optional().describe(`Follow redirects`),method:f.string().optional().describe(`HTTP method`),methodOpt:f.array(f.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:f.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:f.string().optional().describe(`Source token for Tempo auto-swap`),rpcUrl:f.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:f.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:f.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:f.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:f.string().optional().default(`mppx/${hL}`).describe(`Set User-Agent header`),verbose:f.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 kP(e.options.config);n&&e.options.verbose>=1&&t(`${Z.dim(`Using config`)} ${Z.blue(s.relative(process.cwd(),n.path))}\n`);let r={"User-Agent":e.options.userAgent};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});r[t.slice(0,n).trim()]=t.slice(n+1).trim()}let i=EP(n?.config);i&&!Object.keys(r).some(e=>e.toLowerCase()===`accept-payment`)&&(r[`Accept-Payment`]=i);let a=(()=>{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:o}=new URL(a),c=e.options.insecure||o===`localhost`||o.endsWith(`.localhost`)||o.endsWith(`.local`)?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,l=o.endsWith(`.localhost`)&&o!==`localhost`,u=l?a.replace(o,`127.0.0.1`):a;if(l){let{host:e}=new URL(a);r.Host=e}try{let i=nO(e.options.methodOpt),o=GP(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,r[`Content-Type`]??=`application/json`,r.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(r).length>0&&(s.headers=r);let l={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&XD(a,s,t);let d=await c(u,s);if(d.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&&d.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${d.status}`,exitCode:22});ZD(d,l),await CL(d);return}let f=nS(d),p=AL(f,e.options.currency);if(e.options.currency&&p.length===0){let t=f.map(e=>e.request.currency).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 m=await GN(p,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),h=TP(m,n?.config);if(!h){let t=m.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:g,plugin:_,method:v}=h,y=new Response(null,{status:402,headers:{[J.wwwAuthenticate]:qx(g)}}),b=g.request.currency??``,x=g.request.decimals??6,S,C;_&&(C=await _.setup({challenge:g,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:i}),b=C.tokenSymbol,x=C.tokenDecimals,S=C.explorerUrl);let w=!e.options.silent&&e.options.confirm,T=new Set;{ZD(d,g.method===`tempo`&&g.intent===`session`&&e.options.include?{...l,include:!1,verbose:Math.max(l.verbose,2)}:l);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(g))e.has(n)||r===void 0||t.push([n,eO(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:b,tokenDecimals:x,explorerUrl:S},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(g.request))e.has(n)||i===void 0||t.push([n,QD(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=g.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=$D(i);t.push([n,e?`${e}\n${Z.dim(i)}`:i])}else t.push([n,QD(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)T.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),c=` ${``.padEnd(s)} `;if(e.options.verbose>=1||w){t(`${Z.bold(Z.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${Z.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
248
- `);t(` ${Z.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${c}${e}\n`)}}}if(w&&(t(`
249
- `),!await oO(`Proceed with ${g.intent}?`,!0))){t(`Aborted.
250
- `);return}}let ee=process.env.MPPX_PRIVATE_KEY?.trim()||!iO(kO(e.options.account));if(sD(g)&&ee){try{await qF({challenge:g,challengeResponse:y,endpoint:a,fetch:c,fetchInput:u,init:s,info:t,methodOptions:i,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:o})}catch(e){return FF(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});let E;if(C?.createCredential)E=await C.createCredential(y);else if(C)E=await iT({methods:C.methods,polyfill:!1}).createCredential(y,C.credentialContext);else if(v)E=await iT({methods:[v],polyfill:!1}).createCredential(y);else throw Error(`unreachable`);let D={...gw(s.headers),[oS(g)]:E};_?.prepareCredentialRequest?.({challenge:g,credential:E,headers:D});let k={...s,headers:D};e.options.verbose>=2&&XD(a,k,t);let A=await c(u,k);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(`${Z.bold(Z.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,String(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${Z.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(ZD(A,l),!await _?.handleResponse?.({challenge:g,credential:E,response:A,fetchUrl:u,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:w,confirm:oO,tokenSymbol:b,tokenDecimals:x,explorerUrl:S,shownKeys:T})){let n=A.headers.get(J.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(O.toString(n));t(`\n${Z.bold(Z.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||T.has(t)||t===`reference`&&o)continue;let e=_?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${Z.dim(`(${sO(BigInt(n),b,x)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&S?r.push([t,tO(`${S}/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(` ${Z.dim(e.padEnd(c))} ${n}\n`);t(`
251
- `)}catch{}await CL(A)}}catch(t){if(t instanceof L)throw t;let n=t instanceof Error?t.cause:void 0,r=n instanceof Error?n:void 0;if(r&&`code`in r){let t=r.code;return t===`ENOTFOUND`?e.error({code:`DNS_ERROR`,message:`Could not resolve host "${o}". Check the URL and try again.`,exitCode:6}):t===`ECONNREFUSED`?e.error({code:`CONNECTION_REFUSED`,message:`Connection refused by "${o}". Is the server running?`,retryable:!0,exitCode:7}):t===`ECONNRESET`?e.error({code:`CONNECTION_RESET`,message:`Connection to "${o}" was reset.`,retryable:!0,exitCode:56}):t===`ETIMEDOUT`?e.error({code:`CONNECTION_TIMEOUT`,message:`Connection to "${o}" timed out.`,retryable:!0,exitCode:28}):t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?e.error({code:`TLS_ERROR`,message:`TLS certificate error for "${o}". Use --insecure to skip verification.`,exitCode:60}):e.error({code:`REQUEST_FAILED`,message:`Request to "${o}" failed: ${r.message}`})}{let n=t instanceof Error?t.message:String(t);return e.error({code:`REQUEST_FAILED`,message:r?`Request failed: ${n} (Cause: ${r.message})`:`Request failed: ${n}`})}}}}),PL=nb(`account`,{description:`Manage accounts (create, default, delete, export, fund, list, view)`}).command(`create`,{description:`Create new account`,options:f.object({account:f.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:f.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:f.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:f.object({address:f.string(),name:f.string()}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=xL(e),n=e.options.account;if(!n){if((await AO().list()).length===0)n=`main`;else{if(t)return e.error({code:`ACCOUNT_REQUIRED`,message:`Account name is required in structured mode.`,exitCode:2});let r=await aO(`Account name`);if(!r)return;n=r}}let r=AO(n);for(;await r.get();){if(t)return e.error({code:`ACCOUNT_EXISTS`,message:`Account "${n}" already exists.`,exitCode:1});process.stderr.write(`${Z.dim(`Account "${n}" already exists.`)}\n\n`);let i=await aO(`Enter different name`);if(!i)return;n=i,r=AO(n)}let i=pe(),a=he(i);await r.set(i),(await AO().list()).length===1&&OO().set(n);let o=ge.blockExplorers?.default?.url,s=o?tO(`${o}/address/${a.address}`,a.address):a.address,c=lO(e.options),l=cO(e.options.rpcUrl,{network:c});return uO({network:c,rpcUrl:l}).then(e=>ne({chain:e,transport:ue(l)})).then(e=>import(`viem/tempo`).then(({Actions:t})=>t.faucet.fund(e,{account:a}).catch(()=>{}))),SL(e,{address:a.address,name:n},()=>{console.log(`Account "${n}" saved to keychain.`),console.log(Z.dim(`Address ${s}`)),console.log(Z.dim(`Fund testnet tokens: mppx account fund --account ${n} --network testnet`))})}}).command(`default`,{description:`Set default account`,options:f.object({account:f.string().describe(`Account name`)}),output:f.object({name:f.string()}),alias:{account:`a`},async run(e){let t=e.options.account;return iO(t)?fP(t)?(OO().set(t),SL(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69}):await AO(t).get()?(OO().set(t),SL(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69})}}).command(`delete`,{description:`Delete account`,options:f.object({account:f.string().describe(`Account name`),yes:f.boolean().optional().describe(`DANGER!! Skip confirmation prompts`)}),output:f.object({defaultAccount:f.string().optional(),name:f.string()}),alias:{account:`a`},async run(e){let t=AO(e.options.account),n=await t.get();if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${e.options.account}" not found.`,exitCode:69});let r=he(n),i=await hO(r.address,{includeTestnet:!1});if(!e.options.yes){if(xL(e))return e.error({code:`CONFIRMATION_REQUIRED`,message:`Pass --yes to delete an account in structured mode.`,exitCode:2});let t=ge.blockExplorers?.default?.url,n=t?tO(`${t}/address/${r.address}`,r.address):r.address;process.stderr.write(Z.dim(`Delete account "${e.options.account}"\n`)),process.stderr.write(Z.dim(` Address ${n}\n`));for(let e=0;e<i.length;e++)process.stderr.write(Z.dim(` ${e===0?`Balance`:` `} ${i[e]}\n`));if(process.stderr.write(Z.dim(`This action cannot be undone
243
+ `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await ZN({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId,fetchUrl:t.fetchUrl,fetchInit:t.fetchInit,session:t.session,info:t.info,verbose:t.verbose,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,confirmEnabled:!1})}async function ZN(e){let t=await e.session.signVoucher({channelId:e.channelId,cumulativeAmount:e.cumulativeAmount,escrowContract:e.escrowContract,chainId:e.chainId,action:`close`}),n=await globalThis.fetch(e.fetchUrl,{...e.fetchInit,headers:{..._w(e.fetchInit.headers),Authorization:t}});if(n.ok){if(uP(e.channelId),e.verbose>=1){let t=n.headers.get(J.paymentReceipt),r;if(t)try{let e=JSON.parse(O.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${Z.dim(nO(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${Z.dim(`Channel closed.`)} ${Z.dim(`Spent ${cO(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${Z.dim(Z.yellow(`Channel close failed`))} ${Z.dim(`(${n.status})`)}\n`),e.info(`${Z.dim(` channelId: ${e.channelId}`)}\n${Z.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${Z.dim(` escrowContract: ${e.escrowContract}`)}\n${Z.dim(` chainId: ${e.chainId}`)}\n${Z.dim(` response: ${t||`(empty)`}`)}\n`)}}function QN(e=100){return!process.stdin.isTTY||!process.stdout.isTTY?Promise.resolve(void 0):new Promise(t=>{let n=process.stdin.isRaw,r=``,i=()=>{clearTimeout(a),process.stdin.removeListener(`data`,o),process.stdin.isTTY&&process.stdin.setRawMode(n??!1),process.stdin.pause()},a=setTimeout(()=>{i(),t(void 0)},e),o=e=>{r+=e.toString();let n=r.match(/\x1b\]11;rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!n)return;i();let a=e=>Number.parseInt(e.slice(0,2),16);t({r:a(n[1]),g:a(n[2]),b:a(n[3])})};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,o),process.stdout.write(`\x1B]11;?\x07`)})}function $N(e){return rP(yP,e,bP)}function eP(e){return e.method===`tempo`&&e.intent===`charge`}async function tP(e){let t=AO(e.options.account),n=process.env.MPPX_PRIVATE_KEY?.trim()||(aO(t)?void 0:await jO(t).get()),r;if(n)r=he(n).address;else if(aO(t)&&mP())r=pP(t)?.wallet_address;else{let e=gP();if(e){let t=await jO(e).get();t&&(r=he(t).address)}}if(!r)return;let i=lO(e.options.rpcUrl,{network:e.options.network}),a=M({chain:await dO({network:e.options.network,rpcUrl:i}),transport:ue(i)});return{account:r,client:a}}async function nP(e,t){let n=e.request,r=n.currency,i=n.amount;if(typeof r!=`string`||typeof i!=`string`)return`unsupported`;let a=n.methodDetails?.chainId;if(a&&t.client.chain?.id&&a!==t.client.chain.id)return`unsupported`;let o=BigInt(i);if(o===0n)return`payable`;let s=await ke.token.getBalance(t.client,{account:t.account,token:r}).then(e=>e.amount).catch(()=>void 0);return s===void 0?`unknownBalance`:s>=o?`payable`:`insufficientBalance`}function rP(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function iP(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new L({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function aP(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function oP(e){let t=aP(e.tokenIn)??aP(e.payWith);if(!(!e.autoSwap&&!t&&e.slippage===void 0)){if(e.autoSwap===!1&&!t&&e.slippage===void 0)return!1;if(e.slippage!==void 0&&(!Number.isFinite(e.slippage)||e.slippage<0))throw Error(`Invalid CLI options (slippage: expected a non-negative number)`);return{...t?{tokenIn:t}:{},...e.slippage===void 0?{}:{slippage:e.slippage}}}}function sP(){return s.join(process.env.XDG_CONFIG_HOME||s.join(y.homedir(),`.config`),`mppx`,`channels`)}function cP(t){try{let n=e.readFileSync(s.join(sP(),t),`utf-8`).trim();return n?BigInt(n):void 0}catch{return}}function lP(t,n){let r=sP();e.mkdirSync(r,{recursive:!0}),e.writeFileSync(s.join(r,t),n.toString(),`utf-8`)}function uP(t){try{e.unlinkSync(s.join(sP(),t))}catch{}}function dP(){return y.platform()===`darwin`?s.join(y.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):s.join(process.env.XDG_DATA_HOME||s.join(y.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function fP(){try{let t=e.readFileSync(dP(),`utf-8`),n=[],r;for(let e of t.split(`
244
+ `)){let t=e.trim();if(t===`[[keys]]`){r?.wallet_address&&n.push(r),r={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!r)continue;let i=t.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?r.wallet_type=o:a===`wallet_address`?r.wallet_address=o:a===`chain_id`&&(r.chain_id=Number.parseInt(o,10))}return r?.wallet_address&&n.push(r),n}catch{return[]}}function pP(e){let t=fP();if(t.length===0)return;let n=e.slice(6);if(n==="default"||n===``)return t[0];let r=Number.parseInt(n,10);if(!Number.isNaN(r)&&r>=0&&r<t.length)return t[r]}function mP(){if(SP!==void 0)return SP;try{p.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),SP=!0}catch{SP=!1}return SP}async function hP(e){return new Promise((t,n)=>{p.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function gP(){let e=kO();if(aO(e.get())&&!mP()&&y.platform()===`darwin`)try{let t=p.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===_P&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}var _P,vP,yP,bP,xP,SP,CP=I((()=>{Sx(),tT(),kx(),YS(),UN(),vE(),Lj(),LO(),CO(),Pk(),_P=`mppx`,vP=f.union([f.boolean(),f.literal(`true`).transform(()=>!0),f.literal(`false`).transform(()=>!1)]),yP=f.object({allowCustomEscrow:f.optional(vP),autoSwap:f.optional(vP),channel:f.optional(f.coerce.string()),deposit:f.optional(f.union([f.string(),f.number()])),payWith:f.optional(f.string()),slippage:f.optional(f.coerce.number()),tokenIn:f.optional(f.string())}),bP=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`],xP=[`payable`,`unknownBalance`,`insufficientBalance`,`unsupported`]}));xS(),LO(),Pk();const wP=[...Object.entries(VO),...Object.entries(HO),...Object.entries(UO),...Object.entries(WO)];function TP(){return Nk({method:`evm`,supports:EP,async setup({challenge:e,options:t}){let n=e.request,r=n.network?DP(ZO(n.network)):void 0,i=n.network&&n.asset?wP.find(([,e])=>YO(e,n.asset,n.network)):void 0,a=n.extra?.name,o=n.extra?.version,s=n.asset&&n.network&&typeof a==`string`&&typeof o==`string`?zO({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await PO(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...Mk({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function EP(e){if(!yS(e))return!1;let t=e.request,n=t.extra,r=n?.assetTransferMethod;return t.scheme===`exact`&&typeof t.asset==`string`&&typeof t.network==`string`&&typeof n?.name==`string`&&typeof n?.version==`string`&&(r===void 0||r===`eip3009`)}function DP(e){return Object.values(Pe).find(t=>t.id===e)}VS(),CP();const OP=[qN(),Vk(),Fk(),TP()];function kP(e,t){let n=t?.plugins?.find(t=>NP(t,e));if(n)return{plugin:n};let r=OP.find(t=>NP(t,e));if(r)return{plugin:r};let i=MP(t)?.find(t=>t.name===e.method&&t.intent===e.intent);return i?{method:i}:{}}function AP(e,t){let n=MP(t);if(n?.length){let r=ES(e,n,CS(n,t?.paymentPreferences).entries);return r?{challenge:r.challenge,...kP(r.challenge,t)}:void 0}for(let n of e){let e=kP(n,t);if(e.plugin||e.method)return{challenge:n,...e}}}function jP(e){let t=MP(e);if(t?.length)return CS(t,e?.paymentPreferences).header}function MP(e){return Array.isArray(e?.methods)?e.methods.flat():void 0}function NP(e,t){return e.supports?e.supports(t):e.method===t.method}async function PP(e){let t=FP(e);if(!t)return;let n=await import(t);return{config:n.default??n,path:t}}function FP(t){if(t){let n=s.resolve(t);return e.existsSync(n)?n:void 0}let n=process.env.MPPX_CONFIG?.trim();if(n){let t=s.resolve(n);return e.existsSync(t)?t:void 0}}CP(),dS(),Qj(),nN(),dN(),UD();function IP(e){return e??globalThis.fetch.bind(globalThis)}function LP(e,t){let n=e.request.methodDetails?.chainId;if(n!==void 0&&n!==t.chainId)throw Error(`Close challenge changed the session chain.`);if(typeof e.request.recipient!=`string`||e.request.recipient.toLowerCase()!==t.descriptor.payee.toLowerCase())throw Error(`Close challenge changed the session payee.`);if(typeof e.request.currency!=`string`||e.request.currency.toLowerCase()!==t.descriptor.token.toLowerCase())throw Error(`Close challenge changed the session token.`);if(Gj(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Error(`Close challenge changed the session escrow.`);let r=uD(e);if(r&&r.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Close challenge changed the session channel.`)}async function RP(e){LP(e.challenge,e.channel);let t=IP(e.fetch),n,r=async(r,i)=>{n&&=(await e.onChallenge?.(n),void 0);let a=await t(r,i);if(a.status!==402)return a;let o=nS(a).find(cD);if(!o)throw Error(`Refreshed close response did not include tempo/session.`);return LP(o,e.channel),n=o,a},i=uN({...e.manager,bootstrap:!1,escrow:e.channel.escrow,fetch:r});eN(i).rehydrate(e);let a=await i.close();if(!a)throw Error(`Session close response did not include a payment receipt.`);return{manager:i,receipt:a}}dS(),Qj(),iM(),UD(),xj(),Gx();var zP=class extends Error{name=`SessionStateError`;code=`SESSION_STATE_INVALID`;file;constructor(e,t={}){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.file=t.file}},BP=class extends Error{name=`SessionBusyError`;code=`SESSION_BUSY`;exitCode=75;scope;owner;constructor(e,t){super(`Session scope is busy in process ${t.pid} on ${t.hostname}.`),this.scope=e,this.owner=t}};const VP=Y.object({channelId:Vx(),cumulativeAmount:Y.string(),deposit:Y.string(),descriptor:Y.object({payer:Bx(),payee:Bx(),operator:Bx(),token:Bx(),salt:Vx(),authorizedSigner:Bx(),expiringNonceHash:Vx()}),escrow:Bx(),chainId:Y.number(),opened:Y.boolean()}),HP=Y.object({name:Y.optional(Y.string()),address:Bx()}),UP=Y.object({method:Y.literal(`tempo`),intent:Y.literal(`session`),status:Y.literal(`success`),timestamp:Y.string(),reference:Y.string(),challengeId:Y.string(),channelId:Vx(),acceptedCumulative:Y.string(),spent:Y.string(),units:Y.optional(Y.number()),txHash:Y.optional(Vx())}),WP=Y.object({version:Y.literal(1),method:Y.literal(`tempo`),intent:Y.literal(`session`),status:Y.enum([`opening`,`open`,`closing`,`stale`]),channel:VP,account:HP,endpoint:Y.string(),challenge:uS,receipt:Y.optional(UP),spent:Y.string(),units:Y.number(),createdAt:Y.string(),updatedAt:Y.string()}),GP=Y.object({version:Y.literal(1),channelId:Vx()}),KP=Y.object({version:Y.literal(1),scope:Y.string(),hostname:Y.string(),pid:Y.number(),token:Y.string(),createdAt:Y.string()});function qP(e,t,n,r){let i=e.safeParse(t);if(!i.success)throw Q(n,r,i.error);return i.data}function JP(e){let t=iF(e);return[t.payer,t.payee,t.token,t.escrow,t.chainId].join(`:`)}function YP(e){return{payer:e.descriptor.payer,payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId}}function XP(e={}){let t=e.stateRoot??QP(),n={root:t,channels:s.join(t,`channels`),locks:s.join(t,`locks`),preferred:s.join(t,`preferred`)},r=e.hostname??y.hostname(),i=e.pid??process.pid,a=e.now??(()=>new Date),o=e.isProcessAlive??AF;async function c(){for(let e of[n.root,n.channels,n.locks,n.preferred])await S.mkdir(e,{recursive:!0,mode:448}),await S.chmod(e,448)}async function l(e){let t=nF(e),r=$P(n,t),i=await xF(r);if(i===void 0)return;let a=fF(i,r);if(a.channel.channelId.toLowerCase()!==t)throw Q(r,`Session filename does not match its channel ID.`);return pF(a)}async function u(){let e;try{e=await S.readdir(n.channels,{withFileTypes:!0})}catch(e){if(MF(e,`ENOENT`))return[];throw Q(n.channels,`Unable to list managed sessions.`,e)}let t=[];for(let n of e){if(!n.isFile()||n.name.includes(`.tmp-`)||!n.name.endsWith(`.json`))continue;let e=n.name.slice(0,-5);nF(e);let r=await l(e);r&&t.push(r)}return t.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}async function d(e){await c();let t=cF(e.channel),r=nF(t.channelId),i=$P(n,r),o=await xF(i),s=o===void 0?void 0:fF(o,i);s&&mF(s,e,i);let l=uF(e.challenge,i);gF(l,t,i);let u=e.receipt?dF(e.receipt,t.channelId,i):void 0,d=s?rM(s.channel):void 0,f=bF(t.cumulativeAmount,d?.cumulativeAmount??0n),p=bF(e.spent??0n,u?BigInt(u.spent):0n,s?BigInt(s.spent):0n);if(p>f)throw Q(i,`Session spend exceeds the locally authorized cumulative amount.`);let m=lF(nM({...t,cumulativeAmount:f}),i),h=yF(s?.updatedAt,a(),i),g=vF(s?.receipt,u),_=sF(e.account,i),v=fF({version:1,method:`tempo`,intent:`session`,status:e.status,channel:m,account:{..._.name===void 0?s?.account.name===void 0?{}:{name:s.account.name}:{name:_.name},address:_.address},endpoint:oF(e.endpoint,i),challenge:l,...g!==void 0&&{receipt:g},spent:p.toString(),units:Math.max(s?.units??0,e.units??0,u?.units??0),createdAt:s?.createdAt??h,updatedAt:h},i);return await SF(i,v),pF(v)}async function f(e){let t=tF(n,e),r=await xF(t);if(r===void 0)return;let{channelId:i}=qP(GP,r,t,`Preferred session is invalid.`),a=await l(i);if(!a)throw Q(t,`Preferred session ${i} does not exist.`);return _F(a.channel,e,t),i}async function p(e,t){let r=nF(t),i=await l(r),a=tF(n,e);if(!i)throw Q(a,`Session ${r} does not exist.`);_F(i.channel,e,a),await SF(a,{version:1,channelId:r})}async function m(e,t){let r=tF(n,e),i=t===void 0?void 0:nF(t),a=await xF(r);if(a===void 0)return;let o=qP(GP,a,r,`Preferred session is invalid.`).channelId;i&&o.toLowerCase()!==i||await OF(r,`Unable to clear preferred session.`)}async function h(e){let t=nF(e),r=await l(t);r&&(await m(YP(r.channel),t),await OF($P(n,t),`Unable to remove session.`))}async function _(e){await c();let t=eF(n,e);for(let n=0;n<3;n++){let n={version:1,scope:e,hostname:r,pid:i,token:g(),createdAt:a().toISOString()};try{if(await CF(t,n),await EF(TF(t))){await DF(t,n);continue}return{async release(){await DF(t,n)}}}catch(e){if(!MF(e,`EEXIST`))throw e}let s=await xF(t);if(s===void 0)continue;let c=qP(KP,s,t,`Session lock is invalid.`);if(c.scope!==e)throw Q(t,`Session lock scope is invalid.`);if(c.hostname!==r||o(c.pid))throw new BP(e,c);await wF(t,c)}let s=await xF(t);throw s===void 0?Q(t,`Unable to acquire session lock.`):new BP(e,qP(KP,s,t,`Session lock is invalid.`))}async function v(e){return _(JP(e))}return{root:t,get:l,list:u,upsert:d,remove:h,getPreferred:f,setPreferred:p,clearPreferred:m,acquire:v}}function ZP(e,t){let n=aF(t.scope),r=t.selection===`auto`||t.selection===`new`?void 0:nF(t.selection);function i(e){if(e.toLowerCase()!==n)throw new zP(`Session manager requested an unexpected payment scope.`)}async function a(n=!0){if(t.selection===`new`&&!r)return;let i=r??await e.getPreferred(t.scope);if(!i)return;let a=await e.get(i);if(!a)throw new zP(`Session ${i} does not exist.`);if(_F(a.channel,t.scope),!(n&&(a.status!==`open`||!a.channel.opened)))return r=i,a}return{async get(e){return i(e),(await a())?.channel},async set(n){if(i(eM(n)),_F(n,t.scope),r&&r.toLowerCase()!==n.channelId.toLowerCase())throw new zP(`Session manager selected ${r}, but attempted to store ${n.channelId}.`);r||t.onNewChannel?.(n);let a=await e.upsert({...t.context(),channel:n});r=a.channel.channelId,await e.setPreferred(t.scope,a.channel.channelId)},async delete(n){i(n);let o=await a(!1);if(!o)return;let s=t.context();await e.upsert({...o,...s,status:s.status===`closing`?`closing`:`stale`,channel:o.channel,spent:s.spent??o.spent,units:s.units??o.units}),s.status!==`closing`&&await e.clearPreferred(t.scope,o.channel.channelId),r=void 0}}}function QP(){let e=process.env.XDG_STATE_HOME||s.join(y.homedir(),`.local`,`state`);return s.join(e,`mppx`,`sessions`,`v1`)}function $P(e,t){return s.join(e.channels,`${t}.json`)}function eF(e,t){let n=h(`sha256`).update(t).digest(`hex`);return s.join(e.locks,`${n}.lock`)}function tF(e,t){let n=h(`sha256`).update(JP(t)).digest(`hex`);return s.join(e.preferred,`${n}.json`)}function nF(e){return qP(Vx(),e,void 0,`Invalid session channel ID: ${e}.`).toLowerCase()}function rF(e,t,n){return qP(Bx(),e,n,`Invalid ${t}.`).toLowerCase()}function iF(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<0)throw new zP(`Invalid session chain ID.`);return{payer:rF(e.payer,`session payer`),payee:rF(e.payee,`session payee`),token:rF(e.token,`session token`),escrow:rF(e.escrow,`session escrow`),chainId:e.chainId}}function aF(e){let t=iF(e);return[t.payee,t.token,t.escrow,t.chainId].join(`:`)}function oF(e,t){if(typeof e!=`string`)throw Q(t,`Session endpoint is invalid.`);let n;try{n=new URL(e)}catch(e){throw Q(t,`Session endpoint is invalid.`,e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Q(t,`Session endpoint must use HTTP or HTTPS.`);if(n.username||n.password)throw Q(t,`Session endpoint must not contain credentials.`);let r=e.indexOf(`#`);return r===-1?e:e.slice(0,r)}function sF(e,t){return qP(HP,e,t,`Session account is invalid.`)}function cF(e){return rM(lF(nM(e)))}function lF(e,t){return qP(VP,e,t,`Stored session channel is invalid.`)}function uF(e,t){let n=uS.safeParse(e);if(!n.success||!cD(n.data))throw Q(t,`Stored session challenge is invalid.`);return n.data}function dF(e,t,n){let r=qP(UP,e,n,`Stored session receipt is invalid.`);if(r.channelId!==t.toLowerCase())throw Q(n,`Stored session receipt has a different channel ID.`);if(r.reference.toLowerCase()!==t.toLowerCase())throw Q(n,`Stored session receipt has a different reference.`);if(BigInt(r.spent)>BigInt(r.acceptedCumulative))throw Q(n,`Stored session receipt spend exceeds its accepted amount.`);return r}function fF(e,t){let n=qP(WP,e,t,`Stored session is invalid.`),{receipt:r,...i}=n,a=n.channel,o=n.account;if(o.address.toLowerCase()!==a.descriptor.payer.toLowerCase())throw Q(t,`Stored session account does not match the channel payer.`);let s=r?dF(r,a.channelId,t):void 0,c=n.spent,l=BigInt(a.cumulativeAmount);if(BigInt(c)>l)throw Q(t,`Stored session spend exceeds its cumulative authorization.`);if(s&&BigInt(s.acceptedCumulative)>l)throw Q(t,`Stored receipt exceeds the cumulative authorization.`);if(Date.parse(n.updatedAt)<Date.parse(n.createdAt))throw Q(t,`Stored session timestamps are not monotonic.`);let u=oF(n.endpoint,t);if(u!==n.endpoint)throw Q(t,`Stored session endpoint contains a fragment.`);let d=uF(n.challenge,t);return gF(d,rM(a),t),{...i,account:o,channel:a,endpoint:u,challenge:d,...s&&{receipt:s}}}function pF(e){return{version:1,status:e.status,channel:rM(e.channel),account:e.account,endpoint:e.endpoint,challenge:e.challenge,...e.receipt&&{receipt:e.receipt},spent:BigInt(e.spent),units:e.units,createdAt:e.createdAt,updatedAt:e.updatedAt}}function mF(e,t,n){let r=cF(t.channel),i=sF(t.account,n),a=rM(e.channel);if(JSON.stringify(hF(r))!==JSON.stringify(hF(a)))throw Q(n,`Session update changed immutable channel identity.`);if(i.address.toLowerCase()!==e.account.address.toLowerCase())throw Q(n,`Session update changed the payer account.`)}function hF(e){return{channelId:e.channelId.toLowerCase(),descriptor:Object.fromEntries(Object.entries(e.descriptor).map(([e,t])=>[e,typeof t==`string`?t.toLowerCase():t])),escrow:e.escrow.toLowerCase(),chainId:e.chainId}}function gF(e,t,n){if(_j({...t.descriptor,chainId:t.chainId,escrow:t.escrow}).toLowerCase()!==t.channelId.toLowerCase())throw Q(n,`Session channel ID does not match its descriptor.`);let r=rF(e.request.recipient,`challenge recipient`,n),i=rF(e.request.currency,`challenge currency`,n);if(r!==t.descriptor.payee.toLowerCase())throw Q(n,`Session challenge payee does not match the channel.`);if(i!==t.descriptor.token.toLowerCase())throw Q(n,`Session challenge token does not match the channel.`);if(Gj(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Q(n,`Session challenge escrow does not match the channel.`);if(jF(e.request.methodDetails)){let r=e.request.methodDetails;if(r.chainId!==void 0&&r.chainId!==t.chainId)throw Q(n,`Session challenge chain does not match the channel.`)}}function _F(e,t,n){let r=iF(t);if(e.descriptor.payer.toLowerCase()!==r.payer||e.descriptor.payee.toLowerCase()!==r.payee||e.descriptor.token.toLowerCase()!==r.token||e.escrow.toLowerCase()!==r.escrow||e.chainId!==r.chainId)throw Q(n,`Session channel does not match the selected payment scope.`)}function vF(e,t){return e?t&&Date.parse(t.timestamp)>=Date.parse(e.timestamp)?t:e:t}function yF(e,t,n){if(!Number.isFinite(t.getTime()))throw Q(n,`Session clock is invalid.`);let r=t.toISOString();return!e||Date.parse(r)>=Date.parse(e)?r:e}function bF(...e){return e.reduce((e,t)=>t>e?t:e,0n)}async function xF(e){let t;try{t=await S.readFile(e,`utf8`)}catch(t){if(MF(t,`ENOENT`))return;throw Q(e,`Unable to read session state.`,t)}try{return JSON.parse(t)}catch(t){throw Q(e,`Session state contains invalid JSON.`,t)}}async function SF(e,t){await S.mkdir(s.dirname(e),{recursive:!0,mode:448}),await S.chmod(s.dirname(e),448);let n=`${e}.tmp-${process.pid}-${g()}`,r;try{r=await S.open(n,`wx`,384),await r.writeFile(`${JSON.stringify(t,null,2)}\n`,`utf8`),await r.sync(),await r.close(),r=void 0,await S.rename(n,e),await S.chmod(e,384),await kF(s.dirname(e))}catch(t){throw await r?.close().catch(()=>void 0),await S.unlink(n).catch(()=>void 0),t instanceof zP?t:Q(e,`Unable to write session state.`,t)}}async function CF(e,t){let n;try{n=await S.open(e,`wx`,384),await n.writeFile(`${JSON.stringify(t)}\n`,`utf8`),await n.sync(),await n.close(),n=void 0,await kF(s.dirname(e))}catch(t){throw await n?.close().catch(()=>void 0),n&&await S.unlink(e).catch(()=>void 0),t}}async function wF(e,t){let n=TF(e);try{await S.link(e,n)}catch(t){if(MF(t,`EEXIST`)||MF(t,`ENOENT`))return;throw Q(e,`Unable to claim dead lock.`,t)}try{let r=await xF(n);if(r===void 0||qP(KP,r,n,`Session lock is invalid.`).token!==t.token)return;await OF(e,`Unable to reclaim dead lock.`)}finally{await OF(n,`Unable to release dead lock claim.`)}}function TF(e){return`${e}.reclaim`}async function EF(e){try{return await S.access(e),!0}catch(t){if(MF(t,`ENOENT`))return!1;throw Q(e,`Unable to inspect session lock.`,t)}}async function DF(e,t){let n=await xF(e);n!==void 0&&qP(KP,n,e,`Session lock is invalid.`).token===t.token&&await OF(e,`Unable to release session lock.`)}async function OF(e,t){try{await S.unlink(e),await kF(s.dirname(e))}catch(n){if(!MF(n,`ENOENT`))throw Q(e,t,n)}}async function kF(e){let t=await S.open(e,`r`);try{await t.sync()}finally{await t.close()}}function AF(e){try{return process.kill(e,0),!0}catch(e){if(MF(e,`ESRCH`))return!1;if(MF(e,`EPERM`))return!0;throw e}}function jF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function MF(e,t){return e instanceof Error&&`code`in e&&e.code===t}function Q(e,t,n){return new zP(t,{...n!==void 0&&{cause:n},file:e})}Sx(),tT(),KM(),lM(),xj(),LO(),CO();const NF=f.object({status:f.enum([`opening`,`open`,`closing`,`stale`]),channelId:f.string(),account:f.string().optional(),payer:f.string(),payee:f.string(),authorizedSigner:f.string(),token:f.string(),escrow:f.string(),chainId:f.number(),cumulativeAmount:f.string(),confirmedSpend:f.string(),deposit:f.string(),units:f.number(),resourceUrl:f.string(),createdAt:f.string(),updatedAt:f.string()}),PF=f.object({channelId:f.string(),status:f.enum([`closed`,`already-closed`]),spent:f.string(),txHash:f.string().optional()}),FF=f.object({closed:f.array(PF),failed:f.array(f.object({channelId:f.string(),message:f.string()}))});function IF(e){return e===`mainnet`?ge.id:_e.id}function LF(e){if(e===ge.id)return`mainnet`;if(e===_e.id)return`testnet`}function RF(e){let t={};for(let n of e??[]){let e=n.indexOf(`:`);if(e===-1)throw new L({code:`INVALID_HEADER`,message:`Invalid header format: ${n}`,exitCode:2});t[n.slice(0,e).trim()]=n.slice(e+1).trim()}return t}function zF(e){return{status:e.status,channelId:e.channel.channelId,...e.account.name&&{account:e.account.name},payer:e.channel.descriptor.payer,payee:e.channel.descriptor.payee,authorizedSigner:e.channel.descriptor.authorizedSigner,token:e.channel.descriptor.token,escrow:e.channel.escrow,chainId:e.channel.chainId,cumulativeAmount:e.channel.cumulativeAmount.toString(),confirmedSpend:e.spent.toString(),deposit:e.channel.deposit.toString(),units:e.units,resourceUrl:e.endpoint,createdAt:e.createdAt,updatedAt:e.updatedAt}}function BF(e,t){throw e instanceof L?e:e instanceof BP?new L({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e instanceof zP?new L({code:e.code,message:e.message,exitCode:65,cause:e}):new L({code:t,message:e instanceof Error?e.message:String(e),exitCode:75,...e instanceof Error&&{cause:e}})}async function VF(e,t){let n=await NO(t??e.account.name);if(!AM(n.account,e.channel.descriptor))throw new L({code:`SESSION_ACCOUNT_MISMATCH`,message:`Account ${n.account.address} cannot sign for session ${e.channel.channelId}.`,exitCode:2});return n}async function HF(e,t){if(t.network&&IF(t.network)!==e)throw new L({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, not ${t.network}.`,exitCode:2});let n=t.network??LF(e),r=lO(t.rpcUrl,{network:n}),i=await dO({network:n,rpcUrl:r});if(i.id!==e)throw new L({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, but RPC is chainId ${i.id}.`,exitCode:2});return M({chain:i,transport:ue(r)})}const UF=nb(`sessions`,{description:`Manage persistent payment sessions (list, view, close)`}).command(`list`,{description:`List persistent payment sessions`,options:f.object({account:f.string().optional().describe(`Filter by account name`),network:f.enum([`mainnet`,`testnet`]).optional().describe(`Filter by Tempo network`)}),output:f.object({sessions:f.array(NF)}),alias:{account:`a`},async run(e){try{let t=(await XP().list()).filter(t=>!(e.options.account&&t.account.name!==e.options.account||e.options.network&&t.channel.chainId!==IF(e.options.network))).map(zF),n={sessions:t};if(e.format===`json`&&e.formatExplicit)return e.ok(n);t.length===0&&console.log(`No sessions.`);for(let[e,n]of t.entries())e>0&&console.log(``),WF(n);return}catch(e){return BF(e,`SESSION_LIST_FAILED`)}}}).command(`view`,{description:`View a persistent payment session`,args:f.object({channelId:f.string().describe(`Full session channel ID`)}),output:NF,async run(e){try{let t=await XP().get(e.args.channelId);if(!t)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${e.args.channelId} was not found.`,exitCode:2});let n=zF(t);if(e.format===`json`&&e.formatExplicit)return e.ok(n);WF(n);return}catch(e){return BF(e,`SESSION_VIEW_FAILED`)}}}).command(`close`,{description:`Cooperatively close persistent payment sessions`,usage:[{suffix:`<channel-id> [options]`},{suffix:`--all --yes [options]`}],args:f.object({channelId:f.string().optional().describe(`Full session channel ID`)}),options:f.object({account:f.string().optional().describe(`Account name`),all:f.boolean().optional().default(!1).describe(`Close every matching session`),header:f.array(f.string()).optional().describe(`Add close request header (repeatable)`),network:f.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:f.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`),url:f.string().optional().describe(`Override the stored resource URL`),yes:f.boolean().optional().default(!1).describe(`Confirm closing every session`)}),output:f.union([PF,FF]),alias:{account:`a`,header:`H`,rpcUrl:`r`},async run(e){if(e.options.all&&e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all, not both.`,exitCode:2});if(!e.options.all&&!e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all.`,exitCode:2});if(e.options.all&&!e.options.yes)return e.error({code:`CONFIRMATION_REQUIRED`,message:`Closing all sessions requires --yes.`,exitCode:2});if(e.options.all&&(e.options.header||e.options.rpcUrl||e.options.url))return e.error({code:`INVALID_SESSION_CLOSE`,message:`--header, --rpc-url, and --url only apply to a single session.`,exitCode:2});let t=XP();async function n(e,n={}){let r=await t.get(e);if(!r)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let i=YP(r.channel),a=await t.acquire(i);try{let r=await t.get(e);if(!r)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let a=await VF(r,n.account),o=await HF(r.channel.chainId,n);if(_j({...r.channel.descriptor,escrow:r.channel.escrow,chainId:r.channel.chainId}).toLowerCase()!==r.channel.channelId.toLowerCase())throw new L({code:`SESSION_STATE_INVALID`,message:`Stored descriptor does not derive the session channel ID.`,exitCode:65});if((await oM(o,r.channel.channelId,r.channel.escrow)).deposit===0n)return await t.remove(r.channel.channelId),{channelId:r.channel.channelId,status:`already-closed`,spent:r.spent.toString()};let s=oF(n.resourceUrl??r.endpoint),c={...a.source===`keychain`&&{name:a.accountName},address:a.account.address},l=(e=r.challenge)=>({status:`closing`,account:c,endpoint:s,challenge:e,...r.receipt&&{receipt:r.receipt},spent:r.spent,units:r.units}),u=await t.upsert({...l(),channel:r.channel}),d=RF(n.headers),f=u.challenge,p=await RP({channel:u.channel,challenge:u.challenge,fetch:async(e,t)=>globalThis.fetch(e,{...t,headers:{...d,..._w(t?.headers)}}),input:s,spent:u.spent,async onChallenge(e){f=e,await t.upsert({...l(e),channel:u.channel})},manager:{account:a.account,client:o,channelStore:ZP(t,{scope:i,selection:u.channel.channelId,context:()=>l(f)})}});return await t.remove(u.channel.channelId),{channelId:u.channel.channelId,status:`closed`,spent:p.receipt.spent,txHash:p.receipt.txHash}}finally{await a.release()}}try{if(e.options.all){let r=(await t.list()).filter(t=>(!e.options.account||t.account.name===e.options.account)&&(!e.options.network||t.channel.chainId===IF(e.options.network))),i=[],a=[];for(let t of r)try{i.push(await n(t.channel.channelId,{account:e.options.account,network:e.options.network}))}catch(e){a.push({channelId:t.channel.channelId,message:e instanceof Error?e.message:String(e)})}let o={closed:i,failed:a};if(a.length>0){for(let e of a)process.stderr.write(`${e.channelId}: ${e.message}\n`);process.exitCode=1}if(e.format===`json`&&e.formatExplicit)return e.ok(o);for(let e of i)console.log(`${e.channelId} ${e.status} ${e.spent}`);for(let e of a)console.log(`${e.channelId} failed ${e.message}`);return}let r=await n(e.args.channelId,{account:e.options.account,headers:e.options.header,network:e.options.network,resourceUrl:e.options.url,rpcUrl:e.options.rpcUrl});if(e.format===`json`&&e.formatExplicit)return e.ok(r);console.log(`${r.channelId} ${r.status} ${r.spent}`),r.txHash&&console.log(` transaction ${r.txHash}`);return}catch(e){return BF(e,`SESSION_CLOSE_FAILED`)}}});function WF(e){console.log(e.channelId),console.log(` status ${e.status}`),console.log(` cumulative amount ${e.cumulativeAmount}`),console.log(` confirmed spend ${e.confirmedSpend}`),console.log(` deposit ${e.deposit}`),console.log(` chain ${e.chainId}`),console.log(` payer ${e.payer}`),console.log(` payee ${e.payee}`),console.log(` token ${e.token}`),console.log(` resource ${e.resourceUrl}`)}Sx(),KM(),nN(),dN(),vE(),LO(),CO();function GF(e,t){if(t&&e!==`auto`&&t.toLowerCase()!==e.toLowerCase())throw new L({code:`SESSION_SELECTION_CONFLICT`,message:`--session and -M channel= select different sessions.`,exitCode:2});let n=t??e;if(n===`auto`||n===`new`)return n;if(/^0x[0-9a-fA-F]{64}$/.test(n))return n.toLowerCase();throw new L({code:`INVALID_SESSION`,message:`Session must be auto, new, or a 32-byte channel ID.`,exitCode:2})}function KF(e){return typeof e.request.decimals==`number`?e.request.decimals:6}function qF(e){let t=e.allowCustomEscrow;if(t!==void 0){if(t===`true`)return!0;if(t===`false`)return!1;throw new L({code:`INVALID_ALLOW_CUSTOM_ESCROW`,message:`allowCustomEscrow must be true or false.`,exitCode:2})}}function JF(e,t,n){if(t.deposit!==void 0)return t.deposit;let r=e.request.suggestedDeposit;return typeof r==`string`?se(BigInt(r),KF(e)):n?`10`:void 0}function YF(e,t){if(!e)return;if(e.challengeId!==t.challenge.id)throw Error(`Session receipt challenge does not match the paid request.`);if(e.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Session receipt channel does not match the selected channel.`);let n=BigInt(e.acceptedCumulative),r=BigInt(e.spent);if(n>t.cumulative)throw Error(`Session receipt exceeds the local cumulative authorization.`);if(r>n)throw Error(`Session receipt spend exceeds its accepted authorization.`);return e}function XF(e,t){return e.channel.channelId.toLowerCase()===t.toLowerCase()}function ZF(e){if(e.trim()!==`[DONE]`){if(e.length===0){process.stdout.write(`
245
+ `);return}try{let t=JSON.parse(e);process.stdout.write(t.token??t.choices?.[0]?.delta?.content??e)}catch{process.stdout.write(e)}}}async function QF(e){let{options:t}=e,n=await NO(t.account),r=lO(t.rpcUrl,{network:t.network}),i=await dO({network:t.network,rpcUrl:r}),a=M({chain:i,transport:ue(r)}),o=qF(e.methodOptions),s=await wM({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new L({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let c={payer:n.account.address,payee:s.payee,token:s.token,escrow:s.escrow,chainId:s.chainId},l=GF(t.session,e.methodOptions.channel),u=e.registry??XP(),d=await u.acquire(c).catch(e=>{throw e instanceof BP?new L({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=l===`auto`?await u.getPreferred(c):l===`new`?void 0:l,s=r?await u.get(r):void 0;if(r&&!s)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&l!==`auto`&&(s.status!==`open`||!s.channel.opened||JP(YP(s.channel))!==JP(c)||!AM(n.account,s.channel.descriptor)))throw new L({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let d=s?.status===`open`&&s.channel.opened?s:void 0,f=d?`open`:`opening`,p=e.challenge,m=d?.receipt,h=d?.spent??0n,g=d?.units??0,_=oF(e.endpoint),v={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},y=ZP(u,{scope:c,selection:l,context:()=>({status:f,account:v,endpoint:_,challenge:p,...m&&{receipt:m},spent:h,units:g}),onNewChannel(){f=`opening`,m=void 0,h=0n,g=0}}),{signal:b,...x}=e.init,S={...x,...b&&{signal:b},onReceipt(e){m=e,h=h>BigInt(e.spent)?h:BigInt(e.spent),g=Math.max(g,e.units??0)}};if(e.challengeResponse.status!==402||e.challengeResponse.bodyUsed)throw Error(`Session manager requires an unconsumed 402 challenge response.`);let C=!0,w=uN({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:y,decimals:KF(e.challenge),maxDeposit:JF(e.challenge,e.methodOptions,mO(i)),fetch:async(t,n)=>C?(C=!1,e.challengeResponse):e.fetch(t,n)});d&&eN(w).rehydrate({channel:d.channel,challenge:e.challenge,input:e.fetchInput,spent:d.spent});let{onReceipt:T,...ee}=S,E=await w.fetch(e.fetchInput,ee);if(t.fail&&E.status>=400)throw new L({code:`HTTP_ERROR`,message:`HTTP error ${E.status}`,exitCode:22});if(E.status===402)throw new L({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});QD(E,{include:!1,verbose:t.include?Math.max(t.verbose,2):t.verbose,silent:t.silent}),p=E.challenge??e.challenge;let D=w.channelId;if(!D)throw Error(`Session manager did not select a channel.`);if(m=YF(E.receipt,{challenge:p,channelId:D,cumulative:w.cumulative})??m,cE(E)){let t=eN(w).consumeSseResponse(e.fetchInput,E,{onReceipt:T,signal:e.init.signal??void 0});for await(let e of t)ZF(e)}else process.stdout.write(Buffer.from(await E.arrayBuffer()));let O=await u.get(D);if(!O||!XF(O,D))throw Error(`Session ${D} was not persisted.`);if(m){let e=YF(m,{challenge:p,channelId:D,cumulative:w.cumulative});if(!e)throw Error(`Session receipt validation failed.`);m=e,h=h>BigInt(e.spent)?h:BigInt(e.spent),g=Math.max(g,e.units??0),f=`open`}await u.upsert({status:f,channel:O.channel,account:v,endpoint:_,challenge:p,...m&&{receipt:m},spent:h,units:g}),t.silent||(e.info(`Session retained ${D}\n`),e.info(`Close with: mppx sessions close ${D}\n`))}finally{await d.release()}}CO();function $F(e,t){return t?{label:e,detail:t,severity:`pass`}:{label:e,severity:`pass`}}function $(e,t,n){let r={label:e,severity:`fail`};return t&&(r.detail=t),n&&(r.hint=n),r}function eI(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function tI(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}const nI={pass:Z.green(`✓`),fail:Z.red(`✗`),warn:Z.yellow(`⚠`),skip:Z.dim(`○`)};function rI(e){let t=nI[e.severity],n=e.detail?`${e.label} (${e.detail})`:e.label;console.log(` ${t} ${n}`),e.hint&&e.severity!==`pass`&&console.log(Z.dim(` → ${e.hint}`))}function iI(e){console.log(`\n${Z.bold(e)}`)}function aI(e,t){for(let n of e)rI(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`skip`&&t.skipped++}async function oI(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{return await fetch(e,{...t,signal:r.signal})}finally{clearTimeout(i)}}function sI(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const cI=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function lI(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function uI(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function dI(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!cI.has(n))return null;let r=e.slice(t+1);if(!r)return null;let i=r.startsWith(`/`)?r:`/`+r;return{method:n.toUpperCase(),path:i}}function fI(e,t){if(e){try{let n=JSON.parse(e);if(n&&typeof n==`object`&&!Array.isArray(n)){let e=Object.keys(n);if(e.length>0&&e.every(e=>e.startsWith(`/`))){let e=n[t];return e===void 0?void 0:typeof e==`string`?e:JSON.stringify(e)}}}catch{}return e}}function pI(e){if(!e)return{};let t={};for(let n of e){let e=n.indexOf(`:`);e>0&&(t[n.slice(0,e).trim().toLowerCase()]=n.slice(e+1).trim())}return t}async function mI(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await oI(t,{});if(!e.ok)return{error:`HTTP ${e.status}`};let n=await e.text();return{doc:JSON.parse(n),raw:n}}catch(e){return e instanceof DOMException&&e.name===`AbortError`?{error:`Request timed out after 15s`}:e instanceof SyntaxError?{error:`Invalid JSON`}:{error:e.message}}}function hI(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=vI(i.parameters);for(let[a,o]of Object.entries(i)){if(!cI.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=yI(r,vI(i.parameters)),c=s.length>0?s:void 0;if(i[`x-payment-info`]){let n=i[`x-payment-info`];t.push({method:a.toUpperCase(),path:e,amount:n.amount,parameters:c})}else{let t=i.responses;t&&`402`in t&&n.push({method:a.toUpperCase(),path:e,parameters:c})}}}return t.length>0?t:n}function gI(e,t){let n=e.paths;if(!n)return;let r=n[t.path];if(!r)return;let i=r[t.method.toLowerCase()];if(!i?.requestBody)return;let a=i.requestBody.content?.[`application/json`];if(!a)return;if(a.example)return JSON.stringify(a.example);if(a.examples&&typeof a.examples==`object`){let e=Object.values(a.examples)[0];if(e?.value)return JSON.stringify(e.value)}let o=a.schema,s=new Set;if(o=xI(o,e,s),!o||o.type!==`object`)return;let c=SI(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function _I(e,t,n){let r=t.path;t.parameters&&(r=bI(r,t.parameters));let i=r.startsWith(`/`)?r.slice(1):r,a=new URL(i,e.replace(/\/?$/,`/`)).href;if(n){let e=new URL(a);for(let t of n){let[n,...r]=t.split(`=`);n&&e.searchParams.set(n,r.join(`=`))}a=e.href}return a}function vI(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;e.in===`path`&&typeof e.name==`string`&&t.push(e.schema&&typeof e.schema==`object`?{name:e.name,in:`path`,schema:e.schema,example:e.example}:{name:e.name,in:`path`,example:e.example})}return t}function yI(e,t){let n=[...e];for(let e of t){let t=n.findIndex(t=>t.name===e.name);t>=0?n[t]=e:n.push(e)}return n}function bI(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{let r=t.find(e=>e.name===n&&e.in===`path`);if(!r)return e;let i=r.example??r.schema?.example??r.schema?.default;return i===void 0?e:encodeURIComponent(String(i))})}function xI(e,t,n){if(!e||typeof e.$ref!=`string`)return e;if(n?.has(e.$ref))return;let r=e.$ref.replace(/^#\//,``).split(`/`),i=t;for(let e of r)if(i&&typeof i==`object`)i=i[e];else return;return i}function SI(e,t,n){let r=xI(e,t,n)??e;if(r.const!==void 0)return r.const;if(r.example!==void 0)return r.example;if(r.default!==void 0)return r.default;switch(r.type){case`string`:return r.enum&&Array.isArray(r.enum)?r.enum[0]:r.format===`email`?`test@example.com`:r.format===`uuid`?`00000000-0000-0000-0000-000000000000`:r.format===`uri`||r.format===`url`?`https://example.com`:r.format===`date`?`2026-01-01`:r.pattern===`^\\d{5}(?:-\\d{4})?$`?`10001`:r.pattern===`^[A-Z]{2}$`?`US`:`test`;case`number`:case`integer`:return r.minimum??1;case`boolean`:return!0;case`array`:return[];case`object`:{let e=r.properties;if(!e)return{};let i=r.required||[],a={};for(let r of i){let i=e[r];i&&(a[r]=SI(i,t,n))}return a}default:return null}}dS(),kx(),YC(),CO();const CI=Object.values(Pe);function wI(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&CI.find(e=>e.id===t.chainId)?.testnet===!0}async function TI(e,t,n,r){let i=[],a=_I(e,t,r?.query),o=pI(r?.extraHeaders),s;r?.body&&!r.bodyIsAutogenerated&&(s=r.body,o[`content-type`]||=`application/json`);let c;try{let e={method:t.method};Object.keys(o).length>0&&(e.headers=o),s&&(e.body=s),c=await oI(a,e)}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}if(!s&&(c.status===400||c.status===422)){let e=r?.body??(r?.discoveryDoc?gI(r.discoveryDoc,t):void 0);if(e){n&&console.log(Z.dim(` Retrying with body: ${e}`)),s=e,o[`content-type`]=`application/json`;try{c=await oI(a,{method:t.method,headers:o,body:s})}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}}}if(c.status!==402)return c.status===200?i.push(tI(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(tI(`Returns 402 without credentials`,`Got ${c.status} (endpoint requires auth before payment gate)`)):i.push($(`Returns 402 without credentials`,`Got ${c.status} instead`,c.status===400||c.status===422?`Server requires a valid request body before returning 402. Add a requestBody schema with examples to your OpenAPI doc, or use --body.`:`Endpoints that require payment must return HTTP 402 with a WWW-Authenticate: Payment header when no valid credential is provided.`)),{results:i};i.push($F(`Returns 402 without credentials`));let l=c.headers.get(J.wwwAuthenticate),u=II(c);if(!l)return u.length>0?(i.push(tI(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(tI(`Not an MPP endpoint`,`No WWW-Authenticate header (may be x402 or other protocol)`)),{results:i};if(u.length>0&&i.push(...u),!l.startsWith(`${wx.payment} `))return i.push(tI(`Not an MPP endpoint`,`WWW-Authenticate scheme is not Payment`)),{results:i};i.push($F(`WWW-Authenticate header present`,`Payment scheme`));let d;try{d=nS(c)}catch(e){let t=e.message;i.push($(`Challenge parseable`,t,`The Payment challenge must include a request="<base64url>" parameter containing JSON-encoded payment details.`));let n=l.slice(l.indexOf(` `)+1);return i.push(eI(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0)return i.push($(`Challenge parseable`,`No Payment challenges found in header`)),{results:i};let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push($F(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=new URL(e).hostname;EI(d,i),DI(d,i),OI(d,i),kI(d,p,i);let m=d.length>1;for(let e of d){let t=e.request;AI(e,t,i,m)}if(n)for(let e of d)console.log(Z.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function EI(e,t){let n=e.filter(e=>!e.id);n.length===0?t.push($F(`Challenge has id`)):t.push($(`Challenge has id`,`${n.length} missing`,`Every challenge must include a unique id field.`))}function DI(e,t){let n=e.filter(e=>!e.realm);n.length===0?t.push($F(`Challenge has realm`)):t.push($(`Challenge has realm`,`${n.length} missing`,`Set realm to your server's hostname.`))}function OI(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(eI(`Challenge has expiration`,`missing expires field`,`Add an expires field (ISO 8601) to prevent replay attacks.`));return}if(new Date(r.expires)<=n){t.push($(`Challenge expires in the future`,`Expired at ${r.expires}`,`The expires timestamp must be in the future.`));return}}let r=Math.min(...e.map(e=>new Date(e.expires).getTime()-n.getTime()));t.push($F(`Challenge expires in the future`,`${Math.round(r/6e4)}m from now`))}function kI(e,t,n){let r=[...new Set(e.map(e=>e.realm??``))].filter(e=>e&&e!==t&&!t.endsWith(`.${e}`));r.length>0?n.push(eI(`Realm matches server hostname`,`realm="${r[0]}" vs host="${t}"`,`Set the realm to your production hostname (or base domain) in the challenge.`)):n.push($F(`Realm matches server hostname`))}function AI(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===Tx.tempo?jI(t,i,n,e):e.method===Tx.stripe?MI(t,i,n):e.method===Tx.evm&&NI(e,t,i,n)}function jI(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if(lI(e.recipient)?n.push($F(`${t}Valid recipient address`)):e.recipient===void 0&&a?n.push($F(`${t}Uses splits (no single recipient)`)):e.recipient===void 0?n.push($(`${t}Valid recipient address`,`Missing recipient (and no splits defined)`,`Set request.recipient to a valid 0x address, or use methodDetails.splits for multiple recipients.`)):n.push($(`${t}Valid recipient address`,`Got: ${String(e.recipient)}`,`Set request.recipient to a valid 0x-prefixed 40-hex-char address.`)),lI(e.currency)){let e=wI(r)?`testnet`:`mainnet`;n.push($F(`${t}Valid currency address`,e))}else n.push($(`${t}Valid currency address`,`Got: ${String(e.currency)}`,`Set request.currency to a valid token address.`));PI(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function MI(e,t,n){PI(e,t,n,`currency's smallest unit (e.g. "100" = $1.00 for USD)`);let r=e.currency;typeof r==`string`&&/^[a-z]{3}$/i.test(r)?n.push($F(`${t}Valid currency code`,r.toUpperCase())):n.push($(`${t}Valid currency code`,r?`Got: ${r}`:`missing`,`Must be a three-letter ISO currency code (e.g. "usd").`));let i=e.methodDetails,a=i?.networkId;a?n.push($F(`${t}Has networkId`,a.slice(0,20))):n.push($(`${t}Has networkId`,`Missing methodDetails.networkId`,`Set methodDetails.networkId to your Stripe Business Network profile ID.`));let o=i?.paymentMethodTypes;Array.isArray(o)&&o.length>0?n.push($F(`${t}Has paymentMethodTypes`,o.join(`, `))):n.push($(`${t}Has paymentMethodTypes`,`Missing or empty`,`Set methodDetails.paymentMethodTypes to an array (e.g. ["card"]).`))}function NI(e,t,n,r){if(lI(t.recipient)?r.push($F(`${n}Valid recipient address`)):r.push($(`${n}Valid recipient address`,`Got: ${String(t.recipient)}`,`Set request.recipient to a valid 0x-prefixed Ethereum address.`)),lI(t.currency)){let t=wI(e)?`testnet`:`mainnet`;r.push($F(`${n}Valid currency address`,t))}else r.push($(`${n}Valid currency address`,`Got: ${String(t.currency)}`,`Set request.currency to a valid ERC-20 token contract address.`));PI(t,n,r,`token's smallest unit`);let i=t.methodDetails?.chainId;typeof i==`number`&&i>0?r.push($F(`${n}Has chainId`,String(i))):r.push($(`${n}Has chainId`,`Missing methodDetails.chainId`,`Set methodDetails.chainId to the EVM chain ID.`))}function PI(e,t,n,r){uI(e.amount)?n.push($F(`${t}Amount is valid integer string`)):e.amount===void 0||e.amount===null?n.push($(`${t}Amount is valid integer string`,`Missing amount`,`Set request.amount to a string of digits in the ${r}.`)):n.push($(`${t}Amount is valid integer string`,`Got: ${String(e.amount)}`,`request.amount must be a string of digits (no decimals, no prefix).`))}async function FI(e,t,n){let r=[],i=_I(e,t,n?.query),a={[J.authorization]:`${wx.payment} dGhpcyBpcyBnYXJiYWdl`},o;n?.body&&(o=n.body,a[`content-type`]=`application/json`);try{let e=await oI(i,{method:t.method,headers:a,body:o??null});e.status===402?(r.push($F(`Malformed credential returns 402`,`not 500`)),e.headers.get(J.wwwAuthenticate)?.startsWith(`${wx.payment} `)?r.push($F(`Error response includes fresh challenge`)):r.push(eI(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the Authorization header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(eI(`Malformed credential returns 402`,`Got ${e.status}`,`When the Authorization header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function II(e){let t=[],n=e.headers.get(`payment-required`)??e.headers.get(`x-payment-required`);if(!n)return t;let r=e.headers.get(`payment-required`)?`PAYMENT-REQUIRED`:`X-Payment-Required`;try{let e=HC(n);t.push($F(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(eI(`x402 payment challenge`,`${r} header present but failed schema validation`,`Ensure the PAYMENT-REQUIRED header contains a valid base64-encoded JSON payload matching the x402 schema.`))}return t}const LI=[`No discovery document found, endpoints could not be automatically found.`,`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,`The MPP SDKs can automatically expose this endpoint. See https://mpp.dev/sdk.`,``,`To test a specific endpoint: mppx validate <url> --endpoint POST:/your/path`].join(`
246
+ `);Gx();const RI={method:Y.string(),reference:Y.string(),externalId:Y.optional(Y.string()),subscriptionId:Y.optional(Y.string()),status:Y.literal(`success`),timestamp:Ix()};Y.object(RI);const zI=Y.looseObject(RI);function BI(e){let t=O.toString(e);return VI(JSON.parse(t))}function VI(e){return zI.parse(e)}dS(),kx(),UN(),YD(),LO(),CO();async function HI(e,t,n){try{n||console.log(Z.dim(` Provisioning testnet wallet and funding via faucet...`));let t=pe(),r=he(t),i=M({chain:_e,transport:ue()}),a=await ke.faucet.fund(i,{account:r});await Promise.all(a.map(e=>Ee(i,{hash:e}))),n||console.log(Z.dim(` Using wallet: ${r.address}`));let o=e.request.currency;if(typeof o==`string`)for(let e=0;e<10;e++){let e=await ke.token.getBalance(i,{account:r.address,token:o}).catch(()=>void 0);if(e&&e.amount>0n)break;await new Promise(e=>setTimeout(e,500))}return{methods:[...zN({account:r})]}}catch(e){t&&console.log(Z.dim(` Provisioning failed: ${e.message}`));return}}async function UI(){let e=AO(),{isTempoAccount:t}=await Promise.resolve().then(()=>(CO(),XD)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(CP(),WN));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await PO()).address}catch{return}}function WI(e){try{let{execSync:t}=p,n=t(`stripe config --list`,{encoding:`utf8`,timeout:5e3}).match(/test_mode_api_key\s*=\s*'([^']+)'/);if(n?.[1])return e&&console.log(Z.dim(` Using Stripe test key from stripe CLI`)),n[1]}catch{}}async function GI(e,t,n){let r=M({chain:e,transport:ue()}),[i,a]=await Promise.all([xe(r,{address:t,abi:oe,functionName:`balanceOf`,args:[n]}),xe(r,{address:t,abi:oe,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,symbol:a??void 0}}function KI(e){return Object.values(Pe).find(t=>t.id===e)}function qI(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function JI(e){switch(e.method){case Tx.evm:return`no EVM payment plugin yet`;case`solana`:return`no Solana payment plugin yet`;default:return`no plugin for ${e.method}/${e.intent}`}}async function YI(e,t,n,r){let i=[],a=_I(e,t,r.query),o=pI(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await oI(a,{method:t.method,headers:o,body:s??null})}catch(e){return i.push($(`Payment: fetch challenge`,e.message)),i}if(c.status!==402)return i.push(tI(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=nS(c)}catch(e){return i.push($(`Payment: parse challenge`,e.message)),i}if(l.length===0)return i.push($(`Payment: parse challenge`,`No Payment challenges in response`)),i;let u=l.find(e=>{if(e.method!==Tx.tempo)return!1;let t=e.request.methodDetails;return typeof t?.chainId==`number`&&t.chainId!==WD.mainnet});if(u){let e=await HI(u,n,r.silent);if(e){let r=new Response(null,{status:402,headers:{[J.wwwAuthenticate]:qx(u)}});try{let c=await aT({methods:e.methods,polyfill:!1}).createCredential(r);i.push($F(`Payment: submitted`,`ephemeral testnet wallet`)),await $I(i,a,t,c,o,s,n,_e)}catch(e){i.push($(`Payment: create credential`,e.message))}}else i.push($(`Payment: auto-provision wallet`,`Failed to create and fund testnet wallet`));r.onResults?.(i)}let d=await PP().catch(()=>void 0),f=r.interactive,p=process.env.MPPX_STRIPE_SECRET_KEY??WI(n),m=p?.startsWith(`sk_test_`)||p?.startsWith(`rk_test_`),h=new Set([Tx.tempo,Tx.evm,Tx.stripe]);for(let e of l){if(e===u||!h.has(e.method))continue;r.silent||console.log(``);let c=i.length,l=()=>{r.onResults&&i.length>c&&r.onResults(i.slice(c))},g=`Payment [${e.method}]`;try{switch(e.method){case Tx.tempo:case Tx.evm:await XI(e,g,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:d,isInteractive:f,options:r});break;case Tx.stripe:await ZI(e,g,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:d,isInteractive:f,isStripeTestKey:m??!1,stripeKey:p,options:r})}}finally{l()}}return i}async function XI(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u}=n,d=e.request,f=d.methodDetails,p=uI(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,g;try{g=await UI()}catch{}if(!g){r.push(tI(t,`no wallet configured. Run "mppx account create" to create one.`));return}let _;if(e.method===Tx.tempo)_=ge;else if(e.method===Tx.evm){let e=f?.chainId;e&&(_=KI(e))}let v;if(p&&h&&_)try{let n;if(e.method===Tx.tempo){let e=await hO(M({chain:ge,transport:ue()}),h,g);n=e.balance,v=e.symbol}else{let e=await GI(_,h,g);n=e.balance,v=e.symbol}if(n<p){let e=qI(p,m),i=qI(n,m),a=v??`tokens`;r.push(tI(t,`insufficient balance (have ${i}, need ${e} ${a} on ${_.name})`,`Fund wallet ${g} with at least ${e} ${a} on ${_.name}.`));return}}catch(e){c&&console.log(Z.dim(` Balance check skipped: ${e.message}`))}let y=p?qI(p,m):`unknown amount`,b=v??(h?.length===3?h.toUpperCase():``),x=_?.name,S=`${y}${b?` ${b}`:``}${x?` on ${x}`:``}`;if(u.silent||console.log(Z.dim(` Attempting payment with wallet ${g}`)),_?.testnet)u.silent||console.log(Z.dim(` Auto-approved: ${S} (testnet)`));else if(!u.yes&&!n.isInteractive){r.push(tI(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(Z.dim(` Auto-approved: ${S}`));else if(!await sO(` ${Z.yellow(`Pay`)} ${S}. Continue?`,!1)){r.push(tI(t,`declined`));return}let C=kP(e,l?.config),w=C.plugin,T=C.method;if(!w&&!T){r.push(tI(t,JI(e)));return}let ee,E;if(w)try{let t=await w.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});ee=t.methods,E=t.createCredential}catch(e){r.push(tI(t,e.message));return}else ee=[T];let D=await QI(e,ee,E,t,r);D&&(w?.prepareCredentialRequest?.({challenge:e,credential:D,headers:o}),await $I(r,i,a,D,o,s,c,_))}async function ZI(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u,isStripeTestKey:d,stripeKey:f}=n,p=e.request,m=uI(p.amount)?BigInt(p.amount):void 0,h=p.decimals??2,g=p.currency,_=m?qI(m,h):`unknown amount`,v=g?.length===3?g.toUpperCase():``,y=`${_}${v?` ${v}`:``} via Stripe${d?` (testmode)`:``}`;if(d)u.silent||console.log(Z.dim(` Attempting: ${y}`));else if(!u.yes&&!n.isInteractive){r.push(tI(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(Z.dim(` Auto-approved: ${y}`));else if(!await sO(` ${Z.yellow(`Pay`)} ${y}. Continue?`,!1)){r.push(tI(t,`declined`));return}let b=kP(e,l?.config).plugin;if(!b){r.push(tI(t,`no Stripe plugin available`));return}let x,S;try{let t={paymentMethod:`pm_card_visa`};f&&(t.secretKey=f);let n=await b.setup({challenge:e,options:{},methodOpts:t});x=n.methods,S=n.createCredential}catch(e){r.push(tI(t,e.message));return}let C=await QI(e,x,S,t,r);if(C){if(b.prepareCredentialRequest?.({challenge:e,credential:C,headers:o}),d){let e=await oI(i,{method:a.method,headers:{...o,[J.authorization]:C},body:s??null},3e4);e.status>=200&&e.status<300?r.push($F(`${t}: successful`,`HTTP ${e.status}`)):r.push(tI(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await $I(r,i,a,C,o,s,c,void 0)}}async function QI(e,t,n,r,i){let a=new Response(null,{status:402,headers:{[J.wwwAuthenticate]:qx(e)}});try{let e;return e=n?await n(a):await aT({methods:t,polyfill:!1}).createCredential(a),i.push($F(`${r}: submitted`)),e}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(tI(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function $I(e,t,n,r,i,a,o,s){let c;try{c=await oI(t,{method:n.method,headers:{...i,[J.authorization]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}if(c.status===402){let t=await c.text().catch(()=>``),n=`Payment rejected`;try{let e=JSON.parse(t);n=e.detail??e.title??n}catch{}return e.push($(`Payment: accepted`,n,`The server rejected a valid credential. Check that your payment verification logic accepts the credential format and that the payment was processed on-chain.`)),e}if(c.status>=400&&c.status<500)e.push(eI(`Payment: post-payment response`,`Got ${c.status}`,`Payment succeeded but the endpoint returned a client error. The endpoint likely requires request body parameters. Use --body to provide them.`));else if(c.status>=500)return e.push($(`Payment: server response`,`Got ${c.status}`,`Payment was accepted but the server errored while generating the response. Check server logs for the underlying error.`)),e;else e.push($F(`Payment: successful`,`HTTP ${c.status}`));let l=c.headers.get(J.paymentReceipt);if(!l)e.push($(`Payment-Receipt header present`,void 0,`After accepting payment, include a Payment-Receipt header with a base64url-encoded JSON object containing: method, reference, status ("success"), and timestamp (ISO 8601).`));else{e.push($F(`Payment-Receipt header present`));try{let t=BI(l);if(e.push($F(`Receipt parseable`)),t.status===`success`?e.push($F(`Receipt status is "success"`)):e.push($(`Receipt status is "success"`,`Got: ${t.status}`)),t.reference){let n=/^0x[0-9a-fA-F]{64}$/.test(t.reference),r=t.reference.startsWith(`pi_`);n||r?e.push($F(`Receipt reference valid`,t.reference.slice(0,20)+`...`)):e.push(eI(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(eI(`Receipt has reference`,`No reference field`));if(t.timestamp){let n=new Date(t.timestamp),r=Date.now()-n.getTime();r<6e4?e.push($F(`Receipt timestamp recent`,`${Math.round(r/1e3)}s ago`)):e.push(eI(`Receipt timestamp recent`,`${Math.round(r/6e4)}m ago`))}o&&console.log(Z.dim(` Receipt: ${JSON.stringify(t,null,2)}`))}catch(t){e.push($(`Receipt parseable`,t.message))}}let u=c.headers.get(`content-type`)??``,d=await c.text().catch(()=>``);if(d.length>0)e.push($F(`Response body non-empty`,`${u.split(`;`)[0]}, ${sI(d.length)}`));else{let t=[...c.headers.entries()].filter(([e])=>!e.startsWith(`x-`)&&![`content-type`,`content-length`,`date`,`server`,`connection`,`keep-alive`,`cache-control`,`vary`,`access-control-allow-origin`,`payment-receipt`,`payment-session`,`payment-session-snapshot`].includes(e.toLowerCase()));t.length>0?e.push(eI(`Response body empty -- data may be in headers only`,t.map(([e])=>e).join(`, `))):e.push(eI(`Response body empty`))}if(u?e.push($F(`Content-Type header set`,u.split(`;`)[0])):e.push(eI(`Content-Type header set`)),l)try{let t=BI(l);if(t.reference&&/^0x[0-9a-fA-F]{64}$/.test(t.reference)){let n=s?.blockExplorers?.default?.url;if(n){let r=n.includes(`tempo`)?`receipt`:`tx`;e.push($F(`On-chain transaction`,`${n}/${r}/${t.reference}`))}}}catch{}return e}async function*eL(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await aL(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=fI(e.body,i.path),!a&&r.doc&&(a=gI(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await TI(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=(l??[]).filter(e=>e.method!==`stripe`).map(e=>e.request.methodDetails?.chainId).filter(e=>typeof e==`number`),p=f.some(iL),m=f.some(e=>!iL(e)),h=!d&&s.some(e=>e.label===`Not an MPP endpoint`),g=s.some(e=>e.severity===`pass`&&e.label===`WWW-Authenticate header present`),_=s.some(e=>e.severity===`fail`&&e.label===`Challenge parseable`);if(yield{phase:`challenge`,endpoint:i,results:s,isMpp:d,isTestnet:p,isMainnet:m,isNonMppPayment:h,isMalformedChallenge:!d&&g&&_,methods:l?.map(e=>e.method)??[]},d&&(yield{phase:`errorHandling`,endpoint:i,results:await FI(t,i,{body:u,query:e.query})},!e.skipPayment)){let r=e.onPaymentResults,a=await YI(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 tL(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of eL(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,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===`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===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=nL(r,n,{sawTestnet:a,sawMainnet:o});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function nL(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(LI);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 rL=Object.values(Pe);function iL(e){return rL.find(t=>t.id===e)?.testnet===!0}async function aL(e,t){let n=[],r=[],i=null,a=!1,o=!1,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 mI(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=AT(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=dI(t.endpoint);e&&r.push(e)}else if(i){r=hI(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=uI(t.amount)?BigInt(t.amount):e,i=uI(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}}Sx(),CO();const oL=nb(`validate`,{description:`Validate an MPP server implementation end-to-end`,args:f.object({url:f.string().describe(`Base URL of the MPP server to validate`)}),options:f.object({endpoint:f.string().optional().describe(`Endpoint to test (METHOD:path). Skips discovery.`),body:f.string().optional().describe(`Request body. With --endpoint, used directly. In discovery mode, JSON with / keys is a per-path mapping.`),query:f.array(f.string()).optional().describe(`Query parameter (key=value, repeatable)`),header:f.array(f.string()).optional().describe(`Request header (key:value, repeatable)`),verbose:f.number().default(0).meta({count:!0}).describe(`Verbosity level`),yes:f.boolean().default(!1).describe(`Auto-approve mainnet payments`),outputJson:f.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||iO()){let t=await tL({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${Z.bold(`mppx validate`)} ${Z.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of eL({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=>aI(e,n)}))switch(t.phase){case`discovery`:if(iI(`Discovery (/openapi.json)`),aI(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=LI.split(`
247
+ `);console.log(Z.yellow(` ${e}`));for(let e of t)console.log(e?Z.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(Z.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,iI(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(Z.dim(` Challenge`)),aI(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(Z.dim(` Error Handling`)),aI(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}sL(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function sL(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(Z.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(Z.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(Z.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(Z.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(Z.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(Z.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(Z.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(Z.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(Z.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(Z.green(`${e.passed} passed`)),e.failed>0&&r.push(Z.red(`${e.failed} failed`)),e.warnings>0&&r.push(Z.yellow(`${e.warnings} warning(s)`)),e.skipped>0&&r.push(Z.yellow(`${e.skipped} skipped`)),console.log(`${Z.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(Z.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(Z.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 cL(e){return uL(e)?e.offers:[e]}function lL(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=dL(t.amount)??dL(i.amount)??null,o=dL(t.currency)??dL(i.currency),s=dL(e.description)??dL(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 uL(e){return`offers`in e&&!(`_canonicalRequest`in e)}function dL(e){return typeof e==`string`?e:void 0}var fL=I((()=>{})),pL=Ke({generate:()=>mL,generateProxy:()=>hL});function mL(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=>_L(e,r));return gL({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function hL(e){let t=e.routes.map(t=>({...t,path:vL(e.basePath,t.path)}));return gL({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function gL(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`]=CT.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 _L(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:cL(t).map(lL)},...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:jx(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:lL(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function vL(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var yL=I((()=>{Nx(),kT(),fL()}));Sx(),dS(),tT(),RC(),ZC(),ew(),kx(),UD(),YC(),xS(),SC(),LO(),CO();const bL=`0.9.2`,xL=f.object({address:f.string(),isDefault:f.boolean().optional(),name:f.string(),source:f.string().optional()}),SL=f.object({address:f.string(),balances:f.array(f.string()).optional(),name:f.string(),type:f.string().optional()}),CL=f.object({message:f.string(),path:f.string(),severity:f.string()}),wL=f.object({description:f.string().optional(),id:f.string(),name:f.string().optional(),paidEndpoints:f.number(),status:f.string().optional(),url:f.string().optional()}),TL=f.object({description:f.string().optional(),method:f.string(),path:f.string(),payment:f.unknown().optional()});function EL(e){return e.format===`json`&&e.formatExplicit}function DL(e,t,n){if(EL(e))return e.ok(t);n()}async function OL(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}function kL(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function AL(e){return typeof e==`string`?e:void 0}function jL(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function ML(e){let t=jL(e);return{...AL(e.description)?{description:AL(e.description)}:{},id:AL(e.id)??AL(e.name)??`unknown`,...AL(e.name)?{name:AL(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...AL(e.status)?{status:AL(e.status)}:{},...AL(e.serviceUrl)||AL(e.url)?{url:AL(e.serviceUrl)??AL(e.url)}:{}}}function NL(e){return{...AL(e.description)?{description:AL(e.description)}:{},method:AL(e.method)??`GET`,path:AL(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function PL(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=AL(t.amount),r=AL(t.currency),i=AL(t.method),a=AL(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function FL(e){return e.request.currency??e.request.asset}function IL(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=FL(e);return typeof t==`string`&&t.toLowerCase()===n})}async function LL(e,t,n={}){let r=()=>LC().getChallenges(e),i=()=>XC().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 RL(e){return QC({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function zL(e,t){if(!yS(e))return new Response(null,{status:402,headers:{[J.wwwAuthenticate]:qx(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[iC]:KC({accepts:[$S(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function BL(e){let{host:t,hostname:n}=new URL(e);return!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}function VL(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function HL(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function UL(){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 WL(e,t){let n=t.toLowerCase();return e.find(e=>{let t=AL(e.id)?.toLowerCase(),r=AL(e.name)?.toLowerCase();return t===n||r===n})}const GL=nb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:bL,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:f.object({url:f.string().describe(`URL to make request to`)}),options:f.object({account:f.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:f.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:f.string().optional().describe(`Path to config file`),confirm:f.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:f.string().optional().describe(`Payment currency/token address to select`),data:f.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:f.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:f.array(f.string()).optional().describe(`Add header (repeatable)`),include:f.boolean().optional().describe(`Include response headers in output`),insecure:f.boolean().optional().describe(`Skip TLS certificate verification (true for localhost/.local)`),jsonBody:f.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:f.boolean().optional().describe(`Follow redirects`),method:f.string().optional().describe(`HTTP method`),methodOpt:f.array(f.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:f.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:f.string().optional().describe(`Source token for Tempo auto-swap`),protocol:f.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:f.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:f.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:f.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:f.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:f.string().optional().default(`mppx/${bL}`).describe(`Set User-Agent header`),verbose:f.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 PP(e.options.config);n&&e.options.verbose>=1&&t(`${Z.dim(`Using config`)} ${Z.blue(s.relative(process.cwd(),n.path))}\n`);let r={"User-Agent":e.options.userAgent};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});r[t.slice(0,n).trim()]=t.slice(n+1).trim()}let i=jP(n?.config);i&&!Object.keys(r).some(e=>e.toLowerCase()===`accept-payment`)&&(r[`Accept-Payment`]=i);let a=(()=>{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:o}=new URL(a),c=e.options.insecure||o===`localhost`||o.endsWith(`.localhost`)||o.endsWith(`.local`)?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,l=BL(a),u=l.url;l.host&&(r.Host=l.host);try{let i=rO(e.options.methodOpt),o=XP(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,r[`Content-Type`]??=`application/json`,r.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(r).length>0&&(s.headers=r);let d={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&ZD(a,s,t);let f=await c(u,s);if(f.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&&f.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${f.status}`,exitCode:22});QD(f,d),await OL(f);return}let p=f.url?new URL(f.url):void 0,m=l.host!==void 0&&p?.hostname===`127.0.0.1`,h=await LL(f,e.options.protocol,{ignoreX402ResponseUrl:m});if(h.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 g=IL(h,e.options.currency);if(e.options.currency&&g.length===0){let t=h.map(FL).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 _=await KN(g,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),v=AP(_,n?.config);if(!v){let t=_.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:y,plugin:b,method:x}=v,S=yS(y),C=zL(y,f),w=y.request.currency??``,T=y.request.decimals??6,ee,E;b&&(E=await b.setup({challenge:y,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:i}),w=E.tokenSymbol,T=E.tokenDecimals,ee=E.explorerUrl);let D=!e.options.silent&&e.options.confirm,k=new Set;{QD(f,y.method===`tempo`&&y.intent===`session`&&e.options.include?{...d,include:!1,verbose:Math.max(d.verbose,2)}:d);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(y))e.has(n)||r===void 0||t.push([n,tO(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:w,tokenDecimals:T,explorerUrl:ee},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(y.request))e.has(n)||i===void 0||t.push([n,$D(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=y.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=eO(i);t.push([n,e?`${e}\n${Z.dim(i)}`:i])}else t.push([n,$D(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)k.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),c=` ${``.padEnd(s)} `;if(e.options.verbose>=1||D){t(`${Z.bold(Z.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${Z.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
248
+ `);t(` ${Z.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${c}${e}\n`)}}}if(D&&(t(`
249
+ `),!await sO(`Proceed with ${y.intent}?`,!0))){t(`Aborted.
250
+ `);return}}let te=process.env.MPPX_PRIVATE_KEY?.trim()||!aO(AO(e.options.account));if(cD(y)&&te){try{await QF({challenge:y,challengeResponse:C,endpoint:a,fetch:c,fetchInput:u,init:s,info:t,methodOptions:i,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:o})}catch(e){return BF(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});let A;if(E?.createCredential)A=await E.createCredential(C);else if(E)A=await aT({methods:E.methods,polyfill:!1,transport:RL(y)}).createCredential(C,E.credentialContext);else if(x)A=await aT({methods:[x],polyfill:!1,transport:RL(y)}).createCredential(C);else throw Error(`unreachable`);let ne=S?aC:oS(y),j={..._w(s.headers),[ne]:A},M=S?BL((HL(y)??f.url)||a):l;S&&VL(j,M.host),b?.prepareCredentialRequest?.({challenge:y,credential:A,headers:j});let re={...s,...S&&{redirect:`manual`},headers:j};e.options.verbose>=2&&ZD(M.url,re,t);let ie=await c(M.url,re);if(e.options.fail&&ie.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${ie.status}`,exitCode:22});if(ie.status===402){let n=await ie.text();t(`${Z.bold(Z.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,String(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${Z.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(QD(ie,d),!await b?.handleResponse?.({challenge:y,credential:A,response:ie,fetchUrl:u,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:D,confirm:sO,tokenSymbol:w,tokenDecimals:T,explorerUrl:ee,shownKeys:k})){let n=ie.headers.get(J.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(O.toString(n));t(`\n${Z.bold(Z.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||k.has(t)||t===`reference`&&o)continue;let e=b?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${Z.dim(`(${cO(BigInt(n),w,T)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&ee?r.push([t,nO(`${ee}/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(` ${Z.dim(e.padEnd(c))} ${n}\n`);t(`
251
+ `)}catch{}await OL(ie)}}catch(t){if(t instanceof L)throw t;let n=t instanceof Error?t.cause:void 0,r=n instanceof Error?n:void 0;if(r&&`code`in r){let t=r.code;return t===`ENOTFOUND`?e.error({code:`DNS_ERROR`,message:`Could not resolve host "${o}". Check the URL and try again.`,exitCode:6}):t===`ECONNREFUSED`?e.error({code:`CONNECTION_REFUSED`,message:`Connection refused by "${o}". Is the server running?`,retryable:!0,exitCode:7}):t===`ECONNRESET`?e.error({code:`CONNECTION_RESET`,message:`Connection to "${o}" was reset.`,retryable:!0,exitCode:56}):t===`ETIMEDOUT`?e.error({code:`CONNECTION_TIMEOUT`,message:`Connection to "${o}" timed out.`,retryable:!0,exitCode:28}):t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?e.error({code:`TLS_ERROR`,message:`TLS certificate error for "${o}". Use --insecure to skip verification.`,exitCode:60}):e.error({code:`REQUEST_FAILED`,message:`Request to "${o}" failed: ${r.message}`})}{let n=t instanceof Error?t.message:String(t);return e.error({code:`REQUEST_FAILED`,message:r?`Request failed: ${n} (Cause: ${r.message})`:`Request failed: ${n}`})}}}}),KL=nb(`account`,{description:`Manage accounts (create, default, delete, export, fund, list, view)`}).command(`create`,{description:`Create new account`,options:f.object({account:f.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:f.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:f.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:f.object({address:f.string(),name:f.string()}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=EL(e),n=e.options.account;if(!n){if((await jO().list()).length===0)n=`main`;else{if(t)return e.error({code:`ACCOUNT_REQUIRED`,message:`Account name is required in structured mode.`,exitCode:2});let r=await oO(`Account name`);if(!r)return;n=r}}let r=jO(n);for(;await r.get();){if(t)return e.error({code:`ACCOUNT_EXISTS`,message:`Account "${n}" already exists.`,exitCode:1});process.stderr.write(`${Z.dim(`Account "${n}" already exists.`)}\n\n`);let i=await oO(`Enter different name`);if(!i)return;n=i,r=jO(n)}let i=pe(),a=he(i);await r.set(i),(await jO().list()).length===1&&kO().set(n);let o=ge.blockExplorers?.default?.url,s=o?nO(`${o}/address/${a.address}`,a.address):a.address,c=uO(e.options),l=lO(e.options.rpcUrl,{network:c});return dO({network:c,rpcUrl:l}).then(e=>M({chain:e,transport:ue(l)})).then(e=>import(`viem/tempo`).then(({Actions:t})=>t.faucet.fund(e,{account:a}).catch(()=>{}))),DL(e,{address:a.address,name:n},()=>{console.log(`Account "${n}" saved to keychain.`),console.log(Z.dim(`Address ${s}`)),console.log(Z.dim(`Fund testnet tokens: mppx account fund --account ${n} --network testnet`))})}}).command(`default`,{description:`Set default account`,options:f.object({account:f.string().describe(`Account name`)}),output:f.object({name:f.string()}),alias:{account:`a`},async run(e){let t=e.options.account;return aO(t)?pP(t)?(kO().set(t),DL(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69}):await jO(t).get()?(kO().set(t),DL(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69})}}).command(`delete`,{description:`Delete account`,options:f.object({account:f.string().describe(`Account name`),yes:f.boolean().optional().describe(`DANGER!! Skip confirmation prompts`)}),output:f.object({defaultAccount:f.string().optional(),name:f.string()}),alias:{account:`a`},async run(e){let t=jO(e.options.account),n=await t.get();if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${e.options.account}" not found.`,exitCode:69});let r=he(n),i=await gO(r.address,{includeTestnet:!1});if(!e.options.yes){if(EL(e))return e.error({code:`CONFIRMATION_REQUIRED`,message:`Pass --yes to delete an account in structured mode.`,exitCode:2});let t=ge.blockExplorers?.default?.url,n=t?nO(`${t}/address/${r.address}`,r.address):r.address;process.stderr.write(Z.dim(`Delete account "${e.options.account}"\n`)),process.stderr.write(Z.dim(` Address ${n}\n`));for(let e=0;e<i.length;e++)process.stderr.write(Z.dim(` ${e===0?`Balance`:` `} ${i[e]}\n`));if(process.stderr.write(Z.dim(`This action cannot be undone
252
252
 
253
- `)),!await oO(`Confirm delete?`)){console.log(`Canceled`);return}}await t.delete();let a=OO().get(),o;if(a===e.options.account){let e=await AO().list();e.length>0?(o=e[0],OO().set(o)):OO().clear()}return SL(e,{defaultAccount:o,name:e.options.account},()=>{o&&console.log(`Default account set to "${o}"`),console.log(`Account "${e.options.account}" deleted`)})}}).command(`fund`,{description:`Fund account with testnet tokens`,options:f.object({account:f.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:f.enum([`testnet`]).optional().describe(`Tempo network`),rpcUrl:f.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:f.object({account:f.string(),chain:f.string(),transactions:f.array(f.string())}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=xL(e),n=kO(e.options.account),r=await AO(n).get();if(!r)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${n}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let i=he(r),a=lO(e.options),o=cO(e.options.rpcUrl,{network:a}),s=await uO({network:a,rpcUrl:o}),c=ne({chain:s,transport:ue(o)});t||console.log(`Funding "${n}" on ${dO(s)}`);try{let{Actions:r}=await import(`viem/tempo`),a=await r.faucet.fund(c,{account:i}),o=s.blockExplorers?.default?.url;if(!t)for(let e of a){let t=o?tO(`${o}/tx/${e}`,Z.gray(e)):e;console.log(` ${t}`)}let{waitForTransactionReceipt:l}=await import(`viem/actions`);return await Promise.all(a.map(e=>l(c,{hash:e}))),SL(e,{account:n,chain:dO(s),transactions:[...a]},()=>{console.log(`Funded successfully`)})}catch(n){let r=n instanceof Error?n.message:String(n);return t?e.error({code:`FUNDING_FAILED`,message:r,exitCode:1}):e.error({code:`FUNDING_FAILED`,message:`Funding failed: ${r}`,exitCode:1})}}}).command(`list`,{description:`List all accounts`,output:f.object({accounts:f.array(gL)}),async run(e){let t=OO().get(),n=(await AO().list()).sort(),r=[];for(let e of n){let t=await AO(e).get();t&&r.push({name:e,address:he(t).address})}let i=dP();for(let e=0;e<i.length;e++){let t=i[e],n=e===0?`tempo:default`:`tempo:${e}`;t.wallet_address&&r.push({name:n,address:t.wallet_address,source:`tempo wallet`})}if(r.length===0)return SL(e,{accounts:[]},()=>{console.log(`No accounts found.`)});let a=ge.blockExplorers?.default?.url,o=Math.max(...r.map(e=>e.name.length+ +(e.name===t)));return SL(e,{accounts:r.map(e=>({...e,...e.name===t?{isDefault:!0}:void 0}))},()=>{for(let e of r){let n=e.name===t,r=n?`${e.name}${Z.dim(`*`)}`:e.name,i=e.name.length+ +!!n,s=a?tO(`${a}/address/${e.address}`,e.address):e.address,c=e.source?` ${Z.dim(`(${e.source})`)}`:``;console.log(`${r}${` `.repeat(o-i+2)}${Z.dim(s)}${c}`)}})}}).command(`export`,{description:`Export the private key for a local account`,options:f.object({account:f.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`)}),output:f.object({privateKey:f.string()}),alias:{account:`a`},async run(e){let t=kO(e.options.account);if(iO(t))return e.error({code:`UNSUPPORTED_ACCOUNT`,message:`Account "${t}" is managed by Tempo wallet and does not expose a private key via mppx.`,exitCode:2});let n=await AO(t).get();return n?SL(e,{privateKey:n},()=>{console.log(n)}):e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}}).command(`view`,{description:`View account address`,options:f.object({account:f.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:f.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:f.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:_L,alias:{account:`a`,rpcUrl:`r`},async run(e){let t=kO(e.options.account);if(iO(t)){let n=fP(t);if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69});let r=n.wallet_address,i=cO(e.options.rpcUrl,{network:e.options.network}),a=await uO({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?tO(`${o}/address/${r}`,r):r,c=await hO(r,a&&i?{chain:a,rpcUrl:i}:void 0);return SL(e,{address:r,balances:c,name:t,type:`${n.wallet_type} (tempo wallet)`},()=>{console.log(`${Z.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${Z.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${Z.dim(`Name`)} ${t}`),console.log(`${Z.dim(`Type`)} ${n.wallet_type} ${Z.dim(`(tempo wallet)`)}`)})}let n=await AO(t).get();if(!n)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let r=he(n),i=cO(e.options.rpcUrl,{network:e.options.network}),a=await uO({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?tO(`${o}/address/${r.address}`,r.address):r.address,c=await hO(r.address,a&&i?{chain:a,rpcUrl:i}:void 0);return SL(e,{address:r.address,balances:c,name:t},()=>{console.log(`${Z.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${Z.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${Z.dim(`Name`)} ${t}`)})}}),FL=nb(`sign`,{description:`Sign a payment challenge and output the Authorization header`,usage:[{suffix:`--challenge <value> [options]`},{prefix:`echo <challenge> |`,suffix:`[options]`}],options:f.object({account:f.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),challenge:f.string().optional().describe(`WWW-Authenticate challenge value`),config:f.string().optional().describe(`Path to config file`),dryRun:f.boolean().optional().describe(`Validate and parse the challenge without signing`),autoSwap:f.boolean().optional().describe(`Auto-swap source tokens into payment currency`),methodOpt:f.array(f.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:f.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:f.string().optional().describe(`Source token for Tempo auto-swap`),rpcUrl:f.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),slippage:f.number().optional().describe(`Tempo auto-swap max slippage percentage`)}),output:f.object({authorization:f.string()}),alias:{account:`a`,challenge:`C`,config:`c`,methodOpt:`M`,rpcUrl:`r`},async run(e){let t=e.options.challenge||(wL()?await new Promise((e,t)=>{let n=``;process.stdin.setEncoding(`utf-8`),process.stdin.on(`data`,e=>{n+=e}),process.stdin.on(`end`,()=>e(n.trim())),process.stdin.on(`error`,t)}):void 0);if(!t)return e.error({code:`NO_CHALLENGE`,message:`No challenge provided. Use --challenge or pipe via stdin.`,exitCode:2});let n;try{n=iS(t)}catch(t){return e.error({code:`INVALID_CHALLENGE`,message:`Failed to parse challenge: ${t instanceof Error?t.message:t}`,exitCode:2})}if(e.options.dryRun){process.stderr.write(`Challenge is valid.
254
- `);return}let r=await kP(e.options.config),i=TP(n,r?.config);if(!i){let t=n.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:a,plugin:o,method:s}=i,c=nO(e.options.methodOpt),l=qx(a),u=new Response(null,{status:402,headers:{[J.wwwAuthenticate]:l}}),d;if(o){let t=await o.setup({challenge:a,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:c});d=t.createCredential?await t.createCredential(u):await iT({methods:t.methods,polyfill:!1}).createCredential(u,t.credentialContext)}else if(s)d=await iT({methods:[s],polyfill:!1}).createCredential(u);else return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method: ${a.method}/${a.intent}. Add it to mppx.config.ts using defineConfig().`,exitCode:2});return SL(e,{authorization:d},()=>{console.log(d)})}}),IL=nb(`init`,{description:`Create an mppx.config.ts file in the current directory`,options:f.object({force:f.boolean().optional().describe(`Overwrite existing config file`)}),output:f.object({file:f.string()}),alias:{force:`f`},async run(t){let n=process.cwd(),r=`mppx.config${(()=>{if(e.existsSync(s.join(n,`tsconfig.json`)))return`.ts`;try{if(JSON.parse(e.readFileSync(s.join(n,`package.json`),`utf-8`)).type===`module`)return`.mjs`}catch{}return`.js`})()}`,i=s.join(n,r);return e.existsSync(i)&&!t.options.force?t.error({code:`CONFIG_EXISTS`,message:`${r} already exists. Use --force to overwrite.`,exitCode:1}):(e.writeFileSync(i,`import { defineConfig } from 'mppx/cli'
253
+ `)),!await sO(`Confirm delete?`)){console.log(`Canceled`);return}}await t.delete();let a=kO().get(),o;if(a===e.options.account){let e=await jO().list();e.length>0?(o=e[0],kO().set(o)):kO().clear()}return DL(e,{defaultAccount:o,name:e.options.account},()=>{o&&console.log(`Default account set to "${o}"`),console.log(`Account "${e.options.account}" deleted`)})}}).command(`fund`,{description:`Fund account with testnet tokens`,options:f.object({account:f.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:f.enum([`testnet`]).optional().describe(`Tempo network`),rpcUrl:f.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:f.object({account:f.string(),chain:f.string(),transactions:f.array(f.string())}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=EL(e),n=AO(e.options.account),r=await jO(n).get();if(!r)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${n}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let i=he(r),a=uO(e.options),o=lO(e.options.rpcUrl,{network:a}),s=await dO({network:a,rpcUrl:o}),c=M({chain:s,transport:ue(o)});t||console.log(`Funding "${n}" on ${fO(s)}`);try{let{Actions:r}=await import(`viem/tempo`),a=await r.faucet.fund(c,{account:i}),o=s.blockExplorers?.default?.url;if(!t)for(let e of a){let t=o?nO(`${o}/tx/${e}`,Z.gray(e)):e;console.log(` ${t}`)}let{waitForTransactionReceipt:l}=await import(`viem/actions`);return await Promise.all(a.map(e=>l(c,{hash:e}))),DL(e,{account:n,chain:fO(s),transactions:[...a]},()=>{console.log(`Funded successfully`)})}catch(n){let r=n instanceof Error?n.message:String(n);return t?e.error({code:`FUNDING_FAILED`,message:r,exitCode:1}):e.error({code:`FUNDING_FAILED`,message:`Funding failed: ${r}`,exitCode:1})}}}).command(`list`,{description:`List all accounts`,output:f.object({accounts:f.array(xL)}),async run(e){let t=kO().get(),n=(await jO().list()).sort(),r=[];for(let e of n){let t=await jO(e).get();t&&r.push({name:e,address:he(t).address})}let i=fP();for(let e=0;e<i.length;e++){let t=i[e],n=e===0?`tempo:default`:`tempo:${e}`;t.wallet_address&&r.push({name:n,address:t.wallet_address,source:`tempo wallet`})}if(r.length===0)return DL(e,{accounts:[]},()=>{console.log(`No accounts found.`)});let a=ge.blockExplorers?.default?.url,o=Math.max(...r.map(e=>e.name.length+ +(e.name===t)));return DL(e,{accounts:r.map(e=>({...e,...e.name===t?{isDefault:!0}:void 0}))},()=>{for(let e of r){let n=e.name===t,r=n?`${e.name}${Z.dim(`*`)}`:e.name,i=e.name.length+ +!!n,s=a?nO(`${a}/address/${e.address}`,e.address):e.address,c=e.source?` ${Z.dim(`(${e.source})`)}`:``;console.log(`${r}${` `.repeat(o-i+2)}${Z.dim(s)}${c}`)}})}}).command(`export`,{description:`Export the private key for a local account`,options:f.object({account:f.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`)}),output:f.object({privateKey:f.string()}),alias:{account:`a`},async run(e){let t=AO(e.options.account);if(aO(t))return e.error({code:`UNSUPPORTED_ACCOUNT`,message:`Account "${t}" is managed by Tempo wallet and does not expose a private key via mppx.`,exitCode:2});let n=await jO(t).get();return n?DL(e,{privateKey:n},()=>{console.log(n)}):e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}}).command(`view`,{description:`View account address`,options:f.object({account:f.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:f.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:f.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:SL,alias:{account:`a`,rpcUrl:`r`},async run(e){let t=AO(e.options.account);if(aO(t)){let n=pP(t);if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69});let r=n.wallet_address,i=lO(e.options.rpcUrl,{network:e.options.network}),a=await dO({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?nO(`${o}/address/${r}`,r):r,c=await gO(r,a&&i?{chain:a,rpcUrl:i}:void 0);return DL(e,{address:r,balances:c,name:t,type:`${n.wallet_type} (tempo wallet)`},()=>{console.log(`${Z.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${Z.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${Z.dim(`Name`)} ${t}`),console.log(`${Z.dim(`Type`)} ${n.wallet_type} ${Z.dim(`(tempo wallet)`)}`)})}let n=await jO(t).get();if(!n)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let r=he(n),i=lO(e.options.rpcUrl,{network:e.options.network}),a=await dO({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?nO(`${o}/address/${r.address}`,r.address):r.address,c=await gO(r.address,a&&i?{chain:a,rpcUrl:i}:void 0);return DL(e,{address:r.address,balances:c,name:t},()=>{console.log(`${Z.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${Z.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${Z.dim(`Name`)} ${t}`)})}}),qL=nb(`sign`,{description:`Sign a payment challenge and output the Authorization header`,usage:[{suffix:`--challenge <value> [options]`},{prefix:`echo <challenge> |`,suffix:`[options]`}],options:f.object({account:f.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),challenge:f.string().optional().describe(`WWW-Authenticate challenge value`),config:f.string().optional().describe(`Path to config file`),dryRun:f.boolean().optional().describe(`Validate and parse the challenge without signing`),autoSwap:f.boolean().optional().describe(`Auto-swap source tokens into payment currency`),methodOpt:f.array(f.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:f.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:f.string().optional().describe(`Source token for Tempo auto-swap`),rpcUrl:f.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),slippage:f.number().optional().describe(`Tempo auto-swap max slippage percentage`)}),output:f.object({authorization:f.string()}),alias:{account:`a`,challenge:`C`,config:`c`,methodOpt:`M`,rpcUrl:`r`},async run(e){let t=e.options.challenge||(kL()?await new Promise((e,t)=>{let n=``;process.stdin.setEncoding(`utf-8`),process.stdin.on(`data`,e=>{n+=e}),process.stdin.on(`end`,()=>e(n.trim())),process.stdin.on(`error`,t)}):void 0);if(!t)return e.error({code:`NO_CHALLENGE`,message:`No challenge provided. Use --challenge or pipe via stdin.`,exitCode:2});let n;try{n=iS(t)}catch(t){return e.error({code:`INVALID_CHALLENGE`,message:`Failed to parse challenge: ${t instanceof Error?t.message:t}`,exitCode:2})}if(e.options.dryRun){process.stderr.write(`Challenge is valid.
254
+ `);return}let r=await PP(e.options.config),i=AP(n,r?.config);if(!i){let t=n.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:a,plugin:o,method:s}=i,c=rO(e.options.methodOpt),l=qx(a),u=new Response(null,{status:402,headers:{[J.wwwAuthenticate]:l}}),d;if(o){let t=await o.setup({challenge:a,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:c});d=t.createCredential?await t.createCredential(u):await aT({methods:t.methods,polyfill:!1}).createCredential(u,t.credentialContext)}else if(s)d=await aT({methods:[s],polyfill:!1}).createCredential(u);else return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method: ${a.method}/${a.intent}. Add it to mppx.config.ts using defineConfig().`,exitCode:2});return DL(e,{authorization:d},()=>{console.log(d)})}}),JL=nb(`init`,{description:`Create an mppx.config.ts file in the current directory`,options:f.object({force:f.boolean().optional().describe(`Overwrite existing config file`)}),output:f.object({file:f.string()}),alias:{force:`f`},async run(t){let n=process.cwd(),r=`mppx.config${(()=>{if(e.existsSync(s.join(n,`tsconfig.json`)))return`.ts`;try{if(JSON.parse(e.readFileSync(s.join(n,`package.json`),`utf-8`)).type===`module`)return`.mjs`}catch{}return`.js`})()}`,i=s.join(n,r);return e.existsSync(i)&&!t.options.force?t.error({code:`CONFIG_EXISTS`,message:`${r} already exists. Use --force to overwrite.`,exitCode:1}):(e.writeFileSync(i,`import { defineConfig } from 'mppx/cli'
255
255
 
256
256
  export default defineConfig({
257
257
  methods: [],
258
258
  plugins: [],
259
259
  })
260
- `),SL(t,{file:i},()=>{console.log(`Created ${r}`)}))}}),LL=nb(`services`,{description:`Browse the MPP services registry`}).command(`list`,{description:`List registered MPP services`,options:f.object({query:f.string().optional().describe(`Filter by id, name, category, tag, or description`)}),output:f.object({services:f.array(yL)}),alias:{query:`q`},async run(e){let t=e.options.query?.toLowerCase(),n=await jL(),r=(t?n.filter(e=>[e.id,e.name,e.description,...Array.isArray(e.categories)?e.categories:[],...Array.isArray(e.tags)?e.tags:[]].filter(e=>typeof e==`string`).some(e=>e.toLowerCase().includes(t))):n).map(DL).sort((e,t)=>e.id.localeCompare(t.id));return SL(e,{services:r},()=>{if(r.length===0){console.log(`No services found.`);return}let e=Math.max(...r.map(e=>e.id.length)),t=Math.max(...r.map(e=>String(e.paidEndpoints).length));for(let n of r){let r=n.name&&n.name!==n.id?` ${n.name}`:``,i=n.url?` ${Z.dim(n.url)}`:``;console.log(`${n.id.padEnd(e)} ${String(n.paidEndpoints).padStart(t)} paid${r}${i}`)}})}}).command(`show`,{description:`Show one registered MPP service`,args:f.object({service:f.string().describe(`Service id or name`)}),output:f.object({service:f.record(f.string(),f.unknown())}),async run(e){let t=ML(await jL(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=DL(t),r=EL(t);return SL(e,{service:t},()=>{console.log(`${n.name??n.id} ${Z.dim(`(${n.id})`)}`),n.description&&console.log(n.description),n.url&&console.log(`${Z.dim(`URL`)} ${tO(n.url,n.url)}`),n.status&&console.log(`${Z.dim(`Status`)} ${n.status}`),console.log(`${Z.dim(`Endpoints`)} ${r.length} (${n.paidEndpoints} paid)`);let e=t.docs,i=e&&TL(e.homepage);i&&console.log(`${Z.dim(`Docs`)} ${tO(i,i)}`)})}}).command(`endpoints`,{description:`List endpoints for a registered MPP service`,args:f.object({service:f.string().describe(`Service id or name`)}),output:f.object({endpoints:f.array(bL),service:yL}),async run(e){let t=ML(await jL(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=DL(t),r=EL(t).map(OL);return SL(e,{endpoints:r,service:n},()=>{if(r.length===0){console.log(`No endpoints found for ${n.id}.`);return}let e=Math.max(...r.map(e=>e.method.length)),t=Math.max(...r.map(e=>e.path.length));for(let n of r){let r=kL(n.payment),i=n.description?` ${Z.dim(n.description)}`:``;console.log(`${n.method.padEnd(e)} ${n.path.padEnd(t)} ${r}${i}`)}})}}),RL=nb(`discover`,{description:`Discovery tooling`}).command(`generate`,{description:`Generate a static OpenAPI discovery document from a module`,args:f.object({module:f.string().describe(`Path to a module that default-exports a discovery config`)}),options:f.object({output:f.string().optional().describe(`Write output to a file instead of stdout`)}),output:f.record(f.string(),f.unknown()),alias:{output:`o`},async run(t){let n=s.resolve(t.args.module);if(!e.existsSync(n))return t.error({code:`MODULE_NOT_FOUND`,message:`Module not found: ${n}`,exitCode:1});let r;try{r=await import(n)}catch(e){return t.error({code:`MODULE_IMPORT_FAILED`,message:`Failed to import module: ${e.message}`,exitCode:1})}let i=r.default??r,a;if(typeof i.openapi==`string`)a=i;else{let{generate:e}=await Promise.resolve().then(()=>(mL(),cL)),n=i.mppx;if(!n)return t.error({code:`INVALID_MODULE`,message:"Module must default-export an OpenAPI document (with `openapi` key) or an object with `mppx` (server instance) and `routes`.",exitCode:1});a=e(n,i)}let o=JSON.stringify(a,null,2);if(t.options.output){let n=s.resolve(t.options.output);return e.writeFileSync(n,`${o}\n`),process.stderr.write(`Wrote ${n}\n`),SL(t,a,()=>{})}return SL(t,a,()=>{console.log(o)})}}).command(`validate`,{description:`Validate an OpenAPI discovery document from a file or URL`,args:f.object({input:f.string().describe(`Path or URL to a discovery document`)}),output:f.object({errorCount:f.number(),issues:f.array(vL),valid:f.boolean(),warningCount:f.number()}),async run(t){let n=t.args.input,r;if(/^https?:\/\//.test(n)){let e=new AbortController,i=setTimeout(()=>e.abort(),3e4),a;try{a=await globalThis.fetch(n,{signal:e.signal})}catch(e){clearTimeout(i);let n=e instanceof DOMException&&e.name===`AbortError`?`Request timed out after 30s`:e.message;return t.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: ${n}`,exitCode:1})}if(clearTimeout(i),!a.ok)return t.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: HTTP ${a.status}`,exitCode:1});let o=10485760,s=a.headers.get(`content-length`);if(s&&Number(s)>o||(r=await a.text(),r.length>o))return t.error({code:`DISCOVERY_TOO_LARGE`,message:`Discovery document exceeds 10 MB limit`,exitCode:1})}else{let i=s.resolve(n);if(!e.existsSync(i))return t.error({code:`DISCOVERY_NOT_FOUND`,message:`Discovery document not found: ${i}`,exitCode:1});r=e.readFileSync(i,`utf-8`)}let i;try{i=JSON.parse(r)}catch(e){return t.error({code:`DISCOVERY_INVALID_JSON`,message:`Invalid discovery JSON: ${e.message}`,exitCode:1})}let a=kT(i);if(!xL(t))for(let e of a)console.log(`[${e.severity}] ${e.path}: ${e.message}`);let o=a.filter(e=>e.severity===`error`).length,c=a.filter(e=>e.severity===`warning`).length;return o>0?t.error({code:`DISCOVERY_INVALID`,message:`Discovery document has ${o} error(s) and ${c} warning(s).`,exitCode:1}):SL(t,{errorCount:o,issues:a,valid:!0,warningCount:c},()=>{console.log(c>0?`Discovery document is valid with ${c} warning(s).`:`Discovery document is valid.`)})}});NL.command(PL),NL.command(RL),NL.command(IL),NL.command(LL),NL.command(RF),NL.command(FL),NL.command(tL);export{NL as default};
260
+ `),DL(t,{file:i},()=>{console.log(`Created ${r}`)}))}}),YL=nb(`services`,{description:`Browse the MPP services registry`}).command(`list`,{description:`List registered MPP services`,options:f.object({query:f.string().optional().describe(`Filter by id, name, category, tag, or description`)}),output:f.object({services:f.array(wL)}),alias:{query:`q`},async run(e){let t=e.options.query?.toLowerCase(),n=await UL(),r=(t?n.filter(e=>[e.id,e.name,e.description,...Array.isArray(e.categories)?e.categories:[],...Array.isArray(e.tags)?e.tags:[]].filter(e=>typeof e==`string`).some(e=>e.toLowerCase().includes(t))):n).map(ML).sort((e,t)=>e.id.localeCompare(t.id));return DL(e,{services:r},()=>{if(r.length===0){console.log(`No services found.`);return}let e=Math.max(...r.map(e=>e.id.length)),t=Math.max(...r.map(e=>String(e.paidEndpoints).length));for(let n of r){let r=n.name&&n.name!==n.id?` ${n.name}`:``,i=n.url?` ${Z.dim(n.url)}`:``;console.log(`${n.id.padEnd(e)} ${String(n.paidEndpoints).padStart(t)} paid${r}${i}`)}})}}).command(`show`,{description:`Show one registered MPP service`,args:f.object({service:f.string().describe(`Service id or name`)}),output:f.object({service:f.record(f.string(),f.unknown())}),async run(e){let t=WL(await UL(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=ML(t),r=jL(t);return DL(e,{service:t},()=>{console.log(`${n.name??n.id} ${Z.dim(`(${n.id})`)}`),n.description&&console.log(n.description),n.url&&console.log(`${Z.dim(`URL`)} ${nO(n.url,n.url)}`),n.status&&console.log(`${Z.dim(`Status`)} ${n.status}`),console.log(`${Z.dim(`Endpoints`)} ${r.length} (${n.paidEndpoints} paid)`);let e=t.docs,i=e&&AL(e.homepage);i&&console.log(`${Z.dim(`Docs`)} ${nO(i,i)}`)})}}).command(`endpoints`,{description:`List endpoints for a registered MPP service`,args:f.object({service:f.string().describe(`Service id or name`)}),output:f.object({endpoints:f.array(TL),service:wL}),async run(e){let t=WL(await UL(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=ML(t),r=jL(t).map(NL);return DL(e,{endpoints:r,service:n},()=>{if(r.length===0){console.log(`No endpoints found for ${n.id}.`);return}let e=Math.max(...r.map(e=>e.method.length)),t=Math.max(...r.map(e=>e.path.length));for(let n of r){let r=PL(n.payment),i=n.description?` ${Z.dim(n.description)}`:``;console.log(`${n.method.padEnd(e)} ${n.path.padEnd(t)} ${r}${i}`)}})}}),XL=nb(`discover`,{description:`Discovery tooling`}).command(`generate`,{description:`Generate a static OpenAPI discovery document from a module`,args:f.object({module:f.string().describe(`Path to a module that default-exports a discovery config`)}),options:f.object({output:f.string().optional().describe(`Write output to a file instead of stdout`)}),output:f.record(f.string(),f.unknown()),alias:{output:`o`},async run(t){let n=s.resolve(t.args.module);if(!e.existsSync(n))return t.error({code:`MODULE_NOT_FOUND`,message:`Module not found: ${n}`,exitCode:1});let r;try{r=await import(n)}catch(e){return t.error({code:`MODULE_IMPORT_FAILED`,message:`Failed to import module: ${e.message}`,exitCode:1})}let i=r.default??r,a;if(typeof i.openapi==`string`)a=i;else{let{generate:e}=await Promise.resolve().then(()=>(yL(),pL)),n=i.mppx;if(!n)return t.error({code:`INVALID_MODULE`,message:"Module must default-export an OpenAPI document (with `openapi` key) or an object with `mppx` (server instance) and `routes`.",exitCode:1});a=e(n,i)}let o=JSON.stringify(a,null,2);if(t.options.output){let n=s.resolve(t.options.output);return e.writeFileSync(n,`${o}\n`),process.stderr.write(`Wrote ${n}\n`),DL(t,a,()=>{})}return DL(t,a,()=>{console.log(o)})}}).command(`validate`,{description:`Validate an OpenAPI discovery document from a file or URL`,args:f.object({input:f.string().describe(`Path or URL to a discovery document`)}),output:f.object({errorCount:f.number(),issues:f.array(CL),valid:f.boolean(),warningCount:f.number()}),async run(t){let n=t.args.input,r;if(/^https?:\/\//.test(n)){let e=new AbortController,i=setTimeout(()=>e.abort(),3e4),a;try{a=await globalThis.fetch(n,{signal:e.signal})}catch(e){clearTimeout(i);let n=e instanceof DOMException&&e.name===`AbortError`?`Request timed out after 30s`:e.message;return t.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: ${n}`,exitCode:1})}if(clearTimeout(i),!a.ok)return t.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: HTTP ${a.status}`,exitCode:1});let o=10485760,s=a.headers.get(`content-length`);if(s&&Number(s)>o||(r=await a.text(),r.length>o))return t.error({code:`DISCOVERY_TOO_LARGE`,message:`Discovery document exceeds 10 MB limit`,exitCode:1})}else{let i=s.resolve(n);if(!e.existsSync(i))return t.error({code:`DISCOVERY_NOT_FOUND`,message:`Discovery document not found: ${i}`,exitCode:1});r=e.readFileSync(i,`utf-8`)}let i;try{i=JSON.parse(r)}catch(e){return t.error({code:`DISCOVERY_INVALID_JSON`,message:`Invalid discovery JSON: ${e.message}`,exitCode:1})}let a=AT(i);if(!EL(t))for(let e of a)console.log(`[${e.severity}] ${e.path}: ${e.message}`);let o=a.filter(e=>e.severity===`error`).length,c=a.filter(e=>e.severity===`warning`).length;return o>0?t.error({code:`DISCOVERY_INVALID`,message:`Discovery document has ${o} error(s) and ${c} warning(s).`,exitCode:1}):DL(t,{errorCount:o,issues:a,valid:!0,warningCount:c},()=>{console.log(c>0?`Discovery document is valid with ${c} warning(s).`:`Discovery document is valid.`)})}});GL.command(KL),GL.command(XL),GL.command(JL),GL.command(YL),GL.command(UF),GL.command(qL),GL.command(oL);export{GL as default};