mppx 0.21.3 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/BodyDigest.d.ts +3 -3
  3. package/dist/BodyDigest.js +5 -3
  4. package/dist/Challenge.js +12 -2
  5. package/dist/Credential.js +9 -1
  6. package/dist/Errors.d.ts +62 -8
  7. package/dist/Errors.js +57 -6
  8. package/dist/Store.d.ts +7 -4
  9. package/dist/Store.js +18 -8
  10. package/dist/cli/cli.js +135 -135
  11. package/dist/cli/internal.js +1 -1
  12. package/dist/cli/plugins/index.js +12 -12
  13. package/dist/client/Budget.d.ts +49 -0
  14. package/dist/client/Budget.js +101 -0
  15. package/dist/client/Mppx.d.ts +8 -3
  16. package/dist/client/Mppx.js +55 -13
  17. package/dist/client/Spend.d.ts +134 -0
  18. package/dist/client/Spend.js +58 -0
  19. package/dist/client/core.d.ts +2 -0
  20. package/dist/client/core.js +2 -0
  21. package/dist/client/internal/Fetch.d.ts +23 -3
  22. package/dist/client/internal/Fetch.js +155 -37
  23. package/dist/client/internal/FundsMoved.d.ts +9 -0
  24. package/dist/client/internal/FundsMoved.js +18 -0
  25. package/dist/client/internal/SpendGate.d.ts +136 -0
  26. package/dist/client/internal/SpendGate.js +608 -0
  27. package/dist/client/internal/SpendHooks.d.ts +42 -0
  28. package/dist/client/internal/SpendHooks.js +36 -0
  29. package/dist/client/internal/protocols/Mcp.d.ts +9 -0
  30. package/dist/client/internal/protocols/Mcp.js +27 -0
  31. package/dist/client/internal/protocols/Mpp.js +20 -3
  32. package/dist/client/internal/protocols/Shared.js +29 -3
  33. package/dist/evm/client/Charge.js +20 -8
  34. package/dist/extensions/identity/erc8004/server/index.d.ts +7 -1
  35. package/dist/extensions/identity/erc8004/server/index.js +13 -1
  36. package/dist/extensions/identity/link/client/index.js +57 -5
  37. package/dist/identity/Client.d.ts +7 -3
  38. package/dist/identity/Client.js +178 -13
  39. package/dist/identity/Types.d.ts +2 -1
  40. package/dist/integrations/x402/Negotiator.js +4 -1
  41. package/dist/integrations/x402/Solana.d.ts +75 -0
  42. package/dist/integrations/x402/Solana.js +143 -0
  43. package/dist/internal/challengeMeta.d.ts +17 -2
  44. package/dist/internal/challengeMeta.js +35 -7
  45. package/dist/internal/version.d.ts +2 -2
  46. package/dist/internal/version.js +1 -1
  47. package/dist/mcp/client/McpClient.d.ts +6 -1
  48. package/dist/mcp/client/McpClient.js +48 -10
  49. package/dist/middlewares/express.d.ts +1 -1
  50. package/dist/server/Mppx.d.ts +12 -1
  51. package/dist/server/Mppx.js +58 -6
  52. package/dist/server/Request.d.ts +1 -1
  53. package/dist/server/Transport.js +46 -2
  54. package/dist/server/internal/host.js +5 -2
  55. package/dist/stripe/server/internal/html.gen.js +1 -1
  56. package/dist/tempo/client/Charge.js +81 -17
  57. package/dist/tempo/server/Charge.d.ts +7 -1
  58. package/dist/tempo/server/Charge.js +98 -12
  59. package/dist/tempo/server/internal/html.gen.js +1 -1
  60. package/dist/tempo/session/client/SessionManager.js +3 -0
  61. package/dist/x402/server/EvmCharge.js +3 -0
  62. package/package.json +1 -1
package/dist/cli/cli.js CHANGED
@@ -1,8 +1,8 @@
1
- import{once as e}from"node:events";import*as t from"node:fs";import n,{existsSync as r,mkdirSync as i,readFileSync as a,writeFileSync as o}from"node:fs";import{createRequire as s}from"node:module";import*as c from"node:path";import l,{dirname as u,join as d}from"node:path";import{z as f,z as p}from"zod";import*as m from"node:child_process";import{execFile as h,execFileSync as g}from"node:child_process";import{createHash as _,randomUUID as v}from"node:crypto";import*as y from"node:util";import*as b from"node:zlib";import*as x from"node:os";import S,{homedir as C}from"node:os";import*as w from"node:fs/promises";import T from"node:fs/promises";import{PassThrough as ee}from"node:stream";import{fileURLToPath as te,pathToFileURL as E}from"node:url";import*as D from"zod/v4";import{AbiParameters as O,Base64 as k,Bytes as A,Hash as ne,Hex as j,Json as re}from"ox";import{createClient as M,createTransport as N,custom as ie,decodeErrorResult as ae,encodeFunctionData as oe,erc20Abi as P,formatUnits as se,getAbiItem as ce,getAddress as F,hashTypedData as le,http as I,isAddress as ue,isAddressEqual as de,keccak256 as fe,parseAbi as pe,parseEventLogs as me,parseUnits as he,zeroAddress as ge}from"viem";import{generatePrivateKey as _e,parseAccount as ve,privateKeyToAccount as L}from"viem/accounts";import{tempo as ye,tempoModerato as be}from"viem/tempo/chains";import*as xe from"zod/mini";import{Token as Se,isInnerList as Ce,parseList as we}from"structured-headers";import{call as Te,getBlockNumber as Ee,getLogs as De,prepareTransactionRequest as Oe,readContract as ke,sendCallsSync as Ae,sendRawTransactionSync as je,sendTransactionSync as Me,signTransaction as Ne,signTypedData as Pe,waitForTransactionReceipt as Fe}from"viem/actions";import{Abis as Ie,Account as Le,Actions as Re,Addresses as ze,TokenId as Be,Transaction as Ve,withFeePayer as He}from"viem/tempo";import{AccountConfig as Ue,Channel as We,KeyAuthorization as Ge,SignatureEnvelope as Ke,TempoAddress as qe,TxEnvelopeTempo as Je}from"ox/tempo";import*as Ye from"node:readline";import{ousd as Xe,pathusd as Ze,usdce as Qe}from"viem/tokens";import*as $e from"viem/chains";import{tempo as et}from"viem/chains";var tt=Object.defineProperty,nt=Object.getOwnPropertyDescriptor,rt=Object.getOwnPropertyNames,it=Object.prototype.hasOwnProperty,R=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},at=(e,t)=>{let n={};for(var r in e)tt(n,r,{get:e[r],enumerable:!0});return t||tt(n,Symbol.toStringTag,{value:`Module`}),n},ot=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=rt(t),a=0,o=i.length,s;a<o;a++)s=i[a],!it.call(e,s)&&s!==n&&tt(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=nt(t,s))||r.enumerable});return e},st=(e,t,n)=>(ot(e,t,`default`),n&&ot(n,t,`default`));function ct(){let e=process.env.npm_config_user_agent??``,n=process.env.npm_execpath??``,r=(()=>{if(!process.argv[1])return``;try{return t.realpathSync(process.argv[1])}catch{return process.argv[1]}})();return e.includes(`pnpm`)?`pnpm`:e.includes(`bun`)?`bun`:e.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 lt(){let e=ct();return e===`pnpm`?`pnpx`:e===`bun`?`bunx`:`npx`}function ut(e){let t=ct();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 dt=R((()=>{}));function ft(e,t={}){if(Ot())return;let n=gt(e,t);if(!n?.check||!n.current)return;let r=St(n.key),i=Ct(r),a=Date.now(),o=Math.max(0,t.interval??kt);if((!i||a-i.checkedAt>=o)&&Tt(r,a,i?.latest,t.binary),!(!i?.latest||!ht(i.latest,n.current)))return{current:n.current,latest:i.latest,name:n.name}}async function pt(e,t={}){let n=gt(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||!bt(r)||wt(St(n.key),{checkedAt:Date.now(),latest:r})}async function mt(e,t={}){let n=gt(e,t);if(!n?.install)throw Error(`No update installer is configured for '${e}'.`);let r=Ct(St(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 ht(e,t){let n=bt(e),r=bt(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 gt(e,t){let n=_t(e),r=t.package??n?.name;if(r&&!xt(r))return;let i=t.version??n?.version,a=r?ut(r):void 0,o=t.check??(r?()=>yt(r):void 0),s=t.install??(a?()=>Dt(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 _t(e){let n=(()=>{if(process.argv[1])try{return t.realpathSync(process.argv[1])}catch{return}})();if(!n)return;let r=c.dirname(n);for(;;){try{let n=JSON.parse(t.readFileSync(c.join(r,`package.json`),`utf8`));if(typeof n.name==`string`&&typeof n.version==`string`&&vt(n,e))return{name:n.name,version:n.version}}catch{}let n=c.dirname(r);if(n===r)return;r=n}}function vt(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 yt(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 bt(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 xt(e){return/^(?:@[A-Za-z0-9][A-Za-z0-9._~-]*\/)?[A-Za-z0-9][A-Za-z0-9._~-]*$/.test(e)}function St(e){let t=process.env.XDG_CACHE_HOME||c.join(x.homedir(),`.cache`);return c.join(t,`incur`,`updates`,`${encodeURIComponent(e)}.json`)}function Ct(e){try{let n=JSON.parse(t.readFileSync(e,`utf8`));return typeof n.checkedAt!=`number`||n.latest!==void 0&&typeof n.latest!=`string`?void 0:n}catch{return}}function wt(e,n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,JSON.stringify(n)+`
2
- `)}function Tt(e,t,n,r){let i=Et(r);if(i)try{wt(e,{checkedAt:t,...n?{latest:n}:void 0});let r=m.spawn(i.command,i.args,{detached:!0,stdio:`ignore`});r.once(`error`,()=>{}),r.unref()}catch{}}function Et(e){if(e)return{args:[At],command:process.execPath};let n=process.argv[1];if(n){if(n.startsWith(`/$bunfs/`))return{args:[At],command:process.execPath};try{if(t.realpathSync(n)===t.realpathSync(process.execPath))return{args:[At],command:process.execPath}}catch{}return{args:[...process.execArgv,n,At],command:process.execPath}}}function Dt(e,t){return new Promise((n,r)=>{m.execFile(e,t,(e,t,i)=>{if(!e)return n();r(Error(i.trim()||t.trim()||e.message))})})}function Ot(){return process.env.NO_UPDATE_NOTIFIER||process.env.npm_config_update_notifier===`false`?!0:!!(process.env.CI&&process.env.CI!==`false`)}var kt,At,jt=R((()=>{dt(),kt=864e5,At=`--incur-update-check`}));async function Mt(e=process.argv.slice(2)){if(e[0]!==`--incur-binary-apply`)return process.platform===`win32`&&Wt&&Gt&&Kt&&await Rt(process.execPath),!1;if(process.platform!==`win32`)throw Error(`${Ut} is only supported on Windows.`);if(e.length!==2||!e[1])throw Error(`Invalid ${Ut} arguments.`);let t=Number(e[1]);if(!Number.isSafeInteger(t)||t<=0)throw Error(`Invalid ${Ut} arguments.`);return await Nt(t),!0}async function Nt(e){let n=Pt(process.execPath,e),r=!1;try{await Ft(e),await t.promises.rename(n.target,n.backup),r=!0,await t.promises.rename(n.staged,n.target)}catch(e){let i=e,a=`The installed executable remains at '${n.target}'.`;if(r)try{await t.promises.rename(n.backup,n.target),r=!1,a=`The previous executable was restored to '${n.target}'.`}catch(e){try{await t.promises.copyFile(n.backup,n.target,t.constants.COPYFILE_EXCL),a=`The previous executable was copied back to '${n.target}', and its backup remains at '${n.backup}'.`}catch(t){i=Error(`Binary update failed and '${n.target}' could not be restored. The previous executable remains at '${n.backup}': ${Vt(t)}`,{cause:e})}}throw await zt(n,i,a),i}await Bt(n.backup),await Bt(n.error),await Bt(n.staged),await Bt(n.helper)}function Pt(e,t){let n=c.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 Ft(e){let t=Date.now()+Ht;for(;It(e);){if(Date.now()>=t)throw Error(`Timed out waiting for update process ${e} to exit.`);await Lt(100)}}function It(e){try{return process.kill(e,0),!0}catch(e){return e.code!==`ESRCH`}}function Lt(e){return new Promise(t=>setTimeout(t,e))}async function Rt(e){let n=c.dirname(e),r=`${c.basename(e)}.incur-handoff-`;try{let e=await t.promises.readdir(n);await Promise.all(e.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=>Bt(c.join(n,e))))}catch{}}async function zt(e,n,r){let i=[`Binary update failed: ${Vt(n)}`,`Recovery: ${r}`,`Downloaded candidate: ${e.staged}`,`Previous executable backup: ${e.backup}`].join(`
3
- `);try{await t.promises.writeFile(e.error,`${i}\n`,{flag:`wx`,mode:384})}catch{}}async function Bt(e){try{await t.promises.unlink(e)}catch{}}function Vt(e){return e instanceof Error?e.message:String(e)}var Ht,Ut,Wt,Gt,Kt,qt=R((()=>{Ht=6e4,y.promisify(b.gunzip),Ut=`--incur-binary-apply`,Wt=typeof __INCUR_BINARY_NAME__==`string`&&__INCUR_BINARY_NAME__?__INCUR_BINARY_NAME__:void 0,Gt=typeof __INCUR_BINARY_TARGET__==`string`&&__INCUR_BINARY_TARGET__?__INCUR_BINARY_TARGET__:void 0,Kt=typeof __INCUR_BINARY_VERSION__==`string`&&__INCUR_BINARY_VERSION__?__INCUR_BINARY_VERSION__:void 0}));function*Jt(e,t={}){if(!e)return;let n=Yt(t);for(let t of e.split(an))t&&(yield{segment:t,tokenCount:Xt(t,n)})}function Yt(e){return{defaultCharsPerToken:e.defaultCharsPerToken??on,languageConfigs:e.languageConfigs??ln}}function Xt(e,{languageConfigs:t,defaultCharsPerToken:n}){if(rn.whitespace.test(e))return+!!rn.structuredWhitespace.test(e);let r=Zt(e,t);return r===void 0?rn.cjk.test(e)?$t(e):rn.numeric.test(e)?Math.ceil(e.length/3):e.length<=sn?1:rn.punctuation.test(e)?Math.ceil(e.length/2):Math.ceil(e.length/n):Math.ceil(Qt(e)/r)}function Zt(e,t){for(let n of t)if(e.search(n.pattern)!==-1)return n.averageCharsPerToken}function Qt(e){return Array.from(e).length}function $t(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/cn)}function en(e,t={}){if(!e)return 0;let n=0;for(let r of Jt(e,t))n+=r.tokenCount;return n}function tn(e,t=0,n,r={}){if(!e)return``;let i=Jt(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=nn(e,l,t,o,s);n&&c.push(n),l+=t}return c.join(``)}function nn(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 rn,an,on,sn,cn,ln,un=R((()=>{rn={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:/[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_"-]/},an=RegExp(`(\\s+|${rn.punctuation.source}+)`),on=6,sn=3,cn=1.35,ln=[{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 dn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fn(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function pn(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 mn(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=pn(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 hn=R((()=>{}));function gn(e,t){switch(e){case`bash`:return Tn(t);case`zsh`:return En(t);case`fish`:return Dn(t);case`nushell`:return On(t)}}function _n(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=`--${fn(e)}`;n.startsWith(a)&&s.push({value:n,description:Cn(t[e])})}if(e.alias)for(let[n,r]of Object.entries(e.alias)){let e=`-${r}`;if(e.startsWith(a)){let r=Cn(t[n]);s.push({value:e,description:r})}}}if(i){let e=i.schema.shape;for(let t of Object.keys(e)){let n=`--${fn(t)}`;n.startsWith(a)&&!s.some(e=>e.value===n)&&s.push({value:n,description:Cn(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=Cn(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=yn(e,t);if(n){let e=xn(n,t.options);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!bn(n,t.options))return s}}if(i){let t=yn(e,{options:i.schema,alias:i.alias});if(t){let e=xn(t,i.schema);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!bn(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 vn(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(`
1
+ import{once as e}from"node:events";import*as t from"node:fs";import n,{existsSync as r,mkdirSync as i,readFileSync as a,writeFileSync as o}from"node:fs";import{createRequire as s}from"node:module";import*as c from"node:path";import l,{dirname as u,join as d}from"node:path";import{z as f,z as p}from"zod";import*as m from"node:child_process";import{execFile as h,execFileSync as g}from"node:child_process";import{createHash as _,randomUUID as v}from"node:crypto";import*as y from"node:util";import*as b from"node:zlib";import*as x from"node:os";import S,{homedir as C}from"node:os";import*as w from"node:fs/promises";import T from"node:fs/promises";import{PassThrough as E}from"node:stream";import{fileURLToPath as ee,pathToFileURL as D}from"node:url";import*as O from"zod/v4";import{AbiParameters as k,Base64 as te,Bytes as A,Hash as j,Hex as M,Json as ne}from"ox";import{createClient as N,createTransport as P,custom as re,decodeErrorResult as ie,encodeFunctionData as ae,erc20Abi as F,formatUnits as oe,getAbiItem as se,getAddress as I,hashTypedData as ce,http as L,isAddress as le,isAddressEqual as ue,keccak256 as de,parseAbi as fe,parseEventLogs as pe,parseUnits as me,zeroAddress as he}from"viem";import{generatePrivateKey as ge,parseAccount as _e,privateKeyToAccount as R}from"viem/accounts";import{tempo as ve,tempoModerato as ye}from"viem/tempo/chains";import*as be from"zod/mini";import{Token as xe,isInnerList as Se,parseList as Ce}from"structured-headers";import{ousd as we,pathusd as Te,usdce as Ee}from"viem/tokens";import{call as De,getBlockNumber as Oe,getLogs as ke,prepareTransactionRequest as Ae,readContract as je,sendCallsSync as Me,sendRawTransactionSync as Ne,sendTransactionSync as Pe,signTransaction as Fe,signTypedData as Ie,waitForTransactionReceipt as Le}from"viem/actions";import{Abis as Re,Account as ze,Actions as Be,Addresses as Ve,TokenId as He,Transaction as Ue,withFeePayer as We}from"viem/tempo";import{AccountConfig as Ge,Channel as Ke,KeyAuthorization as qe,SignatureEnvelope as Je,TempoAddress as Ye,TxEnvelopeTempo as Xe}from"ox/tempo";import*as Ze from"node:readline";import*as Qe from"viem/chains";import{tempo as $e}from"viem/chains";var et=Object.defineProperty,tt=Object.getOwnPropertyDescriptor,nt=Object.getOwnPropertyNames,rt=Object.prototype.hasOwnProperty,z=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},it=(e,t)=>{let n={};for(var r in e)et(n,r,{get:e[r],enumerable:!0});return t||et(n,Symbol.toStringTag,{value:`Module`}),n},at=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=nt(t),a=0,o=i.length,s;a<o;a++)s=i[a],!rt.call(e,s)&&s!==n&&et(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=tt(t,s))||r.enumerable});return e},ot=(e,t,n)=>(at(e,t,`default`),n&&at(n,t,`default`));function st(){let e=process.env.npm_config_user_agent??``,n=process.env.npm_execpath??``,r=(()=>{if(!process.argv[1])return``;try{return t.realpathSync(process.argv[1])}catch{return process.argv[1]}})();return e.includes(`pnpm`)?`pnpm`:e.includes(`bun`)?`bun`:e.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 ct(){let e=st();return e===`pnpm`?`pnpx`:e===`bun`?`bunx`:`npx`}function lt(e){let t=st();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 ut=z((()=>{}));function dt(e,t={}){if(Dt())return;let n=ht(e,t);if(!n?.check||!n.current)return;let r=xt(n.key),i=St(r),a=Date.now(),o=Math.max(0,t.interval??Ot);if((!i||a-i.checkedAt>=o)&&wt(r,a,i?.latest,t.binary),!(!i?.latest||!mt(i.latest,n.current)))return{current:n.current,latest:i.latest,name:n.name}}async function ft(e,t={}){let n=ht(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||!yt(r)||Ct(xt(n.key),{checkedAt:Date.now(),latest:r})}async function pt(e,t={}){let n=ht(e,t);if(!n?.install)throw Error(`No update installer is configured for '${e}'.`);let r=St(xt(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 mt(e,t){let n=yt(e),r=yt(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 ht(e,t){let n=gt(e),r=t.package??n?.name;if(r&&!bt(r))return;let i=t.version??n?.version,a=r?lt(r):void 0,o=t.check??(r?()=>vt(r):void 0),s=t.install??(a?()=>Et(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 gt(e){let n=(()=>{if(process.argv[1])try{return t.realpathSync(process.argv[1])}catch{return}})();if(!n)return;let r=c.dirname(n);for(;;){try{let n=JSON.parse(t.readFileSync(c.join(r,`package.json`),`utf8`));if(typeof n.name==`string`&&typeof n.version==`string`&&_t(n,e))return{name:n.name,version:n.version}}catch{}let n=c.dirname(r);if(n===r)return;r=n}}function _t(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 vt(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 yt(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 bt(e){return/^(?:@[A-Za-z0-9][A-Za-z0-9._~-]*\/)?[A-Za-z0-9][A-Za-z0-9._~-]*$/.test(e)}function xt(e){let t=process.env.XDG_CACHE_HOME||c.join(x.homedir(),`.cache`);return c.join(t,`incur`,`updates`,`${encodeURIComponent(e)}.json`)}function St(e){try{let n=JSON.parse(t.readFileSync(e,`utf8`));return typeof n.checkedAt!=`number`||n.latest!==void 0&&typeof n.latest!=`string`?void 0:n}catch{return}}function Ct(e,n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,JSON.stringify(n)+`
2
+ `)}function wt(e,t,n,r){let i=Tt(r);if(i)try{Ct(e,{checkedAt:t,...n?{latest:n}:void 0});let r=m.spawn(i.command,i.args,{detached:!0,stdio:`ignore`});r.once(`error`,()=>{}),r.unref()}catch{}}function Tt(e){if(e)return{args:[kt],command:process.execPath};let n=process.argv[1];if(n){if(n.startsWith(`/$bunfs/`))return{args:[kt],command:process.execPath};try{if(t.realpathSync(n)===t.realpathSync(process.execPath))return{args:[kt],command:process.execPath}}catch{}return{args:[...process.execArgv,n,kt],command:process.execPath}}}function Et(e,t){return new Promise((n,r)=>{m.execFile(e,t,(e,t,i)=>{if(!e)return n();r(Error(i.trim()||t.trim()||e.message))})})}function Dt(){return process.env.NO_UPDATE_NOTIFIER||process.env.npm_config_update_notifier===`false`?!0:!!(process.env.CI&&process.env.CI!==`false`)}var Ot,kt,At=z((()=>{ut(),Ot=864e5,kt=`--incur-update-check`}));async function jt(e=process.argv.slice(2)){if(e[0]!==`--incur-binary-apply`)return process.platform===`win32`&&Ut&&Wt&&Gt&&await Lt(process.execPath),!1;if(process.platform!==`win32`)throw Error(`${Ht} is only supported on Windows.`);if(e.length!==2||!e[1])throw Error(`Invalid ${Ht} arguments.`);let t=Number(e[1]);if(!Number.isSafeInteger(t)||t<=0)throw Error(`Invalid ${Ht} arguments.`);return await Mt(t),!0}async function Mt(e){let n=Nt(process.execPath,e),r=!1;try{await Pt(e),await t.promises.rename(n.target,n.backup),r=!0,await t.promises.rename(n.staged,n.target)}catch(e){let i=e,a=`The installed executable remains at '${n.target}'.`;if(r)try{await t.promises.rename(n.backup,n.target),r=!1,a=`The previous executable was restored to '${n.target}'.`}catch(e){try{await t.promises.copyFile(n.backup,n.target,t.constants.COPYFILE_EXCL),a=`The previous executable was copied back to '${n.target}', and its backup remains at '${n.backup}'.`}catch(t){i=Error(`Binary update failed and '${n.target}' could not be restored. The previous executable remains at '${n.backup}': ${Bt(t)}`,{cause:e})}}throw await Rt(n,i,a),i}await zt(n.backup),await zt(n.error),await zt(n.staged),await zt(n.helper)}function Nt(e,t){let n=c.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 Pt(e){let t=Date.now()+Vt;for(;Ft(e);){if(Date.now()>=t)throw Error(`Timed out waiting for update process ${e} to exit.`);await It(100)}}function Ft(e){try{return process.kill(e,0),!0}catch(e){return e.code!==`ESRCH`}}function It(e){return new Promise(t=>setTimeout(t,e))}async function Lt(e){let n=c.dirname(e),r=`${c.basename(e)}.incur-handoff-`;try{let e=await t.promises.readdir(n);await Promise.all(e.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=>zt(c.join(n,e))))}catch{}}async function Rt(e,n,r){let i=[`Binary update failed: ${Bt(n)}`,`Recovery: ${r}`,`Downloaded candidate: ${e.staged}`,`Previous executable backup: ${e.backup}`].join(`
3
+ `);try{await t.promises.writeFile(e.error,`${i}\n`,{flag:`wx`,mode:384})}catch{}}async function zt(e){try{await t.promises.unlink(e)}catch{}}function Bt(e){return e instanceof Error?e.message:String(e)}var Vt,Ht,Ut,Wt,Gt,Kt=z((()=>{Vt=6e4,y.promisify(b.gunzip),Ht=`--incur-binary-apply`,Ut=typeof __INCUR_BINARY_NAME__==`string`&&__INCUR_BINARY_NAME__?__INCUR_BINARY_NAME__:void 0,Wt=typeof __INCUR_BINARY_TARGET__==`string`&&__INCUR_BINARY_TARGET__?__INCUR_BINARY_TARGET__:void 0,Gt=typeof __INCUR_BINARY_VERSION__==`string`&&__INCUR_BINARY_VERSION__?__INCUR_BINARY_VERSION__:void 0}));function*qt(e,t={}){if(!e)return;let n=Jt(t);for(let t of e.split(rn))t&&(yield{segment:t,tokenCount:Yt(t,n)})}function Jt(e){return{defaultCharsPerToken:e.defaultCharsPerToken??an,languageConfigs:e.languageConfigs??cn}}function Yt(e,{languageConfigs:t,defaultCharsPerToken:n}){if(nn.whitespace.test(e))return+!!nn.structuredWhitespace.test(e);let r=Xt(e,t);return r===void 0?nn.cjk.test(e)?Qt(e):nn.numeric.test(e)?Math.ceil(e.length/3):e.length<=on?1:nn.punctuation.test(e)?Math.ceil(e.length/2):Math.ceil(e.length/n):Math.ceil(Zt(e)/r)}function Xt(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 Qt(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/sn)}function $t(e,t={}){if(!e)return 0;let n=0;for(let r of qt(e,t))n+=r.tokenCount;return n}function en(e,t=0,n,r={}){if(!e)return``;let i=qt(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=tn(e,l,t,o,s);n&&c.push(n),l+=t}return c.join(``)}function tn(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 nn,rn,an,on,sn,cn,ln=z((()=>{nn={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:/[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_"-]/},rn=RegExp(`(\\s+|${nn.punctuation.source}+)`),an=6,on=3,sn=1.35,cn=[{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 un(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function dn(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function fn(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 pn(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=fn(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 mn=z((()=>{}));function hn(e,t){switch(e){case`bash`:return wn(t);case`zsh`:return Tn(t);case`fish`:return En(t);case`nushell`:return Dn(t)}}function gn(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=`--${dn(e)}`;n.startsWith(a)&&s.push({value:n,description:Sn(t[e])})}if(e.alias)for(let[n,r]of Object.entries(e.alias)){let e=`-${r}`;if(e.startsWith(a)){let r=Sn(t[n]);s.push({value:e,description:r})}}}if(i){let e=i.schema.shape;for(let t of Object.keys(e)){let n=`--${dn(t)}`;n.startsWith(a)&&!s.some(e=>e.value===n)&&s.push({value:n,description:Sn(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=Sn(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=vn(e,t);if(n){let e=bn(n,t.options);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!yn(n,t.options))return s}}if(i){let t=vn(e,{options:i.schema,alias:i.alias});if(t){let e=bn(t,i.schema);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!yn(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 _n(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(`
5
- `);case`nushell`:{let e=t.map(e=>{let t={value:e.value};return e.description&&(t.description=e.description),t});return JSON.stringify(e)}}}function yn(e,t){if(!t.options)return;let n=new Set(Object.keys(t.options.shape)),r=new Map;for(let e of n){let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);t!==e&&r.set(t,e)}if(e.startsWith(`--`)){let t=e.slice(2),i=r.get(t)??t;return n.has(i)?i:void 0}if(e.startsWith(`-`)&&e.length===2&&t.alias){let n=e.slice(1);for(let[e,r]of Object.entries(t.alias))if(r===n)return e}}function bn(e,t){let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0||Sn(n).constructor.name===`ZodBoolean`:!1}function xn(e,t){let n=t.shape[e];if(!n)return;let r=Sn(n);if(r.constructor.name===`ZodEnum`)return Object.values(r._zod.def.entries);if(r.constructor.name===`ZodNativeEnum`)return Object.keys(r._zod.def.values)}function Sn(e){let t=e;for(;t._zod?.def?.innerType;)t=t._zod.def.innerType;return t}function Cn(e){if(e)return e.description}function wn(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`)}function Tn(e){let t=wn(e);return`_incur_complete_${t}() {
5
+ `);case`nushell`:{let e=t.map(e=>{let t={value:e.value};return e.description&&(t.description=e.description),t});return JSON.stringify(e)}}}function vn(e,t){if(!t.options)return;let n=new Set(Object.keys(t.options.shape)),r=new Map;for(let e of n){let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);t!==e&&r.set(t,e)}if(e.startsWith(`--`)){let t=e.slice(2),i=r.get(t)??t;return n.has(i)?i:void 0}if(e.startsWith(`-`)&&e.length===2&&t.alias){let n=e.slice(1);for(let[e,r]of Object.entries(t.alias))if(r===n)return e}}function yn(e,t){let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0||xn(n).constructor.name===`ZodBoolean`:!1}function bn(e,t){let n=t.shape[e];if(!n)return;let r=xn(n);if(r.constructor.name===`ZodEnum`)return Object.values(r._zod.def.entries);if(r.constructor.name===`ZodNativeEnum`)return Object.keys(r._zod.def.values)}function xn(e){let t=e;for(;t._zod?.def?.innerType;)t=t._zod.def.innerType;return t}function Sn(e){if(e)return e.description}function Cn(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`)}function wn(e){let t=Cn(e);return`_incur_complete_${t}() {
6
6
  local IFS=$'\\013'
7
7
  local _COMPLETE_INDEX=\${COMP_CWORD}
8
8
  local _completions
@@ -29,7 +29,7 @@ import{once as e}from"node:events";import*as t from"node:fs";import n,{existsSyn
29
29
  compopt -o nospace
30
30
  fi
31
31
  }
32
- complete -o default -o bashdefault -o nosort -F _incur_complete_${t} ${e}`}function En(e){let t=wn(e);return`#compdef ${e}
32
+ complete -o default -o bashdefault -o nosort -F _incur_complete_${t} ${e}`}function Tn(e){let t=Cn(e);return`#compdef ${e}
33
33
  _incur_complete_${t}() {
34
34
  local completions=("\${(@f)$(
35
35
  export _COMPLETE_INDEX=$(( CURRENT - 1 ))
@@ -40,64 +40,64 @@ _incur_complete_${t}() {
40
40
  _describe 'values' completions -S ''
41
41
  fi
42
42
  }
43
- compdef _incur_complete_${t} ${e}`}function Dn(e){return`complete --keep-order --exclusive --command ${e} \\
44
- --arguments "(COMPLETE=fish ${e} -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))"`}function On(e){return`# External completer for ${e}
43
+ compdef _incur_complete_${t} ${e}`}function En(e){return`complete --keep-order --exclusive --command ${e} \\
44
+ --arguments "(COMPLETE=fish ${e} -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))"`}function Dn(e){return`# External completer for ${e}
45
45
  # Add to $env.config.completions.external.completer or use in a dispatch completer.
46
- let _incur_complete_${wn(e)} = {|spans|
46
+ let _incur_complete_${Cn(e)} = {|spans|
47
47
  COMPLETE=nushell ${e} -- ...$spans | from json
48
- }`}var kn=R((()=>{hn()}));function An(e,t){if(t){let n=e?.cause;for(;n;){if(t(n))return n;n=n?.cause}return}let n=e;for(;n?.cause;)n=n.cause;return n}var jn,z,Mn,Nn,Pn=R((()=>{jn=class extends Error{name=`Incur.BaseError`;shortMessage;details;constructor(e,t={}){let n=t.cause instanceof Error?t.cause.message:void 0,r=n?`${e}\n\nDetails: ${n}`:e;super(r,t.cause?{cause:t.cause}:void 0),this.shortMessage=e,this.details=n}walk(e){return An(this,e)}},z=class extends jn{name=`Incur.IncurError`;code;hint;retryable;exitCode;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.code=e.code,this.hint=e.hint,this.retryable=e.retryable??!1,this.exitCode=e.exitCode}},Mn=class extends jn{name=`Incur.ValidationError`;fieldErrors;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.fieldErrors=e.fieldErrors??[]}},Nn=class extends jn{name=`Incur.ParseError`;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0)}}}));function Fn(e){let t=[],n=new Headers,r=new URLSearchParams,i,a,o=0;for(;o<e.length;){let n=e[o];if(n.startsWith(`--`)){let t=n.indexOf(`=`);if(t!==-1){let e=n.slice(2,t),i=n.slice(t+1);Bn.has(e)?s(e,i):r.set(e,i),o++}else{let t=n.slice(2),i=e[o+1];if(i===void 0)throw Error(`Missing value for --${t}`);Bn.has(t)?s(t,i):r.set(t,i),o+=2}}else if(n.startsWith(`-`)&&n.length===2){let t=n[1],r=Vn[t];if(r){let n=e[o+1];if(n===void 0)throw Error(`Missing value for -${t}`);s(r,n),o+=2}else o++}else t.push(n),o++}function s(e,t){if(e===`method`)i=t.toUpperCase();else if(e===`body`||e===`data`)a=t;else if(e===`header`){let e=t.indexOf(`:`);if(e!==-1){let r=t.slice(0,e).trim(),i=t.slice(e+1).trim();n.set(r,i)}}}return{path:t.length>0?`/${t.join(`/`)}`:`/`,method:i??(a===void 0?`GET`:`POST`),headers:n,body:a,query:r}}function In(e){let t=new URL(e.path,`http://localhost`);e.query.forEach((e,n)=>t.searchParams.set(n,e));let n={method:e.method,headers:e.headers};return e.body!==void 0&&(n.body=e.body,e.headers.has(`content-type`)||e.headers.set(`content-type`,`application/json`)),new Request(t.toString(),n)}function Ln(e){return e.body!==null&&e.headers.get(`content-type`)===`application/x-ndjson`}async function*Rn(e){let t=e.body.getReader(),n=new TextDecoder,r=``;for(;;){let{value:e,done:i}=await t.read();if(i)break;r+=n.decode(e,{stream:!0});let a;for(;(a=r.indexOf(`
49
- `))!==-1;){let e=r.slice(0,a).trim();if(r=r.slice(a+1),e.length!==0)try{yield JSON.parse(e)}catch{yield e}}}let i=r.trim();if(i.length>0)try{yield JSON.parse(i)}catch{yield i}}async function zn(e){let t=await e.text(),n;try{n=JSON.parse(t)}catch{n=t}return{ok:e.ok,status:e.status,data:n,headers:e.headers}}var Bn,Vn,Hn=R((()=>{Bn=new Set([`method`,`body`,`data`,`header`]),Vn={X:`method`,d:`data`,H:`header`}}));function Un(e){let t=[],n=[],r=``,i=0;for(let t=0;t<e.length;t++){let a=e[t];a===`[`?i++:a===`]`&&i--,a===`,`&&i===0?(n.push(r),r=``):r+=a}r&&n.push(r);for(let e of n){let n=[],r=e;for(;r.length>0;){let e=r.indexOf(`[`);if(e===-1){for(let e of r.split(`.`))e&&n.push({key:e});break}let t=r.slice(0,e);for(let e of t.split(`.`))e&&n.push({key:e});let i=r.indexOf(`]`,e),[a,o]=r.slice(e+1,i).split(`,`);n.push({start:Number(a),end:Number(o)}),r=r.slice(i+1),r.startsWith(`.`)&&(r=r.slice(1))}t.push(n)}return t}function Wn(e,t){if(t.length===0)return e;if(t.length===1&&t[0].length===1&&`key`in t[0][0]){let n=t[0][0].key;if(Array.isArray(e))return e.map(e=>Wn(e,t));if(typeof e==`object`&&e){let t=e[n];return typeof t!=`object`||!t?t:{[n]:t}}return}if(Array.isArray(e))return e.map(e=>Wn(e,t));let n={};for(let r of t)Gn(n,e,r,0);return n}function Gn(e,t,n,r){if(r>=n.length||typeof t!=`object`||!t)return;let i=n[r];if(`key`in i){let a=t[i.key];if(a===void 0)return;if(r+1>=n.length){e[i.key]=a;return}let o=n[r+1];if(`start`in o){if(!Array.isArray(a))return;let t=a.slice(o.start,o.end);if(r+2>=n.length){e[i.key]=t;return}e[i.key]=t.map(e=>{let t={};return Gn(t,e,n,r+2),t});return}if(typeof a!=`object`||!a)return;(!e[i.key]||typeof e[i.key]!=`object`)&&(e[i.key]={}),Gn(e[i.key],a,n,r+1);return}}var Kn=R((()=>{}));function qn(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`).replace(/[\u0000-\u001F]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function Jn(e){return e===`true`||e===`false`||e===`null`}function Yn(e,t,n){if(t===`__proto__`){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0});return}e[t]=n}function Xn(e){if(e===null)return null;if(typeof e==`object`&&e&&`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();if(t!==e)return Xn(t)}if(typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e==`bigint`)return e>=-(2**53-1)&&e<=2**53-1?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(Xn);if(e instanceof Set)return Array.from(e).map(Xn);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),Xn(t)]));if(tr(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&Yn(t,n,Xn(e[n]));return t}return null}function Zn(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function Qn(e){return Array.isArray(e)}function $n(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function er(e){return Object.keys(e).length===0}function tr(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function nr(e){return e.length===0||e.every(e=>Zn(e))}function rr(e){return e.length===0||e.every(e=>Qn(e))}function ir(e){return e.length===0||e.every(e=>$n(e))}function ar(e){return/^[A-Z_][\w.]*$/i.test(e)}function or(e){return/^[A-Z_]\w*$/i.test(e)}function sr(e,t=Vr){return!(!e||e!==e.trim()||Jn(e)||cr(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith(`-`))}function cr(e){return Hr.test(e)||Ur.test(e)}function lr(e,t,n,r,i,a,o){if(r.keyFolding!==`safe`||!$n(t))return;let{segments:s,tail:c,leafValue:l}=ur(e,t,o??r.flattenDepth);if(s.length<2||!s.every(e=>or(e)))return;let u=dr(s),d=a?`${a}.${u}`:u;if(!n.includes(u)&&!(i&&i.has(d)))return{foldedKey:u,remainder:c,leafValue:l,segmentCount:s.length}}function ur(e,t,n){let r=[e],i=t;for(;r.length<n&&$n(i);){let e=Object.keys(i);if(e.length!==1)break;let t=e[0],n=i[t];r.push(t),i=n}return!$n(i)||er(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function dr(e){return e.join(`.`)}function fr(e,t){return e===null?zr:typeof e==`boolean`||typeof e==`number`?String(e):pr(e,t)}function pr(e,t=Vr){return sr(e,t)?e:`"${qn(e)}"`}function mr(e){return ar(e)?e:`"${qn(e)}"`}function hr(e,t=Vr){return e.map(e=>fr(e,t)).join(t)}function gr(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;if(n!=null&&(a+=mr(n)),a+=`[${e}${i===Vr?``:i}]`,r){let e=r.map(e=>mr(e));a+=`{${e.join(i)}}`}return a+=`:`,a}function*_r(e,t,n){if(Zn(e)){let n=fr(e,t.delimiter);n!==``&&(yield n);return}Qn(e)?yield*br(void 0,e,n,t):$n(e)&&(yield*vr(e,n,t))}function*vr(e,t,n,r,i,a){let o=Object.keys(e);t===0&&!r&&(r=new Set(o.filter(e=>e.includes(`.`))));let s=a??n.flattenDepth;for(let[a,c]of Object.entries(e))yield*yr(a,c,t,n,o,r,i,s)}function*yr(e,t,n,r,i,a,o,s){let c=o?`${o}.${e}`:e,l=s??r.flattenDepth;if(r.keyFolding===`safe`&&i){let s=lr(e,t,i,r,a,o,l);if(s){let{foldedKey:e,remainder:t,leafValue:i,segmentCount:c}=s,u=mr(e);if(t===void 0){if(Zn(i)){yield Ar(n,`${u}: ${fr(i,r.delimiter)}`,r.indent);return}if(Qn(i)){yield*br(e,i,n,r);return}if($n(i)&&er(i)){yield Ar(n,`${u}:`,r.indent);return}}if($n(t)){yield Ar(n,`${u}:`,r.indent);let i=l-c,s=o?`${o}.${e}`:e;yield*vr(t,n+1,r,a,s,i);return}}}let u=mr(e);Zn(t)?yield Ar(n,`${u}: ${fr(t,r.delimiter)}`,r.indent):Qn(t)?yield*br(e,t,n,r):$n(t)&&(yield Ar(n,`${u}:`,r.indent),er(t)||(yield*vr(t,n+1,r,a,c,l)))}function*br(e,t,n,r){if(t.length===0){yield Ar(n,e==null?`[]`:`${mr(e)}: []`,r.indent);return}if(nr(t)){yield Ar(n,Sr(t,r.delimiter,e),r.indent);return}if(rr(t)&&t.every(e=>nr(e))){yield*xr(e,t,n,r);return}if(ir(t)){let i=wr(t);i?yield*Cr(e,t,i,n,r):yield*Dr(e,t,n,r);return}yield*Dr(e,t,n,r)}function*xr(e,t,n,r){yield Ar(n,gr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)if(nr(e)){let t=Sr(e,r.delimiter);yield jr(n+1,t,r.indent)}}function Sr(e,t,n){let r=gr(e.length,{key:n,delimiter:t}),i=hr(e,t);return e.length===0?r:`${r} ${i}`}function*Cr(e,t,n,r,i){yield Ar(r,gr(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*Er(t,n,r+1,i)}function wr(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&Tr(e,n))return n}function Tr(e,t){for(let n of e){if(Object.keys(n).length!==t.length)return!1;for(let e of t)if(!Object.hasOwn(n,e)||!Zn(n[e]))return!1}return!0}function*Er(e,t,n,r){for(let i of e)yield Ar(n,hr(t.map(e=>i[e]),r.delimiter),r.indent)}function*Dr(e,t,n,r){yield Ar(n,gr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)yield*kr(e,n+1,r)}function*Or(e,t,n){if(er(e)){yield Ar(t,`-`,n.indent);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(Qn(a)&&ir(a)){let e=wr(a);if(e){yield jr(t,gr(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indent),yield*Er(a,e,t+2,n),o.length>0&&(yield*vr(Object.fromEntries(o),t+1,n));return}}let s=mr(i);if(Zn(a))yield jr(t,`${s}: ${fr(a,n.delimiter)}`,n.indent);else if(Qn(a)){if(a.length===0)yield jr(t,`${s}: []`,n.indent);else if(nr(a))yield jr(t,`${s}${Sr(a,n.delimiter)}`,n.indent);else{yield jr(t,`${s}${gr(a.length,{delimiter:n.delimiter})}`,n.indent);for(let e of a)yield*kr(e,t+2,n)}}else $n(a)&&(yield jr(t,`${s}:`,n.indent),er(a)||(yield*vr(a,t+2,n)));o.length>0&&(yield*vr(Object.fromEntries(o),t+1,n))}function*kr(e,t,n){if(Zn(e))yield jr(t,fr(e,n.delimiter),n.indent);else if(Qn(e)){if(nr(e))yield jr(t,Sr(e,n.delimiter),n.indent);else{yield jr(t,gr(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*kr(r,t+1,n)}}else $n(e)&&(yield*Or(e,t,n))}function Ar(e,t,n){return` `.repeat(n*e)+t}function jr(e,t,n){return Ar(e,`- `+t,n)}function Mr(e,t){let n=t(``,e,[]);return Nr(n===void 0?e:Xn(n),t,[])}function Nr(e,t,n){return $n(e)?Pr(e,t,n):Qn(e)?Fr(e,t,n):e}function Pr(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=[...n,i],o=t(i,a,e);o!==void 0&&Yn(r,i,Nr(Xn(o),t,e))}return r}function Fr(e,t,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i],o=[...n,i],s=t(String(i),a,o);if(s===void 0)continue;let c=Xn(s);r.push(Nr(c,t,o))}return r}function Ir(e,t){return Array.from(Lr(e,t)).join(`
50
- `)}function Lr(e,t){let n=Xn(e),r=Rr(t);return _r(r.replacer?Mr(n,r.replacer):n,r,0)}function Rr(e){return{indent:e?.indent??2,delimiter:e?.delimiter??Vr,keyFolding:e?.keyFolding??`off`,flattenDepth:e?.flattenDepth??1/0,replacer:e?.replacer}}var zr,Br,Vr,Hr,Ur,Wr=R((()=>{zr=`null`,Br={comma:`,`,tab:` `,pipe:`|`},Vr=Br.comma,Hr=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,Ur=/^0\d+$/}));function Gr(e,t){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t,t)}function Kr(e){return JSON.parse(Gr(e))}var qr=R((()=>{}));function Jr(e){if(e&&typeof e==`object`)switch(e[ni]){case Qr:case ti:return!0}return!1}function Yr(e){if(e&&typeof e==`object`)switch(e[ni]){case Xr:case Qr:case ei:case ti:return!0}return!1}var Xr,Zr,Qr,$r,ei,ti,ni,ri,ii,ai,oi,si,ci,li,ui=R((()=>{Xr=Symbol.for(`yaml.alias`),Zr=Symbol.for(`yaml.document`),Qr=Symbol.for(`yaml.map`),$r=Symbol.for(`yaml.pair`),ei=Symbol.for(`yaml.scalar`),ti=Symbol.for(`yaml.seq`),ni=Symbol.for(`yaml.node.type`),ri=e=>!!e&&typeof e==`object`&&e[ni]===Xr,ii=e=>!!e&&typeof e==`object`&&e[ni]===Zr,ai=e=>!!e&&typeof e==`object`&&e[ni]===Qr,oi=e=>!!e&&typeof e==`object`&&e[ni]===$r,si=e=>!!e&&typeof e==`object`&&e[ni]===ei,ci=e=>!!e&&typeof e==`object`&&e[ni]===ti,li=e=>(si(e)||Jr(e))&&!!e.anchor}));function di(e,t){let n=hi(t);ii(e)?fi(null,e.contents,n,Object.freeze([e]))===bi&&(e.contents=null):fi(null,e,n,Object.freeze([]))}function fi(e,t,n,r){let i=gi(e,t,n,r);if(Yr(i)||oi(i))return _i(e,r,i),fi(e,i,n,r);if(typeof i!=`symbol`){if(Jr(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=fi(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===vi)return vi;else i===bi&&(t.items.splice(e,1),--e)}}else if(oi(t)){r=Object.freeze(r.concat(t));let e=fi(`key`,t.key,n,r);if(e===vi)return vi;e===bi&&(t.key=null);let i=fi(`value`,t.value,n,r);if(i===vi)return vi;i===bi&&(t.value=null)}}return i}async function pi(e,t){let n=hi(t);ii(e)?await mi(null,e.contents,n,Object.freeze([e]))===bi&&(e.contents=null):await mi(null,e,n,Object.freeze([]))}async function mi(e,t,n,r){let i=await gi(e,t,n,r);if(Yr(i)||oi(i))return _i(e,r,i),mi(e,i,n,r);if(typeof i!=`symbol`){if(Jr(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=await mi(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===vi)return vi;else i===bi&&(t.items.splice(e,1),--e)}}else if(oi(t)){r=Object.freeze(r.concat(t));let e=await mi(`key`,t.key,n,r);if(e===vi)return vi;e===bi&&(t.key=null);let i=await mi(`value`,t.value,n,r);if(i===vi)return vi;i===bi&&(t.value=null)}}return i}function hi(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function gi(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(ai(t))return n.Map?.(e,t,r);if(ci(t))return n.Seq?.(e,t,r);if(oi(t))return n.Pair?.(e,t,r);if(si(t))return n.Scalar?.(e,t,r);if(ri(t))return n.Alias?.(e,t,r)}function _i(e,t,n){let r=t[t.length-1];if(Jr(r))r.items[e]=n;else if(oi(r))e===`key`?r.key=n:r.value=n;else if(ii(r))r.contents=n;else{let e=ri(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var vi,yi,bi,xi=R((()=>{ui(),vi=Symbol(`break visit`),yi=Symbol(`skip children`),bi=Symbol(`remove node`),di.BREAK=vi,di.SKIP=yi,di.REMOVE=bi,pi.BREAK=vi,pi.SKIP=yi,pi.REMOVE=bi})),Si,Ci,wi,Ti=R((()=>{ui(),xi(),Si={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},Ci=e=>e.replace(/[!,[\]{}]/g,e=>Si[e]),wi=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Ci(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],n=Object.entries(this.tags),r;if(e&&n.length>0&&Yr(e.contents)){let t={};di(e.contents,(e,n)=>{Yr(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(let[i,a]of n)(i!==`!!`||a!==`tag:yaml.org,2002:`)&&(!e||r.some(e=>e.startsWith(a)))&&t.push(`%TAG ${i} ${a}`);return t.join(`
51
- `)}},wi.defaultYaml={explicit:!1,version:`1.2`},wi.defaultTags={"!!":`tag:yaml.org,2002:`}}));function Ei(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function Di(e){let t=new Set;return di(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function Oi(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function ki(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=Di(e);let a=Oi(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(si(t.node)||Jr(t.node)))t.node.anchor=t.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:r}}var Ai=R((()=>{ui(),xi()}));function ji(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=ji(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=ji(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=ji(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=ji(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}var Mi=R((()=>{}));function Ni(e,t,n){if(Array.isArray(e))return e.map((e,t)=>Ni(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!li(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var Pi=R((()=>{ui()})),Fi,Ii=R((()=>{Mi(),ui(),Pi(),Fi=class{constructor(e){Object.defineProperty(this,ni,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!ii(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=Ni(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?ji(i,{"":o},``,o):o}}}));function Li(e,t,n){if(ri(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Jr(t)){let r=0;for(let i of t.items){let t=Li(e,i,n);t>r&&(r=t)}return r}if(oi(t)){let r=Li(e,t.key,n),i=Li(e,t.value,n);return Math.max(r,i)}return 1}var Ri,zi=R((()=>{Ai(),xi(),ui(),Ii(),Pi(),Ri=class extends Fi{constructor(e){super(Xr),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],di(e,{Node:(e,t)=>{(ri(t)||li(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}return r}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,a=this.resolve(r,t);if(!a){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let o=n.get(a);if(o||=(Ni(a,null,t),n.get(a)),o?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(o.count+=1,o.aliasCount===0&&(o.aliasCount=Li(r,a,n)),o.count*o.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return o.res}toString(e,t,n){let r=`*${this.source}`;if(e){if(Ei(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}}})),Bi,B,Vi=R((()=>{ui(),Ii(),Pi(),Bi=e=>!e||typeof e!=`function`&&typeof e!=`object`,B=class extends Fi{constructor(e){super(ei),this.value=e}toJSON(e,t){return t?.keep?this.value:Ni(this.value,e,t)}toString(){return String(this.value)}},B.BLOCK_FOLDED=`BLOCK_FOLDED`,B.BLOCK_LITERAL=`BLOCK_LITERAL`,B.PLAIN=`PLAIN`,B.QUOTE_DOUBLE=`QUOTE_DOUBLE`,B.QUOTE_SINGLE=`QUOTE_SINGLE`}));function Hi(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function Ui(e,t,n){if(ii(e)&&(e=e.contents),Yr(e))return e;if(oi(e)){let t=n.schema[Qr].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new Ri(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=Wi+t.slice(2));let l=Hi(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new B(e);return c&&(c.node=t),t}l=e instanceof Map?o[Qr]:Symbol.iterator in Object(e)?o[ti]:o[Qr]}a&&(a(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from==`function`?l.nodeClass.from(n.schema,e,n):new B(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}var Wi,Gi=R((()=>{zi(),ui(),Vi(),Wi=`tag:yaml.org,2002:`}));function Ki(e,t,n){let r=n;for(let e=t.length-1;e>=0;--e){let n=t[e];if(typeof n==`number`&&Number.isInteger(n)&&n>=0){let e=[];e[n]=r,r=e}else r=new Map([[n,r]])}return Ui(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var qi,Ji,Yi=R((()=>{Gi(),ui(),Ii(),qi=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,Ji=class extends Fi{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>Yr(t)||oi(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(qi(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(Jr(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Ki(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let r=this.get(t,!0);if(Jr(r))return r.deleteIn(n);throw Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&si(i)?i.value:i:Jr(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!oi(t))return!1;let n=t.value;return n==null||e&&si(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let r=this.get(t,!0);return Jr(r)?r.hasIn(n):!1}setIn(e,t){let[n,...r]=e;if(r.length===0)this.set(n,t);else{let e=this.get(n,!0);if(Jr(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,Ki(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}}));function Xi(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Zi,Qi,$i=R((()=>{Zi=e=>e.replace(/^(?!$)(?: $)?/gm,`#`),Qi=(e,t,n)=>e.endsWith(`
52
- `)?Xi(n,t):n.includes(`
48
+ }`}var On=z((()=>{mn()}));function kn(e,t){if(t){let n=e?.cause;for(;n;){if(t(n))return n;n=n?.cause}return}let n=e;for(;n?.cause;)n=n.cause;return n}var An,B,jn,Mn,Nn=z((()=>{An=class extends Error{name=`Incur.BaseError`;shortMessage;details;constructor(e,t={}){let n=t.cause instanceof Error?t.cause.message:void 0,r=n?`${e}\n\nDetails: ${n}`:e;super(r,t.cause?{cause:t.cause}:void 0),this.shortMessage=e,this.details=n}walk(e){return kn(this,e)}},B=class extends An{name=`Incur.IncurError`;code;hint;retryable;exitCode;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.code=e.code,this.hint=e.hint,this.retryable=e.retryable??!1,this.exitCode=e.exitCode}},jn=class extends An{name=`Incur.ValidationError`;fieldErrors;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.fieldErrors=e.fieldErrors??[]}},Mn=class extends An{name=`Incur.ParseError`;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0)}}}));function Pn(e){let t=[],n=new Headers,r=new URLSearchParams,i,a,o=0;for(;o<e.length;){let n=e[o];if(n.startsWith(`--`)){let t=n.indexOf(`=`);if(t!==-1){let e=n.slice(2,t),i=n.slice(t+1);zn.has(e)?s(e,i):r.set(e,i),o++}else{let t=n.slice(2),i=e[o+1];if(i===void 0)throw Error(`Missing value for --${t}`);zn.has(t)?s(t,i):r.set(t,i),o+=2}}else if(n.startsWith(`-`)&&n.length===2){let t=n[1],r=Bn[t];if(r){let n=e[o+1];if(n===void 0)throw Error(`Missing value for -${t}`);s(r,n),o+=2}else o++}else t.push(n),o++}function s(e,t){if(e===`method`)i=t.toUpperCase();else if(e===`body`||e===`data`)a=t;else if(e===`header`){let e=t.indexOf(`:`);if(e!==-1){let r=t.slice(0,e).trim(),i=t.slice(e+1).trim();n.set(r,i)}}}return{path:t.length>0?`/${t.join(`/`)}`:`/`,method:i??(a===void 0?`GET`:`POST`),headers:n,body:a,query:r}}function Fn(e){let t=new URL(e.path,`http://localhost`);e.query.forEach((e,n)=>t.searchParams.set(n,e));let n={method:e.method,headers:e.headers};return e.body!==void 0&&(n.body=e.body,e.headers.has(`content-type`)||e.headers.set(`content-type`,`application/json`)),new Request(t.toString(),n)}function In(e){return e.body!==null&&e.headers.get(`content-type`)===`application/x-ndjson`}async function*Ln(e){let t=e.body.getReader(),n=new TextDecoder,r=``;for(;;){let{value:e,done:i}=await t.read();if(i)break;r+=n.decode(e,{stream:!0});let a;for(;(a=r.indexOf(`
49
+ `))!==-1;){let e=r.slice(0,a).trim();if(r=r.slice(a+1),e.length!==0)try{yield JSON.parse(e)}catch{yield e}}}let i=r.trim();if(i.length>0)try{yield JSON.parse(i)}catch{yield i}}async function Rn(e){let t=await e.text(),n;try{n=JSON.parse(t)}catch{n=t}return{ok:e.ok,status:e.status,data:n,headers:e.headers}}var zn,Bn,Vn=z((()=>{zn=new Set([`method`,`body`,`data`,`header`]),Bn={X:`method`,d:`data`,H:`header`}}));function Hn(e){let t=[],n=[],r=``,i=0;for(let t=0;t<e.length;t++){let a=e[t];a===`[`?i++:a===`]`&&i--,a===`,`&&i===0?(n.push(r),r=``):r+=a}r&&n.push(r);for(let e of n){let n=[],r=e;for(;r.length>0;){let e=r.indexOf(`[`);if(e===-1){for(let e of r.split(`.`))e&&n.push({key:e});break}let t=r.slice(0,e);for(let e of t.split(`.`))e&&n.push({key:e});let i=r.indexOf(`]`,e),[a,o]=r.slice(e+1,i).split(`,`);n.push({start:Number(a),end:Number(o)}),r=r.slice(i+1),r.startsWith(`.`)&&(r=r.slice(1))}t.push(n)}return t}function Un(e,t){if(t.length===0)return e;if(t.length===1&&t[0].length===1&&`key`in t[0][0]){let n=t[0][0].key;if(Array.isArray(e))return e.map(e=>Un(e,t));if(typeof e==`object`&&e){let t=e[n];return typeof t!=`object`||!t?t:{[n]:t}}return}if(Array.isArray(e))return e.map(e=>Un(e,t));let n={};for(let r of t)Wn(n,e,r,0);return n}function Wn(e,t,n,r){if(r>=n.length||typeof t!=`object`||!t)return;let i=n[r];if(`key`in i){let a=t[i.key];if(a===void 0)return;if(r+1>=n.length){e[i.key]=a;return}let o=n[r+1];if(`start`in o){if(!Array.isArray(a))return;let t=a.slice(o.start,o.end);if(r+2>=n.length){e[i.key]=t;return}e[i.key]=t.map(e=>{let t={};return Wn(t,e,n,r+2),t});return}if(typeof a!=`object`||!a)return;(!e[i.key]||typeof e[i.key]!=`object`)&&(e[i.key]={}),Wn(e[i.key],a,n,r+1);return}}var Gn=z((()=>{}));function Kn(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`).replace(/[\u0000-\u001F]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function qn(e){return e===`true`||e===`false`||e===`null`}function Jn(e,t,n){if(t===`__proto__`){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0});return}e[t]=n}function Yn(e){if(e===null)return null;if(typeof e==`object`&&e&&`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();if(t!==e)return Yn(t)}if(typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e==`bigint`)return e>=-(2**53-1)&&e<=2**53-1?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(Yn);if(e instanceof Set)return Array.from(e).map(Yn);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),Yn(t)]));if(er(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&Jn(t,n,Yn(e[n]));return t}return null}function Xn(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function Zn(e){return Array.isArray(e)}function Qn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $n(e){return Object.keys(e).length===0}function er(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function tr(e){return e.length===0||e.every(e=>Xn(e))}function nr(e){return e.length===0||e.every(e=>Zn(e))}function rr(e){return e.length===0||e.every(e=>Qn(e))}function ir(e){return/^[A-Z_][\w.]*$/i.test(e)}function ar(e){return/^[A-Z_]\w*$/i.test(e)}function or(e,t=Br){return!(!e||e!==e.trim()||qn(e)||sr(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith(`-`))}function sr(e){return Vr.test(e)||Hr.test(e)}function cr(e,t,n,r,i,a,o){if(r.keyFolding!==`safe`||!Qn(t))return;let{segments:s,tail:c,leafValue:l}=lr(e,t,o??r.flattenDepth);if(s.length<2||!s.every(e=>ar(e)))return;let u=ur(s),d=a?`${a}.${u}`:u;if(!n.includes(u)&&!(i&&i.has(d)))return{foldedKey:u,remainder:c,leafValue:l,segmentCount:s.length}}function lr(e,t,n){let r=[e],i=t;for(;r.length<n&&Qn(i);){let e=Object.keys(i);if(e.length!==1)break;let t=e[0],n=i[t];r.push(t),i=n}return!Qn(i)||$n(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function ur(e){return e.join(`.`)}function dr(e,t){return e===null?Rr:typeof e==`boolean`||typeof e==`number`?String(e):fr(e,t)}function fr(e,t=Br){return or(e,t)?e:`"${Kn(e)}"`}function pr(e){return ir(e)?e:`"${Kn(e)}"`}function mr(e,t=Br){return e.map(e=>dr(e,t)).join(t)}function hr(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;if(n!=null&&(a+=pr(n)),a+=`[${e}${i===Br?``:i}]`,r){let e=r.map(e=>pr(e));a+=`{${e.join(i)}}`}return a+=`:`,a}function*gr(e,t,n){if(Xn(e)){let n=dr(e,t.delimiter);n!==``&&(yield n);return}Zn(e)?yield*yr(void 0,e,n,t):Qn(e)&&(yield*_r(e,n,t))}function*_r(e,t,n,r,i,a){let o=Object.keys(e);t===0&&!r&&(r=new Set(o.filter(e=>e.includes(`.`))));let s=a??n.flattenDepth;for(let[a,c]of Object.entries(e))yield*vr(a,c,t,n,o,r,i,s)}function*vr(e,t,n,r,i,a,o,s){let c=o?`${o}.${e}`:e,l=s??r.flattenDepth;if(r.keyFolding===`safe`&&i){let s=cr(e,t,i,r,a,o,l);if(s){let{foldedKey:e,remainder:t,leafValue:i,segmentCount:c}=s,u=pr(e);if(t===void 0){if(Xn(i)){yield kr(n,`${u}: ${dr(i,r.delimiter)}`,r.indent);return}if(Zn(i)){yield*yr(e,i,n,r);return}if(Qn(i)&&$n(i)){yield kr(n,`${u}:`,r.indent);return}}if(Qn(t)){yield kr(n,`${u}:`,r.indent);let i=l-c,s=o?`${o}.${e}`:e;yield*_r(t,n+1,r,a,s,i);return}}}let u=pr(e);Xn(t)?yield kr(n,`${u}: ${dr(t,r.delimiter)}`,r.indent):Zn(t)?yield*yr(e,t,n,r):Qn(t)&&(yield kr(n,`${u}:`,r.indent),$n(t)||(yield*_r(t,n+1,r,a,c,l)))}function*yr(e,t,n,r){if(t.length===0){yield kr(n,e==null?`[]`:`${pr(e)}: []`,r.indent);return}if(tr(t)){yield kr(n,xr(t,r.delimiter,e),r.indent);return}if(nr(t)&&t.every(e=>tr(e))){yield*br(e,t,n,r);return}if(rr(t)){let i=Cr(t);i?yield*Sr(e,t,i,n,r):yield*Er(e,t,n,r);return}yield*Er(e,t,n,r)}function*br(e,t,n,r){yield kr(n,hr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)if(tr(e)){let t=xr(e,r.delimiter);yield Ar(n+1,t,r.indent)}}function xr(e,t,n){let r=hr(e.length,{key:n,delimiter:t}),i=mr(e,t);return e.length===0?r:`${r} ${i}`}function*Sr(e,t,n,r,i){yield kr(r,hr(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*Tr(t,n,r+1,i)}function Cr(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&wr(e,n))return n}function wr(e,t){for(let n of e){if(Object.keys(n).length!==t.length)return!1;for(let e of t)if(!Object.hasOwn(n,e)||!Xn(n[e]))return!1}return!0}function*Tr(e,t,n,r){for(let i of e)yield kr(n,mr(t.map(e=>i[e]),r.delimiter),r.indent)}function*Er(e,t,n,r){yield kr(n,hr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)yield*Or(e,n+1,r)}function*Dr(e,t,n){if($n(e)){yield kr(t,`-`,n.indent);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(Zn(a)&&rr(a)){let e=Cr(a);if(e){yield Ar(t,hr(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indent),yield*Tr(a,e,t+2,n),o.length>0&&(yield*_r(Object.fromEntries(o),t+1,n));return}}let s=pr(i);if(Xn(a))yield Ar(t,`${s}: ${dr(a,n.delimiter)}`,n.indent);else if(Zn(a)){if(a.length===0)yield Ar(t,`${s}: []`,n.indent);else if(tr(a))yield Ar(t,`${s}${xr(a,n.delimiter)}`,n.indent);else{yield Ar(t,`${s}${hr(a.length,{delimiter:n.delimiter})}`,n.indent);for(let e of a)yield*Or(e,t+2,n)}}else Qn(a)&&(yield Ar(t,`${s}:`,n.indent),$n(a)||(yield*_r(a,t+2,n)));o.length>0&&(yield*_r(Object.fromEntries(o),t+1,n))}function*Or(e,t,n){if(Xn(e))yield Ar(t,dr(e,n.delimiter),n.indent);else if(Zn(e)){if(tr(e))yield Ar(t,xr(e,n.delimiter),n.indent);else{yield Ar(t,hr(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*Or(r,t+1,n)}}else Qn(e)&&(yield*Dr(e,t,n))}function kr(e,t,n){return` `.repeat(n*e)+t}function Ar(e,t,n){return kr(e,`- `+t,n)}function jr(e,t){let n=t(``,e,[]);return Mr(n===void 0?e:Yn(n),t,[])}function Mr(e,t,n){return Qn(e)?Nr(e,t,n):Zn(e)?Pr(e,t,n):e}function Nr(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=[...n,i],o=t(i,a,e);o!==void 0&&Jn(r,i,Mr(Yn(o),t,e))}return r}function Pr(e,t,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i],o=[...n,i],s=t(String(i),a,o);if(s===void 0)continue;let c=Yn(s);r.push(Mr(c,t,o))}return r}function Fr(e,t){return Array.from(Ir(e,t)).join(`
50
+ `)}function Ir(e,t){let n=Yn(e),r=Lr(t);return gr(r.replacer?jr(n,r.replacer):n,r,0)}function Lr(e){return{indent:e?.indent??2,delimiter:e?.delimiter??Br,keyFolding:e?.keyFolding??`off`,flattenDepth:e?.flattenDepth??1/0,replacer:e?.replacer}}var Rr,zr,Br,Vr,Hr,Ur=z((()=>{Rr=`null`,zr={comma:`,`,tab:` `,pipe:`|`},Br=zr.comma,Vr=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,Hr=/^0\d+$/}));function Wr(e,t){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t,t)}function Gr(e){return JSON.parse(Wr(e))}var Kr=z((()=>{}));function qr(e){if(e&&typeof e==`object`)switch(e[ti]){case Zr:case ei:return!0}return!1}function Jr(e){if(e&&typeof e==`object`)switch(e[ti]){case Yr:case Zr:case $r:case ei:return!0}return!1}var Yr,Xr,Zr,Qr,$r,ei,ti,ni,ri,ii,ai,oi,si,ci,li=z((()=>{Yr=Symbol.for(`yaml.alias`),Xr=Symbol.for(`yaml.document`),Zr=Symbol.for(`yaml.map`),Qr=Symbol.for(`yaml.pair`),$r=Symbol.for(`yaml.scalar`),ei=Symbol.for(`yaml.seq`),ti=Symbol.for(`yaml.node.type`),ni=e=>!!e&&typeof e==`object`&&e[ti]===Yr,ri=e=>!!e&&typeof e==`object`&&e[ti]===Xr,ii=e=>!!e&&typeof e==`object`&&e[ti]===Zr,ai=e=>!!e&&typeof e==`object`&&e[ti]===Qr,oi=e=>!!e&&typeof e==`object`&&e[ti]===$r,si=e=>!!e&&typeof e==`object`&&e[ti]===ei,ci=e=>(oi(e)||qr(e))&&!!e.anchor}));function ui(e,t){let n=mi(t);ri(e)?di(null,e.contents,n,Object.freeze([e]))===yi&&(e.contents=null):di(null,e,n,Object.freeze([]))}function di(e,t,n,r){let i=hi(e,t,n,r);if(Jr(i)||ai(i))return gi(e,r,i),di(e,i,n,r);if(typeof i!=`symbol`){if(qr(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=di(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===_i)return _i;else i===yi&&(t.items.splice(e,1),--e)}}else if(ai(t)){r=Object.freeze(r.concat(t));let e=di(`key`,t.key,n,r);if(e===_i)return _i;e===yi&&(t.key=null);let i=di(`value`,t.value,n,r);if(i===_i)return _i;i===yi&&(t.value=null)}}return i}async function fi(e,t){let n=mi(t);ri(e)?await pi(null,e.contents,n,Object.freeze([e]))===yi&&(e.contents=null):await pi(null,e,n,Object.freeze([]))}async function pi(e,t,n,r){let i=await hi(e,t,n,r);if(Jr(i)||ai(i))return gi(e,r,i),pi(e,i,n,r);if(typeof i!=`symbol`){if(qr(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=await pi(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===_i)return _i;else i===yi&&(t.items.splice(e,1),--e)}}else if(ai(t)){r=Object.freeze(r.concat(t));let e=await pi(`key`,t.key,n,r);if(e===_i)return _i;e===yi&&(t.key=null);let i=await pi(`value`,t.value,n,r);if(i===_i)return _i;i===yi&&(t.value=null)}}return i}function mi(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function hi(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(ii(t))return n.Map?.(e,t,r);if(si(t))return n.Seq?.(e,t,r);if(ai(t))return n.Pair?.(e,t,r);if(oi(t))return n.Scalar?.(e,t,r);if(ni(t))return n.Alias?.(e,t,r)}function gi(e,t,n){let r=t[t.length-1];if(qr(r))r.items[e]=n;else if(ai(r))e===`key`?r.key=n:r.value=n;else if(ri(r))r.contents=n;else{let e=ni(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var _i,vi,yi,bi=z((()=>{li(),_i=Symbol(`break visit`),vi=Symbol(`skip children`),yi=Symbol(`remove node`),ui.BREAK=_i,ui.SKIP=vi,ui.REMOVE=yi,fi.BREAK=_i,fi.SKIP=vi,fi.REMOVE=yi})),xi,Si,Ci,wi=z((()=>{li(),bi(),xi={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},Si=e=>e.replace(/[!,[\]{}]/g,e=>xi[e]),Ci=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Si(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],n=Object.entries(this.tags),r;if(e&&n.length>0&&Jr(e.contents)){let t={};ui(e.contents,(e,n)=>{Jr(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(let[i,a]of n)(i!==`!!`||a!==`tag:yaml.org,2002:`)&&(!e||r.some(e=>e.startsWith(a)))&&t.push(`%TAG ${i} ${a}`);return t.join(`
51
+ `)}},Ci.defaultYaml={explicit:!1,version:`1.2`},Ci.defaultTags={"!!":`tag:yaml.org,2002:`}}));function Ti(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function Ei(e){let t=new Set;return ui(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function Di(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function Oi(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=Ei(e);let a=Di(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(oi(t.node)||qr(t.node)))t.node.anchor=t.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:r}}var ki=z((()=>{li(),bi()}));function Ai(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=Ai(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=Ai(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=Ai(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=Ai(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}var ji=z((()=>{}));function Mi(e,t,n){if(Array.isArray(e))return e.map((e,t)=>Mi(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!ci(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var Ni=z((()=>{li()})),Pi,Fi=z((()=>{ji(),li(),Ni(),Pi=class{constructor(e){Object.defineProperty(this,ti,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!ri(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=Mi(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?Ai(i,{"":o},``,o):o}}}));function Ii(e,t,n){if(ni(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(qr(t)){let r=0;for(let i of t.items){let t=Ii(e,i,n);t>r&&(r=t)}return r}if(ai(t)){let r=Ii(e,t.key,n),i=Ii(e,t.value,n);return Math.max(r,i)}return 1}var Li,Ri=z((()=>{ki(),bi(),li(),Fi(),Ni(),Li=class extends Pi{constructor(e){super(Yr),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],ui(e,{Node:(e,t)=>{(ni(t)||ci(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}return r}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,a=this.resolve(r,t);if(!a){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let o=n.get(a);if(o||=(Mi(a,null,t),n.get(a)),o?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(o.count+=1,o.aliasCount===0&&(o.aliasCount=Ii(r,a,n)),o.count*o.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return o.res}toString(e,t,n){let r=`*${this.source}`;if(e){if(Ti(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}}})),zi,V,Bi=z((()=>{li(),Fi(),Ni(),zi=e=>!e||typeof e!=`function`&&typeof e!=`object`,V=class extends Pi{constructor(e){super($r),this.value=e}toJSON(e,t){return t?.keep?this.value:Mi(this.value,e,t)}toString(){return String(this.value)}},V.BLOCK_FOLDED=`BLOCK_FOLDED`,V.BLOCK_LITERAL=`BLOCK_LITERAL`,V.PLAIN=`PLAIN`,V.QUOTE_DOUBLE=`QUOTE_DOUBLE`,V.QUOTE_SINGLE=`QUOTE_SINGLE`}));function Vi(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function Hi(e,t,n){if(ri(e)&&(e=e.contents),Jr(e))return e;if(ai(e)){let t=n.schema[Zr].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new Li(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=Ui+t.slice(2));let l=Vi(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new V(e);return c&&(c.node=t),t}l=e instanceof Map?o[Zr]:Symbol.iterator in Object(e)?o[ei]:o[Zr]}a&&(a(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from==`function`?l.nodeClass.from(n.schema,e,n):new V(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}var Ui,Wi=z((()=>{Ri(),li(),Bi(),Ui=`tag:yaml.org,2002:`}));function Gi(e,t,n){let r=n;for(let e=t.length-1;e>=0;--e){let n=t[e];if(typeof n==`number`&&Number.isInteger(n)&&n>=0){let e=[];e[n]=r,r=e}else r=new Map([[n,r]])}return Hi(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var Ki,qi,Ji=z((()=>{Wi(),li(),Fi(),Ki=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,qi=class extends Pi{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>Jr(t)||ai(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Ki(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(qr(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Gi(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let r=this.get(t,!0);if(qr(r))return r.deleteIn(n);throw Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&oi(i)?i.value:i:qr(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ai(t))return!1;let n=t.value;return n==null||e&&oi(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let r=this.get(t,!0);return qr(r)?r.hasIn(n):!1}setIn(e,t){let[n,...r]=e;if(r.length===0)this.set(n,t);else{let e=this.get(n,!0);if(qr(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,Gi(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}}));function Yi(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Xi,Zi,Qi=z((()=>{Xi=e=>e.replace(/^(?!$)(?: $)?/gm,`#`),Zi=(e,t,n)=>e.endsWith(`
52
+ `)?Yi(n,t):n.includes(`
53
53
  `)?`
54
- `+Xi(n,t):(e.endsWith(` `)?``:` `)+n}));function ea(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof r==`number`&&(r>i-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=ta(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
55
- `)n===`block`&&(h=ta(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
54
+ `+Yi(n,t):(e.endsWith(` `)?``:` `)+n}));function $i(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof r==`number`&&(r>i-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=ea(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
55
+ `)n===`block`&&(h=ea(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
56
56
  `&&p!==` `){let t=e[h+1];t&&t!==` `&&t!==`
57
- `&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r<l.length;++r){let i=l[r],a=l[r+1]||e.length;i===0?v=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(v+=`${e[i]}\\`),v+=`\n${t}${e.slice(i+1,a)}`)}return v}function ta(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
58
- `);r=t,i=t+1,a=e[i]}return r}var na,ra,ia,aa=R((()=>{na=`flow`,ra=`block`,ia=`quoted`}));function oa(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
59
- `){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function sa(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(ma(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length<i)e+=1;else{for(o+=n.slice(s,e)+`
57
+ `&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r<l.length;++r){let i=l[r],a=l[r+1]||e.length;i===0?v=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(v+=`${e[i]}\\`),v+=`\n${t}${e.slice(i+1,a)}`)}return v}function ea(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
58
+ `);r=t,i=t+1,a=e[i]}return r}var ta,na,ra,ia=z((()=>{ta=`flow`,na=`block`,ra=`quoted`}));function aa(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
59
+ `){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function oa(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(pa(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length<i)e+=1;else{for(o+=n.slice(s,e)+`
60
60
 
61
61
  `;n[e+2]===`\\`&&n[e+3]===`n`&&n[e+4]!==`"`;)o+=`
62
- `,e+=2;o+=a,n[e+2]===` `&&(o+=`\\`),e+=1,s=e+1}break;default:e+=1}return o=s?o+n.slice(s):n,r?o:ea(o,a,ia,pa(t,!1))}function ca(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
63
- `)||/[ \t]\n|\n[ \t]/.test(e))return sa(e,t);let n=t.indent||(ma(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:ea(r,n,na,pa(t,!1))}function la(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=sa;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?ca:i&&!t?sa:n?ca:sa}return r(e,t)}function ua({comment:e,type:t,value:n},r,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return la(n,r);let l=r.indent||(r.forceBlockIndent||ma(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===B.BLOCK_FOLDED?!1:t===B.BLOCK_LITERAL||!oa(n,c,l.length);if(!n)return u?`|
62
+ `,e+=2;o+=a,n[e+2]===` `&&(o+=`\\`),e+=1,s=e+1}break;default:e+=1}return o=s?o+n.slice(s):n,r?o:$i(o,a,ra,fa(t,!1))}function sa(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
63
+ `)||/[ \t]\n|\n[ \t]/.test(e))return oa(e,t);let n=t.indent||(pa(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:$i(r,n,ta,fa(t,!1))}function ca(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=oa;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?sa:i&&!t?oa:n?sa:oa}return r(e,t)}function la({comment:e,type:t,value:n},r,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return ca(n,r);let l=r.indent||(r.forceBlockIndent||pa(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===V.BLOCK_FOLDED?!1:t===V.BLOCK_LITERAL||!aa(n,c,l.length);if(!n)return u?`|
64
64
  `:`>
65
65
  `;let d,f;for(f=n.length;f>0;--f){let e=n[f-1];if(e!==`
66
66
  `&&e!==` `&&e!==` `)break}let p=n.substring(f),m=p.indexOf(`
67
67
  `);m===-1?d=`-`:n===p||m!==p.length-1?(d=`+`,a&&a()):d=``,p&&=(n=n.slice(0,-p.length),p[p.length-1]===`
68
- `&&(p=p.slice(0,-1)),p.replace(ha,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
68
+ `&&(p=p.slice(0,-1)),p.replace(ma,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
69
69
  `)_=g;else break}let v=n.substring(0,_<g?_+1:g);v&&=(n=n.substring(v.length),v.replace(/\n+/g,`$&${l}`));let y=(h?l?`2`:`1`:``)+d;if(e&&(y+=` `+s(e.replace(/ ?[\r\n]+/g,` `)),i&&i()),!u){let e=n.replace(/\n+/g,`
70
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=pa(r,!0);o!==`folded`&&t!==B.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=ea(`${v}${e}${p}`,l,ra,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function da(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
71
- `)||u&&/[[\]{},]/.test(a))return la(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
72
- `)?la(a,t):ua(e,t,n,r);if(!s&&!u&&i!==B.PLAIN&&a.includes(`
73
- `))return ua(e,t,n,r);if(ma(a)){if(c===``)return t.forceBlockIndent=!0,ua(e,t,n,r);if(s&&c===l)return la(a,t)}let d=a.replace(/\n+/g,`$&\n${c}`);if(o){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return la(a,t)}return s?d:ea(d,c,na,pa(t,!1))}function fa(e,t,n,r){let{implicitKey:i,inFlow:a}=t,o=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==B.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=B.QUOTE_DOUBLE);let c=e=>{switch(e){case B.BLOCK_FOLDED:case B.BLOCK_LITERAL:return i||a?la(o.value,t):ua(o,t,n,r);case B.QUOTE_DOUBLE:return sa(o.value,t);case B.QUOTE_SINGLE:return ca(o.value,t);case B.PLAIN:return da(o,t,n,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}var pa,ma,ha,ga=R((()=>{Vi(),aa(),pa=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ma=e=>/^(%|---|\.\.\.)/m.test(e);try{ha=RegExp(`(^|(?<!
70
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=fa(r,!0);o!==`folded`&&t!==V.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=$i(`${v}${e}${p}`,l,na,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function ua(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
71
+ `)||u&&/[[\]{},]/.test(a))return ca(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
72
+ `)?ca(a,t):la(e,t,n,r);if(!s&&!u&&i!==V.PLAIN&&a.includes(`
73
+ `))return la(e,t,n,r);if(pa(a)){if(c===``)return t.forceBlockIndent=!0,la(e,t,n,r);if(s&&c===l)return ca(a,t)}let d=a.replace(/\n+/g,`$&\n${c}`);if(o){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return ca(a,t)}return s?d:$i(d,c,ta,fa(t,!1))}function da(e,t,n,r){let{implicitKey:i,inFlow:a}=t,o=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==V.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=V.QUOTE_DOUBLE);let c=e=>{switch(e){case V.BLOCK_FOLDED:case V.BLOCK_LITERAL:return i||a?ca(o.value,t):la(o,t,n,r);case V.QUOTE_DOUBLE:return oa(o.value,t);case V.QUOTE_SINGLE:return sa(o.value,t);case V.PLAIN:return ua(o,t,n,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}var fa,pa,ma,ha=z((()=>{Bi(),ia(),fa=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),pa=e=>/^(%|---|\.\.\.)/m.test(e);try{ma=RegExp(`(^|(?<!
74
74
  ))
75
75
  +(?!
76
- |$)`,`g`)}catch{ha=/\n+(?!\n|$)/g}}));function _a(e,t){let n=Object.assign({blockQuote:!0,commentString:Zi,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function va(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(si(t)){r=t.value;let i=e.filter(e=>e.identify?.(r));if(i.length>1){let e=i.filter(e=>e.test);e.length>0&&(i=e)}n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n){let e=r?.constructor?.name??(r===null?`null`:typeof r);throw Error(`Tag not resolved for ${e} value`)}return n}function ya(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(si(e)||Jr(e))&&e.anchor;a&&Ei(a)&&(n.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(` `)}function ba(e,t,n,r){if(oi(e))return e.toString(t,n,r);if(ri(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=Yr(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=va(t.doc.schema.tags,a);let o=ya(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify==`function`?i.stringify(a,t,n,r):si(a)?fa(a,t,n,r):a.toString(t,n,r);return o?si(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}var xa=R((()=>{Ai(),ui(),$i(),ga()}));function Sa({key:e,value:t},n,r,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=Yr(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(Jr(e)||!Yr(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let p=!d&&(!e||f&&t==null&&!n.inFlow||Jr(e)||(si(e)?e.type===B.BLOCK_FOLDED||e.type===B.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=ba(e,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);p=!0}if(n.inFlow){if(a||t==null)return m&&r&&r(),g===``?`?`:p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=Qi(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=Qi(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=Qi(g,n.indent,l(f))));let _,v,y;Yr(t)?(_=!!t.spaceBefore,v=t.commentBefore,y=t.comment):(_=!1,v=null,y=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&si(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&ci(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=ba(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?`
77
- `:``,v){let e=l(v);S+=`\n${Xi(e,n.indent)}`}x===``&&!n.inFlow?S===`
76
+ |$)`,`g`)}catch{ma=/\n+(?!\n|$)/g}}));function ga(e,t){let n=Object.assign({blockQuote:!0,commentString:Xi,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function _a(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(oi(t)){r=t.value;let i=e.filter(e=>e.identify?.(r));if(i.length>1){let e=i.filter(e=>e.test);e.length>0&&(i=e)}n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n){let e=r?.constructor?.name??(r===null?`null`:typeof r);throw Error(`Tag not resolved for ${e} value`)}return n}function va(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(oi(e)||qr(e))&&e.anchor;a&&Ti(a)&&(n.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(` `)}function ya(e,t,n,r){if(ai(e))return e.toString(t,n,r);if(ni(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=Jr(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=_a(t.doc.schema.tags,a);let o=va(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify==`function`?i.stringify(a,t,n,r):oi(a)?da(a,t,n,r):a.toString(t,n,r);return o?oi(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}var ba=z((()=>{ki(),li(),Qi(),ha()}));function xa({key:e,value:t},n,r,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=Jr(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(qr(e)||!Jr(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let p=!d&&(!e||f&&t==null&&!n.inFlow||qr(e)||(oi(e)?e.type===V.BLOCK_FOLDED||e.type===V.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=ya(e,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);p=!0}if(n.inFlow){if(a||t==null)return m&&r&&r(),g===``?`?`:p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=Zi(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=Zi(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=Zi(g,n.indent,l(f))));let _,v,y;Jr(t)?(_=!!t.spaceBefore,v=t.commentBefore,y=t.comment):(_=!1,v=null,y=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&oi(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&si(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=ya(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?`
77
+ `:``,v){let e=l(v);S+=`\n${Yi(e,n.indent)}`}x===``&&!n.inFlow?S===`
78
78
  `&&y&&(S=`
79
79
 
80
- `):S+=`\n${n.indent}`}else if(!p&&Jr(t)){let e=x[0],r=x.indexOf(`
80
+ `):S+=`\n${n.indent}`}else if(!p&&qr(t)){let e=x[0],r=x.indexOf(`
81
81
  `),i=r!==-1,a=n.inFlow??t.flow??t.items.length===0;if(i||!a){let t=!1;if(i&&(e===`&`||e===`!`)){let n=x.indexOf(` `);e===`&`&&n!==-1&&n<r&&x[n+1]===`!`&&(n=x.indexOf(` `,n+1)),(n===-1||r<n)&&(t=!0)}t||(S=`\n${n.indent}`)}}else(x===``||x[0]===`
82
- `)&&(S=``);return g+=S+x,n.inFlow?b&&r&&r():y&&!b?g+=Qi(g,n.indent,l(y)):h&&i&&i(),g}var Ca=R((()=>{ui(),Vi(),xa(),$i()}));function wa(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var Ta=R((()=>{}));function Ea(e,t,n){let r=Oa(e,n);if(ci(r))for(let n of r.items)Da(e,t,n);else if(Array.isArray(r))for(let n of r)Da(e,t,n);else Da(e,t,r)}function Da(e,t,n){let r=Oa(e,n);if(!ai(r))throw Error(`Merge sources must be maps or map aliases`);let i=r.toJSON(null,e,Map);for(let[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function Oa(e,t){return e&&ri(t)?t.resolve(e.doc,e):t}var ka,Aa,ja,Ma=R((()=>{ui(),Vi(),ka=`<<`,Aa={identify:e=>e===ka||typeof e==`symbol`&&e.description===ka,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new B(Symbol(ka)),{addToJSMap:Ea}),stringify:()=>ka},ja=(e,t)=>(Aa.identify(t)||si(t)&&(!t.type||t.type===B.PLAIN)&&Aa.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===Aa.tag&&e.default)}));function Na(e,t,{key:n,value:r}){if(Yr(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(ja(e,n))Ea(e,t,r);else{let i=Ni(n,``,e);if(t instanceof Map)t.set(i,Ni(r,i,e));else if(t instanceof Set)t.add(i);else{let a=Pa(n,i,e),o=Ni(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Pa(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(Yr(e)&&n?.doc){let t=_a(n.doc,{});t.anchors=new Set;for(let e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;let r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+`..."`),wa(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}var Fa=R((()=>{Ta(),Ma(),xa(),ui(),Pi()}));function Ia(e,t,n){let r=Ui(e,void 0,n),i=Ui(t,void 0,n);return new La(r,i)}var La,Ra=R((()=>{Gi(),Ca(),Fa(),ui(),La=class e{constructor(e,t=null){Object.defineProperty(this,ni,{value:$r}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return Yr(n)&&(n=n.clone(t)),Yr(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return Na(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?Sa(this,e,t,n):JSON.stringify(this)}}}));function za(e,t,n){return(t.inFlow??e.flow?Va:Ba)(e,t,n)}function Ba({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:a,type:null}),d=!1,f=[];for(let e=0;e<t.length;++e){let i=t[e],o=null;if(Yr(i))!d&&i.spaceBefore&&f.push(``),Ha(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(oi(i)){let e=Yr(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),Ha(n,f,e.commentBefore,d))}d=!1;let s=ba(i,u,()=>o=null,()=>d=!0);o&&(s+=Qi(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;e<f.length;++e){let t=f[e];p+=t?`\n${c}${t}`:`
82
+ `)&&(S=``);return g+=S+x,n.inFlow?b&&r&&r():y&&!b?g+=Zi(g,n.indent,l(y)):h&&i&&i(),g}var Sa=z((()=>{li(),Bi(),ba(),Qi()}));function Ca(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var wa=z((()=>{}));function Ta(e,t,n){let r=Da(e,n);if(si(r))for(let n of r.items)Ea(e,t,n);else if(Array.isArray(r))for(let n of r)Ea(e,t,n);else Ea(e,t,r)}function Ea(e,t,n){let r=Da(e,n);if(!ii(r))throw Error(`Merge sources must be maps or map aliases`);let i=r.toJSON(null,e,Map);for(let[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function Da(e,t){return e&&ni(t)?t.resolve(e.doc,e):t}var Oa,ka,Aa,ja=z((()=>{li(),Bi(),Oa=`<<`,ka={identify:e=>e===Oa||typeof e==`symbol`&&e.description===Oa,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new V(Symbol(Oa)),{addToJSMap:Ta}),stringify:()=>Oa},Aa=(e,t)=>(ka.identify(t)||oi(t)&&(!t.type||t.type===V.PLAIN)&&ka.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===ka.tag&&e.default)}));function Ma(e,t,{key:n,value:r}){if(Jr(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(Aa(e,n))Ta(e,t,r);else{let i=Mi(n,``,e);if(t instanceof Map)t.set(i,Mi(r,i,e));else if(t instanceof Set)t.add(i);else{let a=Na(n,i,e),o=Mi(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Na(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(Jr(e)&&n?.doc){let t=ga(n.doc,{});t.anchors=new Set;for(let e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;let r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+`..."`),Ca(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}var Pa=z((()=>{wa(),ja(),ba(),li(),Ni()}));function Fa(e,t,n){let r=Hi(e,void 0,n),i=Hi(t,void 0,n);return new Ia(r,i)}var Ia,La=z((()=>{Wi(),Sa(),Pa(),li(),Ia=class e{constructor(e,t=null){Object.defineProperty(this,ti,{value:Qr}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return Jr(n)&&(n=n.clone(t)),Jr(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return Ma(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?xa(this,e,t,n):JSON.stringify(this)}}}));function Ra(e,t,n){return(t.inFlow??e.flow?Ba:za)(e,t,n)}function za({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:a,type:null}),d=!1,f=[];for(let e=0;e<t.length;++e){let i=t[e],o=null;if(Jr(i))!d&&i.spaceBefore&&f.push(``),Va(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(ai(i)){let e=Jr(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),Va(n,f,e.commentBefore,d))}d=!1;let s=ya(i,u,()=>o=null,()=>d=!0);o&&(s+=Zi(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;e<f.length;++e){let t=f[e];p+=t?`\n${c}${t}`:`
83
83
  `}}return e?(p+=`
84
- `+Xi(l(e),c),s&&s()):d&&o&&o(),p}function Va({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let n=0;n<e.length;++n){let i=e[n],a=null;if(Yr(i))i.spaceBefore&&d.push(``),Ha(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(oi(i)){let e=Yr(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),Ha(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=Yr(i.value)?i.value:null;n?(n.comment&&(a=n.comment),n.commentBefore&&(l=!0)):i.value==null&&e?.comment&&(a=e.comment)}a&&(l=!0);let o=ba(i,c,()=>a=null);l||=d.length>u||o.includes(`
85
- `),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=Qi(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
86
- `;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function Ha({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=Xi(t(r),e);n.push(i.trimStart())}}var Ua=R((()=>{ui(),xa(),$i()}));function Wa(e,t){let n=si(t)?t.value:t;for(let r of e)if(oi(r)&&(r.key===t||r.key===n||si(r.key)&&r.key.value===n))return r}var Ga,Ka=R((()=>{Ua(),Fa(),Yi(),ui(),Ra(),Vi(),Ga=class extends Ji{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(Qr,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(Ia(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=oi(e)?e:!e||typeof e!=`object`||!(`key`in e)?new La(e,e?.value):new La(e.key,e.value);let r=Wa(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);si(r.value)&&Bi(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=Wa(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=Wa(this.items,e)?.value;return(!t&&si(n)?n.value:n)??void 0}has(e){return!!Wa(this.items,e)}set(e,t){this.add(new La(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)Na(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!oi(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),za(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}}})),qa,Ja=R((()=>{ui(),Ka(),qa={collection:`map`,default:!0,nodeClass:Ga,tag:`tag:yaml.org,2002:map`,resolve(e,t){return ai(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>Ga.from(e,t,n)}}));function Ya(e){let t=si(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var Xa,Za=R((()=>{Gi(),Ua(),Yi(),ui(),Vi(),Pi(),Xa=class extends Ji{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(ti,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Ya(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=Ya(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&si(r)?r.value:r}has(e){let t=Ya(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=Ya(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];si(r)&&Bi(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(Ni(e,String(r++),t));return n}toString(e,t,n){return e?za(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push(Ui(a,void 0,n))}}return i}}})),Qa,$a=R((()=>{ui(),Za(),Qa={collection:`seq`,default:!0,nodeClass:Xa,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return ci(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>Xa.from(e,t,n)}})),eo,to=R((()=>{ga(),eo={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),fa(e,t,n,r)}}})),no,ro=R((()=>{Vi(),no={identify:e=>e==null,createNode:()=>new B(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new B(null),stringify:({source:e},t)=>typeof e==`string`&&no.test.test(e)?e:t.options.nullStr}})),io,ao=R((()=>{Vi(),io={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new B(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&io.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}}}));function oo({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}var so=R((()=>{})),co,lo,uo,fo=R((()=>{Vi(),so(),co={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:oo},lo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():oo(e)}},uo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new B(parseFloat(e)),n=e.indexOf(`.`);return n!==-1&&e[e.length-1]===`0`&&(t.minFractionDigits=e.length-n-1),t},stringify:oo}}));function po(e,t,n){let{value:r}=e;return mo(r)&&r>=0?n+r.toString(t):oo(e)}var mo,ho,go,_o,vo,yo=R((()=>{so(),mo=e=>typeof e==`bigint`||Number.isInteger(e),ho=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n),go={identify:e=>mo(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>ho(e,2,8,n),stringify:e=>po(e,8,`0o`)},_o={identify:mo,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>ho(e,0,10,n),stringify:oo},vo={identify:e=>mo(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>ho(e,2,16,n),stringify:e=>po(e,16,`0x`)}})),bo,xo=R((()=>{Ja(),ro(),$a(),to(),ao(),fo(),yo(),bo=[qa,Qa,eo,no,io,go,_o,vo,co,lo,uo]}));function So(e){return typeof e==`bigint`||Number.isInteger(e)}var Co,wo,To,Eo=R((()=>{Vi(),Ja(),$a(),Co=({value:e})=>JSON.stringify(e),wo=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:Co},{identify:e=>e==null,createNode:()=>new B(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:Co},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:Co},{identify:So,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>So(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Co}],To=[qa,Qa].concat(wo,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),Do,Oo=R((()=>{Vi(),ga(),Do={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,t){if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return t(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:t,value:n},r,i,a){if(!n)return``;let o=n,s;if(typeof btoa==`function`){let e=``;for(let t=0;t<o.length;++t)e+=String.fromCharCode(o[t]);s=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(t??=B.BLOCK_LITERAL,t!==B.QUOTE_DOUBLE){let e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(s.length/e),i=Array(n);for(let t=0,r=0;t<n;++t,r+=e)i[t]=s.substr(r,e);s=i.join(t===B.BLOCK_LITERAL?`
87
- `:` `)}return fa({comment:e,type:t,value:s},r,i,a)}}}));function ko(e,t){if(ci(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!oi(r)){if(ai(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new La(new B(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){let t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=oi(r)?r:new La(r)}}else t(`Expected a sequence for this tag`);return e}function Ao(e,t,n){let{replacer:r}=n,i=new Xa(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(Ia(o,s,n))}return i}var jo,Mo=R((()=>{ui(),Ra(),Vi(),Za(),jo={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:ko,createNode:Ao}})),No,Po,Fo=R((()=>{ui(),Pi(),Ka(),Za(),Mo(),No=class e extends Xa{constructor(){super(),this.add=Ga.prototype.add.bind(this),this.delete=Ga.prototype.delete.bind(this),this.get=Ga.prototype.get.bind(this),this.has=Ga.prototype.has.bind(this),this.set=Ga.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(oi(e)?(r=Ni(e.key,``,t),i=Ni(e.value,r,t)):r=Ni(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=Ao(e,t,n),i=new this;return i.items=r.items,i}},No.tag=`tag:yaml.org,2002:omap`,Po={collection:`seq`,identify:e=>e instanceof Map,nodeClass:No,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=ko(e,t),r=[];for(let{key:e}of n.items)si(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new No,n)},createNode:(e,t,n)=>No.from(e,t,n)}}));function Io({value:e,source:t},n){return t&&(e?Lo:Ro).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Lo,Ro,zo=R((()=>{Vi(),Lo={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new B(!0),stringify:Io},Ro={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new B(!1),stringify:Io}})),Bo,Vo,Ho,Uo=R((()=>{Vi(),so(),Bo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:oo},Vo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():oo(e)}},Ho={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new B(parseFloat(e.replace(/_/g,``))),n=e.indexOf(`.`);if(n!==-1){let r=e.substring(n+1).replace(/_/g,``);r[r.length-1]===`0`&&(t.minFractionDigits=r.length)}return t},stringify:oo}}));function Wo(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function Go(e,t,n){let{value:r}=e;if(Ko(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return oo(e)}var Ko,qo,Jo,Yo,Xo,Zo=R((()=>{so(),Ko=e=>typeof e==`bigint`||Number.isInteger(e),qo={identify:Ko,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Wo(e,2,2,n),stringify:e=>Go(e,2,`0b`)},Jo={identify:Ko,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Wo(e,1,8,n),stringify:e=>Go(e,8,`0`)},Yo={identify:Ko,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Wo(e,0,10,n),stringify:oo},Xo={identify:Ko,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Wo(e,2,16,n),stringify:e=>Go(e,16,`0x`)}})),Qo,$o,es=R((()=>{ui(),Ra(),Ka(),Qo=class e extends Ga{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=oi(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new La(e.key,null):new La(e,null),Wa(this.items,t.key)||this.items.push(t)}get(e,t){let n=Wa(this.items,e);return!t&&oi(n)?si(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Wa(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new La(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof r==`function`&&(e=r.call(t,e,e)),i.items.push(Ia(e,null,n));return i}},Qo.tag=`tag:yaml.org,2002:set`,$o={collection:`map`,identify:e=>e instanceof Set,nodeClass:Qo,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>Qo.from(e,t,n),resolve(e,t){if(ai(e)){if(e.hasAllNullValues(!0))return Object.assign(new Qo,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}}}));function ts(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function ns(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return oo(e);let r=``;t<0&&(r=`-`,t*=n(-1));let i=n(60),a=[t%i];return t<60?a.unshift(0):(t=(t-a[0])/i,a.unshift(t%i),t>=60&&(t=(t-a[0])/i,a.unshift(t))),r+a.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var rs,is,as,os=R((()=>{so(),rs={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>ts(e,n),stringify:ns},is={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>ts(e,!1),stringify:ns},as={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(as.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,n,r,i,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+`00`).substr(1,3)):0,l=Date.UTC(n,r-1,i,a||0,o||0,s||0,c),u=t[8];if(u&&u!==`Z`){let e=ts(u,!1);Math.abs(e)<30&&(e*=60),l-=6e4*e}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``}})),ss,cs=R((()=>{Ja(),ro(),$a(),to(),Oo(),zo(),Uo(),Zo(),Ma(),Fo(),Mo(),es(),os(),ss=[qa,Qa,eo,no,Lo,Ro,qo,Jo,Yo,Xo,Bo,Vo,Ho,Do,Aa,Po,jo,$o,rs,is,as]}));function ls(e,t,n){let r=us.get(t);if(r&&!e)return n&&!r.includes(Aa)?r.concat(Aa):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(us.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(Aa)),i.reduce((e,t)=>{let n=typeof t==`string`?ds[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(ds).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}var us,ds,fs,ps=R((()=>{Ja(),ro(),$a(),to(),ao(),fo(),yo(),xo(),Eo(),Oo(),Ma(),Fo(),Mo(),cs(),es(),os(),us=new Map([[`core`,bo],[`failsafe`,[qa,Qa,eo]],[`json`,To],[`yaml11`,ss],[`yaml-1.1`,ss]]),ds={binary:Do,bool:io,float:uo,floatExp:lo,floatNaN:co,floatTime:is,int:_o,intHex:vo,intOct:go,intTime:rs,map:qa,merge:Aa,null:no,omap:Po,pairs:jo,seq:Qa,set:$o,timestamp:as},fs={"tag:yaml.org,2002:binary":Do,"tag:yaml.org,2002:merge":Aa,"tag:yaml.org,2002:omap":Po,"tag:yaml.org,2002:pairs":jo,"tag:yaml.org,2002:set":$o,"tag:yaml.org,2002:timestamp":as}})),ms,hs,gs=R((()=>{ui(),Ja(),$a(),to(),ps(),ms=(e,t)=>e.key<t.key?-1:+(e.key>t.key),hs=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?ls(e,`compat`):e?ls(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?fs:{},this.tags=ls(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,Qr,{value:qa}),Object.defineProperty(this,ei,{value:eo}),Object.defineProperty(this,ti,{value:Qa}),this.sortMapEntries=typeof a==`function`?a:a===!0?ms:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}}));function _s(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(n.push(t),r=!0):e.directives.docStart&&(r=!0)}r&&n.push(`---`);let i=_a(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(Xi(t,``))}let o=!1,s=null;if(e.contents){if(Yr(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(Xi(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=ba(e.contents,i,()=>s=null,t);s&&(c+=Qi(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(ba(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
88
- `)?(n.push(`...`),n.push(Xi(t,``))):n.push(`... ${t}`)}else n.push(`...`)}else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,``)),t&&((!o||s)&&n[n.length-1]!==``&&n.push(``),n.push(Xi(a(t),``)))}return n.join(`
84
+ `+Yi(l(e),c),s&&s()):d&&o&&o(),p}function Ba({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let n=0;n<e.length;++n){let i=e[n],a=null;if(Jr(i))i.spaceBefore&&d.push(``),Va(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(ai(i)){let e=Jr(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),Va(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=Jr(i.value)?i.value:null;n?(n.comment&&(a=n.comment),n.commentBefore&&(l=!0)):i.value==null&&e?.comment&&(a=e.comment)}a&&(l=!0);let o=ya(i,c,()=>a=null);l||=d.length>u||o.includes(`
85
+ `),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=Zi(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
86
+ `;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function Va({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=Yi(t(r),e);n.push(i.trimStart())}}var Ha=z((()=>{li(),ba(),Qi()}));function Ua(e,t){let n=oi(t)?t.value:t;for(let r of e)if(ai(r)&&(r.key===t||r.key===n||oi(r.key)&&r.key.value===n))return r}var Wa,Ga=z((()=>{Ha(),Pa(),Ji(),li(),La(),Bi(),Wa=class extends qi{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(Zr,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(Fa(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=ai(e)?e:!e||typeof e!=`object`||!(`key`in e)?new Ia(e,e?.value):new Ia(e.key,e.value);let r=Ua(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);oi(r.value)&&zi(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=Ua(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=Ua(this.items,e)?.value;return(!t&&oi(n)?n.value:n)??void 0}has(e){return!!Ua(this.items,e)}set(e,t){this.add(new Ia(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)Ma(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!ai(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ra(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}}})),Ka,qa=z((()=>{li(),Ga(),Ka={collection:`map`,default:!0,nodeClass:Wa,tag:`tag:yaml.org,2002:map`,resolve(e,t){return ii(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>Wa.from(e,t,n)}}));function Ja(e){let t=oi(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var Ya,Xa=z((()=>{Wi(),Ha(),Ji(),li(),Bi(),Ni(),Ya=class extends qi{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(ei,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Ja(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=Ja(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&oi(r)?r.value:r}has(e){let t=Ja(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=Ja(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];oi(r)&&zi(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(Mi(e,String(r++),t));return n}toString(e,t,n){return e?Ra(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push(Hi(a,void 0,n))}}return i}}})),Za,Qa=z((()=>{li(),Xa(),Za={collection:`seq`,default:!0,nodeClass:Ya,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return si(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>Ya.from(e,t,n)}})),$a,eo=z((()=>{ha(),$a={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),da(e,t,n,r)}}})),to,no=z((()=>{Bi(),to={identify:e=>e==null,createNode:()=>new V(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new V(null),stringify:({source:e},t)=>typeof e==`string`&&to.test.test(e)?e:t.options.nullStr}})),ro,io=z((()=>{Bi(),ro={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new V(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&ro.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}}}));function ao({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}var oo=z((()=>{})),so,co,lo,uo=z((()=>{Bi(),oo(),so={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:ao},co={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():ao(e)}},lo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new V(parseFloat(e)),n=e.indexOf(`.`);return n!==-1&&e[e.length-1]===`0`&&(t.minFractionDigits=e.length-n-1),t},stringify:ao}}));function fo(e,t,n){let{value:r}=e;return po(r)&&r>=0?n+r.toString(t):ao(e)}var po,mo,ho,go,_o,vo=z((()=>{oo(),po=e=>typeof e==`bigint`||Number.isInteger(e),mo=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n),ho={identify:e=>po(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>mo(e,2,8,n),stringify:e=>fo(e,8,`0o`)},go={identify:po,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>mo(e,0,10,n),stringify:ao},_o={identify:e=>po(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>mo(e,2,16,n),stringify:e=>fo(e,16,`0x`)}})),yo,bo=z((()=>{qa(),no(),Qa(),eo(),io(),uo(),vo(),yo=[Ka,Za,$a,to,ro,ho,go,_o,so,co,lo]}));function xo(e){return typeof e==`bigint`||Number.isInteger(e)}var So,Co,wo,To=z((()=>{Bi(),qa(),Qa(),So=({value:e})=>JSON.stringify(e),Co=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:So},{identify:e=>e==null,createNode:()=>new V(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:So},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:So},{identify:xo,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>xo(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:So}],wo=[Ka,Za].concat(Co,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),Eo,Do=z((()=>{Bi(),ha(),Eo={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,t){if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return t(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:t,value:n},r,i,a){if(!n)return``;let o=n,s;if(typeof btoa==`function`){let e=``;for(let t=0;t<o.length;++t)e+=String.fromCharCode(o[t]);s=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(t??=V.BLOCK_LITERAL,t!==V.QUOTE_DOUBLE){let e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(s.length/e),i=Array(n);for(let t=0,r=0;t<n;++t,r+=e)i[t]=s.substr(r,e);s=i.join(t===V.BLOCK_LITERAL?`
87
+ `:` `)}return da({comment:e,type:t,value:s},r,i,a)}}}));function Oo(e,t){if(si(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!ai(r)){if(ii(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new Ia(new V(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){let t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=ai(r)?r:new Ia(r)}}else t(`Expected a sequence for this tag`);return e}function ko(e,t,n){let{replacer:r}=n,i=new Ya(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(Fa(o,s,n))}return i}var Ao,jo=z((()=>{li(),La(),Bi(),Xa(),Ao={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:Oo,createNode:ko}})),Mo,No,Po=z((()=>{li(),Ni(),Ga(),Xa(),jo(),Mo=class e extends Ya{constructor(){super(),this.add=Wa.prototype.add.bind(this),this.delete=Wa.prototype.delete.bind(this),this.get=Wa.prototype.get.bind(this),this.has=Wa.prototype.has.bind(this),this.set=Wa.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(ai(e)?(r=Mi(e.key,``,t),i=Mi(e.value,r,t)):r=Mi(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=ko(e,t,n),i=new this;return i.items=r.items,i}},Mo.tag=`tag:yaml.org,2002:omap`,No={collection:`seq`,identify:e=>e instanceof Map,nodeClass:Mo,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=Oo(e,t),r=[];for(let{key:e}of n.items)oi(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new Mo,n)},createNode:(e,t,n)=>Mo.from(e,t,n)}}));function Fo({value:e,source:t},n){return t&&(e?Io:Lo).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Io,Lo,Ro=z((()=>{Bi(),Io={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new V(!0),stringify:Fo},Lo={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new V(!1),stringify:Fo}})),zo,Bo,Vo,Ho=z((()=>{Bi(),oo(),zo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:ao},Bo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():ao(e)}},Vo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new V(parseFloat(e.replace(/_/g,``))),n=e.indexOf(`.`);if(n!==-1){let r=e.substring(n+1).replace(/_/g,``);r[r.length-1]===`0`&&(t.minFractionDigits=r.length)}return t},stringify:ao}}));function Uo(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function Wo(e,t,n){let{value:r}=e;if(Go(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return ao(e)}var Go,Ko,qo,Jo,Yo,Xo=z((()=>{oo(),Go=e=>typeof e==`bigint`||Number.isInteger(e),Ko={identify:Go,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Uo(e,2,2,n),stringify:e=>Wo(e,2,`0b`)},qo={identify:Go,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Uo(e,1,8,n),stringify:e=>Wo(e,8,`0`)},Jo={identify:Go,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Uo(e,0,10,n),stringify:ao},Yo={identify:Go,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Uo(e,2,16,n),stringify:e=>Wo(e,16,`0x`)}})),Zo,Qo,$o=z((()=>{li(),La(),Ga(),Zo=class e extends Wa{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=ai(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new Ia(e.key,null):new Ia(e,null),Ua(this.items,t.key)||this.items.push(t)}get(e,t){let n=Ua(this.items,e);return!t&&ai(n)?oi(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Ua(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Ia(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof r==`function`&&(e=r.call(t,e,e)),i.items.push(Fa(e,null,n));return i}},Zo.tag=`tag:yaml.org,2002:set`,Qo={collection:`map`,identify:e=>e instanceof Set,nodeClass:Zo,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>Zo.from(e,t,n),resolve(e,t){if(ii(e)){if(e.hasAllNullValues(!0))return Object.assign(new Zo,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}}}));function es(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function ts(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return ao(e);let r=``;t<0&&(r=`-`,t*=n(-1));let i=n(60),a=[t%i];return t<60?a.unshift(0):(t=(t-a[0])/i,a.unshift(t%i),t>=60&&(t=(t-a[0])/i,a.unshift(t))),r+a.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var ns,rs,is,as=z((()=>{oo(),ns={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>es(e,n),stringify:ts},rs={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>es(e,!1),stringify:ts},is={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(is.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,n,r,i,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+`00`).substr(1,3)):0,l=Date.UTC(n,r-1,i,a||0,o||0,s||0,c),u=t[8];if(u&&u!==`Z`){let e=es(u,!1);Math.abs(e)<30&&(e*=60),l-=6e4*e}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``}})),os,ss=z((()=>{qa(),no(),Qa(),eo(),Do(),Ro(),Ho(),Xo(),ja(),Po(),jo(),$o(),as(),os=[Ka,Za,$a,to,Io,Lo,Ko,qo,Jo,Yo,zo,Bo,Vo,Eo,ka,No,Ao,Qo,ns,rs,is]}));function cs(e,t,n){let r=ls.get(t);if(r&&!e)return n&&!r.includes(ka)?r.concat(ka):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(ls.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(ka)),i.reduce((e,t)=>{let n=typeof t==`string`?us[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(us).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}var ls,us,ds,fs=z((()=>{qa(),no(),Qa(),eo(),io(),uo(),vo(),bo(),To(),Do(),ja(),Po(),jo(),ss(),$o(),as(),ls=new Map([[`core`,yo],[`failsafe`,[Ka,Za,$a]],[`json`,wo],[`yaml11`,os],[`yaml-1.1`,os]]),us={binary:Eo,bool:ro,float:lo,floatExp:co,floatNaN:so,floatTime:rs,int:go,intHex:_o,intOct:ho,intTime:ns,map:Ka,merge:ka,null:to,omap:No,pairs:Ao,seq:Za,set:Qo,timestamp:is},ds={"tag:yaml.org,2002:binary":Eo,"tag:yaml.org,2002:merge":ka,"tag:yaml.org,2002:omap":No,"tag:yaml.org,2002:pairs":Ao,"tag:yaml.org,2002:set":Qo,"tag:yaml.org,2002:timestamp":is}})),ps,ms,hs=z((()=>{li(),qa(),Qa(),eo(),fs(),ps=(e,t)=>e.key<t.key?-1:+(e.key>t.key),ms=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?cs(e,`compat`):e?cs(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?ds:{},this.tags=cs(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,Zr,{value:Ka}),Object.defineProperty(this,$r,{value:$a}),Object.defineProperty(this,ei,{value:Za}),this.sortMapEntries=typeof a==`function`?a:a===!0?ps:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}}));function gs(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(n.push(t),r=!0):e.directives.docStart&&(r=!0)}r&&n.push(`---`);let i=ga(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(Yi(t,``))}let o=!1,s=null;if(e.contents){if(Jr(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(Yi(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=ya(e.contents,i,()=>s=null,t);s&&(c+=Zi(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(ya(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
88
+ `)?(n.push(`...`),n.push(Yi(t,``))):n.push(`... ${t}`)}else n.push(`...`)}else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,``)),t&&((!o||s)&&n[n.length-1]!==``&&n.push(``),n.push(Yi(a(t),``)))}return n.join(`
89
89
  `)+`
90
- `}var vs=R((()=>{ui(),xa(),$i()}));function ys(e){if(Jr(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var bs,xs=R((()=>{zi(),Yi(),ui(),Ra(),Pi(),gs(),vs(),Ai(),Mi(),Gi(),Ti(),bs=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ni,{value:Zr});let r=null;typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=i;let{version:a}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new wi({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[ni]:{value:Zr}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Yr(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){ys(this.contents)&&this.contents.add(e)}addIn(e,t){ys(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=Di(this);e.anchor=!t||n.has(t)?Oi(t||`a`,n):t}return new Ri(e.anchor)}createNode(e,t,n){let r;if(typeof t==`function`)e=t.call({"":e},``,e),r=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),r=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:a,flow:o,keepUndefined:s,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:f}=ki(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=Ui(e,l,p);return o&&Jr(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){let r=this.createNode(e,null,n),i=this.createNode(t,null,n);return new La(r,i)}delete(e){return ys(this.contents)?this.contents.delete(e):!1}deleteIn(e){return qi(e)?this.contents!=null&&(this.contents=null,!0):ys(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return Jr(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return qi(e)?!t&&si(this.contents)?this.contents.value:this.contents:Jr(this.contents)?this.contents.getIn(e,t):void 0}has(e){return Jr(this.contents)?this.contents.has(e):!1}hasIn(e){return qi(e)?this.contents!==void 0:Jr(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ki(this.schema,[e],t):ys(this.contents)&&this.contents.set(e,t)}setIn(e,t){qi(e)?this.contents=t:this.contents==null?this.contents=Ki(this.schema,Array.from(e),t):ys(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new wi({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new wi({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new hs(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:a}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},s=Ni(this.contents,t??``,o);if(typeof i==`function`)for(let{count:e,res:t}of o.anchors.values())i(t,e);return typeof a==`function`?ji(a,{"":s},``,s):s}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return _s(this,e)}}})),Ss,Cs,ws,Ts,Es=R((()=>{Ss=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},Cs=class extends Ss{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},ws=class extends Ss{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},Ts=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
91
- `),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}}}));function Ds(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!b||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}var Os=R((()=>{}));function ks(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
92
- `))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let t of e.items){for(let e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(ks(t.key)||ks(t.value))return!0}return!1;default:return!0}}var As=R((()=>{}));function js(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&ks(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}var Ms=R((()=>{As()}));function Ns(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||si(e)&&si(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var Ps=R((()=>{ui()}));function Fs({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??Ga)(n.schema);n.atRoot&&=!1;let s=r.offset,c=null;for(let a of r.items){let{start:l,key:u,sep:d,value:f}=a,p=Ds(l,{indicator:`explicit-key-ind`,next:u??d?.[0],offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(u&&(u.type===`block-seq`?i(s,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in u&&u.indent!==r.indent&&i(s,`BAD_INDENT`,Is)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
93
- `+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||ks(u))&&i(u??l[l.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else p.found?.indent!==r.indent&&i(s,`BAD_INDENT`,Is);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&js(r.indent,u,i),n.atKey=!1,Ns(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=Ds(d??[],{indicator:`map-value-ind`,next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||u.type===`block-scalar`});if(s=_.end,_.found){m&&(f?.type===`block-map`&&!_.hasNewline&&i(s,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),n.options.strict&&p.start<_.found.offset-1024&&i(g.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let c=f?e(n,f,_,i):t(n,s,d,null,_,i);n.schema.compat&&js(r.indent,f,i),s=c.range[2];let l=new La(g,c);n.options.keepSourceTokens&&(l.srcToken=a),o.items.push(l)}else{m&&i(g.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),_.comment&&(g.comment?g.comment+=`
94
- `+_.comment:g.comment=_.comment);let e=new La(g);n.options.keepSourceTokens&&(e.srcToken=a),o.items.push(e)}}return c&&c<s&&i(c,`IMPOSSIBLE`,`Map comment with trailing content`),o.range=[r.offset,s,c??s],o}var Is,Ls=R((()=>{Ra(),Ka(),Os(),As(),Ms(),Ps(),Is=`All mapping items must start at the same column`}));function Rs({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??Xa)(n.schema);n.atRoot&&=!1,n.atKey&&=!1;let s=r.offset,c=null;for(let{start:a,value:l}of r.items){let u=Ds(a,{indicator:`seq-item-ind`,next:l,offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(u.anchor||u.tag||l)l?.type===`block-seq`?i(u.end,`BAD_INDENT`,`All sequence items must start at the same column`):i(s,`MISSING_CHAR`,`Sequence item without - indicator`);else{c=u.end,u.comment&&(o.comment=u.comment);continue}}let d=l?e(n,l,u,i):t(n,u.end,a,null,u,i);n.schema.compat&&js(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}var zs=R((()=>{Za(),Os(),Ms()}));function Bs(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}var Vs=R((()=>{}));function Hs({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?Ga:Xa))(n.schema);c.flow=!0;let l=n.atRoot;l&&(n.atRoot=!1),n.atKey&&=!1;let u=r.offset+r.start.source.length;for(let a=0;a<r.items.length;++a){let l=r.items[a],{start:d,key:f,sep:p,value:m}=l,h=Ds(d,{flow:s,indicator:`explicit-key-ind`,next:f??p?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!h.found){if(!h.anchor&&!h.tag&&!p&&!m){a===0&&h.comma?i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`):a<r.items.length-1&&i(h.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${s}`),h.comment&&(c.comment?c.comment+=`
95
- `+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&ks(f)&&i(f,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(a===0)h.comma&&i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`);else if(h.comma||i(h.start,`MISSING_CHAR`,`Missing , between ${s} items`),h.comment){let e=``;loop:for(let t of d)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let t=c.items[c.items.length-1];oi(t)&&(t=t.value??t.key),t.comment?t.comment+=`
96
- `+e:t.comment=e,h.comment=h.comment.substring(e.length+1)}}if(!o&&!p&&!h.found){let r=m?e(n,m,h,i):t(n,h.end,p,null,h,i);c.items.push(r),u=r.range[2],Ws(m)&&i(r.range,`BLOCK_IN_FLOW`,Us)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);Ws(f)&&i(g.range,`BLOCK_IN_FLOW`,Us),n.atKey=!1;let _=Ds(p??[],{flow:s,indicator:`map-value-ind`,next:m,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!h.found&&n.options.strict){if(p)for(let e of p){if(e===_.found)break;if(e.type===`newline`){i(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}h.start<_.found.offset-1024&&i(_.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else m&&(`source`in m&&m.source?.[0]===`:`?i(m,`MISSING_CHAR`,`Missing space after : in ${s}`):i(_.start,`MISSING_CHAR`,`Missing , or : between ${s} items`));let v=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;v?Ws(m)&&i(v.range,`BLOCK_IN_FLOW`,Us):_.comment&&(g.comment?g.comment+=`
97
- `+_.comment:g.comment=_.comment);let y=new La(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;Ns(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new Ga(n.schema);e.flow=!0,e.items.push(y);let t=(v??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=v?v.range[2]:_.end}}let d=o?`}`:`]`,[f,...p]=r.end,m=u;if(f?.source===d)m=f.offset+f.source.length;else{let e=s[0].toUpperCase()+s.substring(1),t=l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`;i(u,l?`MISSING_CHAR`:`BAD_INDENT`,t),f&&f.source.length!==1&&p.unshift(f)}if(p.length>0){let e=Bs(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
98
- `+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}var Us,Ws,Gs=R((()=>{ui(),Ra(),Ka(),Za(),Vs(),Os(),As(),Ps(),Us=`Block collections are not allowed within flow collections`,Ws=e=>e&&(e.type===`block-map`||e.type===`block-seq`)}));function Ks(e,t,n,r,i,a){let o=n.type===`block-map`?Fs(e,t,n,r,a):n.type===`block-seq`?Rs(e,t,n,r,a):Hs(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function qs(e,t,n,r,i){let a=r.tag,o=a?t.directives.tagName(a.source,e=>i(a,`TAG_RESOLVE_FAILED`,e)):null;if(n.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=r,n=e&&a?e.offset>a.offset?e:a:e??a;n&&(!t||t.offset<n.offset)&&i(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let s=n.type===`block-map`?`map`:n.type===`block-seq`?`seq`:n.start.source===`{`?`map`:`seq`;if(!a||!o||o===`!`||o===Ga.tagName&&s===`map`||o===Xa.tagName&&s===`seq`)return Ks(e,t,n,i,o);let c=t.schema.tags.find(e=>e.tag===o&&e.collection===s);if(!c){let r=t.schema.knownTags[o];if(r?.collection===s)t.schema.tags.push(Object.assign({},r,{default:!1})),c=r;else return r?i(a,`BAD_COLLECTION_TYPE`,`${r.tag} used for ${s} collection, but expects ${r.collection??`scalar`}`,!0):i(a,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${o}`,!0),Ks(e,t,n,i,o)}let l=Ks(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=Yr(u)?u:new B(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}var Js=R((()=>{ui(),Vi(),Ka(),Za(),Ls(),zs(),Gs()}));function Ys(e,t,n){let r=t.offset,i=Xs(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?B.BLOCK_FOLDED:B.BLOCK_LITERAL,o=t.source?Zs(t.source):[],s=o.length;for(let e=o.length-1;e>=0;--e){let t=o[e][1];if(t===``||t===`\r`)s=e;else break}if(s===0){let e=i.chomp===`+`&&o.length>0?`
90
+ `}var _s=z((()=>{li(),ba(),Qi()}));function vs(e){if(qr(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var ys,bs=z((()=>{Ri(),Ji(),li(),La(),Ni(),hs(),_s(),ki(),ji(),Wi(),wi(),ys=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ti,{value:Xr});let r=null;typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=i;let{version:a}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new Ci({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[ti]:{value:Xr}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Jr(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){vs(this.contents)&&this.contents.add(e)}addIn(e,t){vs(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=Ei(this);e.anchor=!t||n.has(t)?Di(t||`a`,n):t}return new Li(e.anchor)}createNode(e,t,n){let r;if(typeof t==`function`)e=t.call({"":e},``,e),r=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),r=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:a,flow:o,keepUndefined:s,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:f}=Oi(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=Hi(e,l,p);return o&&qr(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){let r=this.createNode(e,null,n),i=this.createNode(t,null,n);return new Ia(r,i)}delete(e){return vs(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ki(e)?this.contents!=null&&(this.contents=null,!0):vs(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return qr(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Ki(e)?!t&&oi(this.contents)?this.contents.value:this.contents:qr(this.contents)?this.contents.getIn(e,t):void 0}has(e){return qr(this.contents)?this.contents.has(e):!1}hasIn(e){return Ki(e)?this.contents!==void 0:qr(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Gi(this.schema,[e],t):vs(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ki(e)?this.contents=t:this.contents==null?this.contents=Gi(this.schema,Array.from(e),t):vs(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new Ci({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new Ci({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new ms(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:a}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},s=Mi(this.contents,t??``,o);if(typeof i==`function`)for(let{count:e,res:t}of o.anchors.values())i(t,e);return typeof a==`function`?Ai(a,{"":s},``,s):s}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return gs(this,e)}}})),xs,Ss,Cs,ws,Ts=z((()=>{xs=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},Ss=class extends xs{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},Cs=class extends xs{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},ws=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
91
+ `),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}}}));function Es(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!b||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}var Ds=z((()=>{}));function Os(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
92
+ `))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let t of e.items){for(let e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(Os(t.key)||Os(t.value))return!0}return!1;default:return!0}}var ks=z((()=>{}));function As(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&Os(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}var js=z((()=>{ks()}));function Ms(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||oi(e)&&oi(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var Ns=z((()=>{li()}));function Ps({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??Wa)(n.schema);n.atRoot&&=!1;let s=r.offset,c=null;for(let a of r.items){let{start:l,key:u,sep:d,value:f}=a,p=Es(l,{indicator:`explicit-key-ind`,next:u??d?.[0],offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(u&&(u.type===`block-seq`?i(s,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in u&&u.indent!==r.indent&&i(s,`BAD_INDENT`,Fs)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
93
+ `+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||Os(u))&&i(u??l[l.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else p.found?.indent!==r.indent&&i(s,`BAD_INDENT`,Fs);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&As(r.indent,u,i),n.atKey=!1,Ms(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=Es(d??[],{indicator:`map-value-ind`,next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||u.type===`block-scalar`});if(s=_.end,_.found){m&&(f?.type===`block-map`&&!_.hasNewline&&i(s,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),n.options.strict&&p.start<_.found.offset-1024&&i(g.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let c=f?e(n,f,_,i):t(n,s,d,null,_,i);n.schema.compat&&As(r.indent,f,i),s=c.range[2];let l=new Ia(g,c);n.options.keepSourceTokens&&(l.srcToken=a),o.items.push(l)}else{m&&i(g.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),_.comment&&(g.comment?g.comment+=`
94
+ `+_.comment:g.comment=_.comment);let e=new Ia(g);n.options.keepSourceTokens&&(e.srcToken=a),o.items.push(e)}}return c&&c<s&&i(c,`IMPOSSIBLE`,`Map comment with trailing content`),o.range=[r.offset,s,c??s],o}var Fs,Is=z((()=>{La(),Ga(),Ds(),ks(),js(),Ns(),Fs=`All mapping items must start at the same column`}));function Ls({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??Ya)(n.schema);n.atRoot&&=!1,n.atKey&&=!1;let s=r.offset,c=null;for(let{start:a,value:l}of r.items){let u=Es(a,{indicator:`seq-item-ind`,next:l,offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(u.anchor||u.tag||l)l?.type===`block-seq`?i(u.end,`BAD_INDENT`,`All sequence items must start at the same column`):i(s,`MISSING_CHAR`,`Sequence item without - indicator`);else{c=u.end,u.comment&&(o.comment=u.comment);continue}}let d=l?e(n,l,u,i):t(n,u.end,a,null,u,i);n.schema.compat&&As(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}var Rs=z((()=>{Xa(),Ds(),js()}));function zs(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}var Bs=z((()=>{}));function Vs({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?Wa:Ya))(n.schema);c.flow=!0;let l=n.atRoot;l&&(n.atRoot=!1),n.atKey&&=!1;let u=r.offset+r.start.source.length;for(let a=0;a<r.items.length;++a){let l=r.items[a],{start:d,key:f,sep:p,value:m}=l,h=Es(d,{flow:s,indicator:`explicit-key-ind`,next:f??p?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!h.found){if(!h.anchor&&!h.tag&&!p&&!m){a===0&&h.comma?i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`):a<r.items.length-1&&i(h.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${s}`),h.comment&&(c.comment?c.comment+=`
95
+ `+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&Os(f)&&i(f,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(a===0)h.comma&&i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`);else if(h.comma||i(h.start,`MISSING_CHAR`,`Missing , between ${s} items`),h.comment){let e=``;loop:for(let t of d)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let t=c.items[c.items.length-1];ai(t)&&(t=t.value??t.key),t.comment?t.comment+=`
96
+ `+e:t.comment=e,h.comment=h.comment.substring(e.length+1)}}if(!o&&!p&&!h.found){let r=m?e(n,m,h,i):t(n,h.end,p,null,h,i);c.items.push(r),u=r.range[2],Us(m)&&i(r.range,`BLOCK_IN_FLOW`,Hs)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);Us(f)&&i(g.range,`BLOCK_IN_FLOW`,Hs),n.atKey=!1;let _=Es(p??[],{flow:s,indicator:`map-value-ind`,next:m,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!h.found&&n.options.strict){if(p)for(let e of p){if(e===_.found)break;if(e.type===`newline`){i(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}h.start<_.found.offset-1024&&i(_.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else m&&(`source`in m&&m.source?.[0]===`:`?i(m,`MISSING_CHAR`,`Missing space after : in ${s}`):i(_.start,`MISSING_CHAR`,`Missing , or : between ${s} items`));let v=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;v?Us(m)&&i(v.range,`BLOCK_IN_FLOW`,Hs):_.comment&&(g.comment?g.comment+=`
97
+ `+_.comment:g.comment=_.comment);let y=new Ia(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;Ms(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new Wa(n.schema);e.flow=!0,e.items.push(y);let t=(v??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=v?v.range[2]:_.end}}let d=o?`}`:`]`,[f,...p]=r.end,m=u;if(f?.source===d)m=f.offset+f.source.length;else{let e=s[0].toUpperCase()+s.substring(1),t=l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`;i(u,l?`MISSING_CHAR`:`BAD_INDENT`,t),f&&f.source.length!==1&&p.unshift(f)}if(p.length>0){let e=zs(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
98
+ `+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}var Hs,Us,Ws=z((()=>{li(),La(),Ga(),Xa(),Bs(),Ds(),ks(),Ns(),Hs=`Block collections are not allowed within flow collections`,Us=e=>e&&(e.type===`block-map`||e.type===`block-seq`)}));function Gs(e,t,n,r,i,a){let o=n.type===`block-map`?Ps(e,t,n,r,a):n.type===`block-seq`?Ls(e,t,n,r,a):Vs(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function Ks(e,t,n,r,i){let a=r.tag,o=a?t.directives.tagName(a.source,e=>i(a,`TAG_RESOLVE_FAILED`,e)):null;if(n.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=r,n=e&&a?e.offset>a.offset?e:a:e??a;n&&(!t||t.offset<n.offset)&&i(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let s=n.type===`block-map`?`map`:n.type===`block-seq`?`seq`:n.start.source===`{`?`map`:`seq`;if(!a||!o||o===`!`||o===Wa.tagName&&s===`map`||o===Ya.tagName&&s===`seq`)return Gs(e,t,n,i,o);let c=t.schema.tags.find(e=>e.tag===o&&e.collection===s);if(!c){let r=t.schema.knownTags[o];if(r?.collection===s)t.schema.tags.push(Object.assign({},r,{default:!1})),c=r;else return r?i(a,`BAD_COLLECTION_TYPE`,`${r.tag} used for ${s} collection, but expects ${r.collection??`scalar`}`,!0):i(a,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${o}`,!0),Gs(e,t,n,i,o)}let l=Gs(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=Jr(u)?u:new V(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}var qs=z((()=>{li(),Bi(),Ga(),Xa(),Is(),Rs(),Ws()}));function Js(e,t,n){let r=t.offset,i=Ys(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?V.BLOCK_FOLDED:V.BLOCK_LITERAL,o=t.source?Xs(t.source):[],s=o.length;for(let e=o.length-1;e>=0;--e){let t=o[e][1];if(t===``||t===`\r`)s=e;else break}if(s===0){let e=i.chomp===`+`&&o.length>0?`
99
99
  `.repeat(Math.max(1,o.length-1)):``,n=r+i.length;return t.source&&(n+=t.source.length),{value:e,type:a,comment:i.comment,range:[r,n,n]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let t=0;t<s;++t){let[r,a]=o[t];if(a===``||a===`\r`)i.indent===0&&r.length>c&&(c=r.length);else{r.length<c&&n(l+r.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),i.indent===0&&(c=r.length),u=t,c===0&&!e.atRoot&&n(l,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}l+=r.length+a.length+1}for(let e=o.length-1;e>=s;--e)o[e][0].length>c&&(s=e+1);let d=``,f=``,p=!1;for(let e=0;e<u;++e)d+=o[e][0].slice(c)+`
100
- `;for(let e=u;e<s;++e){let[t,r]=o[e];l+=t.length+r.length+1;let s=r[r.length-1]===`\r`;if(s&&(r=r.slice(0,-1)),r&&t.length<c){let e=`Block scalar lines must not be less indented than their ${i.indent?`explicit indentation indicator`:`first line`}`;n(l-r.length-(s?2:1),`BAD_INDENT`,e),t=``}a===B.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
100
+ `;for(let e=u;e<s;++e){let[t,r]=o[e];l+=t.length+r.length+1;let s=r[r.length-1]===`\r`;if(s&&(r=r.slice(0,-1)),r&&t.length<c){let e=`Block scalar lines must not be less indented than their ${i.indent?`explicit indentation indicator`:`first line`}`;n(l-r.length-(s?2:1),`BAD_INDENT`,e),t=``}a===V.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
101
101
  `):t.length>c||r[0]===` `?(f===` `?f=`
102
102
  `:!p&&f===`
103
103
  `&&(f=`
@@ -110,150 +110,150 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
110
110
  `+o[e][0].slice(c);d[d.length-1]!==`
111
111
  `&&(d+=`
112
112
  `);break;default:d+=`
113
- `}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function Xs({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function Zs(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}var Qs=R((()=>{Vi()}));function $s(e,t,n){let{offset:r,type:i,source:a,end:o}=e,s,c,l=(e,t,i)=>n(r+e,t,i);switch(i){case`scalar`:s=B.PLAIN,c=ec(a,l);break;case`single-quoted-scalar`:s=B.QUOTE_SINGLE,c=tc(a,l);break;case`double-quoted-scalar`:s=B.QUOTE_DOUBLE,c=rc(a,l);break;default:return n(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${i}`),{value:``,type:null,comment:``,range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=Bs(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function ec(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),nc(e)}function tc(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),nc(e.slice(1,-1)).replace(/''/g,`'`)}function nc(e){let t,n;try{t=RegExp(`(.*?)(?<![ ])[ ]*\r?
113
+ `}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function Ys({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function Xs(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}var Zs=z((()=>{Bi()}));function Qs(e,t,n){let{offset:r,type:i,source:a,end:o}=e,s,c,l=(e,t,i)=>n(r+e,t,i);switch(i){case`scalar`:s=V.PLAIN,c=$s(a,l);break;case`single-quoted-scalar`:s=V.QUOTE_SINGLE,c=ec(a,l);break;case`double-quoted-scalar`:s=V.QUOTE_DOUBLE,c=nc(a,l);break;default:return n(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${i}`),{value:``,type:null,comment:``,range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=zs(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function $s(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),tc(e)}function ec(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),tc(e.slice(1,-1)).replace(/''/g,`'`)}function tc(e){let t,n;try{t=RegExp(`(.*?)(?<![ ])[ ]*\r?
114
114
  `,`sy`),n=RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
115
115
  `,`sy`)}catch{t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let i=r[1],a=` `,o=t.lastIndex;for(n.lastIndex=o;r=n.exec(e);)r[1]===``?a===`
116
116
  `?i+=a:a=`
117
- `:(i+=a+r[1],a=` `),o=n.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),i+a+(r?.[1]??``)}function rc(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
117
+ `:(i+=a+r[1],a=` `),o=n.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),i+a+(r?.[1]??``)}function nc(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
118
118
  `){if(i===`
119
- `){let{fold:t,offset:i}=ic(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=oc[i];if(a)n+=a;else if(i===`
119
+ `){let{fold:t,offset:i}=rc(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=ac[i];if(a)n+=a;else if(i===`
120
120
  `)for(i=e[r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`\r`&&e[r+1]===`
121
- `)for(i=e[++r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`x`||i===`u`||i===`U`){let a=i===`x`?2:i===`u`?4:8;n+=ac(e,r+1,a,t),r+=a}else{let i=e.substr(r-1,2);t(r-1,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),n+=i}}else if(i===` `||i===` `){let t=r,a=e[r+1];for(;a===` `||a===` `;)a=e[++r+1];a!==`
121
+ `)for(i=e[++r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`x`||i===`u`||i===`U`){let a=i===`x`?2:i===`u`?4:8;n+=ic(e,r+1,a,t),r+=a}else{let i=e.substr(r-1,2);t(r-1,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),n+=i}}else if(i===` `||i===` `){let t=r,a=e[r+1];for(;a===` `||a===` `;)a=e[++r+1];a!==`
122
122
  `&&(a!==`\r`||e[r+2]!==`
123
- `)&&(n+=r>t?e.slice(t,r+1):i)}else n+=i}}return(e[e.length-1]!==`"`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing "quote`),n}function ic(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
123
+ `)&&(n+=r>t?e.slice(t,r+1):i)}else n+=i}}return(e[e.length-1]!==`"`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing "quote`),n}function rc(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
124
124
  `||r===`\r`)&&(r!==`\r`||e[t+2]===`
125
125
  `);)r===`
126
126
  `&&(n+=`
127
- `),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}function ac(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}var oc,sc=R((()=>{Vi(),Vs(),oc={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
128
- `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `}}));function cc(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?Ys(e,t,r):$s(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,`TAG_RESOLVE_FAILED`,e)):null,l;l=e.options.stringKeys&&e.atKey?e.schema[ei]:c?lc(e.schema,i,c,n,r):t.type===`scalar`?uc(e,i,t,r):e.schema[ei];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=si(a)?a:new B(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new B(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function lc(e,t,n,r,i){if(n===`!`)return e[ei];let a=[];for(let t of e.tags)if(!t.collection&&t.tag===n){if(t.default&&t.test)a.push(t);else return t}for(let e of a)if(e.test?.test(t))return e;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${n}`,n!==`tag:yaml.org,2002:str`),e[ei])}function uc({atKey:e,directives:t,schema:n},r,i,a){let o=n.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(r))||n[ei];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[ei];o.tag!==e.tag&&a(i,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${t.tagString(o.tag)} or ${t.tagString(e.tag)}`,!0)}return o}var dc=R((()=>{ui(),Vi(),Qs(),sc()}));function fc(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}var pc=R((()=>{}));function mc(e,t,n,r){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=n,l,u=!0;switch(t.type){case`alias`:l=gc(e,t,r),(s||c)&&r(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:l=cc(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=qs(_c,e,t,n,r),s&&(l.anchor=s.source.substring(1))}catch(e){r(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:r(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),u=!1}return l??=hc(e,t.offset,void 0,null,n,r),s&&l.anchor===``&&r(s,`BAD_ALIAS`,`Anchor cannot be an empty string`),i&&e.options.stringKeys&&(!si(l)||typeof l.value!=`string`||l.tag&&l.tag!==`tag:yaml.org,2002:str`)&&r(c??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),a&&(l.spaceBefore=!0),o&&(t.type===`scalar`&&t.source===``?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function hc(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=cc(e,{type:`scalar`,offset:fc(t,n,r),indent:-1,source:``},s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===``&&l(o,`BAD_ALIAS`,`Anchor cannot be an empty string`)),i&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function gc({options:e},{offset:t,source:n,end:r},i){let a=new Ri(n.substring(1));a.source===``&&i(t,`BAD_ALIAS`,`Alias cannot be an empty string`),a.source.endsWith(`:`)&&i(t+n.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let o=t+n.length,s=Bs(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}var _c,vc=R((()=>{zi(),ui(),Js(),dc(),Vs(),pc(),_c={composeNode:mc,composeEmptyNode:hc}}));function yc(e,t,{offset:n,start:r,value:i,end:a},o){let s=Object.assign({_directives:t},e),c=new bs(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Ds(r,{indicator:`doc-start`,next:i??a?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type===`block-map`||i.type===`block-seq`)&&!u.hasNewline&&o(u.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),c.contents=i?mc(l,i,u,o):hc(l,u.end,r,null,u,o);let d=c.contents.range[2],f=Bs(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,d,f.offset],c}var bc=R((()=>{xs(),vc(),Vs(),Os()}));function xc(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function Sc(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
127
+ `),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}function ic(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}var ac,oc=z((()=>{Bi(),Bs(),ac={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
128
+ `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `}}));function sc(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?Js(e,t,r):Qs(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,`TAG_RESOLVE_FAILED`,e)):null,l;l=e.options.stringKeys&&e.atKey?e.schema[$r]:c?cc(e.schema,i,c,n,r):t.type===`scalar`?lc(e,i,t,r):e.schema[$r];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=oi(a)?a:new V(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new V(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function cc(e,t,n,r,i){if(n===`!`)return e[$r];let a=[];for(let t of e.tags)if(!t.collection&&t.tag===n){if(t.default&&t.test)a.push(t);else return t}for(let e of a)if(e.test?.test(t))return e;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${n}`,n!==`tag:yaml.org,2002:str`),e[$r])}function lc({atKey:e,directives:t,schema:n},r,i,a){let o=n.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(r))||n[$r];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[$r];o.tag!==e.tag&&a(i,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${t.tagString(o.tag)} or ${t.tagString(e.tag)}`,!0)}return o}var uc=z((()=>{li(),Bi(),Zs(),oc()}));function dc(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}var fc=z((()=>{}));function pc(e,t,n,r){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=n,l,u=!0;switch(t.type){case`alias`:l=hc(e,t,r),(s||c)&&r(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:l=sc(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=Ks(gc,e,t,n,r),s&&(l.anchor=s.source.substring(1))}catch(e){r(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:r(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),u=!1}return l??=mc(e,t.offset,void 0,null,n,r),s&&l.anchor===``&&r(s,`BAD_ALIAS`,`Anchor cannot be an empty string`),i&&e.options.stringKeys&&(!oi(l)||typeof l.value!=`string`||l.tag&&l.tag!==`tag:yaml.org,2002:str`)&&r(c??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),a&&(l.spaceBefore=!0),o&&(t.type===`scalar`&&t.source===``?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function mc(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=sc(e,{type:`scalar`,offset:dc(t,n,r),indent:-1,source:``},s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===``&&l(o,`BAD_ALIAS`,`Anchor cannot be an empty string`)),i&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function hc({options:e},{offset:t,source:n,end:r},i){let a=new Li(n.substring(1));a.source===``&&i(t,`BAD_ALIAS`,`Alias cannot be an empty string`),a.source.endsWith(`:`)&&i(t+n.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let o=t+n.length,s=zs(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}var gc,_c=z((()=>{Ri(),li(),qs(),uc(),Bs(),fc(),gc={composeNode:pc,composeEmptyNode:mc}}));function vc(e,t,{offset:n,start:r,value:i,end:a},o){let s=Object.assign({_directives:t},e),c=new ys(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Es(r,{indicator:`doc-start`,next:i??a?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type===`block-map`||i.type===`block-seq`)&&!u.hasNewline&&o(u.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),c.contents=i?pc(l,i,u,o):mc(l,u.end,r,null,u,o);let d=c.contents.range[2],f=zs(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,d,f.offset],c}var yc=z((()=>{bs(),_c(),Bs(),Ds()}));function bc(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function xc(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
129
129
 
130
130
  `:`
131
- `)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var Cc,wc=R((()=>{Ti(),xs(),Es(),ui(),bc(),Vs(),Cc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=xc(e);r?this.warnings.push(new ws(i,t,n)):this.errors.push(new Cs(i,t,n))},this.directives=new wi({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=Sc(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(Jr(i)&&!i.flow&&i.items.length>0){let e=i.items[0];oi(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Sc(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=xc(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=yc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new Cs(xc(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new Cs(xc(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=Bs(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Cs(xc(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=Object.assign({_directives:this.directives},this.options),n=new bs(void 0,e);this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),n.range=[0,t,t],this.decorate(n,!1),yield n}}}}));function Tc(e,t=!0,n){if(e){let r=(e,t,r)=>{let i=typeof e==`number`?e:Array.isArray(e)?e[0]:e.offset;if(n)n(i,t,r);else throw new Cs([i,i+1],t,r)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return $s(e,t,r);case`block-scalar`:return Ys({options:{strict:t}},e,r)}}return null}function Ec(e,t){let{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:a=-1,type:o=`PLAIN`}=t,s=fa({type:o,value:e},{implicitKey:n,indent:r>0?` `.repeat(r):``,inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:`newline`,offset:-1,indent:r,source:`
131
+ `)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var Sc,Cc=z((()=>{wi(),bs(),Ts(),li(),yc(),Bs(),Sc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=bc(e);r?this.warnings.push(new Cs(i,t,n)):this.errors.push(new Ss(i,t,n))},this.directives=new Ci({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=xc(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(qr(i)&&!i.flow&&i.items.length>0){let e=i.items[0];ai(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:xc(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=bc(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=vc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new Ss(bc(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new Ss(bc(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=zs(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Ss(bc(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=Object.assign({_directives:this.directives},this.options),n=new ys(void 0,e);this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),n.range=[0,t,t],this.decorate(n,!1),yield n}}}}));function wc(e,t=!0,n){if(e){let r=(e,t,r)=>{let i=typeof e==`number`?e:Array.isArray(e)?e[0]:e.offset;if(n)n(i,t,r);else throw new Ss([i,i+1],t,r)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return Qs(e,t,r);case`block-scalar`:return Js({options:{strict:t}},e,r)}}return null}function Tc(e,t){let{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:a=-1,type:o=`PLAIN`}=t,s=da({type:o,value:e},{implicitKey:n,indent:r>0?` `.repeat(r):``,inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:`newline`,offset:-1,indent:r,source:`
132
132
  `}];switch(s[0]){case`|`:case`>`:{let e=s.indexOf(`
133
133
  `),t=s.substring(0,e),n=s.substring(e+1)+`
134
- `,i=[{type:`block-scalar-header`,offset:a,indent:r,source:t}];return kc(i,c)||i.push({type:`newline`,offset:-1,indent:r,source:`
135
- `}),{type:`block-scalar`,offset:a,indent:r,props:i,source:n}}case`"`:return{type:`double-quoted-scalar`,offset:a,indent:r,source:s,end:c};case`'`:return{type:`single-quoted-scalar`,offset:a,indent:r,source:s,end:c};default:return{type:`scalar`,offset:a,indent:r,source:s,end:c}}}function Dc(e,t,n={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:a=!1,type:o}=n,s=`indent`in e?e.indent:null;if(r&&typeof s==`number`&&(s+=2),!o)switch(e.type){case`single-quoted-scalar`:o=`QUOTE_SINGLE`;break;case`double-quoted-scalar`:o=`QUOTE_DOUBLE`;break;case`block-scalar`:{let t=e.props[0];if(t.type!==`block-scalar-header`)throw Error(`Invalid block scalar header`);o=t.source[0]===`>`?`BLOCK_FOLDED`:`BLOCK_LITERAL`;break}default:o=`PLAIN`}let c=fa({type:o,value:t},{implicitKey:i||s===null,indent:s!==null&&s>0?` `.repeat(s):``,inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case`|`:case`>`:Oc(e,c);break;case`"`:Ac(e,c,`double-quoted-scalar`);break;case`'`:Ac(e,c,`single-quoted-scalar`);break;default:Ac(e,c,`scalar`)}}function Oc(e,t){let n=t.indexOf(`
134
+ `,i=[{type:`block-scalar-header`,offset:a,indent:r,source:t}];return Oc(i,c)||i.push({type:`newline`,offset:-1,indent:r,source:`
135
+ `}),{type:`block-scalar`,offset:a,indent:r,props:i,source:n}}case`"`:return{type:`double-quoted-scalar`,offset:a,indent:r,source:s,end:c};case`'`:return{type:`single-quoted-scalar`,offset:a,indent:r,source:s,end:c};default:return{type:`scalar`,offset:a,indent:r,source:s,end:c}}}function Ec(e,t,n={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:a=!1,type:o}=n,s=`indent`in e?e.indent:null;if(r&&typeof s==`number`&&(s+=2),!o)switch(e.type){case`single-quoted-scalar`:o=`QUOTE_SINGLE`;break;case`double-quoted-scalar`:o=`QUOTE_DOUBLE`;break;case`block-scalar`:{let t=e.props[0];if(t.type!==`block-scalar-header`)throw Error(`Invalid block scalar header`);o=t.source[0]===`>`?`BLOCK_FOLDED`:`BLOCK_LITERAL`;break}default:o=`PLAIN`}let c=da({type:o,value:t},{implicitKey:i||s===null,indent:s!==null&&s>0?` `.repeat(s):``,inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case`|`:case`>`:Dc(e,c);break;case`"`:kc(e,c,`double-quoted-scalar`);break;case`'`:kc(e,c,`single-quoted-scalar`);break;default:kc(e,c,`scalar`)}}function Dc(e,t){let n=t.indexOf(`
136
136
  `),r=t.substring(0,n),i=t.substring(n+1)+`
137
- `;if(e.type===`block-scalar`){let t=e.props[0];if(t.type!==`block-scalar-header`)throw Error(`Invalid block scalar header`);t.source=r,e.source=i}else{let{offset:t}=e,n=`indent`in e?e.indent:-1,a=[{type:`block-scalar-header`,offset:t,indent:n,source:r}];kc(a,`end`in e?e.end:void 0)||a.push({type:`newline`,offset:-1,indent:n,source:`
138
- `});for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:`block-scalar`,indent:n,props:a,source:i})}}function kc(e,t){if(t)for(let n of t)switch(n.type){case`space`:case`comment`:e.push(n);break;case`newline`:return e.push(n),!0}return!1}function Ac(e,t,n){switch(e.type){case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:e.type=n,e.source=t;break;case`block-scalar`:{let r=e.props.slice(1),i=t.length;e.props[0].type===`block-scalar-header`&&(i-=e.props[0].source.length);for(let e of r)e.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case`block-map`:case`block-seq`:{let r={type:`newline`,offset:e.offset+t.length,indent:e.indent,source:`
139
- `};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let r=`indent`in e?e.indent:-1,i=`end`in e&&Array.isArray(e.end)?e.end.filter(e=>e.type===`space`||e.type===`comment`||e.type===`newline`):[];for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}var jc=R((()=>{Qs(),sc(),Es(),ga()}));function Mc(e){switch(e.type){case`block-scalar`:{let t=``;for(let n of e.props)t+=Mc(n);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=Nc(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=Nc(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=Nc(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if(`end`in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function Nc({start:e,key:t,sep:n,value:r}){let i=``;for(let t of e)i+=t.source;if(t&&(i+=Mc(t)),n)for(let e of n)i+=e.source;return r&&(i+=Mc(r)),i}var Pc,Fc=R((()=>{Pc=e=>`type`in e?Mc(e):Nc(e)}));function Ic(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),Lc(Object.freeze([]),e,t)}function Lc(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=Lc(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===Rc)return Rc;else r===Bc&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}var Rc,zc,Bc,Vc=R((()=>{Rc=Symbol(`break visit`),zc=Symbol(`skip children`),Bc=Symbol(`remove item`),Ic.BREAK=Rc,Ic.SKIP=zc,Ic.REMOVE=Bc,Ic.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},Ic.parentCollection=(e,t)=>{let n=Ic.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)}})),Hc=at({BOM:()=>``,DOCUMENT:()=>``,FLOW_END:()=>``,SCALAR:()=>``,createScalarToken:()=>Ec,isCollection:()=>Gc,isScalar:()=>Kc,prettyToken:()=>Uc,resolveAsScalar:()=>Tc,setScalarValue:()=>Dc,stringify:()=>Pc,tokenType:()=>Wc,visit:()=>Ic});function Uc(e){switch(e){case``:return`<BOM>`;case``:return`<DOC>`;case``:return`<FLOW_END>`;case``:return`<SCALAR>`;default:return JSON.stringify(e)}}function Wc(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
137
+ `;if(e.type===`block-scalar`){let t=e.props[0];if(t.type!==`block-scalar-header`)throw Error(`Invalid block scalar header`);t.source=r,e.source=i}else{let{offset:t}=e,n=`indent`in e?e.indent:-1,a=[{type:`block-scalar-header`,offset:t,indent:n,source:r}];Oc(a,`end`in e?e.end:void 0)||a.push({type:`newline`,offset:-1,indent:n,source:`
138
+ `});for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:`block-scalar`,indent:n,props:a,source:i})}}function Oc(e,t){if(t)for(let n of t)switch(n.type){case`space`:case`comment`:e.push(n);break;case`newline`:return e.push(n),!0}return!1}function kc(e,t,n){switch(e.type){case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:e.type=n,e.source=t;break;case`block-scalar`:{let r=e.props.slice(1),i=t.length;e.props[0].type===`block-scalar-header`&&(i-=e.props[0].source.length);for(let e of r)e.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case`block-map`:case`block-seq`:{let r={type:`newline`,offset:e.offset+t.length,indent:e.indent,source:`
139
+ `};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let r=`indent`in e?e.indent:-1,i=`end`in e&&Array.isArray(e.end)?e.end.filter(e=>e.type===`space`||e.type===`comment`||e.type===`newline`):[];for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}var Ac=z((()=>{Zs(),oc(),Ts(),ha()}));function jc(e){switch(e.type){case`block-scalar`:{let t=``;for(let n of e.props)t+=jc(n);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=Mc(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=Mc(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=Mc(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if(`end`in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function Mc({start:e,key:t,sep:n,value:r}){let i=``;for(let t of e)i+=t.source;if(t&&(i+=jc(t)),n)for(let e of n)i+=e.source;return r&&(i+=jc(r)),i}var Nc,Pc=z((()=>{Nc=e=>`type`in e?jc(e):Mc(e)}));function Fc(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),Ic(Object.freeze([]),e,t)}function Ic(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=Ic(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===Lc)return Lc;else r===zc&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}var Lc,Rc,zc,Bc=z((()=>{Lc=Symbol(`break visit`),Rc=Symbol(`skip children`),zc=Symbol(`remove item`),Fc.BREAK=Lc,Fc.SKIP=Rc,Fc.REMOVE=zc,Fc.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},Fc.parentCollection=(e,t)=>{let n=Fc.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)}})),Vc=it({BOM:()=>``,DOCUMENT:()=>``,FLOW_END:()=>``,SCALAR:()=>``,createScalarToken:()=>Tc,isCollection:()=>Wc,isScalar:()=>Gc,prettyToken:()=>Hc,resolveAsScalar:()=>wc,setScalarValue:()=>Ec,stringify:()=>Nc,tokenType:()=>Uc,visit:()=>Fc});function Hc(e){switch(e){case``:return`<BOM>`;case``:return`<DOC>`;case``:return`<FLOW_END>`;case``:return`<SCALAR>`;default:return JSON.stringify(e)}}function Uc(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
140
140
  `:case`\r
141
- `:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}var Gc,Kc,qc=R((()=>{jc(),Fc(),Vc(),Gc=e=>!!e&&`items`in e,Kc=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`)}));function Jc(e){switch(e){case void 0:case` `:case`
142
- `:case`\r`:case` `:return!0;default:return!1}}var Yc,Xc,Zc,Qc,$c,el,tl=R((()=>{qc(),Yc=new Set(`0123456789ABCDEFabcdef`),Xc=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),Zc=new Set(`,[]{}`),Qc=new Set(` ,[]{}
143
- \r `),$c=e=>!e||Qc.has(e),el=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
141
+ `:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}var Wc,Gc,Kc=z((()=>{Ac(),Pc(),Bc(),Wc=e=>!!e&&`items`in e,Gc=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`)}));function qc(e){switch(e){case void 0:case` `:case`
142
+ `:case`\r`:case` `:return!0;default:return!1}}var Jc,Yc,Xc,Zc,Qc,$c,el=z((()=>{Kc(),Jc=new Set(`0123456789ABCDEFabcdef`),Yc=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),Xc=new Set(`,[]{}`),Zc=new Set(` ,[]{}
143
+ \r `),Qc=e=>!e||Zc.has(e),$c=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
144
144
  `||t===`\r`&&this.buffer[e+1]===`
145
145
  `}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===` `;)t=this.buffer[++n+e];if(t===`\r`){let t=this.buffer[n+e+1];if(t===`
146
146
  `||!t&&!this.atEnd)return e+n+1}return t===`
147
- `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&Jc(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=`number`||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
148
- `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===`\r`&&--e,this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case`stream`:return yield*this.parseStream();case`line-start`:return yield*this.parseLineStart();case`block-start`:return yield*this.parseBlockStart();case`doc`:return yield*this.parseDocument();case`flow`:return yield*this.parseFlowCollection();case`quoted-scalar`:return yield*this.parseQuotedScalar();case`block-scalar`:return yield*this.parseBlockScalar();case`plain-scalar`:return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(`stream`);if(e[0]===``&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===`%`){let t=e.length,n=e.indexOf(`#`);for(;n!==-1;){let r=e[n-1];if(r===` `||r===` `){t=n-1;break}n=e.indexOf(`#`,n+1)}for(;;){let n=e[t-1];if(n===` `||n===` `)--t;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),`stream`}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),`stream`}return yield``,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(`line-start`);if(e===`-`||e===`.`){if(!this.atEnd&&!this.hasChars(4))return this.setNext(`line-start`);let e=this.peek(3);if((e===`---`||e===`...`)&&Jc(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,e===`---`?`doc`:`stream`}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Jc(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext(`block-start`);if((e===`-`||e===`?`||e===`:`)&&Jc(t)){let e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,`block-start`}return`doc`}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext(`doc`);let t=yield*this.pushIndicators();switch(e[t]){case`#`:yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),`doc`;case`*`:return yield*this.pushUntil($c),`doc`;case`"`:case`'`:return yield*this.parseQuotedScalar();case`|`:case`>`:return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext(`flow`);if((n!==-1&&n<this.indentNext&&r[0]!==`#`||n===0&&(r.startsWith(`---`)||r.startsWith(`...`))&&Jc(r[3]))&&(n!==this.indentNext-1||this.flowLevel!==1||r[0]!==`]`&&r[0]!==`}`))return this.flowLevel=0,yield``,yield*this.parseLineStart();let i=0;for(;r[i]===`,`;)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return`flow`;case`#`:return yield*this.pushCount(r.length-i),`flow`;case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),this.flowKey=!0,--this.flowLevel,this.flowLevel?`flow`:`doc`;case`*`:return yield*this.pushUntil($c),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||Jc(e)||e===`,`)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),`flow`}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===`'`)for(;t!==-1&&this.buffer[t+1]===`'`;)t=this.buffer.indexOf(`'`,t+2);else for(;t!==-1;){let e=0;for(;this.buffer[t-1-e]===`\\`;)e+=1;if(e%2==0)break;t=this.buffer.indexOf(`"`,t+1)}let n=this.buffer.substring(0,t),r=n.indexOf(`
147
+ `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&qc(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=`number`||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
148
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===`\r`&&--e,this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case`stream`:return yield*this.parseStream();case`line-start`:return yield*this.parseLineStart();case`block-start`:return yield*this.parseBlockStart();case`doc`:return yield*this.parseDocument();case`flow`:return yield*this.parseFlowCollection();case`quoted-scalar`:return yield*this.parseQuotedScalar();case`block-scalar`:return yield*this.parseBlockScalar();case`plain-scalar`:return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(`stream`);if(e[0]===``&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===`%`){let t=e.length,n=e.indexOf(`#`);for(;n!==-1;){let r=e[n-1];if(r===` `||r===` `){t=n-1;break}n=e.indexOf(`#`,n+1)}for(;;){let n=e[t-1];if(n===` `||n===` `)--t;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),`stream`}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),`stream`}return yield``,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(`line-start`);if(e===`-`||e===`.`){if(!this.atEnd&&!this.hasChars(4))return this.setNext(`line-start`);let e=this.peek(3);if((e===`---`||e===`...`)&&qc(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,e===`---`?`doc`:`stream`}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!qc(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext(`block-start`);if((e===`-`||e===`?`||e===`:`)&&qc(t)){let e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,`block-start`}return`doc`}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext(`doc`);let t=yield*this.pushIndicators();switch(e[t]){case`#`:yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),`doc`;case`*`:return yield*this.pushUntil(Qc),`doc`;case`"`:case`'`:return yield*this.parseQuotedScalar();case`|`:case`>`:return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext(`flow`);if((n!==-1&&n<this.indentNext&&r[0]!==`#`||n===0&&(r.startsWith(`---`)||r.startsWith(`...`))&&qc(r[3]))&&(n!==this.indentNext-1||this.flowLevel!==1||r[0]!==`]`&&r[0]!==`}`))return this.flowLevel=0,yield``,yield*this.parseLineStart();let i=0;for(;r[i]===`,`;)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return`flow`;case`#`:return yield*this.pushCount(r.length-i),`flow`;case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),this.flowKey=!0,--this.flowLevel,this.flowLevel?`flow`:`doc`;case`*`:return yield*this.pushUntil(Qc),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||qc(e)||e===`,`)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),`flow`}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===`'`)for(;t!==-1&&this.buffer[t+1]===`'`;)t=this.buffer.indexOf(`'`,t+2);else for(;t!==-1;){let e=0;for(;this.buffer[t-1-e]===`\\`;)e+=1;if(e%2==0)break;t=this.buffer.indexOf(`"`,t+1)}let n=this.buffer.substring(0,t),r=n.indexOf(`
149
149
  `,this.pos);if(r!==-1){for(;r!==-1;){let e=this.continueScalar(r+1);if(e===-1)break;r=n.indexOf(`
150
- `,e)}r!==-1&&(t=r-(n[r-1]===`\r`?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(`quoted-scalar`);t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?`flow`:`doc`}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===`+`)this.blockScalarKeep=!0;else if(t>`0`&&t<=`9`)this.blockScalarIndent=Number(t)-1;else if(t!==`-`)break}return yield*this.pushUntil(e=>Jc(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,t=0,n;loop:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case` `:t+=1;break;case`
150
+ `,e)}r!==-1&&(t=r-(n[r-1]===`\r`?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(`quoted-scalar`);t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?`flow`:`doc`}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===`+`)this.blockScalarKeep=!0;else if(t>`0`&&t<=`9`)this.blockScalarIndent=Number(t)-1;else if(t!==`-`)break}return yield*this.pushUntil(e=>qc(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,t=0,n;loop:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case` `:t+=1;break;case`
151
151
  `:e=r,t=0;break;case`\r`:{let e=this.buffer[r+1];if(!e&&!this.atEnd)return this.setNext(`block-scalar`);if(e===`
152
152
  `)break}default:break loop}if(!n&&!this.atEnd)return this.setNext(`block-scalar`);if(t>=this.indentNext){this.indentNext=this.blockScalarIndent===-1?t:this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let t=this.continueScalar(e+1);if(t===-1)break;e=this.buffer.indexOf(`
153
153
  `,t)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext(`block-scalar`);e=this.buffer.length}}let r=e+1;for(n=this.buffer[r];n===` `;)n=this.buffer[++r];if(n===` `){for(;n===` `||n===` `||n===`\r`||n===`
154
154
  `;)n=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let n=e-1,r=this.buffer[n];r===`\r`&&(r=this.buffer[--n]);let i=n;for(;r===` `;)r=this.buffer[--n];if(r===`
155
- `&&n>=this.pos&&n+1+t>i)e=n;else break}while(!0);return yield``,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===`:`){let r=this.buffer[n+1];if(Jc(r)||e&&Zc.has(r))break;t=n}else if(Jc(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
155
+ `&&n>=this.pos&&n+1+t>i)e=n;else break}while(!0);return yield``,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===`:`){let r=this.buffer[n+1];if(qc(r)||e&&Xc.has(r))break;t=n}else if(qc(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
156
156
  `?(n+=1,r=`
157
- `,i=this.buffer[n+1]):t=n),i===`#`||e&&Zc.has(i))break;if(r===`
158
- `){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&Zc.has(r))break;t=n}return!r&&!this.atEnd?this.setNext(`plain-scalar`):(yield``,yield*this.pushToIndex(t+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil($c),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(Jc(n)||t&&Zc.has(n)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!Jc(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(Xc.has(t))t=this.buffer[++e];else if(t===`%`&&Yc.has(this.buffer[e+1])&&Yc.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
157
+ `,i=this.buffer[n+1]):t=n),i===`#`||e&&Xc.has(i))break;if(r===`
158
+ `){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&Xc.has(r))break;t=n}return!r&&!this.atEnd?this.setNext(`plain-scalar`):(yield``,yield*this.pushToIndex(t+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(Qc),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(qc(n)||t&&Xc.has(n)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!qc(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(Yc.has(t))t=this.buffer[++e];else if(t===`%`&&Jc.has(this.buffer[e+1])&&Jc.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
159
159
  `?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
160
- `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}})),nl,rl=R((()=>{nl=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}}}));function il(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function al(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function ol(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function sl(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function cl(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function ll(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function ul(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!il(t.start,`explicit-key-ind`)&&!il(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,ol(t.value)?t.value.end?ll(t.value.end,t.sep):t.value.end=t.sep:ll(t.start,t.sep),delete t.sep)}var dl,fl=R((()=>{qc(),tl(),dl=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new el,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Wc(e);if(!t){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(t===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=t,yield*this.step(),t){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&ul(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&al(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.indent<t.indent))&&(e.type===`document`?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case`directive-line`:yield{type:`directive`,offset:this.offset,source:this.source};return;case`byte-order-mark`:case`space`:case`comment`:case`newline`:yield this.sourceToken;return;case`doc-mode`:case`doc-start`:{let e={type:`document`,offset:this.offset,start:[]};this.type===`doc-start`&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case`doc-start`:al(e.start)===-1?e.start.push(this.sourceToken):(yield*this.pop(),yield*this.step());return;case`anchor`:case`tag`:case`space`:case`comment`:case`newline`:e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===`map-value-ind`){let t=cl(sl(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
160
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}})),tl,nl=z((()=>{tl=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}}}));function rl(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function il(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function al(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function ol(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function sl(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function cl(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function ll(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!rl(t.start,`explicit-key-ind`)&&!rl(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,al(t.value)?t.value.end?cl(t.value.end,t.sep):t.value.end=t.sep:cl(t.start,t.sep),delete t.sep)}var ul,dl=z((()=>{Kc(),el(),ul=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new $c,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Uc(e);if(!t){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(t===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=t,yield*this.step(),t){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&ll(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&il(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.indent<t.indent))&&(e.type===`document`?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case`directive-line`:yield{type:`directive`,offset:this.offset,source:this.source};return;case`byte-order-mark`:case`space`:case`comment`:case`newline`:yield this.sourceToken;return;case`doc-mode`:case`doc-start`:{let e={type:`document`,offset:this.offset,start:[]};this.type===`doc-start`&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case`doc-start`:il(e.start)===-1?e.start.push(this.sourceToken):(yield*this.pop(),yield*this.step());return;case`anchor`:case`tag`:case`space`:case`comment`:case`newline`:e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===`map-value-ind`){let t=sl(ol(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
161
161
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
162
- `,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){ll(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(il(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=cl(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(il(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(ol(t.key)&&!il(t.sep,`newline`)){let e=cl(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):il(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!il(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){ll(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||il(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=cl(sl(t));ul(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
162
+ `,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){cl(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(rl(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=sl(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(rl(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(al(t.key)&&!rl(t.sep,`newline`)){let e=sl(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):rl(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!rl(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){cl(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||rl(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=sl(ol(t));ll(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
163
163
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
164
- `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=cl(sl(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=cl(sl(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}}));function pl(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new nl||null,prettyErrors:t}}function ml(e,t={}){let{lineCounter:n,prettyErrors:r}=pl(t),i=new dl(n?.addNewLine),a=new Cc(t),o=Array.from(a.compose(i.parse(e)));if(r&&n)for(let t of o)t.errors.forEach(Ts(e,n)),t.warnings.forEach(Ts(e,n));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function hl(e,t={}){let{lineCounter:n,prettyErrors:r}=pl(t),i=new dl(n?.addNewLine),a=new Cc(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new Cs(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(Ts(e,n)),o.warnings.forEach(Ts(e,n))),o}function gl(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let i=hl(e,n);if(!i)return null;if(i.warnings.forEach(e=>wa(i.options.logLevel,e)),i.errors.length>0){if(i.options.logLevel!==`silent`)throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function _l(e,t,n){let r=null;if(typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n==`string`&&(n=n.length),typeof n==`number`){let e=Math.round(n);n=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=n??t??{};if(!e)return}return ii(e)&&!r?e.toString(n):new bs(e,r,n).toString(n)}var vl=R((()=>{wc(),xs(),Es(),Ta(),ui(),rl(),fl()})),yl=at({Alias:()=>Ri,CST:()=>Hc,Composer:()=>Cc,Document:()=>bs,Lexer:()=>el,LineCounter:()=>nl,Pair:()=>La,Parser:()=>dl,Scalar:()=>B,Schema:()=>hs,YAMLError:()=>Ss,YAMLMap:()=>Ga,YAMLParseError:()=>Cs,YAMLSeq:()=>Xa,YAMLWarning:()=>ws,isAlias:()=>ri,isCollection:()=>Jr,isDocument:()=>ii,isMap:()=>ai,isNode:()=>Yr,isPair:()=>oi,isScalar:()=>si,isSeq:()=>ci,parse:()=>gl,parseAllDocuments:()=>ml,parseDocument:()=>hl,stringify:()=>_l,visit:()=>di,visitAsync:()=>pi}),bl=R((()=>{wc(),xs(),gs(),Es(),zi(),ui(),Ra(),Vi(),Ka(),Za(),qc(),tl(),rl(),fl(),vl(),xi()})),xl=at({Alias:()=>Ri,CST:()=>Hc,Composer:()=>Cc,Document:()=>bs,Lexer:()=>el,LineCounter:()=>nl,Pair:()=>La,Parser:()=>dl,Scalar:()=>B,Schema:()=>hs,YAMLError:()=>Ss,YAMLMap:()=>Ga,YAMLParseError:()=>Cs,YAMLSeq:()=>Xa,YAMLWarning:()=>ws,default:()=>Sl,isAlias:()=>ri,isCollection:()=>Jr,isDocument:()=>ii,isMap:()=>ai,isNode:()=>Yr,isPair:()=>oi,isScalar:()=>si,isSeq:()=>ci,parse:()=>gl,parseAllDocuments:()=>ml,parseDocument:()=>hl,stringify:()=>_l,visit:()=>di,visitAsync:()=>pi}),Sl,Cl=R((()=>{bl(),bl(),Sl=yl}));async function wl(){return El??=await Promise.resolve().then(()=>(Cl(),xl)),El}function Tl(){return El??=s(import.meta.url)(`yaml`),El}var El,Dl=R((()=>{}));function Ol(e,t=`toon`){if(e==null)return``;if(t===`json`){if(typeof e==`string`){let t=e.trim();if(t.startsWith(`{`)||t.startsWith(`[`))try{return JSON.stringify(JSON.parse(e),null,2)}catch{}}return Gr(e,2)}return t===`yaml`?Tl().stringify(e):t===`md`?Fl(e):t===`jsonl`?Array.isArray(e)?e.map(e=>Gr(e)).join(`
165
- `):Gr(e):kl(e)?String(e):Ir(e)}function kl(e){return typeof e!=`object`||!e}function Al(e){return Object.values(e).every(kl)}function jl(e){return Array.isArray(e)&&e.length>0&&e.every(e=>typeof e==`object`&&!!e&&!Array.isArray(e))}function Ml(e,t){let n=e.map((e,n)=>Math.max(e.length,...t.map(e=>(e[n]??``).length))),r=(e,t)=>e.padEnd(n[t]);return`${`| ${e.map(r).join(` | `)} |`}\n${`|${n.map(e=>`-`.repeat(e+2)).join(`|`)}|`}\n${t.map(t=>`| ${e.map((e,n)=>r(t[n]??``,n)).join(` | `)} |`).join(`
166
- `)}`}function Nl(e){return Ml([`Key`,`Value`],Object.entries(e).map(([e,t])=>[e,String(t)]))}function Pl(e){let t=[...new Set(e.flatMap(Object.keys))];return Ml(t,e.map(e=>t.map(t=>String(e[t]??``))))}function Fl(e,t=[]){if(kl(e))return t.length===0?String(e):`## ${t.join(`.`)}\n\n${String(e)}`;if(Array.isArray(e)){if(jl(e)){let n=Pl(e);return t.length===0?n:`## ${t.join(`.`)}\n\n${n}`}return Fl(String(e),t)}let n=e,r=Object.entries(n);return t.length===0&&Al(n)?Nl(n):t.length>0||r.length>1||r.some(([,e])=>!kl(e))?r.map(([e,n])=>{let r=[...t,e];if(kl(n))return`## ${r.join(`.`)}\n\n${String(n)}`;if(jl(n))return`## ${r.join(`.`)}\n\n${Pl(n)}`;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=n;return Al(e)?`## ${r.join(`.`)}\n\n${Nl(e)}`:Fl(e,r)}return`## ${r.join(`.`)}\n\n${String(n)}`}).join(`
164
+ `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=sl(ol(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=sl(ol(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}}));function fl(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new tl||null,prettyErrors:t}}function pl(e,t={}){let{lineCounter:n,prettyErrors:r}=fl(t),i=new ul(n?.addNewLine),a=new Sc(t),o=Array.from(a.compose(i.parse(e)));if(r&&n)for(let t of o)t.errors.forEach(ws(e,n)),t.warnings.forEach(ws(e,n));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function ml(e,t={}){let{lineCounter:n,prettyErrors:r}=fl(t),i=new ul(n?.addNewLine),a=new Sc(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new Ss(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(ws(e,n)),o.warnings.forEach(ws(e,n))),o}function hl(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let i=ml(e,n);if(!i)return null;if(i.warnings.forEach(e=>Ca(i.options.logLevel,e)),i.errors.length>0){if(i.options.logLevel!==`silent`)throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function gl(e,t,n){let r=null;if(typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n==`string`&&(n=n.length),typeof n==`number`){let e=Math.round(n);n=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=n??t??{};if(!e)return}return ri(e)&&!r?e.toString(n):new ys(e,r,n).toString(n)}var _l=z((()=>{Cc(),bs(),Ts(),wa(),li(),nl(),dl()})),vl=it({Alias:()=>Li,CST:()=>Vc,Composer:()=>Sc,Document:()=>ys,Lexer:()=>$c,LineCounter:()=>tl,Pair:()=>Ia,Parser:()=>ul,Scalar:()=>V,Schema:()=>ms,YAMLError:()=>xs,YAMLMap:()=>Wa,YAMLParseError:()=>Ss,YAMLSeq:()=>Ya,YAMLWarning:()=>Cs,isAlias:()=>ni,isCollection:()=>qr,isDocument:()=>ri,isMap:()=>ii,isNode:()=>Jr,isPair:()=>ai,isScalar:()=>oi,isSeq:()=>si,parse:()=>hl,parseAllDocuments:()=>pl,parseDocument:()=>ml,stringify:()=>gl,visit:()=>ui,visitAsync:()=>fi}),yl=z((()=>{Cc(),bs(),hs(),Ts(),Ri(),li(),La(),Bi(),Ga(),Xa(),Kc(),el(),nl(),dl(),_l(),bi()})),bl=it({Alias:()=>Li,CST:()=>Vc,Composer:()=>Sc,Document:()=>ys,Lexer:()=>$c,LineCounter:()=>tl,Pair:()=>Ia,Parser:()=>ul,Scalar:()=>V,Schema:()=>ms,YAMLError:()=>xs,YAMLMap:()=>Wa,YAMLParseError:()=>Ss,YAMLSeq:()=>Ya,YAMLWarning:()=>Cs,default:()=>xl,isAlias:()=>ni,isCollection:()=>qr,isDocument:()=>ri,isMap:()=>ii,isNode:()=>Jr,isPair:()=>ai,isScalar:()=>oi,isSeq:()=>si,parse:()=>hl,parseAllDocuments:()=>pl,parseDocument:()=>ml,stringify:()=>gl,visit:()=>ui,visitAsync:()=>fi}),xl,Sl=z((()=>{yl(),yl(),xl=vl}));async function Cl(){return Tl??=await Promise.resolve().then(()=>(Sl(),bl)),Tl}function wl(){return Tl??=s(import.meta.url)(`yaml`),Tl}var Tl,El=z((()=>{}));function Dl(e,t=`toon`){if(e==null)return``;if(t===`json`){if(typeof e==`string`){let t=e.trim();if(t.startsWith(`{`)||t.startsWith(`[`))try{return JSON.stringify(JSON.parse(e),null,2)}catch{}}return Wr(e,2)}return t===`yaml`?wl().stringify(e):t===`md`?Pl(e):t===`jsonl`?Array.isArray(e)?e.map(e=>Wr(e)).join(`
165
+ `):Wr(e):Ol(e)?String(e):Fr(e)}function Ol(e){return typeof e!=`object`||!e}function kl(e){return Object.values(e).every(Ol)}function Al(e){return Array.isArray(e)&&e.length>0&&e.every(e=>typeof e==`object`&&!!e&&!Array.isArray(e))}function jl(e,t){let n=e.map((e,n)=>Math.max(e.length,...t.map(e=>(e[n]??``).length))),r=(e,t)=>e.padEnd(n[t]);return`${`| ${e.map(r).join(` | `)} |`}\n${`|${n.map(e=>`-`.repeat(e+2)).join(`|`)}|`}\n${t.map(t=>`| ${e.map((e,n)=>r(t[n]??``,n)).join(` | `)} |`).join(`
166
+ `)}`}function Ml(e){return jl([`Key`,`Value`],Object.entries(e).map(([e,t])=>[e,String(t)]))}function Nl(e){let t=[...new Set(e.flatMap(Object.keys))];return jl(t,e.map(e=>t.map(t=>String(e[t]??``))))}function Pl(e,t=[]){if(Ol(e))return t.length===0?String(e):`## ${t.join(`.`)}\n\n${String(e)}`;if(Array.isArray(e)){if(Al(e)){let n=Nl(e);return t.length===0?n:`## ${t.join(`.`)}\n\n${n}`}return Pl(String(e),t)}let n=e,r=Object.entries(n);return t.length===0&&kl(n)?Ml(n):t.length>0||r.length>1||r.some(([,e])=>!Ol(e))?r.map(([e,n])=>{let r=[...t,e];if(Ol(n))return`## ${r.join(`.`)}\n\n${String(n)}`;if(Al(n))return`## ${r.join(`.`)}\n\n${Nl(n)}`;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=n;return kl(e)?`## ${r.join(`.`)}\n\n${Ml(e)}`:Pl(e,r)}return`## ${r.join(`.`)}\n\n${String(n)}`}).join(`
167
167
 
168
- `):Nl(n)}var Il=R((()=>{Wr(),qr(),Dl()}));function Ll(e,t={}){let{args:n,options:r,alias:i,defaults:a}=t,o=Rl(r,i),s=[],c={},l=0;for(;l<e.length;){let t=e[l];if(t.startsWith(`--no-`)&&t.length>5){let e=zl(t.slice(5),o);if(!e)throw new Nn({message:`Unknown flag: ${t}`});c[e]=!1,l++}else if(t.startsWith(`--`)){let n=t.indexOf(`=`);if(n!==-1){let e=t.slice(2,n),i=zl(e,o);if(!i)throw new Nn({message:`Unknown flag: --${e}`});Gl(c,i,t.slice(n+1),r),l++}else{let n=zl(t.slice(2),o);if(!n)throw new Nn({message:`Unknown flag: ${t}`});if(Ul(n,r))c[n]=(c[n]??0)+1,l++;else if(Hl(n,r))c[n]=!0,l++;else{let i=e[l+1];if(i===void 0)throw new Nn({message:`Missing value for flag: ${t}`});Gl(c,n,i,r),l+=2}}}else if(t.startsWith(`-`)&&!t.startsWith(`--`)&&t.length>=2){let n=t.slice(1);for(let t=0;t<n.length;t++){let i=n[t],a=o.aliasToName.get(i);if(!a)throw new Nn({message:`Unknown flag: -${i}`});if(t!==n.length-1){if(Ul(a,r))c[a]=(c[a]??0)+1;else if(Hl(a,r))c[a]=!0;else throw new Nn({message:`Non-boolean flag -${i} must be last in a stacked alias`})}else if(Ul(a,r))c[a]=(c[a]??0)+1;else if(Hl(a,r))c[a]=!0;else{let t=e[l+1];if(t===void 0)throw new Nn({message:`Missing value for flag: -${i}`});Gl(c,a,t,r),l++}}l++}else s.push(t),l++}let u={};if(n){let e=Object.keys(n.shape);for(let t=0;t<e.length;t++){let r=e[t];if(Wl(r,n)){if(t!==e.length-1)throw Error(`Variadic arg "${r}" must be the last key in the args schema`);let n=s.slice(t);n.length>0&&(u[r]=n)}else s[t]!==void 0&&(u[r]=s[t])}}let d=n?Kl(n,u):{},f=Bl(a,r,o);if(r)for(let[e,t]of Object.entries(c))c[e]=Xl(t,e,r);let p={...f,...c};return{args:d,options:r?Kl(r,p):{}}}function Rl(e,t){let n=new Map;if(t)for(let[e,r]of Object.entries(t))n.set(r,e);let r=new Set(e?Object.keys(e.shape):[]),i=new Map;for(let e of r){let t=fn(e);t!==e&&i.set(t,e)}return{aliasToName:n,kebabToCamel:i,knownOptions:r}}function zl(e,t){let n=t.kebabToCamel.get(e)??e;return t.knownOptions.has(n)?n:void 0}function Bl(e,t,n){if(e===void 0)return{};if(!dn(e))throw new Nn({message:`Invalid config section: expected an object of option defaults`});if(!t){let[t]=Object.keys(e);if(t)throw new Nn({message:`Unknown config option: ${t}`});return{}}let r={};for(let[t,i]of Object.entries(e)){let e=zl(t,n);if(!e)throw new Nn({message:`Unknown config option: ${t}`});r[e]=i}return r}function Vl(e){let t=e;for(;t.def?.innerType;)t=t.def.innerType;return t}function Hl(e,t){if(!t)return!1;let n=t.shape[e];return n?Vl(n).constructor.name===`ZodBoolean`:!1}function Ul(e,t){if(!t)return!1;let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0:!1}function Wl(e,t){if(!t)return!1;let n=t.shape[e];return n?Vl(n).constructor.name===`ZodArray`:!1}function Gl(e,t,n,r){if(Wl(t,r)){let r=e[t];Array.isArray(r)?r.push(n):e[t]=[n]}else e[t]=n}function Kl(e,t){try{return e.parse(t)}catch(e){let n=e?.issues??e?.error?.issues??[],r=n.map(e=>({code:e.code,missing:!ql(t,e.path??[]),path:(e.path??[]).join(`.`),expected:e.expected??``,received:e.received??``,message:e.message??``}));throw new Mn({message:n.map(e=>e.message).join(`; `)||`Validation failed`,fieldErrors:r,cause:e instanceof Error?e:void 0})}}function ql(e,t){if(t.length===0)return!0;let n=e;for(let e of t){if(!dn(n)&&!Array.isArray(n)||!(e in n))return!1;n=n[e]}return!0}function Jl(e,t=Ql()){let n={};for(let[r,i]of Object.entries(e.shape)){let e=t[r];e!==void 0&&(n[r]=Yl(e,i))}return Kl(e,n)}function Yl(e,t){let n=Vl(t).constructor.name;return n===`ZodNumber`?Number(e):n===`ZodBoolean`?e===`true`||e===`1`:e}function Xl(e,t,n){let r=n.shape[t];if(!r)return e;let i=Vl(r).constructor.name;return i===`ZodNumber`&&typeof e==`string`?Number(e):i===`ZodBoolean`&&typeof e==`string`?e===`true`:e}function Zl(e,t,n,r={}){let i=Rl(t,n),a=[],o={},s=0;for(;s<e.length;){let n=e[s];if(n===`--`){for(let t=s;t<e.length;t++)a.push(e[t]);break}if(n.startsWith(`--no-`)&&n.length>5){let e=zl(n.slice(5),i);e?o[e]=!1:a.push(n),s++}else if(n.startsWith(`--`)){let r=n.indexOf(`=`);if(r!==-1){let e=zl(n.slice(2,r),i);e?Gl(o,e,n.slice(r+1),t):a.push(n),s++}else{let r=zl(n.slice(2),i);if(!r)a.push(n),s++;else if(Ul(r,t))o[r]=(o[r]??0)+1,s++;else if(Hl(r,t))o[r]=!0,s++;else{let i=e[s+1];if(i===void 0)throw new Nn({message:`Missing value for flag: ${n}`});Gl(o,r,i,t),s+=2}}}else if(n.startsWith(`-`)&&!n.startsWith(`--`)&&n.length>=2){let r=n.slice(1),c=!0;for(let e=0;e<r.length;e++)if(!i.aliasToName.has(r[e])){c=!1;break}if(!c)a.push(n),s++;else{for(let n=0;n<r.length;n++){let a=r[n],c=i.aliasToName.get(a);if(n!==r.length-1){if(Ul(c,t))o[c]=(o[c]??0)+1;else if(Hl(c,t))o[c]=!0;else throw new Nn({message:`Non-boolean flag -${a} must be last in a stacked alias`})}else if(Ul(c,t))o[c]=(o[c]??0)+1;else if(Hl(c,t))o[c]=!0;else{let n=e[s+1];if(n===void 0)throw new Nn({message:`Missing value for flag: -${a}`});Gl(o,c,n,t),s++}}s++}}else a.push(n),s++}if(r.validate===!1)return{parsed:o,rest:a};for(let[e,n]of Object.entries(o))o[e]=Xl(n,e,t);return{parsed:Kl(t,o),rest:a}}function Ql(){if(typeof globalThis<`u`){let e=globalThis;if(e.process?.env)return e.process.env;if(e.Deno?.env)return new Proxy({},{get:(t,n)=>e.Deno.env.get(n)})}return{}}var $l=R((()=>{Pn(),hn()}));async function eu(e,t){let{argv:n,inputOptions:r,agent:i,format:a,formatExplicit:o,name:s,path:c,version:l,envSource:u=process.env,env:d,globals:f={},vars:p,middlewares:m=[],request:h}=t,g=t.displayName??s,_=t.parseMode??`argv`,v=p?p.parse({}):{},y,b,x,S,C=new Promise(e=>{S=e}),w=async()=>{let c,d;if(_===`argv`){let r=Ll(n,{alias:e.alias,args:e.args,defaults:t.defaults,options:e.options});c=r.args,d=r.options}else if(_===`split`)c=Ll(n,{args:e.args}).args,d=e.options?Kl(e.options,r):{};else{let t=tu(r,e);c=e.args?Kl(e.args,t.args):{},d=e.options?Kl(e.options,t.options):{}}let p=e.env?Jl(e.env,u):{},C=e.run({agent:i,args:c,displayName:g,env:p,error:e=>({[su]:`error`,...e}),format:a,formatExplicit:o,globals:f,name:s,ok:(e,t={})=>({[su]:`ok`,data:e,cta:t.cta}),options:d,request:h,var:v,version:l});if(ru(C)){if(m.length>0){b=new Promise(e=>{x=e});async function*e(){try{return yield*C}finally{x()}}y={stream:e()},S(),await b}else y={stream:C};return}let w=await C;if(nu(w)){if(w[su]===`ok`){let e=w;y={ok:!0,data:e.data,...e.cta?{cta:e.cta}:void 0}}else{let e=w;y={ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},...e.cta?{cta:e.cta}:void 0,...e.exitCode===void 0?void 0:{exitCode:e.exitCode}}}return}y={ok:!0,data:w}};try{let e=d?Jl(d,u):{};if(m.length>0){let t={agent:i,command:c,displayName:g,env:e,error:e=>{y={ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},...e.cta?{cta:e.cta}:void 0,...e.exitCode===void 0?void 0:{exitCode:e.exitCode}}},format:a,formatExplicit:o,globals:f,name:s,request:h,set(e,t){v[e]=t},var:v,version:l},n=m.reduceRight((e,n)=>async()=>{await n(t,e)},w)();if(await Promise.race([n,C]),b)return y;await n}else await w()}catch(e){return e instanceof Mn?{ok:!1,error:{code:`VALIDATION_ERROR`,message:e.message,fieldErrors:e.fieldErrors}}:{ok:!1,error:{code:e instanceof z?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof z?{retryable:e.retryable}:void 0},...e instanceof z&&e.exitCode!==void 0?{exitCode:e.exitCode}:void 0}}return y??{ok:!0,data:void 0}}function tu(e,t){let n=new Set(t.args?Object.keys(t.args.shape):[]),r={},i={};for(let[t,a]of Object.entries(e))n.has(t)?r[t]=a:i[t]=a;return{args:r,options:i}}function nu(e){return typeof e==`object`&&!!e&&su in e}function ru(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e&&typeof e.next==`function`}function iu(e){return e}function au(e){return lu.find(t=>t.name===e||t.aliases?.includes(e))}function ou(e,t){return e.subcommands?.find(e=>e.name===t||e.aliases?.includes(t))}var su,cu,lu,uu=R((()=>{Pn(),$l(),su=Symbol.for(`incur.sentinel`),cu=[`bash`,`fish`,`nushell`,`zsh`],lu=[{name:`completions`,description:`Generate shell completion script`,args:f.object({shell:f.enum(cu).describe(`Shell to generate completions for`)}),hint(e){let t=[[`bash`,`eval "$(${e} completions bash)"`,`# add to ~/.bashrc`],[`fish`,`${e} completions fish | source`,`# add to ~/.config/fish/config.fish`],[`nushell`,`see \`${e} completions nushell\``,`# add to config.nu`],[`zsh`,`eval "$(${e} completions zsh)"`,`# add to ~/.zshrc`]],n=Math.max(...t.map(e=>e[0].length)),r=Math.max(...t.map(e=>e[1].length));return`Setup:
168
+ `):Ml(n)}var Fl=z((()=>{Ur(),Kr(),El()}));function Il(e,t={}){let{args:n,options:r,alias:i,defaults:a}=t,o=Ll(r,i),s=[],c={},l=0;for(;l<e.length;){let t=e[l];if(t.startsWith(`--no-`)&&t.length>5){let e=Rl(t.slice(5),o);if(!e)throw new Mn({message:`Unknown flag: ${t}`});c[e]=!1,l++}else if(t.startsWith(`--`)){let n=t.indexOf(`=`);if(n!==-1){let e=t.slice(2,n),i=Rl(e,o);if(!i)throw new Mn({message:`Unknown flag: --${e}`});Wl(c,i,t.slice(n+1),r),l++}else{let n=Rl(t.slice(2),o);if(!n)throw new Mn({message:`Unknown flag: ${t}`});if(Hl(n,r))c[n]=(c[n]??0)+1,l++;else if(Vl(n,r))c[n]=!0,l++;else{let i=e[l+1];if(i===void 0)throw new Mn({message:`Missing value for flag: ${t}`});Wl(c,n,i,r),l+=2}}}else if(t.startsWith(`-`)&&!t.startsWith(`--`)&&t.length>=2){let n=t.slice(1);for(let t=0;t<n.length;t++){let i=n[t],a=o.aliasToName.get(i);if(!a)throw new Mn({message:`Unknown flag: -${i}`});if(t!==n.length-1){if(Hl(a,r))c[a]=(c[a]??0)+1;else if(Vl(a,r))c[a]=!0;else throw new Mn({message:`Non-boolean flag -${i} must be last in a stacked alias`})}else if(Hl(a,r))c[a]=(c[a]??0)+1;else if(Vl(a,r))c[a]=!0;else{let t=e[l+1];if(t===void 0)throw new Mn({message:`Missing value for flag: -${i}`});Wl(c,a,t,r),l++}}l++}else s.push(t),l++}let u={};if(n){let e=Object.keys(n.shape);for(let t=0;t<e.length;t++){let r=e[t];if(Ul(r,n)){if(t!==e.length-1)throw Error(`Variadic arg "${r}" must be the last key in the args schema`);let n=s.slice(t);n.length>0&&(u[r]=n)}else s[t]!==void 0&&(u[r]=s[t])}}let d=n?Gl(n,u):{},f=zl(a,r,o);if(r)for(let[e,t]of Object.entries(c))c[e]=Yl(t,e,r);let p={...f,...c};return{args:d,options:r?Gl(r,p):{}}}function Ll(e,t){let n=new Map;if(t)for(let[e,r]of Object.entries(t))n.set(r,e);let r=new Set(e?Object.keys(e.shape):[]),i=new Map;for(let e of r){let t=dn(e);t!==e&&i.set(t,e)}return{aliasToName:n,kebabToCamel:i,knownOptions:r}}function Rl(e,t){let n=t.kebabToCamel.get(e)??e;return t.knownOptions.has(n)?n:void 0}function zl(e,t,n){if(e===void 0)return{};if(!un(e))throw new Mn({message:`Invalid config section: expected an object of option defaults`});if(!t){let[t]=Object.keys(e);if(t)throw new Mn({message:`Unknown config option: ${t}`});return{}}let r={};for(let[t,i]of Object.entries(e)){let e=Rl(t,n);if(!e)throw new Mn({message:`Unknown config option: ${t}`});r[e]=i}return r}function Bl(e){let t=e;for(;t.def?.innerType;)t=t.def.innerType;return t}function Vl(e,t){if(!t)return!1;let n=t.shape[e];return n?Bl(n).constructor.name===`ZodBoolean`:!1}function Hl(e,t){if(!t)return!1;let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0:!1}function Ul(e,t){if(!t)return!1;let n=t.shape[e];return n?Bl(n).constructor.name===`ZodArray`:!1}function Wl(e,t,n,r){if(Ul(t,r)){let r=e[t];Array.isArray(r)?r.push(n):e[t]=[n]}else e[t]=n}function Gl(e,t){try{return e.parse(t)}catch(e){let n=e?.issues??e?.error?.issues??[],r=n.map(e=>({code:e.code,missing:!Kl(t,e.path??[]),path:(e.path??[]).join(`.`),expected:e.expected??``,received:e.received??``,message:e.message??``}));throw new jn({message:n.map(e=>e.message).join(`; `)||`Validation failed`,fieldErrors:r,cause:e instanceof Error?e:void 0})}}function Kl(e,t){if(t.length===0)return!0;let n=e;for(let e of t){if(!un(n)&&!Array.isArray(n)||!(e in n))return!1;n=n[e]}return!0}function ql(e,t=Zl()){let n={};for(let[r,i]of Object.entries(e.shape)){let e=t[r];e!==void 0&&(n[r]=Jl(e,i))}return Gl(e,n)}function Jl(e,t){let n=Bl(t).constructor.name;return n===`ZodNumber`?Number(e):n===`ZodBoolean`?e===`true`||e===`1`:e}function Yl(e,t,n){let r=n.shape[t];if(!r)return e;let i=Bl(r).constructor.name;return i===`ZodNumber`&&typeof e==`string`?Number(e):i===`ZodBoolean`&&typeof e==`string`?e===`true`:e}function Xl(e,t,n,r={}){let i=Ll(t,n),a=[],o={},s=0;for(;s<e.length;){let n=e[s];if(n===`--`){for(let t=s;t<e.length;t++)a.push(e[t]);break}if(n.startsWith(`--no-`)&&n.length>5){let e=Rl(n.slice(5),i);e?o[e]=!1:a.push(n),s++}else if(n.startsWith(`--`)){let r=n.indexOf(`=`);if(r!==-1){let e=Rl(n.slice(2,r),i);e?Wl(o,e,n.slice(r+1),t):a.push(n),s++}else{let r=Rl(n.slice(2),i);if(!r)a.push(n),s++;else if(Hl(r,t))o[r]=(o[r]??0)+1,s++;else if(Vl(r,t))o[r]=!0,s++;else{let i=e[s+1];if(i===void 0)throw new Mn({message:`Missing value for flag: ${n}`});Wl(o,r,i,t),s+=2}}}else if(n.startsWith(`-`)&&!n.startsWith(`--`)&&n.length>=2){let r=n.slice(1),c=!0;for(let e=0;e<r.length;e++)if(!i.aliasToName.has(r[e])){c=!1;break}if(!c)a.push(n),s++;else{for(let n=0;n<r.length;n++){let a=r[n],c=i.aliasToName.get(a);if(n!==r.length-1){if(Hl(c,t))o[c]=(o[c]??0)+1;else if(Vl(c,t))o[c]=!0;else throw new Mn({message:`Non-boolean flag -${a} must be last in a stacked alias`})}else if(Hl(c,t))o[c]=(o[c]??0)+1;else if(Vl(c,t))o[c]=!0;else{let n=e[s+1];if(n===void 0)throw new Mn({message:`Missing value for flag: -${a}`});Wl(o,c,n,t),s++}}s++}}else a.push(n),s++}if(r.validate===!1)return{parsed:o,rest:a};for(let[e,n]of Object.entries(o))o[e]=Yl(n,e,t);return{parsed:Gl(t,o),rest:a}}function Zl(){if(typeof globalThis<`u`){let e=globalThis;if(e.process?.env)return e.process.env;if(e.Deno?.env)return new Proxy({},{get:(t,n)=>e.Deno.env.get(n)})}return{}}var Ql=z((()=>{Nn(),mn()}));async function $l(e,t){let{argv:n,inputOptions:r,agent:i,format:a,formatExplicit:o,name:s,path:c,version:l,envSource:u=process.env,env:d,globals:f={},vars:p,middlewares:m=[],request:h}=t,g=t.displayName??s,_=t.parseMode??`argv`,v=p?p.parse({}):{},y,b,x,S,C=new Promise(e=>{S=e}),w=async()=>{let c,d;if(_===`argv`){let r=Il(n,{alias:e.alias,args:e.args,defaults:t.defaults,options:e.options});c=r.args,d=r.options}else if(_===`split`)c=Il(n,{args:e.args}).args,d=e.options?Gl(e.options,r):{};else{let t=eu(r,e);c=e.args?Gl(e.args,t.args):{},d=e.options?Gl(e.options,t.options):{}}let p=e.env?ql(e.env,u):{},C=e.run({agent:i,args:c,displayName:g,env:p,error:e=>({[ou]:`error`,...e}),format:a,formatExplicit:o,globals:f,name:s,ok:(e,t={})=>({[ou]:`ok`,data:e,cta:t.cta}),options:d,request:h,var:v,version:l});if(nu(C)){if(m.length>0){b=new Promise(e=>{x=e});async function*e(){try{return yield*C}finally{x()}}y={stream:e()},S(),await b}else y={stream:C};return}let w=await C;if(tu(w)){if(w[ou]===`ok`){let e=w;y={ok:!0,data:e.data,...e.cta?{cta:e.cta}:void 0}}else{let e=w;y={ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},...e.cta?{cta:e.cta}:void 0,...e.exitCode===void 0?void 0:{exitCode:e.exitCode}}}return}y={ok:!0,data:w}};try{let e=d?ql(d,u):{};if(m.length>0){let t={agent:i,command:c,displayName:g,env:e,error:e=>{y={ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},...e.cta?{cta:e.cta}:void 0,...e.exitCode===void 0?void 0:{exitCode:e.exitCode}}},format:a,formatExplicit:o,globals:f,name:s,request:h,set(e,t){v[e]=t},var:v,version:l},n=m.reduceRight((e,n)=>async()=>{await n(t,e)},w)();if(await Promise.race([n,C]),b)return y;await n}else await w()}catch(e){return e instanceof jn?{ok:!1,error:{code:`VALIDATION_ERROR`,message:e.message,fieldErrors:e.fieldErrors}}:{ok:!1,error:{code:e instanceof B?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof B?{retryable:e.retryable}:void 0},...e instanceof B&&e.exitCode!==void 0?{exitCode:e.exitCode}:void 0}}return y??{ok:!0,data:void 0}}function eu(e,t){let n=new Set(t.args?Object.keys(t.args.shape):[]),r={},i={};for(let[t,a]of Object.entries(e))n.has(t)?r[t]=a:i[t]=a;return{args:r,options:i}}function tu(e){return typeof e==`object`&&!!e&&ou in e}function nu(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e&&typeof e.next==`function`}function ru(e){return e}function iu(e){return cu.find(t=>t.name===e||t.aliases?.includes(e))}function au(e,t){return e.subcommands?.find(e=>e.name===t||e.aliases?.includes(t))}var ou,su,cu,lu=z((()=>{Nn(),Ql(),ou=Symbol.for(`incur.sentinel`),su=[`bash`,`fish`,`nushell`,`zsh`],cu=[{name:`completions`,description:`Generate shell completion script`,args:f.object({shell:f.enum(su).describe(`Shell to generate completions for`)}),hint(e){let t=[[`bash`,`eval "$(${e} completions bash)"`,`# add to ~/.bashrc`],[`fish`,`${e} completions fish | source`,`# add to ~/.config/fish/config.fish`],[`nushell`,`see \`${e} completions nushell\``,`# add to config.nu`],[`zsh`,`eval "$(${e} completions zsh)"`,`# add to ~/.zshrc`]],n=Math.max(...t.map(e=>e[0].length)),r=Math.max(...t.map(e=>e[1].length));return`Setup:
169
169
  `+t.map(([e,t,i])=>` ${e.padEnd(n)} ${t.padEnd(r)} ${i}`).join(`
170
- `)}},{name:`mcp`,description:`Register as MCP server`,subcommands:[iu({name:`add`,description:`Register as MCP server`,alias:{command:`c`},options:f.object({agent:f.string().optional().describe(`Target a specific agent (e.g. claude-code, cursor)`),command:f.string().optional().describe(`Override the command agents will run (e.g. "pnpm my-cli --mcp")`),noGlobal:f.boolean().optional().describe(`Install to project instead of globally`)})}),iu({name:`doctor`,description:`Validate MCP server startup and tool listing`})]},{name:`skills`,aliases:[`skill`],description:`Sync skill files to agents`,subcommands:[iu({name:`add`,description:`Sync skill files to agents`,options:f.object({depth:f.number().optional().describe(`Grouping depth for skill files (default: 1)`),noGlobal:f.boolean().optional().describe(`Install to project instead of globally`)})}),iu({name:`list`,aliases:[`ls`],description:`List skills`})]}]}));function du(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(...Su(c,r,a)),l.join(`
171
- `)}function fu(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=pu(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=mu(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=gu(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(...Su(f,i,o)),l){let e=hu(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??Ql();n.name in i&&r.push(`set: ${Cu(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
- `)}function pu(e,t){if(!t)return e;let n=[e];for(let[e,r]of Object.entries(t.shape)){let t=_u(r),i=(t.includes(`|`)?t:e)+(t===`array`?`...`:``);n.push(r._zod.optout===`optional`?`[${i}]`:`<${i}>`)}return n.join(` `)}function mu(e){let t=[];for(let[n,r]of Object.entries(e.shape))t.push({name:n,description:r.description??``});return t}function hu(e){let t=[];for(let[n,r]of Object.entries(e.shape)){let e=bu(r);t.push({name:n,description:r.description??``,defaultValue:e})}return t}function gu(e,t){let n=[];for(let[r,i]of Object.entries(e.shape)){let e=_u(i),a=t?.[r],o=fn(r),s=e===`boolean`?``:` <${e}>`,c=a?`--${o}, -${a}${s}`:`--${o}${s}`,l=bu(i);e===`boolean`&&l===!1&&(l=void 0);let u=xu(i);n.push({flag:c,description:i.description??``,defaultValue:l,deprecated:u})}return n}function _u(e){if(vu(e))return`count`;let t=yu(e);if(t instanceof f.ZodString)return`string`;if(t instanceof f.ZodNumber)return`number`;if(t instanceof f.ZodBoolean)return`boolean`;if(t instanceof f.ZodArray)return`array`;if(t instanceof f.ZodEnum)return Object.values(t._zod.def.entries).join(`|`);if(t instanceof f.ZodUnion){let e=t._zod?.def?.options;if(e?.every(e=>e instanceof f.ZodLiteral))return e.map(e=>String(e._zod.def.values[0])).join(`|`)}return`value`}function vu(e){let t=e;return typeof t?.meta==`function`&&t.meta()?.count===!0}function yu(e){return e instanceof f.ZodOptional?yu(e.unwrap()):e instanceof f.ZodDefault?yu(e.removeDefault()):e instanceof f.ZodNullable?yu(e.unwrap()):e}function bu(e){if(e instanceof f.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 f.ZodOptional)return bu(e.unwrap())}function xu(e){return e?.meta?.()?.deprecated===!0||void 0}function Su(e=!1,t,n){let r=[];if(e){let e=lu.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=gu(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 Cu(e){return e.length<=4?`****`:`****${e.slice(-4)}`}var wu=R((()=>{uu(),hn(),$l()}));function Tu(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=>Du(e,t))}}function Eu(e){let t=[e.description];for(let n of e.commands)t.push(` ${n.command}${n.description?` - ${n.description}`:``}`);return t.join(`
173
- `)}function Du(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 Ou=R((()=>{}));async function ku(e,t={}){let n=[],r=t.exclude?c.resolve(t.exclude):void 0;async function i(e,t){let a=await w.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=c.join(e,o.name);if(o.isDirectory()){Mu(o.name,a),await i(a,[...t,o.name]);continue}if(!o.isFile()||a===r)continue;let s=Nu.find(e=>o.name.endsWith(e));if(!s)continue;let l=o.name.slice(0,-s.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}Mu(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 Au(){return globalThis[Symbol.for(Fu)]?.shift()}async function ju(e){return Promise.all(e.map(async({load:e,...t})=>({...t,command:await e()})))}function Mu(e,t){if(!Pu.test(e))throw Error(`Invalid filesystem command segment '${e}' from '${t}'. Use lowercase kebab-case names.`)}var Nu,Pu,Fu,Iu=R((()=>{Nu=[`.cts`,`.cjs`,`.mts`,`.mjs`,`.ts`,`.js`],Pu=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Fu=`incur.fs.manifests`}));function Lu(e){let t=f.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 Ru=R((()=>{}));function zu(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(!zu(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(!zu(e[r],t[r]))return!1;return!0}return e===t}var Bu=R((()=>{}));function Vu(e){return encodeURI(Hu(e))}function Hu(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var Uu=R((()=>{}));function Wu(e,t=Object.create(null),n=Ju,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:Wu(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(qu[i])continue;let a=`${r}/${Vu(i)}`,o=e[i];if(Array.isArray(o)){if(Gu[i]){let e=o.length;for(let r=0;r<e;r++)Wu(o[r],t,n,`${a}/${r}`)}}else if(Ku[i])for(let e in o)Wu(o[e],t,n,`${a}/${Vu(e)}`);else Wu(o,t,n,a)}return t}var Gu,Ku,qu,Ju,Yu=R((()=>{Uu(),Gu={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Ku={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},qu={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},Ju=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 Xu(e){return e.test.bind(e)}function Zu(e){return e%4==0&&(e%100!=0||e%400==0)}function Qu(e){let t=e.match(rd);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&Zu(n)?29:id[r])}function $u(e,t){let n=t.match(ad);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 ed(e){let t=e.split(yd);return t.length==2&&Qu(t[0])&&$u(!0,t[1])}function td(e){return bd.test(e)&&xd.test(e)}function nd(e){if(Sd.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}var rd,id,ad,od,sd,cd,ld,ud,dd,fd,pd,md,hd,gd,_d,vd,yd,bd,xd,Sd,Cd=R((()=>{rd=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,id=[0,31,28,31,30,31,30,31,31,30,31,30,31],ad=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,od=/^(?=.{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,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=/^(?:(?:[^\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,ld=/^(?:(?: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,ud=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,dd=/^(?:\/(?:[^~/]|~0|~1)*)*$/,fd=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,pd=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,md=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))},hd=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,gd=/^((([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,_d=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)),vd={date:Qu,time:$u.bind(void 0,!1),"date-time":ed,duration:_d,uri:td,"uri-reference":Xu(sd),"uri-template":Xu(cd),url:Xu(ld),email:md,hostname:Xu(od),ipv4:Xu(hd),ipv6:Xu(gd),regex:nd,uuid:Xu(ud),"json-pointer":Xu(dd),"json-pointer-uri-fragment":Xu(fd),"relative-json-pointer":Xu(pd)},yd=/t|\s/i,bd=/\/|:/,xd=/^(?:[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,Sd=/[^\\]\\Z/})),wd=R((()=>{}));function Td(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 Ed=R((()=>{}));function Dd(e,t,n=`2019-09`,r=Wu(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:te,additionalProperties:E,unevaluatedProperties:D,minProperties:O,maxProperties:k,propertyNames:A,dependentRequired:ne,dependentSchemas:j,dependencies:re,prefixItems:M,items:N,additionalItems:ie,unevaluatedItems:ae,contains:oe,minContains:P,maxContains:se,minItems:ce,maxItems:F,uniqueItems:le,minimum:I,maximum:ue,exclusiveMinimum:de,exclusiveMaximum:fe,multipleOf:pe,minLength:me,maxLength:he,pattern:ge,__absolute_ref__:_e,__absolute_recursive_ref__:ve}=t,L=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[ve]:a,u=`${s}/$recursiveRef`,d=Dd(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||L.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[_e||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw _e&&_e!==d&&(e+=` Absolute URI "${_e}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
174
- - `)}`,Error(e)}let l=`${s}/$ref`,u=Dd(e,t,n,r,i,a,o,l,c);if(u.valid||L.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:L.length===0,errors:L}}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||L.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)&&L.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&L.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?zu(e,h)||L.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&L.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=>zu(e,t))||L.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||L.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`;Dd(e,v,n,r,i,a,o,t).valid&&L.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let ye=[];if(y!==void 0){let t=`${s}/anyOf`,l=L.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=Dd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);L.push(...f.errors),u||=f.valid,f.valid&&ye.push(d)}u?L.length=l:L.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=L.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=Dd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);L.push(...f.errors),u&&=f.valid,f.valid&&ye.push(d)}u?L.length=l:L.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=L.length,u=x.filter((s,l)=>{let u=Object.create(c),d=Dd(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return L.push(...d.errors),d.valid&&ye.push(u),d.valid}).length;u===1?L.length=l:L.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,...ye),S!==void 0){let t=`${s}/if`;if(Dd(e,S,n,r,i,a,o,t,c).valid){if(C!==void 0){let l=Dd(e,C,n,r,i,a,o,`${s}/then`,c);l.valid||L.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(w!==void 0){let l=Dd(e,w,n,r,i,a,o,`${s}/else`,c);l.valid||L.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||L.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(O!==void 0&&t.length<O&&L.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${O} properties.`}),k!==void 0&&t.length>k&&L.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${k} properties.`}),A!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${Vu(s)}`,c=Dd(s,A,n,r,i,a,e,t);c.valid||L.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||L.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=Dd(e,j[t],n,r,i,a,o,`${l}/${Vu(t)}`,c);s.valid||L.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(re!==void 0){let t=`${s}/dependencies`;for(let s in re)if(s in e){let c=re[s];if(Array.isArray(c))for(let n of c)n in e||L.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=Dd(e,c,n,r,i,a,o,`${t}/${Vu(s)}`);l.valid||L.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}/${Vu(s)}`,f=Dd(e[s],ee[s],n,r,i,a,d,`${t}/${Vu(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,L.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&te!==void 0){let t=`${s}/patternProperties`;for(let s in te){let d=new RegExp(s,`u`),f=te[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${Vu(p)}`,h=Dd(e[p],f,n,r,i,a,m,`${t}/${Vu(s)}`);h.valid?c[p]=l[p]=!0:(u=i,L.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&E!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${Vu(s)}`,f=Dd(e[s],E,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,L.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&D!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${Vu(s)}`,u=Dd(e[s],D,n,r,i,a,l,t);u.valid?c[s]=!0:L.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){F!==void 0&&e.length>F&&L.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${F}).`}),ce!==void 0&&e.length<ce&&L.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${ce}).`});let t=e.length,l=0,u=!1;if(M!==void 0){let d=`${s}/prefixItems`,f=Math.min(M.length,t);for(;l<f;l++){let t=Dd(e[l],M[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,L.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(N!==void 0){let d=`${s}/items`;if(Array.isArray(N)){let s=Math.min(N.length,t);for(;l<s;l++){let t=Dd(e[l],N[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,L.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=Dd(e[l],N,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,L.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ie!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=Dd(e[l],ie,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,L.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(oe!==void 0){if(t===0&&P===void 0)L.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(P!==void 0&&t<P)L.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${P}).`});else{let l=`${s}/contains`,u=L.length,d=0;for(let s=0;s<t;s++){let t=Dd(e[s],oe,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):L.push(...t.errors)}d>=(P||0)&&(L.length=u),P===void 0&&se===void 0&&d===0?L.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):P!==void 0&&d<P?L.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${P} items matching schema. Only ${d} items were found.`}):se!==void 0&&d>se&&L.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${se} items matching schema. ${d} items were found.`})}}if(!u&&ae!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=Dd(e[l],ae,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||L.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(le)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&&zu(r,t))&&(L.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`?(I!==void 0&&(de===!0&&e<=I||e<I)&&L.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${de?`or equal to `:``} ${I}.`}),ue!==void 0&&(fe===!0&&e>=ue||e>ue)&&L.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${fe?`or equal to `:``} ${ue}.`})):(I!==void 0&&e<I&&L.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${I}.`}),ue!==void 0&&e>ue&&L.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${ue}.`}),de!==void 0&&e<=de&&L.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${de}.`}),fe!==void 0&&e>=fe&&L.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${fe}.`})),pe!==void 0){let t=e%pe;Math.abs(0-t)>=1.1920929e-7&&Math.abs(pe-t)>=1.1920929e-7&&L.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${pe}.`})}}else if(u===`string`){let t=me===void 0&&he===void 0?0:Td(e);me!==void 0&&t<me&&L.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${me}).`}),he!==void 0&&t>he&&L.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${he}).`}),ge!==void 0&&!new RegExp(ge,`u`).test(e)&&L.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),T!==void 0&&vd[T]&&!vd[T](e)&&L.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${T}".`})}return{valid:L.length===0,errors:L}}var Od=R((()=>{Bu(),Yu(),Cd(),Uu(),Ed()})),kd,Ad=R((()=>{Yu(),Od(),kd=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Wu(e)}validate(e){return Dd(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Wu(e,this.lookup)}}})),jd=R((()=>{Bu(),Yu(),Cd(),Uu(),wd(),Ed(),Od(),Ad()}));function Md(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Nd({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 Pd(e){return e.title!==void 0&&e.title!==``?e.title:`annotations`in e&&e.annotations?.title?e.annotations.title:e.name}function Fd(e){return Eh[e]}function Id(e){let t={};for(let n of e){let e=n.shape.method.value;t[e]=n}return t}function Ld(e){return Dh[e]}function Rd(e){return Oh[e]}function zd(e){return ep.parse(e)}function Bd(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Vd(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}function Hd(e,t){return D.safeParse(e,t)}function Ud(e){return e===`completed`||e===`failed`||e===`cancelled`}function Wd(e){if(!e)return;let{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}=e;return{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}}function Gd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Kd(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]=Gd(a)&&Gd(i)?{...a,...i}:i}return n}async function qd(e){let t=[];for await(let n of e)t.push(n);return t}async function Jd(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 Yd(e){return ep.parse(JSON.parse(e))}function Xd(e){return JSON.stringify(e)+`
175
- `}function Zd(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`),!Vh.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 Qd(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 $d(e){let t=Zd(e);return Qd(e,t.warnings),t.isValid}function ef(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function tf(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...ef(t.headers),...ef(r.headers)}:t.headers}):e}function nf(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 rf(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function af(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>rf(e)).join(`, `)}:{success:!0,data:n.value}}function of(e){let t=nf(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 sf(){let e=new l_.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,u_.default)(e),e}function cf(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 lf,uf,df,ff,pf,mf,V,hf,gf,_f,vf,yf,H,bf,xf,Sf,Cf,wf,Tf,Ef,Df,Of,kf,Af,jf,Mf,Nf,Pf,U,W,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,Ph,Fh,Ih,Lh,Rh,zh,Bh,Vh,Hh,Uh,Wh,Gh,Kh,qh,Jh,G,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,Qg,$g,e_,t_,n_,r_,i_,a_,o_,s_,c_,l_,u_,d_,f_,p_=R((()=>{jd(),lf=Object.create,uf=Object.defineProperty,df=Object.getOwnPropertyDescriptor,ff=Object.getOwnPropertyNames,pf=Object.getPrototypeOf,mf=Object.prototype.hasOwnProperty,V=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),hf=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=ff(t),a=0,o=i.length,s;a<o;a++)s=i[a],!mf.call(e,s)&&s!==n&&uf(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=df(t,s))||r.enumerable});return e},gf=(e,t,n)=>(n=e==null?{}:lf(pf(e)),hf(t||!e||!e.__esModule?uf(n,`default`,{value:e,enumerable:!0}):n,e)),_f=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}({}),vf=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)}},yf=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`}},bf=D.url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:D.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),D.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`}),D.looseObject({resource:D.string().url(),authorization_servers:D.array(bf).optional(),jwks_uri:D.string().url().optional(),scopes_supported:D.array(D.string()).optional(),bearer_methods_supported:D.array(D.string()).optional(),resource_signing_alg_values_supported:D.array(D.string()).optional(),resource_name:D.string().optional(),resource_documentation:D.string().optional(),resource_policy_uri:D.string().url().optional(),resource_tos_uri:D.string().url().optional(),tls_client_certificate_bound_access_tokens:D.boolean().optional(),authorization_details_types_supported:D.array(D.string()).optional(),dpop_signing_alg_values_supported:D.array(D.string()).optional(),dpop_bound_access_tokens_required:D.boolean().optional()}),xf=D.looseObject({issuer:D.string(),authorization_endpoint:bf,token_endpoint:bf,registration_endpoint:bf.optional(),scopes_supported:D.array(D.string()).optional(),response_types_supported:D.array(D.string()),response_modes_supported:D.array(D.string()).optional(),grant_types_supported:D.array(D.string()).optional(),token_endpoint_auth_methods_supported:D.array(D.string()).optional(),token_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),service_documentation:bf.optional(),revocation_endpoint:bf.optional(),revocation_endpoint_auth_methods_supported:D.array(D.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),introspection_endpoint:D.string().optional(),introspection_endpoint_auth_methods_supported:D.array(D.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),code_challenge_methods_supported:D.array(D.string()).optional(),client_id_metadata_document_supported:D.boolean().optional()}),Sf=D.looseObject({issuer:D.string(),authorization_endpoint:bf,token_endpoint:bf,userinfo_endpoint:bf.optional(),jwks_uri:bf,registration_endpoint:bf.optional(),scopes_supported:D.array(D.string()).optional(),response_types_supported:D.array(D.string()),response_modes_supported:D.array(D.string()).optional(),grant_types_supported:D.array(D.string()).optional(),acr_values_supported:D.array(D.string()).optional(),subject_types_supported:D.array(D.string()),id_token_signing_alg_values_supported:D.array(D.string()),id_token_encryption_alg_values_supported:D.array(D.string()).optional(),id_token_encryption_enc_values_supported:D.array(D.string()).optional(),userinfo_signing_alg_values_supported:D.array(D.string()).optional(),userinfo_encryption_alg_values_supported:D.array(D.string()).optional(),userinfo_encryption_enc_values_supported:D.array(D.string()).optional(),request_object_signing_alg_values_supported:D.array(D.string()).optional(),request_object_encryption_alg_values_supported:D.array(D.string()).optional(),request_object_encryption_enc_values_supported:D.array(D.string()).optional(),token_endpoint_auth_methods_supported:D.array(D.string()).optional(),token_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),display_values_supported:D.array(D.string()).optional(),claim_types_supported:D.array(D.string()).optional(),claims_supported:D.array(D.string()).optional(),service_documentation:D.string().optional(),claims_locales_supported:D.array(D.string()).optional(),ui_locales_supported:D.array(D.string()).optional(),claims_parameter_supported:D.boolean().optional(),request_parameter_supported:D.boolean().optional(),request_uri_parameter_supported:D.boolean().optional(),require_request_uri_registration:D.boolean().optional(),op_policy_uri:bf.optional(),op_tos_uri:bf.optional(),client_id_metadata_document_supported:D.boolean().optional()}),D.object({...Sf.shape,...xf.pick({code_challenge_methods_supported:!0}).shape}),D.object({access_token:D.string(),id_token:D.string().optional(),token_type:D.string(),expires_in:D.coerce.number().optional(),scope:D.string().optional(),refresh_token:D.string().optional()}).strip(),D.object({issued_token_type:D.literal(`urn:ietf:params:oauth:token-type:id-jag`),access_token:D.string(),token_type:D.string().optional(),expires_in:D.number().optional(),scope:D.string().optional()}).strip(),D.object({error:D.string(),error_description:D.string().optional(),error_uri:D.string().optional()}),Cf=bf.optional().or(D.literal(``).transform(()=>void 0)),wf=D.object({redirect_uris:D.array(bf),token_endpoint_auth_method:D.string().optional(),grant_types:D.array(D.string()).optional(),response_types:D.array(D.string()).optional(),client_name:D.string().optional(),client_uri:bf.optional(),logo_uri:Cf,scope:D.string().optional(),contacts:D.array(D.string()).optional(),tos_uri:Cf,policy_uri:D.string().optional(),jwks_uri:bf.optional(),jwks:D.any().optional(),software_id:D.string().optional(),software_version:D.string().optional(),software_statement:D.string().optional()}).strip(),Tf=D.object({client_id:D.string(),client_secret:D.string().optional(),client_id_issued_at:D.number().optional(),client_secret_expires_at:D.number().optional()}).strip(),wf.merge(Tf),D.object({error:D.string(),error_description:D.string().optional()}).strip(),D.object({token:D.string(),token_type_hint:D.string().optional()}).strip(),Ef=`2025-11-25`,Df=`2025-03-26`,Of=[Ef,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],kf=`io.modelcontextprotocol/related-task`,Af=-32700,jf=-32600,Mf=-32601,Nf=-32602,Pf=-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 Ff(e.elicitations,n)}return new e(t,n,r)}},Ff=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??[]}},If=D.lazy(()=>D.union([D.string(),D.number(),D.boolean(),D.null(),D.record(D.string(),If),D.array(If)])),Lf=D.record(D.string(),If),D.array(If),Rf=D.union([D.string(),D.number().int()]),zf=D.string(),D.looseObject({ttl:D.number().optional(),pollInterval:D.number().optional()}),Bf=D.object({ttl:D.number().optional()}),Vf=D.object({taskId:D.string()}),Hf=D.looseObject({progressToken:Rf.optional(),[kf]:Vf.optional()}),Uf=D.object({_meta:Hf.optional()}),Wf=Uf.extend({task:Bf.optional()}),Gf=D.object({method:D.string(),params:Uf.loose().optional()}),Kf=D.object({_meta:Hf.optional()}),qf=D.object({method:D.string(),params:Kf.loose().optional()}),Jf=D.looseObject({_meta:Hf.optional()}),Yf=D.union([D.string(),D.number().int()]),Xf=D.object({jsonrpc:D.literal(`2.0`),id:Yf,...Gf.shape}).strict(),Zf=D.object({jsonrpc:D.literal(`2.0`),...qf.shape}).strict(),Qf=D.object({jsonrpc:D.literal(`2.0`),id:Yf,result:Jf}).strict(),$f=D.object({jsonrpc:D.literal(`2.0`),id:Yf.optional(),error:D.object({code:D.number().int(),message:D.string(),data:D.unknown().optional()})}).strict(),ep=D.union([Xf,Zf,Qf,$f]),D.union([Qf,$f]),tp=Jf.strict(),np=Kf.extend({requestId:Yf.optional(),reason:D.string().optional()}),rp=qf.extend({method:D.literal(`notifications/cancelled`),params:np}),ip=D.object({src:D.string(),mimeType:D.string().optional(),sizes:D.array(D.string()).optional(),theme:D.enum([`light`,`dark`]).optional()}),ap=D.object({icons:D.array(ip).optional()}),op=D.object({name:D.string(),title:D.string().optional()}),sp=op.extend({...op.shape,...ap.shape,version:D.string(),websiteUrl:D.string().optional(),description:D.string().optional()}),cp=D.intersection(D.object({applyDefaults:D.boolean().optional()}),Lf),lp=D.preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,D.intersection(D.object({form:cp.optional(),url:Lf.optional()}),Lf.optional())),up=D.looseObject({list:Lf.optional(),cancel:Lf.optional(),requests:D.looseObject({sampling:D.looseObject({createMessage:Lf.optional()}).optional(),elicitation:D.looseObject({create:Lf.optional()}).optional()}).optional()}),dp=D.looseObject({list:Lf.optional(),cancel:Lf.optional(),requests:D.looseObject({tools:D.looseObject({call:Lf.optional()}).optional()}).optional()}),fp=D.object({experimental:D.record(D.string(),Lf).optional(),sampling:D.object({context:Lf.optional(),tools:Lf.optional()}).optional(),elicitation:lp.optional(),roots:D.object({listChanged:D.boolean().optional()}).optional(),tasks:up.optional(),extensions:D.record(D.string(),Lf).optional()}),pp=Uf.extend({protocolVersion:D.string(),capabilities:fp,clientInfo:sp}),mp=Gf.extend({method:D.literal(`initialize`),params:pp}),hp=D.object({experimental:D.record(D.string(),Lf).optional(),logging:Lf.optional(),completions:Lf.optional(),prompts:D.object({listChanged:D.boolean().optional()}).optional(),resources:D.object({subscribe:D.boolean().optional(),listChanged:D.boolean().optional()}).optional(),tools:D.object({listChanged:D.boolean().optional()}).optional(),tasks:dp.optional(),extensions:D.record(D.string(),Lf).optional()}),gp=Jf.extend({protocolVersion:D.string(),capabilities:hp,serverInfo:sp,instructions:D.string().optional()}),_p=qf.extend({method:D.literal(`notifications/initialized`),params:Kf.optional()}),vp=Gf.extend({method:D.literal(`ping`),params:Uf.optional()}),yp=D.object({progress:D.number(),total:D.optional(D.number()),message:D.optional(D.string())}),bp=D.object({...Kf.shape,...yp.shape,progressToken:Rf}),xp=qf.extend({method:D.literal(`notifications/progress`),params:bp}),Sp=Uf.extend({cursor:zf.optional()}),Cp=Gf.extend({params:Sp.optional()}),wp=Jf.extend({nextCursor:zf.optional()}),Tp=D.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Ep=D.object({taskId:D.string(),status:Tp,ttl:D.union([D.number(),D.null()]),createdAt:D.string(),lastUpdatedAt:D.string(),pollInterval:D.optional(D.number()),statusMessage:D.optional(D.string())}),Dp=Jf.extend({task:Ep}),Op=Kf.merge(Ep),kp=qf.extend({method:D.literal(`notifications/tasks/status`),params:Op}),Ap=Gf.extend({method:D.literal(`tasks/get`),params:Uf.extend({taskId:D.string()})}),jp=Jf.merge(Ep),Mp=Gf.extend({method:D.literal(`tasks/result`),params:Uf.extend({taskId:D.string()})}),Np=Jf.loose(),Pp=Cp.extend({method:D.literal(`tasks/list`)}),Fp=wp.extend({tasks:D.array(Ep)}),Ip=Gf.extend({method:D.literal(`tasks/cancel`),params:Uf.extend({taskId:D.string()})}),Lp=Jf.merge(Ep),Rp=D.object({uri:D.string(),mimeType:D.optional(D.string()),_meta:D.record(D.string(),D.unknown()).optional()}),zp=Rp.extend({text:D.string()}),Bp=D.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Vp=Rp.extend({blob:Bp}),Hp=D.enum([`user`,`assistant`]),Up=D.object({audience:D.array(Hp).optional(),priority:D.number().min(0).max(1).optional(),lastModified:D.iso.datetime({offset:!0}).optional()}),Wp=D.object({...op.shape,...ap.shape,uri:D.string(),description:D.optional(D.string()),mimeType:D.optional(D.string()),size:D.optional(D.number()),annotations:Up.optional(),_meta:D.optional(D.looseObject({}))}),Gp=D.object({...op.shape,...ap.shape,uriTemplate:D.string(),description:D.optional(D.string()),mimeType:D.optional(D.string()),annotations:Up.optional(),_meta:D.optional(D.looseObject({}))}),Kp=Cp.extend({method:D.literal(`resources/list`)}),qp=wp.extend({resources:D.array(Wp)}),Jp=Cp.extend({method:D.literal(`resources/templates/list`)}),Yp=wp.extend({resourceTemplates:D.array(Gp)}),Xp=Uf.extend({uri:D.string()}),Zp=Xp,Qp=Gf.extend({method:D.literal(`resources/read`),params:Zp}),$p=Jf.extend({contents:D.array(D.union([zp,Vp]))}),em=qf.extend({method:D.literal(`notifications/resources/list_changed`),params:Kf.optional()}),tm=Xp,nm=Gf.extend({method:D.literal(`resources/subscribe`),params:tm}),rm=Xp,im=Gf.extend({method:D.literal(`resources/unsubscribe`),params:rm}),am=Kf.extend({uri:D.string()}),om=qf.extend({method:D.literal(`notifications/resources/updated`),params:am}),sm=D.object({name:D.string(),description:D.optional(D.string()),required:D.optional(D.boolean())}),cm=D.object({...op.shape,...ap.shape,description:D.optional(D.string()),arguments:D.optional(D.array(sm)),_meta:D.optional(D.looseObject({}))}),lm=Cp.extend({method:D.literal(`prompts/list`)}),um=wp.extend({prompts:D.array(cm)}),dm=Uf.extend({name:D.string(),arguments:D.record(D.string(),D.string()).optional()}),fm=Gf.extend({method:D.literal(`prompts/get`),params:dm}),pm=D.object({type:D.literal(`text`),text:D.string(),annotations:Up.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),mm=D.object({type:D.literal(`image`),data:Bp,mimeType:D.string(),annotations:Up.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),hm=D.object({type:D.literal(`audio`),data:Bp,mimeType:D.string(),annotations:Up.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),gm=D.object({type:D.literal(`tool_use`),name:D.string(),id:D.string(),input:D.record(D.string(),D.unknown()),_meta:D.record(D.string(),D.unknown()).optional()}),_m=D.object({type:D.literal(`resource`),resource:D.union([zp,Vp]),annotations:Up.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),vm=Wp.extend({type:D.literal(`resource_link`)}),ym=D.union([pm,mm,hm,vm,_m]),bm=D.object({role:Hp,content:ym}),xm=Jf.extend({description:D.string().optional(),messages:D.array(bm)}),Sm=qf.extend({method:D.literal(`notifications/prompts/list_changed`),params:Kf.optional()}),Cm=D.object({title:D.string().optional(),readOnlyHint:D.boolean().optional(),destructiveHint:D.boolean().optional(),idempotentHint:D.boolean().optional(),openWorldHint:D.boolean().optional()}),wm=D.object({taskSupport:D.enum([`required`,`optional`,`forbidden`]).optional()}),Tm=D.object({...op.shape,...ap.shape,description:D.string().optional(),inputSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),If).optional(),required:D.array(D.string()).optional()}).catchall(D.unknown()),outputSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),If).optional(),required:D.array(D.string()).optional()}).catchall(D.unknown()).optional(),annotations:Cm.optional(),execution:wm.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),Em=Cp.extend({method:D.literal(`tools/list`)}),Dm=wp.extend({tools:D.array(Tm)}),Om=Jf.extend({content:D.array(ym).default([]),structuredContent:D.record(D.string(),D.unknown()).optional(),isError:D.boolean().optional()}),Om.or(Jf.extend({toolResult:D.unknown()})),km=Wf.extend({name:D.string(),arguments:D.record(D.string(),D.unknown()).optional()}),Am=Gf.extend({method:D.literal(`tools/call`),params:km}),jm=qf.extend({method:D.literal(`notifications/tools/list_changed`),params:Kf.optional()}),D.object({autoRefresh:D.boolean().default(!0),debounceMs:D.number().int().nonnegative().default(300)}),Mm=D.enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Nm=Uf.extend({level:Mm}),Pm=Gf.extend({method:D.literal(`logging/setLevel`),params:Nm}),Fm=Kf.extend({level:Mm,logger:D.string().optional(),data:D.unknown()}),Im=qf.extend({method:D.literal(`notifications/message`),params:Fm}),Lm=D.object({name:D.string().optional()}),Rm=D.object({hints:D.array(Lm).optional(),costPriority:D.number().min(0).max(1).optional(),speedPriority:D.number().min(0).max(1).optional(),intelligencePriority:D.number().min(0).max(1).optional()}),zm=D.object({mode:D.enum([`auto`,`required`,`none`]).optional()}),Bm=D.object({type:D.literal(`tool_result`),toolUseId:D.string().describe(`The unique identifier for the corresponding tool call.`),content:D.array(ym).default([]),structuredContent:D.object({}).loose().optional(),isError:D.boolean().optional(),_meta:D.record(D.string(),D.unknown()).optional()}),Vm=D.discriminatedUnion(`type`,[pm,mm,hm]),Hm=D.discriminatedUnion(`type`,[pm,mm,hm,gm,Bm]),Um=D.object({role:Hp,content:D.union([Hm,D.array(Hm)]),_meta:D.record(D.string(),D.unknown()).optional()}),Wm=Wf.extend({messages:D.array(Um),modelPreferences:Rm.optional(),systemPrompt:D.string().optional(),includeContext:D.enum([`none`,`thisServer`,`allServers`]).optional(),temperature:D.number().optional(),maxTokens:D.number().int(),stopSequences:D.array(D.string()).optional(),metadata:Lf.optional(),tools:D.array(Tm).optional(),toolChoice:zm.optional()}),Gm=Gf.extend({method:D.literal(`sampling/createMessage`),params:Wm}),Km=Jf.extend({model:D.string(),stopReason:D.optional(D.enum([`endTurn`,`stopSequence`,`maxTokens`]).or(D.string())),role:Hp,content:Vm}),qm=Jf.extend({model:D.string(),stopReason:D.optional(D.enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(D.string())),role:Hp,content:D.union([Hm,D.array(Hm)])}),Jm=D.object({type:D.literal(`boolean`),title:D.string().optional(),description:D.string().optional(),default:D.boolean().optional()}),Ym=D.object({type:D.literal(`string`),title:D.string().optional(),description:D.string().optional(),minLength:D.number().optional(),maxLength:D.number().optional(),format:D.enum([`email`,`uri`,`date`,`date-time`]).optional(),default:D.string().optional()}),Xm=D.object({type:D.enum([`number`,`integer`]),title:D.string().optional(),description:D.string().optional(),minimum:D.number().optional(),maximum:D.number().optional(),default:D.number().optional()}),Zm=D.object({type:D.literal(`string`),title:D.string().optional(),description:D.string().optional(),enum:D.array(D.string()),default:D.string().optional()}),Qm=D.object({type:D.literal(`string`),title:D.string().optional(),description:D.string().optional(),oneOf:D.array(D.object({const:D.string(),title:D.string()})),default:D.string().optional()}),$m=D.object({type:D.literal(`string`),title:D.string().optional(),description:D.string().optional(),enum:D.array(D.string()),enumNames:D.array(D.string()).optional(),default:D.string().optional()}),eh=D.union([Zm,Qm]),th=D.object({type:D.literal(`array`),title:D.string().optional(),description:D.string().optional(),minItems:D.number().optional(),maxItems:D.number().optional(),items:D.object({type:D.literal(`string`),enum:D.array(D.string())}),default:D.array(D.string()).optional()}),nh=D.object({type:D.literal(`array`),title:D.string().optional(),description:D.string().optional(),minItems:D.number().optional(),maxItems:D.number().optional(),items:D.object({anyOf:D.array(D.object({const:D.string(),title:D.string()}))}),default:D.array(D.string()).optional()}),rh=D.union([th,nh]),ih=D.union([$m,eh,rh]),ah=D.union([ih,Jm,Ym,Xm]),oh=Wf.extend({mode:D.literal(`form`).optional(),message:D.string(),requestedSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),ah),required:D.array(D.string()).optional()})}),sh=Wf.extend({mode:D.literal(`url`),message:D.string(),elicitationId:D.string(),url:D.string().url()}),ch=D.union([oh,sh]),lh=Gf.extend({method:D.literal(`elicitation/create`),params:ch}),uh=Kf.extend({elicitationId:D.string()}),dh=qf.extend({method:D.literal(`notifications/elicitation/complete`),params:uh}),fh=Jf.extend({action:D.enum([`accept`,`decline`,`cancel`]),content:D.preprocess(e=>e===null?void 0:e,D.record(D.string(),D.union([D.string(),D.number(),D.boolean(),D.array(D.string())])).optional())}),ph=D.object({type:D.literal(`ref/resource`),uri:D.string()}),mh=D.object({type:D.literal(`ref/prompt`),name:D.string()}),hh=Uf.extend({ref:D.union([mh,ph]),argument:D.object({name:D.string(),value:D.string()}),context:D.object({arguments:D.record(D.string(),D.string()).optional()}).optional()}),gh=Gf.extend({method:D.literal(`completion/complete`),params:hh}),_h=Jf.extend({completion:D.looseObject({values:D.array(D.string()).max(100),total:D.optional(D.number().int()),hasMore:D.optional(D.boolean())})}),vh=D.object({uri:D.string().startsWith(`file://`),name:D.string().optional(),_meta:D.record(D.string(),D.unknown()).optional()}),yh=Gf.extend({method:D.literal(`roots/list`),params:Uf.optional()}),bh=Jf.extend({roots:D.array(vh)}),xh=qf.extend({method:D.literal(`notifications/roots/list_changed`),params:Kf.optional()}),Sh=D.union([vp,mp,gh,Pm,fm,lm,Kp,Jp,Qp,nm,im,Am,Em,Ap,Mp,Pp,Ip]),Ch=D.union([rp,xp,_p,xh,kp]),D.union([tp,Km,qm,fh,bh,jp,Fp,Dp]),wh=D.union([vp,Gm,lh,yh,Ap,Mp,Pp,Ip]),Th=D.union([rp,xp,Im,om,em,jm,Sm,kp,dh]),D.union([tp,gp,_h,xm,um,qp,Yp,$p,Om,Dm,jp,Fp,Dp]),Eh={ping:tp,initialize:gp,"completion/complete":_h,"logging/setLevel":tp,"prompts/get":xm,"prompts/list":um,"resources/list":qp,"resources/templates/list":Yp,"resources/read":$p,"resources/subscribe":tp,"resources/unsubscribe":tp,"tools/call":D.union([Om,Dp]),"tools/list":Dm,"sampling/createMessage":D.union([qm,Dp]),"elicitation/create":D.union([fh,Dp]),"roots/list":bh,"tasks/get":jp,"tasks/result":Jf,"tasks/list":Fp,"tasks/cancel":Lp},Dh=Id([...Sh.options,...wh.options]),Oh=Id([...Ch.options,...Th.options]),kh=e=>Xf.safeParse(e).success,Ah=e=>Zf.safeParse(e).success,jh=e=>Qf.safeParse(e).success,Mh=e=>$f.safeParse(e).success,Nh=e=>Wf.safeParse(e).success,Ph=e=>mp.safeParse(e).success,Fh=e=>_p.safeParse(e).success,Ih=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,Dp,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},Ud(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},jp,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},Fp,t)}async cancelTask(e,t){return this._requireHost.request({method:`tasks/cancel`,params:e},Lp,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(!Ud(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,[kf]:{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(Ud(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,[kf]: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)?.[kf]?.taskId,r=Nh(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),jh(e)?n(e):n(new W(e.error.code,e.error.message,e.error.data)),!0):!1}shouldPreserveProgressHandler(e,t){if(jh(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,[kf]: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(Mh(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=kp.parse({method:`notifications/tasks/status`,params:o});await r?.notification(t),Ud(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(Ud(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=kp.parse({method:`notifications/tasks/status`,params:s});await r?.notification(t),Ud(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,[kf]: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`&&kh(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))}},Lh=class extends Ih{constructor(){super({})}processInboundRequest(e,t){let n=Nh(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`}}}},Rh=6e4,zh=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??Of,this._taskManager=e?.tasks?new Ih(e.tasks):new Lh,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=Ld(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(yf.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),jh(e)||Mh(e)?this._onresponse(e):kh(e)?this._onrequest(e,t):Ah(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(yf.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,Fd(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),jh(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=Fd(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(yf.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Hd(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(yf.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(yf.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=Ld(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=Rd(e);this._notificationHandlers.set(e,e=>{let r=n.parse(e);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}},Bh=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 Yd(t)}catch(e){if(e instanceof SyntaxError)continue;throw e}}return null}clear(){this._buffer=void 0}},Vh=/^[A-Za-z0-9._-]{1,128}$/,Hh=1e6,Uh=1e6,Wh=1e4,Gh=1e6,Kh=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,Hh,`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>Wh)throw Error(`Template contains too many expressions (max ${Wh})`);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,Uh,`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,Uh,`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,Uh,`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,Hh,`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,Gh,`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}},qh=V((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})),Jh=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=qh();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=V((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=qh(),n=Jh();var r=qh();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=Jh();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&&=D(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=D(this.rhs,e,n),this}get names(){return E(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=D(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)||(O(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>te(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(k(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=D(this.condition,e,t),this}get names(){let e=super.names;return E(e,this.condition),this.else&&te(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=D(this.iteration,e,t),this}get names(){return te(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 E(E(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=D(this.iterable,e,t),this}get names(){return te(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&&te(e,this.catch.names),this.finally&&te(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 te(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function E(e,n){return n instanceof t._CodeOrName?te(e,n.names):e}function D(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 O(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function k(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${N(e)}`}e.not=k;let A=M(e.operators.AND);function ne(...e){return e.reduce(A)}e.and=ne;let j=M(e.operators.OR);function re(...e){return e.reduce(j)}e.or=re;function M(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${N(n)} ${e} ${N(r)}`}function N(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),Yh=V((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=qh();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})),Xh=V((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`)}})),Zh=V((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=Yh(),r=Xh();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])}})),Qh=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Zh(),n=G(),r=Xh(),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)}})),$h=V((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})),eg=V((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})),tg=V((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=$h(),n=eg(),r=Zh(),i=G(),a=Yh();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
170
+ `)}},{name:`mcp`,description:`Register as MCP server`,subcommands:[ru({name:`add`,description:`Register as MCP server`,alias:{command:`c`},options:f.object({agent:f.string().optional().describe(`Target a specific agent (e.g. claude-code, cursor)`),command:f.string().optional().describe(`Override the command agents will run (e.g. "pnpm my-cli --mcp")`),noGlobal:f.boolean().optional().describe(`Install to project instead of globally`)})}),ru({name:`doctor`,description:`Validate MCP server startup and tool listing`})]},{name:`skills`,aliases:[`skill`],description:`Sync skill files to agents`,subcommands:[ru({name:`add`,description:`Sync skill files to agents`,options:f.object({depth:f.number().optional().describe(`Grouping depth for skill files (default: 1)`),noGlobal:f.boolean().optional().describe(`Install to project instead of globally`)})}),ru({name:`list`,aliases:[`ls`],description:`List skills`})]}]}));function uu(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(...xu(c,r,a)),l.join(`
171
+ `)}function du(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=fu(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=pu(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=hu(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(...xu(f,i,o)),l){let e=mu(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??Zl();n.name in i&&r.push(`set: ${Su(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
+ `)}function fu(e,t){if(!t)return e;let n=[e];for(let[e,r]of Object.entries(t.shape)){let t=gu(r),i=(t.includes(`|`)?t:e)+(t===`array`?`...`:``);n.push(r._zod.optout===`optional`?`[${i}]`:`<${i}>`)}return n.join(` `)}function pu(e){let t=[];for(let[n,r]of Object.entries(e.shape))t.push({name:n,description:r.description??``});return t}function mu(e){let t=[];for(let[n,r]of Object.entries(e.shape)){let e=yu(r);t.push({name:n,description:r.description??``,defaultValue:e})}return t}function hu(e,t){let n=[];for(let[r,i]of Object.entries(e.shape)){let e=gu(i),a=t?.[r],o=dn(r),s=e===`boolean`?``:` <${e}>`,c=a?`--${o}, -${a}${s}`:`--${o}${s}`,l=yu(i);e===`boolean`&&l===!1&&(l=void 0);let u=bu(i);n.push({flag:c,description:i.description??``,defaultValue:l,deprecated:u})}return n}function gu(e){if(_u(e))return`count`;let t=vu(e);if(t instanceof f.ZodString)return`string`;if(t instanceof f.ZodNumber)return`number`;if(t instanceof f.ZodBoolean)return`boolean`;if(t instanceof f.ZodArray)return`array`;if(t instanceof f.ZodEnum)return Object.values(t._zod.def.entries).join(`|`);if(t instanceof f.ZodUnion){let e=t._zod?.def?.options;if(e?.every(e=>e instanceof f.ZodLiteral))return e.map(e=>String(e._zod.def.values[0])).join(`|`)}return`value`}function _u(e){let t=e;return typeof t?.meta==`function`&&t.meta()?.count===!0}function vu(e){return e instanceof f.ZodOptional?vu(e.unwrap()):e instanceof f.ZodDefault?vu(e.removeDefault()):e instanceof f.ZodNullable?vu(e.unwrap()):e}function yu(e){if(e instanceof f.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 f.ZodOptional)return yu(e.unwrap())}function bu(e){return e?.meta?.()?.deprecated===!0||void 0}function xu(e=!1,t,n){let r=[];if(e){let e=cu.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=hu(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 Su(e){return e.length<=4?`****`:`****${e.slice(-4)}`}var Cu=z((()=>{lu(),mn(),Ql()}));function wu(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=>Eu(e,t))}}function Tu(e){let t=[e.description];for(let n of e.commands)t.push(` ${n.command}${n.description?` - ${n.description}`:``}`);return t.join(`
173
+ `)}function Eu(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 Du=z((()=>{}));async function Ou(e,t={}){let n=[],r=t.exclude?c.resolve(t.exclude):void 0;async function i(e,t){let a=await w.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=c.join(e,o.name);if(o.isDirectory()){ju(o.name,a),await i(a,[...t,o.name]);continue}if(!o.isFile()||a===r)continue;let s=Mu.find(e=>o.name.endsWith(e));if(!s)continue;let l=o.name.slice(0,-s.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}ju(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 ku(){return globalThis[Symbol.for(Pu)]?.shift()}async function Au(e){return Promise.all(e.map(async({load:e,...t})=>({...t,command:await e()})))}function ju(e,t){if(!Nu.test(e))throw Error(`Invalid filesystem command segment '${e}' from '${t}'. Use lowercase kebab-case names.`)}var Mu,Nu,Pu,Fu=z((()=>{Mu=[`.cts`,`.cjs`,`.mts`,`.mjs`,`.ts`,`.js`],Nu=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Pu=`incur.fs.manifests`}));function Iu(e){let t=f.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 Lu=z((()=>{}));function Ru(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(!Ru(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(!Ru(e[r],t[r]))return!1;return!0}return e===t}var zu=z((()=>{}));function Bu(e){return encodeURI(Vu(e))}function Vu(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var Hu=z((()=>{}));function Uu(e,t=Object.create(null),n=qu,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:Uu(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(Ku[i])continue;let a=`${r}/${Bu(i)}`,o=e[i];if(Array.isArray(o)){if(Wu[i]){let e=o.length;for(let r=0;r<e;r++)Uu(o[r],t,n,`${a}/${r}`)}}else if(Gu[i])for(let e in o)Uu(o[e],t,n,`${a}/${Bu(e)}`);else Uu(o,t,n,a)}return t}var Wu,Gu,Ku,qu,Ju=z((()=>{Hu(),Wu={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Gu={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Ku={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},qu=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 Yu(e){return e.test.bind(e)}function Xu(e){return e%4==0&&(e%100!=0||e%400==0)}function Zu(e){let t=e.match(nd);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&Xu(n)?29:rd[r])}function Qu(e,t){let n=t.match(id);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 $u(e){let t=e.split(vd);return t.length==2&&Zu(t[0])&&Qu(!0,t[1])}function ed(e){return yd.test(e)&&bd.test(e)}function td(e){if(xd.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}var nd,rd,id,ad,od,sd,cd,ld,ud,dd,fd,pd,md,hd,gd,_d,vd,yd,bd,xd,Sd=z((()=>{nd=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,rd=[0,31,28,31,30,31,30,31,31,30,31,30,31],id=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,ad=/^(?=.{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,od=/^(?:[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,sd=/^(?:(?:[^\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,cd=/^(?:(?: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,ld=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,ud=/^(?:\/(?:[^~/]|~0|~1)*)*$/,dd=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,fd=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,pd=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))},md=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,hd=/^((([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,gd=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)),_d={date:Zu,time:Qu.bind(void 0,!1),"date-time":$u,duration:gd,uri:ed,"uri-reference":Yu(od),"uri-template":Yu(sd),url:Yu(cd),email:pd,hostname:Yu(ad),ipv4:Yu(md),ipv6:Yu(hd),regex:td,uuid:Yu(ld),"json-pointer":Yu(ud),"json-pointer-uri-fragment":Yu(dd),"relative-json-pointer":Yu(fd)},vd=/t|\s/i,yd=/\/|:/,bd=/^(?:[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,xd=/[^\\]\\Z/})),Cd=z((()=>{}));function wd(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 Td=z((()=>{}));function Ed(e,t,n=`2019-09`,r=Uu(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:E,patternProperties:ee,additionalProperties:D,unevaluatedProperties:O,minProperties:k,maxProperties:te,propertyNames:A,dependentRequired:j,dependentSchemas:M,dependencies:ne,prefixItems:N,items:P,additionalItems:re,unevaluatedItems:ie,contains:ae,minContains:F,maxContains:oe,minItems:se,maxItems:I,uniqueItems:ce,minimum:L,maximum:le,exclusiveMinimum:ue,exclusiveMaximum:de,multipleOf:fe,minLength:pe,maxLength:me,pattern:he,__absolute_ref__:ge,__absolute_recursive_ref__:_e}=t,R=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[_e]:a,u=`${s}/$recursiveRef`,d=Ed(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||R.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[ge||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw ge&&ge!==d&&(e+=` Absolute URI "${ge}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
174
+ - `)}`,Error(e)}let l=`${s}/$ref`,u=Ed(e,t,n,r,i,a,o,l,c);if(u.valid||R.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:R.length===0,errors:R}}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||R.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)&&R.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&R.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?Ru(e,h)||R.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&R.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=>Ru(e,t))||R.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||R.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`;Ed(e,v,n,r,i,a,o,t).valid&&R.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let ve=[];if(y!==void 0){let t=`${s}/anyOf`,l=R.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=Ed(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);R.push(...f.errors),u||=f.valid,f.valid&&ve.push(d)}u?R.length=l:R.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=R.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=Ed(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);R.push(...f.errors),u&&=f.valid,f.valid&&ve.push(d)}u?R.length=l:R.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=R.length,u=x.filter((s,l)=>{let u=Object.create(c),d=Ed(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return R.push(...d.errors),d.valid&&ve.push(u),d.valid}).length;u===1?R.length=l:R.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,...ve),S!==void 0){let t=`${s}/if`;if(Ed(e,S,n,r,i,a,o,t,c).valid){if(C!==void 0){let l=Ed(e,C,n,r,i,a,o,`${s}/then`,c);l.valid||R.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(w!==void 0){let l=Ed(e,w,n,r,i,a,o,`${s}/else`,c);l.valid||R.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||R.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&&R.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),te!==void 0&&t.length>te&&R.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}/${Bu(s)}`,c=Ed(s,A,n,r,i,a,e,t);c.valid||R.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(j!==void 0){let t=`${s}/dependantRequired`;for(let n in j)if(n in e){let r=j[n];for(let i of r)i in e||R.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=Ed(e,M[t],n,r,i,a,o,`${l}/${Bu(t)}`,c);s.valid||R.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||R.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=Ed(e,c,n,r,i,a,o,`${t}/${Bu(s)}`);l.valid||R.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(E!==void 0){let t=`${s}/properties`;for(let s in E){if(!(s in e))continue;let d=`${o}/${Bu(s)}`,f=Ed(e[s],E[s],n,r,i,a,d,`${t}/${Bu(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,R.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&ee!==void 0){let t=`${s}/patternProperties`;for(let s in ee){let d=new RegExp(s,`u`),f=ee[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${Bu(p)}`,h=Ed(e[p],f,n,r,i,a,m,`${t}/${Bu(s)}`);h.valid?c[p]=l[p]=!0:(u=i,R.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}/${Bu(s)}`,f=Ed(e[s],D,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,R.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}/${Bu(s)}`,u=Ed(e[s],O,n,r,i,a,l,t);u.valid?c[s]=!0:R.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){I!==void 0&&e.length>I&&R.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${I}).`}),se!==void 0&&e.length<se&&R.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${se}).`});let t=e.length,l=0,u=!1;if(N!==void 0){let d=`${s}/prefixItems`,f=Math.min(N.length,t);for(;l<f;l++){let t=Ed(e[l],N[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,R.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(P!==void 0){let d=`${s}/items`;if(Array.isArray(P)){let s=Math.min(P.length,t);for(;l<s;l++){let t=Ed(e[l],P[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,R.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=Ed(e[l],P,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,R.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&re!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=Ed(e[l],re,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,R.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(ae!==void 0){if(t===0&&F===void 0)R.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(F!==void 0&&t<F)R.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${F}).`});else{let l=`${s}/contains`,u=R.length,d=0;for(let s=0;s<t;s++){let t=Ed(e[s],ae,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):R.push(...t.errors)}d>=(F||0)&&(R.length=u),F===void 0&&oe===void 0&&d===0?R.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):F!==void 0&&d<F?R.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${F} items matching schema. Only ${d} items were found.`}):oe!==void 0&&d>oe&&R.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${oe} items matching schema. ${d} items were found.`})}}if(!u&&ie!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=Ed(e[l],ie,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||R.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(ce)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&&Ru(r,t))&&(R.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`?(L!==void 0&&(ue===!0&&e<=L||e<L)&&R.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${ue?`or equal to `:``} ${L}.`}),le!==void 0&&(de===!0&&e>=le||e>le)&&R.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${de?`or equal to `:``} ${le}.`})):(L!==void 0&&e<L&&R.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${L}.`}),le!==void 0&&e>le&&R.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${le}.`}),ue!==void 0&&e<=ue&&R.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${ue}.`}),de!==void 0&&e>=de&&R.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${de}.`})),fe!==void 0){let t=e%fe;Math.abs(0-t)>=1.1920929e-7&&Math.abs(fe-t)>=1.1920929e-7&&R.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${fe}.`})}}else if(u===`string`){let t=pe===void 0&&me===void 0?0:wd(e);pe!==void 0&&t<pe&&R.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${pe}).`}),me!==void 0&&t>me&&R.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${me}).`}),he!==void 0&&!new RegExp(he,`u`).test(e)&&R.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),T!==void 0&&_d[T]&&!_d[T](e)&&R.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${T}".`})}return{valid:R.length===0,errors:R}}var Dd=z((()=>{zu(),Ju(),Sd(),Hu(),Td()})),Od,kd=z((()=>{Ju(),Dd(),Od=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Uu(e)}validate(e){return Ed(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Uu(e,this.lookup)}}})),Ad=z((()=>{zu(),Ju(),Sd(),Hu(),Cd(),Td(),Dd(),kd()}));function jd(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Md({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 Nd(e){return e.title!==void 0&&e.title!==``?e.title:`annotations`in e&&e.annotations?.title?e.annotations.title:e.name}function Pd(e){return Eh[e]}function Fd(e){let t={};for(let n of e){let e=n.shape.method.value;t[e]=n}return t}function Id(e){return Dh[e]}function Ld(e){return Oh[e]}function Rd(e){return ep.parse(e)}function zd(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Bd(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}function Vd(e,t){return O.safeParse(e,t)}function Hd(e){return e===`completed`||e===`failed`||e===`cancelled`}function Ud(e){if(!e)return;let{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}=e;return{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}}function Wd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Gd(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]=Wd(a)&&Wd(i)?{...a,...i}:i}return n}async function Kd(e){let t=[];for await(let n of e)t.push(n);return t}async function qd(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 Jd(e){return ep.parse(JSON.parse(e))}function Yd(e){return JSON.stringify(e)+`
175
+ `}function Xd(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`),!Vh.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 Zd(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 Qd(e){let t=Xd(e);return Zd(e,t.warnings),t.isValid}function $d(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function ef(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...$d(t.headers),...$d(r.headers)}:t.headers}):e}function tf(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 nf(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function rf(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>nf(e)).join(`, `)}:{success:!0,data:n.value}}function af(e){let t=tf(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 of(){let e=new l_.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,u_.default)(e),e}function sf(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 cf,lf,uf,df,ff,pf,H,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Tf,Ef,Df,Of,kf,Af,jf,Mf,Nf,Pf,U,W,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,Ph,Fh,Ih,Lh,Rh,zh,Bh,Vh,Hh,Uh,Wh,Gh,Kh,qh,Jh,G,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,Qg,$g,e_,t_,n_,r_,i_,a_,o_,s_,c_,l_,u_,d_,f_,p_=z((()=>{Ad(),cf=Object.create,lf=Object.defineProperty,uf=Object.getOwnPropertyDescriptor,df=Object.getOwnPropertyNames,ff=Object.getPrototypeOf,pf=Object.prototype.hasOwnProperty,H=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),mf=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=df(t),a=0,o=i.length,s;a<o;a++)s=i[a],!pf.call(e,s)&&s!==n&&lf(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=uf(t,s))||r.enumerable});return e},hf=(e,t,n)=>(n=e==null?{}:cf(ff(e)),mf(t||!e||!e.__esModule?lf(n,`default`,{value:e,enumerable:!0}):n,e)),gf=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}({}),_f=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)}},vf=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}({}),yf=class extends Error{constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`SdkError`}},bf=O.url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:O.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),O.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`}),O.looseObject({resource:O.string().url(),authorization_servers:O.array(bf).optional(),jwks_uri:O.string().url().optional(),scopes_supported:O.array(O.string()).optional(),bearer_methods_supported:O.array(O.string()).optional(),resource_signing_alg_values_supported:O.array(O.string()).optional(),resource_name:O.string().optional(),resource_documentation:O.string().optional(),resource_policy_uri:O.string().url().optional(),resource_tos_uri:O.string().url().optional(),tls_client_certificate_bound_access_tokens:O.boolean().optional(),authorization_details_types_supported:O.array(O.string()).optional(),dpop_signing_alg_values_supported:O.array(O.string()).optional(),dpop_bound_access_tokens_required:O.boolean().optional()}),xf=O.looseObject({issuer:O.string(),authorization_endpoint:bf,token_endpoint:bf,registration_endpoint:bf.optional(),scopes_supported:O.array(O.string()).optional(),response_types_supported:O.array(O.string()),response_modes_supported:O.array(O.string()).optional(),grant_types_supported:O.array(O.string()).optional(),token_endpoint_auth_methods_supported:O.array(O.string()).optional(),token_endpoint_auth_signing_alg_values_supported:O.array(O.string()).optional(),service_documentation:bf.optional(),revocation_endpoint:bf.optional(),revocation_endpoint_auth_methods_supported:O.array(O.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:O.array(O.string()).optional(),introspection_endpoint:O.string().optional(),introspection_endpoint_auth_methods_supported:O.array(O.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:O.array(O.string()).optional(),code_challenge_methods_supported:O.array(O.string()).optional(),client_id_metadata_document_supported:O.boolean().optional()}),Sf=O.looseObject({issuer:O.string(),authorization_endpoint:bf,token_endpoint:bf,userinfo_endpoint:bf.optional(),jwks_uri:bf,registration_endpoint:bf.optional(),scopes_supported:O.array(O.string()).optional(),response_types_supported:O.array(O.string()),response_modes_supported:O.array(O.string()).optional(),grant_types_supported:O.array(O.string()).optional(),acr_values_supported:O.array(O.string()).optional(),subject_types_supported:O.array(O.string()),id_token_signing_alg_values_supported:O.array(O.string()),id_token_encryption_alg_values_supported:O.array(O.string()).optional(),id_token_encryption_enc_values_supported:O.array(O.string()).optional(),userinfo_signing_alg_values_supported:O.array(O.string()).optional(),userinfo_encryption_alg_values_supported:O.array(O.string()).optional(),userinfo_encryption_enc_values_supported:O.array(O.string()).optional(),request_object_signing_alg_values_supported:O.array(O.string()).optional(),request_object_encryption_alg_values_supported:O.array(O.string()).optional(),request_object_encryption_enc_values_supported:O.array(O.string()).optional(),token_endpoint_auth_methods_supported:O.array(O.string()).optional(),token_endpoint_auth_signing_alg_values_supported:O.array(O.string()).optional(),display_values_supported:O.array(O.string()).optional(),claim_types_supported:O.array(O.string()).optional(),claims_supported:O.array(O.string()).optional(),service_documentation:O.string().optional(),claims_locales_supported:O.array(O.string()).optional(),ui_locales_supported:O.array(O.string()).optional(),claims_parameter_supported:O.boolean().optional(),request_parameter_supported:O.boolean().optional(),request_uri_parameter_supported:O.boolean().optional(),require_request_uri_registration:O.boolean().optional(),op_policy_uri:bf.optional(),op_tos_uri:bf.optional(),client_id_metadata_document_supported:O.boolean().optional()}),O.object({...Sf.shape,...xf.pick({code_challenge_methods_supported:!0}).shape}),O.object({access_token:O.string(),id_token:O.string().optional(),token_type:O.string(),expires_in:O.coerce.number().optional(),scope:O.string().optional(),refresh_token:O.string().optional()}).strip(),O.object({issued_token_type:O.literal(`urn:ietf:params:oauth:token-type:id-jag`),access_token:O.string(),token_type:O.string().optional(),expires_in:O.number().optional(),scope:O.string().optional()}).strip(),O.object({error:O.string(),error_description:O.string().optional(),error_uri:O.string().optional()}),Cf=bf.optional().or(O.literal(``).transform(()=>void 0)),wf=O.object({redirect_uris:O.array(bf),token_endpoint_auth_method:O.string().optional(),grant_types:O.array(O.string()).optional(),response_types:O.array(O.string()).optional(),client_name:O.string().optional(),client_uri:bf.optional(),logo_uri:Cf,scope:O.string().optional(),contacts:O.array(O.string()).optional(),tos_uri:Cf,policy_uri:O.string().optional(),jwks_uri:bf.optional(),jwks:O.any().optional(),software_id:O.string().optional(),software_version:O.string().optional(),software_statement:O.string().optional()}).strip(),Tf=O.object({client_id:O.string(),client_secret:O.string().optional(),client_id_issued_at:O.number().optional(),client_secret_expires_at:O.number().optional()}).strip(),wf.merge(Tf),O.object({error:O.string(),error_description:O.string().optional()}).strip(),O.object({token:O.string(),token_type_hint:O.string().optional()}).strip(),Ef=`2025-11-25`,Df=`2025-03-26`,Of=[Ef,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],kf=`io.modelcontextprotocol/related-task`,Af=-32700,jf=-32600,Mf=-32601,Nf=-32602,Pf=-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 Ff(e.elicitations,n)}return new e(t,n,r)}},Ff=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??[]}},If=O.lazy(()=>O.union([O.string(),O.number(),O.boolean(),O.null(),O.record(O.string(),If),O.array(If)])),Lf=O.record(O.string(),If),O.array(If),Rf=O.union([O.string(),O.number().int()]),zf=O.string(),O.looseObject({ttl:O.number().optional(),pollInterval:O.number().optional()}),Bf=O.object({ttl:O.number().optional()}),Vf=O.object({taskId:O.string()}),Hf=O.looseObject({progressToken:Rf.optional(),[kf]:Vf.optional()}),Uf=O.object({_meta:Hf.optional()}),Wf=Uf.extend({task:Bf.optional()}),Gf=O.object({method:O.string(),params:Uf.loose().optional()}),Kf=O.object({_meta:Hf.optional()}),qf=O.object({method:O.string(),params:Kf.loose().optional()}),Jf=O.looseObject({_meta:Hf.optional()}),Yf=O.union([O.string(),O.number().int()]),Xf=O.object({jsonrpc:O.literal(`2.0`),id:Yf,...Gf.shape}).strict(),Zf=O.object({jsonrpc:O.literal(`2.0`),...qf.shape}).strict(),Qf=O.object({jsonrpc:O.literal(`2.0`),id:Yf,result:Jf}).strict(),$f=O.object({jsonrpc:O.literal(`2.0`),id:Yf.optional(),error:O.object({code:O.number().int(),message:O.string(),data:O.unknown().optional()})}).strict(),ep=O.union([Xf,Zf,Qf,$f]),O.union([Qf,$f]),tp=Jf.strict(),np=Kf.extend({requestId:Yf.optional(),reason:O.string().optional()}),rp=qf.extend({method:O.literal(`notifications/cancelled`),params:np}),ip=O.object({src:O.string(),mimeType:O.string().optional(),sizes:O.array(O.string()).optional(),theme:O.enum([`light`,`dark`]).optional()}),ap=O.object({icons:O.array(ip).optional()}),op=O.object({name:O.string(),title:O.string().optional()}),sp=op.extend({...op.shape,...ap.shape,version:O.string(),websiteUrl:O.string().optional(),description:O.string().optional()}),cp=O.intersection(O.object({applyDefaults:O.boolean().optional()}),Lf),lp=O.preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,O.intersection(O.object({form:cp.optional(),url:Lf.optional()}),Lf.optional())),up=O.looseObject({list:Lf.optional(),cancel:Lf.optional(),requests:O.looseObject({sampling:O.looseObject({createMessage:Lf.optional()}).optional(),elicitation:O.looseObject({create:Lf.optional()}).optional()}).optional()}),dp=O.looseObject({list:Lf.optional(),cancel:Lf.optional(),requests:O.looseObject({tools:O.looseObject({call:Lf.optional()}).optional()}).optional()}),fp=O.object({experimental:O.record(O.string(),Lf).optional(),sampling:O.object({context:Lf.optional(),tools:Lf.optional()}).optional(),elicitation:lp.optional(),roots:O.object({listChanged:O.boolean().optional()}).optional(),tasks:up.optional(),extensions:O.record(O.string(),Lf).optional()}),pp=Uf.extend({protocolVersion:O.string(),capabilities:fp,clientInfo:sp}),mp=Gf.extend({method:O.literal(`initialize`),params:pp}),hp=O.object({experimental:O.record(O.string(),Lf).optional(),logging:Lf.optional(),completions:Lf.optional(),prompts:O.object({listChanged:O.boolean().optional()}).optional(),resources:O.object({subscribe:O.boolean().optional(),listChanged:O.boolean().optional()}).optional(),tools:O.object({listChanged:O.boolean().optional()}).optional(),tasks:dp.optional(),extensions:O.record(O.string(),Lf).optional()}),gp=Jf.extend({protocolVersion:O.string(),capabilities:hp,serverInfo:sp,instructions:O.string().optional()}),_p=qf.extend({method:O.literal(`notifications/initialized`),params:Kf.optional()}),vp=Gf.extend({method:O.literal(`ping`),params:Uf.optional()}),yp=O.object({progress:O.number(),total:O.optional(O.number()),message:O.optional(O.string())}),bp=O.object({...Kf.shape,...yp.shape,progressToken:Rf}),xp=qf.extend({method:O.literal(`notifications/progress`),params:bp}),Sp=Uf.extend({cursor:zf.optional()}),Cp=Gf.extend({params:Sp.optional()}),wp=Jf.extend({nextCursor:zf.optional()}),Tp=O.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Ep=O.object({taskId:O.string(),status:Tp,ttl:O.union([O.number(),O.null()]),createdAt:O.string(),lastUpdatedAt:O.string(),pollInterval:O.optional(O.number()),statusMessage:O.optional(O.string())}),Dp=Jf.extend({task:Ep}),Op=Kf.merge(Ep),kp=qf.extend({method:O.literal(`notifications/tasks/status`),params:Op}),Ap=Gf.extend({method:O.literal(`tasks/get`),params:Uf.extend({taskId:O.string()})}),jp=Jf.merge(Ep),Mp=Gf.extend({method:O.literal(`tasks/result`),params:Uf.extend({taskId:O.string()})}),Np=Jf.loose(),Pp=Cp.extend({method:O.literal(`tasks/list`)}),Fp=wp.extend({tasks:O.array(Ep)}),Ip=Gf.extend({method:O.literal(`tasks/cancel`),params:Uf.extend({taskId:O.string()})}),Lp=Jf.merge(Ep),Rp=O.object({uri:O.string(),mimeType:O.optional(O.string()),_meta:O.record(O.string(),O.unknown()).optional()}),zp=Rp.extend({text:O.string()}),Bp=O.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Vp=Rp.extend({blob:Bp}),Hp=O.enum([`user`,`assistant`]),Up=O.object({audience:O.array(Hp).optional(),priority:O.number().min(0).max(1).optional(),lastModified:O.iso.datetime({offset:!0}).optional()}),Wp=O.object({...op.shape,...ap.shape,uri:O.string(),description:O.optional(O.string()),mimeType:O.optional(O.string()),size:O.optional(O.number()),annotations:Up.optional(),_meta:O.optional(O.looseObject({}))}),Gp=O.object({...op.shape,...ap.shape,uriTemplate:O.string(),description:O.optional(O.string()),mimeType:O.optional(O.string()),annotations:Up.optional(),_meta:O.optional(O.looseObject({}))}),Kp=Cp.extend({method:O.literal(`resources/list`)}),qp=wp.extend({resources:O.array(Wp)}),Jp=Cp.extend({method:O.literal(`resources/templates/list`)}),Yp=wp.extend({resourceTemplates:O.array(Gp)}),Xp=Uf.extend({uri:O.string()}),Zp=Xp,Qp=Gf.extend({method:O.literal(`resources/read`),params:Zp}),$p=Jf.extend({contents:O.array(O.union([zp,Vp]))}),em=qf.extend({method:O.literal(`notifications/resources/list_changed`),params:Kf.optional()}),tm=Xp,nm=Gf.extend({method:O.literal(`resources/subscribe`),params:tm}),rm=Xp,im=Gf.extend({method:O.literal(`resources/unsubscribe`),params:rm}),am=Kf.extend({uri:O.string()}),om=qf.extend({method:O.literal(`notifications/resources/updated`),params:am}),sm=O.object({name:O.string(),description:O.optional(O.string()),required:O.optional(O.boolean())}),cm=O.object({...op.shape,...ap.shape,description:O.optional(O.string()),arguments:O.optional(O.array(sm)),_meta:O.optional(O.looseObject({}))}),lm=Cp.extend({method:O.literal(`prompts/list`)}),um=wp.extend({prompts:O.array(cm)}),dm=Uf.extend({name:O.string(),arguments:O.record(O.string(),O.string()).optional()}),fm=Gf.extend({method:O.literal(`prompts/get`),params:dm}),pm=O.object({type:O.literal(`text`),text:O.string(),annotations:Up.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),mm=O.object({type:O.literal(`image`),data:Bp,mimeType:O.string(),annotations:Up.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),hm=O.object({type:O.literal(`audio`),data:Bp,mimeType:O.string(),annotations:Up.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),gm=O.object({type:O.literal(`tool_use`),name:O.string(),id:O.string(),input:O.record(O.string(),O.unknown()),_meta:O.record(O.string(),O.unknown()).optional()}),_m=O.object({type:O.literal(`resource`),resource:O.union([zp,Vp]),annotations:Up.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),vm=Wp.extend({type:O.literal(`resource_link`)}),ym=O.union([pm,mm,hm,vm,_m]),bm=O.object({role:Hp,content:ym}),xm=Jf.extend({description:O.string().optional(),messages:O.array(bm)}),Sm=qf.extend({method:O.literal(`notifications/prompts/list_changed`),params:Kf.optional()}),Cm=O.object({title:O.string().optional(),readOnlyHint:O.boolean().optional(),destructiveHint:O.boolean().optional(),idempotentHint:O.boolean().optional(),openWorldHint:O.boolean().optional()}),wm=O.object({taskSupport:O.enum([`required`,`optional`,`forbidden`]).optional()}),Tm=O.object({...op.shape,...ap.shape,description:O.string().optional(),inputSchema:O.object({type:O.literal(`object`),properties:O.record(O.string(),If).optional(),required:O.array(O.string()).optional()}).catchall(O.unknown()),outputSchema:O.object({type:O.literal(`object`),properties:O.record(O.string(),If).optional(),required:O.array(O.string()).optional()}).catchall(O.unknown()).optional(),annotations:Cm.optional(),execution:wm.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),Em=Cp.extend({method:O.literal(`tools/list`)}),Dm=wp.extend({tools:O.array(Tm)}),Om=Jf.extend({content:O.array(ym).default([]),structuredContent:O.record(O.string(),O.unknown()).optional(),isError:O.boolean().optional()}),Om.or(Jf.extend({toolResult:O.unknown()})),km=Wf.extend({name:O.string(),arguments:O.record(O.string(),O.unknown()).optional()}),Am=Gf.extend({method:O.literal(`tools/call`),params:km}),jm=qf.extend({method:O.literal(`notifications/tools/list_changed`),params:Kf.optional()}),O.object({autoRefresh:O.boolean().default(!0),debounceMs:O.number().int().nonnegative().default(300)}),Mm=O.enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Nm=Uf.extend({level:Mm}),Pm=Gf.extend({method:O.literal(`logging/setLevel`),params:Nm}),Fm=Kf.extend({level:Mm,logger:O.string().optional(),data:O.unknown()}),Im=qf.extend({method:O.literal(`notifications/message`),params:Fm}),Lm=O.object({name:O.string().optional()}),Rm=O.object({hints:O.array(Lm).optional(),costPriority:O.number().min(0).max(1).optional(),speedPriority:O.number().min(0).max(1).optional(),intelligencePriority:O.number().min(0).max(1).optional()}),zm=O.object({mode:O.enum([`auto`,`required`,`none`]).optional()}),Bm=O.object({type:O.literal(`tool_result`),toolUseId:O.string().describe(`The unique identifier for the corresponding tool call.`),content:O.array(ym).default([]),structuredContent:O.object({}).loose().optional(),isError:O.boolean().optional(),_meta:O.record(O.string(),O.unknown()).optional()}),Vm=O.discriminatedUnion(`type`,[pm,mm,hm]),Hm=O.discriminatedUnion(`type`,[pm,mm,hm,gm,Bm]),Um=O.object({role:Hp,content:O.union([Hm,O.array(Hm)]),_meta:O.record(O.string(),O.unknown()).optional()}),Wm=Wf.extend({messages:O.array(Um),modelPreferences:Rm.optional(),systemPrompt:O.string().optional(),includeContext:O.enum([`none`,`thisServer`,`allServers`]).optional(),temperature:O.number().optional(),maxTokens:O.number().int(),stopSequences:O.array(O.string()).optional(),metadata:Lf.optional(),tools:O.array(Tm).optional(),toolChoice:zm.optional()}),Gm=Gf.extend({method:O.literal(`sampling/createMessage`),params:Wm}),Km=Jf.extend({model:O.string(),stopReason:O.optional(O.enum([`endTurn`,`stopSequence`,`maxTokens`]).or(O.string())),role:Hp,content:Vm}),qm=Jf.extend({model:O.string(),stopReason:O.optional(O.enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(O.string())),role:Hp,content:O.union([Hm,O.array(Hm)])}),Jm=O.object({type:O.literal(`boolean`),title:O.string().optional(),description:O.string().optional(),default:O.boolean().optional()}),Ym=O.object({type:O.literal(`string`),title:O.string().optional(),description:O.string().optional(),minLength:O.number().optional(),maxLength:O.number().optional(),format:O.enum([`email`,`uri`,`date`,`date-time`]).optional(),default:O.string().optional()}),Xm=O.object({type:O.enum([`number`,`integer`]),title:O.string().optional(),description:O.string().optional(),minimum:O.number().optional(),maximum:O.number().optional(),default:O.number().optional()}),Zm=O.object({type:O.literal(`string`),title:O.string().optional(),description:O.string().optional(),enum:O.array(O.string()),default:O.string().optional()}),Qm=O.object({type:O.literal(`string`),title:O.string().optional(),description:O.string().optional(),oneOf:O.array(O.object({const:O.string(),title:O.string()})),default:O.string().optional()}),$m=O.object({type:O.literal(`string`),title:O.string().optional(),description:O.string().optional(),enum:O.array(O.string()),enumNames:O.array(O.string()).optional(),default:O.string().optional()}),eh=O.union([Zm,Qm]),th=O.object({type:O.literal(`array`),title:O.string().optional(),description:O.string().optional(),minItems:O.number().optional(),maxItems:O.number().optional(),items:O.object({type:O.literal(`string`),enum:O.array(O.string())}),default:O.array(O.string()).optional()}),nh=O.object({type:O.literal(`array`),title:O.string().optional(),description:O.string().optional(),minItems:O.number().optional(),maxItems:O.number().optional(),items:O.object({anyOf:O.array(O.object({const:O.string(),title:O.string()}))}),default:O.array(O.string()).optional()}),rh=O.union([th,nh]),ih=O.union([$m,eh,rh]),ah=O.union([ih,Jm,Ym,Xm]),oh=Wf.extend({mode:O.literal(`form`).optional(),message:O.string(),requestedSchema:O.object({type:O.literal(`object`),properties:O.record(O.string(),ah),required:O.array(O.string()).optional()})}),sh=Wf.extend({mode:O.literal(`url`),message:O.string(),elicitationId:O.string(),url:O.string().url()}),ch=O.union([oh,sh]),lh=Gf.extend({method:O.literal(`elicitation/create`),params:ch}),uh=Kf.extend({elicitationId:O.string()}),dh=qf.extend({method:O.literal(`notifications/elicitation/complete`),params:uh}),fh=Jf.extend({action:O.enum([`accept`,`decline`,`cancel`]),content:O.preprocess(e=>e===null?void 0:e,O.record(O.string(),O.union([O.string(),O.number(),O.boolean(),O.array(O.string())])).optional())}),ph=O.object({type:O.literal(`ref/resource`),uri:O.string()}),mh=O.object({type:O.literal(`ref/prompt`),name:O.string()}),hh=Uf.extend({ref:O.union([mh,ph]),argument:O.object({name:O.string(),value:O.string()}),context:O.object({arguments:O.record(O.string(),O.string()).optional()}).optional()}),gh=Gf.extend({method:O.literal(`completion/complete`),params:hh}),_h=Jf.extend({completion:O.looseObject({values:O.array(O.string()).max(100),total:O.optional(O.number().int()),hasMore:O.optional(O.boolean())})}),vh=O.object({uri:O.string().startsWith(`file://`),name:O.string().optional(),_meta:O.record(O.string(),O.unknown()).optional()}),yh=Gf.extend({method:O.literal(`roots/list`),params:Uf.optional()}),bh=Jf.extend({roots:O.array(vh)}),xh=qf.extend({method:O.literal(`notifications/roots/list_changed`),params:Kf.optional()}),Sh=O.union([vp,mp,gh,Pm,fm,lm,Kp,Jp,Qp,nm,im,Am,Em,Ap,Mp,Pp,Ip]),Ch=O.union([rp,xp,_p,xh,kp]),O.union([tp,Km,qm,fh,bh,jp,Fp,Dp]),wh=O.union([vp,Gm,lh,yh,Ap,Mp,Pp,Ip]),Th=O.union([rp,xp,Im,om,em,jm,Sm,kp,dh]),O.union([tp,gp,_h,xm,um,qp,Yp,$p,Om,Dm,jp,Fp,Dp]),Eh={ping:tp,initialize:gp,"completion/complete":_h,"logging/setLevel":tp,"prompts/get":xm,"prompts/list":um,"resources/list":qp,"resources/templates/list":Yp,"resources/read":$p,"resources/subscribe":tp,"resources/unsubscribe":tp,"tools/call":O.union([Om,Dp]),"tools/list":Dm,"sampling/createMessage":O.union([qm,Dp]),"elicitation/create":O.union([fh,Dp]),"roots/list":bh,"tasks/get":jp,"tasks/result":Jf,"tasks/list":Fp,"tasks/cancel":Lp},Dh=Fd([...Sh.options,...wh.options]),Oh=Fd([...Ch.options,...Th.options]),kh=e=>Xf.safeParse(e).success,Ah=e=>Zf.safeParse(e).success,jh=e=>Qf.safeParse(e).success,Mh=e=>$f.safeParse(e).success,Nh=e=>Wf.safeParse(e).success,Ph=e=>mp.safeParse(e).success,Fh=e=>_p.safeParse(e).success,Ih=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,Dp,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},Hd(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},jp,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},Fp,t)}async cancelTask(e,t){return this._requireHost.request({method:`tasks/cancel`,params:e},Lp,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(!Hd(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,[kf]:{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(Hd(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,[kf]: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)?.[kf]?.taskId,r=Nh(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),jh(e)?n(e):n(new W(e.error.code,e.error.message,e.error.data)),!0):!1}shouldPreserveProgressHandler(e,t){if(jh(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,[kf]: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(Mh(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=kp.parse({method:`notifications/tasks/status`,params:o});await r?.notification(t),Hd(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(Hd(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=kp.parse({method:`notifications/tasks/status`,params:s});await r?.notification(t),Hd(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,[kf]: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`&&kh(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))}},Lh=class extends Ih{constructor(){super({})}processInboundRequest(e,t){let n=Nh(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`}}}},Rh=6e4,zh=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??Of,this._taskManager=e?.tasks?new Ih(e.tasks):new Lh,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=Id(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 yf(vf.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),jh(e)||Mh(e)?this._onresponse(e):kh(e)?this._onrequest(e,t):Ah(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 yf(vf.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,Pd(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),jh(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=Pd(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 yf?e:new yf(vf.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Vd(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 yf(vf.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 yf(vf.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=Id(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=Ld(e);this._notificationHandlers.set(e,e=>{let r=n.parse(e);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}},Bh=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 Jd(t)}catch(e){if(e instanceof SyntaxError)continue;throw e}}return null}clear(){this._buffer=void 0}},Vh=/^[A-Za-z0-9._-]{1,128}$/,Hh=1e6,Uh=1e6,Wh=1e4,Gh=1e6,Kh=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,Hh,`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>Wh)throw Error(`Template contains too many expressions (max ${Wh})`);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,Uh,`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,Uh,`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,Uh,`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,Hh,`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,Gh,`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}},qh=H((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})),Jh=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=qh();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=H((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=qh(),n=Jh();var r=qh();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=Jh();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)=>ee(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&&ee(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 ee(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 ee(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&&ee(e,this.catch.names),this.finally&&ee(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 E=class extends m{render(e){return`finally`+super.render(e)}};E.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 E,this.code(n)),this._endBlockNode(T,E)}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 ee(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?ee(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._)`!${P(e)}`}e.not=te;let A=N(e.operators.AND);function j(...e){return e.reduce(A)}e.and=j;let M=N(e.operators.OR);function ne(...e){return e.reduce(M)}e.or=ne;function N(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${P(n)} ${e} ${P(r)}`}function P(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),Yh=H((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=qh();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})),Xh=H((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`)}})),Zh=H((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=Yh(),r=Xh();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])}})),Qh=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Zh(),n=G(),r=Xh(),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)}})),$h=H((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})),eg=H((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})),tg=H((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=$h(),n=eg(),r=Zh(),i=G(),a=Yh();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}}})),ng=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=G(),n=Yh();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)}`)}})),rg=V((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=Yh(),r=Xh(),i=Yh();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})),ig=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=G(),n=Xh(),r=rg(),i=Zh();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})),ag=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=G(),n=Yh();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})),og=V(((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}})),sg=V(((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`)}})),cg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=Yh(),n=og(),r=sg(),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})),lg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Qh(),n=tg(),r=eg(),i=tg(),a=ng(),o=ig(),s=ag(),c=G(),l=Xh(),u=cg(),d=Yh(),f=Zh();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&&O(e),te(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),k(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&&O(e),E(e),D(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 te(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 E(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function D(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function O({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 k(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(()=>F(e,`$ref`,h.all.$ref.definition));return}p.jtd||re(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)&&F(e,n.keyword,n.definition,t.type)})}function re(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(M(e,t),e.opts.allowUnionTypes||N(e,t),ie(e,e.dataTypes))}function M(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{oe(e.dataTypes,t)||se(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),P(e,t)}}function N(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&se(e,`use allowUnionTypes to allow union type keyword`)}function ie(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=>ae(t,e))&&se(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function ae(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function oe(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function P(e,t){let n=[];for(let r of e.dataTypes)oe(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function se(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var ce=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`,ue(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=ce;function F(e,t,n,r){let i=new ce(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 le=/^\/(?:[^~]|~0|~1)*$/,I=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ue(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!le.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=I.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=ue})),ug=V((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}}})),dg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=cg();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))}}})),fg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=G(),n=ug(),r=Xh(),i=cg(),a=Yh(),o=lg();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}})),pg=V(((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}})),mg=V(((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}})),hg=V(((e,t)=>{let{isUUID:n}=mg(),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}})),gg=V(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=mg(),{SCHEMES:c,getSchemeHandler:l}=hg();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=_})),_g=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=gg();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),vg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=lg();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=ug(),i=dg(),a=$h(),o=fg(),s=G(),c=cg(),l=tg(),u=Yh(),d=pg(),f=_g(),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=te(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(D.call(this,n,t),!t)return(0,u.eachItem)(n,e=>O.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=>O.call(this,e,r):e=>r.type.forEach(t=>O.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 te(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 E=/^[a-z_$][a-z0-9_$:-]*$/i;function D(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!E.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 O(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?k.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 k(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]}}})),yg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),bg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=dg(),n=rg(),r=G(),i=Xh(),a=fg(),o=Yh(),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})),xg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=yg(),n=bg();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),Sg=V((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})`)}}})),Cg=V((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}))`)}}})),wg=V((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`})),Tg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh(),r=wg();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}`)}}})),Eg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rg(),n=Yh(),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=V((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}`)}}})),Og=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rg(),n=G(),r=Yh();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)}}}})),kg=V((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}`)}}})),Ag=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=og();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),jg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=tg(),n=G(),r=Yh(),i=Ag();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)})))}}}})),Mg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh(),r=Ag();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}`)}}})),Ng=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh(),r=Ag();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}`}}}})),Pg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Sg(),n=Cg(),r=Tg(),i=Eg(),a=Dg(),o=Og(),s=kg(),c=jg(),l=Mg(),u=Ng();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]})),Fg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=G(),n=Yh(),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})),Ig=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=G(),n=Yh(),r=rg(),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})),Lg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ig();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Rg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh(),r=rg(),i=Fg();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)))}}})),zg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh();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)))}}}})),Bg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=G(),n=Yh(),r=rg();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}}})),ng=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=G(),n=Yh();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)}`)}})),rg=H((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=Yh(),r=Xh(),i=Yh();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})),ig=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=G(),n=Xh(),r=rg(),i=Zh();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})),ag=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=G(),n=Yh();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})),og=H(((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}})),sg=H(((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`)}})),cg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=Yh(),n=og(),r=sg(),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})),lg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Qh(),n=tg(),r=eg(),i=tg(),a=ng(),o=ig(),s=ag(),c=G(),l=Xh(),u=cg(),d=Yh(),f=Zh();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),ee(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),E(e)}function T(e,t){if(e.opts.jtd)return j(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);j(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function E(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 ee(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 j(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(()=>I(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)&&I(e,n.keyword,n.definition,t.type)})}function ne(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(N(e,t),e.opts.allowUnionTypes||P(e,t),re(e,e.dataTypes))}function N(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{ae(e.dataTypes,t)||oe(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),F(e,t)}}function P(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&oe(e,`use allowUnionTypes to allow union type keyword`)}function re(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=>ie(t,e))&&oe(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function ie(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function ae(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function F(e,t){let n=[];for(let r of e.dataTypes)ae(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function oe(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var se=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`,le(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=se;function I(e,t,n,r){let i=new se(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 ce=/^\/(?:[^~]|~0|~1)*$/,L=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function le(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!ce.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=L.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=le})),ug=H((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}}})),dg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=cg();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))}}})),fg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=G(),n=ug(),r=Xh(),i=cg(),a=Yh(),o=lg();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}})),pg=H(((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}})),mg=H(((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}})),hg=H(((e,t)=>{let{isUUID:n}=mg(),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}})),gg=H(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=mg(),{SCHEMES:c,getSchemeHandler:l}=hg();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=_})),_g=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=gg();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),vg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=lg();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=ug(),i=dg(),a=$h(),o=fg(),s=G(),c=cg(),l=tg(),u=Yh(),d=pg(),f=_g(),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=ee(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]=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 E={log(){},warn(){},error(){}};function ee(e){if(e===!1)return E;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=M(t)),e.validateSchema=this.compile(t,!0))}let j={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function M(e){return{anyOf:[e,j]}}})),yg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),bg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=dg(),n=rg(),r=G(),i=Xh(),a=fg(),o=Yh(),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})),xg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=yg(),n=bg();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),Sg=H((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})`)}}})),Cg=H((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}))`)}}})),wg=H((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`})),Tg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh(),r=wg();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}`)}}})),Eg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rg(),n=Yh(),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=H((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}`)}}})),Og=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rg(),n=G(),r=Yh();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)}}}})),kg=H((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}`)}}})),Ag=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=og();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),jg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=tg(),n=G(),r=Yh(),i=Ag();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)})))}}}})),Mg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh(),r=Ag();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}`)}}})),Ng=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh(),r=Ag();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}`}}}})),Pg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Sg(),n=Cg(),r=Tg(),i=Eg(),a=Dg(),o=Og(),s=kg(),c=jg(),l=Mg(),u=Ng();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]})),Fg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=G(),n=Yh(),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})),Ig=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=G(),n=Yh(),r=rg(),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})),Lg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ig();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Rg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh(),r=rg(),i=Fg();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)))}}})),zg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh();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)))}}}})),Bg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=G(),n=Yh(),r=rg();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
- 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})),Vg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh();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)}}})),Hg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rg(),n=G(),r=Xh(),i=Yh();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)}}}})),Ug=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=lg(),n=rg(),r=Yh(),i=Hg();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)}}}})),Wg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rg(),n=G(),r=Yh(),i=Yh();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())})})}}}})),Gg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Yh();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`}}})),Kg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:rg().validateUnion,error:{message:`must match a schema in anyOf`}}})),qg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh();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)})})}}}})),Jg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Yh();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)})}}})),Yg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh(),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})),Xg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Yh();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`)}}})),Zg=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Fg(),n=Lg(),r=Ig(),i=Rg(),a=zg(),o=Bg(),s=Vg(),c=Hg(),l=Ug(),u=Wg(),d=Gg(),f=Kg(),p=qg(),m=Jg(),h=Yg(),g=Xg();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=_})),Qg=V((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})`}}}}})),$g=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Qg().default]})),e_=V((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`]})),t_=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=xg(),n=Pg(),r=Zg(),i=$g(),a=e_();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),n_=V((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={}))})),r_=V((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=n_(),r=fg(),i=dg(),a=Yh();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}}}}})),i_=V(((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}})),a_=V(((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=vg(),r=t_(),i=r_(),a=i_(),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=lg();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=ug();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=dg();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),o_=V((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}}})),s_=V((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=a_(),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)})),c_=V(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=o_(),r=s_(),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})),l_=a_(),u_=gf(c_(),1),d_=class{_ajv;constructor(e){this._ajv=e??sf()}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)}}},f_=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft??`2020-12`}getValidator(e){let t=new kd(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 m_(){throw Error(`StdioServerTransport is not supported in this environment. Use StreamableHTTPServerTransport instead.`)}var h_,g_=R((()=>{p_(),h_={get stdin(){return m_()},get stdout(){return m_()}}})),__=at({AjvJsonSchemaValidator:()=>d_,CfWorkerJsonSchemaValidator:()=>f_,DEFAULT_NEGOTIATED_PROTOCOL_VERSION:()=>Df,DEFAULT_REQUEST_TIMEOUT_MSEC:()=>Rh,ExperimentalMcpServerTasks:()=>I_,ExperimentalServerTasks:()=>L_,INTERNAL_ERROR:()=>Pf,INVALID_PARAMS:()=>Nf,INVALID_REQUEST:()=>jf,InMemoryTaskMessageQueue:()=>F_,InMemoryTaskStore:()=>P_,JSONRPC_VERSION:()=>`2.0`,LATEST_PROTOCOL_VERSION:()=>Ef,METHOD_NOT_FOUND:()=>Mf,McpServer:()=>z_,OAuthError:()=>vf,OAuthErrorCode:()=>_f,PARSE_ERROR:()=>Af,ProtocolError:()=>W,ProtocolErrorCode:()=>U,RELATED_TASK_META_KEY:()=>kf,ReadBuffer:()=>Bh,ResourceTemplate:()=>B_,SUPPORTED_PROTOCOL_VERSIONS:()=>Of,SdkError:()=>H,SdkErrorCode:()=>yf,Server:()=>R_,StdioServerTransport:()=>U_,UriTemplate:()=>Kh,UrlElicitationRequiredError:()=>Ff,WebStandardStreamableHTTPServerTransport:()=>W_,assertClientRequestTaskCapability:()=>S_,assertCompleteRequestPrompt:()=>Bd,assertCompleteRequestResourceTemplate:()=>Vd,assertToolsCallTaskCapability:()=>x_,checkResourceAllowed:()=>Nd,completable:()=>v_,createFetchWithInit:()=>tf,deserializeMessage:()=>Yd,fromJsonSchema:()=>M_,getDisplayName:()=>Pd,hostHeaderValidationResponse:()=>j_,isCompletable:()=>y_,isInitializeRequest:()=>Ph,isInitializedNotification:()=>Fh,isJSONRPCErrorResponse:()=>Mh,isJSONRPCNotification:()=>Ah,isJSONRPCRequest:()=>kh,isJSONRPCResultResponse:()=>jh,isTaskAugmentedRequestParams:()=>Nh,isTerminal:()=>Ud,localhostAllowedHostnames:()=>A_,parseJSONRPCMessage:()=>zd,resourceUrlFromServerUrl:()=>Md,serializeMessage:()=>Xd,takeResult:()=>Jd,toArrayAsync:()=>qd,validateHostHeader:()=>k_});function v_(e,t){return Object.defineProperty(e,N_,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function y_(e){return!!e&&typeof e==`object`&&N_ in e}function b_(e){return e[N_]?.complete}function x_(e,t,n){if(!e)throw new H(yf.CapabilityNotSupported,`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw new H(yf.CapabilityNotSupported,`${n} does not support task creation for tools/call (required for ${t})`)}function S_(e,t,n){if(!e)throw new H(yf.CapabilityNotSupported,`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw new H(yf.CapabilityNotSupported,`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw new H(yf.CapabilityNotSupported,`${n} does not support task creation for elicitation/create (required for ${t})`)}}function C_(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 w_(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await af(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 T_(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}function E_(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function D_(e){return e?.type===`optional`}function O_(e){return D_(e)?e.def?.innerType??e:e}function k_(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 A_(){return[`localhost`,`127.0.0.1`,`[::1]`]}function j_(e,t){let n=k_(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 M_(e,t){return cf(e,t??(G_??=new f_))}var N_,P_,F_,I_,L_,R_,z_,B_,V_,H_,U_,W_,G_,K_=R((()=>{p_(),g_(),N_=Symbol.for(`mcp.completable`),P_=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(Ud(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(Ud(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(),Ud(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}))}},F_=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}},I_=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)}},L_=class{constructor(e){this._server=e}get _module(){return this._server.taskManager}requestStream(e,t){let n=Fd(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(yf.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(yf.CapabilityNotSupported,`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw new H(yf.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},Np,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)}},R_=class extends zh{_clientCapabilities;_clientVersion;_capabilities;_instructions;_jsonSchemaValidator;_experimental;oninitialized;constructor(e,t){if(super({...t,tasks:Wd(t?.capabilities?.tasks)}),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new f_,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=Hd(Mm,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 L_(this)},this._experimental}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Mm.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(yf.AlreadyConnected,`Cannot register capabilities after connecting to transport`);let t=!!this._capabilities.logging;this._capabilities=Kd(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}setRequestHandler(e,t){return e===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=Hd(Am,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=Hd(Dp,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=Hd(Om,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(yf.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw new H(yf.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw new H(yf.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw new H(yf.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(yf.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw new H(yf.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(yf.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(yf.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case`completion/complete`:if(!this._capabilities.completions)throw new H(yf.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw new H(yf.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw new H(yf.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(yf.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw new H(yf.CapabilityNotSupported,`Server does not support tools (required for ${e})`)}}assertTaskCapability(e){S_(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){x_(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`},tp)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new H(yf.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},qm,t):this._requestWithSchema({method:`sampling/createMessage`,params:e},Km,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw new H(yf.CapabilityNotSupported,`Client does not support url elicitation.`);let n=e;return this._requestWithSchema({method:`elicitation/create`,params:n},fh,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw new H(yf.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},fh,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(yf.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},bh,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`})}},z_=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_experimental;constructor(e,t){this.server=new R_(e,t)}get experimental(){return this._experimental||={tasks:new I_(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?nf(t.inputSchema,`input`):V_,annotations:t.annotations,execution:t.execution,_meta:t._meta};return t.outputSchema&&(n.outputSchema=nf(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 af(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 af(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 Bd(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Vd(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 H_;let r=O_(E_(n.argsSchema)?.[e.params.argument.name]);if(!y_(r))return H_;let i=b_(r);return i?T_(await i(e.params.argument.value,e.params.context)):H_}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 H_;throw new W(U.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?T_(await r(e.params.argument.value,e.params.context)):H_}_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?of(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:w_(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=w_(e,o,s)),t.enabled!==void 0&&(c.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=c,r){let e=E_(r);e&&Object.values(e).some(e=>y_(O_(e)))&&this.setCompletionRequestHandler()}return c}_createRegisteredTool(e,t,n,r,i,a,o,s,c){$d(e);let l=c,u={title:t,description:n,inputSchema:r,outputSchema:i,annotations:a,execution:o,_meta:s,handler:c,executor:C_(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`&&$d(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=C_(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()}},B_=class{_uriTemplate;constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new Kh(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},V_={type:`object`,properties:{}},H_={completion:{values:[],hasMore:!1}},U_=class{_readBuffer=new Bh;_started=!1;_closed=!1;constructor(e=h_.stdin,t=h_.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=Xd(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)})}},W_=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??Of}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
184
- `;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null},{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let r=e.headers.get(`content-type`);if(!r||!r.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let i=e,a;if(t?.parsedBody===void 0)try{a=await e.json()}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}else a=t.parsedBody;let o;try{o=Array.isArray(a)?a.map(e=>ep.parse(e)):[ep.parse(a)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let s=o.some(e=>Ph(e));if(s){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(o.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!s){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(!o.some(e=>kh(e))){for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,request:i});return new Response(null,{status:202})}let c=crypto.randomUUID(),l=o.find(e=>Ph(e)),u=l?l.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(c,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(c)}});for(let e of o)kh(e)&&this._requestToStreamMapping.set(e.id,c);for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,request:i})});let d=new TextEncoder,f,p=new ReadableStream({start:e=>{f=e},cancel:()=>{this._streamMapping.delete(c)}}),m={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(m[`mcp-session-id`]=this.sessionId);for(let e of o)kh(e)&&(this._streamMapping.set(c,{controller:f,encoder:d,cleanup:()=>{this._streamMapping.delete(c);try{f.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));await this.writePrimingEvent(f,d,c,u);for(let e of o){let n,r;kh(e)&&this._eventStore&&u>=`2025-11-25`&&(n=()=>{this.closeSSEStream(e.id)},r=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,request:i,closeSSEStream:n,closeStandaloneSSEStream:r})}return new Response(p,{status:200,headers:m})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!this._supportedProtocolVersions.includes(t)){let e=`Bad Request: Unsupported protocol version: ${t} (supported versions: ${this._supportedProtocolVersions.join(`, `)})`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(400,-32e3,e)}}async close(){for(let{cleanup:e}of this._streamMapping.values())e();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((jh(e)||Mh(e))&&(n=e.id),n===void 0){if(jh(e)||Mh(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e)),this.writeSSEEvent(i.controller,i.encoder,e,t)}if(jh(e)||Mh(e)){this._requestResponseMap.set(n,e);let t=[...this._requestToStreamMapping.entries()].filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i)throw Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(Response.json(n[0],{status:200,headers:e})):i.resolveJson(Response.json(n,{status:200,headers:e}))}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}}}));async function q_(e,t,n,r={}){let i=Y_(),a=await Promise.resolve().then(()=>(K_(),__)),{fromJsonSchema:o,McpServer:s}=a,c=await J_(a,i),l=new s({name:e,...r.title?{title:r.title}:void 0,version:t},r.instructions?{instructions:r.instructions}:void 0);Z_(l,n,{env:r.env,fromJsonSchema:o,middlewares:r.middlewares,name:e,sendNotification:e=>l.server.notification(e),tools:r.tools,vars:r.vars,version:t});let u=new c(r.input??process.stdin,r.output??process.stdout);await l.connect(u)}async function J_(e,t){let n=e.StdioServerTransport;if(n)return n;let r=await t;if(r.error)throw r.error;return r.module.StdioServerTransport}function Y_(){return Promise.resolve().then(()=>(K_(),__)).then(e=>({module:e})).catch(e=>({error:e}))}async function X_(e,t,n={}){let r=[...n.middlewares??[],...e.middlewares??[],...e.command.middleware??[]],i=await eu(e.command,{agent:!0,argv:[],env:n.env,format:`json`,formatExplicit:!0,inputOptions:t,middlewares:r,name:n.name??e.name,parseMode:`flat`,path:e.name,request:n.request,vars:n.vars,version:n.version});if(`stream`in i){let e=[],t=n.extra?.mcpReq?._meta?.progressToken,r=0;try{for await(let a of i.stream)e.push(a),t!==void 0&&n.sendNotification&&await n.sendNotification({method:`notifications/progress`,params:{progressToken:t,progress:++r,message:Gr(a)}})}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}return{content:[{type:`text`,text:Gr(e)}]}}if(!i.ok){let t=Tu(n.name??e.name,i.cta),r=i.error.fieldErrors?JSON.stringify(i.error):i.error.message??`Command failed`;return{content:[{type:`text`,text:t?`${r}\n\n${Eu(t)}`:r}],...t?{_meta:{cta:t}}:void 0,isError:!0}}let a=i.data??null,o=Kr(a),s=Tu(n.name??e.name,i.cta),c=Gr(o);return{content:[{type:`text`,text:s?`${c}\n\n${Eu(s)}`:c}],...a!==null&&e.outputSchema?{structuredContent:o}:void 0,...s?{_meta:{cta:s}}:void 0}}function Z_(e,t,n){let r=ov(t,[],[],n.tools);if(r.length!==0){if((n.tools?.discovery??`progressive`)===`direct`){for(let t of r)Q_(e,t,n);return}$_(e,r,n)}}function Q_(e,t,n){let r={...t.command.args?.shape,...t.command.options?.shape},i=Object.keys(r).length>0;e.registerTool(t.name,{...t.description?{description:t.description}:void 0,...i?{inputSchema:f.object(r)}:void 0,...t.outputSchema?{outputSchema:n.fromJsonSchema(t.outputSchema)}:void 0,...t.annotations?{annotations:t.annotations}:void 0,...t.instructions?{_meta:{instructions:t.instructions}}:void 0},async(...e)=>X_(t,i?e[0]:{},ev(n,i?e[1]:e[0])))}function $_(e,t,n){let r=new Map(t.map(e=>[e.name,e]));e.registerTool(`search_tools`,{description:`Search or page through available tools by capability. Returns names and descriptions without loading their schemas. Inspect a result before calling it.`,inputSchema:f.object({limit:f.number().int().min(1).max(20).default(5).describe(`Maximum matches.`),offset:f.number().int().min(0).default(0).describe(`Matches to skip.`),query:f.string().default(``).describe(`Capability to find. Empty lists all tools.`)}),annotations:hv},async e=>{let n=tv(t,e.query),r=n.slice(e.offset,e.offset+e.limit);return iv({tools:r.map(e=>({name:e.name,...e.description?{description:e.description}:void 0,...e.annotations?{annotations:e.annotations}:void 0})),...e.offset+r.length<n.length?{nextOffset:e.offset+r.length}:void 0})}),e.registerTool(`get_tool_details`,{description:`Inspect one tool returned by search_tools. Returns its complete input schema and metadata.`,inputSchema:f.object({name:f.string().min(1).describe(`Exact tool name.`)}),annotations:hv},async e=>{let t=r.get(e.name);return t?iv({name:t.name,...t.description?{description:t.description}:void 0,inputSchema:t.inputSchema,...t.outputSchema?{outputSchema:t.outputSchema}:void 0,...t.annotations?{annotations:t.annotations}:void 0,...t.instructions?{instructions:t.instructions}:void 0}):av(`Unknown tool: ${e.name}`)}),e.registerTool(`call_read_tool`,{description:`Execute a tool marked read-only after inspecting its schema with get_tool_details.`,inputSchema:mv,annotations:gv},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?X_(i,e.arguments,ev(n,t)):av(`Tool is not read-only: ${e.name}`):av(`Unknown tool: ${e.name}`)}),e.registerTool(`call_write_tool`,{description:`Execute a writable or unclassified tool after inspecting its schema with get_tool_details.`,inputSchema:mv,annotations:_v},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?av(`Tool is read-only: ${e.name}`):X_(i,e.arguments,ev(n,t)):av(`Unknown tool: ${e.name}`)})}function ev(e,t){return{env:e.env,extra:t,middlewares:e.middlewares,name:e.name,request:e.request?.(t),...e.sendNotification?{sendNotification:e.sendNotification}:void 0,vars:e.vars,version:e.version}}function tv(e,t){let n=rv(t),r=n.split(` `).filter(Boolean);return e.map(e=>({tool:e,score:nv(e,n,r)})).filter(({score:e})=>e>0).sort((e,t)=>t.score-e.score||e.tool.name.localeCompare(t.tool.name)).map(({tool:e})=>e)}function nv(e,t,n){let r=rv(e.name),i=rv(e.description??``);if(r===t)return 1e3;let a=r.startsWith(t)?100:r.includes(t)?50:0;for(let e of n)r.split(` `).includes(e)?a+=20:r.includes(e)&&(a+=10),i.includes(e)&&(a+=2);return a}function rv(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,` `).trim()}function iv(e){return{content:[{type:`text`,text:Gr(e)}]}}function av(e){return{...iv({error:e}),isError:!0}}function ov(e,t,n=[],r){let i=lv(sv(e,t,n),r);return dv(i),i.sort((e,t)=>e.name.localeCompare(t.name))}function sv(e,t,n=[]){let r=[];for(let[i,a]of e){if(`_alias`in a||a.mcp===!1)continue;let e=[...t,i];if(`_group`in a&&a._group){let t=[...n,...a.middlewares??[]];a.root&&a.root.mcp!==!1&&r.push(cv(a.root,e,t)),r.push(...sv(a.commands,e,t))}else r.push(cv(a,e,n))}return r}function cv(e,t,n){let r=e.mcp===!1?void 0:e.mcp,i=e.output?fv(e.output):void 0;return{name:r?.name??t.join(`_`),description:r?.description??e.description,inputSchema:pv(e.args,e.options),...i?{outputSchema:i}:void 0,...r?.annotations?{annotations:r.annotations}:void 0,...r?.instructions?{instructions:r.instructions}:void 0,command:e,...n.length>0?{middlewares:n}:void 0}}function lv(e,t){if(!t)return e;let n=t.include?.map(uv),r=t.exclude?.map(uv)??[];return e.filter(e=>r.some(t=>t.test(e.name))?!1:!n||n.length===0||n.some(t=>t.test(e.name)))}function uv(e){let t=e.replace(/[|\\{}()[\]^$+?.]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function dv(e){let t=new Set;for(let n of e){if(t.has(n.name))throw Error(`Duplicate MCP tool name: ${n.name}`);t.add(n.name)}}function fv(e){let t=Lu(e);if(t.type===`object`)return t}function pv(e,t){let n={},r=[];for(let i of[e,t]){if(!i)continue;let e=Lu(i);Object.assign(n,e.properties??{}),r.push(...e.required??[])}return r.length>0?{type:`object`,properties:n,required:r}:{type:`object`,properties:n}}var mv,hv,gv,_v,vv=R((()=>{uu(),Ou(),qr(),Ru(),mv=f.object({name:f.string().min(1).describe(`Exact tool name.`),arguments:f.record(f.string(),f.unknown()).default({}).describe(`Arguments from its schema.`)}),hv={destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},gv={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},_v={destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1}}));function yv(e){return bv(e,e,new Map)}function bv(e,t,n){if(Array.isArray(e))return e.map(e=>bv(e,t,n));if(typeof e!=`object`||!e)return e;let r=e;if(typeof r.$ref==`string`&&r.$ref.startsWith(`#`)){let e=r.$ref;if(n.has(e))return n.get(e);let i=xv(t,e);if(typeof i!=`object`||!i||Array.isArray(i)){let r=bv(i,t,n);return n.set(e,r),r}let a={};n.set(e,a);let o=bv(i,t,n);return typeof o!=`object`||!o||Array.isArray(o)?(n.set(e,o),o):(Object.assign(a,o),a)}let i={};for(let e of Object.keys(r))i[e]=bv(r[e],t,n);return i}function xv(e,t){let n=t.slice(1);if(n===``||n===`/`)return e;let r=n.slice(1).split(`/`).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),i=e;for(let e of r){if(typeof i!=`object`||!i)throw Error(`Cannot resolve $ref "${t}": path segment "${e}" not found`);if(i=i[e],i===void 0)throw Error(`Cannot resolve $ref "${t}": "${e}" not found`)}return i}var Sv=R((()=>{}));function Cv(e,t={}){let n=Dx.get(e);if(!n)throw Error(`No commands registered on this CLI instance`);let r={},i=Ax.get(e);i&&Ev(r,[],i);for(let[e,t]of n)wv(r,Tv(e),t);return{openapi:`3.2.0`,info:{title:t.title??e.name,version:t.version??`0.0.0`,...t.description??e.description?{description:t.description??e.description}:void 0},...t.servers?{servers:t.servers}:void 0,paths:r}}function wv(e,t,n){if(!(`_alias`in n)&&!(`_fetch`in n)){if(`_group`in n){n.root&&Ev(e,t,n.root);for(let[r,i]of n.commands)wv(e,[...t,...Tv(r)],i);return}Ev(e,t,n)}}function Tv(e){return e.split(/\s+/).filter(Boolean)}function Ev(e,t,n){let r=n.args?Lu(n.args):void 0,i=n.options?Lu(n.options):void 0,a=n.output?Lu(n.output):void 0,o=Pv(r),s=new Set(Fv(r)),c=Ov(t),l=Dv(t,o,s);for(let r of l){let s=[];for(let e of r.args){let t=o[e]??{type:`string`};s.push({name:e,in:`path`,required:!0,schema:t})}if(c===`get`||c===`delete`)for(let[e,t]of Object.entries(Pv(i)))s.push({name:e,in:`query`,...Fv(i).includes(e)?{required:!0}:void 0,schema:t});let l={operationId:Iv(t,c,r.args),...n.description?{summary:n.description}:void 0,...s.length?{parameters:s}:void 0,...Av(c,i),responses:jv(a)},u=e[r.path]??{};u[c]=l,e[r.path]=u}}function Dv(e,t,n){let r=Object.keys(t),i=r.findIndex(e=>!n.has(e)),a=i===-1?r.length:i,o=[];for(let t=a;t<=r.length;t++){let n=r.slice(0,t),i=n.map(e=>`{${e}}`);o.push({args:n,path:`/${[...e,...i].map(Lv).join(`/`)}`})}return o.length===0&&o.push({args:[],path:`/${e.map(Lv).join(`/`)}`}),o}function Ov(e){let t=e.map(kv).join(` `).toLowerCase();return/\b(delete|remove|rm|destroy|clear)\b/.test(t)?`delete`:/\b(update|edit|modify|set|enable|disable|rename|patch)\b/.test(t)?`patch`:/\b(get|list|show|read|search|find|status|describe|info|health|check)\b/.test(t)?`get`:`post`}function kv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`)}function Av(e,t){return!t||e===`get`||e===`delete`?{}:{requestBody:{required:Fv(t).length>0,content:{"application/json":{schema:t}}}}}function jv(e){return{200:{description:`Command completed successfully.`,content:{"application/json":{schema:{type:`object`,required:[`ok`,`data`,`meta`],properties:{ok:{const:!0},data:e??{},meta:Nv()}}}}},400:Mv(`Validation error.`),500:Mv(`Command failed.`)}}function Mv(e){return{description:e,content:{"application/json":{schema:{type:`object`,required:[`ok`,`error`,`meta`],properties:{ok:{const:!1},error:{type:`object`,required:[`code`,`message`],properties:{code:{type:`string`},message:{type:`string`},retryable:{type:`boolean`}}},meta:Nv()}}}}}}function Nv(){return{type:`object`,required:[`command`,`duration`],properties:{command:{type:`string`},duration:{type:`string`}}}}function Pv(e){return e?.properties??{}}function Fv(e){return e?.required??[]}function Iv(e,t,n){return`${t}${[...e,...n.length?[n.join(` `)]:[]].join(` `).replace(/(?:^|[\s_-]+)(\w)/g,(e,t)=>t.toUpperCase())}`}function Lv(e){return e.startsWith(`{`)&&e.endsWith(`}`)?e:encodeURIComponent(e)}async function Rv(e,t={}){if(typeof e!=`string`&&!(e instanceof URL))return e;let n=await fetch(zv(e,t.baseUrl));if(!n.ok)throw Error(`Failed to fetch OpenAPI spec from ${e}: ${n.status}`);return await n.json()}function zv(e,t){if(e instanceof URL)return e;try{return new URL(e)}catch{if(t===void 0)throw Error(`Relative OpenAPI spec URL requires a fetch URL base: ${e}`);let n=new URL(t);return n.pathname.endsWith(`/`)||(n.pathname=`${n.pathname}/`),new URL(e,n)}}async function Bv(e,t,n={}){let r=yv(structuredClone(e)),i=new Map,a=Hv(r.paths??{}),o=Xv(a),{config:s}=n;s?.compact&&Gv(a);for(let{method:e,operation:c,path:l}of a){let a=Zv({method:e,mode:s?.mode??`operation`,namespaceInfo:o,operation:c,path:l}),u=e.toUpperCase(),d=(c.parameters??[]).filter(e=>e.in===`path`),p=(c.parameters??[]).filter(e=>e.in===`query`),m=Jv([...(c.parameters??[]).filter(e=>e.in===`header`),...s?.security===!1?[]:Uv(r,c)]),h=c.requestBody?.content?.[`application/json`]?.schema,g=h?.properties??{},_=new Set(h?.required??[]),v;if(d.length>0){let e={};for(let t of d){let n=t.schema?sy(t.schema):f.string();t.description&&(n=n.describe(t.description)),e[t.name]=cy(n)}v=f.object(e)}let y={},b=new Set;for(let e of p){let t=e.schema?sy(e.schema):f.string();e.required||(t=t.optional()),e.description&&(t=t.describe(e.description)),y[e.name]=cy(t),b.add(e.name)}for(let[e,t]of Object.entries(g)){let n=sy(t);_.has(e)||(n=n.optional()),y[e]=n,b.add(e)}for(let e of m){let t=Yv(e.optionName,b);e.optionName=t;let n=e.schema?sy(e.schema):f.string();e.required||(n=n.optional()),n=n.describe(e.description??`${e.name} header`),y[t]=cy(n),b.add(t)}let x=Object.keys(y).length>0?f.object(y):void 0;iy(i,a,{description:c.summary??c.description,mcp:{annotations:Vv(e),...c.summary&&c.description&&c.summary!==c.description?{description:`${c.summary}\n\n${c.description}`}:void 0},args:v,options:x,run:oy({basePath:n.basePath,fetch:t,forwardHeaders:s?.forwardHeaders,httpMethod:u,path:l,headerParams:m,pathParams:d,queryParams:p,bodyProps:g})})}return i}function Vv(e){let t=[`get`,`head`,`options`,`trace`].includes(e);return{destructiveHint:!t,idempotentHint:t||e===`delete`||e===`put`,openWorldHint:!0,readOnlyHint:t}}function Hv(e){let t=[];for(let[n,r]of Object.entries(e))for(let[e,i]of Object.entries(r))ly.has(e)&&t.push({method:e,operation:i,path:n});return t}function Uv(e,t){let n=e.components?.securitySchemes??{},r=t.security??e.security??[],i=[];for(let e of r)for(let t of Object.keys(e)){let e=n[t],r=Wv(t,e);r&&i.push(r)}return i}function Wv(e,t){if(t){if(t.type===`apiKey`&&t.in===`header`&&t.name)return{description:t.description??`${t.name} header`,in:`header`,name:t.name,required:!1,schema:{type:`string`}};if(t.type===`http`&&uy.has(t.scheme?.toLowerCase()??``))return{description:t.description??`${e} authorization header`,in:`header`,name:`authorization`,required:!1,schema:{type:`string`}}}}function Gv(e){for(let{operation:t}of e){for(let e of t.parameters??[])e.schema&&=Kv(e.schema);let e=t.requestBody?.content?.[`application/json`];e?.schema&&(e.schema=Kv(e.schema))}}function Kv(e,t=new Map){let n=t.get(e);if(n)return n;let r={...e};t.set(e,r),delete r.example,delete r.examples,typeof r.pattern==`string`&&r.pattern.length>dy&&delete r.pattern,typeof r.format==`string`&&fy.has(r.format)&&delete r.format;for(let e of[`allOf`,`anyOf`,`oneOf`,`prefixItems`]){if(!Array.isArray(r[e]))continue;let n=r[e].map(e=>Kv(e,t)).filter(e=>Object.keys(e).length>0);n.length>0?r[e]=n:delete r[e]}for(let e of[`additionalProperties`,`contains`,`items`,`not`,`propertyNames`]){let n=r[e];qv(n)&&(r[e]=Kv(n,t))}for(let e of[`$defs`,`patternProperties`,`properties`]){let n=r[e];if(!qv(n))continue;let i={};for(let[e,r]of Object.entries(n))i[e]=qv(r)?Kv(r,t):r;r[e]=i}return r}function qv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jv(e){let t=new Set,n=[];for(let r of e){let e=r.name.toLowerCase();t.has(e)||(t.add(e),n.push({...r,optionName:e}))}return n}function Yv(e,t){if(!t.has(e))return e;let n=`header-${e}`;if(!t.has(n))return n;for(let e=2;;e++){let r=`${n}-${e}`;if(!t.has(r))return r}}function Xv(e){let t=new Map,n=new Set;for(let{path:r}of e){t.set(r,(t.get(r)??0)+1);let e=$v(r);for(let t=1;t<e.length;t++)n.add(`/${e.slice(0,t).join(`/`)}`)}return{parentPaths:n,pathOperations:t}}function Zv(e){let{method:t,mode:n,namespaceInfo:r,operation:i,path:a}=e;if(n===`operation`)return[{name:i.operationId??`${t}_${a.replace(/[/{}]/g,`_`)}`}];let o=Qv(a,i),s=o.length===0||r.parentPaths.has(ey(a))||(r.pathOperations.get(a)??0)>1,c=ry(o,i.summary??i.description);return[...c.length>0?c:[{name:`root`}],...s?[{name:t}]:[]]}function Qv(e,t){return e.split(`/`).map(e=>ty(e,t)).filter(ny)}function $v(e){return Qv(e).map(e=>e.name)}function ey(e){return`/${$v(e).join(`/`)}`}function ty(e,t){if(!e)return;let n=e.startsWith(`{`)&&e.endsWith(`}`)?e.slice(1,-1):e,r=t?.parameters?.find(e=>e.in===`path`&&e.name===n)?.description;return{...r?{description:r}:void 0,name:n.replace(/[^\w.-]+/g,`-`)}}function ny(e){return e!==void 0}function ry(e,t){return!t||e.length===0?e:e.map((n,r)=>r===e.length-1&&!n.description?{...n,description:t}:n)}function iy(e,t,n){let[r,...i]=t;if(r){if(i.length===0){e.set(r.name,n);return}iy(ay(e,r).commands,i,n)}}function ay(e,t){let n=e.get(t.name);if(n&&`_group`in n)return!n.description&&t.description&&(n.description=t.description),n;let r={_group:!0,commands:new Map,...t.description?{description:t.description}:void 0};return e.set(t.name,r),r}function oy(e){return async t=>{let{args:n={},options:r={}}=t,i=(e.basePath??``)+e.path;for(let t of e.pathParams){let e=n[t.name];e!==void 0&&(i=i.replace(`{${t.name}}`,String(e)))}let a=new URLSearchParams;for(let t of e.queryParams){let e=r[t.name];e!==void 0&&a.set(t.name,String(e))}let o,s=Object.keys(e.bodyProps);if(s.length>0){let e={};for(let t of s)r[t]!==void 0&&(e[t]=r[t]);Object.keys(e).length>0&&(o=JSON.stringify(e))}let c={path:i,method:e.httpMethod,headers:new Headers,body:o,query:a};for(let t of e.headerParams){let e=r[t.optionName];e!==void 0&&c.headers.set(t.name,String(e))}for(let n of e.forwardHeaders??[]){let e=t.request?.headers.get(n);!c.headers.has(n)&&e!=null&&c.headers.set(n,e)}o&&!c.headers.has(`content-type`)&&c.headers.set(`content-type`,`application/json`);let l=In(c),u=await zn(await e.fetch(l));return u.ok?u.data:t.error({code:`HTTP_${u.status}`,message:typeof u.data==`object`&&u.data!==null&&`message`in u.data?String(u.data.message):typeof u.data==`string`?u.data:`HTTP ${u.status}`})}}function sy(e){return f.fromJSONSchema(e)}function cy(e){let t=e instanceof f.ZodOptional,n=t?e.unwrap():e,r=(()=>{if(n instanceof f.ZodNumber)return t?f.coerce.number().optional():f.coerce.number();if(n instanceof f.ZodBoolean)return t?f.coerce.boolean().optional():f.coerce.boolean();if(n instanceof f.ZodUnion){let e=n._zod?.def?.options;if(e?.some(e=>e instanceof f.ZodNumber))return t?f.coerce.number().optional():f.coerce.number();if(e?.some(e=>e instanceof f.ZodBoolean))return t?f.coerce.boolean().optional():f.coerce.boolean()}})();if(!r)return e;let i=e.description??n.description;return i?r.describe(i):r}var ly,uy,dy,fy,py=R((()=>{Lx(),Hn(),Sv(),Ru(),ly=new Set([`delete`,`get`,`head`,`options`,`patch`,`post`,`put`,`trace`]),uy=new Set([`basic`,`bearer`]),dy=100,fy=new Set([`date`,`date-time`,`duration`,`time`])}));async function my(e,t={}){let n=yy(e);await by(n,`initialize`,{protocolVersion:Ey,capabilities:{},clientInfo:{name:`incur`,version:t.version??`1.0.0`}}),n.initialized=!0,await by(n,`notifications/initialized`);let r=(await by(n,`tools/list`)).tools??[];return gy(r)?{discovery:`progressive`,tools:await _y(n),session:n}:{tools:r,session:n}}function hy(e){let t=new Map;for(let n of e.tools){let r=n.inputSchema?Sy(n.inputSchema):void 0,i=Cy(n.outputSchema);t.set(n.name,{description:n.description,...n.annotations?{mcp:{annotations:n.annotations}}:void 0,...r?{options:r}:void 0,...i?{output:i}:void 0,async run(t){let r={name:n.name,arguments:{...t.args,...t.options}},i=await by(e.session,`tools/call`,e.discovery===`progressive`?{name:n.annotations?.readOnlyHint===!0?`call_read_tool`:`call_write_tool`,arguments:r}:r);return i.isError?t.error({code:`MCP_TOOL_ERROR`,message:wy(i)}):Ty(i)}})}return t}function gy(e){if(e.length!==4)return!1;let t=new Set(e.map(e=>e.name));return t.has(`search_tools`)&&t.has(`get_tool_details`)&&t.has(`call_read_tool`)&&t.has(`call_write_tool`)}async function _y(e){let t=[],n=0;for(;n!==void 0;){let r=await vy(e,`search_tools`,{query:``,limit:20,offset:n});for(let n of r.tools??[]){if(!n.name)continue;let r=await vy(e,`get_tool_details`,{name:n.name});r.name&&t.push(r)}if(r.nextOffset!==void 0&&r.nextOffset<=n)throw Error(`MCP tool catalog returned a non-advancing offset`);n=r.nextOffset}return t}async function vy(e,t,n){let r=await by(e,`tools/call`,{name:t,arguments:n});if(r.isError)throw Error(wy(r)||`MCP tool failed: ${t}`);return Ty(r)}function yy(e){return typeof e==`string`||e instanceof URL?{url:new URL(e),fetch:globalThis.fetch.bind(globalThis)}:{url:new URL(e.url),fetch:e.fetch??globalThis.fetch.bind(globalThis),...e.headers?{headers:e.headers}:void 0}}async function by(e,t,n){let r=t.startsWith(`notifications/`),i=r?void 0:crypto.randomUUID(),a=new Headers(e.headers);a.set(`content-type`,`application/json`),a.set(`accept`,`application/json, text/event-stream`),e.id&&a.set(`mcp-session-id`,e.id),e.initialized&&a.set(`MCP-Protocol-Version`,Ey);let o=JSON.stringify({jsonrpc:`2.0`,...i?{id:i}:void 0,method:t,params:n}),s=await e.fetch(new Request(e.url,{method:`POST`,headers:a,body:o})),c=s.headers.get(`mcp-session-id`);if(c&&(e.id=c),!s.ok)throw Error(`MCP HTTP ${s.status}`);if(r&&s.status===202)return{};let l=await s.text();if(!l)return{};let u=(s.headers.get(`content-type`)??``).includes(`text/event-stream`)?xy(l,i):JSON.parse(l);if(u.error)throw Error(u.error.message??`MCP request failed`);return u.result??{}}function xy(e,t){for(let n of e.split(/\r?\n\r?\n/)){let e=n.split(/\r?\n/).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(`
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})),Vg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh();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)}}})),Hg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rg(),n=G(),r=Xh(),i=Yh();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)}}}})),Ug=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=lg(),n=rg(),r=Yh(),i=Hg();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)}}}})),Wg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rg(),n=G(),r=Yh(),i=Yh();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())})})}}}})),Gg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Yh();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`}}})),Kg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:rg().validateUnion,error:{message:`must match a schema in anyOf`}}})),qg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh();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)})})}}}})),Jg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Yh();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)})}}})),Yg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=Yh(),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})),Xg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Yh();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`)}}})),Zg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Fg(),n=Lg(),r=Ig(),i=Rg(),a=zg(),o=Bg(),s=Vg(),c=Hg(),l=Ug(),u=Wg(),d=Gg(),f=Kg(),p=qg(),m=Jg(),h=Yg(),g=Xg();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=_})),Qg=H((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})`}}}}})),$g=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Qg().default]})),e_=H((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`]})),t_=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=xg(),n=Pg(),r=Zg(),i=$g(),a=e_();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),n_=H((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={}))})),r_=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G(),n=n_(),r=fg(),i=dg(),a=Yh();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}}}}})),i_=H(((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}})),a_=H(((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=vg(),r=t_(),i=r_(),a=i_(),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=lg();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=ug();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=dg();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),o_=H((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:E,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 E(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),s_=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=a_(),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)})),c_=H(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=o_(),r=s_(),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})),l_=a_(),u_=hf(c_(),1),d_=class{_ajv;constructor(e){this._ajv=e??of()}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)}}},f_=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft??`2020-12`}getValidator(e){let t=new Od(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 m_(){throw Error(`StdioServerTransport is not supported in this environment. Use StreamableHTTPServerTransport instead.`)}var h_,g_=z((()=>{p_(),h_={get stdin(){return m_()},get stdout(){return m_()}}})),__=it({AjvJsonSchemaValidator:()=>d_,CfWorkerJsonSchemaValidator:()=>f_,DEFAULT_NEGOTIATED_PROTOCOL_VERSION:()=>Df,DEFAULT_REQUEST_TIMEOUT_MSEC:()=>Rh,ExperimentalMcpServerTasks:()=>I_,ExperimentalServerTasks:()=>L_,INTERNAL_ERROR:()=>Pf,INVALID_PARAMS:()=>Nf,INVALID_REQUEST:()=>jf,InMemoryTaskMessageQueue:()=>F_,InMemoryTaskStore:()=>P_,JSONRPC_VERSION:()=>`2.0`,LATEST_PROTOCOL_VERSION:()=>Ef,METHOD_NOT_FOUND:()=>Mf,McpServer:()=>z_,OAuthError:()=>_f,OAuthErrorCode:()=>gf,PARSE_ERROR:()=>Af,ProtocolError:()=>W,ProtocolErrorCode:()=>U,RELATED_TASK_META_KEY:()=>kf,ReadBuffer:()=>Bh,ResourceTemplate:()=>B_,SUPPORTED_PROTOCOL_VERSIONS:()=>Of,SdkError:()=>yf,SdkErrorCode:()=>vf,Server:()=>R_,StdioServerTransport:()=>U_,UriTemplate:()=>Kh,UrlElicitationRequiredError:()=>Ff,WebStandardStreamableHTTPServerTransport:()=>W_,assertClientRequestTaskCapability:()=>S_,assertCompleteRequestPrompt:()=>zd,assertCompleteRequestResourceTemplate:()=>Bd,assertToolsCallTaskCapability:()=>x_,checkResourceAllowed:()=>Md,completable:()=>v_,createFetchWithInit:()=>ef,deserializeMessage:()=>Jd,fromJsonSchema:()=>M_,getDisplayName:()=>Nd,hostHeaderValidationResponse:()=>j_,isCompletable:()=>y_,isInitializeRequest:()=>Ph,isInitializedNotification:()=>Fh,isJSONRPCErrorResponse:()=>Mh,isJSONRPCNotification:()=>Ah,isJSONRPCRequest:()=>kh,isJSONRPCResultResponse:()=>jh,isTaskAugmentedRequestParams:()=>Nh,isTerminal:()=>Hd,localhostAllowedHostnames:()=>A_,parseJSONRPCMessage:()=>Rd,resourceUrlFromServerUrl:()=>jd,serializeMessage:()=>Yd,takeResult:()=>qd,toArrayAsync:()=>Kd,validateHostHeader:()=>k_});function v_(e,t){return Object.defineProperty(e,N_,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function y_(e){return!!e&&typeof e==`object`&&N_ in e}function b_(e){return e[N_]?.complete}function x_(e,t,n){if(!e)throw new yf(vf.CapabilityNotSupported,`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw new yf(vf.CapabilityNotSupported,`${n} does not support task creation for tools/call (required for ${t})`)}function S_(e,t,n){if(!e)throw new yf(vf.CapabilityNotSupported,`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw new yf(vf.CapabilityNotSupported,`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw new yf(vf.CapabilityNotSupported,`${n} does not support task creation for elicitation/create (required for ${t})`)}}function C_(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 w_(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await rf(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 T_(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}function E_(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function D_(e){return e?.type===`optional`}function O_(e){return D_(e)?e.def?.innerType??e:e}function k_(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 A_(){return[`localhost`,`127.0.0.1`,`[::1]`]}function j_(e,t){let n=k_(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 M_(e,t){return sf(e,t??(G_??=new f_))}var N_,P_,F_,I_,L_,R_,z_,B_,V_,H_,U_,W_,G_,K_=z((()=>{p_(),g_(),N_=Symbol.for(`mcp.completable`),P_=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(Hd(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(Hd(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(),Hd(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}))}},F_=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}},I_=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)}},L_=class{constructor(e){this._server=e}get _module(){return this._server.taskManager}requestStream(e,t){let n=Pd(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 yf(vf.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 yf(vf.CapabilityNotSupported,`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw new yf(vf.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},Np,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)}},R_=class extends zh{_clientCapabilities;_clientVersion;_capabilities;_instructions;_jsonSchemaValidator;_experimental;oninitialized;constructor(e,t){if(super({...t,tasks:Ud(t?.capabilities?.tasks)}),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new f_,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=Vd(Mm,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 L_(this)},this._experimental}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Mm.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 yf(vf.AlreadyConnected,`Cannot register capabilities after connecting to transport`);let t=!!this._capabilities.logging;this._capabilities=Gd(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}setRequestHandler(e,t){return e===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=Vd(Am,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=Vd(Dp,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=Vd(Om,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 yf(vf.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw new yf(vf.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw new yf(vf.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw new yf(vf.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 yf(vf.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw new yf(vf.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 yf(vf.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 yf(vf.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case`completion/complete`:if(!this._capabilities.completions)throw new yf(vf.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw new yf(vf.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw new yf(vf.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 yf(vf.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw new yf(vf.CapabilityNotSupported,`Server does not support tools (required for ${e})`)}}assertTaskCapability(e){S_(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){x_(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`},tp)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new yf(vf.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},qm,t):this._requestWithSchema({method:`sampling/createMessage`,params:e},Km,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw new yf(vf.CapabilityNotSupported,`Client does not support url elicitation.`);let n=e;return this._requestWithSchema({method:`elicitation/create`,params:n},fh,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw new yf(vf.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},fh,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 yf(vf.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},bh,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`})}},z_=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_experimental;constructor(e,t){this.server=new R_(e,t)}get experimental(){return this._experimental||={tasks:new I_(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?tf(t.inputSchema,`input`):V_,annotations:t.annotations,execution:t.execution,_meta:t._meta};return t.outputSchema&&(n.outputSchema=tf(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 rf(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 rf(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 zd(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Bd(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 H_;let r=O_(E_(n.argsSchema)?.[e.params.argument.name]);if(!y_(r))return H_;let i=b_(r);return i?T_(await i(e.params.argument.value,e.params.context)):H_}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 H_;throw new W(U.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?T_(await r(e.params.argument.value,e.params.context)):H_}_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?af(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:w_(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=w_(e,o,s)),t.enabled!==void 0&&(c.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=c,r){let e=E_(r);e&&Object.values(e).some(e=>y_(O_(e)))&&this.setCompletionRequestHandler()}return c}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Qd(e);let l=c,u={title:t,description:n,inputSchema:r,outputSchema:i,annotations:a,execution:o,_meta:s,handler:c,executor:C_(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`&&Qd(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=C_(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()}},B_=class{_uriTemplate;constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new Kh(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},V_={type:`object`,properties:{}},H_={completion:{values:[],hasMore:!1}},U_=class{_readBuffer=new Bh;_started=!1;_closed=!1;constructor(e=h_.stdin,t=h_.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=Yd(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)})}},W_=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??Of}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
184
+ `;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null},{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let r=e.headers.get(`content-type`);if(!r||!r.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let i=e,a;if(t?.parsedBody===void 0)try{a=await e.json()}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}else a=t.parsedBody;let o;try{o=Array.isArray(a)?a.map(e=>ep.parse(e)):[ep.parse(a)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let s=o.some(e=>Ph(e));if(s){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(o.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!s){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(!o.some(e=>kh(e))){for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,request:i});return new Response(null,{status:202})}let c=crypto.randomUUID(),l=o.find(e=>Ph(e)),u=l?l.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(c,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(c)}});for(let e of o)kh(e)&&this._requestToStreamMapping.set(e.id,c);for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,request:i})});let d=new TextEncoder,f,p=new ReadableStream({start:e=>{f=e},cancel:()=>{this._streamMapping.delete(c)}}),m={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(m[`mcp-session-id`]=this.sessionId);for(let e of o)kh(e)&&(this._streamMapping.set(c,{controller:f,encoder:d,cleanup:()=>{this._streamMapping.delete(c);try{f.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));await this.writePrimingEvent(f,d,c,u);for(let e of o){let n,r;kh(e)&&this._eventStore&&u>=`2025-11-25`&&(n=()=>{this.closeSSEStream(e.id)},r=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,request:i,closeSSEStream:n,closeStandaloneSSEStream:r})}return new Response(p,{status:200,headers:m})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!this._supportedProtocolVersions.includes(t)){let e=`Bad Request: Unsupported protocol version: ${t} (supported versions: ${this._supportedProtocolVersions.join(`, `)})`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(400,-32e3,e)}}async close(){for(let{cleanup:e}of this._streamMapping.values())e();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((jh(e)||Mh(e))&&(n=e.id),n===void 0){if(jh(e)||Mh(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e)),this.writeSSEEvent(i.controller,i.encoder,e,t)}if(jh(e)||Mh(e)){this._requestResponseMap.set(n,e);let t=[...this._requestToStreamMapping.entries()].filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i)throw Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(Response.json(n[0],{status:200,headers:e})):i.resolveJson(Response.json(n,{status:200,headers:e}))}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}}}));async function q_(e,t,n,r={}){let i=Y_(),a=await Promise.resolve().then(()=>(K_(),__)),{fromJsonSchema:o,McpServer:s}=a,c=await J_(a,i),l=new s({name:e,...r.title?{title:r.title}:void 0,version:t},r.instructions?{instructions:r.instructions}:void 0);Z_(l,n,{env:r.env,fromJsonSchema:o,middlewares:r.middlewares,name:e,sendNotification:e=>l.server.notification(e),tools:r.tools,vars:r.vars,version:t});let u=new c(r.input??process.stdin,r.output??process.stdout);await l.connect(u)}async function J_(e,t){let n=e.StdioServerTransport;if(n)return n;let r=await t;if(r.error)throw r.error;return r.module.StdioServerTransport}function Y_(){return Promise.resolve().then(()=>(K_(),__)).then(e=>({module:e})).catch(e=>({error:e}))}async function X_(e,t,n={}){let r=[...n.middlewares??[],...e.middlewares??[],...e.command.middleware??[]],i=await $l(e.command,{agent:!0,argv:[],env:n.env,format:`json`,formatExplicit:!0,inputOptions:t,middlewares:r,name:n.name??e.name,parseMode:`flat`,path:e.name,request:n.request,vars:n.vars,version:n.version});if(`stream`in i){let e=[],t=n.extra?.mcpReq?._meta?.progressToken,r=0;try{for await(let a of i.stream)e.push(a),t!==void 0&&n.sendNotification&&await n.sendNotification({method:`notifications/progress`,params:{progressToken:t,progress:++r,message:Wr(a)}})}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}return{content:[{type:`text`,text:Wr(e)}]}}if(!i.ok){let t=wu(n.name??e.name,i.cta),r=i.error.fieldErrors?JSON.stringify(i.error):i.error.message??`Command failed`;return{content:[{type:`text`,text:t?`${r}\n\n${Tu(t)}`:r}],...t?{_meta:{cta:t}}:void 0,isError:!0}}let a=i.data??null,o=Gr(a),s=wu(n.name??e.name,i.cta),c=Wr(o);return{content:[{type:`text`,text:s?`${c}\n\n${Tu(s)}`:c}],...a!==null&&e.outputSchema?{structuredContent:o}:void 0,...s?{_meta:{cta:s}}:void 0}}function Z_(e,t,n){let r=ov(t,[],[],n.tools);if(r.length!==0){if((n.tools?.discovery??`progressive`)===`direct`){for(let t of r)Q_(e,t,n);return}$_(e,r,n)}}function Q_(e,t,n){let r={...t.command.args?.shape,...t.command.options?.shape},i=Object.keys(r).length>0;e.registerTool(t.name,{...t.description?{description:t.description}:void 0,...i?{inputSchema:f.object(r)}:void 0,...t.outputSchema?{outputSchema:n.fromJsonSchema(t.outputSchema)}:void 0,...t.annotations?{annotations:t.annotations}:void 0,...t.instructions?{_meta:{instructions:t.instructions}}:void 0},async(...e)=>X_(t,i?e[0]:{},ev(n,i?e[1]:e[0])))}function $_(e,t,n){let r=new Map(t.map(e=>[e.name,e]));e.registerTool(`search_tools`,{description:`Search or page through available tools by capability. Returns names and descriptions without loading their schemas. Inspect a result before calling it.`,inputSchema:f.object({limit:f.number().int().min(1).max(20).default(5).describe(`Maximum matches.`),offset:f.number().int().min(0).default(0).describe(`Matches to skip.`),query:f.string().default(``).describe(`Capability to find. Empty lists all tools.`)}),annotations:hv},async e=>{let n=tv(t,e.query),r=n.slice(e.offset,e.offset+e.limit);return iv({tools:r.map(e=>({name:e.name,...e.description?{description:e.description}:void 0,...e.annotations?{annotations:e.annotations}:void 0})),...e.offset+r.length<n.length?{nextOffset:e.offset+r.length}:void 0})}),e.registerTool(`get_tool_details`,{description:`Inspect one tool returned by search_tools. Returns its complete input schema and metadata.`,inputSchema:f.object({name:f.string().min(1).describe(`Exact tool name.`)}),annotations:hv},async e=>{let t=r.get(e.name);return t?iv({name:t.name,...t.description?{description:t.description}:void 0,inputSchema:t.inputSchema,...t.outputSchema?{outputSchema:t.outputSchema}:void 0,...t.annotations?{annotations:t.annotations}:void 0,...t.instructions?{instructions:t.instructions}:void 0}):av(`Unknown tool: ${e.name}`)}),e.registerTool(`call_read_tool`,{description:`Execute a tool marked read-only after inspecting its schema with get_tool_details.`,inputSchema:mv,annotations:gv},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?X_(i,e.arguments,ev(n,t)):av(`Tool is not read-only: ${e.name}`):av(`Unknown tool: ${e.name}`)}),e.registerTool(`call_write_tool`,{description:`Execute a writable or unclassified tool after inspecting its schema with get_tool_details.`,inputSchema:mv,annotations:_v},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?av(`Tool is read-only: ${e.name}`):X_(i,e.arguments,ev(n,t)):av(`Unknown tool: ${e.name}`)})}function ev(e,t){return{env:e.env,extra:t,middlewares:e.middlewares,name:e.name,request:e.request?.(t),...e.sendNotification?{sendNotification:e.sendNotification}:void 0,vars:e.vars,version:e.version}}function tv(e,t){let n=rv(t),r=n.split(` `).filter(Boolean);return e.map(e=>({tool:e,score:nv(e,n,r)})).filter(({score:e})=>e>0).sort((e,t)=>t.score-e.score||e.tool.name.localeCompare(t.tool.name)).map(({tool:e})=>e)}function nv(e,t,n){let r=rv(e.name),i=rv(e.description??``);if(r===t)return 1e3;let a=r.startsWith(t)?100:r.includes(t)?50:0;for(let e of n)r.split(` `).includes(e)?a+=20:r.includes(e)&&(a+=10),i.includes(e)&&(a+=2);return a}function rv(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,` `).trim()}function iv(e){return{content:[{type:`text`,text:Wr(e)}]}}function av(e){return{...iv({error:e}),isError:!0}}function ov(e,t,n=[],r){let i=lv(sv(e,t,n),r);return dv(i),i.sort((e,t)=>e.name.localeCompare(t.name))}function sv(e,t,n=[]){let r=[];for(let[i,a]of e){if(`_alias`in a||a.mcp===!1)continue;let e=[...t,i];if(`_group`in a&&a._group){let t=[...n,...a.middlewares??[]];a.root&&a.root.mcp!==!1&&r.push(cv(a.root,e,t)),r.push(...sv(a.commands,e,t))}else r.push(cv(a,e,n))}return r}function cv(e,t,n){let r=e.mcp===!1?void 0:e.mcp,i=e.output?fv(e.output):void 0;return{name:r?.name??t.join(`_`),description:r?.description??e.description,inputSchema:pv(e.args,e.options),...i?{outputSchema:i}:void 0,...r?.annotations?{annotations:r.annotations}:void 0,...r?.instructions?{instructions:r.instructions}:void 0,command:e,...n.length>0?{middlewares:n}:void 0}}function lv(e,t){if(!t)return e;let n=t.include?.map(uv),r=t.exclude?.map(uv)??[];return e.filter(e=>r.some(t=>t.test(e.name))?!1:!n||n.length===0||n.some(t=>t.test(e.name)))}function uv(e){let t=e.replace(/[|\\{}()[\]^$+?.]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function dv(e){let t=new Set;for(let n of e){if(t.has(n.name))throw Error(`Duplicate MCP tool name: ${n.name}`);t.add(n.name)}}function fv(e){let t=Iu(e);if(t.type===`object`)return t}function pv(e,t){let n={},r=[];for(let i of[e,t]){if(!i)continue;let e=Iu(i);Object.assign(n,e.properties??{}),r.push(...e.required??[])}return r.length>0?{type:`object`,properties:n,required:r}:{type:`object`,properties:n}}var mv,hv,gv,_v,vv=z((()=>{lu(),Du(),Kr(),Lu(),mv=f.object({name:f.string().min(1).describe(`Exact tool name.`),arguments:f.record(f.string(),f.unknown()).default({}).describe(`Arguments from its schema.`)}),hv={destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},gv={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},_v={destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1}}));function yv(e){return bv(e,e,new Map)}function bv(e,t,n){if(Array.isArray(e))return e.map(e=>bv(e,t,n));if(typeof e!=`object`||!e)return e;let r=e;if(typeof r.$ref==`string`&&r.$ref.startsWith(`#`)){let e=r.$ref;if(n.has(e))return n.get(e);let i=xv(t,e);if(typeof i!=`object`||!i||Array.isArray(i)){let r=bv(i,t,n);return n.set(e,r),r}let a={};n.set(e,a);let o=bv(i,t,n);return typeof o!=`object`||!o||Array.isArray(o)?(n.set(e,o),o):(Object.assign(a,o),a)}let i={};for(let e of Object.keys(r))i[e]=bv(r[e],t,n);return i}function xv(e,t){let n=t.slice(1);if(n===``||n===`/`)return e;let r=n.slice(1).split(`/`).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),i=e;for(let e of r){if(typeof i!=`object`||!i)throw Error(`Cannot resolve $ref "${t}": path segment "${e}" not found`);if(i=i[e],i===void 0)throw Error(`Cannot resolve $ref "${t}": "${e}" not found`)}return i}var Sv=z((()=>{}));function Cv(e,t={}){let n=Dx.get(e);if(!n)throw Error(`No commands registered on this CLI instance`);let r={},i=Ax.get(e);i&&Ev(r,[],i);for(let[e,t]of n)wv(r,Tv(e),t);return{openapi:`3.2.0`,info:{title:t.title??e.name,version:t.version??`0.0.0`,...t.description??e.description?{description:t.description??e.description}:void 0},...t.servers?{servers:t.servers}:void 0,paths:r}}function wv(e,t,n){if(!(`_alias`in n)&&!(`_fetch`in n)){if(`_group`in n){n.root&&Ev(e,t,n.root);for(let[r,i]of n.commands)wv(e,[...t,...Tv(r)],i);return}Ev(e,t,n)}}function Tv(e){return e.split(/\s+/).filter(Boolean)}function Ev(e,t,n){let r=n.args?Iu(n.args):void 0,i=n.options?Iu(n.options):void 0,a=n.output?Iu(n.output):void 0,o=Pv(r),s=new Set(Fv(r)),c=Ov(t),l=Dv(t,o,s);for(let r of l){let s=[];for(let e of r.args){let t=o[e]??{type:`string`};s.push({name:e,in:`path`,required:!0,schema:t})}if(c===`get`||c===`delete`)for(let[e,t]of Object.entries(Pv(i)))s.push({name:e,in:`query`,...Fv(i).includes(e)?{required:!0}:void 0,schema:t});let l={operationId:Iv(t,c,r.args),...n.description?{summary:n.description}:void 0,...s.length?{parameters:s}:void 0,...Av(c,i),responses:jv(a)},u=e[r.path]??{};u[c]=l,e[r.path]=u}}function Dv(e,t,n){let r=Object.keys(t),i=r.findIndex(e=>!n.has(e)),a=i===-1?r.length:i,o=[];for(let t=a;t<=r.length;t++){let n=r.slice(0,t),i=n.map(e=>`{${e}}`);o.push({args:n,path:`/${[...e,...i].map(Lv).join(`/`)}`})}return o.length===0&&o.push({args:[],path:`/${e.map(Lv).join(`/`)}`}),o}function Ov(e){let t=e.map(kv).join(` `).toLowerCase();return/\b(delete|remove|rm|destroy|clear)\b/.test(t)?`delete`:/\b(update|edit|modify|set|enable|disable|rename|patch)\b/.test(t)?`patch`:/\b(get|list|show|read|search|find|status|describe|info|health|check)\b/.test(t)?`get`:`post`}function kv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`)}function Av(e,t){return!t||e===`get`||e===`delete`?{}:{requestBody:{required:Fv(t).length>0,content:{"application/json":{schema:t}}}}}function jv(e){return{200:{description:`Command completed successfully.`,content:{"application/json":{schema:{type:`object`,required:[`ok`,`data`,`meta`],properties:{ok:{const:!0},data:e??{},meta:Nv()}}}}},400:Mv(`Validation error.`),500:Mv(`Command failed.`)}}function Mv(e){return{description:e,content:{"application/json":{schema:{type:`object`,required:[`ok`,`error`,`meta`],properties:{ok:{const:!1},error:{type:`object`,required:[`code`,`message`],properties:{code:{type:`string`},message:{type:`string`},retryable:{type:`boolean`}}},meta:Nv()}}}}}}function Nv(){return{type:`object`,required:[`command`,`duration`],properties:{command:{type:`string`},duration:{type:`string`}}}}function Pv(e){return e?.properties??{}}function Fv(e){return e?.required??[]}function Iv(e,t,n){return`${t}${[...e,...n.length?[n.join(` `)]:[]].join(` `).replace(/(?:^|[\s_-]+)(\w)/g,(e,t)=>t.toUpperCase())}`}function Lv(e){return e.startsWith(`{`)&&e.endsWith(`}`)?e:encodeURIComponent(e)}async function Rv(e,t={}){if(typeof e!=`string`&&!(e instanceof URL))return e;let n=await fetch(zv(e,t.baseUrl));if(!n.ok)throw Error(`Failed to fetch OpenAPI spec from ${e}: ${n.status}`);return await n.json()}function zv(e,t){if(e instanceof URL)return e;try{return new URL(e)}catch{if(t===void 0)throw Error(`Relative OpenAPI spec URL requires a fetch URL base: ${e}`);let n=new URL(t);return n.pathname.endsWith(`/`)||(n.pathname=`${n.pathname}/`),new URL(e,n)}}async function Bv(e,t,n={}){let r=yv(structuredClone(e)),i=new Map,a=Hv(r.paths??{}),o=Xv(a),{config:s}=n;s?.compact&&Gv(a);for(let{method:e,operation:c,path:l}of a){let a=Zv({method:e,mode:s?.mode??`operation`,namespaceInfo:o,operation:c,path:l}),u=e.toUpperCase(),d=(c.parameters??[]).filter(e=>e.in===`path`),p=(c.parameters??[]).filter(e=>e.in===`query`),m=Jv([...(c.parameters??[]).filter(e=>e.in===`header`),...s?.security===!1?[]:Uv(r,c)]),h=c.requestBody?.content?.[`application/json`]?.schema,g=h?.properties??{},_=new Set(h?.required??[]),v;if(d.length>0){let e={};for(let t of d){let n=t.schema?sy(t.schema):f.string();t.description&&(n=n.describe(t.description)),e[t.name]=cy(n)}v=f.object(e)}let y={},b=new Set;for(let e of p){let t=e.schema?sy(e.schema):f.string();e.required||(t=t.optional()),e.description&&(t=t.describe(e.description)),y[e.name]=cy(t),b.add(e.name)}for(let[e,t]of Object.entries(g)){let n=sy(t);_.has(e)||(n=n.optional()),y[e]=n,b.add(e)}for(let e of m){let t=Yv(e.optionName,b);e.optionName=t;let n=e.schema?sy(e.schema):f.string();e.required||(n=n.optional()),n=n.describe(e.description??`${e.name} header`),y[t]=cy(n),b.add(t)}let x=Object.keys(y).length>0?f.object(y):void 0;iy(i,a,{description:c.summary??c.description,mcp:{annotations:Vv(e),...c.summary&&c.description&&c.summary!==c.description?{description:`${c.summary}\n\n${c.description}`}:void 0},args:v,options:x,run:oy({basePath:n.basePath,fetch:t,forwardHeaders:s?.forwardHeaders,httpMethod:u,path:l,headerParams:m,pathParams:d,queryParams:p,bodyProps:g})})}return i}function Vv(e){let t=[`get`,`head`,`options`,`trace`].includes(e);return{destructiveHint:!t,idempotentHint:t||e===`delete`||e===`put`,openWorldHint:!0,readOnlyHint:t}}function Hv(e){let t=[];for(let[n,r]of Object.entries(e))for(let[e,i]of Object.entries(r))ly.has(e)&&t.push({method:e,operation:i,path:n});return t}function Uv(e,t){let n=e.components?.securitySchemes??{},r=t.security??e.security??[],i=[];for(let e of r)for(let t of Object.keys(e)){let e=n[t],r=Wv(t,e);r&&i.push(r)}return i}function Wv(e,t){if(t){if(t.type===`apiKey`&&t.in===`header`&&t.name)return{description:t.description??`${t.name} header`,in:`header`,name:t.name,required:!1,schema:{type:`string`}};if(t.type===`http`&&uy.has(t.scheme?.toLowerCase()??``))return{description:t.description??`${e} authorization header`,in:`header`,name:`authorization`,required:!1,schema:{type:`string`}}}}function Gv(e){for(let{operation:t}of e){for(let e of t.parameters??[])e.schema&&=Kv(e.schema);let e=t.requestBody?.content?.[`application/json`];e?.schema&&(e.schema=Kv(e.schema))}}function Kv(e,t=new Map){let n=t.get(e);if(n)return n;let r={...e};t.set(e,r),delete r.example,delete r.examples,typeof r.pattern==`string`&&r.pattern.length>dy&&delete r.pattern,typeof r.format==`string`&&fy.has(r.format)&&delete r.format;for(let e of[`allOf`,`anyOf`,`oneOf`,`prefixItems`]){if(!Array.isArray(r[e]))continue;let n=r[e].map(e=>Kv(e,t)).filter(e=>Object.keys(e).length>0);n.length>0?r[e]=n:delete r[e]}for(let e of[`additionalProperties`,`contains`,`items`,`not`,`propertyNames`]){let n=r[e];qv(n)&&(r[e]=Kv(n,t))}for(let e of[`$defs`,`patternProperties`,`properties`]){let n=r[e];if(!qv(n))continue;let i={};for(let[e,r]of Object.entries(n))i[e]=qv(r)?Kv(r,t):r;r[e]=i}return r}function qv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jv(e){let t=new Set,n=[];for(let r of e){let e=r.name.toLowerCase();t.has(e)||(t.add(e),n.push({...r,optionName:e}))}return n}function Yv(e,t){if(!t.has(e))return e;let n=`header-${e}`;if(!t.has(n))return n;for(let e=2;;e++){let r=`${n}-${e}`;if(!t.has(r))return r}}function Xv(e){let t=new Map,n=new Set;for(let{path:r}of e){t.set(r,(t.get(r)??0)+1);let e=$v(r);for(let t=1;t<e.length;t++)n.add(`/${e.slice(0,t).join(`/`)}`)}return{parentPaths:n,pathOperations:t}}function Zv(e){let{method:t,mode:n,namespaceInfo:r,operation:i,path:a}=e;if(n===`operation`)return[{name:i.operationId??`${t}_${a.replace(/[/{}]/g,`_`)}`}];let o=Qv(a,i),s=o.length===0||r.parentPaths.has(ey(a))||(r.pathOperations.get(a)??0)>1,c=ry(o,i.summary??i.description);return[...c.length>0?c:[{name:`root`}],...s?[{name:t}]:[]]}function Qv(e,t){return e.split(`/`).map(e=>ty(e,t)).filter(ny)}function $v(e){return Qv(e).map(e=>e.name)}function ey(e){return`/${$v(e).join(`/`)}`}function ty(e,t){if(!e)return;let n=e.startsWith(`{`)&&e.endsWith(`}`)?e.slice(1,-1):e,r=t?.parameters?.find(e=>e.in===`path`&&e.name===n)?.description;return{...r?{description:r}:void 0,name:n.replace(/[^\w.-]+/g,`-`)}}function ny(e){return e!==void 0}function ry(e,t){return!t||e.length===0?e:e.map((n,r)=>r===e.length-1&&!n.description?{...n,description:t}:n)}function iy(e,t,n){let[r,...i]=t;if(r){if(i.length===0){e.set(r.name,n);return}iy(ay(e,r).commands,i,n)}}function ay(e,t){let n=e.get(t.name);if(n&&`_group`in n)return!n.description&&t.description&&(n.description=t.description),n;let r={_group:!0,commands:new Map,...t.description?{description:t.description}:void 0};return e.set(t.name,r),r}function oy(e){return async t=>{let{args:n={},options:r={}}=t,i=(e.basePath??``)+e.path;for(let t of e.pathParams){let e=n[t.name];e!==void 0&&(i=i.replace(`{${t.name}}`,String(e)))}let a=new URLSearchParams;for(let t of e.queryParams){let e=r[t.name];e!==void 0&&a.set(t.name,String(e))}let o,s=Object.keys(e.bodyProps);if(s.length>0){let e={};for(let t of s)r[t]!==void 0&&(e[t]=r[t]);Object.keys(e).length>0&&(o=JSON.stringify(e))}let c={path:i,method:e.httpMethod,headers:new Headers,body:o,query:a};for(let t of e.headerParams){let e=r[t.optionName];e!==void 0&&c.headers.set(t.name,String(e))}for(let n of e.forwardHeaders??[]){let e=t.request?.headers.get(n);!c.headers.has(n)&&e!=null&&c.headers.set(n,e)}o&&!c.headers.has(`content-type`)&&c.headers.set(`content-type`,`application/json`);let l=Fn(c),u=await Rn(await e.fetch(l));return u.ok?u.data:t.error({code:`HTTP_${u.status}`,message:typeof u.data==`object`&&u.data!==null&&`message`in u.data?String(u.data.message):typeof u.data==`string`?u.data:`HTTP ${u.status}`})}}function sy(e){return f.fromJSONSchema(e)}function cy(e){let t=e instanceof f.ZodOptional,n=t?e.unwrap():e,r=(()=>{if(n instanceof f.ZodNumber)return t?f.coerce.number().optional():f.coerce.number();if(n instanceof f.ZodBoolean)return t?f.coerce.boolean().optional():f.coerce.boolean();if(n instanceof f.ZodUnion){let e=n._zod?.def?.options;if(e?.some(e=>e instanceof f.ZodNumber))return t?f.coerce.number().optional():f.coerce.number();if(e?.some(e=>e instanceof f.ZodBoolean))return t?f.coerce.boolean().optional():f.coerce.boolean()}})();if(!r)return e;let i=e.description??n.description;return i?r.describe(i):r}var ly,uy,dy,fy,py=z((()=>{Lx(),Vn(),Sv(),Lu(),ly=new Set([`delete`,`get`,`head`,`options`,`patch`,`post`,`put`,`trace`]),uy=new Set([`basic`,`bearer`]),dy=100,fy=new Set([`date`,`date-time`,`duration`,`time`])}));async function my(e,t={}){let n=yy(e);await by(n,`initialize`,{protocolVersion:Ey,capabilities:{},clientInfo:{name:`incur`,version:t.version??`1.0.0`}}),n.initialized=!0,await by(n,`notifications/initialized`);let r=(await by(n,`tools/list`)).tools??[];return gy(r)?{discovery:`progressive`,tools:await _y(n),session:n}:{tools:r,session:n}}function hy(e){let t=new Map;for(let n of e.tools){let r=n.inputSchema?Sy(n.inputSchema):void 0,i=Cy(n.outputSchema);t.set(n.name,{description:n.description,...n.annotations?{mcp:{annotations:n.annotations}}:void 0,...r?{options:r}:void 0,...i?{output:i}:void 0,async run(t){let r={name:n.name,arguments:{...t.args,...t.options}},i=await by(e.session,`tools/call`,e.discovery===`progressive`?{name:n.annotations?.readOnlyHint===!0?`call_read_tool`:`call_write_tool`,arguments:r}:r);return i.isError?t.error({code:`MCP_TOOL_ERROR`,message:wy(i)}):Ty(i)}})}return t}function gy(e){if(e.length!==4)return!1;let t=new Set(e.map(e=>e.name));return t.has(`search_tools`)&&t.has(`get_tool_details`)&&t.has(`call_read_tool`)&&t.has(`call_write_tool`)}async function _y(e){let t=[],n=0;for(;n!==void 0;){let r=await vy(e,`search_tools`,{query:``,limit:20,offset:n});for(let n of r.tools??[]){if(!n.name)continue;let r=await vy(e,`get_tool_details`,{name:n.name});r.name&&t.push(r)}if(r.nextOffset!==void 0&&r.nextOffset<=n)throw Error(`MCP tool catalog returned a non-advancing offset`);n=r.nextOffset}return t}async function vy(e,t,n){let r=await by(e,`tools/call`,{name:t,arguments:n});if(r.isError)throw Error(wy(r)||`MCP tool failed: ${t}`);return Ty(r)}function yy(e){return typeof e==`string`||e instanceof URL?{url:new URL(e),fetch:globalThis.fetch.bind(globalThis)}:{url:new URL(e.url),fetch:e.fetch??globalThis.fetch.bind(globalThis),...e.headers?{headers:e.headers}:void 0}}async function by(e,t,n){let r=t.startsWith(`notifications/`),i=r?void 0:crypto.randomUUID(),a=new Headers(e.headers);a.set(`content-type`,`application/json`),a.set(`accept`,`application/json, text/event-stream`),e.id&&a.set(`mcp-session-id`,e.id),e.initialized&&a.set(`MCP-Protocol-Version`,Ey);let o=JSON.stringify({jsonrpc:`2.0`,...i?{id:i}:void 0,method:t,params:n}),s=await e.fetch(new Request(e.url,{method:`POST`,headers:a,body:o})),c=s.headers.get(`mcp-session-id`);if(c&&(e.id=c),!s.ok)throw Error(`MCP HTTP ${s.status}`);if(r&&s.status===202)return{};let l=await s.text();if(!l)return{};let u=(s.headers.get(`content-type`)??``).includes(`text/event-stream`)?xy(l,i):JSON.parse(l);if(u.error)throw Error(u.error.message??`MCP request failed`);return u.result??{}}function xy(e,t){for(let n of e.split(/\r?\n\r?\n/)){let e=n.split(/\r?\n/).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(`
185
185
  `);if(!e)continue;let r=JSON.parse(e);if(t===void 0||r.id===t)return r}throw Error(`MCP SSE response did not include the matching JSON-RPC message`)}function Sy(e){let t=e.properties??{},n=new Set(e.required??[]),r={};for(let[e,i]of Object.entries(t)){let t=sy(i);n.has(e)||(t=t.optional()),typeof i.description==`string`&&(t=t.describe(i.description)),r[e]=cy(t)}return Object.keys(r).length>0?f.object(r):void 0}function Cy(e){if(!(!e||e.type!==`object`))try{return f.fromJSONSchema(e)}catch{return}}function wy(e){return(Array.isArray(e.content)?e.content:[]).map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
186
- `)}function Ty(e){if(e.structuredContent!==void 0)return e.structuredContent;let t=(Array.isArray(e.content)?e.content:[]).filter(e=>e.type===`text`).map(e=>e.text);if(t.length===1)try{return JSON.parse(t[0])}catch{return t[0]}return t}var Ey,Dy=R((()=>{py(),Ey=`2025-06-18`}));function Oy(e,t,n){let r=[`# ${e}`];n&&r.push(``,n),r.push(``),r.push(`| Command | Description |`),r.push(`|---------|-------------|`);for(let n of t){let t=ky(e,n),i=n.description??``;r.push(`| \`${t}\` | ${i} |`)}return r.push(``,`Run \`${e} --llms-full\` for full manifest. Run \`${e} <command> --schema\` for argument details.`),r.join(`
187
- `)}function ky(e,t){let n=t.name?`${e} ${t.name}`:e;if(!t.args)return n;let r=t.args.shape,i=Lu(t.args),a=new Set(i.required??[]),o=i.properties;return`${n} ${Object.keys(r).map(e=>{let t=o?.[e]?.type===`array`?`${e}...`:e;return a.has(e)?`<${t}>`:`[${t}]`}).join(` `)}`}function Ay(e,t,n=new Map){if(!(n.size>0))return t.map(t=>Ny(e,t)).join(`
186
+ `)}function Ty(e){if(e.structuredContent!==void 0)return e.structuredContent;let t=(Array.isArray(e.content)?e.content:[]).filter(e=>e.type===`text`).map(e=>e.text);if(t.length===1)try{return JSON.parse(t[0])}catch{return t[0]}return t}var Ey,Dy=z((()=>{py(),Ey=`2025-06-18`}));function Oy(e,t,n){let r=[`# ${e}`];n&&r.push(``,n),r.push(``),r.push(`| Command | Description |`),r.push(`|---------|-------------|`);for(let n of t){let t=ky(e,n),i=n.description??``;r.push(`| \`${t}\` | ${i} |`)}return r.push(``,`Run \`${e} --llms-full\` for full manifest. Run \`${e} <command> --schema\` for argument details.`),r.join(`
187
+ `)}function ky(e,t){let n=t.name?`${e} ${t.name}`:e;if(!t.args)return n;let r=t.args.shape,i=Iu(t.args),a=new Set(i.required??[]),o=i.properties;return`${n} ${Object.keys(r).map(e=>{let t=o?.[e]?.type===`array`?`${e}...`:e;return a.has(e)?`<${t}>`:`[${t}]`}).join(` `)}`}function Ay(e,t,n=new Map){if(!(n.size>0))return t.map(t=>Ny(e,t)).join(`
188
188
 
189
189
  `);let r=[`# ${e}`],i;for(let a of t){let t=a.name?a.name.split(` `)[0]:``;if(t!==i&&(i=t,t)){let i=n.get(t),a=i?`## ${e} ${t}\n\n${i}`:`## ${e} ${t}`;r.push(a)}r.push(Ny(e,a,t?3:2))}return r.join(`
190
190
 
191
- `)}function jy(e,t,n,r=new Map){if(n===0)return[{dir:``,content:My(e,e,t,r,e)}];let i=new Map;for(let r of t){if(!r.name){let t=Iy(e),n=i.get(t)??[];n.push(r),i.set(t,n);continue}let t=r.name.split(` `).slice(0,n).join(`-`),a=i.get(t)??[];a.push(r),i.set(t,a)}return[...i.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([t,i])=>{let a=i[0],o=a.name?a.name.split(` `).slice(0,n).join(` `):``;return{dir:t,content:My(e,o?`${e} ${o}`:e,i,r,o||void 0)}})}function My(e,t,n,r,i){let a=i?r.get(i):void 0,o=n.length===1&&n[0].description?n[0].description:void 0,s=a??o,c=s?`${s.replace(/\.$/,``)}. Run \`${t} --help\` for usage details.`:`Run \`${t} --help\` for usage details.`;return`${`---\n${Tl().stringify({name:Iy(t),description:c,requires_bin:e,command:t},{lineWidth:0}).trimEnd()}\n---`}\n\n${n.map(t=>Ny(e,t)).join(`
191
+ `)}function jy(e,t,n,r=new Map){if(n===0)return[{dir:``,content:My(e,e,t,r,e)}];let i=new Map;for(let r of t){if(!r.name){let t=Iy(e),n=i.get(t)??[];n.push(r),i.set(t,n);continue}let t=r.name.split(` `).slice(0,n).join(`-`),a=i.get(t)??[];a.push(r),i.set(t,a)}return[...i.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([t,i])=>{let a=i[0],o=a.name?a.name.split(` `).slice(0,n).join(` `):``;return{dir:t,content:My(e,o?`${e} ${o}`:e,i,r,o||void 0)}})}function My(e,t,n,r,i){let a=i?r.get(i):void 0,o=n.length===1&&n[0].description?n[0].description:void 0,s=a??o,c=s?`${s.replace(/\.$/,``)}. Run \`${t} --help\` for usage details.`:`Run \`${t} --help\` for usage details.`;return`${`---\n${wl().stringify({name:Iy(t),description:c,requires_bin:e,command:t},{lineWidth:0}).trimEnd()}\n---`}\n\n${n.map(t=>Ny(e,t)).join(`
192
192
 
193
193
  ---
194
194
 
195
- `)}`}function Ny(e,t,n=1){let r=t.name?`${e} ${t.name}`:e,i=[],a=e=>`#`.repeat(e),o=`${a(n)} ${r}`;t.description&&(o+=`\n\n${t.description}`),i.push(o);let s=a(n+1);if(t.args){let e=t.args.shape,n=Lu(t.args),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e];return`| \`${e}\` | \`${Ly(n)}\` | ${r.has(e)?`yes`:`no`} | ${t.description??``} |`});i.push(`${s} Arguments\n\n| Name | Type | Required | Description |\n|------|------|----------|-------------|\n${o.join(`
196
- `)}`)}if(t.env){let e=t.env.shape,n=Lu(t.env),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e],i=Ly(n),o=n?.default===void 0?``:String(n.default),s=r.has(e)?`yes`:`no`,c=t.description??``;return`| \`${e}\` | \`${i}\` | ${s} | ${o?`\`${o}\``:``} | ${c} |`});i.push(`${s} Environment Variables\n\n| Name | Type | Required | Default | Description |\n|------|------|----------|---------|-------------|\n${o.join(`
197
- `)}`)}if(t.options){let e=t.options.shape,n=Lu(t.options).properties,r=Object.entries(e).map(([e,t])=>{let r=n?.[e],i=Ly(r),a=r?.default===void 0?``:String(r.default),o=t.description??``,s=r?.deprecated?`**Deprecated.** ${o}`:o;return`| \`--${e}\` | \`${i}\` | ${a?`\`${a}\``:``} | ${s} |`});i.push(`${s} Options\n\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n${r.join(`
198
- `)}`)}if(t.output){let e=Lu(t.output),n=Fy(e);if(n)i.push(`${s} Output\n\n${n}`);else{let t=Ly(e);i.push(`${s} Output\n\nType: \`${t}\``)}}if(t.examples&&t.examples.length>0){let n=t.examples.map(t=>`${t.description?`# ${t.description}\n`:``}${e} ${t.command}`);i.push(`${s} Examples\n\n\`\`\`sh\n${n.join(`
195
+ `)}`}function Ny(e,t,n=1){let r=t.name?`${e} ${t.name}`:e,i=[],a=e=>`#`.repeat(e),o=`${a(n)} ${r}`;t.description&&(o+=`\n\n${t.description}`),i.push(o);let s=a(n+1);if(t.args){let e=t.args.shape,n=Iu(t.args),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e];return`| \`${e}\` | \`${Ly(n)}\` | ${r.has(e)?`yes`:`no`} | ${t.description??``} |`});i.push(`${s} Arguments\n\n| Name | Type | Required | Description |\n|------|------|----------|-------------|\n${o.join(`
196
+ `)}`)}if(t.env){let e=t.env.shape,n=Iu(t.env),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e],i=Ly(n),o=n?.default===void 0?``:String(n.default),s=r.has(e)?`yes`:`no`,c=t.description??``;return`| \`${e}\` | \`${i}\` | ${s} | ${o?`\`${o}\``:``} | ${c} |`});i.push(`${s} Environment Variables\n\n| Name | Type | Required | Default | Description |\n|------|------|----------|---------|-------------|\n${o.join(`
197
+ `)}`)}if(t.options){let e=t.options.shape,n=Iu(t.options).properties,r=Object.entries(e).map(([e,t])=>{let r=n?.[e],i=Ly(r),a=r?.default===void 0?``:String(r.default),o=t.description??``,s=r?.deprecated?`**Deprecated.** ${o}`:o;return`| \`--${e}\` | \`${i}\` | ${a?`\`${a}\``:``} | ${s} |`});i.push(`${s} Options\n\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n${r.join(`
198
+ `)}`)}if(t.output){let e=Iu(t.output),n=Fy(e);if(n)i.push(`${s} Output\n\n${n}`);else{let t=Ly(e);i.push(`${s} Output\n\nType: \`${t}\``)}}if(t.examples&&t.examples.length>0){let n=t.examples.map(t=>`${t.description?`# ${t.description}\n`:``}${e} ${t.command}`);i.push(`${s} Examples\n\n\`\`\`sh\n${n.join(`
199
199
 
200
200
  `)}\n\`\`\``)}return t.hint&&i.push(`> ${t.hint}`),i.join(`
201
201
 
202
- `)}function Py(e){let t=e.map(e=>({name:e.name,description:e.description,hint:e.hint,args:e.args?Lu(e.args):void 0,env:e.env?Lu(e.env):void 0,options:e.options?Lu(e.options):void 0,output:e.output?Lu(e.output):void 0}));return _(`sha256`).update(JSON.stringify(t)).digest(`hex`).slice(0,16)}function Fy(e,t=``){if(e.type!==`object`)return;let n=e.properties;if(!n||Object.keys(n).length===0)return;let r=new Set(e.required??[]),i=[];for(let[e,a]of Object.entries(n)){let n=t?`${t}.${e}`:e,o=Ly(a),s=r.has(e)?`yes`:`no`,c=a.description??``;if(i.push(`| \`${n}\` | \`${o}\` | ${s} | ${c} |`),a.type===`object`&&a.properties){let e=Fy(a,n);if(e){let t=e.split(`
202
+ `)}function Py(e){let t=e.map(e=>({name:e.name,description:e.description,hint:e.hint,args:e.args?Iu(e.args):void 0,env:e.env?Iu(e.env):void 0,options:e.options?Iu(e.options):void 0,output:e.output?Iu(e.output):void 0}));return _(`sha256`).update(JSON.stringify(t)).digest(`hex`).slice(0,16)}function Fy(e,t=``){if(e.type!==`object`)return;let n=e.properties;if(!n||Object.keys(n).length===0)return;let r=new Set(e.required??[]),i=[];for(let[e,a]of Object.entries(n)){let n=t?`${t}.${e}`:e,o=Ly(a),s=r.has(e)?`yes`:`no`,c=a.description??``;if(i.push(`| \`${n}\` | \`${o}\` | ${s} | ${c} |`),a.type===`object`&&a.properties){let e=Fy(a,n);if(e){let t=e.split(`
203
203
  `);i.push(...t.slice(2))}}if(a.type===`array`&&a.items){let e=a.items;if(e.type===`object`&&e.properties){let t=Fy(e,`${n}[]`);if(t){let e=t.split(`
204
204
  `);i.push(...e.slice(2))}}}}return`| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n${i.join(`
205
- `)}`}function Iy(e){return e.toLowerCase().replace(/[^a-z0-9-]+/g,`-`).replace(/-{2,}/g,`-`).replace(/^-|-$/g,``)}function Ly(e){if(!e)return`unknown`;let t=e.type;return t?t===`integer`?`number`:t:`unknown`}var Ry=R((()=>{Dl(),Ru()}));async function zy(e,t={}){let n=lt(),r=t.command??Vy(t.cli??e,n),i=t.agents??[],a=i.length===1&&i[0]===`amp`,o=[];if(!a){let a=[r,`--name`,e,`-y`];t.global!==!1&&a.push(`-g`);for(let e of i.filter(e=>e!==`amp`))a.push(`-a`,e);let[s,...c]=n.split(` `),{stdout:l}=await qy(s,[...c,`add-mcp`,...a]);o.push(...l.split(`
205
+ `)}`}function Iy(e){return e.toLowerCase().replace(/[^a-z0-9-]+/g,`-`).replace(/-{2,}/g,`-`).replace(/^-|-$/g,``)}function Ly(e){if(!e)return`unknown`;let t=e.type;return t?t===`integer`?`number`:t:`unknown`}var Ry=z((()=>{El(),Lu()}));async function zy(e,t={}){let n=ct(),r=t.command??Vy(t.cli??e,n),i=t.agents??[],a=i.length===1&&i[0]===`amp`,o=[];if(!a){let a=[r,`--name`,e,`-y`];t.global!==!1&&a.push(`-g`);for(let e of i.filter(e=>e!==`amp`))a.push(`-a`,e);let[s,...c]=n.split(` `),{stdout:l}=await qy(s,[...c,`add-mcp`,...a]);o.push(...l.split(`
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`))&&By(e,r)&&o.push(`Amp`),{command:r,agents:o}}function By(e,t){let n=d(C(),`.config`,`amp`,`settings.json`),s={};if(r(n))try{s=JSON.parse(a(n,`utf-8`))}catch{return!1}let[c,...l]=Ky(t);if(!c)return!1;let f=s[`amp.mcpServers`]??{};f[e]={command:c,args:l},s[`amp.mcpServers`]=f;let p=u(n);return r(p)||i(p,{recursive:!0}),o(n,JSON.stringify(s,null,2)+`
207
- `),!0}function Vy(e,t){return Uy(e)?`${e} --mcp`:`${t} ${Gy(e)} --mcp`}function Hy(){let e=(process.argv[1]?.replace(/\\/g,`/`))?.match(/^(.+)\/node_modules\/(.+)$/);return e?{root:e[1],entry:e[2]}:null}function Uy(e){let t=process.argv[1];if(!t)return!1;let n=Hy();if(n)return!n.entry.startsWith(`.bin/`)&&!Wy(n.root,e);let r=t.replace(/\\/g,`/`).split(`/`).pop();return r===e||r===`${e}.cmd`||r===`${e}.ps1`}function Wy(e,t){try{let n=JSON.parse(a(d(e,`package.json`),`utf-8`));return[n.dependencies,n.devDependencies,n.optionalDependencies,n.peerDependencies].some(e=>t in(e??{}))}catch{return!1}}function Gy(e){let t=Hy();if(!t)return e;try{let n=JSON.parse(a(d(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 Ky(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 qy(e,t){return new Promise((n,r)=>{h(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 Jy=R((()=>{dt()}));function Yy(){return ab.filter(e=>e.detect())}function Xy(e,n={}){let r=n.global!==!1,i=n.cwd||process.cwd(),a=r?K:i,o=c.join(a,`.agents`,`skills`),s=n.agents??Yy(),l=[],u=[];for(let n of Qy(e)){let e=c.join(o,n.name);eb(e),t.mkdirSync(e,{recursive:!0}),n.root?t.copyFileSync(c.join(n.dir,`SKILL.md`),c.join(e,`SKILL.md`)):t.cpSync(n.dir,e,{recursive:!0}),l.push(e);for(let a of s){if(a.universal)continue;let o=r?a.globalSkillsDir:c.join(i,a.projectSkillsDir),s=c.join(o,n.name);if(tb(s)!==tb(e))try{eb(s),t.mkdirSync(c.dirname(s),{recursive:!0});let n=tb(c.dirname(s)),r=tb(e),i=c.relative(n,r);t.symlinkSync(i,s),u.push({agent:a.name,path:s,mode:`symlink`})}catch{try{t.cpSync(e,s,{recursive:!0}),u.push({agent:a.name,path:s,mode:`copy`})}catch{}}}}return{paths:l,agents:u}}function Zy(e,t={}){let n=t.global!==!1,r=t.cwd||process.cwd(),i=n?K:r;eb(c.join(i,`.agents`,`skills`,e));for(let t of Yy()){if(t.universal)continue;let i=n?t.globalSkillsDir:c.join(r,t.projectSkillsDir);eb(c.join(i,e))}}function Qy(e){let n=[];function r(e){let i;try{i=t.readdirSync(e,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let i=c.join(e,a.name),o=c.join(i,`SKILL.md`);if(t.existsSync(o)){let e=t.readFileSync(o,`utf8`).match(/^name:\s*(.+)$/m);n.push({name:$y(e?.[1]??a.name),dir:i})}r(i)}}r(e);let i=c.join(e,`SKILL.md`);if(t.existsSync(i)){let r=$y(t.readFileSync(i,`utf8`).match(/^name:\s*(.+)$/m)?.[1]??`skill`);n.some(e=>e.name===r)||n.push({name:r,dir:e,root:!0})}return n}function $y(e){return e.trim().replace(/[/\\]/g,`-`).replace(/\.\./g,``).slice(0,255)}function eb(e){try{t.lstatSync(e).isSymbolicLink()?t.unlinkSync(e):t.rmSync(e,{recursive:!0,force:!0})}catch{}}function tb(e){try{return t.realpathSync(e)}catch{let n=c.dirname(e);if(n===e)return e;try{return c.join(t.realpathSync(n),c.relative(n,e))}catch{return e}}}var K,nb,rb,ib,ab,ob=R((()=>{K=x.homedir(),nb=process.env.XDG_CONFIG_HOME||c.join(K,`.config`),rb=process.env.CLAUDE_CONFIG_DIR?.trim()||c.join(K,`.claude`),ib=process.env.CODEX_HOME?.trim()||c.join(K,`.codex`),ab=[{name:`Amp`,globalSkillsDir:c.join(nb,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(nb,`amp`))},{name:`Cline`,globalSkillsDir:c.join(K,`.agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.cline`))},{name:`Codex`,globalSkillsDir:c.join(ib,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(ib)},{name:`Cursor`,globalSkillsDir:c.join(K,`.cursor`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.cursor`))},{name:`Gemini CLI`,globalSkillsDir:c.join(K,`.gemini`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.gemini`))},{name:`GitHub Copilot`,globalSkillsDir:c.join(K,`.copilot`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.copilot`))},{name:`Kimi CLI`,globalSkillsDir:c.join(nb,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.kimi`))},{name:`OpenCode`,globalSkillsDir:c.join(nb,`opencode`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(nb,`opencode`))},{name:`Claude Code`,globalSkillsDir:c.join(rb,`skills`),projectSkillsDir:`.claude/skills`,universal:!1,detect:()=>t.existsSync(rb)},{name:`Windsurf`,globalSkillsDir:c.join(K,`.codeium`,`windsurf`,`skills`),projectSkillsDir:`.windsurf/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.codeium`,`windsurf`))},{name:`Continue`,globalSkillsDir:c.join(K,`.continue`,`skills`),projectSkillsDir:`.continue/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.continue`))},{name:`Roo`,globalSkillsDir:c.join(K,`.roo`,`skills`),projectSkillsDir:`.roo/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.roo`))},{name:`Kilo`,globalSkillsDir:c.join(K,`.kilocode`,`skills`),projectSkillsDir:`.kilocode/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.kilocode`))},{name:`Goose`,globalSkillsDir:c.join(nb,`goose`,`skills`),projectSkillsDir:`.goose/skills`,universal:!1,detect:()=>t.existsSync(c.join(nb,`goose`))},{name:`Augment`,globalSkillsDir:c.join(K,`.augment`,`skills`),projectSkillsDir:`.augment/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.augment`))},{name:`Trae`,globalSkillsDir:c.join(K,`.trae`,`skills`),projectSkillsDir:`.trae/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.trae`))},{name:`Junie`,globalSkillsDir:c.join(K,`.junie`,`skills`),projectSkillsDir:`.junie/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.junie`))},{name:`Crush`,globalSkillsDir:c.join(nb,`crush`,`skills`),projectSkillsDir:`.crush/skills`,universal:!1,detect:()=>t.existsSync(c.join(nb,`crush`))},{name:`Kiro CLI`,globalSkillsDir:c.join(K,`.kiro`,`skills`),projectSkillsDir:`.kiro/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.kiro`))},{name:`Qwen Code`,globalSkillsDir:c.join(K,`.qwen`,`skills`),projectSkillsDir:`.qwen/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.qwen`))},{name:`OpenHands`,globalSkillsDir:c.join(K,`.openhands`,`skills`),projectSkillsDir:`.openhands/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.openhands`))}]}));async function sb(e,t,n={}){let{depth:r=1,description:i,global:a=!0}=n,o=n.cwd??(a?ub():process.cwd());await wl();let s=new Map;i&&s.set(e,i);let c=jy(e,hx(t,[],s,n.rootCommand),r,s),u=await T.mkdtemp(l.join(S.tmpdir(),`incur-skills-${e}-`));try{let r=[];for(let t of c){let n=t.dir?l.join(u,t.dir,`SKILL.md`):l.join(u,`SKILL.md`);await T.mkdir(l.dirname(n),{recursive:!0}),await T.writeFile(n,`${t.content}\n`);let i=bx(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`:l.join(t,`SKILL.md`);for await(let i of T.glob(n,{cwd:o}))try{let n=await T.readFile(l.resolve(o,i),`utf8`),a=bx(n),s=t===`_root`?a.name??e:l.basename(l.dirname(i)),c=l.join(u,s,`SKILL.md`);await T.mkdir(l.dirname(c),{recursive:!0}),await T.writeFile(c,n),r.some(e=>e.name===s)||r.push({name:s,description:a.description,external:!0})}catch{}}let{paths:i,agents:s}=Xy(u,{global:a,cwd:o}),d=new Set(i.map(e=>l.basename(e))),f=pb(e);if(f?.skills)for(let e of f.skills)d.has(e)||Zy(e,{global:a,cwd:o});return fb(e,Py(hx(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 T.rm(u,{recursive:!0,force:!0})}}async function cb(e,t,n={}){let{depth:r=1,description:i}=n,a=n.cwd??process.cwd();await wl();let o=new Map;i&&o.set(e,i);let s=jy(e,hx(t,[],o,n.rootCommand),r,o),c=[],u=mb(e,{cwd:a});for(let t of s){let n=bx(t.content),r=n.name??(t.dir||e);c.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`:l.join(t,`SKILL.md`);for await(let r of T.glob(n,{cwd:a}))try{let n=bx(await T.readFile(l.resolve(a,r),`utf8`)),i=t===`_root`?n.name??e:l.basename(l.dirname(r));c.some(e=>e.name===i)||c.push({name:i,description:n.description,installed:u.has(i)})}catch{}}return c.sort((e,t)=>e.name.localeCompare(t.name))}function lb(e,t={}){return mb(e,t).size>0}function ub(){let e=process.argv[1];if(!e)return process.cwd();let t=l.dirname((()=>{try{return n.realpathSync(e)}catch{return process.execPath}})()),r=l.parse(t).root;for(;t!==r;){try{return n.accessSync(l.join(t,`package.json`)),t}catch{}t=l.dirname(t)}return process.cwd()}function db(e){let t=process.env.XDG_DATA_HOME||l.join(S.homedir(),`.local`,`share`);return l.join(t,`incur`,`${e}.json`)}function fb(e,t,r,i){let a=db(e),o=l.dirname(a);n.existsSync(o)||n.mkdirSync(o,{recursive:!0}),n.writeFileSync(a,JSON.stringify({hash:t,skills:r,paths:i,at:new Date().toISOString()})+`
208
- `)}function pb(e){try{return JSON.parse(n.readFileSync(db(e),`utf-8`))}catch{return}}function mb(e,t={}){let n=pb(e);if(!n?.skills?.length)return new Set;if(n.paths?.length){let e=n.paths.filter(e=>hb(e)).map(e=>l.basename(e));return new Set(e)}let r=t.cwd??process.cwd(),i=[l.join(S.homedir(),`.agents`,`skills`),l.join(r,`.agents`,`skills`)],a=n.skills.filter(e=>i.some(t=>hb(l.join(t,e))));return new Set(a)}function hb(e){return n.existsSync(l.join(e,`SKILL.md`))}function gb(e){return pb(e)?.hash}var _b=R((()=>{Lx(),ob(),Dl(),Ry()}));function vb(e,t){let n=typeof e==`string`?e:e.name,r=typeof e==`string`?t??{}:e,i=r.version??Kt,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:Zb(o),c=o===void 0?void 0:Qb(o),l=new Map,u=[],d=[],f=bb(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 Bv(await Rv(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(Xb(t))return d.push((async()=>{let n=hy(await my(t.mcp)),r={_group:!0,description:t.description,commands:n,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0};rx(e,r,Px.get(p)),l.set(e,r)})()),p;if(t&&`fetch`in t&&Yb(t.fetch)){let n=Zb(t.fetch);return t.openapi?(d.push((async()=>{let r=await Bv(await Rv(t.openapi,{baseUrl:Qb(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};rx(e,i,Px.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(rx(e,t,Px.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=Ax.get(e),r=e,i=Dx.get(r),a=Nx.get(r),o=kx.get(r),s=Ox.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(()=>{rx(r.name,c,Px.get(p))})):rx(r.name,c,Px.get(p)),l.set(r.name,c),n){let t=Fx.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=Px.get(p);return Cb(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=Au();return d.push((async()=>{let n=t?await ju(t):await Gb(await Wb(e));for(let e of n){if(!Kb(e.command))throw Error(`Expected the default export from '${e.file}' to be created with \`Cli.command()\`.`);qb(l,e.segments,e.command,e.file,Px.get(p))}})()),p},async serve(e=process.argv.slice(2),t={}){if(await Mt(e))return;d.length>0&&await Promise.all(d);let o=Px.get(p);return yb(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&&Ax.set(p,a),a&&r.aliases&&Fx.set(p,r.aliases),r.options&&jx.set(p,r.options),r.config!==void 0&&Mx.set(p,!0),r.outputPolicy&&Nx.set(p,r.outputPolicy),r.globals){Px.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 kx.set(p,u),Dx.set(p,l),Ox.set(p,d),p}async function yb(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=Cx(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=Ob(n,{configFlag:l})}catch(e){let t=e instanceof Error?e.message:String(e);d(s?ix({code:`UNKNOWN`,message:t}):Ol({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:te,schema:E,configPath:D,configDisabled:O,rest:k}=p;s=o&&!g;let A={...typeof r.update==`object`?r.update:void 0,binary:Gt!==void 0,version:r.version},ne={},j=k;function re(e){if(!r.globals)return!0;try{let t=Zl(k,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?ix({code:`UNKNOWN`,message:t}):Ol({code:`UNKNOWN`,message:t},`toon`)),a(1),!1}}if(!re(!1))return;if(h===`yaml`&&await wl(),ee){if(r.update!==!1)try{await pt(e,A)}catch{}return}if(T&&!w){try{let t=await mt(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
- `))}else d(Ol(t,h))}catch(e){let t={code:`UPDATE_FAILED`,message:e instanceof Error?e.message:String(e)};d(s?ix(t):Ol(t,h)),a(1)}return}if(C){await q_(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 M=process.env.COMPLETE;if(M){let a=n.indexOf(`--`),o=a===-1?n:n.slice(a+1);if(o.length===0)i([e,...r.aliases??[]].map(e=>gn(M,e)).join(`
211
- `));else{let e=Number(process.env._COMPLETE_INDEX??o.length-1),n=_n(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 lu)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=au(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=vn(M,n);c&&i(c)}return}let N;if(!x&&!S&&!E&&!w&&!T&&!ee&&!te){let n=Fb(j,e,`skills`)!==-1,i=Fb(j,e,`mcp`)!==-1;if(!n&&!i){let n=gb(e);n&&lb(e,{cwd:r.sync?.cwd})&&Py(hx(t,[],new Map,r.rootCommand))!==n&&(N={description:`Skills are out of date:`,commands:[{command:process.env.npm_config_user_agent||process.env.npm_execpath?`${lt()} ${Gy(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=nx(n,t);if($b(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=hx(n,s,t,o);d(Ay(i.length>0?`${e} ${i.join(` `)}`:e,r,t));return}d(Ol(fx(n,i,r.globals?.schema,o),h));return}if(!g||h===`md`){let t=hx(n,s,new Map,o);d(Oy(i.length>0?`${e} ${i.join(` `)}`:e,t,a));return}d(Ol(ux(n,i,r.globals?.schema,o),h));return}let ie=Fb(j,e,`completions`);if(ie!==-1){let t=j[ie+1];if(w||!t){let t=au(`completions`);d(fu(`${e} completions`,{args:t.args,description:t.description,hideGlobalOptions:!0,hint:t.hint?.(e)}));return}if(!cu.includes(t)){d(ix({code:`INVALID_SHELL`,message:`Unknown shell '${t}'. Supported: ${cu.join(`, `)}`})),a(1);return}d([e,...r.aliases??[]].map(e=>gn(t,e)).join(`
212
- `));return}let ae=Fb(j,e,`skills`);if(ae!==-1){let o=au(`skills`),c=j[ae+1],l=c?ou(o,c):void 0;if(c&&!l){let t=mn(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(ix({code:`COMMAND_NOT_FOUND`,message:r})),d(ax(l))):d(Ol({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(Ib(e,o));return}if(l?.name===`list`){if(w){d(Lb(e,o,`list`));return}try{let n=await cb(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(Ol({code:`LIST_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(w){d(Lb(e,o,`add`));return}let u=j.slice(ae+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 sb(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(Ol(e,g?h:`toon`))}}catch(e){d(Ol({code:`SYNC_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}let oe=Fb(j,e,`mcp`);if(oe!==-1){let o=au(`mcp`),c=j[oe+1],l=c?ou(o,c):void 0;if(c&&!l){let t=mn(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(ix({code:`COMMAND_NOT_FOUND`,message:r})),d(ax(l))):d(Ol({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(Ib(e,o));return}if(w){d(Lb(e,o,l.name));return}if(l.name===`doctor`){let n=await Rb(e,t,r);d(Ol(n,g?h:`toon`)),n.ok||a(1);return}let u=j.slice(oe+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 zy(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(Ol({name:t,command:n.command,agents:n.agents},g?h:`toon`))}catch(e){d(Ol({code:`MCP_ADD_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(te&&!w&&r.version){d(r.version);return}if(j.length===0){if(r.rootCommand&&s&&r.rootCommand.args&&sx(r.rootCommand.args)){let n=r.rootCommand;await f(),d(fu(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:yx(n.examples),usage:n.usage,commands:t.size>0?Pb(t):void 0,root:!0}));return}if(!(r.rootCommand||r.rootFetch)){await f(),d(du(e,{aliases:r.aliases,configFlag:l,description:r.description,globals:r.globals,version:r.version,commands:Pb(t),root:!0}));return}}let P=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 P){let n=P.path===e?e:`${e} ${P.path}`;P.path===e&&t.size>0?d(du(e,{aliases:r.aliases,configFlag:l,description:r.description,version:r.version,commands:Pb(t),root:!0})):d(Ub(n,P.fetchGateway.description));return}if(w){if(`help`in P||`error`in P){let n=`help`in P?`${e} ${P.path}`:e,i=`help`in P?P.description:r.description,a=`help`in P?P.commands:t,o=n===e;if(o&&r.rootCommand&&a.size>0){let t=r.rootCommand;d(fu(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:yx(t.examples),usage:t.usage,commands:Pb(a),root:!0}))}else d(du(n,{aliases:o?r.aliases:void 0,configFlag:l,description:i,globals:r.globals,version:o?r.version:void 0,commands:Pb(a),root:o}))}else if(`command`in P){let n=P.command,i=P.path===e,a=i?e:`${e} ${P.path}`,o=`commands`in P&&P.commands&&P.commands.size>0?Pb(P.commands):i&&r.rootCommand&&t.size>0?Pb(t):void 0;d(fu(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:yx(n.examples),usage:n.usage,commands:o,root:i}))}return}if(E){if(`help`in P){d(du(`${e} ${P.path}`,{configFlag:l,description:P.description,globals:r.globals,commands:Pb(P.commands)}));return}if(`error`in P){let t=P.path?`${e} ${P.path}`:e,n=mn(P.error,P.commands.keys()),r=n?` Did you mean '${n}'?`:``;d(`Error: '${P.error}' is not a command for '${t}'.${r}`),a(1);return}if(`fetchGateway`in P){d(`--schema is not supported for fetch commands.`),a(1);return}let t=P.command,n=g?h:`toon`,i={};t.args&&(i.args=Lu(t.args)),t.env&&(i.env=Lu(t.env)),t.options&&(i.options=Lu(t.options)),t.output&&(i.output=Lu(t.output)),r.globals?.schema&&(i.globals=Lu(r.globals.schema)),d(Ol(i,n));return}if(`help`in P){d(du(`${e} ${P.path}`,{configFlag:l,description:P.description,globals:r.globals,commands:Pb(P.commands)}));return}let se;if(s&&r.update!==!1){let t=ft(e,A);t&&(se={description:`Update available for ${t.name}:`,commands:[{command:`${u} --update`,description:`upgrade from ${t.current} to ${t.latest}`}]})}let ce=ox(N,se),F=performance.now(),le=`command`in P&&P.command.format,I=g?h:le||r.format||`toon`;I===`yaml`&&await wl();let ue=`error`in P&&!P.path&&(()=>{let e=[...P.commands.keys()];for(let t of lu)e.push(t.name);return mn(P.error,e)!==void 0})(),de=`error`in P&&r.rootFetch&&!P.path&&!ue?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:j}:`error`in P&&r.rootCommand&&!P.path&&!ue?{command:r.rootCommand,path:e,rest:j}:P,fe=`outputPolicy`in P&&P.outputPolicy||r.outputPolicy,pe=!(s&&!g&&fe===`agent-only`),me=_?Un(_):void 0;function he(e){if(v==null&&y==null)return{text:e,truncated:!1};let t=en(e),n=y??0,r=v==null?t:n+v;if(n===0&&r>=t)return{text:e,truncated:!1};let i=tn(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 ge(e){if(me&&e.ok&&e.data!=null&&(e={...e,data:Wn(e.data,me)}),ce){let t=e.meta.cta;e={...e,meta:{...e.meta,cta:t?{description:t.description,commands:[...t.commands,...ce.commands]}:ce}}}if(b){let t=e.ok?e.data:e.error,n=t==null?``:Ol(t,I);return d(String(en(n)))}let t=e.meta.cta;if(s&&!m){e.ok&&e.data!=null&&pe?d(he(Ol(e.data,I)).text):e.ok||d(ix(e.error)),t&&d(ax(t));return}if(m){if(v!=null||y!=null){let t=he(e.ok&&e.data!=null?Ol(e.data,I):e.ok?``:Ol(e.error,I));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(Ol(n,I))}}return d(Ol(e,I))}let n=e.ok?e.data:e.error,r=Ol(n,I);if(!t){r&&d(he(r).text);return}d(he(Ol(typeof n==`object`&&n?{...n,cta:t}:{data:n,cta:t},I)).text)}if(`error`in de){let t=de.path?`${e} ${de.path} --help`:`${e} --help`,r=de.path?`${e} ${de.path}`:e,i=`commands`in de?[...de.commands.keys()]:[];if(!de.path)for(let e of lu)i.push(e.name);let o=mn(de.error,i),c=o?` Did you mean '${o}'?`:``,l=`'${de.error}' is not a command for '${r}'.${c}`,u=[];if(o){let t=n.map(e=>e===de.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(ix({code:`COMMAND_NOT_FOUND`,message:l})),d(ax(ce?{...f,commands:[...f.commands,...ce.commands]}:f)),a(1);return}ge({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:l},meta:{command:de.error,cta:f,duration:`${Math.round(performance.now()-F)}ms`}}),a(1);return}if(`fetchGateway`in de){if(!re(!0))return;let{fetchGateway:t,path:n,rest:i}=de,o=[...r.middlewares??[],...de.middlewares??[]],c=async()=>{let r=Fn(i);t.basePath&&(r.path=t.basePath+r.path);let o=In(r),c=await t.fetch(o);if(Ln(c)){await lx(Rn(c),{name:e,path:n,start:F,format:I,formatExplicit:g,human:s,renderOutput:pe,fullOutput:m,truncate:he,write:ge,writeln:d,exit:a});return}let l=await zn(c);l.ok?ge({ok:!0,data:l.data,meta:{command:n,duration:`${Math.round(performance.now()-F)}ms`}}):(ge({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()-F)}ms`}}),a(1))};try{let t=r.envSchema?Jl(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=>({[Ix]:`error`,...e}),format:I,formatExplicit:g,globals:ne,name:e,set(e,t){i[e]=t},var:i,version:r.version},d=e=>{if(!cx(e)||e[Ix]!==`error`)return;let t=e,r=Tu(u,t.cta);ge({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()-F)}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){ge({ok:!1,error:{code:e instanceof z?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:n,duration:`${Math.round(performance.now()-F)}ms`}}),a(e instanceof z?e.exitCode??1:1)}return}let{command:_e,path:ve,rest:L}=de;if(!re(!0))return;let ye=[...r.middlewares??[],...`middlewares`in P?P.middlewares??[]:[],..._e.middleware??[]];s&&Sx(L,_e.options,_e.alias);let be;if(c)try{be=await kb(e,ve,{configDisabled:O,configPath:D,files:r.config?.files,loader:r.config?.loader})}catch(e){ge({ok:!1,error:{code:e instanceof z?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:ve,duration:`${Math.round(performance.now()-F)}ms`}}),a(e instanceof z?e.exitCode??1:1);return}let xe=await eu(_e,{agent:!s,argv:L,defaults:be,displayName:u,env:r.envSchema,envSource:r.env,format:I,formatExplicit:g,globals:ne,inputOptions:{},middlewares:ye,name:e,path:ve,vars:r.vars,version:r.version}),Se=`${Math.round(performance.now()-F)}ms`;if(`stream`in xe){await lx(xe.stream,{name:u,path:ve,start:F,format:I,formatExplicit:g,human:s,renderOutput:pe,fullOutput:m,truncate:he,write:ge,writeln:d,exit:a});return}if(xe.ok){let e=Tu(u,xe.cta);ge({ok:!0,data:xe.data,meta:{command:ve,duration:Se,...e?{cta:e}:void 0}})}else{let e=Tu(u,xe.cta);if(s&&!g&&xe.error.fieldErrors){d(Tb(u,ve,_e,new Mn({message:xe.error.message,fieldErrors:xe.error.fieldErrors}),r.env,l)),a(1);return}ge({ok:!1,error:{code:xe.error.code,message:xe.error.message,...xe.error.retryable===void 0?void 0:{retryable:xe.error.retryable},...xe.error.fieldErrors?{fieldErrors:xe.error.fieldErrors}:void 0},meta:{command:ve,duration:Se,...e?{cta:e}:void 0}}),a(xe.exitCode??1)}}function bb(e,t,n={}){let r;async function i(r,i,a){let{fromJsonSchema:o,McpServer:s,WebStandardStreamableHTTPServerTransport:c}=await Promise.resolve().then(()=>(K_(),__)),l=new s({name:e,...n.title?{title:n.title}:void 0,version:t},n.instructions?{instructions:n.instructions}:void 0);Z_(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 xb(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 Sb(e,t,n){let r={name:e,description:n.description};return Dx.set(r,t),n.rootCommand&&Ax.set(r,n.rootCommand),Cv(r,{title:e,...n.version?{version:n.version}:void 0,...n.description?{description:n.description}:void 0})}async function Cb(e,t,n,r={}){let i=performance.now(),a=new URL(n.url),o=a.pathname.split(`/`).filter(Boolean);if(n.method===`GET`&&xb(o)){let n=Sb(e,t,r),i=o[0]===`openapi.yml`||o[0]===`openapi.yaml`;return new Response(i?(await wl()).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 wl();let n=new Map,i=hx(t,[],n,r.rootCommand);if(o[2]===`index.json`&&o.length===3){let t=jy(e,i,1,n).map(t=>{let n=t.content.match(/^---\n([\s\S]*?)\n---/),r=n?Tl().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=jy(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(Gr(e),{status:t,headers:{"content-type":`application/json`}})}if(o.length===0)return r.rootCommand?wb(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=mn(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 wb(d,u,f,s,n,i,{...r,groupMiddlewares:p})}async function wb(e,t,n,r,i,a,o){function s(e,t){return new Response(Gr(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 eu(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(Tu(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(cx(s)&&s[Ix]===`error`){a.enqueue(n.encode(Gr(i(s))+`
216
- `)),a.close();return}let t=cx(s)&&s[Ix]===`ok`?Tu(o.name??e,s.cta):void 0;a.enqueue(n.encode(Gr({type:`done`,ok:!0,meta:r(t)})+`
217
- `)),a.close();return}if(cx(s)&&s[Ix]===`error`){a.enqueue(n.encode(Gr(i(s))+`
218
- `)),await t.return(void 0),a.close();return}a.enqueue(n.encode(Gr({type:`chunk`,data:s})+`
219
- `))}catch(e){a.enqueue(n.encode(Gr({type:`error`,ok:!1,error:{code:e instanceof z?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof z?{retryable:e.retryable}:void 0},meta:r()})+`
220
- `)),a.close()}}});return new Response(s,{status:200,headers:{"content-type":`application/x-ndjson`}})}if(!d.ok){let t=Tu(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=Tu(o.name??e,d.cta);return s({ok:!0,data:d.data,meta:{command:e,duration:f,...p?{cta:p}:void 0}},200)}function Tb(e,t,n,r,i,a){let o=[];for(let e of r.fieldErrors){let t=(()=>{let t=Eb(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(fu(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:yx(n.examples),usage:n.usage})),o.join(`
221
- `)}function Eb(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:`--${fn(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=nx(e,e.get(n)),a=[n],o=r,s,c=[];if(ex(i)){let e=i.outputPolicy??s;return{fetchGateway:i,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}for(;$b(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&&!mn(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=nx(i.commands,t);if(a.push(e),o=o.slice(1),i=n,ex(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 Ob(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(!Ex.has(e[t+1]))throw new Nn({message:`Invalid format: "${e[t+1]}". Expected one of: ${[...Ex].join(`, `)}`});d=e[t+1],f=!0,t++}else if(b&&C===b){let n=e[t+1];if(n===void 0)throw new Nn({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 Nn({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 Nn({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 Nn({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 kb(e,t,n={}){if(n.configDisabled)return;let{loader:r}=n,i;i=n.configPath?Ab(n.configPath):await jb(n.files??[`${e}.json`]);let a;if(r){let e=await r(i);if(e===void 0)return;if(!dn(e))throw new Nn({message:`Config loader must return a plain object or undefined`});a=e}else{if(!i)return;let e=await Mb(i,!!n.configPath);if(!e)return;a=e}return Nb(a,e,t)}function Ab(e){return e.startsWith(`~/`)||e===`~`?c.join(x.homedir(),e.slice(1)):c.resolve(process.cwd(),e)}async function jb(e){for(let t of e){let e=Ab(t);try{return await w.access(e,w.constants.R_OK),e}catch{}}}async function Mb(e,t){let n;try{n=await w.readFile(e,`utf8`)}catch(n){if(n.code===`ENOENT`){if(t)throw new Nn({message:`Config file not found: ${e}`});return}throw n}let r;try{r=JSON.parse(n)}catch(t){throw new Nn({message:`Invalid JSON config file: ${e}`,cause:t instanceof Error?t:void 0})}if(!dn(r))throw new Nn({message:`Invalid config file: expected a top-level object in ${e}`});return r}function Nb(e,t,n){let r=n===t?[]:n.split(` `),i=e;for(let e of r){if(!dn(i))return;let t=i.commands;if(!dn(t)||(i=t[e],i===void 0))return}if(!dn(i))throw new Nn({message:`Invalid config section for '${n}': expected an object`});let a=i.options;if(a!==void 0){if(!dn(a))throw new Nn({message:`Invalid config 'options' for '${n}': expected an object`});return Object.keys(a).length>0?a:void 0}}function Pb(e){let t=[];for(let[n,r]of e)tx(r)||t.push({name:n,description:r.description});return t.sort((e,t)=>e.name.localeCompare(t.name))}function Fb(e,t,n){return au(e[0])?.name===n?0:e[0]===t&&au(e[1])?.name===n?1:-1}function Ib(e,t){return du(`${e} ${t.name}`,{aliases:t.aliases,description:t.description,commands:t.subcommands?.map(e=>({name:e.name,description:e.description}))})}function Lb(e,t,n){let r=ou(t,n);return fu(`${e} ${t.name} ${n}`,{alias:r?.alias,aliases:r?.aliases,description:r?.description,hideGlobalOptions:!0,options:r?.options})}async function Rb(e,t,n){let r=[],i=[],a=new ee,o=new ee,s=[];o.on(`data`,e=>s.push(e.toString()));let c,l=q_(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(`${Gr({jsonrpc:`2.0`,id:1,method:`initialize`,params:{protocolVersion:`2024-11-05`,capabilities:{},clientInfo:{name:`incur-doctor`,version:`1.0.0`}}})}\n`),a.write(`${Gr({jsonrpc:`2.0`,id:2,method:`tools/list`,params:{}})}\n`),await zb(s,()=>u),a.end(),await l,c)return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_SERVER_FAILED`,message:Vb(c)}]};let d;try{d=Bb(s)}catch(e){return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_RESPONSE_PARSE_FAILED`,message:Vb(e)}]}}let f=d.find(e=>e.id===1);f?f.error&&i.push({code:`MCP_INITIALIZE_FAILED`,message:Hb(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:Hb(p.error)}):!dn(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(dn).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 zb(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 Bb(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(!dn(r))throw Error(`Expected JSON-RPC response object.`);t.push(r)}return t}function Vb(e){return e instanceof Error?e.message:String(e)}function Hb(e){return dn(e)&&typeof e.message==`string`?e.message:Gr(e)}function Ub(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
- `)}async function Wb(e){if(e)return{directory:te(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=c.resolve(t);try{let e=await w.realpath(n);return{directory:c.dirname(e),exclude:e}}catch(e){if(e.code!==`ENOENT`)throw e;return{directory:c.dirname(n),exclude:n}}}async function Gb(e){let t=await ku(e.directory,{exclude:e.exclude});return Promise.all(t.map(async e=>({...e,command:(await import(E(e.file).href)).default})))}function Kb(e){return typeof e==`object`&&!!e&&e[Tx]===!0}function qb(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($b(c)&&!c.root)c.root=n,c.description??=n.description;else throw Jb(t,r);rx(t.join(` `),n,i);for(let e of n.aliases??[]){if(a.has(e))throw Jb([...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(tx(c)||ex(c))throw Jb(t,r);if($b(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 Jb(e,t){return Error(`Filesystem command '${e.join(` `)}' from '${t}' conflicts with an existing command or alias.`)}function Yb(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 Xb(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 Zb(e){return typeof e==`function`?e:e.fetch}function Qb(e){return typeof e==`function`?void 0:e.url}function $b(e){return`_group`in e}function ex(e){return`_fetch`in e}function tx(e){return`_alias`in e}function nx(e,t){return tx(t)?e.get(t.target):t}function rx(e,t,n){if(!(!n||ex(t)||tx(t))){if($b(t)){t.root&&rx(e,t.root,n);for(let[r,i]of t.commands)rx(`${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 ix(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 ax(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 ox(...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 sx(e){return Object.values(e.shape).some(e=>e._zod.optout!==`optional`)}function cx(e){return typeof e==`object`&&!!e&&Ix in e}async function lx(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(cx(i)){let e=i;if(e[Ix]===`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(ix({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}}n?t.writeln(Gr({type:`chunk`,data:i})):t.renderOutput&&t.writeln(t.truncate(Ol(i,t.format)).text)}if(cx(r)&&r[Ix]===`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(ix({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}let i=cx(r)&&r[Ix]===`ok`?Tu(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(ax(i))}catch(e){n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e instanceof z?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof z?{retryable:e.retryable}:void 0}})):t.writeln(ix({code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)})),t.exit(e instanceof z?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(cx(i)){let e=i;if(e[Ix]===`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(cx(r)&&r[Ix]===`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=cx(r)&&r[Ix]===`ok`?Tu(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 z?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof z?{retryable:e.retryable}:void 0},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e instanceof z?e.exitCode??1:1)}}}function ux(e,t=[],n,r){let i=dx(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:Lu(n)}:void 0}}function dx(e,t){let n=[];for(let[r,i]of e){if(tx(i))continue;let e=[...t,r];if($b(i)){if(i.root){let t={name:e.join(` `)};i.root.description&&(t.description=i.root.description),n.push(t)}n.push(...dx(i.commands,e))}else{let t={name:e.join(` `)};ex(i),i.description&&(t.description=i.description),n.push(t)}}return n}function fx(e,t=[],n,r){let i=px(e,t);return r&&t.length>0&&i.push(mx(t,r)),{version:`incur.v1`,commands:i.sort((e,t)=>e.name.localeCompare(t.name)),...n?{globals:Lu(n)}:void 0}}function px(e,t){let n=[];for(let[r,i]of e){if(tx(i))continue;let e=[...t,r];if(ex(i)){let t={name:e.join(` `)};i.description&&(t.description=i.description),n.push(t)}else $b(i)?(i.root&&n.push(mx(e,i.root)),n.push(...px(i.commands,e))):n.push(mx(e,i))}return n}function mx(e,t){let n={name:e.join(` `)};t.description&&(n.description=t.description);let r=xx(t.args,t.env,t.options),i=t.output?Lu(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=yx(t.examples);if(a){let t=e.join(` `);n.examples=a.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function hx(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),_x(r)&&(e.hint=vx(e.hint)),r.options&&(e.options=r.options),r.output&&(e.output=r.output);let t=yx(r.examples);t&&(e.examples=t),i.push(e)}for(let[r,a]of e){if(tx(a))continue;let e=[...t,r];if(ex(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 $b(a)?(a.description&&n.set(e.join(` `),a.description),a.root&&i.push(gx(e,a.root)),i.push(...hx(a.commands,e,n))):i.push(gx(e,a))}return i.sort((e,t)=>(e.name??``).localeCompare(t.name??``))}function gx(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),_x(t)&&(n.hint=vx(n.hint)),t.options&&(n.options=t.options),t.output&&(n.output=t.output);let r=yx(t.examples);if(r){let t=e.join(` `);n.examples=r.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function _x(e){return e.destructive===!0||e.mcp!==!1&&e.mcp?.annotations?.destructiveHint===!0}function vx(e){return e?e.includes(wx)?e:`${e} ${wx}`:wx}function yx(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 bx(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return{};let n=Tl().parse(t[1]);return!n||typeof n!=`object`?{}:n}function xx(e,t,n){if(!e&&!t&&!n)return;let r={};return e&&(r.args=Lu(e)),t&&(r.env=Lu(t)),n&&(r.options=Lu(n)),r}function Sx(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 Cx(e,t){let n=process.argv[1];if(!n)return e;let r=c.basename(n);return r===e?e:t?.includes(r)?r:e}var wx,Tx,Ex,Dx,Ox,kx,Ax,jx,Mx,Nx,Px,Fx,Ix,Lx=R((()=>{un(),qt(),kn(),Pn(),Hn(),Kn(),Il(),wu(),uu(),Ou(),Iu(),hn(),qr(),dt(),jt(),Dl(),vv(),Dy(),py(),$l(),Ru(),Ry(),Jy(),_b(),wx=`Confirm with the user before executing this destructive command.`,Tx=Symbol.for(`incur.fileCommand`),Ex=new Set([`toon`,`json`,`yaml`,`md`,`jsonl`]),Dx=new WeakMap,Ox=new WeakMap,kx=new WeakMap,Ax=new WeakMap,jx=new WeakMap,Mx=new WeakMap,Nx=new WeakMap,Px=new WeakMap,Fx=new WeakMap,Ix=Symbol.for(`incur.sentinel`)})),Rx=R((()=>{qt(),Lx(),kn(),Pn(),Il(),wu(),vv(),Hn(),py(),$l(),Ru(),Ry(),Dl(),Jy(),_b()}));function zx(e,t){if(!(!e||typeof e!=`object`))return e[t]}var q,Bx,Vx,Hx,Ux,Wx,Gx=R((()=>{q={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Bx={payment:`Payment`},Vx={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Hx={charge:`charge`,session:`session`,subscription:`subscription`},Ux={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},Wx={v1:`v1`,v2:`v2`}}));function Kx(e,t){return t?`${e} Add funds at ${t}`:e}var qx,Jx,J,Yx,Xx,Zx,Qx,$x,eS,tS,nS,rS=R((()=>{qx=class extends Error{details;status=402;hint;fundingUrl;constructor(e,t={}){super(e),this.details=t.details,this.fundingUrl=t.fundingUrl,t.cause!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t.cause,writable:!0})}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},...this.fundingUrl&&{fundingUrl:this.fundingUrl},...e&&{challengeId:e}}}},Jx=class extends qx{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}.`)}},J=class extends qx{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,fundingUrl:n,reason:r}=e;super(Kx(r?`Payment verification failed: ${r}.`:`Payment verification failed.`,n),{details:t,fundingUrl:n})}},Yx=class extends qx{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.`)}},Xx=class extends qx{name=`PaymentOutcomeUnknownError`;title=`Payment Outcome Unknown`;type=`https://paymentauth.org/problems/payment-outcome-unknown`;challenge;credential;transactionHash;constructor(e){let{cause:t,challenge:n,credential:r,transactionHash:i}=e;super(`Payment outcome is unknown after sending a credential for challenge "${n.id}". Do not blindly retry.`,{cause:t}),this.challenge=n,this.credential=r,this.transactionHash=i}},Zx=class extends Error{name=`LegacyUnicodeEscapedChallengeError`;constructor(){super(`Legacy unicode-escaped challenge: the server escaped a bound parameter as \\uXXXX; upgrade the server.`)}},Qx=class extends Error{name=`ConfigurableVouchersUnsupportedError`;signer;constructor(e){let{signer:t}=e;super(`Configurable account ${t} signs vouchers with TIP-1166 configurable account signatures, but the session challenge does not advertise \`configurableVouchers\`, so the channel was not opened.`),this.signer=t}},$x=class extends Error{name=`SignerConfigChangedError`;channelId;reason;signer;constructor(e){let{cause:t,channelId:n,reason:r,signer:i}=e;super(`Signer ${i} of channel ${n} changed its account config since the channel opened, so the top-up was not signed. Close the channel and open a new one.`),this.channelId=n,this.reason=r,this.signer=i,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},eS=class extends Error{name=`SpendingLimitExceededError`;accessKey;account;constructor(e){let{accessKey:t,account:n,cause:r}=e;super(`Access key spending limit exceeded: ${t?`key ${t} of `:``}account ${n} cannot pay this amount, so the payment was not signed.`),this.accessKey=t,this.account=n,r!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:r,writable:!0})}},tS=class extends Error{name=`ZoneSettlementPendingError`;challengeId;senderTag;senderTags;zoneId;constructor(e){let{cause:t,challengeId:n,zoneId:r}=e,i=e.senderTags??(e.senderTag?[e.senderTag]:[]),a=i.length===1?i[0]:void 0,o=a??(i.length?`with sender tag ${i.join(` or `)}`:void 0);super(`Zone ${r} withdrawal ${o?`${o} `:``}for challenge "${n}" has not settled on Tempo yet. Retry the challenge to resume waiting instead of paying again.`),this.challengeId=n,this.senderTag=a,this.senderTags=i,this.zoneId=r,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},nS=class extends qx{name=`InsufficientBalanceError`;title=`Insufficient Balance`;status=402;type=`https://paymentauth.org/problems/session/insufficient-balance`;constructor(e={}){let{cause:t,fundingUrl:n,reason:r}=e;super(Kx(r?`Insufficient balance: ${r}.`:`Insufficient balance.`,n),{cause:t,fundingUrl:n})}}}));function iS(e){let t=k.toString(e);return JSON.parse(t)}function aS(e,t){return e.schema.request.parse(t)}function oS(e){let t=re.canonicalize(e);return k.fromString(t,{pad:!1,url:!0})}var sS=R((()=>{})),Y=at({address:()=>mS,amount:()=>lS,datetime:()=>uS,datetimeInput:()=>dS,hash:()=>hS,period:()=>gS,signature:()=>_S,toDate:()=>fS,toDatetimeString:()=>pS,unwrapOptional:()=>vS});import*as cS from"zod/mini";st(Y,cS);function lS(){return xe.string().check(xe.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function uS(){return xe.string().check(xe.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 dS(e=`Invalid ISO 8601 datetime`){return xe.pipe(xe.union([uS(),xe.custom(e=>e instanceof Date)]),xe.transform(fS)).check(xe.refine(e=>Number.isFinite(e.getTime()),e))}function fS(e){return e instanceof Date?e:new Date(e)}function pS(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function mS(){return xe.string().check(xe.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function hS(){return xe.string().check(xe.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function gS(){return xe.string().check(xe.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function _S(){return xe.string().check(xe.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function vS(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}var yS=R((()=>{}));function bS(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=KS(o),f=e.expires?pS(e.expires):void 0,p=e.opaque??(i===void 0?void 0:oS(i)),m=u?JS({...e,expires:f,header:d,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return eC.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 xS(e){ES(e);let{method:t}=e;SS(t);let n=[CS(`id`,e.id),CS(`realm`,e.realm),CS(`method`,t),CS(`intent`,e.intent),CS(`request`,oS(e.request))];e.description!==void 0&&n.push(CS(`description`,e.description,{escapeUnicode:!0})),e.digest!==void 0&&n.push(CS(`digest`,e.digest)),e.expires!==void 0&&n.push(CS(`expires`,e.expires));let r=qS(e.header);return r!==void 0&&n.push(CS(`header`,r)),e.opaque===void 0?e.meta!==void 0&&n.push(CS(`opaque`,oS(e.meta))):n.push(CS(`opaque`,e.opaque)),`${Bx.payment} ${n.join(`, `)}`}function SS(e){if(!nC.test(e))throw new rC(e)}function CS(e,t,n={}){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);let r=t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);if(!/[\u0100-\uffff]/.test(r))return`${e}="${r}"`;if(n.escapeUnicode)return`${e}="${r.replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`;throw Error(`Invalid ${e}: characters above U+00FF cannot be sent in a header.`)}function wS(e,t){let n=DS(e);if(!n)throw Error(`Missing Payment scheme.`);let r=new Set,{request:i,opaque:a,header:o,...s}=OS(n,r);if(!i)throw Error(`Missing request parameter.`);if(i.length>YS)throw Error(`Request parameter too large.`);if(s.method!==void 0&&SS(s.method),o!==void 0&&!GS(o))throw new $S;let c=bS({...s,request:iS(i),...a&&{opaque:a}},t),l=o===void 0?c:{...c,header:o};return[...r].some(e=>ZS.has(e))&&(l[XS]=!0),l}function TS(e){return!!(e&&typeof e==`object`&&e[XS])}function ES(e){if(TS(e))throw new Zx}function DS(e){let t=Bx.payment,[n]=NS(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 OS(e,t){let n=Object.create(null),r=0;for(;r<e.length;){for(;r<e.length&&/[\s,]/.test(e[r]??``);)r++;if(r>=e.length)break;let i=r;for(;r<e.length&&/[A-Za-z0-9_-]/.test(e[r]??``);)r++;let a=e.slice(i,r).toLowerCase();if(!a)throw Error(`Malformed auth-param.`);for(;r<e.length&&/\s/.test(e[r]??``);)r++;if(e[r]!==`=`)break;for(r++;r<e.length&&/\s/.test(e[r]??``);)r++;let[o,s,c]=kS(e,r);if(r=s,c&&t?.add(a),a in n)throw Error(`Duplicate parameter: ${a}`);n[a]=o}return n}function kS(e,t){if(e[t]===`"`)return AS(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function AS(e,t){let n=t,r=!1,i=!1,a=t,o;for(;n<e.length;){let s=e[n];if(n++,r){s===`u`&&/^[0-9a-fA-F]{4}/.test(e.slice(n,n+4))&&(i=!0),o??=[],o.push(s),a=n,r=!1;continue}if(s===`\\`){o??=[],o.push(e.slice(a,n-1)),a=n,r=!0;continue}if(s===`"`)return[o?[...o,e.slice(a,n-1)].join(``):e.slice(t,n-1),n,i]}throw Error(`Unterminated quoted-string.`)}function jS(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 MS(e){return NS(e,Bx.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===Bx.payment.toLowerCase())}function NS(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(!jS(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 PS(e,t){let n=e.get(q.wwwAuthenticate);if(!n)throw Error(`Missing ${q.wwwAuthenticate} header.`);return wS(n,t)}function FS(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return PS(e.headers,t)}function IS(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return LS(e.headers,t)}function LS(e,t){let n=e.get(q.wwwAuthenticate);if(!n)throw Error(`Missing ${q.wwwAuthenticate} header.`);return RS(n,t)}function RS(e,t){let n=VS(e);if(n.length===0)throw Error(`No Payment schemes found.`);return n.flatMap(e=>{try{return[wS(e,t)]}catch(e){if(e instanceof $S||e instanceof rC)return[];throw e}})}function zS(e){return e?VS(e).filter(e=>{try{return wS(e),!1}catch(e){return e instanceof $S}}).length:0}function BS(e,t){return t<=0?e:t===1?`${e}. Skipped 1 challenge that selects a credential header other than Payment-Authorization`:`${e}. Skipped ${t} challenges that select a credential header other than Payment-Authorization`}function VS(e){let t=NS(e,Bx.payment);return t.map((n,r)=>{let i=r+1<t.length?t[r+1]:e.length;return e.slice(n,i).replace(/,\s*$/,``)})}function HS(e){let t=[e.realm,e.method,e.intent,oS(e.request),e.expires??``,e.digest??``],n=qS(e.header);return n!==void 0&&t.push(n),t.push(e.opaque??(e.meta?oS(e.meta):``)),t.join(`|`)}function US(e){let{header:t}=e;return t===void 0?q.authorization:GS(t)?q.paymentAuthorization:t}function WS(e){if(typeof e!=`object`||!e||!(`header`in e))return!1;let{header:t}=e;return t!==void 0&&!(typeof t==`string`&&GS(t))}function GS(e){return/^payment-authorization$/i.test(e)}function KS(e){return qS(e)===void 0?void 0:q.paymentAuthorization}function qS(e){if(e!==void 0&&!/^authorization$/i.test(e)){if(GS(e))return e;throw new $S}}function JS(e,t){let n=HS(e),r=A.fromString(t.secretKey),i=A.fromString(n),a=ne.hmac256(r,i,{as:`Bytes`});return k.fromBytes(a,{url:!0,pad:!1})}var YS,XS,ZS,QS,$S,eC,tC,nC,rC,iC=R((()=>{Gx(),rS(),sS(),yS(),YS=16384,XS=Symbol(`mppx.Challenge.legacyUnicodeEscape`),ZS=new Set([`digest`,`expires`,`header`,`intent`,`method`,`opaque`,`realm`,`request`]),QS=`Unsupported credential header: challenges may only select Payment-Authorization.`,$S=class extends Error{name=`UnsupportedCredentialHeaderError`;constructor(){super(QS)}},eC=Y.object({description:Y.optional(Y.string()),digest:Y.optional(Y.string().check(Y.regex(/^sha-256=/,`Invalid digest format`))),expires:Y.optional(uS()),header:Y.optional(Y.string().check(Y.refine(GS,QS))),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())}),tC=Y.extend(eC,{header:Y.optional(Y.string())}),nC=/^[a-z]+$/,rC=class extends Error{name=`InvalidMethodError`;constructor(e){super(`Invalid method: "${e}". Must be lowercase letters a-z per spec.`)}}}));function aC(e){if(e.length>dC)throw new pC;let t=e.match(RegExp(`^${Bx.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new fC;try{let e=k.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=oC(r);return{challenge:eC.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:iS(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new pC}}function oC(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!sC(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:oS(e)}}function sC(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function cC(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function lC(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:oS(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:oS(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=k.fromString(s,{pad:!1,url:!0});return`${Bx.payment} ${c}`}function uC(e){return e.length>dC?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${Bx.payment}\\s+`,`i`).test(e))??null}var dC,fC,pC,mC=R((()=>{iC(),Gx(),sS(),dC=65536,fC=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},pC=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}}}));function hC(e,t){if(!e)throw new Jx({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new Jx({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new Yx({expires:e})}var gC=R((()=>{rS()}));function _C(e){if(!e)return[];let t;try{t=we(e)}catch{return[]}let n=[];for(let e of t){if(Ce(e)||!(e[0]instanceof Se))continue;let t=e[1].get(`issuer`);n.push(Object.freeze({type:e[0].toString(),...typeof t==`string`&&{issuer:t}}))}return Object.freeze(n)}var vC,yC=R((()=>{vC=`Identity-Required`,Object.freeze([`identity-attestation-required`])}));function bC(){let e=new Uint8Array(64);return crypto.getRandomValues(e),{created:Math.floor(Date.now()/1e3),nonce:k.fromBytes(e,{pad:!1,url:!0})}}var xC=R((()=>{}));function SC(e,t){switch(t.type){case`send`:if(e.phase!==`unproved`)break;return Object.freeze({phase:t.payment===`paid`?`paid`:`sent`});case`response`:if(t.resend===void 0){if(e.phase===`unproved`||e.phase===`done`)break;return Object.freeze({phase:`done`})}if(e.phase!==`sent`)break;return Object.freeze({phase:`resent`,headers:t.resend})}let n=t.type===`response`&&t.resend!==void 0?` with resend`:``;throw TypeError(`Illegal identity attempt transition "${t.type}${n}" from phase "${e.phase}".`)}function CC(e){if(e.length===0)throw TypeError(`Mppx client identity must configure at least one prover.`);for(let t of e)if(t.scope!==`*`&&!Array.isArray(t.scope))throw TypeError(`Identity prover scope must be "*" or an array of origins.`);let t=Object.freeze([...new Set(e.flatMap(e=>{if(e.headers!==void 0&&!Array.isArray(e.headers))throw TypeError(`Identity prover headers must be an array of header names.`);return(e.headers??[]).map(e=>e.toLowerCase())}))]),n=t=>{let n=new URL(t).origin;return e.filter(e=>e.scope===`*`||e.scope.includes(n))};async function r(e){let{context:t,fetch:r,headers:i,keepReadable:a,request:o}=e,s=a?o.clone():o,c=n(o.url);if(c.length===0)return{request:s,response:await r(s)};let l=Object.freeze({...bC(),...t.challenge&&{challenge:t.challenge}}),u=new Headers(s.headers),d=new Set(NC);t.challenge&&d.add(US(t.challenge).toLowerCase());for(let[e,t]of s.headers)uC(t)!==null&&d.add(e.toLowerCase());for(let[e,t]of i)d.has(e.toLowerCase())||u.set(e,t);let f=new Request(s,{headers:u,redirect:o.redirect===`follow`?`error`:o.redirect});for(let e of c)f=await e.prove(f,l);return{request:f,response:await r(f)}}return{headers:t,async send(e,t,i={}){let a=SC(PC,{type:`send`,payment:wC(t,i)?`paid`:`unpaid`}),o=n(t.url).filter(e=>e.retry),s=a.phase===`sent`&&o.length>0,c=i.headers??[],l=await r({context:i,fetch:e,headers:c,keepReadable:s,request:t}),{response:u}=l,d=s&&u.status>=400&&u.status!==402?await TC(o,u,l.request):void 0;if(a=SC(a,{type:`response`,resend:d}),a.phase!==`resent`)return{...l,headers:c};EC([u]);let f=AC(c,a.headers),p=await r({context:i,fetch:e,headers:f,keepReadable:!1,request:t});return SC(a,{type:`response`,resend:void 0}),{...p,headers:f}},async challenge(e,{challenge:t},r){let i=Object.freeze({challenge:t,requirements:_C(e.headers.get(vC))});for(let t of n(r)){if(!t.prepare)continue;let n=e.clone();try{await t.prepare(n,i)}finally{EC([n])}}}}}function wC(e,t){return t.challenge!==void 0||MC.some(t=>e.headers.has(t))||[...e.headers.values()].some(e=>uC(e)!==null)}async function TC(e,t,n){let r=Object.freeze({request:n}),i=[],a=!1,o=new Headers;try{for(let n of e){let e=t.clone();i.push(e);let s=await n.retry(e,r);if(s===!0)a=!0;else if(typeof s==`object`&&s){a=!0;for(let[e,t]of new Headers(s))NC.has(e)||o.append(e,t)}}}finally{EC(i)}if(a)return Object.freeze([...o].map(([e,t])=>Object.freeze([e,t])))}function EC(e){for(let t of e)t.bodyUsed||t.body?.cancel().catch(()=>{})}function DC(e,t,n={}){return async(r,i)=>{let a=new Request(r,i),o=OC(a.headers)??n.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[jC]?{[jC]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of kC(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{challenge:e},a.url);return s}}function OC(e){for(let[,t]of e){let e=uC(t);if(e)try{return aC(e).challenge}catch{}}}function kC(e){try{return IS(e)}catch{return[]}}function AC(e,t){let n=new Headers;for(let[t,r]of e)n.set(t,r);for(let[e,r]of t)n.set(e,r);return Object.freeze([...n].map(e=>Object.freeze(e)))}var jC,MC,NC,PC,FC=R((()=>{iC(),mC(),yC(),xC(),jC=Symbol.for(`mppx.fetch.skipPayment`),MC=[`payment-signature`,`x-payment`],NC=new Set([`authorization`,`payment-authorization`,...MC]),PC=Object.freeze({phase:`unproved`})}));function IC(e){return Object.defineProperty(e,RC,{value:!0}),e}function LC(e){return!!e?.[RC]}var RC,zC=R((()=>{RC=Symbol.for(`mppx.x402.challenge`)}));function BC(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=KC(n)}return t}function VC(e,t){let n=BC(e),r=$C(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[KC(e)]??1,index:t}));return{definition:r,entries:i,header:UC(i),keys:n}}function HC(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)=>ZC(e,t))}function UC(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${rw(n)}`}).join(`, `)}function WC(e,t,n){let r=GC(e,t,n)[0];if(r)return{challenge:r.challenge,method:r.method}}function GC(e,t,n,r){let i=new Map;for(let e of t){let t=KC(e),n=i.get(t);n?n.push(e):i.set(t,[e])}let a=e.flatMap((e,t)=>{let a=i.get(KC(e));if(!a)return[];let o=qC(e,n);return!o||o.q<=0?[]:a.filter(t=>t.canHandleChallenge?.(r===void 0?{challenge:e}:{challenge:e,context:r})??!0).map(n=>({challenge:e,index:t,match:o,method:n}))}).sort((e,t)=>XC(e.challenge)-XC(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n}),o=a.filter(({challenge:e})=>!TS(e));return o.length===0&&a[0]&&ES(a[0].challenge),o}function KC(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function qC(e,t){let n;for(let r of t){if(!JC(e,r))continue;let t={...r,specificity:YC(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 JC(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function YC(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function XC(e){return+!!LC(e)}function ZC(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}`);iw(r,`method`),iw(i,`intent`);let a=1;for(let t of QC(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=tw(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function QC(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function $C(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>KC(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]=ew(t,`payment preference "${e}"`)}return a}function ew(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return nw(e,t)}function tw(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 nw(Number(e),t)}function nw(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 rw(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function iw(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}var aw,ow=R((()=>{iC(),zC(),aw=Symbol(`mppx.deferredContext`)})),sw,cw,lw=R((()=>{sw=`org.paymentauth/credential`,cw=`org.paymentauth/payment-required`}));function uw(e){let t=``,n=!1,r=!1,i,a=``;function o(t){if(t===``){i!==void 0&&e({data:i,event:a||`message`}),i=void 0,a=``;return}let n=t.indexOf(`:`);if(n===0)return;let r=n===-1?t:t.slice(0,n);if(r!==`data`&&r!==`event`)return;let o=``;n!==-1&&(o=t.slice(t.charCodeAt(n+1)===32?n+2:n+1)),r===`event`?a=o:i=i===void 0?o:i+`
207
+ `),!0}function Vy(e,t){return Uy(e)?`${e} --mcp`:`${t} ${Gy(e)} --mcp`}function Hy(){let e=(process.argv[1]?.replace(/\\/g,`/`))?.match(/^(.+)\/node_modules\/(.+)$/);return e?{root:e[1],entry:e[2]}:null}function Uy(e){let t=process.argv[1];if(!t)return!1;let n=Hy();if(n)return!n.entry.startsWith(`.bin/`)&&!Wy(n.root,e);let r=t.replace(/\\/g,`/`).split(`/`).pop();return r===e||r===`${e}.cmd`||r===`${e}.ps1`}function Wy(e,t){try{let n=JSON.parse(a(d(e,`package.json`),`utf-8`));return[n.dependencies,n.devDependencies,n.optionalDependencies,n.peerDependencies].some(e=>t in(e??{}))}catch{return!1}}function Gy(e){let t=Hy();if(!t)return e;try{let n=JSON.parse(a(d(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 Ky(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 qy(e,t){return new Promise((n,r)=>{h(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 Jy=z((()=>{ut()}));function Yy(){return ab.filter(e=>e.detect())}function Xy(e,n={}){let r=n.global!==!1,i=n.cwd||process.cwd(),a=r?K:i,o=c.join(a,`.agents`,`skills`),s=n.agents??Yy(),l=[],u=[];for(let n of Qy(e)){let e=c.join(o,n.name);eb(e),t.mkdirSync(e,{recursive:!0}),n.root?t.copyFileSync(c.join(n.dir,`SKILL.md`),c.join(e,`SKILL.md`)):t.cpSync(n.dir,e,{recursive:!0}),l.push(e);for(let a of s){if(a.universal)continue;let o=r?a.globalSkillsDir:c.join(i,a.projectSkillsDir),s=c.join(o,n.name);if(tb(s)!==tb(e))try{eb(s),t.mkdirSync(c.dirname(s),{recursive:!0});let n=tb(c.dirname(s)),r=tb(e),i=c.relative(n,r);t.symlinkSync(i,s),u.push({agent:a.name,path:s,mode:`symlink`})}catch{try{t.cpSync(e,s,{recursive:!0}),u.push({agent:a.name,path:s,mode:`copy`})}catch{}}}}return{paths:l,agents:u}}function Zy(e,t={}){let n=t.global!==!1,r=t.cwd||process.cwd(),i=n?K:r;eb(c.join(i,`.agents`,`skills`,e));for(let t of Yy()){if(t.universal)continue;let i=n?t.globalSkillsDir:c.join(r,t.projectSkillsDir);eb(c.join(i,e))}}function Qy(e){let n=[];function r(e){let i;try{i=t.readdirSync(e,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let i=c.join(e,a.name),o=c.join(i,`SKILL.md`);if(t.existsSync(o)){let e=t.readFileSync(o,`utf8`).match(/^name:\s*(.+)$/m);n.push({name:$y(e?.[1]??a.name),dir:i})}r(i)}}r(e);let i=c.join(e,`SKILL.md`);if(t.existsSync(i)){let r=$y(t.readFileSync(i,`utf8`).match(/^name:\s*(.+)$/m)?.[1]??`skill`);n.some(e=>e.name===r)||n.push({name:r,dir:e,root:!0})}return n}function $y(e){return e.trim().replace(/[/\\]/g,`-`).replace(/\.\./g,``).slice(0,255)}function eb(e){try{t.lstatSync(e).isSymbolicLink()?t.unlinkSync(e):t.rmSync(e,{recursive:!0,force:!0})}catch{}}function tb(e){try{return t.realpathSync(e)}catch{let n=c.dirname(e);if(n===e)return e;try{return c.join(t.realpathSync(n),c.relative(n,e))}catch{return e}}}var K,nb,rb,ib,ab,ob=z((()=>{K=x.homedir(),nb=process.env.XDG_CONFIG_HOME||c.join(K,`.config`),rb=process.env.CLAUDE_CONFIG_DIR?.trim()||c.join(K,`.claude`),ib=process.env.CODEX_HOME?.trim()||c.join(K,`.codex`),ab=[{name:`Amp`,globalSkillsDir:c.join(nb,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(nb,`amp`))},{name:`Cline`,globalSkillsDir:c.join(K,`.agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.cline`))},{name:`Codex`,globalSkillsDir:c.join(ib,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(ib)},{name:`Cursor`,globalSkillsDir:c.join(K,`.cursor`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.cursor`))},{name:`Gemini CLI`,globalSkillsDir:c.join(K,`.gemini`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.gemini`))},{name:`GitHub Copilot`,globalSkillsDir:c.join(K,`.copilot`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.copilot`))},{name:`Kimi CLI`,globalSkillsDir:c.join(nb,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.kimi`))},{name:`OpenCode`,globalSkillsDir:c.join(nb,`opencode`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(nb,`opencode`))},{name:`Claude Code`,globalSkillsDir:c.join(rb,`skills`),projectSkillsDir:`.claude/skills`,universal:!1,detect:()=>t.existsSync(rb)},{name:`Windsurf`,globalSkillsDir:c.join(K,`.codeium`,`windsurf`,`skills`),projectSkillsDir:`.windsurf/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.codeium`,`windsurf`))},{name:`Continue`,globalSkillsDir:c.join(K,`.continue`,`skills`),projectSkillsDir:`.continue/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.continue`))},{name:`Roo`,globalSkillsDir:c.join(K,`.roo`,`skills`),projectSkillsDir:`.roo/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.roo`))},{name:`Kilo`,globalSkillsDir:c.join(K,`.kilocode`,`skills`),projectSkillsDir:`.kilocode/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.kilocode`))},{name:`Goose`,globalSkillsDir:c.join(nb,`goose`,`skills`),projectSkillsDir:`.goose/skills`,universal:!1,detect:()=>t.existsSync(c.join(nb,`goose`))},{name:`Augment`,globalSkillsDir:c.join(K,`.augment`,`skills`),projectSkillsDir:`.augment/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.augment`))},{name:`Trae`,globalSkillsDir:c.join(K,`.trae`,`skills`),projectSkillsDir:`.trae/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.trae`))},{name:`Junie`,globalSkillsDir:c.join(K,`.junie`,`skills`),projectSkillsDir:`.junie/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.junie`))},{name:`Crush`,globalSkillsDir:c.join(nb,`crush`,`skills`),projectSkillsDir:`.crush/skills`,universal:!1,detect:()=>t.existsSync(c.join(nb,`crush`))},{name:`Kiro CLI`,globalSkillsDir:c.join(K,`.kiro`,`skills`),projectSkillsDir:`.kiro/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.kiro`))},{name:`Qwen Code`,globalSkillsDir:c.join(K,`.qwen`,`skills`),projectSkillsDir:`.qwen/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.qwen`))},{name:`OpenHands`,globalSkillsDir:c.join(K,`.openhands`,`skills`),projectSkillsDir:`.openhands/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.openhands`))}]}));async function sb(e,t,n={}){let{depth:r=1,description:i,global:a=!0}=n,o=n.cwd??(a?ub():process.cwd());await Cl();let s=new Map;i&&s.set(e,i);let c=jy(e,hx(t,[],s,n.rootCommand),r,s),u=await T.mkdtemp(l.join(S.tmpdir(),`incur-skills-${e}-`));try{let r=[];for(let t of c){let n=t.dir?l.join(u,t.dir,`SKILL.md`):l.join(u,`SKILL.md`);await T.mkdir(l.dirname(n),{recursive:!0}),await T.writeFile(n,`${t.content}\n`);let i=bx(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`:l.join(t,`SKILL.md`);for await(let i of T.glob(n,{cwd:o}))try{let n=await T.readFile(l.resolve(o,i),`utf8`),a=bx(n),s=t===`_root`?a.name??e:l.basename(l.dirname(i)),c=l.join(u,s,`SKILL.md`);await T.mkdir(l.dirname(c),{recursive:!0}),await T.writeFile(c,n),r.some(e=>e.name===s)||r.push({name:s,description:a.description,external:!0})}catch{}}let{paths:i,agents:s}=Xy(u,{global:a,cwd:o}),d=new Set(i.map(e=>l.basename(e))),f=pb(e);if(f?.skills)for(let e of f.skills)d.has(e)||Zy(e,{global:a,cwd:o});return fb(e,Py(hx(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 T.rm(u,{recursive:!0,force:!0})}}async function cb(e,t,n={}){let{depth:r=1,description:i}=n,a=n.cwd??process.cwd();await Cl();let o=new Map;i&&o.set(e,i);let s=jy(e,hx(t,[],o,n.rootCommand),r,o),c=[],u=mb(e,{cwd:a});for(let t of s){let n=bx(t.content),r=n.name??(t.dir||e);c.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`:l.join(t,`SKILL.md`);for await(let r of T.glob(n,{cwd:a}))try{let n=bx(await T.readFile(l.resolve(a,r),`utf8`)),i=t===`_root`?n.name??e:l.basename(l.dirname(r));c.some(e=>e.name===i)||c.push({name:i,description:n.description,installed:u.has(i)})}catch{}}return c.sort((e,t)=>e.name.localeCompare(t.name))}function lb(e,t={}){return mb(e,t).size>0}function ub(){let e=process.argv[1];if(!e)return process.cwd();let t=l.dirname((()=>{try{return n.realpathSync(e)}catch{return process.execPath}})()),r=l.parse(t).root;for(;t!==r;){try{return n.accessSync(l.join(t,`package.json`)),t}catch{}t=l.dirname(t)}return process.cwd()}function db(e){let t=process.env.XDG_DATA_HOME||l.join(S.homedir(),`.local`,`share`);return l.join(t,`incur`,`${e}.json`)}function fb(e,t,r,i){let a=db(e),o=l.dirname(a);n.existsSync(o)||n.mkdirSync(o,{recursive:!0}),n.writeFileSync(a,JSON.stringify({hash:t,skills:r,paths:i,at:new Date().toISOString()})+`
208
+ `)}function pb(e){try{return JSON.parse(n.readFileSync(db(e),`utf-8`))}catch{return}}function mb(e,t={}){let n=pb(e);if(!n?.skills?.length)return new Set;if(n.paths?.length){let e=n.paths.filter(e=>hb(e)).map(e=>l.basename(e));return new Set(e)}let r=t.cwd??process.cwd(),i=[l.join(S.homedir(),`.agents`,`skills`),l.join(r,`.agents`,`skills`)],a=n.skills.filter(e=>i.some(t=>hb(l.join(t,e))));return new Set(a)}function hb(e){return n.existsSync(l.join(e,`SKILL.md`))}function gb(e){return pb(e)?.hash}var _b=z((()=>{Lx(),ob(),El(),Ry()}));function vb(e,t){let n=typeof e==`string`?e:e.name,r=typeof e==`string`?t??{}:e,i=r.version??Gt,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:Zb(o),c=o===void 0?void 0:Qb(o),l=new Map,u=[],d=[],f=bb(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 Bv(await Rv(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(Xb(t))return d.push((async()=>{let n=hy(await my(t.mcp)),r={_group:!0,description:t.description,commands:n,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0};rx(e,r,Px.get(p)),l.set(e,r)})()),p;if(t&&`fetch`in t&&Yb(t.fetch)){let n=Zb(t.fetch);return t.openapi?(d.push((async()=>{let r=await Bv(await Rv(t.openapi,{baseUrl:Qb(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};rx(e,i,Px.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(rx(e,t,Px.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=Ax.get(e),r=e,i=Dx.get(r),a=Nx.get(r),o=kx.get(r),s=Ox.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(()=>{rx(r.name,c,Px.get(p))})):rx(r.name,c,Px.get(p)),l.set(r.name,c),n){let t=Fx.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=Px.get(p);return Cb(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=ku();return d.push((async()=>{let n=t?await Au(t):await Gb(await Wb(e));for(let e of n){if(!Kb(e.command))throw Error(`Expected the default export from '${e.file}' to be created with \`Cli.command()\`.`);qb(l,e.segments,e.command,e.file,Px.get(p))}})()),p},async serve(e=process.argv.slice(2),t={}){if(await jt(e))return;d.length>0&&await Promise.all(d);let o=Px.get(p);return yb(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&&Ax.set(p,a),a&&r.aliases&&Fx.set(p,r.aliases),r.options&&jx.set(p,r.options),r.config!==void 0&&Mx.set(p,!0),r.outputPolicy&&Nx.set(p,r.outputPolicy),r.globals){Px.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 kx.set(p,u),Dx.set(p,l),Ox.set(p,d),p}async function yb(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=Cx(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=Ob(n,{configFlag:l})}catch(e){let t=e instanceof Error?e.message:String(e);d(s?ix({code:`UNKNOWN`,message:t}):Dl({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:E,version:ee,schema:D,configPath:O,configDisabled:k,rest:te}=p;s=o&&!g;let A={...typeof r.update==`object`?r.update:void 0,binary:Wt!==void 0,version:r.version},j={},M=te;function ne(e){if(!r.globals)return!0;try{let t=Xl(te,r.globals.schema,r.globals.alias,{validate:e});return e&&(j=t.parsed),M=t.rest,!0}catch(e){let t=e instanceof Error?e.message:String(e);return d(s?ix({code:`UNKNOWN`,message:t}):Dl({code:`UNKNOWN`,message:t},`toon`)),a(1),!1}}if(!ne(!1))return;if(h===`yaml`&&await Cl(),E){if(r.update!==!1)try{await ft(e,A)}catch{}return}if(T&&!w){try{let t=await pt(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
+ `))}else d(Dl(t,h))}catch(e){let t={code:`UPDATE_FAILED`,message:e instanceof Error?e.message:String(e)};d(s?ix(t):Dl(t,h)),a(1)}return}if(C){await q_(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 N=process.env.COMPLETE;if(N){let a=n.indexOf(`--`),o=a===-1?n:n.slice(a+1);if(o.length===0)i([e,...r.aliases??[]].map(e=>hn(N,e)).join(`
211
+ `));else{let e=Number(process.env._COMPLETE_INDEX??o.length-1),n=gn(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 cu)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=iu(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=_n(N,n);c&&i(c)}return}let P;if(!x&&!S&&!D&&!w&&!T&&!E&&!ee){let n=Fb(M,e,`skills`)!==-1,i=Fb(M,e,`mcp`)!==-1;if(!n&&!i){let n=gb(e);n&&lb(e,{cwd:r.sync?.cwd})&&Py(hx(t,[],new Map,r.rootCommand))!==n&&(P={description:`Skills are out of date:`,commands:[{command:process.env.npm_config_user_agent||process.env.npm_execpath?`${ct()} ${Gy(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=nx(n,t);if($b(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=hx(n,s,t,o);d(Ay(i.length>0?`${e} ${i.join(` `)}`:e,r,t));return}d(Dl(fx(n,i,r.globals?.schema,o),h));return}if(!g||h===`md`){let t=hx(n,s,new Map,o);d(Oy(i.length>0?`${e} ${i.join(` `)}`:e,t,a));return}d(Dl(ux(n,i,r.globals?.schema,o),h));return}let re=Fb(M,e,`completions`);if(re!==-1){let t=M[re+1];if(w||!t){let t=iu(`completions`);d(du(`${e} completions`,{args:t.args,description:t.description,hideGlobalOptions:!0,hint:t.hint?.(e)}));return}if(!su.includes(t)){d(ix({code:`INVALID_SHELL`,message:`Unknown shell '${t}'. Supported: ${su.join(`, `)}`})),a(1);return}d([e,...r.aliases??[]].map(e=>hn(t,e)).join(`
212
+ `));return}let ie=Fb(M,e,`skills`);if(ie!==-1){let o=iu(`skills`),c=M[ie+1],l=c?au(o,c):void 0;if(c&&!l){let t=pn(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(ix({code:`COMMAND_NOT_FOUND`,message:r})),d(ax(l))):d(Dl({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(Ib(e,o));return}if(l?.name===`list`){if(w){d(Lb(e,o,`list`));return}try{let n=await cb(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(Dl({code:`LIST_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(w){d(Lb(e,o,`add`));return}let u=M.slice(ie+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 sb(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(Dl(e,g?h:`toon`))}}catch(e){d(Dl({code:`SYNC_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}let ae=Fb(M,e,`mcp`);if(ae!==-1){let o=iu(`mcp`),c=M[ae+1],l=c?au(o,c):void 0;if(c&&!l){let t=pn(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(ix({code:`COMMAND_NOT_FOUND`,message:r})),d(ax(l))):d(Dl({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(Ib(e,o));return}if(w){d(Lb(e,o,l.name));return}if(l.name===`doctor`){let n=await Rb(e,t,r);d(Dl(n,g?h:`toon`)),n.ok||a(1);return}let u=M.slice(ae+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 zy(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(Dl({name:t,command:n.command,agents:n.agents},g?h:`toon`))}catch(e){d(Dl({code:`MCP_ADD_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(ee&&!w&&r.version){d(r.version);return}if(M.length===0){if(r.rootCommand&&s&&r.rootCommand.args&&sx(r.rootCommand.args)){let n=r.rootCommand;await f(),d(du(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:yx(n.examples),usage:n.usage,commands:t.size>0?Pb(t):void 0,root:!0}));return}if(!(r.rootCommand||r.rootFetch)){await f(),d(uu(e,{aliases:r.aliases,configFlag:l,description:r.description,globals:r.globals,version:r.version,commands:Pb(t),root:!0}));return}}let F=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 F){let n=F.path===e?e:`${e} ${F.path}`;F.path===e&&t.size>0?d(uu(e,{aliases:r.aliases,configFlag:l,description:r.description,version:r.version,commands:Pb(t),root:!0})):d(Ub(n,F.fetchGateway.description));return}if(w){if(`help`in F||`error`in F){let n=`help`in F?`${e} ${F.path}`:e,i=`help`in F?F.description:r.description,a=`help`in F?F.commands:t,o=n===e;if(o&&r.rootCommand&&a.size>0){let t=r.rootCommand;d(du(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:yx(t.examples),usage:t.usage,commands:Pb(a),root:!0}))}else d(uu(n,{aliases:o?r.aliases:void 0,configFlag:l,description:i,globals:r.globals,version:o?r.version:void 0,commands:Pb(a),root:o}))}else if(`command`in F){let n=F.command,i=F.path===e,a=i?e:`${e} ${F.path}`,o=`commands`in F&&F.commands&&F.commands.size>0?Pb(F.commands):i&&r.rootCommand&&t.size>0?Pb(t):void 0;d(du(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:yx(n.examples),usage:n.usage,commands:o,root:i}))}return}if(D){if(`help`in F){d(uu(`${e} ${F.path}`,{configFlag:l,description:F.description,globals:r.globals,commands:Pb(F.commands)}));return}if(`error`in F){let t=F.path?`${e} ${F.path}`:e,n=pn(F.error,F.commands.keys()),r=n?` Did you mean '${n}'?`:``;d(`Error: '${F.error}' is not a command for '${t}'.${r}`),a(1);return}if(`fetchGateway`in F){d(`--schema is not supported for fetch commands.`),a(1);return}let t=F.command,n=g?h:`toon`,i={};t.args&&(i.args=Iu(t.args)),t.env&&(i.env=Iu(t.env)),t.options&&(i.options=Iu(t.options)),t.output&&(i.output=Iu(t.output)),r.globals?.schema&&(i.globals=Iu(r.globals.schema)),d(Dl(i,n));return}if(`help`in F){d(uu(`${e} ${F.path}`,{configFlag:l,description:F.description,globals:r.globals,commands:Pb(F.commands)}));return}let oe;if(s&&r.update!==!1){let t=dt(e,A);t&&(oe={description:`Update available for ${t.name}:`,commands:[{command:`${u} --update`,description:`upgrade from ${t.current} to ${t.latest}`}]})}let se=ox(P,oe),I=performance.now(),ce=`command`in F&&F.command.format,L=g?h:ce||r.format||`toon`;L===`yaml`&&await Cl();let le=`error`in F&&!F.path&&(()=>{let e=[...F.commands.keys()];for(let t of cu)e.push(t.name);return pn(F.error,e)!==void 0})(),ue=`error`in F&&r.rootFetch&&!F.path&&!le?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:M}:`error`in F&&r.rootCommand&&!F.path&&!le?{command:r.rootCommand,path:e,rest:M}:F,de=`outputPolicy`in F&&F.outputPolicy||r.outputPolicy,fe=!(s&&!g&&de===`agent-only`),pe=_?Hn(_):void 0;function me(e){if(v==null&&y==null)return{text:e,truncated:!1};let t=$t(e),n=y??0,r=v==null?t:n+v;if(n===0&&r>=t)return{text:e,truncated:!1};let i=en(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 he(e){if(pe&&e.ok&&e.data!=null&&(e={...e,data:Un(e.data,pe)}),se){let t=e.meta.cta;e={...e,meta:{...e.meta,cta:t?{description:t.description,commands:[...t.commands,...se.commands]}:se}}}if(b){let t=e.ok?e.data:e.error,n=t==null?``:Dl(t,L);return d(String($t(n)))}let t=e.meta.cta;if(s&&!m){e.ok&&e.data!=null&&fe?d(me(Dl(e.data,L)).text):e.ok||d(ix(e.error)),t&&d(ax(t));return}if(m){if(v!=null||y!=null){let t=me(e.ok&&e.data!=null?Dl(e.data,L):e.ok?``:Dl(e.error,L));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(Dl(n,L))}}return d(Dl(e,L))}let n=e.ok?e.data:e.error,r=Dl(n,L);if(!t){r&&d(me(r).text);return}d(me(Dl(typeof n==`object`&&n?{...n,cta:t}:{data:n,cta:t},L)).text)}if(`error`in ue){let t=ue.path?`${e} ${ue.path} --help`:`${e} --help`,r=ue.path?`${e} ${ue.path}`:e,i=`commands`in ue?[...ue.commands.keys()]:[];if(!ue.path)for(let e of cu)i.push(e.name);let o=pn(ue.error,i),c=o?` Did you mean '${o}'?`:``,l=`'${ue.error}' is not a command for '${r}'.${c}`,u=[];if(o){let t=n.map(e=>e===ue.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(ix({code:`COMMAND_NOT_FOUND`,message:l})),d(ax(se?{...f,commands:[...f.commands,...se.commands]}:f)),a(1);return}he({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:l},meta:{command:ue.error,cta:f,duration:`${Math.round(performance.now()-I)}ms`}}),a(1);return}if(`fetchGateway`in ue){if(!ne(!0))return;let{fetchGateway:t,path:n,rest:i}=ue,o=[...r.middlewares??[],...ue.middlewares??[]],c=async()=>{let r=Pn(i);t.basePath&&(r.path=t.basePath+r.path);let o=Fn(r),c=await t.fetch(o);if(In(c)){await lx(Ln(c),{name:e,path:n,start:I,format:L,formatExplicit:g,human:s,renderOutput:fe,fullOutput:m,truncate:me,write:he,writeln:d,exit:a});return}let l=await Rn(c);l.ok?he({ok:!0,data:l.data,meta:{command:n,duration:`${Math.round(performance.now()-I)}ms`}}):(he({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()-I)}ms`}}),a(1))};try{let t=r.envSchema?ql(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=>({[Ix]:`error`,...e}),format:L,formatExplicit:g,globals:j,name:e,set(e,t){i[e]=t},var:i,version:r.version},d=e=>{if(!cx(e)||e[Ix]!==`error`)return;let t=e,r=wu(u,t.cta);he({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()-I)}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){he({ok:!1,error:{code:e instanceof B?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:n,duration:`${Math.round(performance.now()-I)}ms`}}),a(e instanceof B?e.exitCode??1:1)}return}let{command:ge,path:_e,rest:R}=ue;if(!ne(!0))return;let ve=[...r.middlewares??[],...`middlewares`in F?F.middlewares??[]:[],...ge.middleware??[]];s&&Sx(R,ge.options,ge.alias);let ye;if(c)try{ye=await kb(e,_e,{configDisabled:k,configPath:O,files:r.config?.files,loader:r.config?.loader})}catch(e){he({ok:!1,error:{code:e instanceof B?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:_e,duration:`${Math.round(performance.now()-I)}ms`}}),a(e instanceof B?e.exitCode??1:1);return}let be=await $l(ge,{agent:!s,argv:R,defaults:ye,displayName:u,env:r.envSchema,envSource:r.env,format:L,formatExplicit:g,globals:j,inputOptions:{},middlewares:ve,name:e,path:_e,vars:r.vars,version:r.version}),xe=`${Math.round(performance.now()-I)}ms`;if(`stream`in be){await lx(be.stream,{name:u,path:_e,start:I,format:L,formatExplicit:g,human:s,renderOutput:fe,fullOutput:m,truncate:me,write:he,writeln:d,exit:a});return}if(be.ok){let e=wu(u,be.cta);he({ok:!0,data:be.data,meta:{command:_e,duration:xe,...e?{cta:e}:void 0}})}else{let e=wu(u,be.cta);if(s&&!g&&be.error.fieldErrors){d(Tb(u,_e,ge,new jn({message:be.error.message,fieldErrors:be.error.fieldErrors}),r.env,l)),a(1);return}he({ok:!1,error:{code:be.error.code,message:be.error.message,...be.error.retryable===void 0?void 0:{retryable:be.error.retryable},...be.error.fieldErrors?{fieldErrors:be.error.fieldErrors}:void 0},meta:{command:_e,duration:xe,...e?{cta:e}:void 0}}),a(be.exitCode??1)}}function bb(e,t,n={}){let r;async function i(r,i,a){let{fromJsonSchema:o,McpServer:s,WebStandardStreamableHTTPServerTransport:c}=await Promise.resolve().then(()=>(K_(),__)),l=new s({name:e,...n.title?{title:n.title}:void 0,version:t},n.instructions?{instructions:n.instructions}:void 0);Z_(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 xb(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 Sb(e,t,n){let r={name:e,description:n.description};return Dx.set(r,t),n.rootCommand&&Ax.set(r,n.rootCommand),Cv(r,{title:e,...n.version?{version:n.version}:void 0,...n.description?{description:n.description}:void 0})}async function Cb(e,t,n,r={}){let i=performance.now(),a=new URL(n.url),o=a.pathname.split(`/`).filter(Boolean);if(n.method===`GET`&&xb(o)){let n=Sb(e,t,r),i=o[0]===`openapi.yml`||o[0]===`openapi.yaml`;return new Response(i?(await Cl()).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 Cl();let n=new Map,i=hx(t,[],n,r.rootCommand);if(o[2]===`index.json`&&o.length===3){let t=jy(e,i,1,n).map(t=>{let n=t.content.match(/^---\n([\s\S]*?)\n---/),r=n?wl().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=jy(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(Wr(e),{status:t,headers:{"content-type":`application/json`}})}if(o.length===0)return r.rootCommand?wb(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=pn(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 wb(d,u,f,s,n,i,{...r,groupMiddlewares:p})}async function wb(e,t,n,r,i,a,o){function s(e,t){return new Response(Wr(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 $l(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(wu(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(cx(s)&&s[Ix]===`error`){a.enqueue(n.encode(Wr(i(s))+`
216
+ `)),a.close();return}let t=cx(s)&&s[Ix]===`ok`?wu(o.name??e,s.cta):void 0;a.enqueue(n.encode(Wr({type:`done`,ok:!0,meta:r(t)})+`
217
+ `)),a.close();return}if(cx(s)&&s[Ix]===`error`){a.enqueue(n.encode(Wr(i(s))+`
218
+ `)),await t.return(void 0),a.close();return}a.enqueue(n.encode(Wr({type:`chunk`,data:s})+`
219
+ `))}catch(e){a.enqueue(n.encode(Wr({type:`error`,ok:!1,error:{code:e instanceof B?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof B?{retryable:e.retryable}:void 0},meta:r()})+`
220
+ `)),a.close()}}});return new Response(s,{status:200,headers:{"content-type":`application/x-ndjson`}})}if(!d.ok){let t=wu(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=wu(o.name??e,d.cta);return s({ok:!0,data:d.data,meta:{command:e,duration:f,...p?{cta:p}:void 0}},200)}function Tb(e,t,n,r,i,a){let o=[];for(let e of r.fieldErrors){let t=(()=>{let t=Eb(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(du(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:yx(n.examples),usage:n.usage})),o.join(`
221
+ `)}function Eb(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:`--${dn(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=nx(e,e.get(n)),a=[n],o=r,s,c=[];if(ex(i)){let e=i.outputPolicy??s;return{fetchGateway:i,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}for(;$b(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&&!pn(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=nx(i.commands,t);if(a.push(e),o=o.slice(1),i=n,ex(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 Ob(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(!Ex.has(e[t+1]))throw new Mn({message:`Invalid format: "${e[t+1]}". Expected one of: ${[...Ex].join(`, `)}`});d=e[t+1],f=!0,t++}else if(b&&C===b){let n=e[t+1];if(n===void 0)throw new Mn({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 Mn({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 Mn({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 Mn({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 kb(e,t,n={}){if(n.configDisabled)return;let{loader:r}=n,i;i=n.configPath?Ab(n.configPath):await jb(n.files??[`${e}.json`]);let a;if(r){let e=await r(i);if(e===void 0)return;if(!un(e))throw new Mn({message:`Config loader must return a plain object or undefined`});a=e}else{if(!i)return;let e=await Mb(i,!!n.configPath);if(!e)return;a=e}return Nb(a,e,t)}function Ab(e){return e.startsWith(`~/`)||e===`~`?c.join(x.homedir(),e.slice(1)):c.resolve(process.cwd(),e)}async function jb(e){for(let t of e){let e=Ab(t);try{return await w.access(e,w.constants.R_OK),e}catch{}}}async function Mb(e,t){let n;try{n=await w.readFile(e,`utf8`)}catch(n){if(n.code===`ENOENT`){if(t)throw new Mn({message:`Config file not found: ${e}`});return}throw n}let r;try{r=JSON.parse(n)}catch(t){throw new Mn({message:`Invalid JSON config file: ${e}`,cause:t instanceof Error?t:void 0})}if(!un(r))throw new Mn({message:`Invalid config file: expected a top-level object in ${e}`});return r}function Nb(e,t,n){let r=n===t?[]:n.split(` `),i=e;for(let e of r){if(!un(i))return;let t=i.commands;if(!un(t)||(i=t[e],i===void 0))return}if(!un(i))throw new Mn({message:`Invalid config section for '${n}': expected an object`});let a=i.options;if(a!==void 0){if(!un(a))throw new Mn({message:`Invalid config 'options' for '${n}': expected an object`});return Object.keys(a).length>0?a:void 0}}function Pb(e){let t=[];for(let[n,r]of e)tx(r)||t.push({name:n,description:r.description});return t.sort((e,t)=>e.name.localeCompare(t.name))}function Fb(e,t,n){return iu(e[0])?.name===n?0:e[0]===t&&iu(e[1])?.name===n?1:-1}function Ib(e,t){return uu(`${e} ${t.name}`,{aliases:t.aliases,description:t.description,commands:t.subcommands?.map(e=>({name:e.name,description:e.description}))})}function Lb(e,t,n){let r=au(t,n);return du(`${e} ${t.name} ${n}`,{alias:r?.alias,aliases:r?.aliases,description:r?.description,hideGlobalOptions:!0,options:r?.options})}async function Rb(e,t,n){let r=[],i=[],a=new E,o=new E,s=[];o.on(`data`,e=>s.push(e.toString()));let c,l=q_(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(`${Wr({jsonrpc:`2.0`,id:1,method:`initialize`,params:{protocolVersion:`2024-11-05`,capabilities:{},clientInfo:{name:`incur-doctor`,version:`1.0.0`}}})}\n`),a.write(`${Wr({jsonrpc:`2.0`,id:2,method:`tools/list`,params:{}})}\n`),await zb(s,()=>u),a.end(),await l,c)return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_SERVER_FAILED`,message:Vb(c)}]};let d;try{d=Bb(s)}catch(e){return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_RESPONSE_PARSE_FAILED`,message:Vb(e)}]}}let f=d.find(e=>e.id===1);f?f.error&&i.push({code:`MCP_INITIALIZE_FAILED`,message:Hb(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:Hb(p.error)}):!un(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(un).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 zb(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 Bb(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(!un(r))throw Error(`Expected JSON-RPC response object.`);t.push(r)}return t}function Vb(e){return e instanceof Error?e.message:String(e)}function Hb(e){return un(e)&&typeof e.message==`string`?e.message:Wr(e)}function Ub(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
+ `)}async function Wb(e){if(e)return{directory:ee(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=c.resolve(t);try{let e=await w.realpath(n);return{directory:c.dirname(e),exclude:e}}catch(e){if(e.code!==`ENOENT`)throw e;return{directory:c.dirname(n),exclude:n}}}async function Gb(e){let t=await Ou(e.directory,{exclude:e.exclude});return Promise.all(t.map(async e=>({...e,command:(await import(D(e.file).href)).default})))}function Kb(e){return typeof e==`object`&&!!e&&e[Tx]===!0}function qb(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($b(c)&&!c.root)c.root=n,c.description??=n.description;else throw Jb(t,r);rx(t.join(` `),n,i);for(let e of n.aliases??[]){if(a.has(e))throw Jb([...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(tx(c)||ex(c))throw Jb(t,r);if($b(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 Jb(e,t){return Error(`Filesystem command '${e.join(` `)}' from '${t}' conflicts with an existing command or alias.`)}function Yb(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 Xb(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 Zb(e){return typeof e==`function`?e:e.fetch}function Qb(e){return typeof e==`function`?void 0:e.url}function $b(e){return`_group`in e}function ex(e){return`_fetch`in e}function tx(e){return`_alias`in e}function nx(e,t){return tx(t)?e.get(t.target):t}function rx(e,t,n){if(!(!n||ex(t)||tx(t))){if($b(t)){t.root&&rx(e,t.root,n);for(let[r,i]of t.commands)rx(`${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 ix(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 ax(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 ox(...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 sx(e){return Object.values(e.shape).some(e=>e._zod.optout!==`optional`)}function cx(e){return typeof e==`object`&&!!e&&Ix in e}async function lx(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(cx(i)){let e=i;if(e[Ix]===`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(ix({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}}n?t.writeln(Wr({type:`chunk`,data:i})):t.renderOutput&&t.writeln(t.truncate(Dl(i,t.format)).text)}if(cx(r)&&r[Ix]===`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(ix({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}let i=cx(r)&&r[Ix]===`ok`?wu(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(ax(i))}catch(e){n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e instanceof B?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof B?{retryable:e.retryable}:void 0}})):t.writeln(ix({code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)})),t.exit(e instanceof B?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(cx(i)){let e=i;if(e[Ix]===`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(cx(r)&&r[Ix]===`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=cx(r)&&r[Ix]===`ok`?wu(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 B?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof B?{retryable:e.retryable}:void 0},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e instanceof B?e.exitCode??1:1)}}}function ux(e,t=[],n,r){let i=dx(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:Iu(n)}:void 0}}function dx(e,t){let n=[];for(let[r,i]of e){if(tx(i))continue;let e=[...t,r];if($b(i)){if(i.root){let t={name:e.join(` `)};i.root.description&&(t.description=i.root.description),n.push(t)}n.push(...dx(i.commands,e))}else{let t={name:e.join(` `)};ex(i),i.description&&(t.description=i.description),n.push(t)}}return n}function fx(e,t=[],n,r){let i=px(e,t);return r&&t.length>0&&i.push(mx(t,r)),{version:`incur.v1`,commands:i.sort((e,t)=>e.name.localeCompare(t.name)),...n?{globals:Iu(n)}:void 0}}function px(e,t){let n=[];for(let[r,i]of e){if(tx(i))continue;let e=[...t,r];if(ex(i)){let t={name:e.join(` `)};i.description&&(t.description=i.description),n.push(t)}else $b(i)?(i.root&&n.push(mx(e,i.root)),n.push(...px(i.commands,e))):n.push(mx(e,i))}return n}function mx(e,t){let n={name:e.join(` `)};t.description&&(n.description=t.description);let r=xx(t.args,t.env,t.options),i=t.output?Iu(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=yx(t.examples);if(a){let t=e.join(` `);n.examples=a.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function hx(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),_x(r)&&(e.hint=vx(e.hint)),r.options&&(e.options=r.options),r.output&&(e.output=r.output);let t=yx(r.examples);t&&(e.examples=t),i.push(e)}for(let[r,a]of e){if(tx(a))continue;let e=[...t,r];if(ex(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 $b(a)?(a.description&&n.set(e.join(` `),a.description),a.root&&i.push(gx(e,a.root)),i.push(...hx(a.commands,e,n))):i.push(gx(e,a))}return i.sort((e,t)=>(e.name??``).localeCompare(t.name??``))}function gx(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),_x(t)&&(n.hint=vx(n.hint)),t.options&&(n.options=t.options),t.output&&(n.output=t.output);let r=yx(t.examples);if(r){let t=e.join(` `);n.examples=r.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function _x(e){return e.destructive===!0||e.mcp!==!1&&e.mcp?.annotations?.destructiveHint===!0}function vx(e){return e?e.includes(wx)?e:`${e} ${wx}`:wx}function yx(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 bx(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return{};let n=wl().parse(t[1]);return!n||typeof n!=`object`?{}:n}function xx(e,t,n){if(!e&&!t&&!n)return;let r={};return e&&(r.args=Iu(e)),t&&(r.env=Iu(t)),n&&(r.options=Iu(n)),r}function Sx(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 Cx(e,t){let n=process.argv[1];if(!n)return e;let r=c.basename(n);return r===e?e:t?.includes(r)?r:e}var wx,Tx,Ex,Dx,Ox,kx,Ax,jx,Mx,Nx,Px,Fx,Ix,Lx=z((()=>{ln(),Kt(),On(),Nn(),Vn(),Gn(),Fl(),Cu(),lu(),Du(),Fu(),mn(),Kr(),ut(),At(),El(),vv(),Dy(),py(),Ql(),Lu(),Ry(),Jy(),_b(),wx=`Confirm with the user before executing this destructive command.`,Tx=Symbol.for(`incur.fileCommand`),Ex=new Set([`toon`,`json`,`yaml`,`md`,`jsonl`]),Dx=new WeakMap,Ox=new WeakMap,kx=new WeakMap,Ax=new WeakMap,jx=new WeakMap,Mx=new WeakMap,Nx=new WeakMap,Px=new WeakMap,Fx=new WeakMap,Ix=Symbol.for(`incur.sentinel`)})),Rx=z((()=>{Kt(),Lx(),On(),Nn(),Fl(),Cu(),vv(),Vn(),py(),Ql(),Lu(),Ry(),El(),Jy(),_b()}));function zx(e,t){if(!(!e||typeof e!=`object`))return e[t]}var q,Bx,Vx,Hx,Ux,Wx,Gx=z((()=>{q={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Bx={payment:`Payment`},Vx={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Hx={charge:`charge`,session:`session`,subscription:`subscription`},Ux={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},Wx={v1:`v1`,v2:`v2`}}));function Kx(e,t){return t?`${e} Add funds at ${t}`:e}var qx,Jx,J,Yx,Xx,Zx,Qx,$x,eS,tS,nS,rS,iS,aS=z((()=>{qx=class extends Error{details;status=402;hint;fundingUrl;constructor(e,t={}){super(e),this.details=t.details,this.fundingUrl=t.fundingUrl,t.cause!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t.cause,writable:!0})}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},...this.fundingUrl&&{fundingUrl:this.fundingUrl},...e&&{challengeId:e}}}},Jx=class extends qx{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}.`)}},J=class extends qx{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,fundingUrl:n,reason:r}=e;super(Kx(r?`Payment verification failed: ${r}.`:`Payment verification failed.`,n),{details:t,fundingUrl:n})}},Yx=class extends qx{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.`)}},Xx=class extends qx{name=`PaymentOutcomeUnknownError`;title=`Payment Outcome Unknown`;type=`https://paymentauth.org/problems/payment-outcome-unknown`;challenge;credential;transactionHash;constructor(e){let{cause:t,challenge:n,credential:r,transactionHash:i}=e;super(`Payment outcome is unknown after sending a credential for challenge "${n.id}". Do not blindly retry.`,{cause:t}),this.challenge=n,this.credential=r,this.transactionHash=i}},Zx=class extends Error{name=`BroadcastOutcomeUnknownError`;transactionHash;validBefore;constructor(e){let{cause:t,transactionHash:n,validBefore:r}=e;super(`Broadcast outcome is unknown for transaction ${n}. Look up its receipt before retrying.`),this.transactionHash=n,this.validBefore=r,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},Qx=class extends Error{name=`LegacyUnicodeEscapedChallengeError`;constructor(){super(`Legacy unicode-escaped challenge: the server escaped a bound parameter as \\uXXXX; upgrade the server.`)}},$x=class extends Error{name=`ConfigurableVouchersUnsupportedError`;signer;constructor(e){let{signer:t}=e;super(`Configurable account ${t} signs vouchers with TIP-1166 configurable account signatures, but the session challenge does not advertise \`configurableVouchers\`, so the channel was not opened.`),this.signer=t}},eS=class extends Error{name=`SignerConfigChangedError`;channelId;reason;signer;constructor(e){let{cause:t,channelId:n,reason:r,signer:i}=e;super(`Signer ${i} of channel ${n} changed its account config since the channel opened, so the top-up was not signed. Close the channel and open a new one.`),this.channelId=n,this.reason=r,this.signer=i,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},tS=class extends Error{name=`SpendingLimitExceededError`;accessKey;account;constructor(e){let{accessKey:t,account:n,cause:r}=e;super(`Access key spending limit exceeded: ${t?`key ${t} of `:``}account ${n} cannot pay this amount, so the payment was not signed.`),this.accessKey=t,this.account=n,r!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:r,writable:!0})}},nS=class extends Error{name=`ZoneSettlementPendingError`;challengeId;senderTag;senderTags;zoneId;constructor(e){let{cause:t,challengeId:n,zoneId:r}=e,i=e.senderTags??(e.senderTag?[e.senderTag]:[]),a=i.length===1?i[0]:void 0,o=a??(i.length?`with sender tag ${i.join(` or `)}`:void 0);super(`Zone ${r} withdrawal ${o?`${o} `:``}for challenge "${n}" has not settled on Tempo yet. Retry the challenge to resume waiting instead of paying again.`),this.challengeId=n,this.senderTag=a,this.senderTags=i,this.zoneId=r,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},rS=class extends Error{name=`PaymentLimitExceededError`;limit;reason;constructor(e){let{limit:t,reason:n}=e,r=t===`budget`?`the remaining budget`:`maxPayment`;super(n===`amount`?`Payment exceeds ${r}, so no credential was created.`:n===`credential`?`Credential cannot be checked against ${r}: it is unreadable or pays no single challenge the response offered, so it was not used.`:n===`intent`?`Payment intent cannot be checked against ${r}: spending options accept only charges, so no credential was created.`:`Payment asset cannot be checked against ${r}: no limit names it, or the client does not configure its currency and decimals. No credential was created.`),this.limit=t,this.reason=n}},iS=class extends qx{name=`InsufficientBalanceError`;title=`Insufficient Balance`;status=402;type=`https://paymentauth.org/problems/session/insufficient-balance`;constructor(e={}){let{cause:t,fundingUrl:n,reason:r}=e;super(Kx(r?`Insufficient balance: ${r}.`:`Insufficient balance.`,n),{cause:t,fundingUrl:n})}}}));function oS(e){let t=te.toString(e);return JSON.parse(t)}function sS(e,t){return e.schema.request.parse(t)}function cS(e){let t=ne.canonicalize(e);return te.fromString(t,{pad:!1,url:!0})}var lS=z((()=>{})),Y=it({address:()=>gS,amount:()=>dS,datetime:()=>fS,datetimeInput:()=>pS,hash:()=>_S,period:()=>vS,signature:()=>yS,toDate:()=>mS,toDatetimeString:()=>hS,unwrapOptional:()=>bS});import*as uS from"zod/mini";ot(Y,uS);function dS(){return be.string().check(be.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function fS(){return be.string().check(be.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 pS(e=`Invalid ISO 8601 datetime`){return be.pipe(be.union([fS(),be.custom(e=>e instanceof Date)]),be.transform(mS)).check(be.refine(e=>Number.isFinite(e.getTime()),e))}function mS(e){return e instanceof Date?e:new Date(e)}function hS(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function gS(){return be.string().check(be.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function _S(){return be.string().check(be.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function vS(){return be.string().check(be.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function yS(){return be.string().check(be.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function bS(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}var xS=z((()=>{}));function SS(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=JS(o),f=e.expires?hS(e.expires):void 0,p=e.opaque??(i===void 0?void 0:cS(i)),m=u?XS({...e,expires:f,header:d,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return nC.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 CS(e){OS(e);let{method:t}=e;wS(t);let n=[TS(`id`,e.id),TS(`realm`,e.realm),TS(`method`,t),TS(`intent`,e.intent),TS(`request`,cS(e.request))];e.description!==void 0&&n.push(TS(`description`,e.description,{escapeUnicode:!0})),e.digest!==void 0&&n.push(TS(`digest`,e.digest)),e.expires!==void 0&&n.push(TS(`expires`,e.expires));let r=YS(e.header);return r!==void 0&&n.push(TS(`header`,r)),e.opaque===void 0?e.meta!==void 0&&n.push(TS(`opaque`,cS(e.meta))):n.push(TS(`opaque`,e.opaque)),`${Bx.payment} ${n.join(`, `)}`}function wS(e){if(!iC.test(e))throw new aC(e)}function TS(e,t,n={}){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);let r=t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);if(!/[\u0100-\uffff]/.test(r))return`${e}="${r}"`;if(n.escapeUnicode)return`${e}="${r.replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`;throw Error(`Invalid ${e}: characters above U+00FF cannot be sent in a header.`)}function ES(e,t){let n=kS(e);if(!n)throw Error(`Missing Payment scheme.`);let r=new Set,{request:i,opaque:a,header:o,...s}=AS(n,r);if(!i)throw Error(`Missing request parameter.`);if(i.length>ZS)throw Error(`Request parameter too large.`);if(s.method!==void 0&&wS(s.method),o!==void 0&&!qS(o))throw new tC;let c=SS({...s,request:oS(i),...a&&{opaque:a}},t),l=o===void 0?c:{...c,header:o};return[...r].some(e=>$S.has(e))&&(l[QS]=!0),l}function DS(e){return!!(e&&typeof e==`object`&&e[QS])}function OS(e){if(DS(e))throw new Qx}function kS(e){let t=Bx.payment,[n]=FS(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 AS(e,t){let n=Object.create(null),r=0;for(;r<e.length;){for(;r<e.length&&/[\s,]/.test(e[r]??``);)r++;if(r>=e.length)break;let i=r;for(;r<e.length&&/[A-Za-z0-9_-]/.test(e[r]??``);)r++;let a=e.slice(i,r).toLowerCase();if(!a)throw Error(`Malformed auth-param.`);for(;r<e.length&&/\s/.test(e[r]??``);)r++;if(e[r]!==`=`)break;for(r++;r<e.length&&/\s/.test(e[r]??``);)r++;let[o,s,c]=jS(e,r);for(r=s,c&&t?.add(a);r<e.length&&/\s/.test(e[r]??``);)r++;if(r<e.length&&e[r]!==`,`)throw Error(`Malformed auth-param.`);if(a in n)throw Error(`Duplicate parameter: ${a}`);n[a]=o}return n}function jS(e,t){if(e[t]===`"`)return MS(e,t+1);let n=t;for(;n<e.length&&oC.test(e[n]??``);)n++;if(n===t)throw Error(`Malformed auth-param.`);return[e.slice(t,n),n]}function MS(e,t){let n=t,r=!1,i=!1,a=t,o;for(;n<e.length;){let s=e[n];if(n++,r){s===`u`&&/^[0-9a-fA-F]{4}/.test(e.slice(n,n+4))&&(i=!0),o??=[],o.push(s),a=n,r=!1;continue}if(s===`\\`){o??=[],o.push(e.slice(a,n-1)),a=n,r=!0;continue}if(s===`"`)return[o?[...o,e.slice(a,n-1)].join(``):e.slice(t,n-1),n,i]}throw Error(`Unterminated quoted-string.`)}function NS(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 PS(e){return FS(e,Bx.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===Bx.payment.toLowerCase())}function FS(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(!NS(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 IS(e,t){let n=e.get(q.wwwAuthenticate);if(!n)throw Error(`Missing ${q.wwwAuthenticate} header.`);return ES(n,t)}function LS(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return IS(e.headers,t)}function RS(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return zS(e.headers,t)}function zS(e,t){let n=e.get(q.wwwAuthenticate);if(!n)throw Error(`Missing ${q.wwwAuthenticate} header.`);return BS(n,t)}function BS(e,t){let n=US(e);if(n.length===0)throw Error(`No Payment schemes found.`);return n.flatMap(e=>{try{return[ES(e,t)]}catch(e){if(e instanceof tC||e instanceof aC)return[];throw e}})}function VS(e){return e?US(e).filter(e=>{try{return ES(e),!1}catch(e){return e instanceof tC}}).length:0}function HS(e,t){return t<=0?e:t===1?`${e}. Skipped 1 challenge that selects a credential header other than Payment-Authorization`:`${e}. Skipped ${t} challenges that select a credential header other than Payment-Authorization`}function US(e){let t=FS(e,Bx.payment);return t.map((n,r)=>{let i=r+1<t.length?t[r+1]:e.length;return e.slice(n,i).replace(/,\s*$/,``)})}function WS(e){let t=[e.realm,e.method,e.intent,cS(e.request),e.expires??``,e.digest??``],n=YS(e.header);return n!==void 0&&t.push(n),t.push(e.opaque??(e.meta?cS(e.meta):``)),t.join(`|`)}function GS(e){let{header:t}=e;return t===void 0?q.authorization:qS(t)?q.paymentAuthorization:t}function KS(e){if(typeof e!=`object`||!e||!(`header`in e))return!1;let{header:t}=e;return t!==void 0&&!(typeof t==`string`&&qS(t))}function qS(e){return/^payment-authorization$/i.test(e)}function JS(e){return YS(e)===void 0?void 0:q.paymentAuthorization}function YS(e){if(e!==void 0&&!/^authorization$/i.test(e)){if(qS(e))return e;throw new tC}}function XS(e,t){let n=WS(e),r=A.fromString(t.secretKey),i=A.fromString(n),a=j.hmac256(r,i,{as:`Bytes`});return te.fromBytes(a,{url:!0,pad:!1})}var ZS,QS,$S,eC,tC,nC,rC,iC,aC,oC,sC=z((()=>{Gx(),aS(),lS(),xS(),ZS=16384,QS=Symbol(`mppx.Challenge.legacyUnicodeEscape`),$S=new Set([`digest`,`expires`,`header`,`intent`,`method`,`opaque`,`realm`,`request`]),eC=`Unsupported credential header: challenges may only select Payment-Authorization.`,tC=class extends Error{name=`UnsupportedCredentialHeaderError`;constructor(){super(eC)}},nC=Y.object({description:Y.optional(Y.string()),digest:Y.optional(Y.string().check(Y.regex(/^sha-256=/,`Invalid digest format`))),expires:Y.optional(fS()),header:Y.optional(Y.string().check(Y.refine(qS,eC))),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())}),rC=Y.extend(nC,{header:Y.optional(Y.string())}),iC=/^[a-z]+$/,aC=class extends Error{name=`InvalidMethodError`;constructor(e){super(`Invalid method: "${e}". Must be lowercase letters a-z per spec.`)}},oC=/[!#$%&'*+\-.^_`|~0-9A-Za-z]/}));function cC(e){if(e.length>hC)throw new _C;let t=e.match(RegExp(`^${Bx.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new gC;try{let e=te.toString(t[1]),n=JSON.parse(e);if(!uC(n.payload))throw Error(`Invalid payload.`);if(n.source!==void 0&&typeof n.source!=`string`)throw Error(`Invalid source.`);let{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=lC(r);return{challenge:nC.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:oS(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new _C}}function lC(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!dC(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:cS(e)}}function uC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function dC(e){return uC(e)?Object.values(e).every(e=>typeof e==`string`):!1}function fC(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function pC(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:cS(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:cS(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=te.fromString(s,{pad:!1,url:!0});return`${Bx.payment} ${c}`}function mC(e){return e.length>hC?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${Bx.payment}\\s+`,`i`).test(e))??null}var hC,gC,_C,vC=z((()=>{sC(),Gx(),lS(),hC=65536,gC=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},_C=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}}}));function yC(e,t){if(!e)throw new Jx({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new Jx({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new Yx({expires:e})}var bC=z((()=>{aS()}));function xC(e){if(!e)return[];let t;try{t=Ce(e)}catch{return[]}let n=[];for(let e of t){if(Se(e)||!(e[0]instanceof xe))continue;let t=e[1].get(`issuer`);n.push(Object.freeze({type:e[0].toString(),...typeof t==`string`&&{issuer:t}}))}return Object.freeze(n)}var SC,CC=z((()=>{SC=`Identity-Required`,Object.freeze([`identity-attestation-required`])}));function wC(){let e=new Uint8Array(64);return crypto.getRandomValues(e),{created:Math.floor(Date.now()/1e3),nonce:te.fromBytes(e,{pad:!1,url:!0})}}var TC=z((()=>{}));function EC(e,t){switch(t.type){case`send`:if(e.phase!==`unproved`)break;return Object.freeze({phase:t.payment===`paid`?`paid`:`sent`});case`response`:if(t.resend===void 0){if(e.phase===`unproved`||e.phase===`done`)break;return Object.freeze({phase:`done`})}if(e.phase!==`sent`&&e.phase!==`paid`)break;return Object.freeze({phase:`resent`,headers:t.resend})}let n=t.type===`response`&&t.resend!==void 0?` with resend`:``;throw TypeError(`Illegal identity attempt transition "${t.type}${n}" from phase "${e.phase}".`)}function DC(e){if(e.length===0)throw TypeError(`Mppx client identity must configure at least one prover.`);for(let t of e)if(t.scope!==`*`&&!Array.isArray(t.scope))throw TypeError(`Identity prover scope must be "*" or an array of origins.`);let t=Object.freeze([...new Set(e.flatMap(e=>{if(e.headers!==void 0&&!Array.isArray(e.headers))throw TypeError(`Identity prover headers must be an array of header names.`);return(e.headers??[]).map(e=>e.toLowerCase())}))]),n=t=>{let n=new URL(t).origin;return e.filter(e=>e.scope===`*`||e.scope.includes(n))};async function r(e){let{context:t,fetch:r,headers:i,keepReadable:a,proceed:o,request:s}=e,c=a?s.clone():s,l=n(s.url);if(l.length===0){if(o&&!o()){NC(c);return}return{request:c,response:await r(c)}}let u=Object.freeze({...wC(),...t.challenge&&{challenge:t.challenge}}),d=new Headers(c.headers),f=new Set(HC);t.challenge&&f.add(GS(t.challenge).toLowerCase());for(let[e,t]of c.headers)mC(t)!==null&&f.add(e.toLowerCase());for(let[e,t]of i)f.has(e.toLowerCase())||d.set(e,t);let p=new Request(c,{headers:d,redirect:s.redirect===`follow`?`error`:s.redirect});try{for(let e of l)p=await e.prove(p,u)}catch(e){throw NC(p),e}if(o&&!o()){NC(p);return}return{request:p,response:await r(p)}}return{headers:t,async send(e,t,i={}){let a=EC(UC,{type:`send`,payment:jC(t,i)?`paid`:`unpaid`}),o=n(t.url).filter(e=>e.retry),s=a.phase===`paid`?AC(t,i):void 0,c=o.length>0&&(a.phase===`sent`||s!==void 0&&kC(s)),l=i.headers??[],u=await r({context:i,fetch:e,headers:l,keepReadable:c,request:t}),{response:d}=u,f;if(c&&OC(a,d,s))try{f=await MC(o,d,u.request)}catch(e){if(a.phase!==`paid`)throw NC(t),e}if(a=EC(a,{type:`response`,resend:f}),a.phase!==`resent`)return c&&NC(t),{...u,headers:l};let p=s?await PC(d):(FC([d]),void 0),m=()=>(NC(t),{request:u.request,response:p,headers:l}),h=zC(l,a.headers),g=!1,_;try{_=await r({context:i,fetch:e,headers:h,keepReadable:!1,proceed(){return s&&!kC(s)?!1:(g=!0,!0)},request:t})}catch(e){if(p&&!g)return m();throw e}return EC(a,{type:`response`,resend:void 0}),_?{..._,headers:h}:m()},async challenge(e,{challenge:t},r){let i=Object.freeze({challenge:t,requirements:xC(e.headers.get(SC))});for(let t of n(r)){if(!t.prepare)continue;let n=e.clone();try{await t.prepare(n,i)}finally{FC([n])}}}}}function OC(e,t,n){return e.phase===`sent`?t.status>=400&&t.status!==402:e.phase!==`paid`||t.status!==401||!n||WC.some(e=>t.headers.has(e))?!1:kC(n)}function kC(e){return e.expires!==void 0&&Date.parse(e.expires)>Date.now()}function AC(e,t){if(VC.some(t=>e.headers.has(t)))return;let n=t.challenge??LC(e.headers);if(n)for(let[,t]of e.headers){let e=mC(t);if(e)try{if(cC(e).challenge.id===n.id)return n}catch{}}}function jC(e,t){return t.challenge!==void 0||VC.some(t=>e.headers.has(t))||[...e.headers.values()].some(e=>mC(e)!==null)}async function MC(e,t,n){let r=Object.freeze({request:n}),i=[],a=!1,o=new Headers;try{for(let n of e){let e=t.clone();i.push(e);let s=await n.retry(e,r);if(s===!0)a=!0;else if(typeof s==`object`&&s){a=!0;for(let[e,t]of new Headers(s))HC.has(e)||o.append(e,t)}}}finally{FC(i)}if(a)return Object.freeze([...o].map(([e,t])=>Object.freeze([e,t])))}function NC(e){e.body&&!e.bodyUsed&&!e.body.locked&&e.body.cancel().catch(()=>{})}async function PC(e){let t=new Headers(e.headers),n={headers:t,status:e.status,statusText:e.statusText};if(!e.body)return new Response(null,n);let r=e.body.getReader(),i=[],a=0,o=!1,s=setTimeout(()=>{o=!0,r.cancel().catch(()=>{})},KC);try{for(;;){let{done:e,value:t}=await r.read();if(e)break;if(i.push(t),a+=t.byteLength,a>GC){o=!0;break}}}catch{o=!0}finally{clearTimeout(s),r.cancel().catch(()=>{})}return o&&(t.delete(`content-length`),t.set(`Mppx-Body-Truncated`,`true`)),new Response(new Blob(i).slice(0,GC),n)}function FC(e){for(let t of e)t.bodyUsed||t.body?.cancel().catch(()=>{})}function IC(e,t,n={}){return async(r,i)=>{let a=new Request(r,i),o=LC(a.headers)??n.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[BC]?{[BC]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of RC(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{challenge:e},a.url);return s}}function LC(e){for(let[,t]of e){let e=mC(t);if(e)try{return cC(e).challenge}catch{}}}function RC(e){try{return RS(e)}catch{return[]}}function zC(e,t){let n=new Headers;for(let[t,r]of e)n.set(t,r);for(let[e,r]of t)n.set(e,r);return Object.freeze([...n].map(e=>Object.freeze(e)))}var BC,VC,HC,UC,WC,GC,KC,qC=z((()=>{sC(),vC(),CC(),TC(),BC=Symbol.for(`mppx.fetch.skipPayment`),VC=[`payment-signature`,`x-payment`],HC=new Set([`authorization`,`payment-authorization`,...VC]),UC=Object.freeze({phase:`unproved`}),WC=[`payment-receipt`,`payment-response`,`x-payment-response`],GC=65536,KC=2e3}));function JC(e){return Object.defineProperty(e,XC,{value:!0}),e}function YC(e){return!!e?.[XC]}var XC,ZC=z((()=>{XC=Symbol.for(`mppx.x402.challenge`)}));function QC(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=iw(n)}return t}function $C(e,t){let n=QC(e),r=dw(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[iw(e)]??1,index:t}));return{definition:r,entries:i,header:tw(i),keys:n}}function ew(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)=>lw(e,t))}function tw(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${hw(n)}`}).join(`, `)}function nw(e,t,n){let r=rw(e,t,n)[0];if(r)return{challenge:r.challenge,method:r.method}}function rw(e,t,n,r){let i=new Map;for(let e of t){let t=iw(e),n=i.get(t);n?n.push(e):i.set(t,[e])}let a=e.flatMap((e,t)=>{let a=i.get(iw(e));if(!a)return[];let o=aw(e,n);return!o||o.q<=0?[]:a.filter(t=>t.canHandleChallenge?.(r===void 0?{challenge:e}:{challenge:e,context:r})??!0).map(n=>({challenge:e,index:t,match:o,method:n}))}).sort((e,t)=>cw(e.challenge)-cw(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n}),o=a.filter(({challenge:e})=>!DS(e));return o.length===0&&a[0]&&OS(a[0].challenge),o}function iw(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function aw(e,t){let n;for(let r of t){if(!ow(e,r))continue;let t={...r,specificity:sw(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 ow(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function sw(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function cw(e){return+!!YC(e)}function lw(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}`);gw(r,`method`),gw(i,`intent`);let a=1;for(let t of uw(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=pw(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function uw(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function dw(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>iw(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]=fw(t,`payment preference "${e}"`)}return a}function fw(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return mw(e,t)}function pw(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 mw(Number(e),t)}function mw(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 hw(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function gw(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}var _w,vw=z((()=>{sC(),ZC(),_w=Symbol(`mppx.deferredContext`)}));function yw(e){let{extensions:t,resource:n,...r}=e;return Nw.parse(r)}var bw,xw,Sw,Cw,ww,Tw,Ew,Dw,Ow,kw,Aw,jw,Mw,Nw,Pw,Fw,Iw,Lw,Rw,zw,Bw,Vw,Hw,Uw=z((()=>{xS(),bw=`charge`,xw=[`exact`],Sw=`eip155:`,Cw=`x402:`,ww=`PAYMENT-REQUIRED`,Tw=`PAYMENT-SIGNATURE`,Ew=`PAYMENT-RESPONSE`,Dw=Y.string().check(Y.minLength(1)),Ow=Y.number().check(Y.refine(e=>e>0,`Must be positive`)),kw=Y.string().check(Y.regex(/^\d+$/,`Invalid atomic amount`)),Aw=gS(),jw=Y.string().check(Y.regex(RegExp(`^${Sw}\\d+$`),`Invalid EVM CAIP-2 network`)),Mw=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:Dw}),Y.discriminatedUnion(`type`,[Y.object({name:Dw,type:Y.literal(`eip3009`),version:Dw}),Y.object({name:Y.optional(Y.string()),type:Y.literal(`permit2`),version:Y.optional(Y.string())})]),Nw=Y.object({amount:kw,asset:Dw,extra:Y.optional(Y.record(Y.string(),Y.unknown())),maxTimeoutSeconds:Ow,network:jw,payTo:Dw,scheme:Y.enum(xw)}),Pw=Y.looseObject({info:Y.record(Y.string(),Y.unknown()),schema:Y.record(Y.string(),Y.unknown())}),Fw=Y.record(Y.string(),Pw),Iw=Y.object({accepts:Y.array(Nw).check(Y.minLength(1)),error:Y.optional(Y.string()),extensions:Y.optional(Fw),resource:Mw,x402Version:Y.literal(2)}),Lw=Y.object({authorization:Y.object({from:Aw,nonce:_S(),to:Aw,validAfter:kw,validBefore:kw,value:kw}),signature:yS()}),Rw=Y.object({permit2Authorization:Y.object({deadline:kw,from:Aw,nonce:kw,permitted:Y.object({amount:kw,token:Aw}),spender:Aw,witness:Y.object({to:Aw,validAfter:kw})}),signature:yS()}),zw=Y.union([Lw,Rw]),Bw=Y.object({accepted:Nw,extensions:Y.optional(Fw),payload:zw,resource:Y.optional(Mw),x402Version:Y.literal(2)}),Y.object({extensions:Y.optional(Y.record(Y.string(),Y.unknown())),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())}),Vw=Y.object({amount:Y.optional(kw),errorMessage:Y.optional(Y.string()),errorReason:Y.optional(Y.string()),extensions:Y.optional(Y.record(Y.string(),Y.unknown())),extra:Y.optional(Y.record(Y.string(),Y.unknown())),network:Dw,payer:Y.optional(Y.string()),success:Y.boolean(),transaction:Y.string()}),Hw=Y.object({extra:Y.optional(Y.record(Y.string(),Y.unknown())),network:Dw,scheme:Dw,x402Version:Y.number()}),Y.object({extensions:Y.optional(Y.array(Y.string())),kinds:Y.array(Hw),signers:Y.optional(Y.record(Y.string(),Y.array(Y.string())))})}));function Ww(e){let t=te.toString(e);return Gw(JSON.parse(t))}function Gw(e){return qw.parse(e)}var Kw,qw,Jw=z((()=>{xS(),Kw={extensions:Y.optional(Y.record(Y.string(),Y.unknown())),fundingCurrency:Y.optional(Y.string()),method:Y.string(),reference:Y.string(),externalId:Y.optional(Y.string()),subscriptionId:Y.optional(Y.string()),status:Y.literal(`success`),timestamp:fS()},Y.object(Kw),qw=Y.looseObject(Kw)}));function Yw(e){let t=e.headers.get(q.paymentReceipt);if(t!==null){if(t.length>Zw)return;try{let e=Ww(t);return Xw(`mpp`,e.reference,e)}catch{return}}let n=e.headers.get(Ew);if(!(n===null||n.length>Zw))try{let e=atob(n.trim().replace(/-/g,`+`).replace(/_/g,`/`)),t=Uint8Array.from(e,e=>e.charCodeAt(0)),r=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(t)),i=Vw.safeParse(r);return!i.success||!i.data.success?void 0:Xw(`x402`,i.data.transaction,r)}catch{return}}function Xw(e,t,n){return Object.freeze({protocol:e,...t?{reference:t}:{},.../^0x[\da-fA-F]{64}$/.test(t)?{transactionHash:t}:{},raw:Object.freeze({...n})})}var Zw,Qw=z((()=>{Gx(),Uw(),Jw(),Zw=8192})),$w,eT,tT=z((()=>{$w=`org.paymentauth/credential`,eT=`org.paymentauth/payment-required`}));function nT(e){let t=``,n=!1,r=!1,i,a=``;function o(t){if(t===``){i!==void 0&&e({data:i,event:a||`message`}),i=void 0,a=``;return}let n=t.indexOf(`:`);if(n===0)return;let r=n===-1?t:t.slice(0,n);if(r!==`data`&&r!==`event`)return;let o=``;n!==-1&&(o=t.slice(t.charCodeAt(n+1)===32?n+2:n+1)),r===`event`?a=o:i=i===void 0?o:i+`
224
224
  `+o}return{feed(e){if(!n&&e&&(n=!0,e.startsWith(``)&&(e=e.slice(1))),r&&e&&(r=!1,e.startsWith(`
225
225
  `)&&(e=e.slice(1))),t+=e,e.indexOf(`
226
226
  `)===-1&&e.indexOf(`\r`)===-1)return;let i=0,a=t.indexOf(`
227
227
  `),s=t.indexOf(`\r`);for(;a!==-1||s!==-1;){let e=a===-1?s:s===-1?a:Math.min(a,s);o(t.slice(i,e)),i=e+1,e===s&&(i===t.length?r=!0:a===i&&i++,s=t.indexOf(`\r`,i)),a!==-1&&a<i&&(a=t.indexOf(`
228
- `,i))}t=t.slice(i)}}}var dw=R((()=>{}));function fw(e){let{extensions:t,resource:n,...r}=e;return Ew.parse(r)}var pw,mw,hw,gw,_w,vw,yw,bw,xw,Sw,Cw,ww,Tw,Ew,Dw,Ow,kw,Aw,jw,Mw,Nw,Pw,Fw,Iw=R((()=>{yS(),pw=`charge`,mw=[`exact`],hw=`eip155:`,gw=`x402:`,_w=`PAYMENT-REQUIRED`,vw=`PAYMENT-SIGNATURE`,yw=`PAYMENT-RESPONSE`,bw=Y.string().check(Y.minLength(1)),xw=Y.number().check(Y.refine(e=>e>0,`Must be positive`)),Sw=Y.string().check(Y.regex(/^\d+$/,`Invalid atomic amount`)),Cw=mS(),ww=Y.string().check(Y.regex(RegExp(`^${hw}\\d+$`),`Invalid EVM CAIP-2 network`)),Tw=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:bw}),Y.discriminatedUnion(`type`,[Y.object({name:bw,type:Y.literal(`eip3009`),version:bw}),Y.object({name:Y.optional(Y.string()),type:Y.literal(`permit2`),version:Y.optional(Y.string())})]),Ew=Y.object({amount:Sw,asset:bw,extra:Y.optional(Y.record(Y.string(),Y.unknown())),maxTimeoutSeconds:xw,network:ww,payTo:bw,scheme:Y.enum(mw)}),Dw=Y.looseObject({info:Y.record(Y.string(),Y.unknown()),schema:Y.record(Y.string(),Y.unknown())}),Ow=Y.record(Y.string(),Dw),kw=Y.object({accepts:Y.array(Ew).check(Y.minLength(1)),error:Y.optional(Y.string()),extensions:Y.optional(Ow),resource:Tw,x402Version:Y.literal(2)}),Aw=Y.object({authorization:Y.object({from:Cw,nonce:hS(),to:Cw,validAfter:Sw,validBefore:Sw,value:Sw}),signature:_S()}),jw=Y.object({permit2Authorization:Y.object({deadline:Sw,from:Cw,nonce:Sw,permitted:Y.object({amount:Sw,token:Cw}),spender:Cw,witness:Y.object({to:Cw,validAfter:Sw})}),signature:_S()}),Mw=Y.union([Aw,jw]),Nw=Y.object({accepted:Ew,extensions:Y.optional(Ow),payload:Mw,resource:Y.optional(Tw),x402Version:Y.literal(2)}),Y.object({extensions:Y.optional(Y.record(Y.string(),Y.unknown())),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())}),Pw=Y.object({amount:Y.optional(Sw),errorMessage:Y.optional(Y.string()),errorReason:Y.optional(Y.string()),extensions:Y.optional(Y.record(Y.string(),Y.unknown())),extra:Y.optional(Y.record(Y.string(),Y.unknown())),network:bw,payer:Y.optional(Y.string()),success:Y.boolean(),transaction:Y.string()}),Fw=Y.object({extra:Y.optional(Y.record(Y.string(),Y.unknown())),network:bw,scheme:bw,x402Version:Y.number()}),Y.object({extensions:Y.optional(Y.array(Y.string())),kinds:Y.array(Fw),signers:Y.optional(Y.record(Y.string(),Y.array(Y.string())))})}));function Lw(e,t,n){let r=new Headers(e.headers);for(let e of Rw)e===q.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}var Rw,zw=R((()=>{Gx(),Iw(),Rw=[q.authorization,_w,yw,vw]}));function Bw(e){if(typeof e==`string`)try{let t=JSON.parse(e),n=t?.id;return t?.jsonrpc!==`2.0`||typeof t?.method!=`string`?void 0:typeof n==`string`||typeof n==`number`?n:void 0}catch{return}}function Vw(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t?.method===`tools/call`&&t.params?._meta?.[`mppx/payment-client`]===!0}catch{return!1}}function Hw(e){let t=Bw(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 Uw(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 Ww(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){if(!tC.safeParse(e).success)return;if(WS(e))continue;let t=eC.safeParse(e);if(!t.success)return;n.push(t.data)}if(n.length===0)return;let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function Gw(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:Ww(e.error.data):Ww(e.result?._meta?.[cw])}function Kw(e,t){return!e||e.id!==t?[]:Gw(e)?.challenges??[]}async function qw(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=uw(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=Uw(JSON.parse(e.data))}catch{}});try{for(;;){if(i)return a;let{done:e,value:s}=await t.read();if(e)return o.feed(n.decode()),a;if(r+=s.byteLength,r>Zw)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function Jw(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=``;try{for(;;){let{done:e,value:a}=await t.read();if(e)return Uw(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>Zw)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function Yw(e){let t=Qw.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>Zw)){if(t.includes(`application/json`))return Jw(e);if(t.includes(`text/event-stream`))return qw(e)}})();return Qw.set(e,n),n}function Xw(){return{getChallenges(e,t){let n=Hw(t);return e.status===402||n===void 0?[]:Yw(e).then(e=>Kw(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=aC(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,[sw]:r}}})}}}}var Zw,Qw,$w=R((()=>{iC(),mC(),dw(),lw(),zw(),Zw=1048576,Qw=new WeakMap}));function eT(){return{getChallenges(e){let t=e.headers.get(q.wwwAuthenticate);return e.status!==402||!t||!MS(t)?[]:IS(e)},setCredential(e,t,n){return Lw(e,n?.challenge?US(n.challenge):q.authorization,t)}}}var tT=R((()=>{iC(),Gx(),zw()}));function nT(e){return{encode(t){return k.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(k.toString(t)))}catch{throw new rT}}}}var rT,iT=R((()=>{rT=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}}}));function aT(e){try{let t=JSON.parse(k.toString(e));return dT(t)}catch{throw new rT}}var oT,sT,cT,lT,uT,dT,fT=R((()=>{iT(),Iw(),oT=nT(kw),sT=nT(Nw),cT=nT(Pw),lT=oT.encode,oT.decode,uT=sT.encode,sT.decode,cT.encode,cT.decode,dT=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new rT;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new rT;let n=Tw.parse(t.resource),r=t.extensions===void 0?void 0:Ow.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}}}));function pT(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(_w);if(!t)return[];let n=aT(t);return n.accepts.flatMap((e,t)=>{let r=Ew.safeParse(e);if(!r.success)return[];let i=r.data;return IC(bS({id:`${gw}${t}`,intent:pw,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return Lw(e,vw,t)}}}var mT=R((()=>{iC(),zC(),fT(),Iw(),zw()}));function hT(e){return e}function gT(){let e=[eT(),pT(),Xw()],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 hT({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 _T=R((()=>{$w(),tT(),zw(),mT()}));function vT(e,t){return ST.set(e,t),e}function yT(e){return ST.has(e)}function bT(e,t){return Promise.resolve(ST.get(e)?.(t))}function xT(e){return ST.get(e)}var ST,CT=R((()=>{ST=new WeakMap}));function wT(e,t){return NT.set(e,t),e}function TT(e){NT.delete(e)}function ET(e,t,n){NT.has(e)&&PT.set(t,n)}function DT(e){return PT.get(e)}function OT(e,t){return Promise.resolve(NT.get(e)?.(t)??t.response)}function kT(e,t){return IT.set(e,t),e}function AT(e,t){try{return IT.get(e)?.(t)}catch{return}}function jT(e,t){FT.set(e,t)}function MT(e){return FT.get(e)??PT.get(e)?.origin}var NT,PT,FT,IT,LT=R((()=>{NT=new WeakMap,PT=new WeakMap,FT=new WeakMap,IT=new WeakMap}));async function RT(e,t){let{attempts:n,signal:r}=t;for(let t=1;;t++){r?.throwIfAborted();try{return await e()}catch(e){if(!(e instanceof tS)||t>=n)throw e;r?.throwIfAborted()}}}var zT=R((()=>{rS()}));function BT(e,t,n){if(!HT(e)&&(e.method!==`tempo`||e.intent!==`session`))return;t=typeof t==`function`?t():t;let{realm:r}=e;if(r.toLowerCase()===t.hostname.toLowerCase())return;let i=t.origin.toLowerCase();for(let[e,t]of Object.entries(n??{}))if(t===r&&UT(e)===i)return;throw Error(`Refusing to sign Tempo proof for realm ${JSON.stringify(r)} from ${t.origin}. Pin the realm to this origin with \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function VT(e,t){if(!(!HT(e)&&(e.method!==`tempo`||e.intent!==`session`))&&!t?.includes(e.realm))throw Error(`Refusing to sign Tempo proof for untrusted realm ${JSON.stringify(e.realm)}. Add it to \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function HT(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function UT(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}var WT=R((()=>{}));function GT(e={}){return{...e,[RE]:!0}}async function KT(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},VE);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>BE){i=!0;break}}}finally{clearTimeout(a),t.cancel().catch(()=>{})}if(!i)return e;e.body.cancel().catch(()=>{});let o=new Headers(e.headers);o.delete(`content-length`),o.set(HE,`true`);let s=new Response(new Blob(n).slice(0,BE),{headers:o,status:e.status,statusText:e.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{value:e[t]});return s}async function qT(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 JT(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=zE,methods:a,onChallenge:o,orderChallenges:s,transport:c=gT(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&vE(e.fetch)),d=e.eventDispatcher??ZT(),f=t??VC(a),p=yE(r),m=async(e,t,n)=>u?u.send((e,n)=>p(e,t?.[RE]?GT(n):n),new Request(e,t),n):{response:await p(e,t),headers:[]},h=async(e,t,r)=>{let g=_E(e,t?.headers),_=g.has(q.acceptPayment),v=TE(g,f),y=hE(e,t,g),b=mE(e,t,g,v.header,_,n),x=await m(bE(b.input),b.init),S=x.response,C=x.headers,w=gE(b.init,await y);if(t?.[RE]||Vw(w)||!await c.isPaymentRequired(S,w))return S;let T=t?.context,{context:ee,orderChallenges:te,...E}=w??{},D,O,k,A,ne;try{for(let n=0;n<i;n++){O=await c.getChallenges(S,w);let f=(await EE(GC(O,a,v.entries,T),te??s))[0];if(!f){if(await qT(A,{challenges:O,response:S,status:`rejected`}),n>0)return S;throw Error(BS(`No method found for challenges: ${O.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`,PE(S)))}let g=f.challenge;D=g,k=f.method,D.expires&&hC(D.expires,D.id),await u?.challenge(S,{challenge:g},AE(b.input).href);let _=await NE(S,b.input,b.input,E);BT(g,()=>AE(_),l);let y=A,x=FE(g),ee=y?.method===f.method&&y?.key===x,j=!1;if(y){let e=await qT(y,{challenges:O,response:S,status:ee?`pending`:`rejected`});j=ee&&!e}A=j?y:void 0;let re=nE(async n=>{if(n===void 0&&j&&y)return y.promise;j&&y&&(await qT(y,{status:`rejected`}),A=void 0),xE(e,t)?.throwIfAborted();let r=n??T;if(!yT(f.method))return RT(()=>wE(g,f.method,r,jE(_)),{attempts:i,signal:xE(e,t)});let a={origin:AE(_).origin,prepare:()=>bT(f.method,{challenge:g,context:r,fetch:u?DC(p,u,{challenge:g}):p,input:_,signal:xE(e,t)})},o=a.prepare().then(()=>wE(g,f.method,r,a));return A={context:r,attempt:a,key:n===void 0?x:void 0,method:f.method,promise:o},o}),M=await d.emit(`challenge.received`,rE({challenge:g,challenges:O,createCredential:re,init:t,input:e,method:f.method,response:S}))??(o?await o(D,{createCredential:re}):void 0)??await re(),N=A;N&&await N.promise.catch(()=>void 0)!==M&&(await qT(N,{status:`rejected`}),A=void 0);let ie=A?A.context:T;CE(M);let ae=SE(M,g);await d.emit(`credential.created`,iE({challenge:g,credential:M,init:t,input:e,method:f.method,response:S}));let oe=e=>new Xx({cause:e,challenge:g,credential:M,transactionHash:AT(f.method,M)});try{({response:S}=await m(_,{...c.setCredential({...E,headers:b.headers},M,{challenge:g}),redirect:`manual`},{challenge:ae,headers:C}))}catch(e){throw ne=oe(e),e}let P=await c.isPaymentRequired(S,w);if(P||(await qT(N,{response:S,status:S.status>=300&&S.status<400?`pending`:S.ok?`accepted`:`rejected`}),A=void 0),S.ok&&QT(d,`payment.response`)&&await d.emit(`payment.response`,aE({challenge:g,credential:M,init:t,input:e,method:f.method,response:S})),!P){if(S.status>=500&&QT(d,`payment.failed`)){try{S=await KT(S)}catch(e){throw ne=oe(e),S=new Response(null,{headers:S.headers,status:S.status,statusText:S.statusText}),e}await d.emit(`payment.failed`,oE({challenge:g,challenges:O,error:oe(),init:t,input:e,method:f.method,response:S}))}return S.ok?OT(f.method,{context:ie,challenge:g,credential:M,fetch:p,headers:b.headers,input:_,...r?{refetch:()=>h(bE(b.input),t,!1)}:{},response:S,signal:xE(e,t)}):S}}O=void 0;try{O=await c.getChallenges(S,w)}catch{}return await qT(A,{challenges:O,response:S,status:`rejected`}),S}catch(n){throw await qT(A,{challenges:O,response:S,status:`rejected`}),await d.emit(`payment.failed`,oE({challenge:D,challenges:O,error:ne??n,init:t,input:e,method:k,response:S})),n}},g=(e,t)=>h(e,t,!0);return g[IE]=p,u&&(g[LE]=u),g}function YT(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);UE||=globalThis.fetch,globalThis.fetch=JT({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??(kE()?`same-origin`:`always`),fetch:yE(globalThis.fetch)})}function XT(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 ZT(){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 $T(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await tE(e[`*`],t,n),r}case`credential.created`:await eE(e[`credential.created`],n),await tE(e[`*`],t,n);return;case`payment.failed`:await eE(e[`payment.failed`],n),await tE(e[`*`],t,n);return;case`payment.response`:await eE(e[`payment.response`],n),await tE(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 WE.set(t,t=>e[t].size>0||e[`*`].size>0),t}function QT(e,t){return WE.get(e)?.(t)??!0}async function $T(e,t){try{return await e(t)}catch{return}}async function eE(e,t){for(let n of e)try{await n(t)}catch{}}async function tE(e,t,n){await eE(e,Object.freeze({name:t,payload:n}))}function nE(e){let t;return n=>(t??=e(n),t)}function rE(e){return Object.freeze({challenge:dE(e.challenge),challenges:e.challenges.map(e=>dE(e)),createCredential:e.createCredential,init:sE(e.init),input:cE(e.input),method:lE(e.method),response:uE(e.response)})}function iE(e){return Object.freeze({challenge:dE(e.challenge),credential:e.credential,init:sE(e.init),input:cE(e.input),method:lE(e.method),...e.response===void 0?{}:{response:uE(e.response)}})}function aE(e){return Object.freeze({challenge:dE(e.challenge),credential:e.credential,init:sE(e.init),input:cE(e.input),method:lE(e.method),response:uE(e.response)})}function oE(e){return Object.freeze({...e.challenge?{challenge:dE(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>dE(e))}:{},error:e.error,init:sE(e.init),input:cE(e.input),...e.method?{method:lE(e.method)}:{},...e.response===void 0?{}:{response:uE(e.response)}})}function sE(e){if(e)return pE({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function cE(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function lE(e){return pE(Object.assign({},e))}function uE(e){if(e instanceof Response)try{return e.clone()}catch{let t=new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText});for(let n of[`redirected`,`type`,`url`])Object.defineProperty(t,n,{value:e[n]});return t}return dE(e)}function dE(e){try{return fE(structuredClone(e))}catch{return pE(e)}}function fE(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))fE(t);return e}function pE(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function mE(e,t,n,r,i,a){let o=!!r&&!i&&DE(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(q.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function hE(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 gE(e,t){return t===void 0?e:{...e,body:t}}function _E(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function vE(e){return e[LE]}function yE(e){let t=e;for(;t[IE];)t=t[IE];return t}function bE(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function xE(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function SE(e,t){try{let{challenge:n}=aC(e);return n.id===t.id?t:{...n,...t.header!==void 0&&{header:t.header}}}catch{return t}}function CE(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
229
- `))throw Error(`Credential header value contains illegal newline characters`)}async function wE(e,t,n,r){let i=t.context&&n!==void 0?t.context.parse(n):void 0,a=i===void 0?{challenge:e}:{challenge:e,context:i};return r?.origin&&jT(a,r.origin),r&&`prepare`in r&&ET(t,a,r),t.createCredential(a)}function TE(e,t){let n=e.get(q.acceptPayment);if(!n)return t;try{return{...t,entries:HC(n),header:n}}catch{return t}}async function EE(e,t){return t?t(e):e}function DE(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=AE(e);return t===`same-origin`?!kE()||n.origin===globalThis.location.origin:t.origins.some(e=>OE(n,e))}function OE(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 kE(){return globalThis.location!==void 0}function AE(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,kE()?globalThis.location.href:void 0)}function jE(e){try{return{origin:AE(e).origin}}catch{return}}function ME(e,t){let n=e instanceof Request?e:void 0;if((t.mode??n?.mode)===`no-cors`)throw Error(`Cannot automatically pay a no-cors request: it cannot carry a credential.`);if((t.cache??n?.cache)===`only-if-cached`)throw Error(`Cannot automatically pay an only-if-cached request: its retry cannot reach the server.`)}async function NE(e,t,n,r){if(ME(t,r),!e.url)return t;let i=new URL(e.url),a=AE(n);if(i.origin!==a.origin)throw Error(`Refusing to send payment credential across redirect from ${a.origin} to ${i.origin}`);let o=(r.method??(t instanceof Request?t.method:`GET`)).toUpperCase();if(e.redirected&&o!==`GET`&&o!==`HEAD`)throw Error(`Cannot automatically pay a redirected ${o} request. Use prepareRequest() to preserve redirect semantics.`);if(t instanceof Request){let n=r.body==null?t.clone():t,i=new Request(n,t.mode===`navigate`&&r.mode===void 0?{...r,mode:`same-origin`}:r);return i.url.split(`#`)[0]===e.url?i:i.body?new Request(e.url,{body:await i.arrayBuffer(),cache:i.cache,credentials:i.credentials,headers:i.headers,integrity:i.integrity,keepalive:i.keepalive,method:i.method,mode:i.mode,redirect:i.redirect,referrer:i.referrer,referrerPolicy:i.referrerPolicy,signal:i.signal}):new Request(e.url,i)}return e.url}function PE(e){return!(e instanceof Response)||e.status!==402?0:zS(e.headers.get(q.wwwAuthenticate))}function FE(e){let{description:t,...n}=e;return re.canonicalize(n)}var IE,LE,RE,zE,BE,VE,HE,UE,WE,GE=R((()=>{iC(),Gx(),mC(),rS(),gC(),FC(),ow(),_T(),CT(),LT(),zT(),WT(),$w(),IE=Symbol.for(`mppx.fetch.wrapper`),LE=Symbol.for(`mppx.fetch.identity`),RE=Symbol.for(`mppx.fetch.skipPayment`),zE=3,BE=65536,VE=2e3,HE=`Mppx-Body-Truncated`,WE=new WeakMap}));Rx(),GE();const KE=Object.freeze([`agent-id`,`agent-signature`,`dpop`,`identity-attestation`,`identity-presentation`,`poppy-session`,`tempo-id-token`]);Object.freeze([`privatetoken`,`identity-presentation`]),Object.freeze([`identity-attestation-required`,`identity-required`]),iC(),Gx(),rS(),gC(),FC(),ow(),CT(),LT(),WT(),_T();const qE=new WeakMap;function JE(e){let{identity:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=gT(),trustedTempoProofRealms:c}=e;if(`attestation`in e)throw TypeError("Mppx client `attestation` was replaced by `identity: [prover]`.");let l=yE(e.fetch??globalThis.fetch),u=t?CC(t):e.fetch&&vE(e.fetch),d=e.methods.flat(),f=VC(d,e.paymentPreferences),p=ZT(),m=r,h={acceptPayment:f,acceptPaymentPolicy:o,...e.fetch&&{fetch:l},...u&&{identity:u},eventDispatcher:p,...n!==void 0&&{maxPaymentRetries:n},...m&&{onChallenge:m},...i&&{orderChallenges:i},methods:d,transport:s,...c&&{trustedTempoProofRealms:c}},g=JT(h);a&&YT(h);function _(e){return p.on(`challenge.received`,e)}function v(e){return p.on(`credential.created`,e)}function y(e){return p.on(`payment.failed`,e)}function b(e){return p.on(`payment.response`,e)}async function x(e,t,n){let r=cD(e),a=await s.getChallenges(e,t?.request),o=Object.freeze(a.map(e=>lD(e))),l=fD(f.entries,t?.acceptPayment),u,m;try{let f,h;try{f=GC(a,d,l,n)}catch(e){if(!(e instanceof Zx)||n!==void 0)throw e;f=[],h=e}if(f.length===0&&n===void 0&&(f=GC(a,d,l,aw)),f.length===0&&h)throw h;let g=(await pD(f,t?.orderChallenges??i))[0];if(!g)throw Error(BS(`No method found for challenges: ${a.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${d.map(e=>`${e.name}.${e.intent}`).join(`, `)}`,PE(e)));let _=g.challenge;u=o[g.index],m=g.method,u.expires&&hC(u.expires,u.id);let v=hD(e);v?BT(u,v,c):s.name===`mcp`&&VT(u,c&&Object.values(c));let y=u,b=m,x=rD(async e=>{try{y.expires&&hC(y.expires,y.id);let t=rD(t=>mD(y,b,t??e,v?.origin)),n=await p.emit(`challenge.received`,iD({challenge:y,challenges:a,createCredential:t,method:b,response:r}))??await t();return CE(n),await p.emit(`credential.created`,aD({challenge:y,credential:n,method:b,response:r})),n}catch(e){throw await p.emit(`payment.failed`,oD({challenge:y,challenges:a,error:e,method:b,response:r})),e}}),S=Object.freeze({challenge:y,challenges:o,createCredential:x,method:sD(b),setCredential(e,t){return CE(t),s.setCredential(e,t,{challenge:_})}});return qE.set(S,b),S}catch(e){throw await p.emit(`payment.failed`,oD({challenge:u,challenges:a,error:e,method:m,response:r})),e}}async function S(e,t,n){let{maxRedirects:r=20,requirePayment:i=!1,...a}=n??{},d=await QE({acceptPayment:f.header,acceptPaymentPolicy:o,fetch:l,init:t,input:e,maxRedirects:r,identity:u}),p=$E(d.replayRequest,d.body);if(!await s.isPaymentRequired(d.response,p)){if(i)throw Error(`Response does not require payment.`);return Object.freeze({payment:void 0,request:d.request,response:d.response,redirects:d.redirects})}let m=await x(d.response,{...a,request:p});BT(m.challenge,new URL(d.replayRequest.url),c);let h=qE.get(m)??m.method,g=rD(async e=>(await u?.challenge(d.response,{challenge:m.challenge},d.replayRequest.url),yT(h)&&await bT(h,{challenge:m.challenge,context:e,fetch:u?DC(l,u,{challenge:m.challenge}):l,input:d.replayRequest,signal:d.replayRequest.signal}),m.createCredential(e))),_=Object.freeze({...m,createCredential:g,async pay(e){let t=await g(e),n=m.setCredential($E(d.replayRequest,d.body),t),r=new Request(d.replayRequest.url,{...n,redirect:`manual`});if(!u)return l(r);let{response:i}=await u.send(l,r,{challenge:m.challenge,headers:d.identityHeaders});return i}});return Object.freeze({payment:_,request:d.request,response:d.response,redirects:d.redirects})}return{fetch:g,rawFetch:l,methods:d,transport:s,on:p.on,onChallengeReceived:_,onCredentialCreated:v,onPaymentFailed:y,onPaymentResponse:b,preparePayment:x,prepareRequest:S,async createCredential(e,t,n){return(await x(e,n,t)).createCredential(t)}}}const YE=new Set([301,302,303,307,308]),XE=[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`,`transfer-encoding`],ZE=[`authorization`,`cookie`,`cookie2`,`host`,`payment-authorization`,`payment-signature`,`proxy-authorization`,`x-payment`];async function QE(e){let{acceptPayment:t,acceptPaymentPolicy:n,fetch:r,identity:i,init:a,input:o,maxRedirects:s}=e;if(!Number.isInteger(s)||s<0)throw TypeError(`maxRedirects must be a non-negative integer.`);let c=new Set([...ZE,...KE,...i?.headers??[]]),l=new Request(o,{...a,redirect:`manual`}),u=l.headers.has(q.acceptPayment),d=await eD(l,a?.body),f=[];for(;;){l=tD(l,t,u,n);let{request:e,response:a,headers:o}=await(async()=>{if(i)return i.send(r,l.clone());let e=l.clone();return{request:e,response:await r(e),headers:[]}})();if(a.type===`opaqueredirect`||a.status===0)throw Error(`prepareRequest requires a runtime that exposes manual redirect responses.`);if(!YE.has(a.status))return{body:d,identityHeaders:o,replayRequest:l,request:e,response:a,redirects:Object.freeze(f)};let p=a.headers.get(`location`);if(!p)return{body:d,identityHeaders:o,replayRequest:l,request:e,response:a,redirects:Object.freeze(f)};if(f.length>=s)throw await a.body?.cancel(),Error(`Payment request exceeded ${s} redirects.`);let m=new URL(l.url),h=new URL(p,m);if(m.protocol===`https:`&&h.protocol!==`https:`)throw await a.body?.cancel(),Error(`Payment request refused HTTPS downgrade redirect to ${h.href}`);let g=new Headers(l.headers),_=l.method;if((a.status===301||a.status===302)&&_===`POST`||a.status===303&&_!==`GET`&&_!==`HEAD`){_=`GET`,d=void 0;for(let e of XE)g.delete(e)}if(m.origin!==h.origin)for(let e of[...g.keys()]){let t=g.get(e)??``;(c.has(e)||t.startsWith(`Payment `))&&g.delete(e)}f.push(Object.freeze({from:m.href,status:a.status,to:h.href})),await a.body?.cancel(),l=new Request(h,nD(l,g,_,d))}}function $E(e,t){return nD(e,new Headers(e.headers),e.method,t)}async function eD(e,t){if(typeof t==`string`)return t;if(!e.body)return;let n=e.headers.get(`accept`)?.toLowerCase()??``;return e.headers.has(`mcp-method`)||n.includes(`application/json`)&&n.includes(`text/event-stream`)?e.clone().text():e.clone().arrayBuffer()}function tD(e,t,n,r){if(n)return e;let i=new Headers(e.headers);return i.delete(q.acceptPayment),t&&DE(e,r)&&i.set(q.acceptPayment,t),new Request(e,{headers:i})}function nD(e,t,n,r){return{...r?{body:r}:{},cache:e.cache,credentials:e.credentials,headers:t,integrity:e.integrity,keepalive:e.keepalive,method:n,mode:e.mode,redirect:`manual`,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal}}function rD(e){let t;return n=>(t??=e(n),t)}function iD(e){return Object.freeze({challenge:lD(e.challenge),challenges:e.challenges.map(e=>lD(e)),createCredential:e.createCredential,method:sD(e.method),response:cD(e.response)})}function aD(e){return Object.freeze({challenge:lD(e.challenge),credential:e.credential,method:sD(e.method),response:cD(e.response)})}function oD(e){return Object.freeze({...e.challenge?{challenge:lD(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>lD(e))}:{},error:e.error,...e.method?{method:sD(e.method)}:{},response:cD(e.response)})}function sD(e){return dD(Object.assign({},e))}function cD(e){return e instanceof Response?e.body===null?e.clone():new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText}):lD(e)}function lD(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 uD(t)}catch{return dD(e)}}function uD(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))uD(t);return e}function dD(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function fD(e,t){return t?typeof t==`string`?HC(t):t:e}async function pD(e,t){return t?t(e):e}async function mD(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&&jT(a,r),t.createCredential(a)}function hD(e){if(typeof Response<`u`&&e instanceof Response&&e.url)return new URL(e.url)}function gD(){return Y.string().check(Y.regex(_D,`Invalid URI or path`))}var _D,vD,yD,bD,xD,SD,CD,wD,TD,ED=R((()=>{yS(),_D=/^([a-zA-Z][a-zA-Z\d+.-]*:\/\/\S+|\/\S*)$/,vD=new Set([`amount`,`currency`,`description`,`intent`,`method`]),yD=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())}),bD=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(yD).check(Y.minLength(1)))}).check(Y.refine(e=>e.offers===void 0||Object.keys(e).every(e=>e===`offers`||!vD.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`&&(vD.has(n)||r!==void 0)&&(t[n]=r);return{offers:[t]}})),xD=Y.looseObject({apiReference:Y.optional(gD()),homepage:Y.optional(gD()),llms:Y.optional(gD())}),SD=Y.looseObject({categories:Y.optional(Y.array(Y.string())),docs:Y.optional(xD)}),CD=Y.looseObject({"x-payment-info":Y.optional(bD),requestBody:Y.optional(Y.unknown()),responses:Y.optional(Y.record(Y.string(),Y.unknown())),summary:Y.optional(Y.string())}),wD=Y.looseObject({delete:Y.optional(CD),get:Y.optional(CD),head:Y.optional(CD),options:Y.optional(CD),patch:Y.optional(CD),post:Y.optional(CD),put:Y.optional(CD),trace:Y.optional(CD)}),TD=Y.looseObject({openapi:Y.string(),info:Y.looseObject({title:Y.string(),version:Y.string()}),"x-service-info":Y.optional(SD),paths:Y.optional(Y.record(Y.string(),wD))})}));ED();function DD(e){let t=[],n=TD.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=bD.safeParse(o);if(!s.success){for(let e of s.error.issues){let n=e.path.length>0?`.${e.path.map(String).join(`.`)}`:``;t.push({message:e.message,path:`${a}.x-payment-info${n}`,severity:`error`})}continue}let c=n.responses;(!c||!(`402`in c))&&t.push({message:`Operation with x-payment-info MUST have a 402 response`,path:`${a}.responses`,severity:`error`});let l=r.toUpperCase();!n.requestBody&&(l===`POST`||l===`PUT`||l===`PATCH`)&&t.push({message:`Operation with x-payment-info has no requestBody`,path:a,severity:`warning`})}return t}const OD=`2026-07-29.preview`;function kD(e){let{[AD]:t,[MD]:n,[jD]:r,...i}=e??{};return Object.keys(i).length?i:void 0}var AD,jD,MD,ND=R((()=>{AD=`_mppx_nonce`,jD=`_mppx_expiry_grace`,MD=`_mppx_identity`}));function PD(e){return e}function FD(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,async createCredential(e){return ES(e.challenge),i.call(this,e)}}}var ID=R((()=>{iC()}));function LD(e,t){return qe.resolve(e).toLowerCase()===qe.resolve(t).toLowerCase()}var RD=R((()=>{}));function zD(e){return Number.isInteger(e)&&e>0&&e<QD}function BD(e,t){return zD(t)?e===!0||(e?.includes(t)??!1):!1}function VD(e){return ze.zonePortal(e)}function HD(e){if(e>=2**32)return e%2**32;if(e>142431e4&&e<142432e4)return e-142431e4;if(e>4217e5&&e<42171e4)return e-4217e5;throw Error(`Cannot derive a Zone ID from chain ID ${e}. Pass \`zoneId\`.`)}function UD(e){if(e>=2**32)return Math.floor(e/2**32);if(e>142431e4&&e<142432e4)return 42431;if(e>4217e5&&e<42171e4)return 4217}function WD(e){return ne.keccak256(O.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function GD(e,t){let{blockNumber:n,sender:r,transactionHash:i}=t,a=t=>ke(e,{abi:Ie.zoneOutbox,address:ze.zoneOutbox,blockNumber:t,functionName:`lastFallbackNonce`}),[o,s]=await Promise.all([a(n-1n),a(n)]);if(s<=o)throw Error(`Zone withdrawal transaction ${i} did not request a withdrawal from the outbox.`);if(s-o>YD)throw Error(`Zone withdrawal transaction ${i} has ${s-o} candidate sender tags, more than ${YD}.`);let c=[];for(let e=o+1n;e<=s;e++)c.push(WD({fallbackNonce:e,sender:r,transactionHash:i}));return c}async function KD(e,t){let{senderTags:n,timeoutMs:r=qD}=t;if(!Number.isFinite(r)||r<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);if(n.length===0)throw Error(`Zone settlement needs at least one sender tag.`);let i=await Ee(e,{cacheTime:0}),a=i>JD?i-JD:0n,o=Date.now()+r;for(;;){if(a<=i){let[r]=await De(e,{address:t.portal,event:ZD,args:{senderTag:[...n],...t.to?{to:t.to}:{}},fromBlock:a,toBlock:i});if(r?.transactionHash&&r.args.senderTag)return{hash:r.transactionHash,senderTag:r.args.senderTag};a=i+1n}if(Date.now()+XD>o)throw Error(`Zone withdrawal ${n.join(` or `)} did not settle on Tempo within ${r}ms.`);await new Promise(e=>setTimeout(e,XD)),i=await Ee(e,{cacheTime:0})}}var qD,JD,YD,XD,ZD,QD,$D=R((()=>{qD=6e4,JD=7200n,YD=64n,XD=500,ZD=ce({abi:Ie.zonePortal,name:`WithdrawalProcessed`}),QD=4217e5,VD(0).slice(0,-16).toLowerCase()}));function eO(e){return Y.refine(e=>{let{amount:t,decimals:n}=e;return he(t,n)>0n},e)}function tO(e){let{periodCount:t,periodUnit:n}=e;try{let e=aO[n];return e!==void 0&&BigInt(t)*e<=iO}catch{return!1}}var nO,rO,iO,aO,oO,sO,cO,lO,uO,dO,fO,pO,mO,hO=R((()=>{Gx(),ID(),yS(),$D(),nO=[`push`,`pull`],rO=Y.object({amount:lS(),memo:Y.optional(hS()),recipient:Y.pipe(Y.string(),Y.transform(e=>e))}),iO=(1n<<64n)-1n,aO={dev_second:1n,day:86400n,week:604800n},oO=Y.pipe(mS(),Y.transform(e=>e.toLowerCase())),sO=Y.object({accessKeyAddress:oO,keyType:Y.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:Y.optional(Y.pipe(Y.string().check(Y.regex(/^0x[0-9a-fA-F]{120}$/)),Y.transform(e=>e)))}),cO=Y.object({accessKey:Y.optional(sO),chainId:Y.optional(Y.number())}),lO=dS(`subscriptionExpires must be a valid date`).check(Y.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),uO=Y.enum([`dev_second`,`day`,`week`]),dO=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)<=iO}catch{return!1}},`periodCount exceeds uint64`)),fO=PD({name:`tempo`,intent:`charge`,schema:{credential:{payload:Y.discriminatedUnion(`type`,[Y.object({hash:hS(),type:Y.literal(`hash`)}),Y.object({signature:_S(),type:Y.literal(`transaction`)}),Y.object({signature:_S(),type:Y.literal(`proof`)}),Y.object({hash:hS(),senderTag:hS(),type:Y.literal(`zone`),zoneId:Y.number().check(Y.refine(zD,`Invalid Zone ID`))})])},request:Y.pipe(Y.object({machineTokenEnabled:Y.optional(Y.boolean()),amount:lS(),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(Y.never()),recipient:Y.optional(Y.string()),splits:Y.optional(Y.array(rO).check(Y.minLength(1),Y.maxLength(10))),supportedModes:Y.optional(Y.array(Y.enum(nO)).check(Y.minLength(1))),zones:Y.optional(Y.union([Y.literal(!0),Y.array(Y.number().check(Y.refine(zD,`Invalid Zone ID`))).check(Y.minLength(1))]))}).check(Y.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=he(e,t),i=n.reduce((e,n)=>e+he(n.amount,t),0n);return n.every(e=>he(e.amount,t)>0n)&&i<r},`Invalid splits`)),Y.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,zones:c,...l})=>({...l,amount:he(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:he(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),pO=PD({name:`tempo`,intent:`session`,schema:{credential:{payload:Y.discriminatedUnion(`action`,[Y.object({action:Y.literal(`open`),authorizedSigner:Y.optional(Y.string()),channelId:hS(),cumulativeAmount:lS(),descriptor:Y.optional(Y.custom()),signature:_S(),transaction:_S(),type:Y.literal(`transaction`)}),Y.object({action:Y.literal(`topUp`),additionalDeposit:lS(),channelId:hS(),descriptor:Y.optional(Y.custom()),transaction:_S(),type:Y.literal(`transaction`)}),Y.object({action:Y.literal(`voucher`),channelId:hS(),cumulativeAmount:lS(),descriptor:Y.optional(Y.custom()),signature:_S()}),Y.object({action:Y.literal(`close`),channelId:hS(),closeSignature:_S(),cumulativeAmount:lS(),descriptor:Y.optional(Y.custom()),signature:_S()})])},request:Y.pipe(Y.object({amount:lS(),chainId:Y.optional(Y.number()),channelId:Y.optional(hS()),configurableVouchers:Y.optional(Y.boolean()),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(mS()),minVoucherDelta:Y.optional(lS()),operator:Y.optional(mS()),recipient:Y.optional(Y.string()),sessionProtocol:Y.optional(Y.enum([Wx.v2,Wx.v1])),sessionSnapshot:Y.optional(Y.custom()),suggestedDeposit:Y.optional(lS()),unitType:Y.string()}).check(Y.refine(({amount:e,decimals:t})=>he(e,t)>0n,`Session amount must be greater than 0`)),Y.transform(({amount:e,chainId:t,channelId:n,configurableVouchers:r,decimals:i,escrowContract:a,feePayer:o,feeToken:s,minVoucherDelta:c,operator:l,sessionProtocol:u,sessionSnapshot:d,suggestedDeposit:f,...p})=>({...p,amount:he(e,i).toString(),...f?{suggestedDeposit:he(f,i).toString()}:{},methodDetails:{escrowContract:a,...n!==void 0&&{channelId:n},...c!==void 0&&{minVoucherDelta:he(c,i).toString()},...t!==void 0&&{chainId:t},...o!==void 0&&{feePayer:o},...s!==void 0&&{feeToken:s},...l!==void 0&&{operator:l},...r!==void 0&&{configurableVouchers:r},...u!==void 0&&{[Ux.sessionProtocol]:u},...d!==void 0&&{[Ux.sessionSnapshot]:d}}})))}}),mO=PD({name:`tempo`,intent:`subscription`,schema:{credential:{payload:Y.object({signature:_S(),type:Y.literal(`keyAuthorization`)})},request:Y.pipe(Y.object({amount:lS(),accessKey:Y.optional(sO),chainId:Y.optional(Y.number()),currency:oO,decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),methodDetails:Y.optional(cO),periodCount:dO,periodUnit:uO,recipient:oO,subscriptionExpires:lO}).check(eO(`Subscription amount must be greater than 0`),Y.refine(tO,`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:he(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}})}));function gO(e){return e>=0n&&e<=FO}function _O(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return gO(t)?t:void 0}function vO(e){return yO(e),e}function yO(e){if(!gO(e))throw Error(`Value ${e} is outside uint96 bounds.`)}function bO(e){return typeof e==`object`&&!!e}function xO(e){return typeof e==`string`&&IO.has(e)}function SO(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!xO(t.action))}function CO(e,t=`No session credential context available.`){if(!SO(e))throw Error(t);return e}function wO(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function TO(e){return bO(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function EO(e){return bO(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 DO(e){let t=k.toString(e),n=JSON.parse(t);if(!EO(n))throw Error(`Invalid session receipt.`);return n}function OO(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function kO(e){let t=`message`,n=[];for(let r of e.split(`
228
+ `,i))}t=t.slice(i)}}}var rT=z((()=>{}));function iT(e,t,n){let r=new Headers(e.headers);for(let e of sT){let t=r.get(e);if(t===null)continue;if(!oT(e)){r.delete(e);continue}let n=aT(t);n!==t&&(n?r.set(e,n):r.delete(e))}return r.set(t,n),{...e,headers:r}}function aT(e){let t=e.split(`,`).map(e=>e.trim()),n=t.filter(e=>!cT.test(e));return n.length===t.length?e:n.filter(Boolean).join(`, `)}function oT(e){return e===q.authorization||e===q.paymentAuthorization}var sT,cT,lT=z((()=>{Gx(),Uw(),sT=[q.authorization,q.paymentAuthorization,ww,Ew,Tw],cT=RegExp(`^${Bx.payment}(?:\\s|$)`,`i`)}));function uT(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 dT(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t?.method===`tools/call`&&t.params?._meta?.[`mppx/payment-client`]===!0}catch{return!1}}function fT(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t.params?._meta?.[`org.paymentauth/credential`]!=null}catch{return!1}}function pT(e){let t=uT(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 mT(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 hT(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){if(!rC.safeParse(e).success)return;if(KS(e))continue;let t=nC.safeParse(e);if(!t.success)return;n.push(t.data)}if(n.length===0)return;let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function gT(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:hT(e.error.data):hT(e.result?._meta?.[eT])}function _T(e,t){return!e||e.id!==t?[]:gT(e)?.challenges??[]}async function vT(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=nT(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=mT(JSON.parse(e.data))}catch{}});try{for(;;){if(i)return a;let{done:e,value:s}=await t.read();if(e)return o.feed(n.decode()),a;if(r+=s.byteLength,r>CT)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function yT(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=``;try{for(;;){let{done:e,value:a}=await t.read();if(e)return mT(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>CT)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function bT(e){let t=wT.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>CT)){if(t.includes(`application/json`))return yT(e);if(t.includes(`text/event-stream`))return vT(e)}})();return wT.set(e,n),n}function xT(){return{getChallenges(e,t){let n=pT(t);return e.status===402||n===void 0?[]:bT(e).then(e=>_T(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=cC(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,[$w]:r}}})}}}}async function ST(e,t){let n=pT(t);if(e.status===402||n===void 0)return!1;let r=await bT(e);return!r||r.id!==n?!1:gT(r)?.problem?.type===TT}var CT,wT,TT,ET=z((()=>{sC(),vC(),rT(),tT(),lT(),CT=1048576,wT=new WeakMap,TT=`https://paymentauth.org/problems/invalid-challenge`}));function DT(){return{getChallenges(e){let t=e.headers.get(q.wwwAuthenticate);return e.status!==402||!t||!PS(t)?[]:RS(e)},setCredential(e,t,n){let r=n?.challenge??OT(t);return iT(e,r?GS(r):q.authorization,t)}}}function OT(e){if(kT.test(e))try{return cC(e).challenge}catch{return}}var kT,AT=z((()=>{sC(),Gx(),vC(),lT(),kT=/^Payment [A-Za-z0-9_-]+={0,2}$/}));function jT(e){return{encode(t){return te.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(te.toString(t)))}catch{throw new MT}}}}var MT,NT=z((()=>{MT=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}}}));function PT(e){try{let t=JSON.parse(te.toString(e));return VT(t)}catch{throw new MT}}var FT,IT,LT,RT,zT,BT,VT,HT=z((()=>{NT(),Uw(),FT=jT(Iw),IT=jT(Bw),LT=jT(Vw),RT=FT.encode,FT.decode,zT=IT.encode,BT=IT.decode,LT.encode,LT.decode,VT=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new MT;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new MT;let n=Mw.parse(t.resource),r=t.extensions===void 0?void 0:Fw.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}}}));function UT(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(ww);if(!t)return[];let n=PT(t);return n.accepts.flatMap((e,t)=>{let r=Nw.safeParse(e);if(!r.success)return[];let i=r.data;return JC(SS({id:`${Cw}${t}`,intent:bw,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return iT(e,Tw,t)}}}var WT=z((()=>{sC(),ZC(),HT(),Uw(),lT()}));function GT(e){return e}function KT(){let e=[DT(),UT(),xT()],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 GT({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 qT=z((()=>{ET(),AT(),lT(),WT()}));function JT(e,t){return QT.set(e,t),e}function YT(e){return QT.has(e)}function XT(e,t){return Promise.resolve(QT.get(e)?.(t))}function ZT(e){return QT.get(e)}var QT,$T=z((()=>{QT=new WeakMap}));function eE(e,t){return lE.set(e,t),e}function tE(e){lE.delete(e)}function nE(e,t,n){lE.has(e)&&uE.set(t,n)}function rE(e){return uE.get(e)}function iE(e,t){return Promise.resolve(lE.get(e)?.(t)??t.response)}function aE(e,t){return fE.set(e,t),e}function oE(e,t){try{return fE.get(e)?.(t)}catch{return}}function sE(e,t){dE.set(e,t)}function cE(e){return dE.get(e)??uE.get(e)?.origin}var lE,uE,dE,fE,pE=z((()=>{lE=new WeakMap,uE=new WeakMap,dE=new WeakMap,fE=new WeakMap}));async function mE(e,t){let{attempts:n,signal:r}=t;for(let t=1;;t++){r?.throwIfAborted();try{return await e()}catch(e){if(!(e instanceof nS)||t>=n)throw e;r?.throwIfAborted()}}}var hE=z((()=>{aS()}));function gE(e,t,n){if(!vE(e)&&(e.method!==`tempo`||e.intent!==`session`))return;t=typeof t==`function`?t():t;let{realm:r}=e;if(r.toLowerCase()===t.hostname.toLowerCase())return;let i=t.origin.toLowerCase();for(let[e,t]of Object.entries(n??{}))if(t===r&&yE(e)===i)return;throw Error(`Refusing to sign Tempo proof for realm ${JSON.stringify(r)} from ${t.origin}. Pin the realm to this origin with \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function _E(e,t){if(!(!vE(e)&&(e.method!==`tempo`||e.intent!==`session`))&&!t?.includes(e.realm))throw Error(`Refusing to sign Tempo proof for untrusted realm ${JSON.stringify(e.realm)}. Add it to \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function vE(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function yE(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}var bE=z((()=>{}));function xE(e){return Object.defineProperty(e,CE,{value:!0}),e}function SE(e){return typeof e==`object`&&!!e&&e[CE]===!0}var CE,wE=z((()=>{CE=Symbol.for(`mppx.client.fundsMayHaveMoved`)}));function TE(e,t){return jE.set(e,t),e}function EE(e){return jE.get(e)}function DE(e,t){ME.set(e,t)}function OE(e){return ME.get(e)}function kE(e,t){t===void 0||t===e?NE.delete(e):NE.set(e,t)}function AE(e){return NE.get(e)}var jE,ME,NE,PE=z((()=>{jE=new WeakMap,ME=new WeakMap,NE=new WeakMap}));function FE(e){let{authorize:t,funders:n=[],maxPayment:r,tokens:i}=e;if(r!==void 0&&nD(r),t!==void 0&&typeof t!=`function`)throw TypeError(`authorize must be a function.`);if(!Array.isArray(n)||n.some(e=>typeof e?.fund!=`function`))throw TypeError(`funders must be an array of objects with a fund function.`);let a=dD(i),o=e=>iD(e,a),s=r!==void 0||t!==void 0||n.length>0,c=r===void 0?`budget`:`maxPayment`;return{limit:c,resolve(e){if(e.intent===gD)try{return o(e)}catch{return}},prepare:s?async(e,{method:i,signal:a}={})=>{if(a?.throwIfAborted(),e.intent!==gD)throw new rS({limit:c,reason:`intent`});e.expires&&yC(e.expires,e.id);let s=i&&EE(i);if(s?.resumes?.(e))return Object.freeze({settlement:fD(void 0),constraints:l(!0)});let u=HE(e),d=o(e);r!==void 0&&rD(d,r),s?.assert?.(e);let f=Object.freeze({challenge:XE(e),...a?{signal:a}:{}}),p=Object.freeze({requirement:d});_D.add(p);let m=fD(await t?.(p,f)??void 0);try{for(let e of n)a?.throwIfAborted(),await e.fund(d,f);if(a?.throwIfAborted(),HE(e)!==u)throw Error(`Cannot check spending limits: the challenge changed while checked.`);e.expires&&yC(e.expires,e.id)}catch(e){throw m.release(),e}return Object.freeze({settlement:m,constraints:l(!1)})}:void 0};function l(e){let n=Object.freeze({limit:c,resume:e});return vD.set(n,t),n}}function IE(e){let t=AE(e);return t!==void 0&&yD.has(t)&&vD.has(t)&&vD.get(t)===vD.get(e)}function LE(e){return e!==void 0&&(e.maxPayment!==void 0||e.authorize!==void 0||e.funders!==void 0&&e.funders.length>0||e.tokens!==void 0)}function RE(e){let{authorize:t,funders:n,maxPayment:r,tokens:i}=e;return{...t!==void 0&&{authorize:t},...n!==void 0&&{funders:n},...r!==void 0&&{maxPayment:r},...i!==void 0&&{tokens:i}}}function zE(e,t){if(!LE(t))return RE(e);if(LE(e))throw TypeError(`The fetch passed in already has spending options (maxPayment, authorize, funders or tokens). Set them on one fetch only.`);return t}function BE(e,t){return t?e.then(e=>(t.commit(),e),e=>{throw e instanceof nS||e instanceof Zx||SE(e)?t.commit():t.release(),e}):e}function VE(e,t,n,r){let i,a=!1,o,s=()=>i??=Promise.resolve(e.prepare?.(t,{method:r,signal:n})),c=async()=>{if(!e.prepare)return;n?.throwIfAborted();let r=a?void 0:await s();if(r&&!r.constraints.resume)return r.settlement.commit();(await e.prepare(t,{signal:n})).settlement.commit()},l=async()=>{await o,(await i?.catch(()=>void 0))?.settlement.release()};return{prepare:s,async track(e){let r=await s();if(r&&n?.aborted&&(r.settlement.release(),n.throwIfAborted()),r&&!r.constraints.resume&&t.expires)try{yC(t.expires,t.id)}catch(e){throw r.settlement.release(),e}let i=BE(e(r?.constraints),r&&{commit(){a=!0,IE(r.constraints)?r.settlement.release():(r.settlement.commit(),r.constraints.resume||yD.add(r.constraints))},release(){}});return o=i.then(()=>{},()=>{}),i},commit:c,async commitReplacement(r,i){if(!e.prepare)return;let a=WE(r,i);if(!a)throw YE(e);return UE(a)===UE(t)?(await c(),a):(await l(),await VE(e,a,n).commit(),a)},release:l}}function HE(e){let{digest:t,expires:n,id:r,intent:i,meta:a,method:o,opaque:s,realm:c,request:l}=e;return JSON.stringify([YC(e),r,c,o,i,cS(l),n??null,t??null,s??(a===void 0?null:cS(a))])}function UE(e){try{return HE(e)}catch{return}}function WE(e,t){let n=GE(e,t)??KE(e,t);return n?.length===1?n[0]:void 0}function GE(e,t){let n;try{n=cC(e).challenge}catch{return}let r=UE(n);return r===void 0?[]:t.filter(e=>UE(e)===r)}function KE(e,t){let n;try{n=BT(e)}catch{return}return t.filter(e=>YC(e)&&qE(n,e))}function qE(e,t){let n=Nw.safeParse(t.request);if(!n.success)return!1;let r=n.data;try{if(cS(r)!==cS(e.accepted))return!1;let t=BigInt(r.amount),n=e.payload;if(`authorization`in n)return JE(n.authorization.to,r.payTo)&&BigInt(n.authorization.value)===t;let{permitted:i,witness:a}=n.permit2Authorization;return JE(i.token,r.asset)&&BigInt(i.amount)===t&&JE(a.to,r.payTo)}catch{return!1}}function JE(e,t){return e.toLowerCase()===t.toLowerCase()}function YE(e){return new rS({limit:e.limit,reason:`credential`})}function XE(e){let t;try{t=structuredClone(e)}catch{t=JSON.parse(JSON.stringify(e))}return YC(e)&&JC(t),ZE(t)}function ZE(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))ZE(t);return e}function QE(e,t){let n=/^0x[\da-fA-F]{40}$/.test(t)||e===`stripe`?t.toLowerCase():t;return JSON.stringify([e,n])}function $E(e,t){let[,n=`0`,r=``]=bD.exec(e)??[];return BigInt(`${n}${r.slice(0,t).padEnd(t,`0`)}`)}function eD(e,t){let{currency:n,value:r}=e??{};if(typeof n!=`string`||!n.trim())throw TypeError(`${t} currency must be a non-empty string.`);if(typeof r!=`string`||r.length>xD||!bD.test(r))throw TypeError(`${t} value must be a non-negative decimal string.`)}function tD(e){if(typeof e!=`object`||!e)return!1;let{amount:t,asset:n,network:r}=e;return typeof r==`string`&&r.length>0&&typeof n==`string`&&n.length>0&&typeof t==`bigint`&&t>=0n}function nD(e){if(!Array.isArray(e))return eD(e,`maxPayment`);let t=new Set;for(let n of e){if(!tD(n))throw TypeError(`Each maxPayment limit needs a network, an asset and a bigint amount.`);let e=QE(n.network,n.asset);if(t.has(e))throw TypeError(`Duplicate maxPayment limit for ${n.asset}.`);t.add(e)}}function rD(e,t){let n=e=>new rS({limit:`maxPayment`,reason:e});if(Array.isArray(t)){let r=QE(e.network,e.asset),i=t.find(e=>QE(e.network,e.asset)===r);if(!i)throw n(`asset`);if(e.amount>i.amount)throw n(`amount`);return}let r=t,{currency:i,decimals:a}=e;if(i===void 0||a===void 0||i.toUpperCase()!==r.currency.toUpperCase())throw n(`asset`);if(e.amount>$E(r.value,a))throw n(`amount`)}function iD(e,t){let n=YC(e)?oD(e):sD(e),r=t.get(QE(n.network,n.asset)),i={method:e.method,intent:e.intent,...n,...r?{currency:r.currency,decimals:r.decimals}:{}};return Object.defineProperty(i,"toJSON",{value:aD}),Object.freeze(i)}function aD(){return{...this,amount:this.amount.toString(),...this.splits&&{splits:this.splits.map(e=>({...e,amount:e.amount.toString()}))}}}function oD(e){let t=Nw.safeParse(e.request);if(!t.success)throw Error(`Cannot check spending limits: invalid x402 requirements.`);let{amount:n,asset:r,network:i,payTo:a}=t.data;return{protocol:`x402`,network:i,asset:r,amount:uD(n),recipient:a}}function sD(e){let t=e.request,n=typeof t.methodDetails==`object`&&t.methodDetails!==null?t.methodDetails:{},r=n.chainId;if(r!==void 0&&(!Number.isSafeInteger(r)||r<=0))throw Error(`Cannot check spending limits: invalid challenge chain ID.`);if(t.chainId!==void 0&&t.chainId!==r)throw Error(`Cannot check spending limits: challenge names a chain outside methodDetails.chainId.`);let i=t.currency;if(typeof i!=`string`||!i)throw Error(`Cannot check spending limits: challenge names no currency.`);let a=uD(t.amount),o=cD(e.method,t,n),s=lD(n.splits,a);return{protocol:`mpp`,network:r===void 0?e.method:`eip155:${r}`,asset:i,amount:a,...o===void 0?{}:{recipient:o},...s?{splits:s}:{}}}function cD(e,t,n){if(e===`stripe`){if(typeof n.networkId!=`string`||!n.networkId)throw Error(`Cannot check spending limits: Stripe challenge names no networkId.`);return n.networkId}return typeof t.recipient==`string`?t.recipient:void 0}function lD(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw Error(`Cannot check spending limits: invalid payment splits.`);let n=0n,r=e.map(e=>{let{amount:t,recipient:r}=e??{};if(typeof r!=`string`||!r)throw Error(`Cannot check spending limits: payment split names no recipient.`);let i=uD(t);return n+=i,Object.freeze({recipient:r,amount:i})});if(n>=t)throw Error(`Cannot check spending limits: payment splits are not less than the amount.`);return Object.freeze(r)}function uD(e){if(typeof e!=`string`||!/^\d+$/.test(e))throw Error(`Cannot check spending limits: challenge amount is not an atomic integer.`);return BigInt(e)}function dD(e){let t=new Map;for(let e of mD)for(let n of pD){let r=e.addresses[n];r&&t.set(QE(`eip155:${n}`,r),{currency:e.currency,decimals:e.decimals})}for(let{asset:e,currency:n,decimals:r,network:i}of hD)t.set(QE(i,e),{currency:n,decimals:r});if(e===void 0)return t;if(!Array.isArray(e))throw TypeError(`tokens must be an array.`);let n=new Map;for(let t of e){let{currency:e,decimals:r}=t??{};if(typeof e!=`string`||!e.trim())throw TypeError(`Each token needs a currency, such as USD.`);if(typeof r!=`number`||!Number.isInteger(r)||r<0||r>255)throw TypeError(`Token decimals must be an integer from 0 to 255.`);let i=typeof t==`function`?Object.entries(t.addresses).map(([e,t])=>[Number(e),t]):[[t.chainId,t.address]];for(let[t,a]of i){if(!Number.isSafeInteger(t)||t<=0||typeof a!=`string`||!a)throw TypeError(`Each token needs an address and a chain ID.`);let i=QE(`eip155:${t}`,a),o=n.get(i);if(o&&(o.currency.toUpperCase()!==e.toUpperCase()||o.decimals!==r))throw TypeError(`tokens configure conflicting metadata for ${a}.`);n.set(i,Object.freeze({currency:e,decimals:r}))}}for(let[e,r]of n)t.set(e,r);return t}function fD(e){let t=!0,n=n=>{t&&(t=!1,n?.call(e))};return Object.freeze({commit:()=>n(e?.commit),release:()=>n(e?.release)})}var pD,mD,hD,gD,_D,vD,yD,bD,xD,SD=z((()=>{vC(),aS(),bC(),ZC(),HT(),Uw(),lS(),wE(),PE(),pD=[4217,42431],mD=[we,Te,Ee],hD=[{network:`stripe`,asset:`usd`,currency:`USD`,decimals:2}],gD=`charge`,_D=new WeakSet,vD=new WeakMap,yD=new WeakSet,bD=/^(\d+)(?:\.(\d+))?$/,xD=1024}));function CD(e={}){return{...e,[bO]:!0}}async function wD(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},CO);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>SO){i=!0;break}}}finally{clearTimeout(a),t.cancel().catch(()=>{})}if(!i)return e;e.body.cancel().catch(()=>{});let o=new Headers(e.headers);o.delete(`content-length`),o.set(wO,`true`);let s=new Response(new Blob(n).slice(0,SO),{headers:o,status:e.status,statusText:e.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{value:e[t]});return s}async function TD(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 ED(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=xO,methods:a,onChallenge:o,orderChallenges:s,transport:c=KT(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&XD(e.fetch)),d=e.eventDispatcher??kD(),f=t??$C(a),p=zE(e,e.fetch&&ZD(e.fetch)),m=FE(p),h=QD(r),g=async(e,t,n)=>u?u.send((e,n)=>h(e,t?.[bO]?CD(n):n),new Request(e,t),n):{response:await h(e,t),headers:[]},_=async(e,t,r)=>{let p=YD(e,t?.headers),v=p.has(q.acceptPayment),y=iO(p,f),b=eO(e,t),x=qD(e,t,p,m.prepare?b:void 0),S=KD(e,t,p,y.header,v,n);if(m.prepare){let e=await x;if(b?.throwIfAborted(),dT(JD(S.init,e)))throw TypeError(`This fetch has spending options (maxPayment, authorize or funders), but McpClient.wrap pays MCP tool calls itself. Set them on McpClient.wrap and give its transport a fetch without them.`)}let C=await g($D(S.input),S.init),w=C.response,T=C.headers,E=JD(S.init,await x);if(t?.[bO]||dT(E)||!await c.isPaymentRequired(w,E))return w;let ee=t?.context,{context:D,orderChallenges:O,...k}=E??{},te=gO(p)||fT(E),A,j,M,ne,N;try{for(let n=0;n<i;n++){if(j=await c.getChallenges(w,E),(n>0||te)&&await hO(w,E))return await TD(ne,{challenges:j,response:w,status:`rejected`}),w;let f=(await aO(rw(j,a,y.entries,ee),O??s))[0];if(!f){if(await TD(ne,{challenges:j,response:w,status:`rejected`}),n>0)return w;throw Error(HS(`No method found for challenges: ${j.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`,pO(w)))}let p=f.challenge;A=p,M=f.method,A.expires&&yC(A.expires,A.id),await u?.challenge(w,{challenge:p},lO(S.input).href);let v=await fO(w,S.input,S.input,k);gE(p,()=>lO(v),l);let b=ne,x=mO(p),C=b?.method===f.method&&b?.key===x,D=!1;if(b){let e=await TD(b,{challenges:j,response:w,status:C?`pending`:`rejected`});D=C&&!e}ne=D?b:void 0;let P=VE(m,p,eO(e,t),f.method),re,ie=PD(async n=>{if(n===void 0&&D&&b)return re=b.promise,b.promise;D&&b&&(await TD(b,{status:`rejected`}),ne=void 0),eO(e,t)?.throwIfAborted();let r=n??ee;if(!YT(f.method))return re=P.track(n=>mE(()=>rO(p,f.method,r,uO(v),n),{attempts:i,signal:eO(e,t)})),re;let a={origin:lO(v).origin,prepare:()=>XT(f.method,{challenge:p,context:r,fetch:u?IC(h,u,{challenge:p}):h,input:v,signal:eO(e,t)})},o=P.track(e=>a.prepare().then(()=>rO(p,f.method,r,a,e)));return re=o,ne={context:r,attempt:a,key:n===void 0?x:void 0,method:f.method,promise:o},o}),ae,F,oe,se=!1;try{let n=await d.emit(`challenge.received`,FD({challenge:p,challenges:j,createCredential:ie,init:t,input:e,method:f.method,response:w}))??(o?await o(A,{createCredential:ie}):void 0);if(n===!1)return await P.release(),await TD(ne,{challenges:j,response:w,status:`rejected`}),ne=void 0,w;ae=n??await ie(),F=ne,F&&await F.promise.catch(()=>void 0)!==ae&&(await TD(F,{status:`rejected`}),ne=void 0),nO(ae),se=re!==void 0&&await re.catch(()=>void 0)===ae,se||(oe=await P.commitReplacement(ae,j))}catch(e){throw await P.release(),e}let I=ne?ne.context:ee,ce=tO(ae,p);await d.emit(`credential.created`,ID({challenge:p,credential:ae,init:t,input:e,method:f.method,response:w}));let L=e=>new Xx({cause:e,challenge:p,credential:ae,transactionHash:oE(f.method,ae)});try{({response:w,headers:T}=await g(v,{...c.setCredential({...k,headers:S.headers},ae,{challenge:oe??p}),redirect:`manual`},{challenge:ce,headers:T}))}catch(e){throw N=L(e),e}let le=await c.isPaymentRequired(w,E);if(le||(await TD(F,{response:w,status:w.status>=300&&w.status<400?`pending`:w.ok?`accepted`:`rejected`}),ne=void 0),w.ok&&AD(d,`payment.response`)){let n=se?p:oe??WE(ae,j);await d.emit(`payment.response`,LD({challenge:p,credential:ae,init:t,input:e,method:f.method,requirement:n&&m.resolve(n),response:w}))}if(!le){if(w.status>=500&&AD(d,`payment.failed`)){try{w=await wD(w)}catch(e){throw N=L(e),w=new Response(null,{headers:w.headers,status:w.status,statusText:w.statusText}),e}await d.emit(`payment.failed`,RD({challenge:p,challenges:j,error:L(),init:t,input:e,method:f.method,response:w}))}return w.ok?iE(f.method,{context:I,challenge:p,credential:ae,fetch:h,headers:S.headers,input:v,...r?{refetch:()=>_($D(S.input),t,!1)}:{},response:w,signal:eO(e,t)}):w}}j=void 0;try{j=await c.getChallenges(w,E)}catch{}return await TD(ne,{challenges:j,response:w,status:`rejected`}),w}catch(n){throw await TD(ne,{challenges:j,response:w,status:`rejected`}),await d.emit(`payment.failed`,RD({challenge:A,challenges:j,error:N??n,init:t,input:e,method:M,response:w})),n}},v=(e,t)=>_(e,t,!0);return v[_O]=h,u&&(v[vO]=u),LE(p)&&(v[yO]=p),v}function DD(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);TO||=globalThis.fetch,globalThis.fetch=ED({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??(cO()?`same-origin`:`always`),fetch:QD(globalThis.fetch)})}function OD(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 kD(){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 jD(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await ND(e[`*`],t,n),r}case`credential.created`:await MD(e[`credential.created`],n),await ND(e[`*`],t,n);return;case`payment.failed`:await MD(e[`payment.failed`],n),await ND(e[`*`],t,n);return;case`payment.response`:await MD(e[`payment.response`],n),await ND(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 EO.set(t,t=>e[t].size>0||e[`*`].size>0),t}function AD(e,t){return EO.get(e)?.(t)??!0}async function jD(e,t){try{return await e(t)}catch{return}}async function MD(e,t){for(let n of e)try{await n(t)}catch{}}async function ND(e,t,n){await MD(e,Object.freeze({name:t,payload:n}))}function PD(e){let t;return n=>(t??=e(n),t)}function FD(e){return Object.freeze({challenge:UD(e.challenge),challenges:e.challenges.map(e=>UD(e)),createCredential:e.createCredential,init:zD(e.init),input:BD(e.input),method:VD(e.method),response:HD(e.response)})}function ID(e){return Object.freeze({challenge:UD(e.challenge),credential:e.credential,init:zD(e.init),input:BD(e.input),method:VD(e.method),...e.response===void 0?{}:{response:HD(e.response)}})}function LD(e){let{requirement:t,response:n}=e,r=n instanceof Response?Yw(n):void 0;return Object.freeze({...t?{amount:t.amount.toString(),requirement:t}:{},...r?{receipt:r}:{},challenge:UD(e.challenge),credential:e.credential,init:zD(e.init),input:BD(e.input),method:VD(e.method),response:HD(e.response)})}function RD(e){return Object.freeze({...e.challenge?{challenge:UD(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>UD(e))}:{},error:e.error,init:zD(e.init),input:BD(e.input),...e.method?{method:VD(e.method)}:{},...e.response===void 0?{}:{response:HD(e.response)}})}function zD(e){if(e)return GD({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function BD(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function VD(e){return GD(Object.assign({},e))}function HD(e){if(e instanceof Response)try{return e.clone()}catch{let t=new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText});for(let n of[`redirected`,`type`,`url`])Object.defineProperty(t,n,{value:e[n]});return t}return UD(e)}function UD(e){try{return WD(structuredClone(e))}catch{return GD(e)}}function WD(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))WD(t);return e}function GD(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function KD(e,t,n,r,i,a){let o=!!r&&!i&&oO(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(q.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function qD(e,t,n,r){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{let t=e.clone();return(r&&t.body?new Response(t.body.pipeThrough(new TransformStream,{signal:r})):t).text().catch(()=>void 0)}catch{return}}}function JD(e,t){return t===void 0?e:{...e,body:t}}function YD(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function XD(e){return e[vO]}function ZD(e){return e[yO]}function QD(e){let t=e;for(;t[_O];)t=t[_O];return t}function $D(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function eO(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function tO(e,t){try{let{challenge:n}=cC(e);return n.id===t.id?t:{...n,...t.header!==void 0&&{header:t.header}}}catch{return t}}function nO(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
229
+ `))throw Error(`Credential header value contains illegal newline characters`)}async function rO(e,t,n,r,i){let a=t.context&&n!==void 0?t.context.parse(n):void 0,o=a===void 0?{challenge:e}:{challenge:e,context:a};return i&&DE(o,i),r?.origin&&sE(o,r.origin),r&&`prepare`in r&&nE(t,o,r),t.createCredential(o)}function iO(e,t){let n=e.get(q.acceptPayment);if(!n)return t;try{return{...t,entries:ew(n),header:n}}catch{return t}}async function aO(e,t){return t?t(e):e}function oO(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=lO(e);return t===`same-origin`?!cO()||n.origin===globalThis.location.origin:t.origins.some(e=>sO(n,e))}function sO(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 cO(){return globalThis.location!==void 0}function lO(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,cO()?globalThis.location.href:void 0)}function uO(e){try{return{origin:lO(e).origin}}catch{return}}function dO(e,t){let n=e instanceof Request?e:void 0;if((t.mode??n?.mode)===`no-cors`)throw Error(`Cannot automatically pay a no-cors request: it cannot carry a credential.`);if((t.cache??n?.cache)===`only-if-cached`)throw Error(`Cannot automatically pay an only-if-cached request: its retry cannot reach the server.`)}async function fO(e,t,n,r){if(dO(t,r),!e.url)return t;let i=new URL(e.url),a=lO(n);if(i.origin!==a.origin)throw Error(`Refusing to send payment credential across redirect from ${a.origin} to ${i.origin}`);let o=(r.method??(t instanceof Request?t.method:`GET`)).toUpperCase();if(e.redirected&&o!==`GET`&&o!==`HEAD`)throw Error(`Cannot automatically pay a redirected ${o} request. Use prepareRequest() to preserve redirect semantics.`);if(t instanceof Request){let n=r.body==null?t.clone():t,i=new Request(n,t.mode===`navigate`&&r.mode===void 0?{...r,mode:`same-origin`}:r);return i.url.split(`#`)[0]===e.url?i:i.body?new Request(e.url,{body:await i.arrayBuffer(),cache:i.cache,credentials:i.credentials,headers:i.headers,integrity:i.integrity,keepalive:i.keepalive,method:i.method,mode:i.mode,redirect:i.redirect,referrer:i.referrer,referrerPolicy:i.referrerPolicy,signal:i.signal}):new Request(e.url,i)}return e.url}function pO(e){return!(e instanceof Response)||e.status!==402?0:VS(e.headers.get(q.wwwAuthenticate))}function mO(e){let{description:t,...n}=e;return ne.canonicalize(n)}async function hO(e,t){if(!(e instanceof globalThis.Response))return!1;if(await ST(e,t))return!0;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return!1;try{return(await e.clone().json()).type===`https://paymentauth.org/problems/invalid-challenge`}catch{return!1}}function gO(e){return e.get(q.paymentAuthorization)?!0:/(^|,)\s*Payment\s+\S/i.test(e.get(q.authorization)??``)}var _O,vO,yO,bO,xO,SO,CO,wO,TO,EO,DO=z((()=>{sC(),Gx(),vC(),aS(),bC(),qC(),vw(),Qw(),qT(),$T(),pE(),hE(),bE(),ET(),SD(),PE(),_O=Symbol.for(`mppx.fetch.wrapper`),vO=Symbol.for(`mppx.fetch.identity`),yO=Symbol.for(`mppx.fetch.spend`),bO=Symbol.for(`mppx.fetch.skipPayment`),xO=3,SO=65536,CO=2e3,wO=`Mppx-Body-Truncated`,EO=new WeakMap}));Rx(),DO();const OO=Object.freeze([`agent-id`,`agent-signature`,`dpop`,`identity-attestation`,`identity-presentation`,`poppy-session`,`tempo-id-token`]);Object.freeze([`privatetoken`,`identity-presentation`]),Object.freeze([`identity-attestation-required`,`identity-required`]),sC(),Gx(),aS(),bC(),qC(),vw(),$T(),pE(),bE(),SD(),PE(),qT();const kO=new WeakMap,AO=new WeakMap;function jO(e){let{identity:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=KT(),trustedTempoProofRealms:c}=e;if(`attestation`in e)throw TypeError("Mppx client `attestation` was replaced by `identity: [prover]`.");let l=QD(e.fetch??globalThis.fetch),u=t?DC(t):e.fetch&&XD(e.fetch),d=e.methods.flat(),f=$C(d,e.paymentPreferences),p=kD(),m=zE(e,e.fetch&&ZD(e.fetch)),h=FE(m),g=r,_={acceptPayment:f,acceptPaymentPolicy:o,...m,...e.fetch&&{fetch:l},...u&&{identity:u},eventDispatcher:p,...n!==void 0&&{maxPaymentRetries:n},...g&&{onChallenge:g},...i&&{orderChallenges:i},methods:d,transport:s,...c&&{trustedTempoProofRealms:c}},v=ED(_);a&&DD(_);function y(e){return p.on(`challenge.received`,e)}function b(e){return p.on(`credential.created`,e)}function x(e){return p.on(`payment.failed`,e)}function S(e){return p.on(`payment.response`,e)}async function C(e,t,n){let r=GO(e),a=await s.getChallenges(e,t?.request),o=Object.freeze(a.map(e=>KO(e))),l=YO(f.entries,t?.acceptPayment),u,m;try{let f,g;try{f=rw(a,d,l,n)}catch(e){if(!(e instanceof Qx)||n!==void 0)throw e;f=[],g=e}if(f.length===0&&n===void 0&&(f=rw(a,d,l,_w)),f.length===0&&g)throw g;let _=(await XO(f,t?.orderChallenges??i))[0];if(!_)throw Error(HS(`No method found for challenges: ${a.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${d.map(e=>`${e.name}.${e.intent}`).join(`, `)}`,pO(e)));let v=_.challenge;u=o[_.index],m=_.method,u.expires&&yC(u.expires,u.id);let y=$O(e);y?gE(u,y,c):s.name===`mcp`&&_E(u,c&&Object.values(c));let b=u,x=m,S=VE(h,b,QO(t?.request),x),C=BO(async e=>{try{b.expires&&yC(b.expires,b.id);let t,n=BO(n=>t=S.track(t=>ZO(b,x,n??e,y?.origin,t))),i=await p.emit(`challenge.received`,VO({challenge:b,challenges:a,createCredential:n,method:x,response:r}))??await n();return nO(i),(!t||await t.catch(()=>void 0)!==i)&&await S.commitReplacement(i,o),await p.emit(`credential.created`,HO({challenge:b,credential:i,method:x,response:r})),i}catch(e){throw await S.release(),await p.emit(`payment.failed`,UO({challenge:b,challenges:a,error:e,method:x,response:r})),e}}),w=Object.freeze({challenge:b,challenges:o,createCredential:C,method:WO(x),setCredential(e,t){return nO(t),s.setCredential(e,t,{challenge:v})}});return kO.set(w,x),h.prepare&&AO.set(w,S),w}catch(e){throw await p.emit(`payment.failed`,UO({challenge:u,challenges:a,error:e,method:m,response:r})),e}}async function w(e,t,n){let{maxRedirects:r=20,requirePayment:i=!1,...a}=n??{},d=await FO({acceptPayment:f.header,acceptPaymentPolicy:o,fetch:l,init:t,input:e,maxRedirects:r,identity:u}),p=IO(d.replayRequest,d.body);if(!await s.isPaymentRequired(d.response,p)){if(i)throw Error(`Response does not require payment.`);return Object.freeze({payment:void 0,request:d.request,response:d.response,redirects:d.redirects})}let m=await C(d.response,{...a,request:p});gE(m.challenge,new URL(d.replayRequest.url),c);let h=kO.get(m)??m.method,g=AO.get(m),_=BO(async e=>{await u?.challenge(d.response,{challenge:m.challenge},d.replayRequest.url),await g?.prepare();try{return YT(h)&&await XT(h,{challenge:m.challenge,context:e,fetch:u?IC(l,u,{challenge:m.challenge}):l,input:d.replayRequest,signal:d.replayRequest.signal}),await m.createCredential(e)}catch(e){throw await g?.release(),e}}),v=Object.freeze({...m,createCredential:_,async pay(e){let t=await _(e),n=m.setCredential(IO(d.replayRequest,d.body),t),r=new Request(d.replayRequest.url,{...n,redirect:`manual`});if(!u)return l(r);let{response:i}=await u.send(l,r,{challenge:m.challenge,headers:d.identityHeaders});return i}});return Object.freeze({payment:v,request:d.request,response:d.response,redirects:d.redirects})}return{fetch:v,rawFetch:l,methods:d,transport:s,on:p.on,onChallengeReceived:y,onCredentialCreated:b,onPaymentFailed:x,onPaymentResponse:S,preparePayment:C,prepareRequest:w,async createCredential(e,t,n){return(await C(e,n,t)).createCredential(t)}}}const MO=new Set([301,302,303,307,308]),NO=[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`,`transfer-encoding`],PO=[`authorization`,`cookie`,`cookie2`,`host`,`payment-authorization`,`payment-signature`,`proxy-authorization`,`x-payment`];async function FO(e){let{acceptPayment:t,acceptPaymentPolicy:n,fetch:r,identity:i,init:a,input:o,maxRedirects:s}=e;if(!Number.isInteger(s)||s<0)throw TypeError(`maxRedirects must be a non-negative integer.`);let c=new Set([...PO,...OO,...i?.headers??[]]),l=new Request(o,{...a,redirect:`manual`}),u=l.headers.has(q.acceptPayment),d=await LO(l,a?.body),f=[];for(;;){l=RO(l,t,u,n);let{request:e,response:a,headers:o}=await(async()=>{if(i)return i.send(r,l.clone());let e=l.clone();return{request:e,response:await r(e),headers:[]}})();if(a.type===`opaqueredirect`||a.status===0)throw Error(`prepareRequest requires a runtime that exposes manual redirect responses.`);if(!MO.has(a.status))return{body:d,identityHeaders:o,replayRequest:l,request:e,response:a,redirects:Object.freeze(f)};let p=a.headers.get(`location`);if(!p)return{body:d,identityHeaders:o,replayRequest:l,request:e,response:a,redirects:Object.freeze(f)};if(f.length>=s)throw await a.body?.cancel(),Error(`Payment request exceeded ${s} redirects.`);let m=new URL(l.url),h=new URL(p,m);if(m.protocol===`https:`&&h.protocol!==`https:`)throw await a.body?.cancel(),Error(`Payment request refused HTTPS downgrade redirect to ${h.href}`);let g=new Headers(l.headers),_=l.method;if((a.status===301||a.status===302)&&_===`POST`||a.status===303&&_!==`GET`&&_!==`HEAD`){_=`GET`,d=void 0;for(let e of NO)g.delete(e)}if(m.origin!==h.origin)for(let e of[...g.keys()]){let t=g.get(e)??``;(c.has(e)||t.startsWith(`Payment `))&&g.delete(e)}f.push(Object.freeze({from:m.href,status:a.status,to:h.href})),await a.body?.cancel(),l=new Request(h,zO(l,g,_,d))}}function IO(e,t){return zO(e,new Headers(e.headers),e.method,t)}async function LO(e,t){if(typeof t==`string`)return t;if(!e.body)return;let n=e.headers.get(`accept`)?.toLowerCase()??``;return e.headers.has(`mcp-method`)||n.includes(`application/json`)&&n.includes(`text/event-stream`)?e.clone().text():e.clone().arrayBuffer()}function RO(e,t,n,r){if(n)return e;let i=new Headers(e.headers);return i.delete(q.acceptPayment),t&&oO(e,r)&&i.set(q.acceptPayment,t),new Request(e,{headers:i})}function zO(e,t,n,r){return{...r?{body:r}:{},cache:e.cache,credentials:e.credentials,headers:t,integrity:e.integrity,keepalive:e.keepalive,method:n,mode:e.mode,redirect:`manual`,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal}}function BO(e){let t;return n=>(t??=e(n),t)}function VO(e){return Object.freeze({challenge:KO(e.challenge),challenges:e.challenges.map(e=>KO(e)),createCredential:e.createCredential,method:WO(e.method),response:GO(e.response)})}function HO(e){return Object.freeze({challenge:KO(e.challenge),credential:e.credential,method:WO(e.method),response:GO(e.response)})}function UO(e){return Object.freeze({...e.challenge?{challenge:KO(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>KO(e))}:{},error:e.error,...e.method?{method:WO(e.method)}:{},response:GO(e.response)})}function WO(e){return JO(Object.assign({},e))}function GO(e){return e instanceof Response?e.body===null?e.clone():new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText}):KO(e)}function KO(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 qO(t)}catch{return JO(e)}}function qO(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))qO(t);return e}function JO(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function YO(e,t){return t?typeof t==`string`?ew(t):t:e}async function XO(e,t){return t?t(e):e}async function ZO(e,t,n,r,i){let a=t.context&&n!==void 0?t.context.parse(n):void 0,o=a===void 0?{challenge:e}:{challenge:e,context:a};return i&&DE(o,i),r&&sE(o,r),t.createCredential(o)}function QO(e){let t=e?.signal;return typeof AbortSignal<`u`&&t instanceof AbortSignal?t:void 0}function $O(e){if(typeof Response<`u`&&e instanceof Response&&e.url)return new URL(e.url)}function ek(){return Y.string().check(Y.regex(tk,`Invalid URI or path`))}var tk,nk,rk,ik,ak,ok,sk,ck,lk,uk=z((()=>{xS(),tk=/^([a-zA-Z][a-zA-Z\d+.-]*:\/\/\S+|\/\S*)$/,nk=new Set([`amount`,`currency`,`description`,`intent`,`method`]),rk=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())}),ik=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(rk).check(Y.minLength(1)))}).check(Y.refine(e=>e.offers===void 0||Object.keys(e).every(e=>e===`offers`||!nk.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`&&(nk.has(n)||r!==void 0)&&(t[n]=r);return{offers:[t]}})),ak=Y.looseObject({apiReference:Y.optional(ek()),homepage:Y.optional(ek()),llms:Y.optional(ek())}),ok=Y.looseObject({categories:Y.optional(Y.array(Y.string())),docs:Y.optional(ak)}),sk=Y.looseObject({"x-payment-info":Y.optional(ik),requestBody:Y.optional(Y.unknown()),responses:Y.optional(Y.record(Y.string(),Y.unknown())),summary:Y.optional(Y.string())}),ck=Y.looseObject({delete:Y.optional(sk),get:Y.optional(sk),head:Y.optional(sk),options:Y.optional(sk),patch:Y.optional(sk),post:Y.optional(sk),put:Y.optional(sk),trace:Y.optional(sk)}),lk=Y.looseObject({openapi:Y.string(),info:Y.looseObject({title:Y.string(),version:Y.string()}),"x-service-info":Y.optional(ok),paths:Y.optional(Y.record(Y.string(),ck))})}));uk();function dk(e){let t=[],n=lk.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=ik.safeParse(o);if(!s.success){for(let e of s.error.issues){let n=e.path.length>0?`.${e.path.map(String).join(`.`)}`:``;t.push({message:e.message,path:`${a}.x-payment-info${n}`,severity:`error`})}continue}let c=n.responses;(!c||!(`402`in c))&&t.push({message:`Operation with x-payment-info MUST have a 402 response`,path:`${a}.responses`,severity:`error`});let l=r.toUpperCase();!n.requestBody&&(l===`POST`||l===`PUT`||l===`PATCH`)&&t.push({message:`Operation with x-payment-info has no requestBody`,path:a,severity:`warning`})}return t}const fk=`2026-07-29.preview`;function pk(e){let{[mk]:t,[hk]:n,[_k]:r,[gk]:i,...a}=e??{};return Object.keys(a).length?a:void 0}var mk,hk,gk,_k,vk=z((()=>{mk=`_mpp_nonce`,hk=`_mppx_nonce`,gk=`_mppx_expiry_grace`,_k=`_mppx_identity`}));function yk(e){return e}function bk(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,async createCredential(e){return OS(e.challenge),i.call(this,e)}}}var xk=z((()=>{sC()}));function Sk(e,t){return Ye.resolve(e).toLowerCase()===Ye.resolve(t).toLowerCase()}var Ck=z((()=>{}));function wk(e){return Number.isInteger(e)&&e>0&&e<Lk}function Tk(e,t){return wk(t)?e===!0||(e?.includes(t)??!1):!1}function Ek(e){return Ve.zonePortal(e)}function Dk(e){if(e>=2**32)return e%2**32;if(e>142431e4&&e<142432e4)return e-142431e4;if(e>4217e5&&e<42171e4)return e-4217e5;throw Error(`Cannot derive a Zone ID from chain ID ${e}. Pass \`zoneId\`.`)}function Ok(e){if(e>=2**32)return Math.floor(e/2**32);if(e>142431e4&&e<142432e4)return 42431;if(e>4217e5&&e<42171e4)return 4217}function kk(e){return j.keccak256(k.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function Ak(e,t){let{blockNumber:n,sender:r,transactionHash:i}=t,a=t=>je(e,{abi:Re.zoneOutbox,address:Ve.zoneOutbox,blockNumber:t,functionName:`lastFallbackNonce`}),[o,s]=await Promise.all([a(n-1n),a(n)]);if(s<=o)throw Error(`Zone withdrawal transaction ${i} did not request a withdrawal from the outbox.`);if(s-o>Pk)throw Error(`Zone withdrawal transaction ${i} has ${s-o} candidate sender tags, more than ${Pk}.`);let c=[];for(let e=o+1n;e<=s;e++)c.push(kk({fallbackNonce:e,sender:r,transactionHash:i}));return c}async function jk(e,t){let{senderTags:n,timeoutMs:r=Mk}=t;if(!Number.isFinite(r)||r<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);if(n.length===0)throw Error(`Zone settlement needs at least one sender tag.`);let i=await Oe(e,{cacheTime:0}),a=i>Nk?i-Nk:0n,o=Date.now()+r;for(;;){if(a<=i){let[r]=await ke(e,{address:t.portal,event:Ik,args:{senderTag:[...n],...t.to?{to:t.to}:{}},fromBlock:a,toBlock:i});if(r?.transactionHash&&r.args.senderTag)return{hash:r.transactionHash,senderTag:r.args.senderTag};a=i+1n}if(Date.now()+Fk>o)throw Error(`Zone withdrawal ${n.join(` or `)} did not settle on Tempo within ${r}ms.`);await new Promise(e=>setTimeout(e,Fk)),i=await Oe(e,{cacheTime:0})}}var Mk,Nk,Pk,Fk,Ik,Lk,Rk=z((()=>{Mk=6e4,Nk=7200n,Pk=64n,Fk=500,Ik=se({abi:Re.zonePortal,name:`WithdrawalProcessed`}),Lk=4217e5,Ek(0).slice(0,-16).toLowerCase()}));function zk(e){return Y.refine(e=>{let{amount:t,decimals:n}=e;return me(t,n)>0n},e)}function Bk(e){let{periodCount:t,periodUnit:n}=e;try{let e=Wk[n];return e!==void 0&&BigInt(t)*e<=Uk}catch{return!1}}var Vk,Hk,Uk,Wk,Gk,Kk,qk,Jk,Yk,Xk,Zk,Qk,$k,eA=z((()=>{Gx(),xk(),xS(),Rk(),Vk=[`push`,`pull`],Hk=Y.object({amount:dS(),memo:Y.optional(_S()),recipient:Y.pipe(Y.string(),Y.transform(e=>e))}),Uk=(1n<<64n)-1n,Wk={dev_second:1n,day:86400n,week:604800n},Gk=Y.pipe(gS(),Y.transform(e=>e.toLowerCase())),Kk=Y.object({accessKeyAddress:Gk,keyType:Y.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:Y.optional(Y.pipe(Y.string().check(Y.regex(/^0x[0-9a-fA-F]{120}$/)),Y.transform(e=>e)))}),qk=Y.object({accessKey:Y.optional(Kk),chainId:Y.optional(Y.number())}),Jk=pS(`subscriptionExpires must be a valid date`).check(Y.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),Yk=Y.enum([`dev_second`,`day`,`week`]),Xk=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)<=Uk}catch{return!1}},`periodCount exceeds uint64`)),Zk=yk({name:`tempo`,intent:`charge`,schema:{credential:{payload:Y.discriminatedUnion(`type`,[Y.object({hash:_S(),type:Y.literal(`hash`)}),Y.object({signature:yS(),type:Y.literal(`transaction`)}),Y.object({signature:yS(),type:Y.literal(`proof`)}),Y.object({hash:_S(),senderTag:_S(),type:Y.literal(`zone`),zoneId:Y.number().check(Y.refine(wk,`Invalid Zone ID`))})])},request:Y.pipe(Y.object({machineTokenEnabled:Y.optional(Y.boolean()),amount:dS(),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(Y.never()),recipient:Y.optional(Y.string()),splits:Y.optional(Y.array(Hk).check(Y.minLength(1),Y.maxLength(10))),supportedModes:Y.optional(Y.array(Y.enum(Vk)).check(Y.minLength(1))),zones:Y.optional(Y.union([Y.literal(!0),Y.array(Y.number().check(Y.refine(wk,`Invalid Zone ID`))).check(Y.minLength(1))]))}).check(Y.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=me(e,t),i=n.reduce((e,n)=>e+me(n.amount,t),0n);return n.every(e=>me(e.amount,t)>0n)&&i<r},`Invalid splits`)),Y.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,zones:c,...l})=>({...l,amount:me(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:me(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),Qk=yk({name:`tempo`,intent:`session`,schema:{credential:{payload:Y.discriminatedUnion(`action`,[Y.object({action:Y.literal(`open`),authorizedSigner:Y.optional(Y.string()),channelId:_S(),cumulativeAmount:dS(),descriptor:Y.optional(Y.custom()),signature:yS(),transaction:yS(),type:Y.literal(`transaction`)}),Y.object({action:Y.literal(`topUp`),additionalDeposit:dS(),channelId:_S(),descriptor:Y.optional(Y.custom()),transaction:yS(),type:Y.literal(`transaction`)}),Y.object({action:Y.literal(`voucher`),channelId:_S(),cumulativeAmount:dS(),descriptor:Y.optional(Y.custom()),signature:yS()}),Y.object({action:Y.literal(`close`),channelId:_S(),closeSignature:yS(),cumulativeAmount:dS(),descriptor:Y.optional(Y.custom()),signature:yS()})])},request:Y.pipe(Y.object({amount:dS(),chainId:Y.optional(Y.number()),channelId:Y.optional(_S()),configurableVouchers:Y.optional(Y.boolean()),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(gS()),minVoucherDelta:Y.optional(dS()),operator:Y.optional(gS()),recipient:Y.optional(Y.string()),sessionProtocol:Y.optional(Y.enum([Wx.v2,Wx.v1])),sessionSnapshot:Y.optional(Y.custom()),suggestedDeposit:Y.optional(dS()),unitType:Y.string()}).check(Y.refine(({amount:e,decimals:t})=>me(e,t)>0n,`Session amount must be greater than 0`)),Y.transform(({amount:e,chainId:t,channelId:n,configurableVouchers:r,decimals:i,escrowContract:a,feePayer:o,feeToken:s,minVoucherDelta:c,operator:l,sessionProtocol:u,sessionSnapshot:d,suggestedDeposit:f,...p})=>({...p,amount:me(e,i).toString(),...f?{suggestedDeposit:me(f,i).toString()}:{},methodDetails:{escrowContract:a,...n!==void 0&&{channelId:n},...c!==void 0&&{minVoucherDelta:me(c,i).toString()},...t!==void 0&&{chainId:t},...o!==void 0&&{feePayer:o},...s!==void 0&&{feeToken:s},...l!==void 0&&{operator:l},...r!==void 0&&{configurableVouchers:r},...u!==void 0&&{[Ux.sessionProtocol]:u},...d!==void 0&&{[Ux.sessionSnapshot]:d}}})))}}),$k=yk({name:`tempo`,intent:`subscription`,schema:{credential:{payload:Y.object({signature:yS(),type:Y.literal(`keyAuthorization`)})},request:Y.pipe(Y.object({amount:dS(),accessKey:Y.optional(Kk),chainId:Y.optional(Y.number()),currency:Gk,decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),methodDetails:Y.optional(qk),periodCount:Xk,periodUnit:Yk,recipient:Gk,subscriptionExpires:Jk}).check(zk(`Subscription amount must be greater than 0`),Y.refine(Bk,`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:me(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}})}));function tA(e){return e>=0n&&e<=bA}function nA(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return tA(t)?t:void 0}function rA(e){return iA(e),e}function iA(e){if(!tA(e))throw Error(`Value ${e} is outside uint96 bounds.`)}function aA(e){return typeof e==`object`&&!!e}function oA(e){return typeof e==`string`&&xA.has(e)}function sA(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!oA(t.action))}function cA(e,t=`No session credential context available.`){if(!sA(e))throw Error(t);return e}function lA(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function uA(e){return aA(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function dA(e){return aA(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 fA(e){let t=te.toString(e),n=JSON.parse(t);if(!dA(n))throw Error(`Invalid session receipt.`);return n}function pA(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function mA(e){let t=`message`,n=[];for(let r of e.split(`
230
230
  `))r.startsWith(`event: `)?t=r.slice(7).trim():r.startsWith(`data: `)?n.push(r.slice(6)):r===`data:`&&n.push(``);if(n.length===0)return null;let r=n.join(`
231
- `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=AO(r);return TO(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=AO(r);return EO(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function AO(e){try{return JSON.parse(e)}catch{return null}}function jO(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function MO(){return JSON.stringify({mpp:`payment-close-request`})}function NO(e){let t=PO(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`&&EO(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`&&TO(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&EO(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function PO(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}var FO,IO,LO,RO=R((()=>{FO=(1n<<96n)-1n,IO=new Set([`open`,`topUp`,`voucher`,`close`]),LO=`0x4d50500000000000000000000000000000000000`}));function zO(e){return KO.encode(e)}function BO(e){return KO.decode(e)}var VO,HO,UO,WO,GO,KO,qO=R((()=>{iT(),yS(),VO=Y.custom(e=>typeof e==`string`&&ue(e,{strict:!1})),HO=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),UO=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),WO=Y.object({authorizedSigner:VO,expiringNonceHash:HO,operator:VO,payee:VO,payer:VO,salt:HO,token:VO}),GO=Y.object({acceptedCumulative:Y.string(),chainId:Y.number(),channelId:HO,closeRequestedAt:Y.optional(Y.string()),deposit:Y.string(),descriptor:WO,escrow:VO,highestVoucher:Y.optional(Y.object({channelId:HO,cumulativeAmount:Y.string(),signature:UO})),requiredCumulative:Y.string(),settled:Y.string(),spent:Y.string(),units:Y.optional(Y.number())}),KO=nT(GO)}));function JO(e){return{status:`active`,...e}}function YO(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?ek(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?ek(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:QO(e.challengeId,t.snapshot),effects:[]}:ek(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?ek(e,t):{state:fk({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:$O(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:ek(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?ek(e,t):{state:hk(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?ZO({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):ek(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:ek(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?ek(e,t):{state:$O(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}]}:ek(e,t);case`settled`:return e.status===`settling`?{state:$O(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:ek(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:ek(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:ek(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?ek(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`?ek(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function XO(e,t){let n=YO(e.state,t);return e.state=n.state,n}function ZO(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 QO(e,t){return JO({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function $O(e,t,n,r){return JO({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function ek(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function tk(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function nk(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`);tk({cumulativeAmount:i,maxVoucherCumulative:n}),tk({cumulativeAmount:a,maxVoucherCumulative:n})}function rk(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;nk({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function ik(e,t){return typeof e==`bigint`?e:he(e,t)}function ak(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(sk(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 ok(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;tk({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 sk(e,t){tk({cumulativeAmount:e,maxVoucherCumulative:t??null})}function ck(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 lk(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function uk(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!gO(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>lk({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function dk(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=_O(r),s=_O(a.spent);return o===void 0||s===void 0||!gO(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function fk(e){return JO({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 pk(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:xk}}function mk(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=rk({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&XO(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function hk(e,t){return JO({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function gk(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=_O(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 _k(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 YO(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function vk(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 yk(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 bk(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(MO()),e.waitForCloseReady()))(),a=BigInt(i.spent);uk({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=>dk({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(jO(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}var xk,Sk=R((()=>{RO(),qO(),xk={status:`idle`}}));function Ck(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=cA.CLOSED,r=null}if(a.type===`open`&&(i=cA.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 wk(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function Tk(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=ik(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 Ek(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:hk(s,u)}:i?{channel:u,state:fk({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function Dk(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=wk(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,headers:e.headers,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative,...e.signal?{signal:e.signal}:{}});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:vO(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function Ok(e){return e.method===Vx.tempo&&e.intent===Hx.session}function kk(e){return Ok(e)&&zx(e.request.methodDetails,Ux.sessionProtocol)===Wx.v2}function Ak(e){return zx(e.request.methodDetails,Ux.sessionSnapshot)}function jk(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return Lw({...t,redirect:`manual`,headers:{...XT(i),...XT(t?.headers)}},US(r),n)}function Mk(e){return e instanceof Request||typeof e==`object`&&!!e&&!(e instanceof URL)&&typeof e.url==`string`&&typeof e.method==`string`&&typeof e.clone==`function`}function Nk(e){try{let t=typeof location>`u`?void 0:location.href,n=Mk(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function Pk(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function Fk(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 Ik(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);if(t.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let r=await Lk({challenge:e.challenge,context:{action:`topUp`,...e.autoSwap===void 0?{}:{autoSwap:e.autoSwap},channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,headers:e.headers,input:e.input,signal:e.signal}).catch(async n=>{throw n instanceof dA&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(q.paymentReceipt);return i?DO(i):void 0}async function Lk(e){let t=async t=>{e.signal?.throwIfAborted();let n=await e.createSessionCredential(t,e.context);e.signal?.throwIfAborted();let r=new AbortController,i=()=>r.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,i,{once:!0});let a=setTimeout(()=>r.abort(new DOMException(`Session management request timed out; payment outcome unknown`,`TimeoutError`)),3e4),o,s=new Promise((e,t)=>{o=()=>t(r.signal.reason),r.signal.addEventListener(`abort`,o,{once:!0})});try{return await Promise.race([e.fetch(Nk(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:sA(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new dA(t):t}finally{clearTimeout(a),e.signal?.removeEventListener(`abort`,i),r.signal.removeEventListener(`abort`,o)}},n=await t(e.challenge);if(n.status!==402)return n;let r=IS(n).find(kk);return r?t(r):n}async function Rk(e){let t=zk({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,headers:e.init?.headers,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,signal:e.init?.signal??(e.input instanceof Request?e.input.signal:void 0)});let s=e.getChannel();if(!s?.descriptor||s.channelId!==i.channelId)return;let c=s.cumulativeAmount>a?s.cumulativeAmount:a,l=()=>e.restoreCumulative(i.channelId,o),u;try{let t=await e.createSessionCredential(r,{action:`voucher`,channelId:i.channelId,descriptor:s.descriptor,cumulativeAmountRaw:c.toString()});u=await e.fetch(e.input,jk(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(q.paymentReceipt)&&await l(),u}function zk(e){let t=IS(e.response).find(kk);if(!t)return;let n=Ak(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function Bk(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=Mk(e.lastUrl)?e.lastUrl:void 0,i=r?{cache:r.cache,credentials:r.credentials,integrity:r.integrity,keepalive:r.keepalive,mode:r.mode===`navigate`?`same-origin`:r.mode,referrer:r.referrer,referrerPolicy:r.referrerPolicy}:void 0,a=async(a,o=!1)=>{t=a,n=(o?e.resolveSignedCloseAmount?.(a):void 0)??e.signedCloseAmount;let s=await e.createSessionCredential(a,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(r?Nk(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:sA(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=IS(o).find(kk);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await Fk(o),t=o.headers.get(q.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${q.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(q.paymentReceipt);if(!s)return;let c=DO(s);if(!c.txHash||!j.validate(c.txHash,{strict:!0})||j.size(c.txHash)!==32||!dk({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:0n,receipt:c}))throw Error(`Session close response included a mismatched payment receipt.`);return c}async function Vk(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...XT(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!OO(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),Hk(e,c,{onReceipt:r,signal:o},n,s.headers)}function Hk(e,t,n,r,i){if(!OO(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return Uk({onNeedVoucher:t=>Jk({challenge:a,driver:r,headers:i,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*Uk(e){for await(let t of Wk(e))t.data!==void 0&&(yield t.data)}async function*Wk(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=Gk(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=kO(i.replace(/\r\n|\r/g,`
232
- `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function Gk(e,t){for(let n=0;n<e.length;n++){let r=Kk(e,n,t);if(!r)continue;let i=Kk(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function Kk(e,t,n){return e[t]===`
231
+ `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=hA(r);return uA(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=hA(r);return dA(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function hA(e){try{return JSON.parse(e)}catch{return null}}function gA(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function _A(){return JSON.stringify({mpp:`payment-close-request`})}function vA(e){let t=yA(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`&&dA(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`&&uA(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&dA(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function yA(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}var bA,xA,SA,CA=z((()=>{bA=(1n<<96n)-1n,xA=new Set([`open`,`topUp`,`voucher`,`close`]),SA=`0x4d50500000000000000000000000000000000000`}));function wA(e){return jA.encode(e)}function TA(e){return jA.decode(e)}var EA,DA,OA,kA,AA,jA,MA=z((()=>{NT(),xS(),EA=Y.custom(e=>typeof e==`string`&&le(e,{strict:!1})),DA=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),OA=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),kA=Y.object({authorizedSigner:EA,expiringNonceHash:DA,operator:EA,payee:EA,payer:EA,salt:DA,token:EA}),AA=Y.object({acceptedCumulative:Y.string(),chainId:Y.number(),channelId:DA,closeRequestedAt:Y.optional(Y.string()),deposit:Y.string(),descriptor:kA,escrow:EA,highestVoucher:Y.optional(Y.object({channelId:DA,cumulativeAmount:Y.string(),signature:OA})),requiredCumulative:Y.string(),settled:Y.string(),spent:Y.string(),units:Y.optional(Y.number())}),jA=jT(AA)}));function NA(e){return{status:`active`,...e}}function PA(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?zA(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?zA(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:LA(e.challengeId,t.snapshot),effects:[]}:zA(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?zA(e,t):{state:ZA({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:RA(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:zA(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?zA(e,t):{state:ej(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?IA({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):zA(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:zA(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?zA(e,t):{state:RA(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}]}:zA(e,t);case`settled`:return e.status===`settling`?{state:RA(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:zA(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:zA(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:zA(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?zA(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`?zA(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function FA(e,t){let n=PA(e.state,t);return e.state=n.state,n}function IA(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 LA(e,t){return NA({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function RA(e,t,n,r){return NA({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function zA(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function BA(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function VA(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`);BA({cumulativeAmount:i,maxVoucherCumulative:n}),BA({cumulativeAmount:a,maxVoucherCumulative:n})}function HA(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;VA({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function UA(e,t){return typeof e==`bigint`?e:me(e,t)}function WA(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(KA(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 GA(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;BA({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 KA(e,t){BA({cumulativeAmount:e,maxVoucherCumulative:t??null})}function qA(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 JA(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function YA(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!tA(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>JA({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function XA(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=nA(r),s=nA(a.spent);return o===void 0||s===void 0||!tA(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function ZA(e){return NA({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 QA(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:oj}}function $A(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=HA({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&FA(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function ej(e,t){return NA({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function tj(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=nA(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 nj(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 PA(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function rj(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 ij(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 aj(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(_A()),e.waitForCloseReady()))(),a=BigInt(i.spent);YA({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=>XA({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(gA(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}var oj,sj=z((()=>{CA(),MA(),oj={status:`idle`}}));function cj(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=qj.CLOSED,r=null}if(a.type===`open`&&(i=qj.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 lj(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function uj(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=UA(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 dj(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:ej(s,u)}:i?{channel:u,state:ZA({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function fj(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=lj(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,headers:e.headers,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative,...e.signal?{signal:e.signal}:{}});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:rA(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function pj(e){return e.method===Vx.tempo&&e.intent===Hx.session}function mj(e){return pj(e)&&zx(e.request.methodDetails,Ux.sessionProtocol)===Wx.v2}function hj(e){return zx(e.request.methodDetails,Ux.sessionSnapshot)}function gj(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return iT({...t,redirect:`manual`,headers:{...OD(i),...OD(t?.headers)}},GS(r),n)}function _j(e){return e instanceof Request||typeof e==`object`&&!!e&&!(e instanceof URL)&&typeof e.url==`string`&&typeof e.method==`string`&&typeof e.clone==`function`}function vj(e){try{let t=typeof location>`u`?void 0:location.href,n=_j(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function yj(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function bj(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 xj(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);if(t.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let r=await Sj({challenge:e.challenge,context:{action:`topUp`,...e.autoSwap===void 0?{}:{autoSwap:e.autoSwap},channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,headers:e.headers,input:e.input,signal:e.signal}).catch(async n=>{throw n instanceof Xj&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(q.paymentReceipt);return i?fA(i):void 0}async function Sj(e){let t=async t=>{e.signal?.throwIfAborted();let n=await e.createSessionCredential(t,e.context);e.signal?.throwIfAborted();let r=new AbortController,i=()=>r.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,i,{once:!0});let a=setTimeout(()=>r.abort(new DOMException(`Session management request timed out; payment outcome unknown`,`TimeoutError`)),3e4),o,s=new Promise((e,t)=>{o=()=>t(r.signal.reason),r.signal.addEventListener(`abort`,o,{once:!0})});try{return await Promise.race([e.fetch(vj(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:Kj(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new Xj(t):t}finally{clearTimeout(a),e.signal?.removeEventListener(`abort`,i),r.signal.removeEventListener(`abort`,o)}},n=await t(e.challenge);if(n.status!==402)return n;let r=RS(n).find(mj);return r?t(r):n}async function Cj(e){let t=wj({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,headers:e.init?.headers,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,signal:e.init?.signal??(e.input instanceof Request?e.input.signal:void 0)});let s=e.getChannel();if(!s?.descriptor||s.channelId!==i.channelId)return;let c=s.cumulativeAmount>a?s.cumulativeAmount:a,l=()=>e.restoreCumulative(i.channelId,o),u;try{let t=await e.createSessionCredential(r,{action:`voucher`,channelId:i.channelId,descriptor:s.descriptor,cumulativeAmountRaw:c.toString()});u=await e.fetch(e.input,gj(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(q.paymentReceipt)&&await l(),u}function wj(e){let t=RS(e.response).find(mj);if(!t)return;let n=hj(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function Tj(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=_j(e.lastUrl)?e.lastUrl:void 0,i=r?{cache:r.cache,credentials:r.credentials,integrity:r.integrity,keepalive:r.keepalive,mode:r.mode===`navigate`?`same-origin`:r.mode,referrer:r.referrer,referrerPolicy:r.referrerPolicy}:void 0,a=async(a,o=!1)=>{t=a,n=(o?e.resolveSignedCloseAmount?.(a):void 0)??e.signedCloseAmount;let s=await e.createSessionCredential(a,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(r?vj(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:Kj(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=RS(o).find(mj);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await bj(o),t=o.headers.get(q.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${q.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(q.paymentReceipt);if(!s)return;let c=fA(s);if(!c.txHash||!M.validate(c.txHash,{strict:!0})||M.size(c.txHash)!==32||!XA({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:0n,receipt:c}))throw Error(`Session close response included a mismatched payment receipt.`);return c}async function Ej(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...OD(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!pA(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),Dj(e,c,{onReceipt:r,signal:o},n,s.headers)}function Dj(e,t,n,r,i){if(!pA(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return Oj({onNeedVoucher:t=>Nj({challenge:a,driver:r,headers:i,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*Oj(e){for await(let t of kj(e))t.data!==void 0&&(yield t.data)}async function*kj(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=Aj(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=mA(i.replace(/\r\n|\r/g,`
232
+ `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function Aj(e,t){for(let n=0;n<e.length;n++){let r=jj(e,n,t);if(!r)continue;let i=jj(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function jj(e,t,n){return e[t]===`
233
233
  `?1:e[t]===`\r`?e[t+1]===`
234
- `?2:t+1===e.length&&!n?0:1:0}function qk(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=Wk({...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 Jk(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await Dk({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,headers:e.headers,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await Lk({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,headers:e.headers,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function Yk(e){let t=new URL(e.input.toString()),n=Pk(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=IS(r).find(kk);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 Xk(e){e.signal?.throwIfAborted();let t=await Yk(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function Zk(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:aC(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:wO(t)}}function Qk(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function $k(e){if(!Qk(e))return`received mismatched payment-close-ready frame`;let t=_O(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 eA(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!Qk(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!dk({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function tA(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=r?.signal;o?.throwIfAborted();let s=new i(a,r?.protocols),c=Zk({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=Ck(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===cA.CONNECTING||s.readyState===cA.OPEN)&&s.close(lA,t)},d=()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),s.close()};s.addEventListener(`close`,t=>{o?.removeEventListener(`abort`,d),c.socket=null,c.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),l.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),s.addEventListener(`error`,()=>{l.emit(`error`,{type:`error`})}),s.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await rA({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await nA(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(jO(n)),await e.waitForReceipt(),l.socket}function nA(e,t,n,r){return new Promise((i,a)=>{let o=()=>{e.removeEventListener(`open`,s),e.removeEventListener(`error`,c),e.removeEventListener(`close`,c),r?.removeEventListener(`abort`,l)},s=()=>{o(),t(`open`,{type:`open`}),i()},c=()=>{o(),a(Error(`WebSocket connection to ${n} failed to open.`))},l=()=>{o(),a(r?.reason)};e.addEventListener(`open`,s,{once:!0}),e.addEventListener(`error`,c,{once:!0}),e.addEventListener(`close`,c,{once:!0}),r?.addEventListener(`abort`,l,{once:!0}),r?.aborted&&l()})}async function rA(e){let t=NO(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`:iA(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 aA(e,t.data);return;case`payment-receipt`:oA(e,t.data);return}}function iA(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=$k({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 aA(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+uA&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await Dk({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:n,event:t,expectedChannelId:e.socketState.channelId,getChannel:e.driver.getChannel,input:e.driver.httpUrl,signal:e.driver.options?.signal,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(jO(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function oA(e,t){let n=eA({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)}function sA(e,t,n,r){let i=US(e),a=new Headers;if(i.toLowerCase()!==q.authorization.toLowerCase()){let e=new Headers(r).get(q.authorization)??(n instanceof Request?n.headers.get(q.authorization):null);e&&!e.startsWith(`${Bx.payment} `)&&a.set(q.authorization,e)}return a.set(i,t),a}var cA,lA,uA,dA,fA=R((()=>{iC(),GE(),zw(),Gx(),mC(),RO(),Sk(),cA={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},lA=3008,uA=5e3,dA=class extends Error{constructor(e){let t=e instanceof Error||e instanceof DOMException?e.message:String(e);super(`${t}; payment outcome unknown`),this.name=`UncertainFundingError`}}})),X,pA=R((()=>{X=(()=>{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:X.underline(t)}\x1b]8;;\x07`:t}}})()})),mA,hA,gA,_A,vA,yA,bA=R((()=>{mA={mainnet:4217,testnet:42431},hA={ousd:Xe(mA.mainnet).address,usdc:F(Qe(mA.mainnet).address),pathUsd:Ze(mA.mainnet).address},gA={[mA.mainnet]:hA.usdc,[mA.testnet]:hA.pathUsd},_A=Object.freeze({[mA.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[mA.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})}),vA=`https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217`,mA.mainnet,mA.testnet,yA={[mA.mainnet]:`https://rpc.tempo.xyz`,[mA.testnet]:`https://rpc.moderato.tempo.xyz`}})),xA=at({chainName:()=>RA,confirm:()=>NA,decodeMemo:()=>TA,fetchBalanceLines:()=>HA,fetchTokenInfo:()=>VA,fmtBalance:()=>PA,fmtChallengeValue:()=>EA,fmtProblemValue:()=>DA,fmtRequestValue:()=>wA,isAgentEnvironment:()=>AA,isTempoAccount:()=>jA,isTestnet:()=>BA,link:()=>OA,mainnetTokens:()=>qA,networkRpcUrls:()=>WA,parseMethodOpts:()=>kA,pathUsd:()=>GA,pc:()=>X,printRequestHeaders:()=>SA,printResponseHeaders:()=>CA,prompt:()=>MA,resolveChain:()=>LA,resolveFundingNetwork:()=>IA,resolveRpcUrl:()=>FA,testnetTokens:()=>JA,usdc:()=>KA});function SA(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(`>
235
- `)}function CA(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?`<
234
+ `?2:t+1===e.length&&!n?0:1:0}function Mj(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=kj({...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 Nj(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await fj({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,headers:e.headers,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await Sj({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,headers:e.headers,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function Pj(e){let t=new URL(e.input.toString()),n=yj(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=RS(r).find(mj);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 Fj(e){e.signal?.throwIfAborted();let t=await Pj(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function Ij(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:cC(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:lA(t)}}function Lj(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function Rj(e){if(!Lj(e))return`received mismatched payment-close-ready frame`;let t=nA(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 zj(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!Lj(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!XA({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function Bj(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=r?.signal;o?.throwIfAborted();let s=new i(a,r?.protocols),c=Ij({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=cj(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===qj.CONNECTING||s.readyState===qj.OPEN)&&s.close(Jj,t)},d=()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),s.close()};s.addEventListener(`close`,t=>{o?.removeEventListener(`abort`,d),c.socket=null,c.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),l.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),s.addEventListener(`error`,()=>{l.emit(`error`,{type:`error`})}),s.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await Hj({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await Vj(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(gA(n)),await e.waitForReceipt(),l.socket}function Vj(e,t,n,r){return new Promise((i,a)=>{let o=()=>{e.removeEventListener(`open`,s),e.removeEventListener(`error`,c),e.removeEventListener(`close`,c),r?.removeEventListener(`abort`,l)},s=()=>{o(),t(`open`,{type:`open`}),i()},c=()=>{o(),a(Error(`WebSocket connection to ${n} failed to open.`))},l=()=>{o(),a(r?.reason)};e.addEventListener(`open`,s,{once:!0}),e.addEventListener(`error`,c,{once:!0}),e.addEventListener(`close`,c,{once:!0}),r?.addEventListener(`abort`,l,{once:!0}),r?.aborted&&l()})}async function Hj(e){let t=vA(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`:Uj(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 Wj(e,t.data);return;case`payment-receipt`:Gj(e,t.data);return}}function Uj(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=Rj({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 Wj(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+Yj&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await fj({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:n,event:t,expectedChannelId:e.socketState.channelId,getChannel:e.driver.getChannel,input:e.driver.httpUrl,signal:e.driver.options?.signal,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(gA(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function Gj(e,t){let n=zj({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)}function Kj(e,t,n,r){let i=GS(e),a=new Headers;if(i.toLowerCase()!==q.authorization.toLowerCase()){let e=new Headers(r).get(q.authorization)??(n instanceof Request?n.headers.get(q.authorization):null);e&&!e.startsWith(`${Bx.payment} `)&&a.set(q.authorization,e)}return a.set(i,t),a}var qj,Jj,Yj,Xj,Zj=z((()=>{sC(),DO(),lT(),Gx(),vC(),CA(),sj(),qj={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},Jj=3008,Yj=5e3,Xj=class extends Error{constructor(e){let t=e instanceof Error||e instanceof DOMException?e.message:String(e);super(`${t}; payment outcome unknown`),this.name=`UncertainFundingError`}}})),X,Qj=z((()=>{X=(()=>{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:X.underline(t)}\x1b]8;;\x07`:t}}})()})),$j,eM,tM,nM,rM,iM,aM=z((()=>{$j={mainnet:4217,testnet:42431},eM={ousd:we($j.mainnet).address,usdc:I(Ee($j.mainnet).address),pathUsd:Te($j.mainnet).address},tM={[$j.mainnet]:eM.usdc,[$j.testnet]:eM.pathUsd},nM=Object.freeze({[$j.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[$j.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})}),rM=`https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217`,$j.mainnet,$j.testnet,iM={[$j.mainnet]:`https://rpc.tempo.xyz`,[$j.testnet]:`https://rpc.moderato.tempo.xyz`}})),oM=it({chainName:()=>CM,confirm:()=>vM,decodeMemo:()=>uM,fetchBalanceLines:()=>DM,fetchTokenInfo:()=>EM,fmtBalance:()=>yM,fmtChallengeValue:()=>dM,fmtProblemValue:()=>fM,fmtRequestValue:()=>lM,isAgentEnvironment:()=>hM,isTempoAccount:()=>gM,isTestnet:()=>TM,link:()=>pM,mainnetTokens:()=>MM,networkRpcUrls:()=>kM,parseMethodOpts:()=>mM,pathUsd:()=>AM,pc:()=>X,printRequestHeaders:()=>sM,printResponseHeaders:()=>cM,prompt:()=>_M,resolveChain:()=>SM,resolveFundingNetwork:()=>xM,resolveRpcUrl:()=>bM,testnetTokens:()=>NM,usdc:()=>jM});function sM(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(`>
235
+ `)}function cM(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?`<
236
236
  `:`
237
- `)}function wA(e,t,n){if(UA.has(e)&&typeof t==`string`)return`${t} ${X.dim(`(${PA(BigInt(t),n.tokenSymbol,n.tokenDecimals)})`)}`;if(e===`chainId`&&typeof t==`number`){let e=RA({id:t,name:``});return e?`${t} ${X.dim(`(${e})`)}`:String(t)}return typeof t==`string`&&/^0x[0-9a-fA-F]{40}$/.test(t)?n.explorerUrl?OA(`${n.explorerUrl}/address/${t}`,t):t:typeof t==`string`&&/^https?:\/\//.test(t)?X.link(t,t):String(t)}function TA(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 EA(e,t){if(e===`realm`&&typeof t==`string`)try{let e=new URL(t.includes(`://`)?t:`https://${t}`);return X.link(e.href,t)}catch{}return String(t)}function DA(e){return typeof e==`object`&&e?JSON.stringify(e):String(e)}function OA(e,t){return X.link(e,t)}function kA(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 AA(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 jA(e){return e.startsWith(`tempo:`)}function MA(e){let t=Ye.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.on(`close`,()=>n(void 0)),t.question(`${X.bold(`▸ ${e}:`)} `,e=>{t.close(),n(e.trim()||void 0)})})}function NA(e,t=!1){let n=Ye.createInterface({input:process.stdin,output:process.stderr});return new Promise(r=>{let i=t?`(Y/n)`:`(y/N)`;n.question(`${X.bold(`▸ ${e}`)} ${X.dim(i)} `,e=>{n.close();let i=e.trim().toLowerCase();r(i===``?t:i===`y`)})})}function PA(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?X.dim(X.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):X.dim(t);return`${a?`${o}.${a}`:o} ${s}`}function FA(e,t={}){return e??(t.network?WA[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}function IA(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 LA(e={}){let t=FA(e.rpcUrl,{network:e.network});if(!t)return ye;let{getChainId:n}=await import(`viem/actions`),r=await n(M({transport:I(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 RA(e){return{[ye.id]:`mainnet`,[be.id]:`testnet`}[e.id]??e.name}function zA(e){return typeof e==`bigint`?e:e.amount}function BA(e){return e.id!==ye.id}async function VA(e,t,n,r={}){let{Actions:i}=await import(`viem/tempo`),[a,o]=await Promise.all([i.token.getBalance(e,{account:n,token:t}).then(zA).catch(()=>0n),i.token.getMetadata(e,{token:t}).catch(e=>{if(r.requireDecimals)throw e;return{symbol:t}})]),s={"0x20c0000000000000000000000000000000000000":`PathUSD`,"0x20C000000000000000000000b9537d11c60E8b50":`USDC`}[t]??o.symbol,c=`decimals`in o&&typeof o.decimals==`number`?o.decimals:6;if(r.requireDecimals&&!(`decimals`in o&&typeof o.decimals==`number`))throw Error(`Token decimals are unavailable.`);return{balance:a,symbol:s,decimals:c,token:t}}async function HA(e,t){if(t?.chain){let n=M({chain:t.chain,transport:I(t.rpcUrl)}),r=t.chain.blockExplorers?.default?.url,i=X.dim(`(${RA(t.chain)})`);return BA(t.chain)?(await Promise.all(JA.map(t=>VA(n,t,e)))).filter(e=>e.balance>0n).map(e=>`${PA(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`):(await Promise.all(qA.map(t=>VA(n,t,e)))).map(e=>`${PA(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`)}let n=M({chain:ye,transport:I(FA())}),r=ye.blockExplorers?.default?.url,i=(await Promise.all(qA.map(t=>VA(n,t,e)))).map(e=>PA(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token}));if(t?.includeTestnet!==!1){let t=M({chain:be,transport:I()}),n=be.blockExplorers?.default?.url,r=await Promise.all(JA.map(n=>VA(t,n,e)));for(let e of r)e.balance>0n&&i.push(`${PA(e.balance,e.symbol,e.decimals,{explorerUrl:n,token:e.token})} ${X.dim(`(testnet)`)}`)}return i}var UA,WA,GA,KA,qA,JA,YA=R((()=>{pA(),bA(),UA=new Set([`amount`,`suggestedDeposit`,`minVoucherDelta`]),WA={mainnet:yA[mA.mainnet],testnet:yA[mA.testnet]},GA=`0x20c0000000000000000000000000000000000000`,KA=`0x20C000000000000000000000b9537d11c60E8b50`,qA=[GA,KA],JA=[`0x20c0000000000000000000000000000000000000`,`0x20c0000000000000000000000000000000000001`,`0x20c0000000000000000000000000000000000002`,`0x20c0000000000000000000000000000000000003`]}));function XA(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:cj}function ZA(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function QA(e){return new z({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 $A(e){if(e&&ZA(e,`secret-tool`))throw QA(e)}function ej(e,t){return new Promise(n=>{m.execFile(e,t,{timeout:XA()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function tj(){let e=c.join(process.env.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`mppx`,`default`);return{get(){try{return t.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,n,`utf-8`)},clear(){try{t.unlinkSync(e)}catch{}}}}function nj(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:tj().get())}function rj(e=`main`){let t=sj;return{async list(){let e=x.platform();if(e===`darwin`){let{stdout:e,error:n}=await ej(`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 ej(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if($A(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=x.platform();if(n===`darwin`){let{stdout:n,error:r}=await ej(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await ej(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return $A(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=x.platform();if(r===`darwin`){await ej(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await ej(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=m.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),XA());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(ZA(e,`secret-tool`)?QA(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=x.platform();if(n===`darwin`){await ej(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await ej(`secret-tool`,[`clear`,`service`,t,`account`,e]);$A(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function ij(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=nj(e),i=await rj(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function aj(e){let t=nj(e);if(!process.env.MPPX_PRIVATE_KEY?.trim()&&jA(t))throw new z({code:`UNSUPPORTED_ACCOUNT`,message:`Persistent sessions require an mppx account or MPPX_PRIVATE_KEY.`,exitCode:2});return ij(e).catch(e=>{throw new z({code:`ACCOUNT_NOT_FOUND`,message:e instanceof Error?e.message:`No account found.`,exitCode:69,...e instanceof Error&&{cause:e}})})}async function oj(e){return(await ij(e)).account}var sj,cj,lj=R((()=>{YA(),sj=`mppx`,cj=1e4}));fA(),lj();const uj=[[`ANTIGRAVITY_CLI_ALIAS`,`antigravity`],[`CLAUDECODE`,`claude_code`],[`CLINE_ACTIVE`,`cline`],[`CODEX_SANDBOX`,`codex_cli`],[`CODEX_THREAD_ID`,`codex_cli`],[`CODEX_SANDBOX_NETWORK_DISABLED`,`codex_cli`],[`CODEX_CI`,`codex_cli`],[`CURSOR_AGENT`,`cursor`],[`GEMINI_CLI`,`gemini_cli`],[`OPENCODE`,`open_code`],[`OPENCLAW_SHELL`,`openclaw`],[`CLAUDE_CODE_ENTRYPOINT`,`claude_code`],[`CODEX_INTERNAL_ORIGINATOR_OVERRIDE`,`codex_cli`]];function dj(e=process.env){return uj.find(([t])=>e[t])?.[1]}function fj(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function pj(e,t){let{chainId:n,decimals:r}=t;if(typeof e==`string`)return{address:e,chainId:n,decimals:r};if(fj(e))return e.addresses[n]?e(n):void 0;if(e.chainId===n)return e}function mj(e,t,n={}){let{chainId:r,decimals:i}=n,a=e=>e.toLowerCase()===t.toLowerCase();for(let t of e){if(typeof t==`string`){if(a(t))return{currency:t,decimals:i};continue}if((r===void 0?fj(t)?Object.keys(t.addresses).map(e=>pj(t,{chainId:Number(e)})):[t]:[pj(t,{chainId:r})]).some(e=>e&&a(e.address)))return{currency:t,decimals:t.decimals}}}var hj=R((()=>{}));hj();const gj=Symbol(`mppx.x402.asset`);function _j(e){return{[gj]:!0,address:e.address,chainId:jj(e.network),decimals:e.decimals,network:e.network,transfer:e.transfer}}function vj(e,t){let n=e(t.chainId);return _j({address:n.address,decimals:n.decimals,network:Aj(t.chainId),transfer:Mj(t.transfer,n)})}const yj={USDC:_j({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},bj={USDC:_j({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},xj={USDC:_j({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:_j({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},Sj={USDC:_j({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Cj=[yj,bj,xj,Sj].flatMap(e=>Object.values(e));function wj(e,t){let n=e.toLowerCase();return Cj.find(e=>e.network===t&&e.address.toLowerCase()===n)}function Tj(e){return typeof e!=`object`||!e?!1:e[gj]===!0}const Ej=fj;function Dj(e){return typeof e==`string`}function Oj(e,t){if(Tj(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(typeof e==`string`)return{address:e};let n=pj(e,{chainId:jj(t)});if(n)return{address:n.address,decimals:n.decimals,name:n.name}}function kj(e,t,n){let r=Oj(e,n);return r?F(r.address)===F(t):!1}function Aj(e){return`eip155:${e}`}function jj(e){return Number(e.slice(7))}function Mj(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 Nj=at({base:()=>yj,baseSepolia:()=>bj,celo:()=>xj,celoSepolia:()=>Sj,define:()=>_j,fromToken:()=>vj,isAsset:()=>Tj,isRawAddress:()=>Dj,isToken:()=>Ej,lookup:()=>wj,matches:()=>kj,resolve:()=>Oj,toChainId:()=>jj,toNetwork:()=>Aj}),Pj=at({base:()=>Fj,baseSepolia:()=>Ij,celo:()=>Lj,celoSepolia:()=>Rj});const Fj=8453,Ij=84532,Lj=42220,Rj=11142220;sS();function zj(e){let t=[oS(e.accepted),oS(e.resource),oS(e.extensions)].join(`|`);return ne.sha256(A.fromString(t),{as:`Hex`})}fT(),Iw();async function Bj(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=fw(n);if(Wj(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?Kj(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:F(t.address),nonce:i?.mppx?zj({accepted:r,extensions:i,resource:n.resource}):Jj(),to:F(r.payTo),validAfter:(c-600).toString(),validBefore:(c+r.maxTimeoutSeconds).toString(),value:r.amount},u=await t.signTypedData({domain:{chainId:Uj(r.network),name:o,verifyingContract:F(r.asset),version:s},message:{...l,value:BigInt(l.value),validAfter:BigInt(l.validAfter),validBefore:BigInt(l.validBefore)},primaryType:`TransferWithAuthorization`,types:Hj});return uT({accepted:r,...i?{extensions:i}:{},payload:{authorization:l,signature:u},...n.resource?{resource:n.resource}:{},x402Version:2})}function Vj(e){let t=e.challenge.request,n;try{n=fw(t),Wj(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 Hj={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 Uj(e){return Number(e.slice(hw.length))}function Wj(e,t){let n=Uj(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=>Dj(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=F(t.asset);if(!r.some(n=>kj(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=Gj(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>he(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function Gj(e,t){let n=e.currencies??e.assets,r=F(t.asset),i=n?.find(e=>kj(e,r,t.network)),a=i?Oj(i,t.network):void 0;return a?.decimals===void 0?e.decimals===void 0?wj(r,t.network)?.decimals:e.decimals:a.decimals}function Kj(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:qj()}}}:e}function qj(){return Yj().slice(2)}function Jj(){return Yj()}function Yj(){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(``)}`}yS();const Xj=[`authorization`],Zj=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 Qj=Y.object({chainId:Y.number(),credentialTypes:Y.optional(Y.array(Y.enum(Xj)).check(Y.minLength(1))),decimals:Y.optional(Y.number()),permit2Address:Y.optional(mS()),splits:Y.optional(Y.array(Y.object({amount:Zj,recipient:mS()})))});Y.object({amount:Zj,currency:mS(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),methodDetails:Qj,recipient:mS()});const $j=Y.object({amount:lS(),chainId:Y.number(),currency:mS(),credentialTypes:Y.optional(Y.array(Y.enum(Xj)).check(Y.minLength(1))),decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),permit2Address:Y.optional(mS()),recipient:mS(),splits:Y.optional(Y.array(Y.object({amount:Zj,recipient:mS()})))}),eM=Y.object({from:mS(),nonce:hS(),signature:_S(),to:mS(),type:Y.literal(`authorization`),validAfter:Zj,validBefore:Zj,value:Zj}),tM={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 nM(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function rM(e){return ne.keccak256(A.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function iM(e){return`eip155:${e}`}function aM(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}ID(),yS();const oM=PD({name:`evm`,intent:`charge`,schema:{credential:{payload:eM},request:Y.pipe($j,Y.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...c})=>({...c,amount:he(e,i).toString(),currency:F(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:F(a)}:{},...s?{splits:s}:{}},recipient:F(o)})))}});mC(),zC(),ID(),yS();function sM(e){return FD(oM,{canHandleChallenge({challenge:t}){return!cM(t)||Vj({challenge:t,config:e})},context:Y.object({account:Y.optional(Y.custom())}),async createCredential({challenge:t,context:n}){if(cM(t))return Bj({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(lM(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=uM(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return lC(cC({challenge:t,payload:{from:F(r.address),nonce:rM(t),signature:await r.signTypedData({domain:nM({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:F(r.address),nonce:rM(t),to:F(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:tM}),to:F(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:aM({address:F(r.address),chainId:i.methodDetails.chainId})}))}})}function cM(e){return LC(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function lM(e,t){let n=t.methodDetails.chainId,r=iM(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=>Dj(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=F(t.currency);if(!i.some(t=>kj(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=dM(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>he(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function uM(e,t){let n=e.currencies??e.assets,r=F(t.currency),i=iM(t.methodDetails.chainId),a=n?.find(e=>kj(e,r,i)),o=a?Oj(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;let s=wj(r,i)?.transfer;if(s?.type===`eip3009`)return{name:s.name,version:s.version};throw Error(`EVM authorization requires token name and version.`)}function dM(e,t){let n=e.currencies??e.assets,r=F(t.currency),i=iM(t.methodDetails.chainId),a=n?.find(e=>kj(e,r,i)),o=a?Oj(a,i):void 0;return o?.decimals===void 0?e.decimals===void 0?wj(r,i)?.decimals:e.decimals:o.decimals}function fM(e){return[fM.charge(e)]}(function(e){e.charge=sM,e.assets=Nj,e.chains=Pj})(fM||={});function pM(e){return e}var mM=R((()=>{}));zC(),mM();function hM(){return pM({method:`evm`,supports:e=>e.method===`evm`&&!LC(e),async setup({challenge:e,options:t}){let n=e.request,r=n.methodDetails,i=r?.chainId,a=i?gM(i):void 0,o=n.currency,s=await oj(t.account),c=[...Object.values(yj),...Object.values(bj),...Object.values(xj),...Object.values(Sj)],l=o??``;if(a&&o)try{let e=M({chain:a,transport:I()}),t=await ke(e,{address:o,abi:P,functionName:`symbol`});t&&(l=t)}catch{}return{tokenSymbol:l,tokenDecimals:r?.decimals??6,explorerUrl:a?.blockExplorers?.default?.url,methods:[...fM({account:s,currencies:c})]}}})}function gM(e){return Object.values($e).find(t=>t.id===e)}function _M(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`Decimals must be a non-negative integer.`);if(!/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))throw TypeError(`Value \`${e}\` is not a valid decimal number.`);let n=e.startsWith(`-`),[r=`0`,i=``]=(n?e.slice(1):e).split(`.`),a=i.slice(0,t).padEnd(t,`0`),o=BigInt(`${r||`0`}${a}`);return i.length>t&&i[t]>=`5`&&(o+=1n),n?-o:o}yS();const vM=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)))}),yM=Y.custom(e=>typeof e==`function`),bM=Y.union([vM,yM]);ID(),yS();const xM=PD({name:`stripe`,intent:`charge`,schema:{credential:{payload:Y.object({externalId:Y.optional(Y.string()),spt:Y.string()})},request:Y.pipe(Y.object({amount:lS(),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(bM),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:_M(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});mC(),ID(),yS();function SM(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return FD(xM,{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 lC({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function CM(e){return[SM(e)]}(function(e){e.charge=SM})(CM||={}),Rx(),YA(),mM();function wM(){return pM({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=EM(p.object({paymentMethod:p.string(),secretKey:p.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new z({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:[CM.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=TM(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":OD},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 z({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${e.error.message}`,exitCode:77})}}else throw new z({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&&TM(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function TM(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function EM(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 DM(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 ve(r)}}var OM=R((()=>{}));function kM(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}var AM=R((()=>{}));function jM(e,t={}){return I(e.url,{fetchFn:e.fetch,fetchOptions:{headers:kM(e)},...t})}function MM(e){let{chain:t,getClient:n,remoteFeePayer:r,rpcUrl:i}=e;return n?!t?.serializers&&!r&&!e.requireChain?n:async i=>{let a=await n(i);if(e.requireChain&&(a.chain?.id===void 0||a.chain.id!==i.chainId))throw Error(`Subscription chain mismatch: expected ${i.chainId}, got ${a.chain?.id??`unknown`}.`);let o=a;if(r&&a.transport.key!==`feePayer`){let e=a.request.bind(a),t=He(ie({request:t=>e(t)},{retryCount:0}),jM(r,{retryCount:a.transport.retryCount}))({account:a.account,chain:a.chain,pollingInterval:a.pollingInterval,retryCount:0}),n=N({...t.config,retryCount:0},t.value);o=Object.assign({},a,{request:n.request,transport:{...n.config,...n.value}})}return!t?.serializers||o.chain?.serializers?.transaction?o:Object.assign({},o,{chain:{...t,...i.chainId===void 0?{}:{id:i.chainId},...o.chain,formatters:o.chain?.formatters??t.formatters,prepareTransactionRequest:o.chain?.prepareTransactionRequest??t.prepareTransactionRequest,serializers:o.chain?.serializers?.transaction?o.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?He(I(a),jM(r)):I(a);return M({chain:FM[n]??{...t,id:n},transport:o})}}function NM(e,t){if(t!==void 0&&e.chain?.id!==void 0&&e.chain.id!==t)throw Error(`Chain ID mismatch: expected ${t}, got ${e.chain.id}.`)}function PM(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}var FM,IM=R((()=>{AM(),FM={[ye.id]:ye,[be.id]:be}}));function LM(e){let t=ne.keccak256(A.fromString(e),{as:`Hex`});return j.toBytes(j.slice(t,0,10))}function RM(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(j.toBytes(BM),0),i[4]=VM,i.set(LM(t),5),n&&i.set(LM(n),15),i.set(zM(r),25),j.fromBytes(i)}function zM(e){let t=ne.keccak256(A.fromString(e),{as:`Hex`});return j.toBytes(j.slice(t,0,7))}var BM,VM,HM=R((()=>{BM=j.slice(ne.keccak256(A.fromString(`mpp`),{as:`Hex`}),0,4),VM=1}));async function UM(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t;if(!Number.isFinite(o)||o<0||o>50)throw Error(`Auto-swap slippage must be between 0 and 50 percent.`);if(t.maxAmountIn!==void 0&&t.maxAmountIn<=0n)throw Error(`Auto-swap maxAmountIn must be positive.`);let s=e.chain?.id,c=[];for(let e of a){let t=typeof e==`string`?e:s===void 0?void 0:pj(e,{chainId:s})?.address;!t||LD(t,i)||c.some(e=>LD(e,t))||c.push(t)}let l=await Promise.allSettled([ke(e,{...Re.token.getBalance.call(e,{account:n,token:i}),account:null}),...c.map(t=>ke(e,{...Re.token.getBalance.call(e,{account:n,token:t}),account:null}))]),u=l[0];if(u.status!==`fulfilled`)throw u.reason;let d=u.value;if(d>=r)return;let f=r-d,p=BigInt(Math.round(o*100)),m=t.maxAmountIn??f+f*p/GM;for(let t=0;t<c.length;t++){let n=l[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=c[t];try{let t=await Re.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:f});if(t<=0n||t>m)continue;let n=t+t*p/GM,o=n<m?n:m;if(r>=o)return[Re.token.approve.call(e,{amount:o,spender:ze.stablecoinDex,token:a}),Re.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:f,maxAmountIn:o})]}catch{}}throw new qM({currency:i})}function WM(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...e.fallback===!1?[]:t.filter(t=>!e.tokenIn.some(e=>typeof e==`string`&&LD(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var GM,KM,qM,JM=R((()=>{hj(),RD(),bA(),GM=10000n,KM=[hA.pathUsd,hA.usdc,hA.ousd],qM=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}}}));function YM(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:BigInt(e.amount).toString(),memo:e.memo,recipient:e.recipient}))]}var XM=R((()=>{}));function ZM(e,t,n){t&&(n&&!n.some(e=>LD(e,t))||e.some(e=>LD(e,t))||e.push(t))}async function QM(e,t,n){try{return(await Re.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function $M(e){let t=e.chain?.feeToken;if(t)return Be.toAddress(t);let n=e.chain?.id;return n?gA[n]:void 0}function eN(e){let t=[];return ZM(t,hA.pathUsd),ZM(t,gA[e]),t}async function tN(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])ZM(o,e,n);if(ZM(o,await Re.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),ZM(o,$M(i),n),!a)for(let e of r??[])ZM(o,e,n);for(let e of o)if(await QM(i,t,e))return e;return o[0]}var nN=R((()=>{RD(),bA()}));function rN(e){if(e!==void 0)return _A[e]}function iN(e){let t=rN(e.chainId);return!!t&&ue(e.currency,{strict:!1})&&de(e.currency,t.token)}function aN(e){let t=rN(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let r=BigInt(n.amount),i=n.memo;return{calls:[{data:oe({abi:Ie.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:oe({abi:dN,functionName:`swapTo`,args:[t.token,r,e.currency,n.recipient,i]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:r,memo:i,recipient:n.recipient}]}}async function oN(e,t){let n=aN(t);if(n)try{return await ke(e,Re.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await Te(e,{account:t.account,calls:n.calls}),n)}catch{return}}function sN(e={}){let{address:t,amount:n,chainId:r=mA.mainnet}=e;if(r!==mA.mainnet)return;let i=new URL(vA);if(t&&ue(t,{strict:!1})&&i.searchParams.set(`address`,F(t)),n!==void 0&&n>0n){let e=(n+fN-1n)/fN,t=e%100n,r=(e/100n).toString();i.searchParams.set(`amount`,t===0n?r:`${r}.${t.toString().padStart(2,`0`).replace(/0$/,``)}`)}return i.toString()}async function cN(e,t){let n=rN(t.chainId);if(!n)return;let r=await ke(e,Re.token.getBalance.call(e,{account:t.account,token:n.token})).catch(()=>void 0);return typeof r==`bigint`?r:void 0}async function lN(e,t){let{account:n,amount:r,chainId:i}=t,a=await cN(e,{account:n,chainId:i});if(a===void 0||a>=r)return;let o=e=>`${se(e,6)} MACH`,s=r-a;return{fundingUrl:sN({address:n,amount:s,chainId:i}),reason:`requested ${o(r)}, available ${o(a)}`,shortfall:s}}async function uN(e,t){let n=await lN(e,t);if(n)return new nS({fundingUrl:n.fundingUrl,reason:n.reason})}var dN,fN,pN=R((()=>{rS(),bA(),dN=pe([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]),fN=10n**BigInt(4)}));function mN(e){return{name:`MPP`,version:`3`,chainId:e}}function hN(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function gN(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:mN(n),types:yN,primaryType:vN,message:hN({account:t,challengeId:r,realm:i})}}function _N(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}var vN,yN,bN=R((()=>{vN=`Proof`,yN={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]}}));function xN(e){let t=new Set,n=e;for(;typeof n==`object`&&n&&!t.has(n);){t.add(n);let e=n.data;if(wN(e))return e;let r=e?.data;if(wN(r))return r;n=n.cause}}function SN(e,t){let n=xN(e);if(!n)return;let r=(()=>{try{return ae({abi:TN,data:n})}catch{return}})();if(r?.errorName===`SpendingLimitExceeded`){let n=t.account.accessKeyAddress;return new eS({accessKey:typeof n==`string`?n:void 0,account:t.account.address,cause:e})}if(r?.errorName===`InsufficientBalance`){let[n,i,a]=r.args;return new nS({cause:e,reason:`${t.account.address} holds ${n} of token ${a}, but the payment requires ${i}`})}}async function CN(e,t){try{return await t()}catch(t){throw SN(t,e)??t}}function wN(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{8}/.test(e)}var TN,EN=R((()=>{rS(),TN=[...Ie.accountKeychain.filter(e=>e.type===`error`),...Ie.tip20.filter(e=>e.type===`error`)]}));function DN(e={}){let{clientId:t}=e;if((e.maxAmount!==void 0||e.maxAtomicAmount!==void 0)&&e.currencies===void 0)throw Error(`Tempo charge maxAmount and maxAtomicAmount require currencies.`);for(let t of e.currencies??[])UN(e.maxAmount,typeof t==`string`?e.decimals:t.decimals);let n={maxAmount:e.maxAmount,maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=MM({chain:ye,getClient:e.getClient,rpcUrl:yA}),i=DM({account:e.account});FN(e.zone);let a=new Map,o=FD(fO,{canHandleChallenge({challenge:t}){try{return WN(e,n,t.request),!0}catch{return!1}},context:GN,async createCredential(o){let{challenge:s,context:c}=o;WN(e,n,s.request);let l=s.request.methodDetails?.chainId,u=l??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),d=await r({chainId:u});NM(d,u);let f=u??d.chain?.id;if(PM(e.allowedChainIds,f),f===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");l===void 0&&WN(e,n,s.request,f);let{request:p}=s,{amount:m,methodDetails:h}=p,g=h?.supportedModes??[`pull`,`push`],_=e.zone?.client.chain,v=e.zone?e.zone.zoneId??HD(_?.id??0):void 0,y=_?.sourceId??(_?UD(_.id):void 0),b=c?.mode??e.mode;if(BigInt(m)>0n&&e.zone&&v!==void 0&&y===f&&g.includes(`push`)&&(b===void 0||b===`push`)&&BD(h?.zones,v)&&!h?.splits){let r={assertFee:t=>WN(e,n,p,f,t),challenge:s,clientId:t,client:d,origin:PN(MT(o)),pending:a,zone:e.zone,zoneId:v},i=jN(r);if(i)return MN(r,i);if(s.expires&&hC(s.expires,s.id),IN(s.expires,e.zone.settlementTimeoutMs))return AN(r)}let x=i(d,c),S=async t=>await e.resolveAccount?.({account:x,chainId:f,operation:t})??x;if(BigInt(m)===0n){let e=await S({kind:`signPaymentProof`});return lC({challenge:s,payload:{signature:await Pe(d,{account:e,...gN({account:e.address,chainId:f,challengeId:s.id,realm:s.realm})}),type:`proof`},source:_N({address:e.address,chainId:f})})}let C=p.currency,w=iN({chainId:f,currency:C}),T=RM({challengeId:s.id,clientId:t,serverId:s.realm}),ee=YM({amount:m,methodDetails:{...h,memo:T},recipient:p.recipient}),te=ee.map(e=>Re.token.transfer.call(d,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:C})),E=WM(c?.autoSwap??e.autoSwap,KM),D=h?.machineTokenEnabled===!0?aN({chainId:f,currency:C,transfers:ee}):void 0,O=x,k,A=!1;if(D){let e=await(async()=>{try{return await S({calls:D.calls,kind:`executeCalls`})}catch{return}})();e&&(k=await oN(d,{account:e.address,chainId:f,currency:C,transfers:ee}),k?O=e:A=!0)}let ne;if(!k&&(O=await S({kind:`executeCalls`,...E?{}:{calls:te}}),ne=E?await UM(d,{account:O.address,amountOut:BigInt(m),tokenOut:C,tokenIn:E.tokenIn,slippage:E.slippage,maxAmountIn:E.maxAmountIn}):void 0,A&&!E)){let e=await ON(d,{account:O.address,amount:BigInt(m),chainId:f,currency:C});if(e)throw e}let j=k?.calls??[...ne??[],...te],re=eN(f),M=(c?.feeToken??e.feeToken)||(k||w?await tN({account:O.address,allowedTokens:re,candidateTokens:re,client:d,prioritizeCandidates:!0}):void 0),N=(()=>{let t=c?.mode??e.mode;if(t){if(!g.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=O.type===`json-rpc`?`push`:`pull`;return g.includes(n)?n:g[0]})(),ie=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!s.expires)return e;let t=Math.floor(new Date(s.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(N===`push`){let{receipts:e}=O.type===`local`?{receipts:[await CN({account:O},()=>Me(d,{account:O,calls:j,...M?{feeToken:M}:{},nonceKey:`expiring`,validBefore:ie}))]}:await Ae(d,{account:O,...M?{capabilities:{feeToken:M}}:{},calls:j,experimental_fallback:j.length===1,forceAtomic:j.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return lC({challenge:s,payload:{hash:t,type:`hash`},source:_N({address:O.address,chainId:f})})}let ae=()=>{if(h?.feePayer!==!0)return;let e=15e3,t=s.expires?new Date(s.expires).getTime():1/0,n=Date.now();if(!(t-n>=e))throw Error(`Sponsored challenge expires in less than 15 seconds; the fee payer would reject the transaction. Request a new challenge.`);if(!(ie*1e3-n>=e))throw Error(`Sponsored transaction preparation took too long: less than 15 seconds of its validity window remain, so the fee payer would reject it.`)};ae();let oe=await CN({account:O},()=>Oe(d,{account:O,calls:j,...M?{feeToken:M}:{},nonceKey:`expiring`,validBefore:ie}));if(oe.gas=(oe.gas??0n)+5000n,h?.feePayer){let e=oe;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return ae(),lC({challenge:s,payload:{signature:await Ne(d,oe),type:`transaction`},source:_N({address:O.address,chainId:f})})}}),s=new Map,c=async t=>{WN(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=s.get(i);return a||(a=o.createCredential(t).finally(()=>s.delete(i)),s.set(i,a)),a};return kT({...o,createCredential:c},kN)}async function ON(e,t){let{account:n,amount:r,chainId:i,currency:a}=t,o=await ke(e,Re.token.getBalance.call(e,{account:n,token:a})).catch(()=>void 0);if(!(typeof o!=`bigint`||o>=r))return uN(e,{account:n,amount:r,chainId:i})}function kN(e){let t=fO.schema.credential.payload.safeParse(aC(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`||n.type===`zone`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(Je.serializedType))return;let i=Je.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&Je.serialize(i)===r)return fe(r)}function AN(e){let{challenge:t,origin:n,pending:r,zoneId:i}=e,a={sent:!1},o={challenge:t,origin:n,terms:zN(t,i),waiters:0,withdrawal:HN(e,a)},s=RN(t);return r.set(s,o),o.withdrawal.catch(()=>{!a.sent&&r.get(s)===o&&r.delete(s)}),MN(e,o)}function jN(e){let{challenge:t,pending:n,zoneId:r}=e,i=n.get(RN(t));if(i)return i;let a=zN(t,r);if(a!==void 0){for(let[e,t]of n)if(t.terms===a){if(!VN(t.challenge.expires)){n.delete(e);continue}if(t.redeemedLate)throw new tS({challengeId:t.challenge.id,senderTags:t.senderTags,zoneId:r});if(!(t.waiters>0))return t}}}async function MN(e,t){t.waiters++;try{return await NN(e,t)}finally{t.waiters--}}async function NN(e,t){let{client:n,origin:r,pending:i,zone:a,zoneId:o}=e,{challenge:s}=t,c=s.request.recipient,l=RN(s);if((l===RN(e.challenge)?r!==void 0&&t.origin!==void 0&&r!==t.origin:!r||r!==t.origin)||!VN(s.expires))throw new tS({challengeId:s.id,zoneId:o});let u=await t.withdrawal,d=u.senderTags??await GD(a.client,u).catch(e=>{let t=Error(`Zone withdrawal transaction ${u.transactionHash} was sent, but its sender tag could not be read from the Zone. Retry the challenge to resume without withdrawing again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),t}),f;try{f=await KD(n,{portal:VD(o),senderTags:d,timeoutMs:LN(s.expires,a.settlementTimeoutMs),to:c})}catch(e){throw new tS({cause:e,challengeId:s.id,senderTags:d,zoneId:o})}i.get(l)===t&&(BN(s.expires)?(t.redeemedLate=!0,t.senderTags=[f.senderTag]):i.delete(l));let{hash:p,senderTag:m}=f;return lC({challenge:s,payload:{hash:p,senderTag:m,type:`zone`,zoneId:o}})}function PN(e){if(e)try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.origin}catch{return}}function FN(e){let t=e?.settlementTimeoutMs;if(t!==void 0&&(!Number.isFinite(t)||t<0))throw Error("`zone.settlementTimeoutMs` must be a finite, non-negative number.");let n=e?.client.chain?.id;if(e?.zoneId===void 0||n===void 0||UD(n)===void 0)return;let r=HD(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function IN(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+KN}function LN(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function RN(e){return JSON.stringify(e)}function zN(e,t){let n;try{n=e.opaque===void 0?e.meta:iS(e.opaque)}catch{return}let{digest:r,intent:i,method:a,realm:o,request:s}=e;return oS({digest:r,intent:i,meta:kD(n),method:a,realm:o,request:s,zoneId:t})}function BN(e){if(!e)return!1;let t=new Date(e).getTime();return!Number.isNaN(t)&&Date.now()>=t}function VN(e){if(!e)return!0;let t=new Date(e).getTime();return Number.isNaN(t)||Date.now()<t+3e5}async function HN(e,t){let{assertFee:n,challenge:r,clientId:i,zone:a}=e,o=r.request,s=a.client.account;if(!s)throw Error("`zone.client` requires an account.");let c=BigInt(o.amount),l=o.currency,u=o.recipient,d=RM({challengeId:r.id,clientId:i,serverId:r.realm}),f=await Re.zone.getWithdrawalFee(a.client);n(f);let[,p]=Re.zone.requestWithdrawal.calls({amount:c,fallbackRecipient:s.address,memo:d,to:u,token:l}),m=await Oe(a.client,{account:s,calls:[Re.token.approve.call({amount:c+f,spender:ze.zoneOutbox,token:l}),p]}),h=await Ne(a.client,m);t.sent=!0;let g=fe(h),_=await je(a.client,{serializedTransaction:h}).catch(e=>Fe(a.client,{hash:g,timeout:qN}).catch(()=>{let t=Error(`Zone withdrawal outcome is unknown: transaction ${g} may have been sent. Retrying this challenge does not withdraw again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),t}));if(_.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${_.transactionHash} reverted.`);let[v]=me({abi:Ie.zoneOutbox,eventName:`WithdrawalRequested`,logs:_.logs});return{blockNumber:_.blockNumber,sender:s.address,senderTags:v?[WD({fallbackNonce:v.args.fallbackNonce,sender:v.args.sender,transactionHash:_.transactionHash})]:void 0,transactionHash:_.transactionHash}}function UN(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo charge maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo charge maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return he(e,t)}}function WN(e,t,n,r,i){let{methodDetails:a,recipient:o}=n,s=a?.chainId;if(e.expectedChainId!==void 0&&s!==void 0&&s!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${s}.`);(s!==void 0||e.allowedChainIds?.length===0)&&PM(e.allowedChainIds,s);let c=e.currencies?mj(e.currencies,n.currency,{chainId:s??r??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),decimals:e.decimals}):void 0;if(e.currencies&&!c)throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!o||!t.has(o.toLowerCase()))throw Error(`Unexpected primary recipient: ${o}`);let n=a?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(t.maxAtomicAmount===void 0&&t.maxAmount===void 0)return;let l=BigInt(n.amount)+(i??0n),u=i===void 0?`amount exceeds`:`amount plus Zone withdrawal fee exceeds`;if(t.maxAtomicAmount!==void 0&&l>t.maxAtomicAmount)throw Error(`Tempo charge ${u} maxAtomicAmount.`);if(t.maxAmount!==void 0&&l>UN(t.maxAmount,c?.decimals))throw Error(`Tempo charge ${u} maxAmount.`)}var GN,KN,qN,JN=R((()=>{LT(),mC(),hj(),rS(),gC(),ND(),ID(),sS(),OM(),IM(),yS(),HM(),JM(),XM(),bA(),nN(),pN(),bN(),EN(),$D(),hO(),GN=Y.object({account:Y.optional(Y.custom()),autoSwap:Y.optional(Y.custom()),feeToken:Y.optional(Y.custom()),mode:Y.optional(Y.enum(nO))}),KN=15e3,qN=15e3}));function YN(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function XN(e){let t=O.encode(O.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 ne.keccak256(t)}function ZN(e){return Je.encodeForSigning(e)}function QN(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function $N(e,t){return ne.keccak256(j.concat(ZN(e),t.sender))}var eP=R((()=>{RO()})),tP,nP,rP,iP,aP=R((()=>{tP=[{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`}],nP=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],rP={name:`descriptor`,type:`tuple`,components:tP},iP=[{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:[rP,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[rP,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[rP,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[rP],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[rP],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[rP],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:tP},{name:`state`,type:`tuple`,components:nP}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:nP}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:nP}]},{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:`verifyVoucher`,stateMutability:`view`,inputs:[rP,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[{name:`valid`,type:`bool`}]},{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:`OpeningCommitmentRecorded`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`signer`,type:`address`,indexed:!0},{name:`commitment`,type:`bytes32`}]},{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}]},{type:`error`,name:`RootKeyRetired`,inputs:[{name:`account`,type:`address`}]},{type:`error`,name:`SignerConfigChanged`,inputs:[{name:`signer`,type:`address`}]},{type:`error`,name:`SaltNotSignerCommitment`,inputs:[{name:`signer`,type:`address`},{name:`commitment`,type:`bytes32`}]}]}));function oP(e){return e.type===`secp256k1`?e.signature.s<=uP:e.type===`p256`||e.type===`webAuthn`?e.signature.s<=dP:!0}function sP(e){if(e.type===`configurable`)return{...e,signatures:e.signatures.map(e=>sP(e))};if(oP(e))return e;if(e.type===`secp256k1`){let{r:t,s:n,yParity:r}=e.signature;return{...e,signature:{r:t,s:cP-n,yParity:+(r===0)}}}return e.type===`p256`||e.type===`webAuthn`?{...e,signature:{...e.signature,s:lP-e.signature.s}}:e}var cP,lP,uP,dP,fP=R((()=>{cP=115792089237316195423570985008687907852837564279074904382605163141518161494337n,lP=115792089210356248762697446949407573529996955224135760342422259061068512044369n,uP=57896044618658097711785492504343953926418782139537452191302581570759080747168n,dP=57896044605178124381348723474703786764998477612067880171211129530534256022184n}));function pP(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function mP(e){return e===void 0||BigInt(e)===0n}function hP(e,t){let{account:n,config:r,signatures:i}=e,a=Ue.getSignPayload({account:n,config:r,payload:t}),o=Number(r.threshold),s,c=0,l;for(let[e,t]of i.entries()){if(!pP(t.type)||!oP(t)||e>0&&c>=o)return!1;let n=Ke.extractAddress({payload:a,signature:t});if(!Ke.verify(t,{address:n,payload:a}))return!1;let i=r.owners.find(e=>LD(e.owner,n));if(!i)return!1;let u=Number(i.weight);if(u===0)return!1;let d=BigInt(n);if(s!==void 0&&s>=d)return!1;s=d,c+=u,l=l===void 0?u:Math.min(l,u)}return!(i.length===0||c<o||l!==void 0&&c>=o+l)}function gP(e,t){let{account:n,commitment:r,payload:i}=t;if(!LD(e.account,n)||BigInt(e.config.version??0n)===0n&&e.config.owners.some(({owner:t})=>LD(t,e.account)))return!1;if(mP(r)){if(BigInt(e.config.version??0n)!==0n||!LD(Ue.getAddress(e.config),n))return!1}else if(Ue.getCommitment(e.config).toLowerCase()!==r.toLowerCase())return!1;return hP(e,i)}var _P=R((()=>{RD(),fP()}));function vP(e,t){return{name:jP,version:MP,chainId:t,verifyingContract:e}}function yP(e,t,n){return le({domain:vP(e,t),types:PP,primaryType:`CloseAuthorization`,message:n})}function bP(e,t){return We.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function xP(e,t,n){return e.toLowerCase()===We.address.toLowerCase()?bP(t,n):le({domain:vP(e,t),types:NP,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function SP(e,t,n,r){let i=CP(e);return i?wP(i,t,n,r):!1}function CP(e){let t=Ke.from(e);if(Ke.serialize(t).toLowerCase()===e.toLowerCase())return t}function wP(e,t,n,r){if(e.type===`configurable`)return r.configurable?gP(e,{account:n,commitment:r.openingCommitment,payload:t}):!1;if(!pP(e.type)||!oP(e)||!mP(r.openingCommitment))return!1;let i=Ke.extractAddress({payload:t,signature:e});return Ke.verify(e,{address:i,payload:t})&&LD(i,n)}function TP(e){return e.source===`configurable`}function EP(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function DP(e,t){return Le.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function OP(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===We.address.toLowerCase())try{return await DP(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return Pe(e,{account:t,domain:vP(r,i),types:NP,primaryType:`Voucher`,message:n})})(),o=Ke.from(a);if(!pP(o.type)&&o.type!==`configurable`)throw Error(`TIP-1034 vouchers require a TIP-1020 primitive or TIP-1166 configurable account signature; received "${o.type}".`);return Ke.serialize(sP(o))}async function kP(e,t,n,r,i){let a=EP(t)?await t.sign({hash:yP(r,i,n),raw:!0}):await Pe(e,{account:t,domain:vP(r,i),types:PP,primaryType:`CloseAuthorization`,message:n}),o=Ke.from(a);if(!pP(o.type)&&o.type!==`configurable`)throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive or TIP-1166 configurable account signature; received "${o.type}".`);return Ke.serialize(sP(o))}function AP(e,t,n,r,i={}){try{let a=xP(e,t,n);return SP(n.signature,a,r,i)}catch{return!1}}var jP,MP,NP,PP,FP=R((()=>{RD(),_P(),fP(),jP=`TIP20 Channel Reserve`,MP=`1`,NP={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},PP={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]}}));function IP(e){return typeof e==`object`&&!!e}function LP(e){return typeof e==`string`&&ue(e,{strict:!1})?e:void 0}function RP(e){return LP(e.accessKeyAddress)}function zP(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(j.random(8))%e)}function BP(e){return RP(e)??e.address}function VP(e){return HP(e)!==void 0}function HP(e){let t=RP(e);if(t===void 0)return TP(e)?e:void 0;let n=e.delegate;if(n&&TP(n)&&n.address.toLowerCase()===t.toLowerCase())return n}async function UP(e,t){let n=HP(t);if(!n)return j.random(32);let{config:r}=n,i=await Re.accounts.getConfigCommitment(e,{account:n.address}),a=r?Ue.getCommitment(r):void 0;if(BigInt(i)!==0n){if(a&&a.toLowerCase()!==i.toLowerCase())throw Error(`Configurable account ${n.address} holds a config whose commitment ${a} does not match its on-chain commitment ${i}. Use the account's current config.`);return i}if(!a||BigInt(r.version??0n)!==0n)throw Error(`Configurable account ${n.address} is not registered, so it needs its version-zero config to open a channel.`);return a}function WP(e,t){let n=xN(e);if(n)try{let r=ae({abi:iP,data:n});if(r.errorName!==`SignerConfigChanged`&&r.errorName!==`RootKeyRetired`)return;let[i]=r.args;return i.toLowerCase()===t.signer.toLowerCase()?new $x({cause:e,channelId:t.channelId,reason:r.errorName,signer:i}):void 0}catch{return}}async function GP(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return CN({account:n},()=>Oe(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}}))}async function KP(e,t){return await Ne(e,t)}function qP(e,t,n=!1){let r=e.request.methodDetails,i=IP(r)?LP(r.escrowContract)??LP(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!YP(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!YP(i,a)?i:a}function JP(e,t,n,r){return lC({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${t.descriptor?.payer??r.address}`})}function YP(e,t){return e.toLowerCase()===t.toLowerCase()}function XP(e,t){let n=HP(e);if(!n?.config)return;let{config:r}=n;if(Ue.getCommitment(r).toLowerCase()!==t.salt.toLowerCase()&&(BigInt(r.version??0n)!==0n||Ue.getAddress(r).toLowerCase()!==n.address.toLowerCase()))throw Error(`Configurable account ${n.address} holds a config that does not match the channel's opening commitment (salt ${t.salt}), so it cannot sign a voucher the channel settles. Sign with the config the channel opened with, or close the channel and open a new one.`)}async function ZP(e,t,n,r,i,a=LO){let o=XN({...n,chainId:i,escrow:a}),s=vO(r);XP(t,n);let c=await OP(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function QP(e,t,n,r,i,a=LO){let o=await ZP(e,t,n,r,i,a),s=await kP(e,t,{channelId:o.channelId,cumulativeAmount:vO(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function $P(e,t,n){let r=BP(t),i=n.escrow??`0x4d50500000000000000000000000000000000000`,a=n.operator??`0x0000000000000000000000000000000000000000`,o=n.salt??await UP(e,t),s=vO(n.deposit),c=vO(n.initialAmount),l=oe({abi:iP,functionName:`open`,args:[n.payee,a,n.token,s,o,r]}),u=await KP(e,await GP(e,{account:t,calls:[...n.prefixCalls??[],{to:i,data:l}],feePayer:n.feePayer,feeToken:n.feeToken??n.token,validAfter:zP()})),d=Ve.deserialize(u),f={authorizedSigner:r,expiringNonceHash:$N(QN({...n.feePayer?{feePayer:!0}:{},transaction:d}),{sender:t.address}),operator:a,payee:n.payee,payer:t.address,salt:o,token:n.token},p=XN({...f,chainId:n.chainId,escrow:i});return{action:`open`,type:`transaction`,channelId:p,transaction:u,signature:await OP(e,t,{channelId:p,cumulativeAmount:c},i,n.chainId),descriptor:f,cumulativeAmount:c.toString(),authorizedSigner:f.authorizedSigner}}async function eF(e,t,n,r,i,a,o=LO,s=[],c=n.token){let l=XN({...n,chainId:i,escrow:o}),u=vO(r);return{action:`topUp`,type:`transaction`,channelId:l,transaction:await KP(e,await GP(e,{account:t,calls:[...s,{to:o,data:oe({abi:iP,functionName:`topUp`,args:[n,u]})}],feePayer:a,feeToken:c,validAfter:zP()}).catch(e=>{throw WP(e,{channelId:l,signer:YN(n)})??e})),descriptor:n,additionalDeposit:u.toString()}}var tF=R((()=>{mC(),rS(),EN(),eP(),aP(),RO(),FP()}));function nF(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function rF(e){return nF({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function iF(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(rF(t),t)},delete(t){e.delete(t)}}}function aF(e){return{...e,cumulativeAmount:e.cumulativeAmount.toString(),deposit:e.deposit.toString()}}function oF(e){return{...e,cumulativeAmount:BigInt(e.cumulativeAmount),deposit:BigInt(e.deposit)}}function sF(e,t){pF.set(e,pF.get(t)??t)}async function cF(e,t,n){let r=fF.get(e);r||(r=new Map,fF.set(e,r));let i=(r.get(t)??Promise.resolve()).catch(()=>{}).then(n);r.set(t,i);try{return await i}finally{r.get(t)===i&&r.delete(t)}}function lF(e,t,n){return cF(pF.get(e)??e,`funding:${t}`,n)}async function uF(e,t){await cF(e,`write:${rF(t)}`,async()=>{let n=await e.get(rF(t));if(n?.origin!==void 0){if(t.origin!==void 0&&t.origin!==n.origin)throw Error(`SessionManager: stored channel origin mismatch`);t.origin=n.origin}if(n?.uncertainTopUp){if(n.channelId!==t.channelId)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);t.uncertainTopUp=!0}await e.set(t)})}async function dF(e,t){await cF(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}var fF,pF,mF=R((()=>{fF=new WeakMap,pF=new WeakMap}));function hF(e){if(e<0n||e>bF)throw new J({reason:`amount exceeds uint96 range`})}async function gF(e,t,n=LO){let{cumulativeAmount:r,descriptor:i,signature:a}=t;return ke(e,{address:n,abi:iP,functionName:`verifyVoucher`,args:[yF(i),r,a]})}async function _F(e,t,n=LO,r){return vF(await ke(e,{address:n,abi:iP,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function vF(e){return hF(e.settled),hF(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}function yF(e){return{payer:e.payer,payee:e.payee,operator:e.operator,token:e.token,salt:e.salt,authorizedSigner:e.authorizedSigner,expiringNonceHash:e.expiringNonceHash}}var bF,xF=R((()=>{rS(),aP(),RO(),bF=2n**96n-1n}));function SF(e){return`cumulativeAmount`in e}function CF(e){if(SF(e))return BigInt(e.cumulativeAmount)}async function wF(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await uF(e.store,t):await dF(e.store,rF(t)),e.notifyUpdate(t)}async function TF(e,t,n){let r=CF(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 wF(e,i))}function EF(e){return e?.action!==void 0}function DF(e){return EF(e)&&e.descriptor!==void 0}function OF(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 he(i,t)}function kF(e,t,n,r){let i=OF(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function AF(e){return typeof e==`object`&&!!e}function jF(e){return typeof e==`string`&&ue(e,{strict:!1})?e:void 0}function MF(e){let t=e.request.methodDetails;return AF(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:jF(t.escrowContract),escrow:jF(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:jF(t.feeToken),operator:jF(t.operator),configurableVouchers:typeof t.configurableVouchers==`boolean`?t.configurableVouchers:void 0,sessionSnapshot:zx(t,Ux.sessionSnapshot)}:{}}function NF(e,t){if(typeof e==`string`&&ue(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function PF(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function FF(e){return typeof e==`string`?e:void 0}async function IF(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=MF(n);(o.chainId!==void 0||i?.length===0)&&PM(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});NM(c,s);let l=s??c.chain?.id;if(PM(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=qP(n,r,t),d=NF(n.request.recipient,`recipient`),f=NF(n.request.currency,`currency`);return{amount:PF(n.request.amount),challenge:n,chainId:l,client:c,...o.configurableVouchers===void 0?{}:{configurableVouchers:o.configurableVouchers},escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:nF({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:FF(n.request.suggestedDeposit),token:f}}async function LF(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=_F}=e,o=XN({...r,chainId:i.chainId,escrow:i.escrow});RF({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 RF(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(!YP(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!YP(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!YP(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!YP(YN(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function zF(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function BF(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=OF(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function VF(e){let{account:t,client:n,readChannelState:r,snapshot:i,verifyVoucherOnChain:a=gF}=e,o=i.highestVoucher;if(!o)throw Error(`session snapshot is missing its highest signed voucher`);if(o.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let s=BigInt(i.acceptedCumulative),c=BigInt(o.cumulativeAmount),l=BigInt(i.requiredCumulative),u=BigInt(i.deposit),d=BigInt(i.settled),f=BigInt(i.spent);if(c!==s)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(f>s)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(d>u)throw Error(`session snapshot settled amount exceeds deposit`);let p={channelId:o.channelId,cumulativeAmount:c,signature:o.signature},m=YN(i.descriptor),h=VP(t);if(!(AP(i.escrow,i.chainId,p,m,h?{configurable:!0,openingCommitment:i.descriptor.salt}:{})||h&&await a(n,{descriptor:i.descriptor,cumulativeAmount:c,signature:p.signature},i.escrow).catch(()=>!1)))throw Error(`session snapshot highest voucher signature is invalid`);let g=await LF({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:BP(t),token:i.descriptor.token},readChannelState:r}),_=[s,l,g.state.settled].reduce((e,t)=>t>e?t:e,0n);if(_>g.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:g.channelId,cumulativeAmount:_,deposit:g.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:f}}function HF(e,t){return YP(e.address,t.payer)?YP(BP(e),YN(t)):!1}function UF(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(EF(r)){if(!DF(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=zF({context:r,snapshot:o.snapshot});return!n&&s&&HF(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&HF(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 WF(e,t,n=!1){switch(e.type){case`open`:return qF(e,t,n);case`recover`:return JF(e,t);case`voucher`:return YF(e,t);case`manual`:return XF(e,t,n)}}async function GF(e,t){if(e)return await UM(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function KF(e,t){let{account:n,amount:r,chainId:i,client:a,token:o}=t;if(e||!iN({chainId:i,currency:o}))return;let s=await uN(a,{account:n,amount:r,chainId:i});if(s)throw s}async function qF(e,t,n){let{account:r,resolved:i}=e;if(VP(r)&&i.configurableVouchers!==!0)throw new Qx({signer:r.address});let a=ak({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw});await KF(n,{account:r.address,amount:a,chainId:i.chainId,client:i.client,token:i.token});let o=await $P(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 GF(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await wF(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function JF(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await LF({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:BP(n),token:o.token}}),l=BF({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`);sk(l,a);let u=await ZP(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await wF(t,{...d?.channelId===c.channelId&&d.uncertainTopUp?{uncertainTopUp:!0}:{},channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function YF(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;sk(a,e.maxDeposit);let o=await ZP(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await wF(t,r),o}async function XF(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=XN({...s,chainId:o.chainId,escrow:o.escrow});RF({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:BP(r),token:o.token});let l=await ZF({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await TF(t,o.key,l),l}async function ZF(e,t){switch(e.context.action){case`open`:return QF(e);case`topUp`:return $F(e,t);case`voucher`:return eI(e);case`close`:return tI(e)}}async function QF(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=kF(r,i,`cumulativeAmount`,`open`),c=await ZP(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 $F(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=kF(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:(await KF(t,{account:n.address,amount:c,chainId:s.chainId,client:s.client,token:s.token}),eF(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await GF(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken))}function eI(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return ZP(a.client,t,i,kF(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function tI(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return QP(a.client,t,i,kF(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}var nI,rI,iI,aI=R((()=>{Gx(),rS(),IM(),yS(),JM(),pN(),xF(),eP(),FP(),tF(),mF(),Sk(),nI=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),rI=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),iI=Y.object({account:Y.optional(Y.custom()),autoSwap:Y.optional(Y.custom()),action:Y.optional(Y.enum([`open`,`topUp`,`voucher`,`close`])),channelId:Y.optional(rI),cumulativeAmount:Y.optional(lS()),cumulativeAmountRaw:Y.optional(Y.string()),transaction:Y.optional(nI),descriptor:Y.optional(Y.custom()),additionalDeposit:Y.optional(lS()),additionalDepositRaw:Y.optional(Y.string()),depositRaw:Y.optional(Y.string())})}));async function oI(e,t){let n=gI.get(e)??new Map;gI.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 sI(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function cI(e,t,n){try{let r=e.response?.headers.get(q.paymentReceipt);if(r){let e=DO(r);if(e.challengeId===t.id&&sI(n,e))return!0}}catch{}return e.challenges?.some(e=>kk(e)?sI(n,Ak(e)):!1)??!1}function lI(e){let{allowedChainIds:t,currencies:n,decimals:r,expectedRecipients:i,maxAmount:a,maxAtomicAmount:o}=e;if((a!==void 0||o!==void 0)&&n===void 0)throw Error(`Tempo session maxAmount and maxAtomicAmount require currencies.`);for(let e of n??[])uI(a,typeof e==`string`?r:e.decimals);return{chainId:t?.length===1?t[0]:void 0,currencies:n,decimals:r,expectedRecipients:i?new Set(i.map(e=>e.toLowerCase())):void 0,maxAmount:a,maxAtomicAmount:o===void 0?void 0:BigInt(o)}}function uI(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo session maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo session maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return he(e,t)}}function dI(e,t,n){let r=e.currencies?mj(e.currencies,t.currency,{chainId:t.methodDetails?.chainId??n??e.chainId,decimals:e.decimals}):void 0;if(e.currencies&&!r)throw Error(`Tempo session currency is not allowed: ${t.currency}.`);if(e.expectedRecipients&&(!t.recipient||!e.expectedRecipients.has(t.recipient.toLowerCase())))throw Error(`Unexpected session recipient: ${t.recipient}`);let i=BigInt(t.amount);if(e.maxAtomicAmount!==void 0&&i>e.maxAtomicAmount)throw Error(`Tempo session amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0&&i>uI(e.maxAmount,r?.decimals))throw Error(`Tempo session amount exceeds maxAmount.`)}function fI(e,t){try{return dI(e,t),!0}catch{return!1}}function pI(e){return typeof e==`object`&&!!e&&e.action===`close`}function mI(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=lI(e),m=MM({chain:et,getClient:c,rpcUrl:yA}),h=DM({account:t}),g=(e,t)=>{let n=(p.currencies?mj(p.currencies,e.currency,{chainId:e.methodDetails?.chainId??t??p.chainId,decimals:a}):void 0)?.decimals??a??6;return{decimals:n,maxDeposit:l===void 0?void 0:he(l,n),topUpAmount:u===void 0?void 0:he(u,n)}};l!==void 0&&he(l,6),u!==void 0&&he(u,6);let _=e.origin===void 0?void 0:new URL(e.origin);if(_&&![`http:`,`https:`].includes(_.protocol))throw Error(`Session origins require HTTP or HTTPS`);let v=i??iF(),y={store:v,notifyUpdate:e=>d?.(e)},b=async(e,t,n)=>{let r=h(e.client,t),i=t?.action?t.descriptor:n?.descriptor??zF({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:YN(i)}:{}}})??r},x=async(e,t,n)=>{let{decimals:r,maxDeposit:i}=g(e.challenge.request,e.chainId);return UF({account:await b(e,t,n),entry:n,context:t,decimals:r,maxDeposit:i,resolved:e})},S=FD(pO,{canHandleChallenge:({challenge:e,context:t})=>kk(e)&&(pI(t)||t===aw||fI(p,e.request)),context:iI,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&dI(p,t.request);let a=await IF({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m});i?.action!==`close`&&t.request.methodDetails?.chainId===void 0&&dI(p,t.request,a.chainId);let c=DT(e),l=MT(e)??_?.origin;if(l!==void 0&&(l===`null`||![`http:`,`https:`].includes(new URL(l).protocol)))throw Error(`Session payments require an HTTP or HTTPS origin`);if(_&&l!==_.origin)throw Error(`Session channel origin mismatch`);let u={...y,origin:l},d=()=>{};try{let e=!EF(i)&&i?.descriptor===void 0;e&&(d=await oI(v,a.key),c&&(await v.get(a.key))?.opened&&await c.prepare());let n=await v.get(a.key);if(n&&n.origin!==l)throw Error(`Session channel origin mismatch`);if(l&&!n&&a.snapshot&&!i?.descriptor&&!_)throw Error(`Session snapshot recovery requires an explicitly configured origin or descriptor`);let o=await x(a,i,n);if(!e&&c&&o.type===`open`){d=await oI(v,a.key);let e=await v.get(a.key);if(e&&e.origin!==l)throw Error(`Session channel origin mismatch`);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await v.get(a.key)),o=await x(a,i,n))}let s,f=c&&o.type===`open`?{store:{get:e=>v.get(e),async set(e){s=l?{...e,origin:l}:e},delete:e=>v.delete(e)},notifyUpdate(){}}:u,p=await JP(t,await WF(o,f,WM(i?.autoSwap??r,KM)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||cI(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await v.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await uF(v,e),y.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function C(e,t,n){let r={challenge:e,context:t};return jT(r,hI(n)),S.createCredential(r)}let w=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>lF(v,rF(n),async()=>{s?.throwIfAborted();let c=await v.get(rF(n));if(c?.channelId===n.channelId&&(n=c),n.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let l=n.deposit>r?n.deposit:r,{maxDeposit:u,topUpAmount:d}=g(t.request,n.chainId),f=ok({deposit:l,maxDeposit:u,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:d});f>0n&&await Ik({autoSwap:e,additionalDeposit:f,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>C(e,t,a),onUncertainFunding:async e=>{let t=await v.get(rF(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await uF(v,n),y.notifyUpdate(n)},fetch:i,input:a,signal:s});let p=l+f;if(p===n.deposit)return;let m=await v.get(rF(n)),h=m?.channelId.toLowerCase()===n.channelId.toLowerCase()?m:n,_={...h,deposit:h.deposit>p?h.deposit:p};await uF(v,_),y.notifyUpdate(_)});return vT(S,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!kk(e))return;let c=t===void 0?void 0:iI.parse(t);if(EF(c))return;dI(p,e.request);let l=await IF({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await v.get(l.key);if(!u?.opened)return;let d=hI(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,h=u.cumulativeAmount+wO(e),g=f?BigInt(f.requiredCumulative):h,_=g>h?g:h,y=f?BigInt(f.deposit):u.deposit,x=y>u.deposit?y:u.deposit;_<=x&&x===u.deposit||!HF(await b(l,c,u),u.descriptor)||await w({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:x,fetch:r,input:i,requiredCumulative:_,signal:a})}),wT(S,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!kk(e))return u;if(!OO(u))return CO(aC(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await IF({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await v.get(f),h={assertVoucherWithinLocalLimit:t=>sk(t,g(e.request,p?.chainId).maxDeposit),createSessionCredential:(e,t)=>C(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await w({autoSwap:t===void 0?void 0:iI.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return qk({onNeedVoucher:(t,n)=>Jk({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function hI(e){let t=new URL(e instanceof Request?e.url:e,globalThis.location===void 0?void 0:globalThis.location.href);if(![`http:`,`https:`].includes(t.protocol))throw Error(`Session payments require an HTTP or HTTPS origin`);return t.origin}var gI,_I=R((()=>{CT(),LT(),Gx(),mC(),hj(),ow(),ID(),OM(),IM(),JM(),bA(),hO(),eP(),RO(),tF(),mF(),aI(),Sk(),gI=new WeakMap}));function vI(e,t){bI.set(e,t)}function yI(e){let t=bI.get(e);if(!t)throw Error(`Session manager internals are unavailable.`);return t}var bI,xI=R((()=>{bI=new WeakMap}));function SI(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 CI(e){let t=SI(`close-ready`),n=SI(`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 wI=R((()=>{}));function TI(e){return e.method===Vx.tempo&&e.intent===Hx.charge}function EI(e){if(!TI(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function DI(e,t,n){if(!n)return t;let r={...XT(Mk(e)?e.headers:void 0),...XT(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===q.paymentSession.toLowerCase())?t:{...t,headers:{...r,[q.paymentSession]:n}}}function OI(e,t){return e===void 0?t:{...iI.parse(e),...t}}function kI(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:he(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:he(e.topUpAmount,t),WebSocket:n}}function AI(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&PM(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=kI(e),i;function a(e){let t=new URL(Mk(e)?e.url:String(e),typeof location>`u`?void 0:location.href);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`SessionManager: session payments require an HTTP origin`);let n=t.origin;if(i!==void 0&&i!==n)throw Error(`SessionManager: session payment origin mismatch`);return i=n,n}let o=vE(r.fetch),s=yE(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(Mk(e)?e.redirect:void 0))===`manual`?`manual`:`error`});if(r.url&&new URL(r.url).origin!==n)throw Error(`SessionManager: session response origin mismatch`);return r};let c=r.fetch;o&&(r.fetch=DC(c,o));let l=MM({chain:et,getClient:e.client?()=>e.client:e.getClient,rpcUrl:yA}),u=DM({account:e.account}),d=pk(),f=e.credentialContext===void 0?void 0:OI(e.credentialContext,{}),p=CI({getSocketSession:()=>d.socketSession}),m=e.channelStore??iF(),h=new Set,g;async function _(e){let t=await m.get(e);if(t?.opened&&!h.has(t.channelId)){if(t.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return t}}let v=e=>{if(e.origin!==void 0&&e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return e.origin=i,uF(m,e)},y={async get(e){let t=await _(e);return t&&g&&(g.seenExisting.add(e),!g.committed&&!g.created.has(e)&&(g.resumed??=t)),t},async set(e){let t=rF(e);e.opened&&h.delete(e.channelId),g?.trackCreates&&!g.seenExisting.has(t)&&g.created.set(t,e),await v(e)},delete:e=>dF(m,e)};sF(y,m);async function b(e){let t=rF(e),n=await m.get(t);if(e.uncertainTopUp||n?.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);h.add(e.channelId),g?.seenExisting.delete(t),g?.resumed===e&&(g.resumed=void 0),await Promise.resolve(dF(m,t)).catch(()=>void 0)}async function x(){let e=g;if(e?.created.size){for(let[t,n]of e.created){let e=await m.get(t);if(n.uncertainTopUp||e?.channelId===n.channelId&&e.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before discarding the channel.`);h.add(n.channelId),await Promise.resolve(dF(m,t)).catch(()=>void 0)}e.created.clear(),await I(e.committed??e.previous)}}function S(e){let t=zx(e.request.methodDetails,Ux.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=g;if(!n?.created.size||!d.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&d.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=vk({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return XO(d,e)}function w(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function T(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=vk({channel:d.channel,spent:d.spent,state:d.state}))}let ee=mI({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}}),te=xT(ee);te&&vT(ee,e=>se(()=>Promise.resolve(te(e)),e.signal)),TT(ee);let E=DN({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),D=JT({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[ee],onChallenge:async(e,t)=>{if(!Ok(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&FE(e)===FE(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await I(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function O(e,t){let n={challenge:e,context:OI(f,t)};return i&&jT(n,i),ee.createCredential(n)}function k(e){mk({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function A(e=d.state.status===`active`?d.state.units:0){!d.channel||!d.lastChallenge||d.state.status!==`active`&&d.state.status!==`withdrawable`&&d.state.status!==`closeRequested`&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function ne(t){let r=t.headers.get(q.paymentSessionSnapshot);if(!r)return;let i=BO(r);PM(e.allowedChainIds,i.chainId),qP({request:{methodDetails:{escrow:i.escrow}}},e.escrow,n);let a=await l({chainId:i.chainId});NM(a,i.chainId);let o=u(a),{entry:s,spent:c}=await VF({account:await e.resolveAccount?.({account:o,chainId:i.chainId,operation:{authority:YN(i.descriptor),kind:`authorizePaymentChannel`}})??o,client:a,snapshot:i});return ae(s.cumulativeAmount),await Promise.resolve(y.set(s)).catch(()=>void 0),d.channel=s,d.spent=c,s}async function j(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=Mk(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=Mk(t)?t.url:t,l={...s,method:`HEAD`,headers:{...XT(i),...XT(n?.headers),[q.acceptPayment]:`${Vx.tempo}/${Hx.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await ne(t);let n=IS(t).find(TI);if(!n||!EI(n))return;let i=new URL(String(c),typeof location<`u`?location.href:void 0);if(t.url&&new URL(t.url).origin!==i.origin)return;BT(n,i,e.trustedTempoProofRealms);let a=await E.createCredential({challenge:n,context:{}}),o=await r.fetch(c,Lw({...l,redirect:`manual`},US(n),a));return o.ok?await ne(o):void 0}catch{return}}function re(e,t){let n=d.socketSession;return gk({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:d.channel?.channelId===t?d.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:d.spent,tickCost:n?.tickCost})}function M(e,t){let n=Ak(t);if(!n)return;if(XN({...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 N(e,t){let n=M(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(d.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>d.spent&&(d.spent=i),n}function ie(e,t=e.challenge,n=!1){let r=(n?N(e,t):M(e.channel,t))?.acceptedCumulative??re(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return ae(r),r.toString()}function ae(e){tk({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let oe,P;async function se(e,t){if(P)throw P;for(;;){let e=oe;if(!e)break;if(!t)await e;else{t.throwIfAborted();let n;try{await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0})})])}finally{t.removeEventListener(`abort`,n)}}}if(t?.throwIfAborted(),P)throw P;let n=e();oe=n;try{return await n}catch(e){throw e instanceof dA&&(P=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{oe===n&&(oe=void 0)}}async function ce(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return lF(m,rF(d.channel),async()=>{let{knownDeposit:t,...n}=e,i=d.channel?await y.get(rF(d.channel)):void 0;if(i?.channelId===e.channelId&&i.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let a=await Ik({...n,channel:d.channel,createSessionCredential:O,fetch:r.fetch,onUncertainFunding:async e=>{let t=await y.get(rF(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};d.channel?.channelId===e.channelId&&(d.channel=n),await y.set(n),T(n)}});k(a);let o=d.channel,s=Ek({additionalDeposit:e.additionalDeposit,channel:d.channel,channelId:e.channelId,challengeId:d.lastChallenge?.id,currentState:d.state,knownDeposit:t,receipt:a,spent:d.spent});if(s?.channel&&d.lastChallenge){let e=s.channel;for(;;){await y.set(e);let t=d.channel;if(t===o)break;if(!t)return a;let n=s.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,o=t}if(e.channelId!==s.channel.channelId)return a;d.channel=e,C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}return a})}async function F(e){return se(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=ok({deposit:n,maxDeposit:r.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:r.topUpAmount});i!==0n&&await ce({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function le(e,t){let n=_k({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(C({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function I(e){let t=yk(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function ue(e,t=!0){let n=e.headers.get(q.paymentReceipt),r=n?DO(n):null;return t&&k(r),Object.assign(e,{receipt:r,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function de(e,t){if(t?.[RE])return ue(await r.fetch(e,GT(t)),!1);if(g)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a(e),d.lastUrl=e,d.lastHeaders=t?.headers;let n=vk({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await j(e,t),i.trackCreates=!0;let a=DI(e,t,d.channel?.opened?d.channel.channelId:void 0);f&&(a={...a,context:f});let o=!n.channel?.opened;async function s(){let n=i.resumed;return!o||!n?!1:(o=!1,await b(n),a=DI(e,t,void 0),!0)}for(;;){let t;try{t=await D(e,a)}catch(e){if(i.created.size?await x():await I(i.committed??n),await s())continue;throw e}let o=ue(t),c=!1;if(o.status===402){let t=await Rk({input:e,init:a,response:o,createSessionCredential:O,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:le,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:F});t&&(c=!0,o=ue(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await I(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function fe(e){let t=await Bk({createSessionCredential:O,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>ie(e,t,!0),signedCloseAmount:ie(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(A(),C({type:`closeStarted`}),C({type:`closed`,receipt:t})),t}let pe={createSessionCredential:O,doFetch:de,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:ae,acceptReceipt(e){k(e)},topUpIfNeeded:F},me={get channelId(){return d.channel?.channelId},get cumulative(){return d.channel?.cumulativeAmount??0n},get opened(){return d.channel?.opened??!1},get state(){return d.state},fetch:de,async topUp(e){let t=Tk({amount:e,assertVoucherWithinLocalLimit:ae,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return se(async()=>{if(d.channel?.channelId!==t.channelId||d.lastChallenge!==t.challenge||d.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=Tk({amount:e,assertVoucherWithinLocalLimit:ae,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return ce({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){if(t?.[RE])throw Error(`SessionManager.sse requires payment; use fetch for unpaid streams.`);return Vk(e,t,pe)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=Pk(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await j(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await Xk({async createSessionCredential(e,i){return d.lastChallenge=e,await bT(ee,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),O(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:DI(n,i,o),signal:t?.signal});return d.lastChallenge=s,tA({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:O,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await Yk({fetch:r.fetch,input:l,probeInit:DI(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:ae,acceptReceipt:k,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:F,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=ck({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===cA.OPEN){let r=await bk({activeSocket:n,createSessionCredential:O,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return A(),C({type:`closeStarted`}),C({type:`closed`,receipt:r}),r}return fe(t)}};return vI(me,{consumeSseResponse(e,t,n){let r=a(e);if(t.url&&new URL(t.url).origin!==r)throw Error(`SessionManager: session response origin mismatch`);return Hk(e,t,n,pe)},rehydrate({channel:e,challenge:t,input:n,spent:r}){let i=a(n);if(e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!Ok(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.`);ae(e.cumulativeAmount);let o=M(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,C({type:`challengeReceived`,challengeId:t.id}),C({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),me}var jI=R((()=>{iC(),GE(),CT(),LT(),WT(),zw(),Gx(),FC(),OM(),IM(),JN(),bA(),tF(),mF(),aI(),_I(),eP(),RO(),qO(),xI(),wI(),Sk(),fA(),(function(e){e.serializeSnapshot=zO,e.deserializeSnapshot=BO})(AI||={})}));function MI(e){return e instanceof Date?e:new Date(e)}function NI(e){let t=e.getTime();if(!Number.isFinite(t))throw new J({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new J({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new J({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function PI(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new J({reason:`periodCount is invalid`});let t=$I[e.periodUnit];if(t===void 0)throw new J({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>QI)throw new J({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new J({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function FI(e){let{challengeExpires:t,request:n}=e;PI(n);let r=NI(MI(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new J({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function II(e){let t=YI(e.currency,`currency`),n=YI(e.recipient,`recipient`);return[{address:t,selector:ZI,recipients:[n]}]}function LI(e){try{let t=j.fromBytes(k.toBytes(e));if(j.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new J({reason:`challenge id must encode 32 bytes`})}}async function RI(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=BI({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:Ge.getSignPayload(o)}),c=Ke.from(s);if(c.type===`keychain`||c.type===`configurable`)throw new J({reason:`keyAuthorization must use a primitive signature`});return Ge.from(o,{signature:Ke.serialize(sP(c))})}function zI(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new J({reason:`invalid keyAuthorization payload`});let o=VI(i.signature),s=HI(o);if(UI({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==LI(n))throw new J({reason:`keyAuthorization challenge mismatch`});return WI(o,a),KI(GI(o),a),qI(o.scopes,a),{authorization:o,source:{address:JI(o,s),chainId:r}}}function BI(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return Ge.from({address:YI(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:NI(MI(i.subscriptionExpires)),limits:[{token:YI(i.currency,`currency`),limit:BigInt(i.amount),period:PI(i)}],scopes:II(i),type:t.keyType,witness:LI(n)})}function VI(e){try{return Ge.deserialize(e)}catch(e){throw e instanceof Ge.InvalidSignatureTypeError?new J({reason:`keyAuthorization must use a primitive signature`}):new J({reason:`invalid keyAuthorization payload`})}}function HI(e){let t=e.signature;if(!t)throw new J({reason:`keyAuthorization must use a primitive signature`});return t}function UI(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new J({reason:`keyAuthorization chainId mismatch`});if(t){if(!de(n.address,YI(t.accessKeyAddress,`accessKeyAddress`)))throw new J({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new J({reason:`keyAuthorization key type mismatch`})}}function WI(e,t){if(FI({request:t}),e.expiry!==NI(MI(t.subscriptionExpires)))throw new J({reason:`keyAuthorization expiry mismatch`})}function GI(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new J({reason:`keyAuthorization must contain exactly one token limit`});return t}function KI(e,t){if(!de(e.token,YI(t.currency,`currency`)))throw new J({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new J({reason:`keyAuthorization amount mismatch`});if(e.period!==PI(t))throw new J({reason:`keyAuthorization period mismatch`})}function qI(e,t){if(!e||e.length!==1)throw new J({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=YI(t.currency,`currency`),r=YI(t.recipient,`recipient`),i=new Set;for(let t of e){if(!de(t.address,n))throw new J({reason:`keyAuthorization call target mismatch`});let e=XI(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new J({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new J({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!de(t.recipients[0],r))throw new J({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new J({reason:`keyAuthorization must allow transferWithMemo`})}function JI(e,t){let n=Ge.getSignPayload(e);try{let e=Ke.extractAddress({payload:n,signature:t});if(!oP(t)||!Ke.verify(t,{address:e,payload:n}))throw new J({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof J?e:new J({reason:`keyAuthorization signature is invalid`})}}function YI(e,t){if(!ue(e))throw new J({reason:`${t} must be an address`});return e.toLowerCase()}function XI(e){return typeof e==`string`?e.toLowerCase():``}var ZI,QI,$I,eL=R((()=>{rS(),fP(),ZI=`0x95777d59`,QI=(1n<<64n)-1n,$I={dev_second:1n,day:86400n,week:604800n}}));function tL(e={}){let t=MM({chain:ye,requireChain:!0,getClient:e.getClient,rpcUrl:yA}),n=DM({account:e.account});return FD(mO,{context:iL,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??mA.testnet,o=await t({chainId:a});if(o.chain?.id!==a)throw Error(`Subscription chain mismatch: expected ${a}, got ${o.chain?.id??`unknown`}.`);let 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.");rL(r.request),await e.validateRequest?.(r.request);let l=await nL(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=zI({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:Ge.serialize(l),type:`keyAuthorization`},request:r.request});if(!de(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return lC({challenge:r,payload:{signature:Ge.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function nL(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await RI({accessKey:n,account:r,challengeId:i,chainId:a,request:o});if(s)return s;let c=await e.request({method:`wallet_authorizeAccessKey`,params:[{address:n.accessKeyAddress,expiry:NI(MI(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:j.fromNumber(BigInt(o.amount)),period:PI(o)}],scopes:II(o),witness:LI(i)}]});return Ge.fromRpc(c.keyAuthorization)}function rL(e){PI(e),NI(MI(e.subscriptionExpires))}var iL,aL=R((()=>{mC(),ID(),OM(),IM(),yS(),bA(),hO(),eL(),iL=Y.object({accessKey:Y.optional(Y.custom()),account:Y.optional(Y.custom())})}));function oL(e={}){let t=e.expectedChainId!==void 0&&(e.allowedChainIds===void 0||e.allowedChainIds.includes(e.expectedChainId)),n=e.expectedChainId===void 0?e:{...e,allowedChainIds:t?[e.expectedChainId]:[]};return[DN(e),sL(n)]}var sL,cL=R((()=>{_I(),jI(),JN(),aL(),sL=Object.assign(mI,{manager:AI}),(function(e){e.charge=DN,e.common=oL,e.session=sL,e.subscription=tL})(oL||={})})),lL=R((()=>{JN(),cL(),aL(),mF(),_I(),jI()})),uL=at({orderTempoChargeChallengesByBalance:()=>fL,readTempoKeystore:()=>ML,resolveTempoAccount:()=>NL,tempo:()=>pL});async function dL(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}async function fL(e,t){let n=[],r=[];for(let[t,i]of e.entries())bL(i)&&(n.push(t),r.push(i));if(r.length<2)return[...e];let i=await xL(t).catch(()=>void 0);if(!i)return[...e];let a=await Promise.all(r.map(async(e,t)=>({challenge:e,index:t,score:await SL(e,i)})));a.sort((e,t)=>VL.indexOf(e.score)-VL.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 pL(){let e;return pM({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:t,options:n,methodOpts:r}){let i=nj(n.account),a=t.request,o=a.currency,s=yL(r),c=EL({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()||(jA(i)?void 0:await rj(i).get());if(!h&&jA(i)&&PL()){m=!0;let e=NL(i);if(e){let r=FA(n.rpcUrl,{network:n.network});p=M({chain:await LA({network:n.network,rpcUrl:r}),transport:I(r)}),wL({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let i=o?await VA(p,o,e.wallet_address).catch(()=>void 0):void 0;l=i?.symbol??o??``,u=i?.decimals??a.decimals??6}}else if(h)f=L(h);else{let e=IL();if(e){let t=await rj(e).get();t&&(f=L(t))}if(!f)throw n.account?new z({code:`ACCOUNT_NOT_FOUND`,message:`Account "${i}" not found.`,exitCode:69}):new z({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!m&&f){let e=FA(n.rpcUrl,{network:n.network});p=M({chain:await LA({network:n.network,rpcUrl:e}),transport:I(e)}),wL({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let r=o?await VA(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 FL(t)}};if(!f||!p)throw new z({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let g=oL({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??(BA(p.chain)?`10`:void 0);if(!n)throw new z({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=OL(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`);let c={channelId:n,cumulativeAmount:r},l=await OP(p,f,c,i,a);return lC({challenge:t,payload:{action:o,channelId:n,...o===`close`?{closeSignature:await kP(p,f,c,i,a)}:{},descriptor:s,cumulativeAmount:r.toString(),signature:l},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=aC(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?` ${X.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
237
+ `)}function lM(e,t,n){if(OM.has(e)&&typeof t==`string`)return`${t} ${X.dim(`(${yM(BigInt(t),n.tokenSymbol,n.tokenDecimals)})`)}`;if(e===`chainId`&&typeof t==`number`){let e=CM({id:t,name:``});return e?`${t} ${X.dim(`(${e})`)}`:String(t)}return typeof t==`string`&&/^0x[0-9a-fA-F]{40}$/.test(t)?n.explorerUrl?pM(`${n.explorerUrl}/address/${t}`,t):t:typeof t==`string`&&/^https?:\/\//.test(t)?X.link(t,t):String(t)}function uM(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 dM(e,t){if(e===`realm`&&typeof t==`string`)try{let e=new URL(t.includes(`://`)?t:`https://${t}`);return X.link(e.href,t)}catch{}return String(t)}function fM(e){return typeof e==`object`&&e?JSON.stringify(e):String(e)}function pM(e,t){return X.link(e,t)}function mM(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 hM(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 gM(e){return e.startsWith(`tempo:`)}function _M(e){let t=Ze.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.on(`close`,()=>n(void 0)),t.question(`${X.bold(`▸ ${e}:`)} `,e=>{t.close(),n(e.trim()||void 0)})})}function vM(e,t=!1){let n=Ze.createInterface({input:process.stdin,output:process.stderr});return new Promise(r=>{let i=t?`(Y/n)`:`(y/N)`;n.question(`${X.bold(`▸ ${e}`)} ${X.dim(i)} `,e=>{n.close();let i=e.trim().toLowerCase();r(i===``?t:i===`y`)})})}function yM(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?X.dim(X.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):X.dim(t);return`${a?`${o}.${a}`:o} ${s}`}function bM(e,t={}){return e??(t.network?kM[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}function xM(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 SM(e={}){let t=bM(e.rpcUrl,{network:e.network});if(!t)return ve;let{getChainId:n}=await import(`viem/actions`),r=await n(N({transport:L(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 CM(e){return{[ve.id]:`mainnet`,[ye.id]:`testnet`}[e.id]??e.name}function wM(e){return typeof e==`bigint`?e:e.amount}function TM(e){return e.id!==ve.id}async function EM(e,t,n,r={}){let{Actions:i}=await import(`viem/tempo`),[a,o]=await Promise.all([i.token.getBalance(e,{account:n,token:t}).then(wM).catch(()=>0n),i.token.getMetadata(e,{token:t}).catch(e=>{if(r.requireDecimals)throw e;return{symbol:t}})]),s={"0x20c0000000000000000000000000000000000000":`PathUSD`,"0x20C000000000000000000000b9537d11c60E8b50":`USDC`}[t]??o.symbol,c=`decimals`in o&&typeof o.decimals==`number`?o.decimals:6;if(r.requireDecimals&&!(`decimals`in o&&typeof o.decimals==`number`))throw Error(`Token decimals are unavailable.`);return{balance:a,symbol:s,decimals:c,token:t}}async function DM(e,t){if(t?.chain){let n=N({chain:t.chain,transport:L(t.rpcUrl)}),r=t.chain.blockExplorers?.default?.url,i=X.dim(`(${CM(t.chain)})`);return TM(t.chain)?(await Promise.all(NM.map(t=>EM(n,t,e)))).filter(e=>e.balance>0n).map(e=>`${yM(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`):(await Promise.all(MM.map(t=>EM(n,t,e)))).map(e=>`${yM(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`)}let n=N({chain:ve,transport:L(bM())}),r=ve.blockExplorers?.default?.url,i=(await Promise.all(MM.map(t=>EM(n,t,e)))).map(e=>yM(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token}));if(t?.includeTestnet!==!1){let t=N({chain:ye,transport:L()}),n=ye.blockExplorers?.default?.url,r=await Promise.all(NM.map(n=>EM(t,n,e)));for(let e of r)e.balance>0n&&i.push(`${yM(e.balance,e.symbol,e.decimals,{explorerUrl:n,token:e.token})} ${X.dim(`(testnet)`)}`)}return i}var OM,kM,AM,jM,MM,NM,PM=z((()=>{Qj(),aM(),OM=new Set([`amount`,`suggestedDeposit`,`minVoucherDelta`]),kM={mainnet:iM[$j.mainnet],testnet:iM[$j.testnet]},AM=`0x20c0000000000000000000000000000000000000`,jM=`0x20C000000000000000000000b9537d11c60E8b50`,MM=[AM,jM],NM=[`0x20c0000000000000000000000000000000000000`,`0x20c0000000000000000000000000000000000001`,`0x20c0000000000000000000000000000000000002`,`0x20c0000000000000000000000000000000000003`]}));function FM(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:qM}function IM(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function LM(e){return new B({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 RM(e){if(e&&IM(e,`secret-tool`))throw LM(e)}function zM(e,t){return new Promise(n=>{m.execFile(e,t,{timeout:FM()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function BM(){let e=c.join(process.env.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`mppx`,`default`);return{get(){try{return t.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,n,`utf-8`)},clear(){try{t.unlinkSync(e)}catch{}}}}function VM(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:BM().get())}function HM(e=`main`){let t=KM;return{async list(){let e=x.platform();if(e===`darwin`){let{stdout:e,error:n}=await zM(`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 zM(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(RM(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=x.platform();if(n===`darwin`){let{stdout:n,error:r}=await zM(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await zM(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return RM(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=x.platform();if(r===`darwin`){await zM(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await zM(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=m.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),FM());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(IM(e,`secret-tool`)?LM(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=x.platform();if(n===`darwin`){await zM(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await zM(`secret-tool`,[`clear`,`service`,t,`account`,e]);RM(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function UM(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=VM(e),i=await HM(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function WM(e){let t=VM(e);if(!process.env.MPPX_PRIVATE_KEY?.trim()&&gM(t))throw new B({code:`UNSUPPORTED_ACCOUNT`,message:`Persistent sessions require an mppx account or MPPX_PRIVATE_KEY.`,exitCode:2});return UM(e).catch(e=>{throw new B({code:`ACCOUNT_NOT_FOUND`,message:e instanceof Error?e.message:`No account found.`,exitCode:69,...e instanceof Error&&{cause:e}})})}async function GM(e){return(await UM(e)).account}var KM,qM,JM=z((()=>{PM(),KM=`mppx`,qM=1e4}));Zj(),JM();const YM=[[`ANTIGRAVITY_CLI_ALIAS`,`antigravity`],[`CLAUDECODE`,`claude_code`],[`CLINE_ACTIVE`,`cline`],[`CODEX_SANDBOX`,`codex_cli`],[`CODEX_THREAD_ID`,`codex_cli`],[`CODEX_SANDBOX_NETWORK_DISABLED`,`codex_cli`],[`CODEX_CI`,`codex_cli`],[`CURSOR_AGENT`,`cursor`],[`GEMINI_CLI`,`gemini_cli`],[`OPENCODE`,`open_code`],[`OPENCLAW_SHELL`,`openclaw`],[`CLAUDE_CODE_ENTRYPOINT`,`claude_code`],[`CODEX_INTERNAL_ORIGINATOR_OVERRIDE`,`codex_cli`]];function XM(e=process.env){return YM.find(([t])=>e[t])?.[1]}function ZM(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function QM(e,t){let{chainId:n,decimals:r}=t;if(typeof e==`string`)return{address:e,chainId:n,decimals:r};if(ZM(e))return e.addresses[n]?e(n):void 0;if(e.chainId===n)return e}function $M(e,t,n={}){let{chainId:r,decimals:i}=n,a=e=>e.toLowerCase()===t.toLowerCase();for(let t of e){if(typeof t==`string`){if(a(t))return{currency:t,decimals:i};continue}if((r===void 0?ZM(t)?Object.keys(t.addresses).map(e=>QM(t,{chainId:Number(e)})):[t]:[QM(t,{chainId:r})]).some(e=>e&&a(e.address)))return{currency:t,decimals:t.decimals}}}var eN=z((()=>{}));eN();const tN=Symbol(`mppx.x402.asset`);function nN(e){return{[tN]:!0,address:e.address,chainId:gN(e.network),decimals:e.decimals,network:e.network,transfer:e.transfer}}function rN(e,t){let n=e(t.chainId);return nN({address:n.address,decimals:n.decimals,network:hN(t.chainId),transfer:_N(t.transfer,n)})}const iN={USDC:nN({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},aN={USDC:nN({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},oN={USDC:nN({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:nN({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},sN={USDC:nN({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},cN=[iN,aN,oN,sN].flatMap(e=>Object.values(e));function lN(e,t){let n=e.toLowerCase();return cN.find(e=>e.network===t&&e.address.toLowerCase()===n)}function uN(e){return typeof e!=`object`||!e?!1:e[tN]===!0}const dN=ZM;function fN(e){return typeof e==`string`}function pN(e,t){if(uN(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(typeof e==`string`)return{address:e};let n=QM(e,{chainId:gN(t)});if(n)return{address:n.address,decimals:n.decimals,name:n.name}}function mN(e,t,n){let r=pN(e,n);return r?I(r.address)===I(t):!1}function hN(e){return`eip155:${e}`}function gN(e){return Number(e.slice(7))}function _N(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 vN=it({base:()=>iN,baseSepolia:()=>aN,celo:()=>oN,celoSepolia:()=>sN,define:()=>nN,fromToken:()=>rN,isAsset:()=>uN,isRawAddress:()=>fN,isToken:()=>dN,lookup:()=>lN,matches:()=>mN,resolve:()=>pN,toChainId:()=>gN,toNetwork:()=>hN}),yN=it({base:()=>bN,baseSepolia:()=>xN,celo:()=>SN,celoSepolia:()=>CN});const bN=8453,xN=84532,SN=42220,CN=11142220;lS();function wN(e){let t=[cS(e.accepted),cS(e.resource),cS(e.extensions)].join(`|`);return j.sha256(A.fromString(t),{as:`Hex`})}HT(),Uw();async function TN(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=yw(n);if(kN(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?jN(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:I(t.address),nonce:i?.mppx?wN({accepted:r,extensions:i,resource:n.resource}):NN(),to:I(r.payTo),validAfter:(c-600).toString(),validBefore:(c+r.maxTimeoutSeconds).toString(),value:r.amount},u=await t.signTypedData({domain:{chainId:ON(r.network),name:o,verifyingContract:I(r.asset),version:s},message:{...l,value:BigInt(l.value),validAfter:BigInt(l.validAfter),validBefore:BigInt(l.validBefore)},primaryType:`TransferWithAuthorization`,types:DN});return zT({accepted:r,...i?{extensions:i}:{},payload:{authorization:l,signature:u},...n.resource?{resource:n.resource}:{},x402Version:2})}function EN(e){let t=e.challenge.request,n;try{n=yw(t),kN(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 DN={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 ON(e){return Number(e.slice(Sw.length))}function kN(e,t){let n=ON(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=>fN(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=I(t.asset);if(!r.some(n=>mN(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=AN(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>me(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function AN(e,t){let n=e.currencies??e.assets,r=I(t.asset),i=n?.find(e=>mN(e,r,t.network)),a=i?pN(i,t.network):void 0;return a?.decimals===void 0?e.decimals===void 0?lN(r,t.network)?.decimals:e.decimals:a.decimals}function jN(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:MN()}}}:e}function MN(){return PN().slice(2)}function NN(){return PN()}function PN(){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(``)}`}xS();const FN=[`authorization`],IN=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 LN=Y.object({chainId:Y.number(),credentialTypes:Y.optional(Y.array(Y.enum(FN)).check(Y.minLength(1))),decimals:Y.optional(Y.number()),permit2Address:Y.optional(gS()),splits:Y.optional(Y.array(Y.object({amount:IN,recipient:gS()})))});Y.object({amount:IN,currency:gS(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),methodDetails:LN,recipient:gS()});const RN=Y.object({amount:dS(),chainId:Y.number(),currency:gS(),credentialTypes:Y.optional(Y.array(Y.enum(FN)).check(Y.minLength(1))),decimals:Y.number(),description:Y.optional(Y.string()),externalId:Y.optional(Y.string()),permit2Address:Y.optional(gS()),recipient:gS(),splits:Y.optional(Y.array(Y.object({amount:IN,recipient:gS()})))}),zN=Y.object({from:gS(),nonce:_S(),signature:yS(),to:gS(),type:Y.literal(`authorization`),validAfter:IN,validBefore:IN,value:IN}),BN={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 VN(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function HN(e){return j.keccak256(A.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function UN(e){return`eip155:${e}`}function WN(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}xk(),xS();const GN=yk({name:`evm`,intent:`charge`,schema:{credential:{payload:zN},request:Y.pipe(RN,Y.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...c})=>({...c,amount:me(e,i).toString(),currency:I(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:I(a)}:{},...s?{splits:s}:{}},recipient:I(o)})))}});PE(),vC(),ZC(),xk(),xS();function KN(e){return TE(bk(GN,{canHandleChallenge({challenge:t}){return!qN(t)||EN({challenge:t,config:e})},context:Y.object({account:Y.optional(Y.custom())}),async createCredential({challenge:t,context:n}){if(qN(t))return TN({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;JN(e,i);let a=XN(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return pC(fC({challenge:t,payload:{from:I(r.address),nonce:HN(t),signature:await r.signTypedData({domain:VN({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:I(r.address),nonce:HN(t),to:I(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:BN}),to:I(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:WN({address:I(r.address),chainId:i.methodDetails.chainId})}))}}),{assert(t){qN(t)||JN(e,t.request)}})}function qN(e){return YC(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function JN(e,t){if(YN(e,t),!t.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(t.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`)}function YN(e,t){let n=t.methodDetails.chainId,r=UN(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=>fN(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=I(t.currency);if(!i.some(t=>mN(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=ZN(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>me(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function XN(e,t){let n=e.currencies??e.assets,r=I(t.currency),i=UN(t.methodDetails.chainId),a=n?.find(e=>mN(e,r,i)),o=a?pN(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;let s=lN(r,i)?.transfer;if(s?.type===`eip3009`)return{name:s.name,version:s.version};throw Error(`EVM authorization requires token name and version.`)}function ZN(e,t){let n=e.currencies??e.assets,r=I(t.currency),i=UN(t.methodDetails.chainId),a=n?.find(e=>mN(e,r,i)),o=a?pN(a,i):void 0;return o?.decimals===void 0?e.decimals===void 0?lN(r,i)?.decimals:e.decimals:o.decimals}function QN(e){return[QN.charge(e)]}(function(e){e.charge=KN,e.assets=vN,e.chains=yN})(QN||={});function $N(e){return e}var eP=z((()=>{}));ZC(),eP();function tP(){return $N({method:`evm`,supports:e=>e.method===`evm`&&!YC(e),async setup({challenge:e,options:t}){let n=e.request,r=n.methodDetails,i=r?.chainId,a=i?nP(i):void 0,o=n.currency,s=await GM(t.account),c=[...Object.values(iN),...Object.values(aN),...Object.values(oN),...Object.values(sN)],l=o??``;if(a&&o)try{let e=N({chain:a,transport:L()}),t=await je(e,{address:o,abi:F,functionName:`symbol`});t&&(l=t)}catch{}return{tokenSymbol:l,tokenDecimals:r?.decimals??6,explorerUrl:a?.blockExplorers?.default?.url,methods:[...QN({account:s,currencies:c})]}}})}function nP(e){return Object.values(Qe).find(t=>t.id===e)}function rP(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`Decimals must be a non-negative integer.`);if(!/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))throw TypeError(`Value \`${e}\` is not a valid decimal number.`);let n=e.startsWith(`-`),[r=`0`,i=``]=(n?e.slice(1):e).split(`.`),a=i.slice(0,t).padEnd(t,`0`),o=BigInt(`${r||`0`}${a}`);return i.length>t&&i[t]>=`5`&&(o+=1n),n?-o:o}xS();const iP=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)))}),aP=Y.custom(e=>typeof e==`function`),oP=Y.union([iP,aP]);xk(),xS();const sP=yk({name:`stripe`,intent:`charge`,schema:{credential:{payload:Y.object({externalId:Y.optional(Y.string()),spt:Y.string()})},request:Y.pipe(Y.object({amount:dS(),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(oP),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:rP(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});vC(),xk(),xS();function cP(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return bk(sP,{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 pC({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function lP(e){return[cP(e)]}(function(e){e.charge=cP})(lP||={}),Rx(),PM(),eP();function uP(){return $N({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=fP(p.object({paymentMethod:p.string(),secretKey:p.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new B({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:[lP.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=dP(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":fk},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 B({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${e.error.message}`,exitCode:77})}}else throw new B({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&&dP(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function dP(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function fP(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 pP(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 _e(r)}}var mP=z((()=>{}));function hP(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}var gP=z((()=>{}));function _P(e,t={}){return L(e.url,{fetchFn:e.fetch,fetchOptions:{headers:hP(e)},...t})}function vP(e){let{chain:t,getClient:n,remoteFeePayer:r,rpcUrl:i}=e;return n?!t?.serializers&&!r&&!e.requireChain?n:async i=>{let a=await n(i);if(e.requireChain&&(a.chain?.id===void 0||a.chain.id!==i.chainId))throw Error(`Subscription chain mismatch: expected ${i.chainId}, got ${a.chain?.id??`unknown`}.`);let o=a;if(r&&a.transport.key!==`feePayer`){let e=a.request.bind(a),t=We(re({request:t=>e(t)},{retryCount:0}),_P(r,{retryCount:a.transport.retryCount}))({account:a.account,chain:a.chain,pollingInterval:a.pollingInterval,retryCount:0}),n=P({...t.config,retryCount:0},t.value);o=Object.assign({},a,{request:n.request,transport:{...n.config,...n.value}})}return!t?.serializers||o.chain?.serializers?.transaction?o:Object.assign({},o,{chain:{...t,...i.chainId===void 0?{}:{id:i.chainId},...o.chain,formatters:o.chain?.formatters??t.formatters,prepareTransactionRequest:o.chain?.prepareTransactionRequest??t.prepareTransactionRequest,serializers:o.chain?.serializers?.transaction?o.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?We(L(a),_P(r)):L(a);return N({chain:xP[n]??{...t,id:n},transport:o})}}function yP(e,t){if(t!==void 0&&e.chain?.id!==void 0&&e.chain.id!==t)throw Error(`Chain ID mismatch: expected ${t}, got ${e.chain.id}.`)}function bP(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}var xP,SP=z((()=>{gP(),xP={[ve.id]:ve,[ye.id]:ye}}));function CP(e){let t=j.keccak256(A.fromString(e),{as:`Hex`});return M.toBytes(M.slice(t,0,10))}function wP(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(M.toBytes(EP),0),i[4]=DP,i.set(CP(t),5),n&&i.set(CP(n),15),i.set(TP(r),25),M.fromBytes(i)}function TP(e){let t=j.keccak256(A.fromString(e),{as:`Hex`});return M.toBytes(M.slice(t,0,7))}var EP,DP,OP=z((()=>{EP=M.slice(j.keccak256(A.fromString(`mpp`),{as:`Hex`}),0,4),DP=1}));async function kP(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t;if(!Number.isFinite(o)||o<0||o>50)throw Error(`Auto-swap slippage must be between 0 and 50 percent.`);if(t.maxAmountIn!==void 0&&t.maxAmountIn<=0n)throw Error(`Auto-swap maxAmountIn must be positive.`);let s=e.chain?.id,c=[];for(let e of a){let t=typeof e==`string`?e:s===void 0?void 0:QM(e,{chainId:s})?.address;!t||Sk(t,i)||c.some(e=>Sk(e,t))||c.push(t)}let l=await Promise.allSettled([je(e,{...Be.token.getBalance.call(e,{account:n,token:i}),account:null}),...c.map(t=>je(e,{...Be.token.getBalance.call(e,{account:n,token:t}),account:null}))]),u=l[0];if(u.status!==`fulfilled`)throw u.reason;let d=u.value;if(d>=r)return;let f=r-d,p=BigInt(Math.round(o*100)),m=t.maxAmountIn??f+f*p/jP;for(let t=0;t<c.length;t++){let n=l[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=c[t];try{let t=await Be.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:f});if(t<=0n||t>m)continue;let n=t+t*p/jP,o=n<m?n:m;if(r>=o)return[Be.token.approve.call(e,{amount:o,spender:Ve.stablecoinDex,token:a}),Be.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:f,maxAmountIn:o})]}catch{}}throw new NP({currency:i})}function AP(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...e.fallback===!1?[]:t.filter(t=>!e.tokenIn.some(e=>typeof e==`string`&&Sk(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var jP,MP,NP,PP=z((()=>{eN(),Ck(),aM(),jP=10000n,MP=[eM.pathUsd,eM.usdc,eM.ousd],NP=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}}}));function FP(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:BigInt(e.amount).toString(),memo:e.memo,recipient:e.recipient}))]}var IP=z((()=>{}));function LP(e,t,n){t&&(n&&!n.some(e=>Sk(e,t))||e.some(e=>Sk(e,t))||e.push(t))}async function RP(e,t,n){try{return(await Be.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function zP(e){let t=e.chain?.feeToken;if(t)return He.toAddress(t);let n=e.chain?.id;return n?tM[n]:void 0}function BP(e){let t=[];return LP(t,eM.pathUsd),LP(t,tM[e]),t}async function VP(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])LP(o,e,n);if(LP(o,await Be.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),LP(o,zP(i),n),!a)for(let e of r??[])LP(o,e,n);for(let e of o)if(await RP(i,t,e))return e;return o[0]}var HP=z((()=>{Ck(),aM()}));function UP(e){if(e!==void 0)return nM[e]}function WP(e){let t=UP(e.chainId);return!!t&&le(e.currency,{strict:!1})&&ue(e.currency,t.token)}function GP(e){let t=UP(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let r=BigInt(n.amount),i=n.memo;return{calls:[{data:ae({abi:Re.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:ae({abi:ZP,functionName:`swapTo`,args:[t.token,r,e.currency,n.recipient,i]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:r,memo:i,recipient:n.recipient}]}}async function KP(e,t){let n=GP(t);if(n)try{return await je(e,Be.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await De(e,{account:t.account,calls:n.calls}),n)}catch{return}}function qP(e={}){let{address:t,amount:n,chainId:r=$j.mainnet}=e;if(r!==$j.mainnet)return;let i=new URL(rM);if(t&&le(t,{strict:!1})&&i.searchParams.set(`address`,I(t)),n!==void 0&&n>0n){let e=(n+QP-1n)/QP,t=e%100n,r=(e/100n).toString();i.searchParams.set(`amount`,t===0n?r:`${r}.${t.toString().padStart(2,`0`).replace(/0$/,``)}`)}return i.toString()}async function JP(e,t){let n=UP(t.chainId);if(!n)return;let r=await je(e,Be.token.getBalance.call(e,{account:t.account,token:n.token})).catch(()=>void 0);return typeof r==`bigint`?r:void 0}async function YP(e,t){let{account:n,amount:r,chainId:i}=t,a=await JP(e,{account:n,chainId:i});if(a===void 0||a>=r)return;let o=e=>`${oe(e,6)} MACH`,s=r-a;return{fundingUrl:qP({address:n,amount:s,chainId:i}),reason:`requested ${o(r)}, available ${o(a)}`,shortfall:s}}async function XP(e,t){let n=await YP(e,t);if(n)return new iS({fundingUrl:n.fundingUrl,reason:n.reason})}var ZP,QP,$P=z((()=>{aS(),aM(),ZP=fe([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]),QP=10n**BigInt(4)}));function eF(e){return{name:`MPP`,version:`3`,chainId:e}}function tF(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function nF(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:eF(n),types:aF,primaryType:iF,message:tF({account:t,challengeId:r,realm:i})}}function rF(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}var iF,aF,oF=z((()=>{iF=`Proof`,aF={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]}}));function sF(e){let t=new Set,n=e;for(;typeof n==`object`&&n&&!t.has(n);){t.add(n);let e=n.data;if(uF(e))return e;let r=e?.data;if(uF(r))return r;n=n.cause}}function cF(e,t){let n=sF(e);if(!n)return;let r=(()=>{try{return ie({abi:dF,data:n})}catch{return}})();if(r?.errorName===`SpendingLimitExceeded`){let n=t.account.accessKeyAddress;return new tS({accessKey:typeof n==`string`?n:void 0,account:t.account.address,cause:e})}if(r?.errorName===`InsufficientBalance`){let[n,i,a]=r.args;return new iS({cause:e,reason:`${t.account.address} holds ${n} of token ${a}, but the payment requires ${i}`})}}async function lF(e,t){try{return await t()}catch(t){throw cF(t,e)??t}}function uF(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{8}/.test(e)}var dF,fF=z((()=>{aS(),dF=[...Re.accountKeychain.filter(e=>e.type===`error`),...Re.tip20.filter(e=>e.type===`error`)]}));function pF(e={}){let{clientId:t}=e;if((e.maxAmount!==void 0||e.maxAtomicAmount!==void 0)&&e.currencies===void 0)throw Error(`Tempo charge maxAmount and maxAtomicAmount require currencies.`);for(let t of e.currencies??[])AF(e.maxAmount,typeof t==`string`?e.decimals:t.decimals);let n={maxAmount:e.maxAmount,maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=vP({chain:ve,getClient:e.getClient,rpcUrl:iM}),i=pP({account:e.account});SF(e.zone);let a=new Map,o=bk(Zk,{canHandleChallenge({challenge:t}){try{return jF(e,n,t.request),!0}catch{return!1}},context:MF,async createCredential(o){let{challenge:s,context:c}=o,l=OE(o),u=()=>Error(`The Zone withdrawal this challenge resumes is no longer outstanding. Retry the request to pay it.`);jF(e,n,s.request);let d=s.request.methodDetails?.chainId,f=d??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),p=await r({chainId:f});yP(p,f);let m=f??p.chain?.id;if(bP(e.allowedChainIds,m),m===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");d===void 0&&jF(e,n,s.request,m);let{request:h}=s,{amount:g,methodDetails:_}=h,v=_?.supportedModes??[`pull`,`push`],y=e.zone?.client.chain,b=e.zone?e.zone.zoneId??Dk(y?.id??0):void 0,x=y?.sourceId??(y?Ok(y.id):void 0),S=c?.mode??e.mode;if(BigInt(g)>0n&&e.zone&&b!==void 0&&x===m&&v.includes(`push`)&&(S===void 0||S===`push`)&&Tk(_?.zones,b)&&!_?.splits){let r={assertFee:t=>jF(e,n,h,m,t),challenge:s,clientId:t,client:p,origin:xF(cE(o)),pending:a,zone:e.zone,zoneId:b},i=_F(r);if(i)return yF(r,i);if(l?.resume)throw u();if(s.expires&&yC(s.expires,s.id),CF(s.expires,e.zone.settlementTimeoutMs))return gF(r)}if(l?.resume)throw u();let C=i(p,c),w=async t=>await e.resolveAccount?.({account:C,chainId:m,operation:t})??C;if(BigInt(g)===0n){let e=await w({kind:`signPaymentProof`});return pC({challenge:s,payload:{signature:await Ie(p,{account:e,...nF({account:e.address,chainId:m,challengeId:s.id,realm:s.realm})}),type:`proof`},source:rF({address:e.address,chainId:m})})}let T=h.currency,E=WP({chainId:m,currency:T}),ee=_?.memo??wP({challengeId:s.id,clientId:t,serverId:s.realm}),D=FP({amount:g,methodDetails:{..._,memo:ee},recipient:h.recipient}),O=D.map(e=>Be.token.transfer.call(p,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:T})),k=AP(c?.autoSwap??e.autoSwap,MP),te=_?.machineTokenEnabled===!0&&!l?GP({chainId:m,currency:T,transfers:D}):void 0,A=C,j,M=!1;if(te){let e=await(async()=>{try{return await w({calls:te.calls,kind:`executeCalls`})}catch{return}})();e&&(j=await KP(p,{account:e.address,chainId:m,currency:T,transfers:D}),j?A=e:M=!0)}let ne;if(!j){if(A=await w({kind:`executeCalls`,...k?{}:{calls:O}}),ne=k?await kP(p,{account:A.address,amountOut:BigInt(g),tokenOut:T,tokenIn:k.tokenIn,slippage:k.slippage,maxAmountIn:k.maxAmountIn}):void 0,l&&ne)throw new rS({limit:l.limit,reason:`asset`});if(M&&!k){let e=await mF(p,{account:A.address,amount:BigInt(g),chainId:m,currency:T});if(e)throw e}}let N=j?.calls??[...ne??[],...O],P=BP(m),re=(c?.feeToken??e.feeToken)||(j||E?await VP({account:A.address,allowedTokens:P,candidateTokens:P,client:p,prioritizeCandidates:!0}):void 0),ie=(()=>{let t=c?.mode??e.mode;if(t){if(!v.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=A.type===`json-rpc`?`push`:`pull`;return v.includes(n)?n:v[0]})(),ae=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!s.expires)return e;let t=Math.floor(new Date(s.expires).getTime()/1e3)+1;return Math.min(e,t)})(),F=()=>{l&&s.expires&&yC(s.expires,s.id)};if(ie===`push`){F();let{receipts:e}=A.type===`local`?{receipts:[await lF({account:A},()=>Pe(p,{account:A,calls:N,...re?{feeToken:re}:{},nonceKey:`expiring`,validBefore:ae}))]}:await Me(p,{account:A,...re?{capabilities:{feeToken:re}}:{},calls:N,experimental_fallback:N.length===1,forceAtomic:N.length>1}),t=e?.[0]?.transactionHash;if(!t)throw xE(Error(`No transaction receipt returned.`));return pC({challenge:s,payload:{hash:t,type:`hash`},source:rF({address:A.address,chainId:m})})}let oe=()=>{if(_?.feePayer!==!0)return;let e=15e3,t=s.expires?new Date(s.expires).getTime():1/0,n=Date.now();if(!(t-n>=e))throw Error(`Sponsored challenge expires in less than 15 seconds; the fee payer would reject the transaction. Request a new challenge.`);if(!(ae*1e3-n>=e))throw Error(`Sponsored transaction preparation took too long: less than 15 seconds of its validity window remain, so the fee payer would reject it.`)};oe();let se=await lF({account:A},()=>Ae(p,{account:A,calls:N,...re?{feeToken:re}:{},nonceKey:`expiring`,validBefore:ae}));if(se.gas=(se.gas??0n)+5000n,_?.feePayer){let e=se;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return oe(),F(),pC({challenge:s,payload:{signature:await Fe(p,se),type:`transaction`},source:rF({address:A.address,chainId:m})})}}),s=new Map,c=async t=>{jF(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=OE(t),c=s.get(i);if(a&&kE(a,c?.constraints),c)return c.promise;let l=o.createCredential(t).finally(()=>s.delete(i));return s.set(i,{constraints:a,promise:l}),l};return TE(aE({...o,createCredential:c},hF),{assert:t=>jF(e,n,t.request),resumes:t=>vF(a,t,e.zone&&(e.zone.zoneId??Dk(e.zone.client.chain?.id??0)))})}async function mF(e,t){let{account:n,amount:r,chainId:i,currency:a}=t,o=await je(e,Be.token.getBalance.call(e,{account:n,token:a})).catch(()=>void 0);if(!(typeof o!=`bigint`||o>=r))return XP(e,{account:n,amount:r,chainId:i})}function hF(e){let t=Zk.schema.credential.payload.safeParse(cC(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`||n.type===`zone`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(Xe.serializedType))return;let i=Xe.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&Xe.serialize(i)===r)return de(r)}function gF(e){let{challenge:t,origin:n,pending:r,zoneId:i}=e,a={sent:!1},o={challenge:t,origin:n,terms:EF(t,i),waiters:0,withdrawal:kF(e,a)},s=TF(t);return r.set(s,o),o.withdrawal.catch(()=>{!a.sent&&r.get(s)===o&&r.delete(s)}),yF(e,o)}function _F(e){let{challenge:t,pending:n,zoneId:r}=e,i=n.get(TF(t));if(i)return i;let a=EF(t,r);if(a!==void 0){for(let[e,t]of n)if(t.terms===a){if(!OF(t.challenge.expires)){n.delete(e);continue}if(t.redeemedLate)throw new nS({challengeId:t.challenge.id,senderTags:t.senderTags,zoneId:r});if(!(t.waiters>0))return t}}}function vF(e,t,n){if(n===void 0||e.size===0)return!1;if(e.has(TF(t)))return!0;let r=EF(t,n);if(r===void 0)return!1;for(let t of e.values())if(t.terms===r&&OF(t.challenge.expires)&&(t.redeemedLate||t.waiters===0))return!0;return!1}async function yF(e,t){t.waiters++;try{return await bF(e,t)}finally{t.waiters--}}async function bF(e,t){let{client:n,origin:r,pending:i,zone:a,zoneId:o}=e,{challenge:s}=t,c=s.request.recipient,l=TF(s);if((l===TF(e.challenge)?r!==void 0&&t.origin!==void 0&&r!==t.origin:!r||r!==t.origin)||!OF(s.expires))throw new nS({challengeId:s.id,zoneId:o});let u=await t.withdrawal,d=u.senderTags??await Ak(a.client,u).catch(e=>{let t=Error(`Zone withdrawal transaction ${u.transactionHash} was sent, but its sender tag could not be read from the Zone. Retry the challenge to resume without withdrawing again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),xE(t)}),f;try{f=await jk(n,{portal:Ek(o),senderTags:d,timeoutMs:wF(s.expires,a.settlementTimeoutMs),to:c})}catch(e){throw new nS({cause:e,challengeId:s.id,senderTags:d,zoneId:o})}i.get(l)===t&&(DF(s.expires)?(t.redeemedLate=!0,t.senderTags=[f.senderTag]):i.delete(l));let{hash:p,senderTag:m}=f;return pC({challenge:s,payload:{hash:p,senderTag:m,type:`zone`,zoneId:o}})}function xF(e){if(e)try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.origin}catch{return}}function SF(e){let t=e?.settlementTimeoutMs;if(t!==void 0&&(!Number.isFinite(t)||t<0))throw Error("`zone.settlementTimeoutMs` must be a finite, non-negative number.");let n=e?.client.chain?.id;if(e?.zoneId===void 0||n===void 0||Ok(n)===void 0)return;let r=Dk(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function CF(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+NF}function wF(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function TF(e){return JSON.stringify(e)}function EF(e,t){let n;try{n=e.opaque===void 0?e.meta:oS(e.opaque)}catch{return}let{digest:r,intent:i,method:a,realm:o,request:s}=e;return cS({digest:r,intent:i,meta:pk(n),method:a,realm:o,request:s,zoneId:t})}function DF(e){if(!e)return!1;let t=new Date(e).getTime();return!Number.isNaN(t)&&Date.now()>=t}function OF(e){if(!e)return!0;let t=new Date(e).getTime();return Number.isNaN(t)||Date.now()<t+3e5}async function kF(e,t){let{assertFee:n,challenge:r,clientId:i,zone:a}=e,o=r.request,s=a.client.account;if(!s)throw Error("`zone.client` requires an account.");let c=BigInt(o.amount),l=o.currency,u=o.recipient,d=wP({challengeId:r.id,clientId:i,serverId:r.realm}),f=await Be.zone.getWithdrawalFee(a.client);n(f);let[,p]=Be.zone.requestWithdrawal.calls({amount:c,fallbackRecipient:s.address,memo:d,to:u,token:l}),m=await Ae(a.client,{account:s,calls:[Be.token.approve.call({amount:c+f,spender:Ve.zoneOutbox,token:l}),p]}),h=await Fe(a.client,m);t.sent=!0;let g=de(h),_=await Ne(a.client,{serializedTransaction:h}).catch(e=>Le(a.client,{hash:g,timeout:PF}).catch(()=>{let t=new Zx({cause:e,transactionHash:g});throw t.message=`Zone withdrawal outcome is unknown: transaction ${g} may have been sent. Retrying this challenge does not withdraw again.`,t}));if(_.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${_.transactionHash} reverted.`);let[v]=pe({abi:Re.zoneOutbox,eventName:`WithdrawalRequested`,logs:_.logs});return{blockNumber:_.blockNumber,sender:s.address,senderTags:v?[kk({fallbackNonce:v.args.fallbackNonce,sender:v.args.sender,transactionHash:_.transactionHash})]:void 0,transactionHash:_.transactionHash}}function AF(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo charge maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo charge maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return me(e,t)}}function jF(e,t,n,r,i){let{methodDetails:a,recipient:o}=n,s=a?.chainId;if(e.expectedChainId!==void 0&&s!==void 0&&s!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${s}.`);(s!==void 0||e.allowedChainIds?.length===0)&&bP(e.allowedChainIds,s);let c=e.currencies?$M(e.currencies,n.currency,{chainId:s??r??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),decimals:e.decimals}):void 0;if(e.currencies&&!c)throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!o||!t.has(o.toLowerCase()))throw Error(`Unexpected primary recipient: ${o}`);let n=a?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(t.maxAtomicAmount===void 0&&t.maxAmount===void 0)return;let l=BigInt(n.amount)+(i??0n),u=i===void 0?`amount exceeds`:`amount plus Zone withdrawal fee exceeds`;if(t.maxAtomicAmount!==void 0&&l>t.maxAtomicAmount)throw Error(`Tempo charge ${u} maxAtomicAmount.`);if(t.maxAmount!==void 0&&l>AF(t.maxAmount,c?.decimals))throw Error(`Tempo charge ${u} maxAmount.`)}var MF,NF,PF,FF=z((()=>{wE(),pE(),PE(),vC(),eN(),aS(),bC(),vk(),xk(),lS(),mP(),SP(),xS(),OP(),PP(),IP(),aM(),HP(),$P(),oF(),fF(),Rk(),eA(),MF=Y.object({account:Y.optional(Y.custom()),autoSwap:Y.optional(Y.custom()),feeToken:Y.optional(Y.custom()),mode:Y.optional(Y.enum(Vk))}),NF=15e3,PF=15e3}));function IF(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function LF(e){let t=k.encode(k.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 j.keccak256(t)}function RF(e){return Xe.encodeForSigning(e)}function zF(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function BF(e,t){return j.keccak256(M.concat(RF(e),t.sender))}var VF=z((()=>{CA()})),HF,UF,WF,GF,KF=z((()=>{HF=[{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`}],UF=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],WF={name:`descriptor`,type:`tuple`,components:HF},GF=[{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:[WF,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[WF,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[WF,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[WF],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[WF],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[WF],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:HF},{name:`state`,type:`tuple`,components:UF}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:UF}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:UF}]},{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:`verifyVoucher`,stateMutability:`view`,inputs:[WF,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[{name:`valid`,type:`bool`}]},{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:`OpeningCommitmentRecorded`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`signer`,type:`address`,indexed:!0},{name:`commitment`,type:`bytes32`}]},{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}]},{type:`error`,name:`RootKeyRetired`,inputs:[{name:`account`,type:`address`}]},{type:`error`,name:`SignerConfigChanged`,inputs:[{name:`signer`,type:`address`}]},{type:`error`,name:`SaltNotSignerCommitment`,inputs:[{name:`signer`,type:`address`},{name:`commitment`,type:`bytes32`}]}]}));function qF(e){return e.type===`secp256k1`?e.signature.s<=ZF:e.type===`p256`||e.type===`webAuthn`?e.signature.s<=QF:!0}function JF(e){if(e.type===`configurable`)return{...e,signatures:e.signatures.map(e=>JF(e))};if(qF(e))return e;if(e.type===`secp256k1`){let{r:t,s:n,yParity:r}=e.signature;return{...e,signature:{r:t,s:YF-n,yParity:+(r===0)}}}return e.type===`p256`||e.type===`webAuthn`?{...e,signature:{...e.signature,s:XF-e.signature.s}}:e}var YF,XF,ZF,QF,$F=z((()=>{YF=115792089237316195423570985008687907852837564279074904382605163141518161494337n,XF=115792089210356248762697446949407573529996955224135760342422259061068512044369n,ZF=57896044618658097711785492504343953926418782139537452191302581570759080747168n,QF=57896044605178124381348723474703786764998477612067880171211129530534256022184n}));function eI(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function tI(e){return e===void 0||BigInt(e)===0n}function nI(e,t){let{account:n,config:r,signatures:i}=e,a=Ge.getSignPayload({account:n,config:r,payload:t}),o=Number(r.threshold),s,c=0,l;for(let[e,t]of i.entries()){if(!eI(t.type)||!qF(t)||e>0&&c>=o)return!1;let n=Je.extractAddress({payload:a,signature:t});if(!Je.verify(t,{address:n,payload:a}))return!1;let i=r.owners.find(e=>Sk(e.owner,n));if(!i)return!1;let u=Number(i.weight);if(u===0)return!1;let d=BigInt(n);if(s!==void 0&&s>=d)return!1;s=d,c+=u,l=l===void 0?u:Math.min(l,u)}return!(i.length===0||c<o||l!==void 0&&c>=o+l)}function rI(e,t){let{account:n,commitment:r,payload:i}=t;if(!Sk(e.account,n)||BigInt(e.config.version??0n)===0n&&e.config.owners.some(({owner:t})=>Sk(t,e.account)))return!1;if(tI(r)){if(BigInt(e.config.version??0n)!==0n||!Sk(Ge.getAddress(e.config),n))return!1}else if(Ge.getCommitment(e.config).toLowerCase()!==r.toLowerCase())return!1;return nI(e,i)}var iI=z((()=>{Ck(),$F()}));function aI(e,t){return{name:vI,version:yI,chainId:t,verifyingContract:e}}function oI(e,t,n){return ce({domain:aI(e,t),types:xI,primaryType:`CloseAuthorization`,message:n})}function sI(e,t){return Ke.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function cI(e,t,n){return e.toLowerCase()===Ke.address.toLowerCase()?sI(t,n):ce({domain:aI(e,t),types:bI,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function lI(e,t,n,r){let i=uI(e);return i?dI(i,t,n,r):!1}function uI(e){let t=Je.from(e);if(Je.serialize(t).toLowerCase()===e.toLowerCase())return t}function dI(e,t,n,r){if(e.type===`configurable`)return r.configurable?rI(e,{account:n,commitment:r.openingCommitment,payload:t}):!1;if(!eI(e.type)||!qF(e)||!tI(r.openingCommitment))return!1;let i=Je.extractAddress({payload:t,signature:e});return Je.verify(e,{address:i,payload:t})&&Sk(i,n)}function fI(e){return e.source===`configurable`}function pI(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function mI(e,t){return ze.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function hI(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===Ke.address.toLowerCase())try{return await mI(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return Ie(e,{account:t,domain:aI(r,i),types:bI,primaryType:`Voucher`,message:n})})(),o=Je.from(a);if(!eI(o.type)&&o.type!==`configurable`)throw Error(`TIP-1034 vouchers require a TIP-1020 primitive or TIP-1166 configurable account signature; received "${o.type}".`);return Je.serialize(JF(o))}async function gI(e,t,n,r,i){let a=pI(t)?await t.sign({hash:oI(r,i,n),raw:!0}):await Ie(e,{account:t,domain:aI(r,i),types:xI,primaryType:`CloseAuthorization`,message:n}),o=Je.from(a);if(!eI(o.type)&&o.type!==`configurable`)throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive or TIP-1166 configurable account signature; received "${o.type}".`);return Je.serialize(JF(o))}function _I(e,t,n,r,i={}){try{let a=cI(e,t,n);return lI(n.signature,a,r,i)}catch{return!1}}var vI,yI,bI,xI,SI=z((()=>{Ck(),iI(),$F(),vI=`TIP20 Channel Reserve`,yI=`1`,bI={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},xI={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]}}));function CI(e){return typeof e==`object`&&!!e}function wI(e){return typeof e==`string`&&le(e,{strict:!1})?e:void 0}function TI(e){return wI(e.accessKeyAddress)}function EI(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(M.random(8))%e)}function DI(e){return TI(e)??e.address}function OI(e){return kI(e)!==void 0}function kI(e){let t=TI(e);if(t===void 0)return fI(e)?e:void 0;let n=e.delegate;if(n&&fI(n)&&n.address.toLowerCase()===t.toLowerCase())return n}async function AI(e,t){let n=kI(t);if(!n)return M.random(32);let{config:r}=n,i=await Be.accounts.getConfigCommitment(e,{account:n.address}),a=r?Ge.getCommitment(r):void 0;if(BigInt(i)!==0n){if(a&&a.toLowerCase()!==i.toLowerCase())throw Error(`Configurable account ${n.address} holds a config whose commitment ${a} does not match its on-chain commitment ${i}. Use the account's current config.`);return i}if(!a||BigInt(r.version??0n)!==0n)throw Error(`Configurable account ${n.address} is not registered, so it needs its version-zero config to open a channel.`);return a}function jI(e,t){let n=sF(e);if(n)try{let r=ie({abi:GF,data:n});if(r.errorName!==`SignerConfigChanged`&&r.errorName!==`RootKeyRetired`)return;let[i]=r.args;return i.toLowerCase()===t.signer.toLowerCase()?new eS({cause:e,channelId:t.channelId,reason:r.errorName,signer:i}):void 0}catch{return}}async function MI(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return lF({account:n},()=>Ae(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}}))}async function NI(e,t){return await Fe(e,t)}function PI(e,t,n=!1){let r=e.request.methodDetails,i=CI(r)?wI(r.escrowContract)??wI(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!II(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!II(i,a)?i:a}function FI(e,t,n,r){return pC({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${t.descriptor?.payer??r.address}`})}function II(e,t){return e.toLowerCase()===t.toLowerCase()}function LI(e,t){let n=kI(e);if(!n?.config)return;let{config:r}=n;if(Ge.getCommitment(r).toLowerCase()!==t.salt.toLowerCase()&&(BigInt(r.version??0n)!==0n||Ge.getAddress(r).toLowerCase()!==n.address.toLowerCase()))throw Error(`Configurable account ${n.address} holds a config that does not match the channel's opening commitment (salt ${t.salt}), so it cannot sign a voucher the channel settles. Sign with the config the channel opened with, or close the channel and open a new one.`)}async function RI(e,t,n,r,i,a=SA){let o=LF({...n,chainId:i,escrow:a}),s=rA(r);LI(t,n);let c=await hI(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function zI(e,t,n,r,i,a=SA){let o=await RI(e,t,n,r,i,a),s=await gI(e,t,{channelId:o.channelId,cumulativeAmount:rA(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function BI(e,t,n){let r=DI(t),i=n.escrow??`0x4d50500000000000000000000000000000000000`,a=n.operator??`0x0000000000000000000000000000000000000000`,o=n.salt??await AI(e,t),s=rA(n.deposit),c=rA(n.initialAmount),l=ae({abi:GF,functionName:`open`,args:[n.payee,a,n.token,s,o,r]}),u=await NI(e,await MI(e,{account:t,calls:[...n.prefixCalls??[],{to:i,data:l}],feePayer:n.feePayer,feeToken:n.feeToken??n.token,validAfter:EI()})),d=Ue.deserialize(u),f={authorizedSigner:r,expiringNonceHash:BF(zF({...n.feePayer?{feePayer:!0}:{},transaction:d}),{sender:t.address}),operator:a,payee:n.payee,payer:t.address,salt:o,token:n.token},p=LF({...f,chainId:n.chainId,escrow:i});return{action:`open`,type:`transaction`,channelId:p,transaction:u,signature:await hI(e,t,{channelId:p,cumulativeAmount:c},i,n.chainId),descriptor:f,cumulativeAmount:c.toString(),authorizedSigner:f.authorizedSigner}}async function VI(e,t,n,r,i,a,o=SA,s=[],c=n.token){let l=LF({...n,chainId:i,escrow:o}),u=rA(r);return{action:`topUp`,type:`transaction`,channelId:l,transaction:await NI(e,await MI(e,{account:t,calls:[...s,{to:o,data:ae({abi:GF,functionName:`topUp`,args:[n,u]})}],feePayer:a,feeToken:c,validAfter:EI()}).catch(e=>{throw jI(e,{channelId:l,signer:IF(n)})??e})),descriptor:n,additionalDeposit:u.toString()}}var HI=z((()=>{vC(),aS(),fF(),VF(),KF(),CA(),SI()}));function UI(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function WI(e){return UI({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function GI(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(WI(t),t)},delete(t){e.delete(t)}}}function KI(e){return{...e,cumulativeAmount:e.cumulativeAmount.toString(),deposit:e.deposit.toString()}}function qI(e){return{...e,cumulativeAmount:BigInt(e.cumulativeAmount),deposit:BigInt(e.deposit)}}function JI(e,t){eL.set(e,eL.get(t)??t)}async function YI(e,t,n){let r=$I.get(e);r||(r=new Map,$I.set(e,r));let i=(r.get(t)??Promise.resolve()).catch(()=>{}).then(n);r.set(t,i);try{return await i}finally{r.get(t)===i&&r.delete(t)}}function XI(e,t,n){return YI(eL.get(e)??e,`funding:${t}`,n)}async function ZI(e,t){await YI(e,`write:${WI(t)}`,async()=>{let n=await e.get(WI(t));if(n?.origin!==void 0){if(t.origin!==void 0&&t.origin!==n.origin)throw Error(`SessionManager: stored channel origin mismatch`);t.origin=n.origin}if(n?.uncertainTopUp){if(n.channelId!==t.channelId)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);t.uncertainTopUp=!0}await e.set(t)})}async function QI(e,t){await YI(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}var $I,eL,tL=z((()=>{$I=new WeakMap,eL=new WeakMap}));function nL(e){if(e<0n||e>sL)throw new J({reason:`amount exceeds uint96 range`})}async function rL(e,t,n=SA){let{cumulativeAmount:r,descriptor:i,signature:a}=t;return je(e,{address:n,abi:GF,functionName:`verifyVoucher`,args:[oL(i),r,a]})}async function iL(e,t,n=SA,r){return aL(await je(e,{address:n,abi:GF,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function aL(e){return nL(e.settled),nL(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}function oL(e){return{payer:e.payer,payee:e.payee,operator:e.operator,token:e.token,salt:e.salt,authorizedSigner:e.authorizedSigner,expiringNonceHash:e.expiringNonceHash}}var sL,cL=z((()=>{aS(),KF(),CA(),sL=2n**96n-1n}));function lL(e){return`cumulativeAmount`in e}function uL(e){if(lL(e))return BigInt(e.cumulativeAmount)}async function dL(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await ZI(e.store,t):await QI(e.store,WI(t)),e.notifyUpdate(t)}async function fL(e,t,n){let r=uL(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 dL(e,i))}function pL(e){return e?.action!==void 0}function mL(e){return pL(e)&&e.descriptor!==void 0}function hL(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 me(i,t)}function gL(e,t,n,r){let i=hL(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function _L(e){return typeof e==`object`&&!!e}function vL(e){return typeof e==`string`&&le(e,{strict:!1})?e:void 0}function yL(e){let t=e.request.methodDetails;return _L(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:vL(t.escrowContract),escrow:vL(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:vL(t.feeToken),operator:vL(t.operator),configurableVouchers:typeof t.configurableVouchers==`boolean`?t.configurableVouchers:void 0,sessionSnapshot:zx(t,Ux.sessionSnapshot)}:{}}function bL(e,t){if(typeof e==`string`&&le(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function xL(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function SL(e){return typeof e==`string`?e:void 0}async function CL(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=yL(n);(o.chainId!==void 0||i?.length===0)&&bP(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});yP(c,s);let l=s??c.chain?.id;if(bP(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=PI(n,r,t),d=bL(n.request.recipient,`recipient`),f=bL(n.request.currency,`currency`);return{amount:xL(n.request.amount),challenge:n,chainId:l,client:c,...o.configurableVouchers===void 0?{}:{configurableVouchers:o.configurableVouchers},escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:UI({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:SL(n.request.suggestedDeposit),token:f}}async function wL(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=iL}=e,o=LF({...r,chainId:i.chainId,escrow:i.escrow});TL({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 TL(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(!II(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!II(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!II(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!II(IF(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function EL(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function DL(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=hL(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function OL(e){let{account:t,client:n,readChannelState:r,snapshot:i,verifyVoucherOnChain:a=rL}=e,o=i.highestVoucher;if(!o)throw Error(`session snapshot is missing its highest signed voucher`);if(o.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let s=BigInt(i.acceptedCumulative),c=BigInt(o.cumulativeAmount),l=BigInt(i.requiredCumulative),u=BigInt(i.deposit),d=BigInt(i.settled),f=BigInt(i.spent);if(c!==s)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(f>s)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(d>u)throw Error(`session snapshot settled amount exceeds deposit`);let p={channelId:o.channelId,cumulativeAmount:c,signature:o.signature},m=IF(i.descriptor),h=OI(t);if(!(_I(i.escrow,i.chainId,p,m,h?{configurable:!0,openingCommitment:i.descriptor.salt}:{})||h&&await a(n,{descriptor:i.descriptor,cumulativeAmount:c,signature:p.signature},i.escrow).catch(()=>!1)))throw Error(`session snapshot highest voucher signature is invalid`);let g=await wL({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:DI(t),token:i.descriptor.token},readChannelState:r}),_=[s,l,g.state.settled].reduce((e,t)=>t>e?t:e,0n);if(_>g.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:g.channelId,cumulativeAmount:_,deposit:g.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:f}}function kL(e,t){return II(e.address,t.payer)?II(DI(e),IF(t)):!1}function AL(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(pL(r)){if(!mL(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=EL({context:r,snapshot:o.snapshot});return!n&&s&&kL(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&kL(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 jL(e,t,n=!1){switch(e.type){case`open`:return PL(e,t,n);case`recover`:return FL(e,t);case`voucher`:return IL(e,t);case`manual`:return LL(e,t,n)}}async function ML(e,t){if(e)return await kP(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function NL(e,t){let{account:n,amount:r,chainId:i,client:a,token:o}=t;if(e||!WP({chainId:i,currency:o}))return;let s=await XP(a,{account:n,amount:r,chainId:i});if(s)throw s}async function PL(e,t,n){let{account:r,resolved:i}=e;if(OI(r)&&i.configurableVouchers!==!0)throw new $x({signer:r.address});let a=WA({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw});await NL(n,{account:r.address,amount:a,chainId:i.chainId,client:i.client,token:i.token});let o=await BI(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 ML(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await dL(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function FL(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await wL({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:DI(n),token:o.token}}),l=DL({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`);KA(l,a);let u=await RI(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await dL(t,{...d?.channelId===c.channelId&&d.uncertainTopUp?{uncertainTopUp:!0}:{},channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function IL(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;KA(a,e.maxDeposit);let o=await RI(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await dL(t,r),o}async function LL(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=LF({...s,chainId:o.chainId,escrow:o.escrow});TL({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:DI(r),token:o.token});let l=await RL({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await fL(t,o.key,l),l}async function RL(e,t){switch(e.context.action){case`open`:return zL(e);case`topUp`:return BL(e,t);case`voucher`:return VL(e);case`close`:return HL(e)}}async function zL(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=gL(r,i,`cumulativeAmount`,`open`),c=await RI(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 BL(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=gL(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:(await NL(t,{account:n.address,amount:c,chainId:s.chainId,client:s.client,token:s.token}),VI(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await ML(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken))}function VL(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return RI(a.client,t,i,gL(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function HL(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return zI(a.client,t,i,gL(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}var UL,WL,GL,KL=z((()=>{Gx(),aS(),SP(),xS(),PP(),$P(),cL(),VF(),SI(),HI(),tL(),sj(),UL=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),WL=Y.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),GL=Y.object({account:Y.optional(Y.custom()),autoSwap:Y.optional(Y.custom()),action:Y.optional(Y.enum([`open`,`topUp`,`voucher`,`close`])),channelId:Y.optional(WL),cumulativeAmount:Y.optional(dS()),cumulativeAmountRaw:Y.optional(Y.string()),transaction:Y.optional(UL),descriptor:Y.optional(Y.custom()),additionalDeposit:Y.optional(dS()),additionalDepositRaw:Y.optional(Y.string()),depositRaw:Y.optional(Y.string())})}));async function qL(e,t){let n=rR.get(e)??new Map;rR.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 JL(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function YL(e,t,n){try{let r=e.response?.headers.get(q.paymentReceipt);if(r){let e=fA(r);if(e.challengeId===t.id&&JL(n,e))return!0}}catch{}return e.challenges?.some(e=>mj(e)?JL(n,hj(e)):!1)??!1}function XL(e){let{allowedChainIds:t,currencies:n,decimals:r,expectedRecipients:i,maxAmount:a,maxAtomicAmount:o}=e;if((a!==void 0||o!==void 0)&&n===void 0)throw Error(`Tempo session maxAmount and maxAtomicAmount require currencies.`);for(let e of n??[])ZL(a,typeof e==`string`?r:e.decimals);return{chainId:t?.length===1?t[0]:void 0,currencies:n,decimals:r,expectedRecipients:i?new Set(i.map(e=>e.toLowerCase())):void 0,maxAmount:a,maxAtomicAmount:o===void 0?void 0:BigInt(o)}}function ZL(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo session maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo session maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return me(e,t)}}function QL(e,t,n){let r=e.currencies?$M(e.currencies,t.currency,{chainId:t.methodDetails?.chainId??n??e.chainId,decimals:e.decimals}):void 0;if(e.currencies&&!r)throw Error(`Tempo session currency is not allowed: ${t.currency}.`);if(e.expectedRecipients&&(!t.recipient||!e.expectedRecipients.has(t.recipient.toLowerCase())))throw Error(`Unexpected session recipient: ${t.recipient}`);let i=BigInt(t.amount);if(e.maxAtomicAmount!==void 0&&i>e.maxAtomicAmount)throw Error(`Tempo session amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0&&i>ZL(e.maxAmount,r?.decimals))throw Error(`Tempo session amount exceeds maxAmount.`)}function $L(e,t){try{return QL(e,t),!0}catch{return!1}}function eR(e){return typeof e==`object`&&!!e&&e.action===`close`}function tR(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=XL(e),m=vP({chain:$e,getClient:c,rpcUrl:iM}),h=pP({account:t}),g=(e,t)=>{let n=(p.currencies?$M(p.currencies,e.currency,{chainId:e.methodDetails?.chainId??t??p.chainId,decimals:a}):void 0)?.decimals??a??6;return{decimals:n,maxDeposit:l===void 0?void 0:me(l,n),topUpAmount:u===void 0?void 0:me(u,n)}};l!==void 0&&me(l,6),u!==void 0&&me(u,6);let _=e.origin===void 0?void 0:new URL(e.origin);if(_&&![`http:`,`https:`].includes(_.protocol))throw Error(`Session origins require HTTP or HTTPS`);let v=i??GI(),y={store:v,notifyUpdate:e=>d?.(e)},b=async(e,t,n)=>{let r=h(e.client,t),i=t?.action?t.descriptor:n?.descriptor??EL({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:IF(i)}:{}}})??r},x=async(e,t,n)=>{let{decimals:r,maxDeposit:i}=g(e.challenge.request,e.chainId);return AL({account:await b(e,t,n),entry:n,context:t,decimals:r,maxDeposit:i,resolved:e})},S=bk(Qk,{canHandleChallenge:({challenge:e,context:t})=>mj(e)&&(eR(t)||t===_w||$L(p,e.request)),context:GL,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&QL(p,t.request);let a=await CL({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m});i?.action!==`close`&&t.request.methodDetails?.chainId===void 0&&QL(p,t.request,a.chainId);let c=rE(e),l=cE(e)??_?.origin;if(l!==void 0&&(l===`null`||![`http:`,`https:`].includes(new URL(l).protocol)))throw Error(`Session payments require an HTTP or HTTPS origin`);if(_&&l!==_.origin)throw Error(`Session channel origin mismatch`);let u={...y,origin:l},d=()=>{};try{let e=!pL(i)&&i?.descriptor===void 0;e&&(d=await qL(v,a.key),c&&(await v.get(a.key))?.opened&&await c.prepare());let n=await v.get(a.key);if(n&&n.origin!==l)throw Error(`Session channel origin mismatch`);if(l&&!n&&a.snapshot&&!i?.descriptor&&!_)throw Error(`Session snapshot recovery requires an explicitly configured origin or descriptor`);let o=await x(a,i,n);if(!e&&c&&o.type===`open`){d=await qL(v,a.key);let e=await v.get(a.key);if(e&&e.origin!==l)throw Error(`Session channel origin mismatch`);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await v.get(a.key)),o=await x(a,i,n))}let s,f=c&&o.type===`open`?{store:{get:e=>v.get(e),async set(e){s=l?{...e,origin:l}:e},delete:e=>v.delete(e)},notifyUpdate(){}}:u,p=await FI(t,await jL(o,f,AP(i?.autoSwap??r,MP)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||YL(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await v.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await ZI(v,e),y.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function C(e,t,n){let r={challenge:e,context:t};return sE(r,nR(n)),S.createCredential(r)}let w=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>XI(v,WI(n),async()=>{s?.throwIfAborted();let c=await v.get(WI(n));if(c?.channelId===n.channelId&&(n=c),n.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let l=n.deposit>r?n.deposit:r,{maxDeposit:u,topUpAmount:d}=g(t.request,n.chainId),f=GA({deposit:l,maxDeposit:u,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:d});f>0n&&await xj({autoSwap:e,additionalDeposit:f,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>C(e,t,a),onUncertainFunding:async e=>{let t=await v.get(WI(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await ZI(v,n),y.notifyUpdate(n)},fetch:i,input:a,signal:s});let p=l+f;if(p===n.deposit)return;let m=await v.get(WI(n)),h=m?.channelId.toLowerCase()===n.channelId.toLowerCase()?m:n,_={...h,deposit:h.deposit>p?h.deposit:p};await ZI(v,_),y.notifyUpdate(_)});return JT(S,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!mj(e))return;let c=t===void 0?void 0:GL.parse(t);if(pL(c))return;QL(p,e.request);let l=await CL({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await v.get(l.key);if(!u?.opened)return;let d=nR(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,h=u.cumulativeAmount+lA(e),g=f?BigInt(f.requiredCumulative):h,_=g>h?g:h,y=f?BigInt(f.deposit):u.deposit,x=y>u.deposit?y:u.deposit;_<=x&&x===u.deposit||!kL(await b(l,c,u),u.descriptor)||await w({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:x,fetch:r,input:i,requiredCumulative:_,signal:a})}),eE(S,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!mj(e))return u;if(!pA(u))return cA(cC(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await CL({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await v.get(f),h={assertVoucherWithinLocalLimit:t=>KA(t,g(e.request,p?.chainId).maxDeposit),createSessionCredential:(e,t)=>C(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await w({autoSwap:t===void 0?void 0:GL.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return Mj({onNeedVoucher:(t,n)=>Nj({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function nR(e){let t=new URL(e instanceof Request?e.url:e,globalThis.location===void 0?void 0:globalThis.location.href);if(![`http:`,`https:`].includes(t.protocol))throw Error(`Session payments require an HTTP or HTTPS origin`);return t.origin}var rR,iR=z((()=>{$T(),pE(),Gx(),vC(),eN(),vw(),xk(),mP(),SP(),PP(),aM(),eA(),VF(),CA(),HI(),tL(),KL(),sj(),rR=new WeakMap}));function aR(e,t){sR.set(e,t)}function oR(e){let t=sR.get(e);if(!t)throw Error(`Session manager internals are unavailable.`);return t}var sR,cR=z((()=>{sR=new WeakMap}));function lR(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 uR(e){let t=lR(`close-ready`),n=lR(`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 dR=z((()=>{}));function fR(e){return e.method===Vx.tempo&&e.intent===Hx.charge}function pR(e){if(!fR(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function mR(e,t,n){if(!n)return t;let r={...OD(_j(e)?e.headers:void 0),...OD(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===q.paymentSession.toLowerCase())?t:{...t,headers:{...r,[q.paymentSession]:n}}}function hR(e,t){return e===void 0?t:{...GL.parse(e),...t}}function gR(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:me(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:me(e.topUpAmount,t),WebSocket:n}}function _R(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&bP(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=gR(e),i;function a(e){let t=new URL(_j(e)?e.url:String(e),typeof location>`u`?void 0:location.href);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`SessionManager: session payments require an HTTP origin`);let n=t.origin;if(i!==void 0&&i!==n)throw Error(`SessionManager: session payment origin mismatch`);return i=n,n}if(ZD(r.fetch))throw TypeError(`SessionManager: the fetch sets spending options (maxPayment, authorize, funders or tokens), which accept only charges. Pass a fetch without them.`);let o=XD(r.fetch),s=QD(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(_j(e)?e.redirect:void 0))===`manual`?`manual`:`error`});if(r.url&&new URL(r.url).origin!==n)throw Error(`SessionManager: session response origin mismatch`);return r};let c=r.fetch;o&&(r.fetch=IC(c,o));let l=vP({chain:$e,getClient:e.client?()=>e.client:e.getClient,rpcUrl:iM}),u=pP({account:e.account}),d=QA(),f=e.credentialContext===void 0?void 0:hR(e.credentialContext,{}),p=uR({getSocketSession:()=>d.socketSession}),m=e.channelStore??GI(),h=new Set,g;async function _(e){let t=await m.get(e);if(t?.opened&&!h.has(t.channelId)){if(t.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return t}}let v=e=>{if(e.origin!==void 0&&e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return e.origin=i,ZI(m,e)},y={async get(e){let t=await _(e);return t&&g&&(g.seenExisting.add(e),!g.committed&&!g.created.has(e)&&(g.resumed??=t)),t},async set(e){let t=WI(e);e.opened&&h.delete(e.channelId),g?.trackCreates&&!g.seenExisting.has(t)&&g.created.set(t,e),await v(e)},delete:e=>QI(m,e)};JI(y,m);async function b(e){let t=WI(e),n=await m.get(t);if(e.uncertainTopUp||n?.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);h.add(e.channelId),g?.seenExisting.delete(t),g?.resumed===e&&(g.resumed=void 0),await Promise.resolve(QI(m,t)).catch(()=>void 0)}async function x(){let e=g;if(e?.created.size){for(let[t,n]of e.created){let e=await m.get(t);if(n.uncertainTopUp||e?.channelId===n.channelId&&e.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before discarding the channel.`);h.add(n.channelId),await Promise.resolve(QI(m,t)).catch(()=>void 0)}e.created.clear(),await L(e.committed??e.previous)}}function S(e){let t=zx(e.request.methodDetails,Ux.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=g;if(!n?.created.size||!d.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&d.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=rj({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return FA(d,e)}function w(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function T(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=rj({channel:d.channel,spent:d.spent,state:d.state}))}let E=tR({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}}),ee=ZT(E);ee&&JT(E,e=>oe(()=>Promise.resolve(ee(e)),e.signal)),tE(E);let D=pF({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),O=ED({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[E],onChallenge:async(e,t)=>{if(!pj(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&mO(e)===mO(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await L(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function k(e,t){let n={challenge:e,context:hR(f,t)};return i&&sE(n,i),E.createCredential(n)}function te(e){$A({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function A(e=d.state.status===`active`?d.state.units:0){!d.channel||!d.lastChallenge||d.state.status!==`active`&&d.state.status!==`withdrawable`&&d.state.status!==`closeRequested`&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function j(t){let r=t.headers.get(q.paymentSessionSnapshot);if(!r)return;let i=TA(r);bP(e.allowedChainIds,i.chainId),PI({request:{methodDetails:{escrow:i.escrow}}},e.escrow,n);let a=await l({chainId:i.chainId});yP(a,i.chainId);let o=u(a),{entry:s,spent:c}=await OL({account:await e.resolveAccount?.({account:o,chainId:i.chainId,operation:{authority:IF(i.descriptor),kind:`authorizePaymentChannel`}})??o,client:a,snapshot:i});return ie(s.cumulativeAmount),await Promise.resolve(y.set(s)).catch(()=>void 0),d.channel=s,d.spent=c,s}async function M(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=_j(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=_j(t)?t.url:t,l={...s,method:`HEAD`,headers:{...OD(i),...OD(n?.headers),[q.acceptPayment]:`${Vx.tempo}/${Hx.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await j(t);let n=RS(t).find(fR);if(!n||!pR(n))return;let i=new URL(String(c),typeof location<`u`?location.href:void 0);if(t.url&&new URL(t.url).origin!==i.origin)return;gE(n,i,e.trustedTempoProofRealms);let a=await D.createCredential({challenge:n,context:{}}),o=await r.fetch(c,iT({...l,redirect:`manual`},GS(n),a));return o.ok?await j(o):void 0}catch{return}}function ne(e,t){let n=d.socketSession;return tj({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:d.channel?.channelId===t?d.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:d.spent,tickCost:n?.tickCost})}function N(e,t){let n=hj(t);if(!n)return;if(LF({...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 P(e,t){let n=N(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(d.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>d.spent&&(d.spent=i),n}function re(e,t=e.challenge,n=!1){let r=(n?P(e,t):N(e.channel,t))?.acceptedCumulative??ne(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return ie(r),r.toString()}function ie(e){BA({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let ae,F;async function oe(e,t){if(F)throw F;for(;;){let e=ae;if(!e)break;if(!t)await e;else{t.throwIfAborted();let n;try{await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0})})])}finally{t.removeEventListener(`abort`,n)}}}if(t?.throwIfAborted(),F)throw F;let n=e();ae=n;try{return await n}catch(e){throw e instanceof Xj&&(F=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{ae===n&&(ae=void 0)}}async function se(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return XI(m,WI(d.channel),async()=>{let{knownDeposit:t,...n}=e,i=d.channel?await y.get(WI(d.channel)):void 0;if(i?.channelId===e.channelId&&i.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let a=await xj({...n,channel:d.channel,createSessionCredential:k,fetch:r.fetch,onUncertainFunding:async e=>{let t=await y.get(WI(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};d.channel?.channelId===e.channelId&&(d.channel=n),await y.set(n),T(n)}});te(a);let o=d.channel,s=dj({additionalDeposit:e.additionalDeposit,channel:d.channel,channelId:e.channelId,challengeId:d.lastChallenge?.id,currentState:d.state,knownDeposit:t,receipt:a,spent:d.spent});if(s?.channel&&d.lastChallenge){let e=s.channel;for(;;){await y.set(e);let t=d.channel;if(t===o)break;if(!t)return a;let n=s.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,o=t}if(e.channelId!==s.channel.channelId)return a;d.channel=e,C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}return a})}async function I(e){return oe(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=GA({deposit:n,maxDeposit:r.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:r.topUpAmount});i!==0n&&await se({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function ce(e,t){let n=nj({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(C({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function L(e){let t=ij(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function le(e,t=!0){let n=e.headers.get(q.paymentReceipt),r=n?fA(n):null;return t&&te(r),Object.assign(e,{receipt:r,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function ue(e,t){if(t?.[bO])return le(await r.fetch(e,CD(t)),!1);if(g)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a(e),d.lastUrl=e,d.lastHeaders=t?.headers;let n=rj({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await M(e,t),i.trackCreates=!0;let a=mR(e,t,d.channel?.opened?d.channel.channelId:void 0);f&&(a={...a,context:f});let o=!n.channel?.opened;async function s(){let n=i.resumed;return!o||!n?!1:(o=!1,await b(n),a=mR(e,t,void 0),!0)}for(;;){let t;try{t=await O(e,a)}catch(e){if(i.created.size?await x():await L(i.committed??n),await s())continue;throw e}let o=le(t),c=!1;if(o.status===402){let t=await Cj({input:e,init:a,response:o,createSessionCredential:k,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:ce,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:I});t&&(c=!0,o=le(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await L(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function de(e){let t=await Tj({createSessionCredential:k,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>re(e,t,!0),signedCloseAmount:re(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(A(),C({type:`closeStarted`}),C({type:`closed`,receipt:t})),t}let fe={createSessionCredential:k,doFetch:ue,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:ie,acceptReceipt(e){te(e)},topUpIfNeeded:I},pe={get channelId(){return d.channel?.channelId},get cumulative(){return d.channel?.cumulativeAmount??0n},get opened(){return d.channel?.opened??!1},get state(){return d.state},fetch:ue,async topUp(e){let t=uj({amount:e,assertVoucherWithinLocalLimit:ie,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return oe(async()=>{if(d.channel?.channelId!==t.channelId||d.lastChallenge!==t.challenge||d.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=uj({amount:e,assertVoucherWithinLocalLimit:ie,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return se({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){if(t?.[bO])throw Error(`SessionManager.sse requires payment; use fetch for unpaid streams.`);return Ej(e,t,fe)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=yj(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await M(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await Fj({async createSessionCredential(e,i){return d.lastChallenge=e,await XT(E,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),k(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:mR(n,i,o),signal:t?.signal});return d.lastChallenge=s,Bj({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:k,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await Pj({fetch:r.fetch,input:l,probeInit:mR(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:ie,acceptReceipt:te,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:I,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=qA({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===qj.OPEN){let r=await aj({activeSocket:n,createSessionCredential:k,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return A(),C({type:`closeStarted`}),C({type:`closed`,receipt:r}),r}return de(t)}};return aR(pe,{consumeSseResponse(e,t,n){let r=a(e);if(t.url&&new URL(t.url).origin!==r)throw Error(`SessionManager: session response origin mismatch`);return Dj(e,t,n,fe)},rehydrate({channel:e,challenge:t,input:n,spent:r}){let i=a(n);if(e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!pj(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.`);ie(e.cumulativeAmount);let o=N(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,C({type:`challengeReceived`,challengeId:t.id}),C({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),pe}var vR=z((()=>{sC(),DO(),$T(),pE(),bE(),lT(),Gx(),qC(),mP(),SP(),FF(),aM(),HI(),tL(),KL(),iR(),VF(),CA(),MA(),cR(),dR(),sj(),Zj(),(function(e){e.serializeSnapshot=wA,e.deserializeSnapshot=TA})(_R||={})}));function yR(e){return e instanceof Date?e:new Date(e)}function bR(e){let t=e.getTime();if(!Number.isFinite(t))throw new J({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new J({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new J({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function xR(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new J({reason:`periodCount is invalid`});let t=BR[e.periodUnit];if(t===void 0)throw new J({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>zR)throw new J({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new J({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function SR(e){let{challengeExpires:t,request:n}=e;xR(n);let r=bR(yR(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new J({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function CR(e){let t=IR(e.currency,`currency`),n=IR(e.recipient,`recipient`);return[{address:t,selector:RR,recipients:[n]}]}function wR(e){try{let t=M.fromBytes(te.toBytes(e));if(M.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new J({reason:`challenge id must encode 32 bytes`})}}async function TR(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=DR({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:qe.getSignPayload(o)}),c=Je.from(s);if(c.type===`keychain`||c.type===`configurable`)throw new J({reason:`keyAuthorization must use a primitive signature`});return qe.from(o,{signature:Je.serialize(JF(c))})}function ER(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new J({reason:`invalid keyAuthorization payload`});let o=OR(i.signature),s=kR(o);if(AR({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==wR(n))throw new J({reason:`keyAuthorization challenge mismatch`});return jR(o,a),NR(MR(o),a),PR(o.scopes,a),{authorization:o,source:{address:FR(o,s),chainId:r}}}function DR(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return qe.from({address:IR(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:bR(yR(i.subscriptionExpires)),limits:[{token:IR(i.currency,`currency`),limit:BigInt(i.amount),period:xR(i)}],scopes:CR(i),type:t.keyType,witness:wR(n)})}function OR(e){try{return qe.deserialize(e)}catch(e){throw e instanceof qe.InvalidSignatureTypeError?new J({reason:`keyAuthorization must use a primitive signature`}):new J({reason:`invalid keyAuthorization payload`})}}function kR(e){let t=e.signature;if(!t)throw new J({reason:`keyAuthorization must use a primitive signature`});return t}function AR(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new J({reason:`keyAuthorization chainId mismatch`});if(t){if(!ue(n.address,IR(t.accessKeyAddress,`accessKeyAddress`)))throw new J({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new J({reason:`keyAuthorization key type mismatch`})}}function jR(e,t){if(SR({request:t}),e.expiry!==bR(yR(t.subscriptionExpires)))throw new J({reason:`keyAuthorization expiry mismatch`})}function MR(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new J({reason:`keyAuthorization must contain exactly one token limit`});return t}function NR(e,t){if(!ue(e.token,IR(t.currency,`currency`)))throw new J({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new J({reason:`keyAuthorization amount mismatch`});if(e.period!==xR(t))throw new J({reason:`keyAuthorization period mismatch`})}function PR(e,t){if(!e||e.length!==1)throw new J({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=IR(t.currency,`currency`),r=IR(t.recipient,`recipient`),i=new Set;for(let t of e){if(!ue(t.address,n))throw new J({reason:`keyAuthorization call target mismatch`});let e=LR(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new J({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new J({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!ue(t.recipients[0],r))throw new J({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new J({reason:`keyAuthorization must allow transferWithMemo`})}function FR(e,t){let n=qe.getSignPayload(e);try{let e=Je.extractAddress({payload:n,signature:t});if(!qF(t)||!Je.verify(t,{address:e,payload:n}))throw new J({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof J?e:new J({reason:`keyAuthorization signature is invalid`})}}function IR(e,t){if(!le(e))throw new J({reason:`${t} must be an address`});return e.toLowerCase()}function LR(e){return typeof e==`string`?e.toLowerCase():``}var RR,zR,BR,VR=z((()=>{aS(),$F(),RR=`0x95777d59`,zR=(1n<<64n)-1n,BR={dev_second:1n,day:86400n,week:604800n}}));function HR(e={}){let t=vP({chain:ve,requireChain:!0,getClient:e.getClient,rpcUrl:iM}),n=pP({account:e.account});return bk($k,{context:GR,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??$j.testnet,o=await t({chainId:a});if(o.chain?.id!==a)throw Error(`Subscription chain mismatch: expected ${a}, got ${o.chain?.id??`unknown`}.`);let 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.");WR(r.request),await e.validateRequest?.(r.request);let l=await UR(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=ER({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:qe.serialize(l),type:`keyAuthorization`},request:r.request});if(!ue(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return pC({challenge:r,payload:{signature:qe.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function UR(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await TR({accessKey:n,account:r,challengeId:i,chainId:a,request:o});if(s)return s;let c=await e.request({method:`wallet_authorizeAccessKey`,params:[{address:n.accessKeyAddress,expiry:bR(yR(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:M.fromNumber(BigInt(o.amount)),period:xR(o)}],scopes:CR(o),witness:wR(i)}]});return qe.fromRpc(c.keyAuthorization)}function WR(e){xR(e),bR(yR(e.subscriptionExpires))}var GR,KR=z((()=>{vC(),xk(),mP(),SP(),xS(),aM(),eA(),VR(),GR=Y.object({accessKey:Y.optional(Y.custom()),account:Y.optional(Y.custom())})}));function qR(e={}){let t=e.expectedChainId!==void 0&&(e.allowedChainIds===void 0||e.allowedChainIds.includes(e.expectedChainId)),n=e.expectedChainId===void 0?e:{...e,allowedChainIds:t?[e.expectedChainId]:[]};return[pF(e),JR(n)]}var JR,YR=z((()=>{iR(),vR(),FF(),KR(),JR=Object.assign(tR,{manager:_R}),(function(e){e.charge=pF,e.common=qR,e.session=JR,e.subscription=HR})(qR||={})})),XR=z((()=>{FF(),YR(),KR(),tL(),iR(),vR()})),ZR=it({orderTempoChargeChallengesByBalance:()=>$R,readTempoKeystore:()=>yz,resolveTempoAccount:()=>bz,tempo:()=>ez});async function QR(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}async function $R(e,t){let n=[],r=[];for(let[t,i]of e.entries())sz(i)&&(n.push(t),r.push(i));if(r.length<2)return[...e];let i=await cz(t).catch(()=>void 0);if(!i)return[...e];let a=await Promise.all(r.map(async(e,t)=>({challenge:e,index:t,score:await lz(e,i)})));a.sort((e,t)=>Oz.indexOf(e.score)-Oz.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 ez(){let e;return $N({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:t,options:n,methodOpts:r}){let i=VM(n.account),a=t.request,o=a.currency,s=oz(r),c=pz({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()||(gM(i)?void 0:await HM(i).get());if(!h&&gM(i)&&xz()){m=!0;let e=bz(i);if(e){let r=bM(n.rpcUrl,{network:n.network});p=N({chain:await SM({network:n.network,rpcUrl:r}),transport:L(r)}),dz({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let i=o?await EM(p,o,e.wallet_address).catch(()=>void 0):void 0;l=i?.symbol??o??``,u=i?.decimals??a.decimals??6}}else if(h)f=R(h);else{let e=Cz();if(e){let t=await HM(e).get();t&&(f=R(t))}if(!f)throw n.account?new B({code:`ACCOUNT_NOT_FOUND`,message:`Account "${i}" not found.`,exitCode:69}):new B({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!m&&f){let e=bM(n.rpcUrl,{network:n.network});p=N({chain:await SM({network:n.network,rpcUrl:e}),transport:L(e)}),dz({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let r=o?await EM(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 Sz(t)}};if(!f||!p)throw new B({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let g=qR({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??(TM(p.chain)?`10`:void 0);if(!n)throw new B({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=hz(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`);let c={channelId:n,cumulativeAmount:r},l=await hI(p,f,c,i,a);return pC({challenge:t,payload:{action:o,channelId:n,...o===`close`?{closeSignature:await gI(p,f,c,i,a)}:{},descriptor:s,cumulativeAmount:r.toString(),signature:l},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=cC(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?` ${X.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
238
238
  `}${X.dim(`Channel opened ${h.payload.channelId}`)}${t}\n`)}else m(`${l?``:`
239
- `}${X.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(q.paymentReceipt);if(w)try{let e=JSON.parse(k.toString(w));hL(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&kL(v,S),s>=1&&mL(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
240
- `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await gL(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 dL(C),v&&y&&b&&(l&&m(`
241
- `),l&&!await t.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await _L({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 mL(e,t){t.info(`${t.prefix??``}${X.bold(X.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} ${X.dim(`(${PA(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,OA(`${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(` ${X.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
242
- `)}function hL(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 gL(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 vL():void 0,c=(()=>{if(!s||!X.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:{[q.authorization]:a}})}catch(e){t.info(X.dim(X.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{mL(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
239
+ `}${X.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(q.paymentReceipt);if(w)try{let e=JSON.parse(te.toString(w));nz(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&gz(v,S),s>=1&&tz(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
240
+ `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await rz(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 QR(C),v&&y&&b&&(l&&m(`
241
+ `),l&&!await t.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await iz({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 tz(e,t){t.info(`${t.prefix??``}${X.bold(X.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} ${X.dim(`(${yM(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,pM(`${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(` ${X.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
242
+ `)}function nz(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 rz(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 az():void 0,c=(()=>{if(!s||!X.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:{[q.authorization]:a}})}catch(e){t.info(X.dim(X.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{tz(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
243
243
 
244
244
  `})}catch{}o=``;continue}if(e.length===0)u(`
245
245
  `);else try{let t=JSON.parse(e);u(t.token??t.choices?.[0]?.delta?.content??e)}catch{u(e)}o=``}}};for(;;){let{done:e,value:t}=await r.read();if(e)break;a+=i.decode(t,{stream:!0});let n=a.split(`
246
- `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await _L({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 _L(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:{...XT(e.fetchInit.headers),Authorization:t}});if(n.ok){if(AL(e.channelId),e.verbose>=1){let t=n.headers.get(q.paymentReceipt),r;if(t)try{let e=JSON.parse(k.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${X.dim(OA(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${PA(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${X.dim(X.yellow(`Channel close failed`))} ${X.dim(`(${n.status})`)}\n`),e.info(`${X.dim(` channelId: ${e.channelId}`)}\n${X.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${X.dim(` escrowContract: ${e.escrowContract}`)}\n${X.dim(` chainId: ${e.chainId}`)}\n${X.dim(` response: ${t||`(empty)`}`)}\n`)}}function vL(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 yL(e){return CL(zL,e,BL)}function bL(e){return e.method===`tempo`&&e.intent===`charge`}async function xL(e){let t=nj(e.options.account),n=process.env.MPPX_PRIVATE_KEY?.trim()||(jA(t)?void 0:await rj(t).get()),r;if(n)r=L(n).address;else if(jA(t)&&PL())r=NL(t)?.wallet_address;else{let e=IL();if(e){let t=await rj(e).get();t&&(r=L(t).address)}}if(!r)return;let i=FA(e.options.rpcUrl,{network:e.options.network}),a=M({chain:await LA({network:e.options.network,rpcUrl:i}),transport:I(i)});return{account:r,client:a}}async function SL(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,o=a?.chainId;if(o&&t.client.chain?.id&&o!==t.client.chain.id)return`unsupported`;let s=BigInt(i);if(s===0n)return`payable`;let c=await Re.token.getBalance(t.client,{account:t.account,token:r}).then(e=>e.amount).catch(()=>void 0);if(c===void 0)return`unknownBalance`;if(c>=s)return`payable`;if(a?.machineTokenEnabled===!0&&!a.splits?.length){let e=await cN(t.client,{account:t.account,chainId:o??t.client.chain?.id});if(e!==void 0&&e>=s)return`payable`}return`insufficientBalance`}function CL(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 wL(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 z({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function TL(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function EL(e){let t=TL(e.tokenIn)??TL(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 DL(){return c.join(process.env.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`mppx`,`channels`)}function OL(e){try{let n=t.readFileSync(c.join(DL(),e),`utf-8`).trim();return n?BigInt(n):void 0}catch{return}}function kL(e,n){let r=DL();t.mkdirSync(r,{recursive:!0}),t.writeFileSync(c.join(r,e),n.toString(),`utf-8`)}function AL(e){try{t.unlinkSync(c.join(DL(),e))}catch{}}function jL(){return x.platform()===`darwin`?c.join(x.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):c.join(process.env.XDG_DATA_HOME||c.join(x.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function ML(){try{let e=t.readFileSync(jL(),`utf-8`),n=[],r;for(let t of e.split(`
247
- `)){let e=t.trim();if(e===`[[keys]]`){r?.wallet_address&&n.push(r),r={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!r)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?r.wallet_type=o:a===`wallet_address`?r.wallet_address=o:a===`chain_id`&&(r.chain_id=Number.parseInt(o,10))}return r?.wallet_address&&n.push(r),n}catch{return[]}}function NL(e){let t=ML();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 PL(){if(HL!==void 0)return HL;try{m.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),HL=!0}catch{HL=!1}return HL}async function FL(e){return new Promise((t,n)=>{m.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function IL(){let e=tj();if(jA(e.get())&&!PL()&&x.platform()===`darwin`)try{let t=m.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===LL&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}var LL,RL,zL,BL,VL,HL,UL=R((()=>{Rx(),GE(),Gx(),mC(),lL(),pN(),RO(),FP(),lj(),YA(),mM(),LL=`mppx`,RL=p.union([p.boolean(),p.literal(`true`).transform(()=>!0),p.literal(`false`).transform(()=>!1)]),zL=p.object({allowCustomEscrow:p.optional(RL),autoSwap:p.optional(RL),channel:p.optional(p.coerce.string()),deposit:p.optional(p.union([p.string(),p.number()])),payWith:p.optional(p.string()),slippage:p.optional(p.coerce.number()),tokenIn:p.optional(p.string())}),BL=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`],VL=[`payable`,`unknownBalance`,`insufficientBalance`,`unsupported`]}));zC(),lj(),mM();const WL=[...Object.entries(yj),...Object.entries(bj),...Object.entries(xj),...Object.entries(Sj)];function GL(){return pM({method:`evm`,supports:KL,async setup({challenge:e,options:t}){let n=e.request,r=n.network?qL(jj(n.network)):void 0,i=n.network&&n.asset?WL.find(([,e])=>kj(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`?_j({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await oj(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...fM({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function KL(e){if(!LC(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 qL(e){return Object.values($e).find(t=>t.id===e)}iC(),ow(),ND(),sS(),UL();const JL=[pL(),wM(),hM(),GL()];async function YL(e,t,n){let r=n;for(let n of t??[]){let t=await n.preparePayment?.({challenge:e,...r===void 0?{}:{credentialContext:r}});t&&`credentialContext`in t&&(r=t.credentialContext)}return r}function XL(e,t){let n=t?.plugins?.find(t=>eR(t,e));if(n)return{plugin:n};let r=$L(t)?.filter(t=>t.name===e.method&&t.intent===e.intent),i=r?.find(t=>t.canHandleChallenge?.({challenge:e})??!0);if(i)return{method:i};if(r?.length)return{};let a=JL.find(t=>eR(t,e));return a?{plugin:a}:{}}function ZL(e,t){let n=$L(t);if(n?.length){let r=WC(e,n,VC(n,t?.paymentPreferences).entries);if(r){let e=t?.plugins?.find(e=>eR(e,r.challenge));return{challenge:r.challenge,...e?{plugin:e}:{method:r.method}}}return}for(let n of e){let e=XL(n,t);if(e.plugin||e.method)return{challenge:n,...e}}}function QL(e){let t=$L(e);if(t?.length)return VC(t,e?.paymentPreferences).header}function $L(e){return Array.isArray(e?.methods)?e.methods.flat():void 0}function eR(e,t){return e.supports?e.supports(t):e.method===t.method}async function tR(e){let t=nR(e);if(!t)return;let n=await import(t);return{config:n.default??n,path:t}}function nR(e){if(e){let n=c.resolve(e);return t.existsSync(n)?n:void 0}let n=process.env.MPPX_CONFIG?.trim();if(n){let e=c.resolve(n);return t.existsSync(e)?e:void 0}}function rR(e,t){function n(t){let n={...t.request};if(t.method===`tempo`&&t.intent===`session`){let e={...n.methodDetails};delete e.sessionSnapshot,Object.keys(e).length?n.methodDetails=e:delete n.methodDetails}let{meta:r,opaque:i,...a}=t;return JSON.stringify([xS({...a,request:n,id:e.id,expires:e.expires}),iR(t)])}if(n(t)!==n(e))throw Error(`Payment request changed on retry. Run the command again to approve the new payment.`)}function iR(e){let t=e.opaque??(e.meta?oS(e.meta):void 0);if(t===void 0)return;let n;try{n=iS(t)}catch{return t}if(typeof n!=`object`||!n||Array.isArray(n))return t;let r=kD(n);return r?oS(r):void 0}UL(),iC(),WT(),tF(),xI(),jI(),fA();function aR(e){return e??globalThis.fetch.bind(globalThis)}function oR(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(qP(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Error(`Close challenge changed the session escrow.`);let r=Ak(e);if(r&&r.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Close challenge changed the session channel.`)}async function sR(e){oR(e.challenge,e.channel);let t=e.channel;if(t.origin===void 0){let n=new URL(e.input instanceof Request?e.input.url:e.input);if(![`http:`,`https:`].includes(n.protocol))throw Error(`Legacy session close requires an HTTP origin`);BT(e.challenge,n,e.manager.trustedTempoProofRealms),t={...t,origin:n.origin}}let n=aR(e.fetch),r,i=async(t,i)=>{r&&=(await e.onChallenge?.(r),void 0);let a=await n(t,i);if(a.status!==402)return a;let o=IS(a).find(Ok);if(!o)throw Error(`Refreshed close response did not include tempo/session.`);return oR(o,e.channel),r=o,a},a=AI({...e.manager,bootstrap:!1,escrow:e.channel.escrow,fetch:i});yI(a).rehydrate({...e,channel:t}),t!==e.channel&&await e.manager.channelStore?.set(t);let o=await a.close();if(!o)throw Error(`Session close response did not include a payment receipt.`);return{manager:a,receipt:o}}iC(),tF(),mF(),fA(),eP(),yS();var cR=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}},lR=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 uR=Y.object({origin:Y.optional(Y.string()),channelId:hS(),cumulativeAmount:Y.string(),deposit:Y.string(),descriptor:Y.object({payer:mS(),payee:mS(),operator:mS(),token:mS(),salt:hS(),authorizedSigner:mS(),expiringNonceHash:hS()}),escrow:mS(),chainId:Y.number(),opened:Y.boolean()}),dR=Y.object({name:Y.optional(Y.string()),address:mS()}),fR=Y.object({method:Y.literal(`tempo`),intent:Y.literal(`session`),status:Y.literal(`success`),timestamp:Y.string(),reference:Y.string(),challengeId:Y.string(),channelId:hS(),acceptedCumulative:Y.string(),spent:Y.string(),units:Y.optional(Y.number()),txHash:Y.optional(hS())}),pR=Y.object({version:Y.literal(1),method:Y.literal(`tempo`),intent:Y.literal(`session`),status:Y.enum([`opening`,`open`,`closing`,`stale`]),channel:uR,account:dR,endpoint:Y.string(),challenge:tC,receipt:Y.optional(fR),spent:Y.string(),units:Y.number(),createdAt:Y.string(),updatedAt:Y.string()}),mR=Y.object({version:Y.literal(1),channelId:hS()}),hR=Y.object({version:Y.literal(1),scope:Y.string(),hostname:Y.string(),pid:Y.number(),token:Y.string(),createdAt:Y.string()});function gR(e,t,n,r){let i=e.safeParse(t);if(!i.success)throw Z(n,r,i.error);return i.data}function _R(e){let t=DR(e);return[t.payer,t.payee,t.token,t.escrow,t.chainId].join(`:`)}function vR(e){return{payer:e.descriptor.payer,payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId}}function yR(e={}){let t=e.stateRoot??xR(),n={root:t,channels:c.join(t,`channels`),locks:c.join(t,`locks`),preferred:c.join(t,`preferred`)},r=e.hostname??x.hostname(),i=e.pid??process.pid,a=e.now??(()=>new Date),o=e.isProcessAlive??$R;async function s(){for(let e of[n.root,n.channels,n.locks,n.preferred])await w.mkdir(e,{recursive:!0,mode:448}),await w.chmod(e,448)}async function l(e){let t=TR(e),r=SR(n,t),i=await WR(r);if(i===void 0)return;let a=FR(i,r);if(a.channel.channelId.toLowerCase()!==t)throw Z(r,`Session filename does not match its channel ID.`);return IR(a)}async function u(){let e;try{e=await w.readdir(n.channels,{withFileTypes:!0})}catch(e){if(tz(e,`ENOENT`))return[];throw Z(n.channels,`Unable to list managed sessions.`,e)}let t=[];for(let n of e){if(!n.isFile()||n.name.includes(`.tmp-`)||!n.name.endsWith(`.json`))continue;let e=n.name.slice(0,-5);TR(e);let r=await l(e);r&&t.push(r)}return t.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}async function d(e){await s();let t=jR(e.channel),r=TR(t.channelId),i=SR(n,r),o=await WR(i),c=o===void 0?void 0:FR(o,i);c&&LR(c,e,i);let l=c?.channel.origin??t.origin;if(c?.channel.origin&&t.origin&&c.channel.origin!==t.origin)throw Z(i,`Session payment origin mismatch.`);if(l!==void 0&&new URL(l).origin!==l)throw Z(i,`Session payment origin must be a normalized origin.`);let u=NR(e.challenge,i);zR(u,t,i);let d=e.receipt?PR(e.receipt,t.channelId,i):void 0,f=c?oF(c.channel):void 0,p=UR(t.cumulativeAmount,f?.cumulativeAmount??0n),m=UR(e.spent??0n,d?BigInt(d.spent):0n,c?BigInt(c.spent):0n);if(m>p)throw Z(i,`Session spend exceeds the locally authorized cumulative amount.`);let h=MR(aF({...t,cumulativeAmount:p,...l!==void 0&&{origin:l}}),i),g=HR(c?.updatedAt,a(),i),_=VR(c?.receipt,d),v=AR(e.account,i),y=FR({version:1,method:`tempo`,intent:`session`,status:e.status,channel:h,account:{...v.name===void 0?c?.account.name===void 0?{}:{name:c.account.name}:{name:v.name},address:v.address},endpoint:kR(e.endpoint,i),challenge:u,..._!==void 0&&{receipt:_},spent:m.toString(),units:Math.max(c?.units??0,e.units??0,d?.units??0),createdAt:c?.createdAt??g,updatedAt:g},i);return await GR(i,y),IR(y)}async function f(e){let t=wR(n,e),r=await WR(t);if(r===void 0)return;let{channelId:i}=gR(mR,r,t,`Preferred session is invalid.`),a=await l(i);if(!a)throw Z(t,`Preferred session ${i} does not exist.`);return BR(a.channel,e,t),i}async function p(e,t){let r=TR(t),i=await l(r),a=wR(n,e);if(!i)throw Z(a,`Session ${r} does not exist.`);BR(i.channel,e,a),await GR(a,{version:1,channelId:r})}async function m(e,t){let r=wR(n,e),i=t===void 0?void 0:TR(t),a=await WR(r);if(a===void 0)return;let o=gR(mR,a,r,`Preferred session is invalid.`).channelId;i&&o.toLowerCase()!==i||await ZR(r,`Unable to clear preferred session.`)}async function h(e){let t=TR(e),r=await l(t);r&&(await m(vR(r.channel),t),await ZR(SR(n,t),`Unable to remove session.`))}async function g(e){await s();let t=CR(n,e);for(let n=0;n<3;n++){let n={version:1,scope:e,hostname:r,pid:i,token:v(),createdAt:a().toISOString()};try{if(await KR(t,n),await YR(JR(t))){await XR(t,n);continue}return{async release(){await XR(t,n)}}}catch(e){if(!tz(e,`EEXIST`))throw e}let s=await WR(t);if(s===void 0)continue;let c=gR(hR,s,t,`Session lock is invalid.`);if(c.scope!==e)throw Z(t,`Session lock scope is invalid.`);if(c.hostname!==r||o(c.pid))throw new lR(e,c);await qR(t,c)}let c=await WR(t);throw c===void 0?Z(t,`Unable to acquire session lock.`):new lR(e,gR(hR,c,t,`Session lock is invalid.`))}async function _(e){return g(_R(e))}return{root:t,get:l,list:u,upsert:d,remove:h,getPreferred:f,setPreferred:p,clearPreferred:m,acquire:_}}function bR(e,t){let n=OR(t.scope),r=t.selection===`auto`||t.selection===`new`?void 0:TR(t.selection);function i(e){if(e.toLowerCase()!==n)throw new cR(`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 cR(`Session ${i} does not exist.`);if(BR(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(rF(n)),BR(n,t.scope),r&&r.toLowerCase()!==n.channelId.toLowerCase())throw new cR(`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 xR(){let e=process.env.XDG_STATE_HOME||c.join(x.homedir(),`.local`,`state`);return c.join(e,`mppx`,`sessions`,`v1`)}function SR(e,t){return c.join(e.channels,`${t}.json`)}function CR(e,t){let n=_(`sha256`).update(t).digest(`hex`);return c.join(e.locks,`${n}.lock`)}function wR(e,t){let n=_(`sha256`).update(_R(t)).digest(`hex`);return c.join(e.preferred,`${n}.json`)}function TR(e){return gR(hS(),e,void 0,`Invalid session channel ID: ${e}.`).toLowerCase()}function ER(e,t,n){return gR(mS(),e,n,`Invalid ${t}.`).toLowerCase()}function DR(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<0)throw new cR(`Invalid session chain ID.`);return{payer:ER(e.payer,`session payer`),payee:ER(e.payee,`session payee`),token:ER(e.token,`session token`),escrow:ER(e.escrow,`session escrow`),chainId:e.chainId}}function OR(e){let t=DR(e);return[t.payee,t.token,t.escrow,t.chainId].join(`:`)}function kR(e,t){if(typeof e!=`string`)throw Z(t,`Session endpoint is invalid.`);let n;try{n=new URL(e)}catch(e){throw Z(t,`Session endpoint is invalid.`,e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Z(t,`Session endpoint must use HTTP or HTTPS.`);if(n.username||n.password)throw Z(t,`Session endpoint must not contain credentials.`);let r=e.indexOf(`#`);return r===-1?e:e.slice(0,r)}function AR(e,t){return gR(dR,e,t,`Session account is invalid.`)}function jR(e){return oF(MR(aF(e)))}function MR(e,t){return gR(uR,e,t,`Stored session channel is invalid.`)}function NR(e,t){let n=tC.safeParse(e);if(!n.success||!Ok(n.data))throw Z(t,`Stored session challenge is invalid.`);return n.data}function PR(e,t,n){let r=gR(fR,e,n,`Stored session receipt is invalid.`);if(r.channelId!==t.toLowerCase())throw Z(n,`Stored session receipt has a different channel ID.`);if(r.reference.toLowerCase()!==t.toLowerCase())throw Z(n,`Stored session receipt has a different reference.`);if(BigInt(r.spent)>BigInt(r.acceptedCumulative))throw Z(n,`Stored session receipt spend exceeds its accepted amount.`);return r}function FR(e,t){let n=gR(pR,e,t,`Stored session is invalid.`),{receipt:r,...i}=n,a=n.channel,o=n.account;if(o.address.toLowerCase()!==a.descriptor.payer.toLowerCase())throw Z(t,`Stored session account does not match the channel payer.`);let s=r?PR(r,a.channelId,t):void 0,c=n.spent,l=BigInt(a.cumulativeAmount);if(BigInt(c)>l)throw Z(t,`Stored session spend exceeds its cumulative authorization.`);if(s&&BigInt(s.acceptedCumulative)>l)throw Z(t,`Stored receipt exceeds the cumulative authorization.`);if(Date.parse(n.updatedAt)<Date.parse(n.createdAt))throw Z(t,`Stored session timestamps are not monotonic.`);let u=kR(n.endpoint,t);if(u!==n.endpoint)throw Z(t,`Stored session endpoint contains a fragment.`);let d=NR(n.challenge,t);return zR(d,oF(a),t),{...i,account:o,channel:a,endpoint:u,challenge:d,...s&&{receipt:s}}}function IR(e){return{version:1,status:e.status,channel:oF(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 LR(e,t,n){let r=jR(t.channel),i=AR(t.account,n),a=oF(e.channel);if(JSON.stringify(RR(r))!==JSON.stringify(RR(a)))throw Z(n,`Session update changed immutable channel identity.`);if(i.address.toLowerCase()!==e.account.address.toLowerCase())throw Z(n,`Session update changed the payer account.`)}function RR(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 zR(e,t,n){if(XN({...t.descriptor,chainId:t.chainId,escrow:t.escrow}).toLowerCase()!==t.channelId.toLowerCase())throw Z(n,`Session channel ID does not match its descriptor.`);let r=ER(e.request.recipient,`challenge recipient`,n),i=ER(e.request.currency,`challenge currency`,n);if(r!==t.descriptor.payee.toLowerCase())throw Z(n,`Session challenge payee does not match the channel.`);if(i!==t.descriptor.token.toLowerCase())throw Z(n,`Session challenge token does not match the channel.`);if(qP(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Z(n,`Session challenge escrow does not match the channel.`);if(ez(e.request.methodDetails)){let r=e.request.methodDetails;if(r.chainId!==void 0&&r.chainId!==t.chainId)throw Z(n,`Session challenge chain does not match the channel.`)}}function BR(e,t,n){let r=DR(t);if(e.descriptor.payer.toLowerCase()!==r.payer||e.descriptor.payee.toLowerCase()!==r.payee||e.descriptor.token.toLowerCase()!==r.token||e.escrow.toLowerCase()!==r.escrow||e.chainId!==r.chainId)throw Z(n,`Session channel does not match the selected payment scope.`)}function VR(e,t){return e?t&&Date.parse(t.timestamp)>=Date.parse(e.timestamp)?t:e:t}function HR(e,t,n){if(!Number.isFinite(t.getTime()))throw Z(n,`Session clock is invalid.`);let r=t.toISOString();return!e||Date.parse(r)>=Date.parse(e)?r:e}function UR(...e){return e.reduce((e,t)=>t>e?t:e,0n)}async function WR(e){let t;try{t=await w.readFile(e,`utf8`)}catch(t){if(tz(t,`ENOENT`))return;throw Z(e,`Unable to read session state.`,t)}try{return JSON.parse(t)}catch(t){throw Z(e,`Session state contains invalid JSON.`,t)}}async function GR(e,t){await w.mkdir(c.dirname(e),{recursive:!0,mode:448}),await w.chmod(c.dirname(e),448);let n=`${e}.tmp-${process.pid}-${v()}`,r;try{r=await w.open(n,`wx`,384),await r.writeFile(`${JSON.stringify(t,null,2)}\n`,`utf8`),await r.sync(),await r.close(),r=void 0,await w.rename(n,e),await w.chmod(e,384),await QR(c.dirname(e))}catch(t){throw await r?.close().catch(()=>void 0),await w.unlink(n).catch(()=>void 0),t instanceof cR?t:Z(e,`Unable to write session state.`,t)}}async function KR(e,t){let n;try{n=await w.open(e,`wx`,384),await n.writeFile(`${JSON.stringify(t)}\n`,`utf8`),await n.sync(),await n.close(),n=void 0,await QR(c.dirname(e))}catch(t){throw await n?.close().catch(()=>void 0),n&&await w.unlink(e).catch(()=>void 0),t}}async function qR(e,t){let n=JR(e);try{await w.link(e,n)}catch(t){if(tz(t,`EEXIST`)||tz(t,`ENOENT`))return;throw Z(e,`Unable to claim dead lock.`,t)}try{let r=await WR(n);if(r===void 0||gR(hR,r,n,`Session lock is invalid.`).token!==t.token)return;await ZR(e,`Unable to reclaim dead lock.`)}finally{await ZR(n,`Unable to release dead lock claim.`)}}function JR(e){return`${e}.reclaim`}async function YR(e){try{return await w.access(e),!0}catch(t){if(tz(t,`ENOENT`))return!1;throw Z(e,`Unable to inspect session lock.`,t)}}async function XR(e,t){let n=await WR(e);n!==void 0&&gR(hR,n,e,`Session lock is invalid.`).token===t.token&&await ZR(e,`Unable to release session lock.`)}async function ZR(e,t){try{await w.unlink(e),await QR(c.dirname(e))}catch(n){if(!tz(n,`ENOENT`))throw Z(e,t,n)}}async function QR(e){let t=await w.open(e,`r`);try{await t.sync()}finally{await t.close()}}function $R(e){try{return process.kill(e,0),!0}catch(e){if(tz(e,`ESRCH`))return!1;if(tz(e,`EPERM`))return!0;throw e}}function ez(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tz(e,t){return e instanceof Error&&`code`in e&&e.code===t}function Z(e,t,n){return new cR(t,{...n!==void 0&&{cause:n},file:e})}Rx(),iC(),GE(),aI(),xF(),eP(),lj(),YA();const nz=p.object({status:p.enum([`opening`,`open`,`closing`,`stale`]),channelId:p.string(),account:p.string().optional(),payer:p.string(),payee:p.string(),authorizedSigner:p.string(),token:p.string(),escrow:p.string(),chainId:p.number(),cumulativeAmount:p.string(),confirmedSpend:p.string(),deposit:p.string(),units:p.number(),resourceUrl:p.string(),createdAt:p.string(),updatedAt:p.string()}),rz=p.object({channelId:p.string(),status:p.enum([`closed`,`already-closed`]),spent:p.string(),txHash:p.string().optional()}),iz=p.object({closed:p.array(rz),failed:p.array(p.object({channelId:p.string(),message:p.string()}))});function az(e){return e===`mainnet`?ye.id:be.id}function oz(e){if(e===ye.id)return`mainnet`;if(e===be.id)return`testnet`}function sz(e){let t={};for(let n of e??[]){let e=n.indexOf(`:`);if(e===-1)throw new z({code:`INVALID_HEADER`,message:`Invalid header format: ${n}`,exitCode:2});t[n.slice(0,e).trim()]=n.slice(e+1).trim()}return t}function cz(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 lz(e,t){throw e instanceof z?e:e instanceof lR?new z({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e instanceof cR?new z({code:e.code,message:e.message,exitCode:65,cause:e}):new z({code:t,message:e instanceof Error?e.message:String(e),exitCode:75,...e instanceof Error&&{cause:e}})}async function uz(e,t){let n=await aj(t??e.account.name);if(!HF(n.account,e.channel.descriptor))throw new z({code:`SESSION_ACCOUNT_MISMATCH`,message:`Account ${n.account.address} cannot sign for session ${e.channel.channelId}.`,exitCode:2});return n}async function dz(e,t){if(t.network&&az(t.network)!==e)throw new z({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, not ${t.network}.`,exitCode:2});let n=t.network??oz(e),r=FA(t.rpcUrl,{network:n}),i=await LA({network:n,rpcUrl:r});if(i.id!==e)throw new z({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, but RPC is chainId ${i.id}.`,exitCode:2});return M({chain:i,transport:I(r)})}const fz=vb(`sessions`,{description:`Manage persistent payment sessions (list, view, close)`}).command(`list`,{description:`List persistent payment sessions`,options:p.object({account:p.string().optional().describe(`Filter by account name`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Filter by Tempo network`)}),output:p.object({sessions:p.array(nz)}),alias:{account:`a`},async run(e){try{let t=(await yR().list()).filter(t=>!(e.options.account&&t.account.name!==e.options.account||e.options.network&&t.channel.chainId!==az(e.options.network))).map(cz),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(``),pz(n);return}catch(e){return lz(e,`SESSION_LIST_FAILED`)}}}).command(`view`,{description:`View a persistent payment session`,args:p.object({channelId:p.string().describe(`Full session channel ID`)}),output:nz,async run(e){try{let t=await yR().get(e.args.channelId);if(!t)throw new z({code:`SESSION_NOT_FOUND`,message:`Session ${e.args.channelId} was not found.`,exitCode:2});let n=cz(t);if(e.format===`json`&&e.formatExplicit)return e.ok(n);pz(n);return}catch(e){return lz(e,`SESSION_VIEW_FAILED`)}}}).command(`close`,{description:`Cooperatively close persistent payment sessions`,usage:[{suffix:`<channel-id> [options]`},{suffix:`--all --yes [options]`}],args:p.object({channelId:p.string().optional().describe(`Full session channel ID`)}),options:p.object({account:p.string().optional().describe(`Account name`),all:p.boolean().optional().default(!1).describe(`Close every matching session`),header:p.array(p.string()).optional().describe(`Add close request header (repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`),url:p.string().optional().describe(`Override the stored resource URL`),yes:p.boolean().optional().default(!1).describe(`Confirm closing every session`)}),output:p.union([rz,iz]),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=yR();async function n(e,n={}){let r=await t.get(e);if(!r)throw new z({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let i=vR(r.channel),a=await t.acquire(i);try{let r=await t.get(e);if(!r)throw new z({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});if(WS(r.challenge))throw new z({code:`SESSION_STATE_INVALID`,message:`Stored session challenge selects a credential header other than Payment-Authorization.`,exitCode:65});let a=await uz(r,n.account),o=await dz(r.channel.chainId,n);if(XN({...r.channel.descriptor,escrow:r.channel.escrow,chainId:r.channel.chainId}).toLowerCase()!==r.channel.channelId.toLowerCase())throw new z({code:`SESSION_STATE_INVALID`,message:`Stored descriptor does not derive the session channel ID.`,exitCode:65});if((await _F(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=kR(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=sz(n.headers),f=u.challenge,p=await sR({channel:u.channel,challenge:u.challenge,fetch:async(e,t)=>globalThis.fetch(e,{...t,headers:{...d,...XT(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:bR(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===az(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 lz(e,`SESSION_CLOSE_FAILED`)}}});function pz(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}`)}Rx(),aI(),xI(),jI(),RO(),lj(),YA();function mz(e,t){if(t&&e!==`auto`&&t.toLowerCase()!==e.toLowerCase())throw new z({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 z({code:`INVALID_SESSION`,message:`Session must be auto, new, or a 32-byte channel ID.`,exitCode:2})}function hz(e){let t=e.allowCustomEscrow;if(t!==void 0){if(t===`true`)return!0;if(t===`false`)return!1;throw new z({code:`INVALID_ALLOW_CUSTOM_ESCROW`,message:`allowCustomEscrow must be true or false.`,exitCode:2})}}function gz(e,t,n,r){if(t.deposit!==void 0)return t.deposit;let i=e.request.suggestedDeposit;return typeof i==`string`?se(BigInt(i),r):n?`10`:void 0}function _z(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 vz(e,t){return e.channel.channelId.toLowerCase()===t.toLowerCase()}function yz(e){if(e.trim()!==`[DONE]`){if(e.length===0){process.stdout.write(`
248
- `);return}try{let t=JSON.parse(e);process.stdout.write(t.token??t.choices?.[0]?.delta?.content??e)}catch{process.stdout.write(e)}}}async function bz(e){let{options:t}=e,n=await aj(t.account),r=FA(t.rpcUrl,{network:t.network}),i=await LA({network:t.network,rpcUrl:r}),a=M({chain:i,transport:I(r)}),o=hz(e.methodOptions),s=await IF({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new z({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let{decimals:c}=await VA(a,s.token,n.account.address,{requireDecimals:!0}),l={payer:n.account.address,payee:s.payee,token:s.token,escrow:s.escrow,chainId:s.chainId},u=mz(t.session,e.methodOptions.channel),d=e.registry??yR(),f=await d.acquire(l).catch(e=>{throw e instanceof lR?new z({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=u===`auto`?await d.getPreferred(l):u===`new`?void 0:u,s=r?await d.get(r):void 0;if(r&&!s)throw new z({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&u!==`auto`&&(s.status!==`open`||!s.channel.opened||_R(vR(s.channel))!==_R(l)||!HF(n.account,s.channel.descriptor)))throw new z({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let f=s?.status===`open`&&s.channel.opened?s:void 0,p=f?`open`:`opening`,m=e.challenge,h=f?.receipt,g=f?.spent??0n,_=f?.units??0,v=kR(e.endpoint),y={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},b=bR(d,{scope:l,selection:u,context:()=>({status:p,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),onNewChannel(){p=`opening`,h=void 0,g=0n,_=0}}),{signal:x,...S}=e.init,C={...S,...x&&{signal:x},onReceipt(e){h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0)}};if(e.challengeResponse.status!==402||e.challengeResponse.bodyUsed)throw Error(`Session manager requires an unconsumed 402 challenge response.`);let w=!0,T=AI({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:b,credentialContext:e.credentialContext,decimals:c,maxDeposit:gz(e.challenge,e.methodOptions,BA(i),c),fetch:async(t,n)=>w?(w=!1,e.challengeResponse):e.fetch(t,n)});f&&yI(T).rehydrate({channel:f.channel,challenge:e.challenge,input:e.fetchInput,spent:f.spent});let{onReceipt:ee,...te}=C,E=await T.fetch(e.fetchInput,te);if(t.fail&&E.status>=400)throw new z({code:`HTTP_ERROR`,message:`HTTP error ${E.status}`,exitCode:22});if(E.status===402)throw new z({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});CA(E,{include:!1,verbose:t.include?Math.max(t.verbose,2):t.verbose,silent:t.silent}),m=E.challenge??e.challenge;let D=T.channelId;if(!D)throw Error(`Session manager did not select a channel.`);if(h=_z(E.receipt,{challenge:m,channelId:D,cumulative:T.cumulative})??h,OO(E)){let t=yI(T).consumeSseResponse(e.fetchInput,E,{onReceipt:ee,signal:e.init.signal??void 0});for await(let e of t)yz(e)}else process.stdout.write(Buffer.from(await E.arrayBuffer()));let O=await d.get(D);if(!O||!vz(O,D))throw Error(`Session ${D} was not persisted.`);if(h){let e=_z(h,{challenge:m,channelId:D,cumulative:T.cumulative});if(!e)throw Error(`Session receipt validation failed.`);h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0),p=`open`}await d.upsert({status:p,channel:O.channel,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),t.silent||(e.info(`Session retained ${D}\n`),e.info(`Close with: mppx sessions close ${D}\n`))}finally{await f.release()}}const xz=`StripeCLI`;function Sz(e){let t=e.env??process.env,n=e.secretKey?.trim();if(n)return{key:n,source:`flag`};let r=t.STRIPE_SECRET_KEY?.trim();if(r)return{key:r,source:`env`};let i=Cz(e);if(i)return{key:i,source:`stripe-cli`}}function Cz(e){let t=e.env??process.env,n=c.join(t.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`stripe`),r=e.projectName||t.STRIPE_PROJECT_NAME||`default`,i=Dz(c.join(n,`config.toml`),r);if(!e.live)return i.test_mode_api_key||i.secret_key||i.api_key||void 0;let a=i.live_mode_api_key;if(a&&!a.includes(`*`))return a;let o=`${r}.live_mode_api_key`,s=Ez(c.join(n,`credentials.json`))?.[o];return typeof s==`string`&&s?s:wz(o,e)}function wz(e,t){let n=t.platform??process.platform,r=t.exec??Tz,i=(()=>{if(n===`darwin`)return[`security`,[`find-generic-password`,`-s`,xz,`-a`,e,`-w`]];if(n===`linux`)return[`secret-tool`,[`lookup`,`service`,xz,`username`,e]]})();if(i)try{let e=r(i[0],i[1]).trim();return e.startsWith(`go-keyring-base64:`)?Buffer.from(e.slice(18),`base64`).toString(`utf8`)||void 0:e||void 0}catch{return}}function Tz(e,t){return g(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:3e3})}function Ez(e){try{return JSON.parse(t.readFileSync(e,`utf8`))}catch{return}}function Dz(e,n){let r;try{r=t.readFileSync(e,`utf8`)}catch{return{}}let i=new Set([n,`profiles.${n}`]),a={},o;for(let e of r.split(/\r?\n/)){let t=e.trim();if(!t||t.startsWith(`#`))continue;let n=/^\[\s*([^\]]+?)\s*\]$/.exec(t);if(n){o=n[1].replace(/["']/g,``).replace(/\s*\.\s*/g,`.`);continue}if(!o||!i.has(o))continue;let r=/^([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')/.exec(t);r&&(a[r[1]]=r[2]===void 0?r[3]:r[2].replace(/\\(.)/g,`$1`))}return a}function Oz(e,t){return typeof t==`string`?e===`solana`?kz(t)===32:/^0x[0-9a-fA-F]{40}$/.test(t):!1}function kz(e){if(!/^[1-9A-HJ-NP-Za-km-z]{1,64}$/.test(e))return;let t=0n;for(let n of e)t=t*58n+BigInt(`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`.indexOf(n));let n=/^1*/.exec(e)[0].length,r=t===0n?``:t.toString(16);return n+Math.ceil(r.length/2)}function Az(e,n,r){if(/[\r\n]/.test(n)||/[\r\n]/.test(r))throw Error(`env values cannot contain line breaks`);let i=`${n}=${r}`;if(!t.existsSync(e))return t.writeFileSync(e,`${i}\n`,{mode:384});let a=t.readFileSync(e,`utf8`),o=RegExp(`^\\s*(?:export\\s+)?${n}\\s*=`),{lines:s,found:c}=jz(a.split(`
246
+ `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await iz({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 iz(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:{...OD(e.fetchInit.headers),Authorization:t}});if(n.ok){if(_z(e.channelId),e.verbose>=1){let t=n.headers.get(q.paymentReceipt),r;if(t)try{let e=JSON.parse(te.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${X.dim(pM(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${yM(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${X.dim(X.yellow(`Channel close failed`))} ${X.dim(`(${n.status})`)}\n`),e.info(`${X.dim(` channelId: ${e.channelId}`)}\n${X.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${X.dim(` escrowContract: ${e.escrowContract}`)}\n${X.dim(` chainId: ${e.chainId}`)}\n${X.dim(` response: ${t||`(empty)`}`)}\n`)}}function az(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 oz(e){return uz(Ez,e,Dz)}function sz(e){return e.method===`tempo`&&e.intent===`charge`}async function cz(e){let t=VM(e.options.account),n=process.env.MPPX_PRIVATE_KEY?.trim()||(gM(t)?void 0:await HM(t).get()),r;if(n)r=R(n).address;else if(gM(t)&&xz())r=bz(t)?.wallet_address;else{let e=Cz();if(e){let t=await HM(e).get();t&&(r=R(t).address)}}if(!r)return;let i=bM(e.options.rpcUrl,{network:e.options.network}),a=N({chain:await SM({network:e.options.network,rpcUrl:i}),transport:L(i)});return{account:r,client:a}}async function lz(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,o=a?.chainId;if(o&&t.client.chain?.id&&o!==t.client.chain.id)return`unsupported`;let s=BigInt(i);if(s===0n)return`payable`;let c=await Be.token.getBalance(t.client,{account:t.account,token:r}).then(e=>e.amount).catch(()=>void 0);if(c===void 0)return`unknownBalance`;if(c>=s)return`payable`;if(a?.machineTokenEnabled===!0&&!a.splits?.length){let e=await JP(t.client,{account:t.account,chainId:o??t.client.chain?.id});if(e!==void 0&&e>=s)return`payable`}return`insufficientBalance`}function uz(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 dz(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 B({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function fz(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function pz(e){let t=fz(e.tokenIn)??fz(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 mz(){return c.join(process.env.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`mppx`,`channels`)}function hz(e){try{let n=t.readFileSync(c.join(mz(),e),`utf-8`).trim();return n?BigInt(n):void 0}catch{return}}function gz(e,n){let r=mz();t.mkdirSync(r,{recursive:!0}),t.writeFileSync(c.join(r,e),n.toString(),`utf-8`)}function _z(e){try{t.unlinkSync(c.join(mz(),e))}catch{}}function vz(){return x.platform()===`darwin`?c.join(x.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):c.join(process.env.XDG_DATA_HOME||c.join(x.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function yz(){try{let e=t.readFileSync(vz(),`utf-8`),n=[],r;for(let t of e.split(`
247
+ `)){let e=t.trim();if(e===`[[keys]]`){r?.wallet_address&&n.push(r),r={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!r)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?r.wallet_type=o:a===`wallet_address`?r.wallet_address=o:a===`chain_id`&&(r.chain_id=Number.parseInt(o,10))}return r?.wallet_address&&n.push(r),n}catch{return[]}}function bz(e){let t=yz();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 xz(){if(kz!==void 0)return kz;try{m.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),kz=!0}catch{kz=!1}return kz}async function Sz(e){return new Promise((t,n)=>{m.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function Cz(){let e=BM();if(gM(e.get())&&!xz()&&x.platform()===`darwin`)try{let t=m.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===wz&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}var wz,Tz,Ez,Dz,Oz,kz,Az=z((()=>{Rx(),DO(),Gx(),vC(),XR(),$P(),CA(),SI(),JM(),PM(),eP(),wz=`mppx`,Tz=p.union([p.boolean(),p.literal(`true`).transform(()=>!0),p.literal(`false`).transform(()=>!1)]),Ez=p.object({allowCustomEscrow:p.optional(Tz),autoSwap:p.optional(Tz),channel:p.optional(p.coerce.string()),deposit:p.optional(p.union([p.string(),p.number()])),payWith:p.optional(p.string()),slippage:p.optional(p.coerce.number()),tokenIn:p.optional(p.string())}),Dz=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`],Oz=[`payable`,`unknownBalance`,`insufficientBalance`,`unsupported`]}));ZC(),JM(),eP();const jz=[...Object.entries(iN),...Object.entries(aN),...Object.entries(oN),...Object.entries(sN)];function Mz(){return $N({method:`evm`,supports:Nz,async setup({challenge:e,options:t}){let n=e.request,r=n.network?Pz(gN(n.network)):void 0,i=n.network&&n.asset?jz.find(([,e])=>mN(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`?nN({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await GM(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...QN({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function Nz(e){if(!YC(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 Pz(e){return Object.values(Qe).find(t=>t.id===e)}sC(),vw(),vk(),lS(),Az();const Fz=[ez(),uP(),tP(),Mz()];async function Iz(e,t,n){let r=n;for(let n of t??[]){let t=await n.preparePayment?.({challenge:e,...r===void 0?{}:{credentialContext:r}});t&&`credentialContext`in t&&(r=t.credentialContext)}return r}function Lz(e,t){let n=t?.plugins?.find(t=>Vz(t,e));if(n)return{plugin:n};let r=Bz(t)?.filter(t=>t.name===e.method&&t.intent===e.intent),i=r?.find(t=>t.canHandleChallenge?.({challenge:e})??!0);if(i)return{method:i};if(r?.length)return{};let a=Fz.find(t=>Vz(t,e));return a?{plugin:a}:{}}function Rz(e,t){let n=Bz(t);if(n?.length){let r=nw(e,n,$C(n,t?.paymentPreferences).entries);if(r){let e=t?.plugins?.find(e=>Vz(e,r.challenge));return{challenge:r.challenge,...e?{plugin:e}:{method:r.method}}}return}for(let n of e){let e=Lz(n,t);if(e.plugin||e.method)return{challenge:n,...e}}}function zz(e){let t=Bz(e);if(t?.length)return $C(t,e?.paymentPreferences).header}function Bz(e){return Array.isArray(e?.methods)?e.methods.flat():void 0}function Vz(e,t){return e.supports?e.supports(t):e.method===t.method}async function Hz(e){let t=Uz(e);if(!t)return;let n=await import(t);return{config:n.default??n,path:t}}function Uz(e){if(e){let n=c.resolve(e);return t.existsSync(n)?n:void 0}let n=process.env.MPPX_CONFIG?.trim();if(n){let e=c.resolve(n);return t.existsSync(e)?e:void 0}}function Wz(e,t){function n(t){let n={...t.request};if(t.method===`tempo`&&t.intent===`session`){let e={...n.methodDetails};delete e.sessionSnapshot,Object.keys(e).length?n.methodDetails=e:delete n.methodDetails}let{meta:r,opaque:i,...a}=t;return JSON.stringify([CS({...a,request:n,id:e.id,expires:e.expires}),Gz(t)])}if(n(t)!==n(e))throw Error(`Payment request changed on retry. Run the command again to approve the new payment.`)}function Gz(e){let t=e.opaque??(e.meta?cS(e.meta):void 0);if(t===void 0)return;let n;try{n=oS(t)}catch{return t}if(typeof n!=`object`||!n||Array.isArray(n))return t;let r=pk(n);return r?cS(r):void 0}Az(),sC(),bE(),HI(),cR(),vR(),Zj();function Kz(e){return e??globalThis.fetch.bind(globalThis)}function qz(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(PI(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Error(`Close challenge changed the session escrow.`);let r=hj(e);if(r&&r.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Close challenge changed the session channel.`)}async function Jz(e){qz(e.challenge,e.channel);let t=e.channel;if(t.origin===void 0){let n=new URL(e.input instanceof Request?e.input.url:e.input);if(![`http:`,`https:`].includes(n.protocol))throw Error(`Legacy session close requires an HTTP origin`);gE(e.challenge,n,e.manager.trustedTempoProofRealms),t={...t,origin:n.origin}}let n=Kz(e.fetch),r,i=async(t,i)=>{r&&=(await e.onChallenge?.(r),void 0);let a=await n(t,i);if(a.status!==402)return a;let o=RS(a).find(pj);if(!o)throw Error(`Refreshed close response did not include tempo/session.`);return qz(o,e.channel),r=o,a},a=_R({...e.manager,bootstrap:!1,escrow:e.channel.escrow,fetch:i});oR(a).rehydrate({...e,channel:t}),t!==e.channel&&await e.manager.channelStore?.set(t);let o=await a.close();if(!o)throw Error(`Session close response did not include a payment receipt.`);return{manager:a,receipt:o}}sC(),HI(),tL(),Zj(),VF(),xS();var Yz=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}},Xz=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 Zz=Y.object({origin:Y.optional(Y.string()),channelId:_S(),cumulativeAmount:Y.string(),deposit:Y.string(),descriptor:Y.object({payer:gS(),payee:gS(),operator:gS(),token:gS(),salt:_S(),authorizedSigner:gS(),expiringNonceHash:_S()}),escrow:gS(),chainId:Y.number(),opened:Y.boolean()}),Qz=Y.object({name:Y.optional(Y.string()),address:gS()}),$z=Y.object({method:Y.literal(`tempo`),intent:Y.literal(`session`),status:Y.literal(`success`),timestamp:Y.string(),reference:Y.string(),challengeId:Y.string(),channelId:_S(),acceptedCumulative:Y.string(),spent:Y.string(),units:Y.optional(Y.number()),txHash:Y.optional(_S())}),eB=Y.object({version:Y.literal(1),method:Y.literal(`tempo`),intent:Y.literal(`session`),status:Y.enum([`opening`,`open`,`closing`,`stale`]),channel:Zz,account:Qz,endpoint:Y.string(),challenge:rC,receipt:Y.optional($z),spent:Y.string(),units:Y.number(),createdAt:Y.string(),updatedAt:Y.string()}),tB=Y.object({version:Y.literal(1),channelId:_S()}),nB=Y.object({version:Y.literal(1),scope:Y.string(),hostname:Y.string(),pid:Y.number(),token:Y.string(),createdAt:Y.string()});function rB(e,t,n,r){let i=e.safeParse(t);if(!i.success)throw Z(n,r,i.error);return i.data}function iB(e){let t=mB(e);return[t.payer,t.payee,t.token,t.escrow,t.chainId].join(`:`)}function aB(e){return{payer:e.descriptor.payer,payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId}}function oB(e={}){let t=e.stateRoot??cB(),n={root:t,channels:c.join(t,`channels`),locks:c.join(t,`locks`),preferred:c.join(t,`preferred`)},r=e.hostname??x.hostname(),i=e.pid??process.pid,a=e.now??(()=>new Date),o=e.isProcessAlive??BB;async function s(){for(let e of[n.root,n.channels,n.locks,n.preferred])await w.mkdir(e,{recursive:!0,mode:448}),await w.chmod(e,448)}async function l(e){let t=fB(e),r=lB(n,t),i=await jB(r);if(i===void 0)return;let a=SB(i,r);if(a.channel.channelId.toLowerCase()!==t)throw Z(r,`Session filename does not match its channel ID.`);return CB(a)}async function u(){let e;try{e=await w.readdir(n.channels,{withFileTypes:!0})}catch(e){if(HB(e,`ENOENT`))return[];throw Z(n.channels,`Unable to list managed sessions.`,e)}let t=[];for(let n of e){if(!n.isFile()||n.name.includes(`.tmp-`)||!n.name.endsWith(`.json`))continue;let e=n.name.slice(0,-5);fB(e);let r=await l(e);r&&t.push(r)}return t.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}async function d(e){await s();let t=vB(e.channel),r=fB(t.channelId),i=lB(n,r),o=await jB(i),c=o===void 0?void 0:SB(o,i);c&&wB(c,e,i);let l=c?.channel.origin??t.origin;if(c?.channel.origin&&t.origin&&c.channel.origin!==t.origin)throw Z(i,`Session payment origin mismatch.`);if(l!==void 0&&new URL(l).origin!==l)throw Z(i,`Session payment origin must be a normalized origin.`);let u=bB(e.challenge,i);EB(u,t,i);let d=e.receipt?xB(e.receipt,t.channelId,i):void 0,f=c?qI(c.channel):void 0,p=AB(t.cumulativeAmount,f?.cumulativeAmount??0n),m=AB(e.spent??0n,d?BigInt(d.spent):0n,c?BigInt(c.spent):0n);if(m>p)throw Z(i,`Session spend exceeds the locally authorized cumulative amount.`);let h=yB(KI({...t,cumulativeAmount:p,...l!==void 0&&{origin:l}}),i),g=kB(c?.updatedAt,a(),i),_=OB(c?.receipt,d),v=_B(e.account,i),y=SB({version:1,method:`tempo`,intent:`session`,status:e.status,channel:h,account:{...v.name===void 0?c?.account.name===void 0?{}:{name:c.account.name}:{name:v.name},address:v.address},endpoint:gB(e.endpoint,i),challenge:u,..._!==void 0&&{receipt:_},spent:m.toString(),units:Math.max(c?.units??0,e.units??0,d?.units??0),createdAt:c?.createdAt??g,updatedAt:g},i);return await MB(i,y),CB(y)}async function f(e){let t=dB(n,e),r=await jB(t);if(r===void 0)return;let{channelId:i}=rB(tB,r,t,`Preferred session is invalid.`),a=await l(i);if(!a)throw Z(t,`Preferred session ${i} does not exist.`);return DB(a.channel,e,t),i}async function p(e,t){let r=fB(t),i=await l(r),a=dB(n,e);if(!i)throw Z(a,`Session ${r} does not exist.`);DB(i.channel,e,a),await MB(a,{version:1,channelId:r})}async function m(e,t){let r=dB(n,e),i=t===void 0?void 0:fB(t),a=await jB(r);if(a===void 0)return;let o=rB(tB,a,r,`Preferred session is invalid.`).channelId;i&&o.toLowerCase()!==i||await RB(r,`Unable to clear preferred session.`)}async function h(e){let t=fB(e),r=await l(t);r&&(await m(aB(r.channel),t),await RB(lB(n,t),`Unable to remove session.`))}async function g(e){await s();let t=uB(n,e);for(let n=0;n<3;n++){let n={version:1,scope:e,hostname:r,pid:i,token:v(),createdAt:a().toISOString()};try{if(await NB(t,n),await IB(FB(t))){await LB(t,n);continue}return{async release(){await LB(t,n)}}}catch(e){if(!HB(e,`EEXIST`))throw e}let s=await jB(t);if(s===void 0)continue;let c=rB(nB,s,t,`Session lock is invalid.`);if(c.scope!==e)throw Z(t,`Session lock scope is invalid.`);if(c.hostname!==r||o(c.pid))throw new Xz(e,c);await PB(t,c)}let c=await jB(t);throw c===void 0?Z(t,`Unable to acquire session lock.`):new Xz(e,rB(nB,c,t,`Session lock is invalid.`))}async function _(e){return g(iB(e))}return{root:t,get:l,list:u,upsert:d,remove:h,getPreferred:f,setPreferred:p,clearPreferred:m,acquire:_}}function sB(e,t){let n=hB(t.scope),r=t.selection===`auto`||t.selection===`new`?void 0:fB(t.selection);function i(e){if(e.toLowerCase()!==n)throw new Yz(`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 Yz(`Session ${i} does not exist.`);if(DB(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(WI(n)),DB(n,t.scope),r&&r.toLowerCase()!==n.channelId.toLowerCase())throw new Yz(`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 cB(){let e=process.env.XDG_STATE_HOME||c.join(x.homedir(),`.local`,`state`);return c.join(e,`mppx`,`sessions`,`v1`)}function lB(e,t){return c.join(e.channels,`${t}.json`)}function uB(e,t){let n=_(`sha256`).update(t).digest(`hex`);return c.join(e.locks,`${n}.lock`)}function dB(e,t){let n=_(`sha256`).update(iB(t)).digest(`hex`);return c.join(e.preferred,`${n}.json`)}function fB(e){return rB(_S(),e,void 0,`Invalid session channel ID: ${e}.`).toLowerCase()}function pB(e,t,n){return rB(gS(),e,n,`Invalid ${t}.`).toLowerCase()}function mB(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<0)throw new Yz(`Invalid session chain ID.`);return{payer:pB(e.payer,`session payer`),payee:pB(e.payee,`session payee`),token:pB(e.token,`session token`),escrow:pB(e.escrow,`session escrow`),chainId:e.chainId}}function hB(e){let t=mB(e);return[t.payee,t.token,t.escrow,t.chainId].join(`:`)}function gB(e,t){if(typeof e!=`string`)throw Z(t,`Session endpoint is invalid.`);let n;try{n=new URL(e)}catch(e){throw Z(t,`Session endpoint is invalid.`,e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Z(t,`Session endpoint must use HTTP or HTTPS.`);if(n.username||n.password)throw Z(t,`Session endpoint must not contain credentials.`);let r=e.indexOf(`#`);return r===-1?e:e.slice(0,r)}function _B(e,t){return rB(Qz,e,t,`Session account is invalid.`)}function vB(e){return qI(yB(KI(e)))}function yB(e,t){return rB(Zz,e,t,`Stored session channel is invalid.`)}function bB(e,t){let n=rC.safeParse(e);if(!n.success||!pj(n.data))throw Z(t,`Stored session challenge is invalid.`);return n.data}function xB(e,t,n){let r=rB($z,e,n,`Stored session receipt is invalid.`);if(r.channelId!==t.toLowerCase())throw Z(n,`Stored session receipt has a different channel ID.`);if(r.reference.toLowerCase()!==t.toLowerCase())throw Z(n,`Stored session receipt has a different reference.`);if(BigInt(r.spent)>BigInt(r.acceptedCumulative))throw Z(n,`Stored session receipt spend exceeds its accepted amount.`);return r}function SB(e,t){let n=rB(eB,e,t,`Stored session is invalid.`),{receipt:r,...i}=n,a=n.channel,o=n.account;if(o.address.toLowerCase()!==a.descriptor.payer.toLowerCase())throw Z(t,`Stored session account does not match the channel payer.`);let s=r?xB(r,a.channelId,t):void 0,c=n.spent,l=BigInt(a.cumulativeAmount);if(BigInt(c)>l)throw Z(t,`Stored session spend exceeds its cumulative authorization.`);if(s&&BigInt(s.acceptedCumulative)>l)throw Z(t,`Stored receipt exceeds the cumulative authorization.`);if(Date.parse(n.updatedAt)<Date.parse(n.createdAt))throw Z(t,`Stored session timestamps are not monotonic.`);let u=gB(n.endpoint,t);if(u!==n.endpoint)throw Z(t,`Stored session endpoint contains a fragment.`);let d=bB(n.challenge,t);return EB(d,qI(a),t),{...i,account:o,channel:a,endpoint:u,challenge:d,...s&&{receipt:s}}}function CB(e){return{version:1,status:e.status,channel:qI(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 wB(e,t,n){let r=vB(t.channel),i=_B(t.account,n),a=qI(e.channel);if(JSON.stringify(TB(r))!==JSON.stringify(TB(a)))throw Z(n,`Session update changed immutable channel identity.`);if(i.address.toLowerCase()!==e.account.address.toLowerCase())throw Z(n,`Session update changed the payer account.`)}function TB(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 EB(e,t,n){if(LF({...t.descriptor,chainId:t.chainId,escrow:t.escrow}).toLowerCase()!==t.channelId.toLowerCase())throw Z(n,`Session channel ID does not match its descriptor.`);let r=pB(e.request.recipient,`challenge recipient`,n),i=pB(e.request.currency,`challenge currency`,n);if(r!==t.descriptor.payee.toLowerCase())throw Z(n,`Session challenge payee does not match the channel.`);if(i!==t.descriptor.token.toLowerCase())throw Z(n,`Session challenge token does not match the channel.`);if(PI(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Z(n,`Session challenge escrow does not match the channel.`);if(VB(e.request.methodDetails)){let r=e.request.methodDetails;if(r.chainId!==void 0&&r.chainId!==t.chainId)throw Z(n,`Session challenge chain does not match the channel.`)}}function DB(e,t,n){let r=mB(t);if(e.descriptor.payer.toLowerCase()!==r.payer||e.descriptor.payee.toLowerCase()!==r.payee||e.descriptor.token.toLowerCase()!==r.token||e.escrow.toLowerCase()!==r.escrow||e.chainId!==r.chainId)throw Z(n,`Session channel does not match the selected payment scope.`)}function OB(e,t){return e?t&&Date.parse(t.timestamp)>=Date.parse(e.timestamp)?t:e:t}function kB(e,t,n){if(!Number.isFinite(t.getTime()))throw Z(n,`Session clock is invalid.`);let r=t.toISOString();return!e||Date.parse(r)>=Date.parse(e)?r:e}function AB(...e){return e.reduce((e,t)=>t>e?t:e,0n)}async function jB(e){let t;try{t=await w.readFile(e,`utf8`)}catch(t){if(HB(t,`ENOENT`))return;throw Z(e,`Unable to read session state.`,t)}try{return JSON.parse(t)}catch(t){throw Z(e,`Session state contains invalid JSON.`,t)}}async function MB(e,t){await w.mkdir(c.dirname(e),{recursive:!0,mode:448}),await w.chmod(c.dirname(e),448);let n=`${e}.tmp-${process.pid}-${v()}`,r;try{r=await w.open(n,`wx`,384),await r.writeFile(`${JSON.stringify(t,null,2)}\n`,`utf8`),await r.sync(),await r.close(),r=void 0,await w.rename(n,e),await w.chmod(e,384),await zB(c.dirname(e))}catch(t){throw await r?.close().catch(()=>void 0),await w.unlink(n).catch(()=>void 0),t instanceof Yz?t:Z(e,`Unable to write session state.`,t)}}async function NB(e,t){let n;try{n=await w.open(e,`wx`,384),await n.writeFile(`${JSON.stringify(t)}\n`,`utf8`),await n.sync(),await n.close(),n=void 0,await zB(c.dirname(e))}catch(t){throw await n?.close().catch(()=>void 0),n&&await w.unlink(e).catch(()=>void 0),t}}async function PB(e,t){let n=FB(e);try{await w.link(e,n)}catch(t){if(HB(t,`EEXIST`)||HB(t,`ENOENT`))return;throw Z(e,`Unable to claim dead lock.`,t)}try{let r=await jB(n);if(r===void 0||rB(nB,r,n,`Session lock is invalid.`).token!==t.token)return;await RB(e,`Unable to reclaim dead lock.`)}finally{await RB(n,`Unable to release dead lock claim.`)}}function FB(e){return`${e}.reclaim`}async function IB(e){try{return await w.access(e),!0}catch(t){if(HB(t,`ENOENT`))return!1;throw Z(e,`Unable to inspect session lock.`,t)}}async function LB(e,t){let n=await jB(e);n!==void 0&&rB(nB,n,e,`Session lock is invalid.`).token===t.token&&await RB(e,`Unable to release session lock.`)}async function RB(e,t){try{await w.unlink(e),await zB(c.dirname(e))}catch(n){if(!HB(n,`ENOENT`))throw Z(e,t,n)}}async function zB(e){let t=await w.open(e,`r`);try{await t.sync()}finally{await t.close()}}function BB(e){try{return process.kill(e,0),!0}catch(e){if(HB(e,`ESRCH`))return!1;if(HB(e,`EPERM`))return!0;throw e}}function VB(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function HB(e,t){return e instanceof Error&&`code`in e&&e.code===t}function Z(e,t,n){return new Yz(t,{...n!==void 0&&{cause:n},file:e})}Rx(),sC(),DO(),KL(),cL(),VF(),JM(),PM();const UB=p.object({status:p.enum([`opening`,`open`,`closing`,`stale`]),channelId:p.string(),account:p.string().optional(),payer:p.string(),payee:p.string(),authorizedSigner:p.string(),token:p.string(),escrow:p.string(),chainId:p.number(),cumulativeAmount:p.string(),confirmedSpend:p.string(),deposit:p.string(),units:p.number(),resourceUrl:p.string(),createdAt:p.string(),updatedAt:p.string()}),WB=p.object({channelId:p.string(),status:p.enum([`closed`,`already-closed`]),spent:p.string(),txHash:p.string().optional()}),GB=p.object({closed:p.array(WB),failed:p.array(p.object({channelId:p.string(),message:p.string()}))});function KB(e){return e===`mainnet`?ve.id:ye.id}function qB(e){if(e===ve.id)return`mainnet`;if(e===ye.id)return`testnet`}function JB(e){let t={};for(let n of e??[]){let e=n.indexOf(`:`);if(e===-1)throw new B({code:`INVALID_HEADER`,message:`Invalid header format: ${n}`,exitCode:2});t[n.slice(0,e).trim()]=n.slice(e+1).trim()}return t}function YB(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 XB(e,t){throw e instanceof B?e:e instanceof Xz?new B({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e instanceof Yz?new B({code:e.code,message:e.message,exitCode:65,cause:e}):new B({code:t,message:e instanceof Error?e.message:String(e),exitCode:75,...e instanceof Error&&{cause:e}})}async function ZB(e,t){let n=await WM(t??e.account.name);if(!kL(n.account,e.channel.descriptor))throw new B({code:`SESSION_ACCOUNT_MISMATCH`,message:`Account ${n.account.address} cannot sign for session ${e.channel.channelId}.`,exitCode:2});return n}async function QB(e,t){if(t.network&&KB(t.network)!==e)throw new B({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, not ${t.network}.`,exitCode:2});let n=t.network??qB(e),r=bM(t.rpcUrl,{network:n}),i=await SM({network:n,rpcUrl:r});if(i.id!==e)throw new B({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, but RPC is chainId ${i.id}.`,exitCode:2});return N({chain:i,transport:L(r)})}const $B=vb(`sessions`,{description:`Manage persistent payment sessions (list, view, close)`}).command(`list`,{description:`List persistent payment sessions`,options:p.object({account:p.string().optional().describe(`Filter by account name`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Filter by Tempo network`)}),output:p.object({sessions:p.array(UB)}),alias:{account:`a`},async run(e){try{let t=(await oB().list()).filter(t=>!(e.options.account&&t.account.name!==e.options.account||e.options.network&&t.channel.chainId!==KB(e.options.network))).map(YB),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(``),eV(n);return}catch(e){return XB(e,`SESSION_LIST_FAILED`)}}}).command(`view`,{description:`View a persistent payment session`,args:p.object({channelId:p.string().describe(`Full session channel ID`)}),output:UB,async run(e){try{let t=await oB().get(e.args.channelId);if(!t)throw new B({code:`SESSION_NOT_FOUND`,message:`Session ${e.args.channelId} was not found.`,exitCode:2});let n=YB(t);if(e.format===`json`&&e.formatExplicit)return e.ok(n);eV(n);return}catch(e){return XB(e,`SESSION_VIEW_FAILED`)}}}).command(`close`,{description:`Cooperatively close persistent payment sessions`,usage:[{suffix:`<channel-id> [options]`},{suffix:`--all --yes [options]`}],args:p.object({channelId:p.string().optional().describe(`Full session channel ID`)}),options:p.object({account:p.string().optional().describe(`Account name`),all:p.boolean().optional().default(!1).describe(`Close every matching session`),header:p.array(p.string()).optional().describe(`Add close request header (repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`),url:p.string().optional().describe(`Override the stored resource URL`),yes:p.boolean().optional().default(!1).describe(`Confirm closing every session`)}),output:p.union([WB,GB]),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=oB();async function n(e,n={}){let r=await t.get(e);if(!r)throw new B({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let i=aB(r.channel),a=await t.acquire(i);try{let r=await t.get(e);if(!r)throw new B({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});if(KS(r.challenge))throw new B({code:`SESSION_STATE_INVALID`,message:`Stored session challenge selects a credential header other than Payment-Authorization.`,exitCode:65});let a=await ZB(r,n.account),o=await QB(r.channel.chainId,n);if(LF({...r.channel.descriptor,escrow:r.channel.escrow,chainId:r.channel.chainId}).toLowerCase()!==r.channel.channelId.toLowerCase())throw new B({code:`SESSION_STATE_INVALID`,message:`Stored descriptor does not derive the session channel ID.`,exitCode:65});if((await iL(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=gB(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=JB(n.headers),f=u.challenge,p=await Jz({channel:u.channel,challenge:u.challenge,fetch:async(e,t)=>globalThis.fetch(e,{...t,headers:{...d,...OD(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:sB(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===KB(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 XB(e,`SESSION_CLOSE_FAILED`)}}});function eV(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}`)}Rx(),KL(),cR(),vR(),CA(),JM(),PM();function tV(e,t){if(t&&e!==`auto`&&t.toLowerCase()!==e.toLowerCase())throw new B({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 B({code:`INVALID_SESSION`,message:`Session must be auto, new, or a 32-byte channel ID.`,exitCode:2})}function nV(e){let t=e.allowCustomEscrow;if(t!==void 0){if(t===`true`)return!0;if(t===`false`)return!1;throw new B({code:`INVALID_ALLOW_CUSTOM_ESCROW`,message:`allowCustomEscrow must be true or false.`,exitCode:2})}}function rV(e,t,n,r){if(t.deposit!==void 0)return t.deposit;let i=e.request.suggestedDeposit;return typeof i==`string`?oe(BigInt(i),r):n?`10`:void 0}function iV(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 aV(e,t){return e.channel.channelId.toLowerCase()===t.toLowerCase()}function oV(e){if(e.trim()!==`[DONE]`){if(e.length===0){process.stdout.write(`
248
+ `);return}try{let t=JSON.parse(e);process.stdout.write(t.token??t.choices?.[0]?.delta?.content??e)}catch{process.stdout.write(e)}}}async function sV(e){let{options:t}=e,n=await WM(t.account),r=bM(t.rpcUrl,{network:t.network}),i=await SM({network:t.network,rpcUrl:r}),a=N({chain:i,transport:L(r)}),o=nV(e.methodOptions),s=await CL({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new B({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let{decimals:c}=await EM(a,s.token,n.account.address,{requireDecimals:!0}),l={payer:n.account.address,payee:s.payee,token:s.token,escrow:s.escrow,chainId:s.chainId},u=tV(t.session,e.methodOptions.channel),d=e.registry??oB(),f=await d.acquire(l).catch(e=>{throw e instanceof Xz?new B({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=u===`auto`?await d.getPreferred(l):u===`new`?void 0:u,s=r?await d.get(r):void 0;if(r&&!s)throw new B({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&u!==`auto`&&(s.status!==`open`||!s.channel.opened||iB(aB(s.channel))!==iB(l)||!kL(n.account,s.channel.descriptor)))throw new B({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let f=s?.status===`open`&&s.channel.opened?s:void 0,p=f?`open`:`opening`,m=e.challenge,h=f?.receipt,g=f?.spent??0n,_=f?.units??0,v=gB(e.endpoint),y={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},b=sB(d,{scope:l,selection:u,context:()=>({status:p,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),onNewChannel(){p=`opening`,h=void 0,g=0n,_=0}}),{signal:x,...S}=e.init,C={...S,...x&&{signal:x},onReceipt(e){h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0)}};if(e.challengeResponse.status!==402||e.challengeResponse.bodyUsed)throw Error(`Session manager requires an unconsumed 402 challenge response.`);let w=!0,T=_R({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:b,credentialContext:e.credentialContext,decimals:c,maxDeposit:rV(e.challenge,e.methodOptions,TM(i),c),fetch:async(t,n)=>w?(w=!1,e.challengeResponse):e.fetch(t,n)});f&&oR(T).rehydrate({channel:f.channel,challenge:e.challenge,input:e.fetchInput,spent:f.spent});let{onReceipt:E,...ee}=C,D=await T.fetch(e.fetchInput,ee);if(t.fail&&D.status>=400)throw new B({code:`HTTP_ERROR`,message:`HTTP error ${D.status}`,exitCode:22});if(D.status===402)throw new B({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});cM(D,{include:!1,verbose:t.include?Math.max(t.verbose,2):t.verbose,silent:t.silent}),m=D.challenge??e.challenge;let O=T.channelId;if(!O)throw Error(`Session manager did not select a channel.`);if(h=iV(D.receipt,{challenge:m,channelId:O,cumulative:T.cumulative})??h,pA(D)){let t=oR(T).consumeSseResponse(e.fetchInput,D,{onReceipt:E,signal:e.init.signal??void 0});for await(let e of t)oV(e)}else process.stdout.write(Buffer.from(await D.arrayBuffer()));let k=await d.get(O);if(!k||!aV(k,O))throw Error(`Session ${O} was not persisted.`);if(h){let e=iV(h,{challenge:m,channelId:O,cumulative:T.cumulative});if(!e)throw Error(`Session receipt validation failed.`);h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0),p=`open`}await d.upsert({status:p,channel:k.channel,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),t.silent||(e.info(`Session retained ${O}\n`),e.info(`Close with: mppx sessions close ${O}\n`))}finally{await f.release()}}const cV=`StripeCLI`;function lV(e){let t=e.env??process.env,n=e.secretKey?.trim();if(n)return{key:n,source:`flag`};let r=t.STRIPE_SECRET_KEY?.trim();if(r)return{key:r,source:`env`};let i=uV(e);if(i)return{key:i,source:`stripe-cli`}}function uV(e){let t=e.env??process.env,n=c.join(t.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`stripe`),r=e.projectName||t.STRIPE_PROJECT_NAME||`default`,i=mV(c.join(n,`config.toml`),r);if(!e.live)return i.test_mode_api_key||i.secret_key||i.api_key||void 0;let a=i.live_mode_api_key;if(a&&!a.includes(`*`))return a;let o=`${r}.live_mode_api_key`,s=pV(c.join(n,`credentials.json`))?.[o];return typeof s==`string`&&s?s:dV(o,e)}function dV(e,t){let n=t.platform??process.platform,r=t.exec??fV,i=(()=>{if(n===`darwin`)return[`security`,[`find-generic-password`,`-s`,cV,`-a`,e,`-w`]];if(n===`linux`)return[`secret-tool`,[`lookup`,`service`,cV,`username`,e]]})();if(i)try{let e=r(i[0],i[1]).trim();return e.startsWith(`go-keyring-base64:`)?Buffer.from(e.slice(18),`base64`).toString(`utf8`)||void 0:e||void 0}catch{return}}function fV(e,t){return g(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:3e3})}function pV(e){try{return JSON.parse(t.readFileSync(e,`utf8`))}catch{return}}function mV(e,n){let r;try{r=t.readFileSync(e,`utf8`)}catch{return{}}let i=new Set([n,`profiles.${n}`]),a={},o;for(let e of r.split(/\r?\n/)){let t=e.trim();if(!t||t.startsWith(`#`))continue;let n=/^\[\s*([^\]]+?)\s*\]$/.exec(t);if(n){o=n[1].replace(/["']/g,``).replace(/\s*\.\s*/g,`.`);continue}if(!o||!i.has(o))continue;let r=/^([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')/.exec(t);r&&(a[r[1]]=r[2]===void 0?r[3]:r[2].replace(/\\(.)/g,`$1`))}return a}function hV(e,t){return typeof t==`string`?e===`solana`?gV(t)===32:/^0x[0-9a-fA-F]{40}$/.test(t):!1}function gV(e){if(!/^[1-9A-HJ-NP-Za-km-z]{1,64}$/.test(e))return;let t=0n;for(let n of e)t=t*58n+BigInt(`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`.indexOf(n));let n=/^1*/.exec(e)[0].length,r=t===0n?``:t.toString(16);return n+Math.ceil(r.length/2)}function _V(e,n,r){if(/[\r\n]/.test(n)||/[\r\n]/.test(r))throw Error(`env values cannot contain line breaks`);let i=`${n}=${r}`;if(!t.existsSync(e))return t.writeFileSync(e,`${i}\n`,{mode:384});let a=t.readFileSync(e,`utf8`),o=RegExp(`^\\s*(?:export\\s+)?${n}\\s*=`),{lines:s,found:c}=vV(a.split(`
249
249
  `),o,i),l=a===``||a.endsWith(`
250
250
  `)?``:`
251
251
  `,u=c?s.join(`
252
- `):`${a}${l}${i}\n`,d=y.parseEnv;if(d){let t=d(a),i=d(u),o=new Set([...Object.keys(t),...Object.keys(i)]);if(o.delete(n),i[n]!==r||[...o].some(e=>t[e]!==i[e]))throw Error(`could not update ${n} in ${e} safely: edit it by hand`)}t.writeFileSync(e,u)}function jz(e,t,n){let r={};for(let t of[`"`,`'`,"`"]){let n=Array(e.length+1);n[e.length]=-1;for(let r=e.length-1;r>=0;r--)n[r]=Mz(e[r],t)?r:n[r+1];r[t]=n}let i=[],a=!1;for(let o=0;o<e.length;o++){let s=o,c=/^[ \t]*[^#=\s][^=]*=[ \t]*(["'`])(.*)$/s.exec(e[o]);if(c&&!Mz(c[2],c[1])){let e=r[c[1]][o+1];e!==-1&&(s=e)}let l=t.test(e[o]);if(l&&!a&&i.push(e[o].endsWith(`\r`)?`${n}\r`:n),a||=l,!l)for(let t=o;t<=s;t++)i.push(e[t]);o=s}return{lines:i,found:a}}function Mz(e,t){return e.includes(t)}function Nz(e){let t=e.findIndex((t,n)=>t===`stripe`&&e[n+1]===`address`);if(t===-1)return[...e];let n=e.slice(0,t+2);for(let r=t+2;r<e.length;r++){let t=e[r];if(n.push(t),t===`--`){n.push(...e.slice(r+1));break}let i=e[r+1];t===`--env`&&(i===void 0||i.startsWith(`-`))&&n.push(`.env`)}return n}GE();function Q(e,t){return t?{label:e,detail:t,severity:`pass`}:{label:e,severity:`pass`}}function $(e,t,n){let r={label:e,severity:`fail`};return t&&(r.detail=t),n&&(r.hint=n),r}function Pz(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function Fz(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}async function Iz(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{let n=globalThis.fetch,i=yE(n),a=vE(n),o={[RE]:!0,...t,redirect:`error`,signal:r.signal};return a?(await a.send((e,t)=>i(e,{...t,[RE]:!0}),new Request(e,o))).response:await i(e,o)}finally{clearTimeout(i)}}function Lz(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const Rz=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function zz(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function Bz(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function Vz(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!Rz.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 Hz(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 Uz(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 Wz(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await Iz(t,{});if(!e.ok)return{error:`HTTP ${e.status}`};let n=await e.text();return{doc:JSON.parse(n),raw:n}}catch(e){return e instanceof DOMException&&e.name===`AbortError`?{error:`Request timed out after 15s`}:e instanceof SyntaxError?{error:`Invalid JSON`}:{error:e.message}}}async function Gz(e){let t=new URL(`/llms.txt`,e).href,n=`llms.txt found and nonempty`;try{let e=await Iz(t,{});if(!e.ok)throw Error(`HTTP ${e.status}`);let r=(await e.text()).trim();if(!r)throw Error(`Empty document`);let i=e.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase();if(i&&!i.startsWith(`text/`)||i===`text/html`||/^<(?:!doctype html|html|head|body)\b/i.test(r))throw Error(`Expected text documentation, received non-text or HTML content`);return Q(n,t)}catch(e){return{label:n,detail:`${t}: ${e.message}`,severity:`suggested`,hint:`Serve nonempty text documentation at /llms.txt.`}}}function Kz(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=Yz(i.parameters);for(let[a,o]of Object.entries(i)){if(!Rz.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=Xz(r,Yz(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 qz(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=Qz(o,e,s),!o||o.type!==`object`)return;let c=$z(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function Jz(e,t,n){if(!t.path.startsWith(`/`)||t.path.startsWith(`//`)||t.path.includes(`\\`))throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let r=t.path;t.parameters&&(r=Zz(r,t.parameters));let i=r.startsWith(`/`)?r.slice(1):r,a=new URL(e.replace(/\/?$/,`/`)),o=new URL(i,a);if(o.origin!==a.origin)throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let s=o.href;if(n){let e=new URL(s);for(let t of n){let[n,...r]=t.split(`=`);n&&e.searchParams.set(n,r.join(`=`))}s=e.href}return s}function Yz(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 Xz(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 Zz(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 Qz(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 $z(e,t,n){let r=Qz(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]=$z(i,t,n))}return a}default:return null}}iC(),Gx(),pA(),fT();const eB=Object.values($e);function tB(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&eB.find(e=>e.id===t.chainId)?.testnet===!0}async function nB(e,t,n,r){let i=[],a;try{a=Jz(e,t,r?.query)}catch(e){return i.push($(`Request URL valid`,e.message)),{results:i}}let o=Uz(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 Iz(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?qz(r.discoveryDoc,t):void 0);if(e){n&&console.log(X.dim(` Retrying with body: ${e}`)),s=e,o[`content-type`]=`application/json`;try{c=await Iz(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(Fz(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(Fz(`Returns 402 without credentials`,`Got ${c.status} (endpoint requires auth before payment gate)`)):i.push($(`Returns 402 without credentials`,`Got ${c.status} instead`,c.status===400||c.status===422?`Server requires a valid request body before returning 402. Add a requestBody schema with examples to your OpenAPI doc, or use --body.`:`Endpoints that require payment must return HTTP 402 with a WWW-Authenticate: Payment header when no valid credential is provided.`)),{results:i};i.push(Q(`Returns 402 without credentials`));let l=c.headers.get(q.wwwAuthenticate),u=pB(c);if(!l)return u.length>0?(i.push(Fz(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(Fz(`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(`${Bx.payment} `))return i.push(Fz(`Not an MPP endpoint`,`WWW-Authenticate scheme is not Payment`)),{results:i};i.push(Q(`WWW-Authenticate header present`,`Payment scheme`));let d;try{d=IS(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(Pz(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0){let e=`No Payment challenges found in header`;try{FS(c)}catch(t){e=t.message}return i.push($(`Challenge parseable`,e)),{results:i}}let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push(Q(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=zS(l);p>0&&i.push($(`Challenge credential header`,`${p} of ${d.length+p} challenges select a credential header other than Payment-Authorization`,`A challenge may only set header="Payment-Authorization"; omit header to use Authorization.`));let m=new URL(e).hostname;rB(d,i),iB(d,i),aB(d,i),oB(d,m,i);let h=d.length>1;for(let e of d){let t=e.request;sB(e,t,i,h)}if(n)for(let e of d)console.log(X.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function rB(e,t){let n=e.filter(e=>!e.id);n.length===0?t.push(Q(`Challenge has id`)):t.push($(`Challenge has id`,`${n.length} missing`,`Every challenge must include a unique id field.`))}function iB(e,t){let n=e.filter(e=>!e.realm);n.length===0?t.push(Q(`Challenge has realm`)):t.push($(`Challenge has realm`,`${n.length} missing`,`Set realm to your server's hostname.`))}function aB(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(Pz(`Challenge has expiration`,`missing expires field`,`Add an expires field (ISO 8601) to prevent replay attacks.`));return}if(new Date(r.expires)<=n){t.push($(`Challenge expires in the future`,`Expired at ${r.expires}`,`The expires timestamp must be in the future.`));return}}let r=Math.min(...e.map(e=>new Date(e.expires).getTime()-n.getTime()));t.push(Q(`Challenge expires in the future`,`${Math.round(r/6e4)}m from now`))}function oB(e,t,n){let r=e=>e.toLowerCase().replace(/\.$/,``),i=r(t),a=[...new Set(e.map(e=>e.realm??``))].filter(e=>{let t=r(e);return!t||t!==i&&!i.endsWith(`.${t}`)});a.length>0?n.push($(`Realm matches server hostname`,`realm="${a[0]}" vs host="${t}"`,`Set the realm to your production hostname (or base domain) in the challenge.`)):n.push(Q(`Realm matches server hostname`))}function sB(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===Vx.tempo?cB(t,i,n,e):e.method===Vx.stripe?lB(t,i,n):e.method===Vx.evm&&uB(e,t,i,n)}function cB(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if(zz(e.recipient)?n.push(Q(`${t}Valid recipient address`)):e.recipient===void 0&&a?n.push(Q(`${t}Uses splits (no single recipient)`)):e.recipient===void 0?n.push($(`${t}Valid recipient address`,`Missing recipient (and no splits defined)`,`Set request.recipient to a valid 0x address, or use methodDetails.splits for multiple recipients.`)):n.push($(`${t}Valid recipient address`,`Got: ${String(e.recipient)}`,`Set request.recipient to a valid 0x-prefixed 40-hex-char address.`)),zz(e.currency)){let e=tB(r)?`testnet`:`mainnet`;n.push(Q(`${t}Valid currency address`,e))}else n.push($(`${t}Valid currency address`,`Got: ${String(e.currency)}`,`Set request.currency to a valid token address.`));dB(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function lB(e,t,n){dB(e,t,n,`currency's smallest unit (e.g. "100" = $1.00 for USD)`);let r=e.currency;typeof r==`string`&&/^[a-z]{3}$/i.test(r)?n.push(Q(`${t}Valid currency code`,r.toUpperCase())):n.push($(`${t}Valid currency code`,r?`Got: ${r}`:`missing`,`Must be a three-letter ISO currency code (e.g. "usd").`));let i=e.methodDetails,a=i?.networkId;a?n.push(Q(`${t}Has networkId`,a.slice(0,20))):n.push($(`${t}Has networkId`,`Missing methodDetails.networkId`,`Set methodDetails.networkId to your Stripe Business Network profile ID.`));let o=i?.paymentMethodTypes;Array.isArray(o)&&o.length>0?n.push(Q(`${t}Has paymentMethodTypes`,o.join(`, `))):n.push($(`${t}Has paymentMethodTypes`,`Missing or empty`,`Set methodDetails.paymentMethodTypes to an array (e.g. ["card"]).`))}function uB(e,t,n,r){if(zz(t.recipient)?r.push(Q(`${n}Valid recipient address`)):r.push($(`${n}Valid recipient address`,`Got: ${String(t.recipient)}`,`Set request.recipient to a valid 0x-prefixed Ethereum address.`)),zz(t.currency)){let t=tB(e)?`testnet`:`mainnet`;r.push(Q(`${n}Valid currency address`,t))}else r.push($(`${n}Valid currency address`,`Got: ${String(t.currency)}`,`Set request.currency to a valid ERC-20 token contract address.`));dB(t,n,r,`token's smallest unit`);let i=t.methodDetails?.chainId;typeof i==`number`&&i>0?r.push(Q(`${n}Has chainId`,String(i))):r.push($(`${n}Has chainId`,`Missing methodDetails.chainId`,`Set methodDetails.chainId to the EVM chain ID.`))}function dB(e,t,n,r){Bz(e.amount)?n.push(Q(`${t}Amount is valid integer string`)):e.amount===void 0||e.amount===null?n.push($(`${t}Amount is valid integer string`,`Missing amount`,`Set request.amount to a string of digits in the ${r}.`)):n.push($(`${t}Amount is valid integer string`,`Got: ${String(e.amount)}`,`request.amount must be a string of digits (no decimals, no prefix).`))}async function fB(e,t,n){let r=[],i=Jz(e,t,n?.query),a=Uz(n?.extraHeaders),o=n?.challenge?US(n.challenge):q.authorization;a[o.toLowerCase()]=`${Bx.payment} dGhpcyBpcyBnYXJiYWdl`;let s;n?.body&&(s=n.body,a[`content-type`]||=`application/json`);try{let e=await Iz(i,{method:t.method,headers:a,body:s??null});e.status===402?(r.push(Q(`Malformed credential returns 402`,`not 500`)),e.headers.get(q.wwwAuthenticate)?.startsWith(`${Bx.payment} `)?r.push(Q(`Error response includes fresh challenge`)):r.push(Pz(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the ${o} header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(Pz(`Malformed credential returns 402`,`Got ${e.status}`,`When the ${o} header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function pB(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=aT(n);t.push(Q(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(Pz(`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 mB=[`No discovery document found, endpoints could not be automatically found.`,`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,`The MPP SDKs can automatically expose this endpoint. See https://mpp.dev/sdk.`,``,`To test a specific endpoint: mppx validate <url> --endpoint POST:/your/path`].join(`
253
- `);async function*hB(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await bB(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=Hz(e.body,i.path),!a&&r.doc&&(a=qz(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await nB(t,i,n,{body:a,bodyIsAutogenerated:o,query:e.query,extraHeaders:e.headers,discoveryDoc:r.doc??void 0}),u=c??a,d=s.some(e=>e.severity===`pass`&&e.label===`Challenge parseable`),f=!s.some(e=>e.severity===`fail`),p=(l??[]).filter(e=>e.method!==`stripe`).map(e=>e.request.methodDetails?.chainId).filter(e=>typeof e==`number`),m=p.some(yB),h=p.some(e=>!yB(e)),g=!d&&s.some(e=>e.label===`Not an MPP endpoint`),_=s.some(e=>e.severity===`pass`&&e.label===`WWW-Authenticate header present`),v=s.some(e=>e.severity===`fail`&&e.label===`Challenge parseable`);if(yield{phase:`challenge`,endpoint:i,results:s,isMpp:d,isTestnet:m,isMainnet:h,isNonMppPayment:g,isMalformedChallenge:!d&&_&&v,methods:l?.map(e=>e.method)??[]},d&&(yield{phase:`errorHandling`,endpoint:i,results:await fB(t,i,{body:u,challenge:l?.[0],extraHeaders:e.headers,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults;if(!e.payment){let e=[Fz(`Payment: not tested`,`no payment validator configured`,"Run `mppx validate` to test payment, or pass `payment` to validate().")];r?.(e),yield{phase:`payment`,endpoint:i,results:e,succeeded:!1};continue}let a=await e.payment(t,i,n,{body:u,query:e.query,extraHeaders:e.headers,yes:e.yes,silent:!r,interactive:e.interactive,...r&&{onResults:r}}),o=Array.isArray(a)?a:a.results,s=Array.isArray(a)?a.some(e=>e.severity===`pass`&&e.label===`Payment: successful`):a.succeeded;if(!Array.isArray(a)&&!s&&!o.some(e=>e.severity===`fail`)){let e=$(`Payment: failed`,`the payment validator reported that the payment did not succeed`);o=[...o,e],r?.([{...e}])}yield{phase:`payment`,endpoint:i,results:o,succeeded:s}}}}async function gB(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of hB(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,e.payment&&(i.paymentSucceeded=t.succeeded))}let s={passed:0,failed:0,warnings:0,suggested:0,skipped:0};if(n)for(let e of n.checks)e.severity===`pass`?s.passed++:e.severity===`fail`?s.failed++:e.severity===`warn`?s.warnings++:e.severity===`suggested`?s.suggested++:e.severity===`skip`&&s.skipped++;for(let e of r)for(let t of[...e.challenge,...e.errorHandling,...e.payment])t.severity===`pass`?s.passed++:t.severity===`fail`?s.failed++:t.severity===`warn`?s.warnings++:t.severity===`suggested`?s.suggested++:t.severity===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=_B(r,n,{sawTestnet:a,sawMainnet:o,hasPaymentValidator:!!e.payment});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function _B(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(mB);let a=n.sawMainnet,o=n.sawTestnet,s=i.some(e=>e.label.includes(`[stripe]`)&&e.label.includes(`livemode`));return a&&!o?r.push(n.hasPaymentValidator?`Validate your testnet server to test without real funds (Tempo wallets are automatically provisioned).`:"Validate your testnet server to test without real funds. Run `mppx validate` to test payment with an automatically provisioned Tempo wallet."):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 vB=Object.values($e);function yB(e){return vB.find(t=>t.id===e)?.testnet===!0}async function bB(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await Gz(e));let s=new URL(e).origin,c;t.discoveryPath?c=[new URL(t.discoveryPath,e+`/`).href.replace(/\/openapi\.json$/i,``)]:(c=[e,s,`${s}/api`],c=[...new Set(c)]);let l,u=[];for(let e of c)if(l=await Wz(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=DD(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=Vz(t.endpoint);e&&r.push(e)}else if(i){r=Kz(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=Bz(t.amount)?BigInt(t.amount):e,i=Bz(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}}yS();const xB={extensions:Y.optional(Y.record(Y.string(),Y.unknown())),fundingCurrency:Y.optional(Y.string()),method:Y.string(),reference:Y.string(),externalId:Y.optional(Y.string()),subscriptionId:Y.optional(Y.string()),status:Y.literal(`success`),timestamp:uS()};Y.object(xB);const SB=Y.looseObject(xB);function CB(e){let t=k.toString(e);return wB(JSON.parse(t))}function wB(e){return SB.parse(e)}iC(),WT(),Gx(),lL(),bA(),fA(),RO(),lj(),YA();async function TB(e,t,n){try{n||console.log(X.dim(` Provisioning testnet wallet and funding via faucet...`));let t=_e(),r=L(t),i=M({chain:be,transport:I()});if(Ok(e)){let{chainId:t,operator:n}=e.request.methodDetails??{};if(t===be.id&&typeof n==`string`&&ue(n)&&n!==ge){let e=await Re.faucet.fund(i,{account:n});await Promise.all(e.map(e=>Fe(i,{hash:e})))}}let a=await Re.faucet.fund(i,{account:r});await Promise.all(a.map(e=>Fe(i,{hash:e}))),n||console.log(X.dim(` Using wallet: ${r.address}`));let o=e.request.currency;if(typeof o==`string`)for(let e=0;e<10;e++){let e=await Re.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:[...oL({account:r})]}}catch(e){t&&console.log(X.dim(` Provisioning failed: ${e.message}`));return}}async function EB(){let e=nj(),{isTempoAccount:t}=await Promise.resolve().then(()=>(YA(),xA)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(UL(),uL));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await oj()).address}catch{return}}function DB(e){try{let{execSync:t}=m,n=t(`stripe config --list`,{encoding:`utf8`,timeout:5e3}).match(/test_mode_api_key\s*=\s*'([^']+)'/);if(n?.[1])return e&&console.log(X.dim(` Using Stripe test key from stripe CLI`)),n[1]}catch{}}async function OB(e,t,n){let r=M({chain:e,transport:I()}),[i,a,o]=await Promise.all([n?ke(r,{address:t,abi:P,functionName:`balanceOf`,args:[n]}):0n,ke(r,{address:t,abi:P,functionName:`decimals`}),ke(r,{address:t,abi:P,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,decimals:a,symbol:o??void 0}}function kB(e){return Object.values($e).find(t=>t.id===e)}function AB(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function jB(e){switch(e.method){case Vx.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 MB(e,t,n,r){let i=[],a=Jz(e,t,r.query),o=Uz(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await Iz(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(Fz(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=IS(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=[];oB(l,new URL(a).hostname,u);let d=u.filter(e=>e.severity===`fail`);if(d.length>0)return i.push(...d),r.onResults?.(d),i;let f=await tR().catch(()=>void 0),p=l.find(e=>{if(e.method!==Vx.tempo||$L(f?.config)?.some(t=>t.name===e.method&&t.intent===e.intent))return!1;let t=e.request.methodDetails;return typeof t?.chainId==`number`&&t.chainId!==mA.mainnet});if(p){let e=await TB(p,n,r.silent);if(e)try{let r=zB((e,t)=>Iz(e,t??{},3e4));await LB(i,await JE({methods:e.methods,polyfill:!1,async onChallenge(e,{createCredential:t}){rR(p,e);let n=await t(await YL(e,f?.config.extensions));return i.push(Q(`Payment: submitted`,`ephemeral testnet wallet`)),n},fetch:r.fetch}).fetch(a,{method:t.method,headers:o,body:s??null}),n,be,Ok(p),r.receipt)}catch(e){i.push($(`Payment: create credential`,e.message))}else i.push($(`Payment: auto-provision wallet`,`Failed to create and fund testnet wallet`));r.onResults?.(i)}let m=r.interactive,h=process.env.MPPX_STRIPE_SECRET_KEY??DB(n),g=h?.startsWith(`sk_test_`)||h?.startsWith(`rk_test_`),_=new Set([Vx.tempo,Vx.evm,Vx.stripe]);for(let e of l){if(e===p||!_.has(e.method))continue;r.silent||console.log(``);let c=i.length,l=()=>{r.onResults&&i.length>c&&r.onResults(i.slice(c))},u=`Payment [${e.method}]`;try{switch(e.method){case Vx.tempo:case Vx.evm:await NB(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,options:r});break;case Vx.stripe:await PB(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,isStripeTestKey:g??!1,stripeKey:h,options:r})}}finally{l()}}return i}async function NB(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=Bz(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,{plugin:g,method:_}=XL(e,l?.config);if(!g&&!_){r.push(Fz(t,jB(e)));return}let v;if(!_){try{v=await EB()}catch{}if(!v){r.push(Fz(t,`no wallet configured. Run "mppx account create" to create one.`));return}}let y;if(e.method===Vx.tempo){let e=f?.chainId??(_?void 0:ye.id);e!==void 0&&(y=e===be.id?be:kB(e))}else if(e.method===Vx.evm){let e=f?.chainId;e&&(y=kB(e))}if(p&&h&&!y){r.push(Fz(t,`unable to resolve payment chain and verify token decimals`));return}let b;if(p&&h&&y)try{let n;if(e.method===Vx.tempo){let e=await VA(M({chain:y,transport:I()}),h,v??ge,{requireDecimals:!0});n=e.balance,m=e.decimals,b=e.symbol}else{let e=await OB(y,h,v);n=e.balance,m=e.decimals,b=e.symbol}if(v&&n<p){let e=AB(p,m),i=AB(n,m),a=b??`tokens`;r.push(Fz(t,`insufficient balance (have ${i}, need ${e} ${a} on ${y.name})`,`Fund wallet ${v} with at least ${e} ${a} on ${y.name}.`));return}}catch(e){c&&console.log(X.dim(` Balance check skipped: ${e.message}`)),r.push(Fz(t,`unable to verify token balance and decimals from the payment chain`));return}let x=p?AB(p,m):`unknown amount`,S=b??(h?.length===3?h.toUpperCase():``),C=y?.name,w=`${x}${S?` ${S}`:``}${C?` on ${C}`:``}`;if(u.silent||console.log(X.dim(v?` Attempting payment with wallet ${v}`:` Attempting payment with configured method`)),!_&&y?.testnet)u.silent||console.log(X.dim(` Auto-approved: ${w} (testnet)`));else if(!u.yes&&!n.isInteractive){r.push(Fz(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${w}`));else if(!await NA(` ${X.yellow(`Pay`)} ${w}. Continue?`,!1)){r.push(Fz(t,`declined`));return}let T,ee,te;if(g)try{let t=await g.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});T=t.methods,ee=t.createCredential,te=t.credentialContext}catch(e){r.push(Fz(t,e.message));return}else T=[_];if(_&&Ok(e)){let n=!0,u=zB((e,t)=>Iz(e,t??{},3e4)),d=JE({methods:[_],polyfill:!1,async onChallenge(n,{createCredential:i}){let a=await YL(n,l?.config.extensions);rR(e,n);let o=await i(a);return r.push(Q(`${t}: submitted`)),o},fetch:async(t,r)=>n?(n=!1,new Response(null,{status:402,headers:{[q.wwwAuthenticate]:xS(e)}})):u.fetch(t,r)});try{await LB(r,await d.fetch(i,{method:a.method,headers:o,body:s??null}),c,y,!0,u.receipt)}catch(e){r.push($(t,e.message))}return}let E=await FB(e,T,ee,t,r,l?.config.extensions,te,i);E&&(g?.prepareCredentialRequest?.({challenge:e,credential:E,headers:o}),await IB(r,i,a,E,o,s,c,y,US(e),Ok(e)))}async function PB(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u,stripeKey:d}=n,{plugin:f,method:p}=XL(e,l?.config);if(!f&&!p){r.push(Fz(t,`no Stripe payment method available`));return}let m=!!(f&&!l?.config.plugins?.includes(f)&&n.isStripeTestKey),h=e.request,g=Bz(h.amount)?BigInt(h.amount):void 0,_=h.decimals??2,v=h.currency,y=g?AB(g,_):`unknown amount`,b=v?.length===3?v.toUpperCase():``,x=`${y}${b?` ${b}`:``} via Stripe${m?` (testmode)`:``}`;if(m)u.silent||console.log(X.dim(` Attempting: ${x}`));else if(!u.yes&&!n.isInteractive){r.push(Fz(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${x}`));else if(!await NA(` ${X.yellow(`Pay`)} ${x}. Continue?`,!1)){r.push(Fz(t,`declined`));return}let S,C,w;if(f)try{let t={paymentMethod:`pm_card_visa`};d&&(t.secretKey=d);let n=await f.setup({challenge:e,options:{},methodOpts:t});S=n.methods,C=n.createCredential,w=n.credentialContext}catch(e){r.push(Fz(t,e.message));return}else S=[p];let T=await FB(e,S,C,t,r,l?.config.extensions,w,i);if(T){if(f?.prepareCredentialRequest?.({challenge:e,credential:T,headers:o}),m){let n=await Iz(i,{method:a.method,headers:{...o,[US(e)]:T},body:s??null},3e4);n.status>=200&&n.status<300?r.push(Q(`${t}: successful`,`HTTP ${n.status}`)):r.push(Fz(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await IB(r,i,a,T,o,s,c,void 0,US(e))}}async function FB(e,t,n,r,i,a,o,s){let c=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:xS(e)}});try{BT(e,new URL(s),void 0);let l=await YL(e,a,o),u;return u=n?await n(c,l):await JE({methods:t,polyfill:!1}).createCredential(c,l),i.push(Q(`${r}: submitted`)),u}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(Fz(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function IB(e,t,n,r,i,a,o,s,c=q.authorization,l=!1){let u;try{u=await Iz(t,{method:n.method,headers:{...i,[c]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}return LB(e,u,o,s,l)}async function LB(e,t,n,r,i=!1,a){if(t.status===402){let n=await t.text().catch(()=>``),r=`Payment rejected`;try{let e=JSON.parse(n);r=e.detail??e.title??r}catch{}return e.push($(`Payment: accepted`,r,`The server rejected a valid credential. Check that your payment verification logic accepts the credential format and that the payment was processed on-chain.`)),e}if(t.status>=400&&t.status<500)e.push(Pz(`Payment: post-payment response`,`Got ${t.status}`,`Payment succeeded but the endpoint returned a client error. The endpoint likely requires request body parameters. Use --body to provide them.`));else if(t.status>=500)return e.push($(`Payment: server response`,`Got ${t.status}`,`Payment was accepted but the server errored while generating the response. Check server logs for the underlying error.`)),e;else e.push(Q(`Payment: successful`,`HTTP ${t.status}`));let o=t.headers.get(`content-type`)??``,s=t.headers.get(q.paymentReceipt),c=!s&&i&&OO(t),l=await t.text().catch(()=>``);if(c){let t=a?.(),n=t===void 0?RB(l):t??void 0;n?e.push(Q(`Payment receipt in event stream`,n.reference)):e.push($(`Payment receipt in event stream`,void 0,`SSE session responses without a Payment-Receipt header must end with an "event: payment-receipt" carrying the session receipt.`))}else if(!s)e.push($(`Payment-Receipt header present`,void 0,`After accepting payment, include a Payment-Receipt header with a base64url-encoded JSON object containing: method, reference, status ("success"), and timestamp (ISO 8601).`));else{e.push(Q(`Payment-Receipt header present`));try{let t=CB(s);if(e.push(Q(`Receipt parseable`)),t.status===`success`?e.push(Q(`Receipt status is "success"`)):e.push($(`Receipt status is "success"`,`Got: ${t.status}`)),t.reference){let n=/^0x[0-9a-fA-F]{64}$/.test(t.reference),r=t.reference.startsWith(`pi_`);n||r?e.push(Q(`Receipt reference valid`,t.reference.slice(0,20)+`...`)):e.push(Pz(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(Pz(`Receipt has reference`,`No reference field`));if(t.timestamp){let n=new Date(t.timestamp),r=Date.now()-n.getTime();r<6e4?e.push(Q(`Receipt timestamp recent`,`${Math.round(r/1e3)}s ago`)):e.push(Pz(`Receipt timestamp recent`,`${Math.round(r/6e4)}m ago`))}n&&console.log(X.dim(` Receipt: ${JSON.stringify(t,null,2)}`))}catch(t){e.push($(`Receipt parseable`,t.message))}}if(l.length>0)e.push(Q(`Response body non-empty`,`${o.split(`;`)[0]}, ${Lz(l.length)}`));else{let n=[...t.headers.entries()].filter(([e])=>!e.startsWith(`x-`)&&![`content-type`,`content-length`,`date`,`server`,`connection`,`keep-alive`,`cache-control`,`vary`,`access-control-allow-origin`,`payment-receipt`,`payment-session`,`payment-session-snapshot`].includes(e.toLowerCase()));n.length>0?e.push(Pz(`Response body empty -- data may be in headers only`,n.map(([e])=>e).join(`, `))):e.push(Pz(`Response body empty`))}if(o?e.push(Q(`Content-Type header set`,o.split(`;`)[0])):e.push(Pz(`Content-Type header set`)),s)try{let t=CB(s);if(t.reference&&/^0x[0-9a-fA-F]{64}$/.test(t.reference)){let n=r?.blockExplorers?.default?.url;if(n){let r=n.includes(`tempo`)?`receipt`:`tx`;e.push(Q(`On-chain transaction`,`${n}/${r}/${t.reference}`))}}}catch{}return e}function RB(e){for(let t of e.replace(/\r\n|\r/g,`
252
+ `):`${a}${l}${i}\n`,d=y.parseEnv;if(d){let t=d(a),i=d(u),o=new Set([...Object.keys(t),...Object.keys(i)]);if(o.delete(n),i[n]!==r||[...o].some(e=>t[e]!==i[e]))throw Error(`could not update ${n} in ${e} safely: edit it by hand`)}t.writeFileSync(e,u)}function vV(e,t,n){let r={};for(let t of[`"`,`'`,"`"]){let n=Array(e.length+1);n[e.length]=-1;for(let r=e.length-1;r>=0;r--)n[r]=yV(e[r],t)?r:n[r+1];r[t]=n}let i=[],a=!1;for(let o=0;o<e.length;o++){let s=o,c=/^[ \t]*[^#=\s][^=]*=[ \t]*(["'`])(.*)$/s.exec(e[o]);if(c&&!yV(c[2],c[1])){let e=r[c[1]][o+1];e!==-1&&(s=e)}let l=t.test(e[o]);if(l&&!a&&i.push(e[o].endsWith(`\r`)?`${n}\r`:n),a||=l,!l)for(let t=o;t<=s;t++)i.push(e[t]);o=s}return{lines:i,found:a}}function yV(e,t){return e.includes(t)}function bV(e){let t=e.findIndex((t,n)=>t===`stripe`&&e[n+1]===`address`);if(t===-1)return[...e];let n=e.slice(0,t+2);for(let r=t+2;r<e.length;r++){let t=e[r];if(n.push(t),t===`--`){n.push(...e.slice(r+1));break}let i=e[r+1];t===`--env`&&(i===void 0||i.startsWith(`-`))&&n.push(`.env`)}return n}DO();function Q(e,t){return t?{label:e,detail:t,severity:`pass`}:{label:e,severity:`pass`}}function $(e,t,n){let r={label:e,severity:`fail`};return t&&(r.detail=t),n&&(r.hint=n),r}function xV(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function SV(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}async function CV(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{let n=globalThis.fetch,i=QD(n),a=XD(n),o={[bO]:!0,...t,redirect:`error`,signal:r.signal};return a?(await a.send((e,t)=>i(e,{...t,[bO]:!0}),new Request(e,o))).response:await i(e,o)}finally{clearTimeout(i)}}function wV(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const TV=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function EV(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function DV(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function OV(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!TV.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 kV(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 AV(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 jV(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await CV(t,{});if(!e.ok)return{error:`HTTP ${e.status}`};let n=await e.text();return{doc:JSON.parse(n),raw:n}}catch(e){return e instanceof DOMException&&e.name===`AbortError`?{error:`Request timed out after 15s`}:e instanceof SyntaxError?{error:`Invalid JSON`}:{error:e.message}}}async function MV(e){let t=new URL(`/llms.txt`,e).href,n=`llms.txt found and nonempty`;try{let e=await CV(t,{});if(!e.ok)throw Error(`HTTP ${e.status}`);let r=(await e.text()).trim();if(!r)throw Error(`Empty document`);let i=e.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase();if(i&&!i.startsWith(`text/`)||i===`text/html`||/^<(?:!doctype html|html|head|body)\b/i.test(r))throw Error(`Expected text documentation, received non-text or HTML content`);return Q(n,t)}catch(e){return{label:n,detail:`${t}: ${e.message}`,severity:`suggested`,hint:`Serve nonempty text documentation at /llms.txt.`}}}function NV(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=IV(i.parameters);for(let[a,o]of Object.entries(i)){if(!TV.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=LV(r,IV(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 PV(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=zV(o,e,s),!o||o.type!==`object`)return;let c=BV(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function FV(e,t,n){if(!t.path.startsWith(`/`)||t.path.startsWith(`//`)||t.path.includes(`\\`))throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let r=t.path;t.parameters&&(r=RV(r,t.parameters));let i=r.startsWith(`/`)?r.slice(1):r,a=new URL(e.replace(/\/?$/,`/`)),o=new URL(i,a);if(o.origin!==a.origin)throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let s=o.href;if(n){let e=new URL(s);for(let t of n){let[n,...r]=t.split(`=`);n&&e.searchParams.set(n,r.join(`=`))}s=e.href}return s}function IV(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 LV(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 RV(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 zV(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 BV(e,t,n){let r=zV(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]=BV(i,t,n))}return a}default:return null}}sC(),Gx(),Qj(),HT();const VV=Object.values(Qe);function HV(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&VV.find(e=>e.id===t.chainId)?.testnet===!0}async function UV(e,t,n,r){let i=[],a;try{a=FV(e,t,r?.query)}catch(e){return i.push($(`Request URL valid`,e.message)),{results:i}}let o=AV(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 CV(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?PV(r.discoveryDoc,t):void 0);if(e){n&&console.log(X.dim(` Retrying with body: ${e}`)),s=e,o[`content-type`]=`application/json`;try{c=await CV(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(SV(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(SV(`Returns 402 without credentials`,`Got ${c.status} (endpoint requires auth before payment gate)`)):i.push($(`Returns 402 without credentials`,`Got ${c.status} instead`,c.status===400||c.status===422?`Server requires a valid request body before returning 402. Add a requestBody schema with examples to your OpenAPI doc, or use --body.`:`Endpoints that require payment must return HTTP 402 with a WWW-Authenticate: Payment header when no valid credential is provided.`)),{results:i};i.push(Q(`Returns 402 without credentials`));let l=c.headers.get(q.wwwAuthenticate),u=eH(c);if(!l)return u.length>0?(i.push(SV(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(SV(`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(`${Bx.payment} `))return i.push(SV(`Not an MPP endpoint`,`WWW-Authenticate scheme is not Payment`)),{results:i};i.push(Q(`WWW-Authenticate header present`,`Payment scheme`));let d;try{d=RS(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(xV(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0){let e=`No Payment challenges found in header`;try{LS(c)}catch(t){e=t.message}return i.push($(`Challenge parseable`,e)),{results:i}}let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push(Q(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=VS(l);p>0&&i.push($(`Challenge credential header`,`${p} of ${d.length+p} challenges select a credential header other than Payment-Authorization`,`A challenge may only set header="Payment-Authorization"; omit header to use Authorization.`));let m=new URL(e).hostname;WV(d,i),GV(d,i),KV(d,i),qV(d,m,i);let h=d.length>1;for(let e of d){let t=e.request;JV(e,t,i,h)}if(n)for(let e of d)console.log(X.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function WV(e,t){let n=e.filter(e=>!e.id);n.length===0?t.push(Q(`Challenge has id`)):t.push($(`Challenge has id`,`${n.length} missing`,`Every challenge must include a unique id field.`))}function GV(e,t){let n=e.filter(e=>!e.realm);n.length===0?t.push(Q(`Challenge has realm`)):t.push($(`Challenge has realm`,`${n.length} missing`,`Set realm to your server's hostname.`))}function KV(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(xV(`Challenge has expiration`,`missing expires field`,`Add an expires field (ISO 8601) to prevent replay attacks.`));return}if(new Date(r.expires)<=n){t.push($(`Challenge expires in the future`,`Expired at ${r.expires}`,`The expires timestamp must be in the future.`));return}}let r=Math.min(...e.map(e=>new Date(e.expires).getTime()-n.getTime()));t.push(Q(`Challenge expires in the future`,`${Math.round(r/6e4)}m from now`))}function qV(e,t,n){let r=e=>e.toLowerCase().replace(/\.$/,``),i=r(t),a=[...new Set(e.map(e=>e.realm??``))].filter(e=>{let t=r(e);return!t||t!==i&&!i.endsWith(`.${t}`)});a.length>0?n.push($(`Realm matches server hostname`,`realm="${a[0]}" vs host="${t}"`,`Set the realm to your production hostname (or base domain) in the challenge.`)):n.push(Q(`Realm matches server hostname`))}function JV(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===Vx.tempo?YV(t,i,n,e):e.method===Vx.stripe?XV(t,i,n):e.method===Vx.evm&&ZV(e,t,i,n)}function YV(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if(EV(e.recipient)?n.push(Q(`${t}Valid recipient address`)):e.recipient===void 0&&a?n.push(Q(`${t}Uses splits (no single recipient)`)):e.recipient===void 0?n.push($(`${t}Valid recipient address`,`Missing recipient (and no splits defined)`,`Set request.recipient to a valid 0x address, or use methodDetails.splits for multiple recipients.`)):n.push($(`${t}Valid recipient address`,`Got: ${String(e.recipient)}`,`Set request.recipient to a valid 0x-prefixed 40-hex-char address.`)),EV(e.currency)){let e=HV(r)?`testnet`:`mainnet`;n.push(Q(`${t}Valid currency address`,e))}else n.push($(`${t}Valid currency address`,`Got: ${String(e.currency)}`,`Set request.currency to a valid token address.`));QV(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function XV(e,t,n){QV(e,t,n,`currency's smallest unit (e.g. "100" = $1.00 for USD)`);let r=e.currency;typeof r==`string`&&/^[a-z]{3}$/i.test(r)?n.push(Q(`${t}Valid currency code`,r.toUpperCase())):n.push($(`${t}Valid currency code`,r?`Got: ${r}`:`missing`,`Must be a three-letter ISO currency code (e.g. "usd").`));let i=e.methodDetails,a=i?.networkId;a?n.push(Q(`${t}Has networkId`,a.slice(0,20))):n.push($(`${t}Has networkId`,`Missing methodDetails.networkId`,`Set methodDetails.networkId to your Stripe Business Network profile ID.`));let o=i?.paymentMethodTypes;Array.isArray(o)&&o.length>0?n.push(Q(`${t}Has paymentMethodTypes`,o.join(`, `))):n.push($(`${t}Has paymentMethodTypes`,`Missing or empty`,`Set methodDetails.paymentMethodTypes to an array (e.g. ["card"]).`))}function ZV(e,t,n,r){if(EV(t.recipient)?r.push(Q(`${n}Valid recipient address`)):r.push($(`${n}Valid recipient address`,`Got: ${String(t.recipient)}`,`Set request.recipient to a valid 0x-prefixed Ethereum address.`)),EV(t.currency)){let t=HV(e)?`testnet`:`mainnet`;r.push(Q(`${n}Valid currency address`,t))}else r.push($(`${n}Valid currency address`,`Got: ${String(t.currency)}`,`Set request.currency to a valid ERC-20 token contract address.`));QV(t,n,r,`token's smallest unit`);let i=t.methodDetails?.chainId;typeof i==`number`&&i>0?r.push(Q(`${n}Has chainId`,String(i))):r.push($(`${n}Has chainId`,`Missing methodDetails.chainId`,`Set methodDetails.chainId to the EVM chain ID.`))}function QV(e,t,n,r){DV(e.amount)?n.push(Q(`${t}Amount is valid integer string`)):e.amount===void 0||e.amount===null?n.push($(`${t}Amount is valid integer string`,`Missing amount`,`Set request.amount to a string of digits in the ${r}.`)):n.push($(`${t}Amount is valid integer string`,`Got: ${String(e.amount)}`,`request.amount must be a string of digits (no decimals, no prefix).`))}async function $V(e,t,n){let r=[],i=FV(e,t,n?.query),a=AV(n?.extraHeaders),o=n?.challenge?GS(n.challenge):q.authorization;a[o.toLowerCase()]=`${Bx.payment} dGhpcyBpcyBnYXJiYWdl`;let s;n?.body&&(s=n.body,a[`content-type`]||=`application/json`);try{let e=await CV(i,{method:t.method,headers:a,body:s??null});e.status===402?(r.push(Q(`Malformed credential returns 402`,`not 500`)),e.headers.get(q.wwwAuthenticate)?.startsWith(`${Bx.payment} `)?r.push(Q(`Error response includes fresh challenge`)):r.push(xV(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the ${o} header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(xV(`Malformed credential returns 402`,`Got ${e.status}`,`When the ${o} header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function eH(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=PT(n);t.push(Q(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(xV(`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 tH=[`No discovery document found, endpoints could not be automatically found.`,`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,`The MPP SDKs can automatically expose this endpoint. See https://mpp.dev/sdk.`,``,`To test a specific endpoint: mppx validate <url> --endpoint POST:/your/path`].join(`
253
+ `);async function*nH(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await sH(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=kV(e.body,i.path),!a&&r.doc&&(a=PV(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await UV(t,i,n,{body:a,bodyIsAutogenerated:o,query:e.query,extraHeaders:e.headers,discoveryDoc:r.doc??void 0}),u=c??a,d=s.some(e=>e.severity===`pass`&&e.label===`Challenge parseable`),f=!s.some(e=>e.severity===`fail`),p=(l??[]).filter(e=>e.method!==`stripe`).map(e=>e.request.methodDetails?.chainId).filter(e=>typeof e==`number`),m=p.some(oH),h=p.some(e=>!oH(e)),g=!d&&s.some(e=>e.label===`Not an MPP endpoint`),_=s.some(e=>e.severity===`pass`&&e.label===`WWW-Authenticate header present`),v=s.some(e=>e.severity===`fail`&&e.label===`Challenge parseable`);if(yield{phase:`challenge`,endpoint:i,results:s,isMpp:d,isTestnet:m,isMainnet:h,isNonMppPayment:g,isMalformedChallenge:!d&&_&&v,methods:l?.map(e=>e.method)??[]},d&&(yield{phase:`errorHandling`,endpoint:i,results:await $V(t,i,{body:u,challenge:l?.[0],extraHeaders:e.headers,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults;if(!e.payment){let e=[SV(`Payment: not tested`,`no payment validator configured`,"Run `mppx validate` to test payment, or pass `payment` to validate().")];r?.(e),yield{phase:`payment`,endpoint:i,results:e,succeeded:!1};continue}let a=await e.payment(t,i,n,{body:u,query:e.query,extraHeaders:e.headers,yes:e.yes,silent:!r,interactive:e.interactive,...r&&{onResults:r}}),o=Array.isArray(a)?a:a.results,s=Array.isArray(a)?a.some(e=>e.severity===`pass`&&e.label===`Payment: successful`):a.succeeded;if(!Array.isArray(a)&&!s&&!o.some(e=>e.severity===`fail`)){let e=$(`Payment: failed`,`the payment validator reported that the payment did not succeed`);o=[...o,e],r?.([{...e}])}yield{phase:`payment`,endpoint:i,results:o,succeeded:s}}}}async function rH(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of nH(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,e.payment&&(i.paymentSucceeded=t.succeeded))}let s={passed:0,failed:0,warnings:0,suggested:0,skipped:0};if(n)for(let e of n.checks)e.severity===`pass`?s.passed++:e.severity===`fail`?s.failed++:e.severity===`warn`?s.warnings++:e.severity===`suggested`?s.suggested++:e.severity===`skip`&&s.skipped++;for(let e of r)for(let t of[...e.challenge,...e.errorHandling,...e.payment])t.severity===`pass`?s.passed++:t.severity===`fail`?s.failed++:t.severity===`warn`?s.warnings++:t.severity===`suggested`?s.suggested++:t.severity===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=iH(r,n,{sawTestnet:a,sawMainnet:o,hasPaymentValidator:!!e.payment});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function iH(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(tH);let a=n.sawMainnet,o=n.sawTestnet,s=i.some(e=>e.label.includes(`[stripe]`)&&e.label.includes(`livemode`));return a&&!o?r.push(n.hasPaymentValidator?`Validate your testnet server to test without real funds (Tempo wallets are automatically provisioned).`:"Validate your testnet server to test without real funds. Run `mppx validate` to test payment with an automatically provisioned Tempo wallet."):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 aH=Object.values(Qe);function oH(e){return aH.find(t=>t.id===e)?.testnet===!0}async function sH(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await MV(e));let s=new URL(e).origin,c;t.discoveryPath?c=[new URL(t.discoveryPath,e+`/`).href.replace(/\/openapi\.json$/i,``)]:(c=[e,s,`${s}/api`],c=[...new Set(c)]);let l,u=[];for(let e of c)if(l=await jV(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=dk(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=OV(t.endpoint);e&&r.push(e)}else if(i){r=NV(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=DV(t.amount)?BigInt(t.amount):e,i=DV(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}}sC(),bE(),Gx(),Jw(),XR(),aM(),Zj(),CA(),JM(),PM();async function cH(e,t,n){try{n||console.log(X.dim(` Provisioning testnet wallet and funding via faucet...`));let t=ge(),r=R(t),i=N({chain:ye,transport:L()});if(pj(e)){let{chainId:t,operator:n}=e.request.methodDetails??{};if(t===ye.id&&typeof n==`string`&&le(n)&&n!==he){let e=await Be.faucet.fund(i,{account:n});await Promise.all(e.map(e=>Le(i,{hash:e})))}}let a=await Be.faucet.fund(i,{account:r});await Promise.all(a.map(e=>Le(i,{hash:e}))),n||console.log(X.dim(` Using wallet: ${r.address}`));let o=e.request.currency;if(typeof o==`string`)for(let e=0;e<10;e++){let e=await Be.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:[...qR({account:r})]}}catch(e){t&&console.log(X.dim(` Provisioning failed: ${e.message}`));return}}async function lH(){let e=VM(),{isTempoAccount:t}=await Promise.resolve().then(()=>(PM(),oM)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(Az(),ZR));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await GM()).address}catch{return}}function uH(e){try{let{execSync:t}=m,n=t(`stripe config --list`,{encoding:`utf8`,timeout:5e3}).match(/test_mode_api_key\s*=\s*'([^']+)'/);if(n?.[1])return e&&console.log(X.dim(` Using Stripe test key from stripe CLI`)),n[1]}catch{}}async function dH(e,t,n){let r=N({chain:e,transport:L()}),[i,a,o]=await Promise.all([n?je(r,{address:t,abi:F,functionName:`balanceOf`,args:[n]}):0n,je(r,{address:t,abi:F,functionName:`decimals`}),je(r,{address:t,abi:F,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,decimals:a,symbol:o??void 0}}function fH(e){return Object.values(Qe).find(t=>t.id===e)}function pH(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function mH(e){switch(e.method){case Vx.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 hH(e,t,n,r){let i=[],a=FV(e,t,r.query),o=AV(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await CV(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(SV(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=RS(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=[];qV(l,new URL(a).hostname,u);let d=u.filter(e=>e.severity===`fail`);if(d.length>0)return i.push(...d),r.onResults?.(d),i;let f=await Hz().catch(()=>void 0),p=l.find(e=>{if(e.method!==Vx.tempo||Bz(f?.config)?.some(t=>t.name===e.method&&t.intent===e.intent))return!1;let t=e.request.methodDetails;return typeof t?.chainId==`number`&&t.chainId!==$j.mainnet});if(p){let e=await cH(p,n,r.silent);if(e)try{let r=SH((e,t)=>CV(e,t??{},3e4));await bH(i,await jO({methods:e.methods,polyfill:!1,async onChallenge(e,{createCredential:t}){Wz(p,e);let n=await t(await Iz(e,f?.config.extensions));return i.push(Q(`Payment: submitted`,`ephemeral testnet wallet`)),n},fetch:r.fetch}).fetch(a,{method:t.method,headers:o,body:s??null}),n,ye,pj(p),r.receipt)}catch(e){i.push($(`Payment: create credential`,e.message))}else i.push($(`Payment: auto-provision wallet`,`Failed to create and fund testnet wallet`));r.onResults?.(i)}let m=r.interactive,h=process.env.MPPX_STRIPE_SECRET_KEY??uH(n),g=h?.startsWith(`sk_test_`)||h?.startsWith(`rk_test_`),_=new Set([Vx.tempo,Vx.evm,Vx.stripe]);for(let e of l){if(e===p||!_.has(e.method))continue;r.silent||console.log(``);let c=i.length,l=()=>{r.onResults&&i.length>c&&r.onResults(i.slice(c))},u=`Payment [${e.method}]`;try{switch(e.method){case Vx.tempo:case Vx.evm:await gH(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,options:r});break;case Vx.stripe:await _H(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,isStripeTestKey:g??!1,stripeKey:h,options:r})}}finally{l()}}return i}async function gH(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=DV(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,{plugin:g,method:_}=Lz(e,l?.config);if(!g&&!_){r.push(SV(t,mH(e)));return}let v;if(!_){try{v=await lH()}catch{}if(!v){r.push(SV(t,`no wallet configured. Run "mppx account create" to create one.`));return}}let y;if(e.method===Vx.tempo){let e=f?.chainId??(_?void 0:ve.id);e!==void 0&&(y=e===ye.id?ye:fH(e))}else if(e.method===Vx.evm){let e=f?.chainId;e&&(y=fH(e))}if(p&&h&&!y){r.push(SV(t,`unable to resolve payment chain and verify token decimals`));return}let b;if(p&&h&&y)try{let n;if(e.method===Vx.tempo){let e=await EM(N({chain:y,transport:L()}),h,v??he,{requireDecimals:!0});n=e.balance,m=e.decimals,b=e.symbol}else{let e=await dH(y,h,v);n=e.balance,m=e.decimals,b=e.symbol}if(v&&n<p){let e=pH(p,m),i=pH(n,m),a=b??`tokens`;r.push(SV(t,`insufficient balance (have ${i}, need ${e} ${a} on ${y.name})`,`Fund wallet ${v} with at least ${e} ${a} on ${y.name}.`));return}}catch(e){c&&console.log(X.dim(` Balance check skipped: ${e.message}`)),r.push(SV(t,`unable to verify token balance and decimals from the payment chain`));return}let x=p?pH(p,m):`unknown amount`,S=b??(h?.length===3?h.toUpperCase():``),C=y?.name,w=`${x}${S?` ${S}`:``}${C?` on ${C}`:``}`;if(u.silent||console.log(X.dim(v?` Attempting payment with wallet ${v}`:` Attempting payment with configured method`)),!_&&y?.testnet)u.silent||console.log(X.dim(` Auto-approved: ${w} (testnet)`));else if(!u.yes&&!n.isInteractive){r.push(SV(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${w}`));else if(!await vM(` ${X.yellow(`Pay`)} ${w}. Continue?`,!1)){r.push(SV(t,`declined`));return}let T,E,ee;if(g)try{let t=await g.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});T=t.methods,E=t.createCredential,ee=t.credentialContext}catch(e){r.push(SV(t,e.message));return}else T=[_];if(_&&pj(e)){let n=!0,u=SH((e,t)=>CV(e,t??{},3e4)),d=jO({methods:[_],polyfill:!1,async onChallenge(n,{createCredential:i}){let a=await Iz(n,l?.config.extensions);Wz(e,n);let o=await i(a);return r.push(Q(`${t}: submitted`)),o},fetch:async(t,r)=>n?(n=!1,new Response(null,{status:402,headers:{[q.wwwAuthenticate]:CS(e)}})):u.fetch(t,r)});try{await bH(r,await d.fetch(i,{method:a.method,headers:o,body:s??null}),c,y,!0,u.receipt)}catch(e){r.push($(t,e.message))}return}let D=await vH(e,T,E,t,r,l?.config.extensions,ee,i);D&&(g?.prepareCredentialRequest?.({challenge:e,credential:D,headers:o}),await yH(r,i,a,D,o,s,c,y,GS(e),pj(e)))}async function _H(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u,stripeKey:d}=n,{plugin:f,method:p}=Lz(e,l?.config);if(!f&&!p){r.push(SV(t,`no Stripe payment method available`));return}let m=!!(f&&!l?.config.plugins?.includes(f)&&n.isStripeTestKey),h=e.request,g=DV(h.amount)?BigInt(h.amount):void 0,_=h.decimals??2,v=h.currency,y=g?pH(g,_):`unknown amount`,b=v?.length===3?v.toUpperCase():``,x=`${y}${b?` ${b}`:``} via Stripe${m?` (testmode)`:``}`;if(m)u.silent||console.log(X.dim(` Attempting: ${x}`));else if(!u.yes&&!n.isInteractive){r.push(SV(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${x}`));else if(!await vM(` ${X.yellow(`Pay`)} ${x}. Continue?`,!1)){r.push(SV(t,`declined`));return}let S,C,w;if(f)try{let t={paymentMethod:`pm_card_visa`};d&&(t.secretKey=d);let n=await f.setup({challenge:e,options:{},methodOpts:t});S=n.methods,C=n.createCredential,w=n.credentialContext}catch(e){r.push(SV(t,e.message));return}else S=[p];let T=await vH(e,S,C,t,r,l?.config.extensions,w,i);if(T){if(f?.prepareCredentialRequest?.({challenge:e,credential:T,headers:o}),m){let n=await CV(i,{method:a.method,headers:{...o,[GS(e)]:T},body:s??null},3e4);n.status>=200&&n.status<300?r.push(Q(`${t}: successful`,`HTTP ${n.status}`)):r.push(SV(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await yH(r,i,a,T,o,s,c,void 0,GS(e))}}async function vH(e,t,n,r,i,a,o,s){let c=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:CS(e)}});try{gE(e,new URL(s),void 0);let l=await Iz(e,a,o),u;return u=n?await n(c,l):await jO({methods:t,polyfill:!1}).createCredential(c,l),i.push(Q(`${r}: submitted`)),u}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(SV(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function yH(e,t,n,r,i,a,o,s,c=q.authorization,l=!1){let u;try{u=await CV(t,{method:n.method,headers:{...i,[c]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}return bH(e,u,o,s,l)}async function bH(e,t,n,r,i=!1,a){if(t.status===402){let n=await t.text().catch(()=>``),r=`Payment rejected`;try{let e=JSON.parse(n);r=e.detail??e.title??r}catch{}return e.push($(`Payment: accepted`,r,`The server rejected a valid credential. Check that your payment verification logic accepts the credential format and that the payment was processed on-chain.`)),e}if(t.status>=400&&t.status<500)e.push(xV(`Payment: post-payment response`,`Got ${t.status}`,`Payment succeeded but the endpoint returned a client error. The endpoint likely requires request body parameters. Use --body to provide them.`));else if(t.status>=500)return e.push($(`Payment: server response`,`Got ${t.status}`,`Payment was accepted but the server errored while generating the response. Check server logs for the underlying error.`)),e;else e.push(Q(`Payment: successful`,`HTTP ${t.status}`));let o=t.headers.get(`content-type`)??``,s=t.headers.get(q.paymentReceipt),c=!s&&i&&pA(t),l=await t.text().catch(()=>``);if(c){let t=a?.(),n=t===void 0?xH(l):t??void 0;n?e.push(Q(`Payment receipt in event stream`,n.reference)):e.push($(`Payment receipt in event stream`,void 0,`SSE session responses without a Payment-Receipt header must end with an "event: payment-receipt" carrying the session receipt.`))}else if(!s)e.push($(`Payment-Receipt header present`,void 0,`After accepting payment, include a Payment-Receipt header with a base64url-encoded JSON object containing: method, reference, status ("success"), and timestamp (ISO 8601).`));else{e.push(Q(`Payment-Receipt header present`));try{let t=Ww(s);if(e.push(Q(`Receipt parseable`)),t.status===`success`?e.push(Q(`Receipt status is "success"`)):e.push($(`Receipt status is "success"`,`Got: ${t.status}`)),t.reference){let n=/^0x[0-9a-fA-F]{64}$/.test(t.reference),r=t.reference.startsWith(`pi_`);n||r?e.push(Q(`Receipt reference valid`,t.reference.slice(0,20)+`...`)):e.push(xV(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(xV(`Receipt has reference`,`No reference field`));if(t.timestamp){let n=new Date(t.timestamp),r=Date.now()-n.getTime();r<6e4?e.push(Q(`Receipt timestamp recent`,`${Math.round(r/1e3)}s ago`)):e.push(xV(`Receipt timestamp recent`,`${Math.round(r/6e4)}m ago`))}n&&console.log(X.dim(` Receipt: ${JSON.stringify(t,null,2)}`))}catch(t){e.push($(`Receipt parseable`,t.message))}}if(l.length>0)e.push(Q(`Response body non-empty`,`${o.split(`;`)[0]}, ${wV(l.length)}`));else{let n=[...t.headers.entries()].filter(([e])=>!e.startsWith(`x-`)&&![`content-type`,`content-length`,`date`,`server`,`connection`,`keep-alive`,`cache-control`,`vary`,`access-control-allow-origin`,`payment-receipt`,`payment-session`,`payment-session-snapshot`].includes(e.toLowerCase()));n.length>0?e.push(xV(`Response body empty -- data may be in headers only`,n.map(([e])=>e).join(`, `))):e.push(xV(`Response body empty`))}if(o?e.push(Q(`Content-Type header set`,o.split(`;`)[0])):e.push(xV(`Content-Type header set`)),s)try{let t=Ww(s);if(t.reference&&/^0x[0-9a-fA-F]{64}$/.test(t.reference)){let n=r?.blockExplorers?.default?.url;if(n){let r=n.includes(`tempo`)?`receipt`:`tx`;e.push(Q(`On-chain transaction`,`${n}/${r}/${t.reference}`))}}}catch{}return e}function xH(e){for(let t of e.replace(/\r\n|\r/g,`
254
254
  `).split(`
255
255
 
256
- `)){let e=kO(t);if(e?.type===`payment-receipt`)return e.data}}function zB(e){let t;return{async fetch(n,r){let i=await e(n,r);if(!i.body||!OO(i)||i.headers.get(q.paymentReceipt))return i;t??=null;let a=new TextDecoder,o=[],s=0,c=!1,l=!1,u=(e,n)=>{let r=c?`\r${e}`:e;c=!n&&r.endsWith(`\r`),c&&(r=r.slice(0,-1));let i=r.replace(/\r\n|\r/g,`
256
+ `)){let e=mA(t);if(e?.type===`payment-receipt`)return e.data}}function SH(e){let t;return{async fetch(n,r){let i=await e(n,r);if(!i.body||!pA(i)||i.headers.get(q.paymentReceipt))return i;t??=null;let a=new TextDecoder,o=[],s=0,c=!1,l=!1,u=(e,n)=>{let r=c?`\r${e}`:e;c=!n&&r.endsWith(`\r`),c&&(r=r.slice(0,-1));let i=r.replace(/\r\n|\r/g,`
257
257
  `),a=[];i.startsWith(`
258
258
  `)&&o.at(-1)?.endsWith(`
259
259
  `)&&(a.push(o.join(``).slice(0,-1)),o=[],s=0,i=i.slice(1));for(let e=i.indexOf(`
@@ -262,18 +262,18 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
262
262
 
263
263
  `))a.push(o.join(``)+i.slice(0,e)),o=[],s=0,i=i.slice(e+2);i&&(o.push(i),s+=i.length),n&&(a.push(o.join(``)),o=[],s=0),l&&a.length>0&&(a.shift(),l=!1),s>1048576&&(o=o.at(-1)?.endsWith(`
264
264
  `)?[`
265
- `]:[],s=o.length,l=!0);for(let e of a){let n=kO(e);n?.type===`payment-receipt`&&!t&&(t=n.data)}},d=i.body.pipeThrough(new TransformStream({transform(e,t){u(a.decode(e,{stream:!0}),!1),t.enqueue(e)},flush(){u(a.decode(),!0)}})),f=new Response(d,{headers:i.headers,status:i.status,statusText:i.statusText});return Object.defineProperty(f,"url",{value:i.url}),f},receipt:()=>t}}YA();const BB={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function VB(e){let t=BB[e.severity],n=e.detail?`${e.label} (${e.detail})`:e.label;console.log(` ${t} ${n}`),e.hint&&e.severity!==`pass`&&console.log(X.dim(` → ${e.hint}`))}function HB(e){console.log(`\n${X.bold(e)}`)}function UB(e,t){for(let n of e)VB(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`suggested`?t.suggested++:n.severity===`skip`&&t.skipped++}Rx(),YA();const WB=vb(`validate`,{description:`Validate an MPP server implementation end-to-end`,args:p.object({url:p.string().describe(`Base URL of the MPP server to validate`)}),options:p.object({endpoint:p.string().optional().describe(`Endpoint to test (METHOD:path). Skips discovery.`),body:p.string().optional().describe(`Request body. With --endpoint, used directly. In discovery mode, JSON with / keys is a per-path mapping.`),query:p.array(p.string()).optional().describe(`Query parameter (key=value, repeatable)`),header:p.array(p.string()).optional().describe(`Request header (key:value, repeatable)`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity level`),yes:p.boolean().default(!1).describe(`Auto-approve mainnet payments`),outputJson:p.boolean().default(!1).describe(`Output results as JSON (auto-enabled in known agent environments)`)}),alias:{endpoint:`e`,header:`H`,verbose:`v`,yes:`y`,outputJson:`j`},async run(e){if(e.options.outputJson||AA()){let t=await gB({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,payment:MB});console.log(JSON.stringify(t,null,2));let n=t.endpoints.length===0&&!e.options.endpoint;(t.summary.failed>0||!t.discovery.found||n)&&process.exit(1);return}let t=e.args.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``);console.log(`\n${X.bold(`mppx validate`)} ${X.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,suggested:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of hB({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=>UB(e,n),payment:MB}))switch(t.phase){case`discovery`:if(HB(`Discovery (/openapi.json)`),UB(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=mB.split(`
266
- `);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,HB(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),UB(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),UB(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}GB(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function GB(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function KB(e){return JB(e)?e.offers:[e]}function qB(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=YB(t.amount)??YB(i.amount)??null,o=YB(t.currency)??YB(i.currency),s=YB(e.description)??YB(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 JB(e){return`offers`in e&&!(`_canonicalRequest`in e)}function YB(e){return typeof e==`string`?e:void 0}var XB=R((()=>{})),ZB=at({generate:()=>QB,generateProxy:()=>$B});function QB(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=>tV(e,r));return eV({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function $B(e){let t=e.routes.map(t=>({...t,path:nV(e.basePath,t.path)}));return eV({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function eV(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`]=bD.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 tV(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:KB(t).map(qB)},...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:aS(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:qB(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function nV(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var rV=R((()=>{sS(),ED(),XB()}));Rx(),iC(),GE(),WT(),tT(),mT(),_T(),Gx(),rS(),zC(),fT(),Iw(),fA(),lj(),YA();const iV=`0.21.3`,aV=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),oV=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),sV=p.object({message:p.string(),path:p.string(),severity:p.string()}),cV=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),lV=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function uV(e){return e.format===`json`&&e.formatExplicit}function dV(e,t,n){if(uV(e))return e.ok(t);n()}async function fV(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function pV(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function mV(e){return typeof e==`string`?e:void 0}function hV(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function gV(e){let t=hV(e);return{...mV(e.description)?{description:mV(e.description)}:{},id:mV(e.id)??mV(e.name)??`unknown`,...mV(e.name)?{name:mV(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...mV(e.status)?{status:mV(e.status)}:{},...mV(e.serviceUrl)||mV(e.url)?{url:mV(e.serviceUrl)??mV(e.url)}:{}}}function _V(e){return{...mV(e.description)?{description:mV(e.description)}:{},method:mV(e.method)??`GET`,path:mV(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function vV(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=mV(t.amount),r=mV(t.currency),i=mV(t.method),a=mV(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function yV(e){return e.request.currency??e.request.asset}function bV(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=yV(e);return typeof t==`string`&&t.toLowerCase()===n})}async function xV(e,t,n={}){let r=()=>eT().getChallenges(e),i=()=>pT().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[]}async function SV(e,t){let n=[],r=0,i=e.body?.getReader(),a=!0;if(i)for(;;){let{done:e,value:o}=await i.read();if(e)break;if(n.push(o),r+=o.byteLength,r>t){a=!1;break}}let o=a?i?new Blob(n):null:new ReadableStream({start(e){for(let t of n)e.enqueue(t)},async pull(e){let{done:t,value:n}=await i.read();t?e.close():e.enqueue(n)},cancel(e){return i.cancel(e)}}),s=new Response(o,{headers:e.headers,status:e.status,statusText:e.statusText});return Object.defineProperty(s,"url",{value:e.url}),{complete:a,response:s}}function CV(e){if(!LC(e))return`mpp:${e.id}`;let{description:t,id:n,request:r,...i}=e,{description:a,...o}=r.resource??{};return`x402:${xS({...i,id:``,request:{...r,...r.resource?{resource:o}:{}}})}`}function wV(e,t){if(!e||!t)return!0;try{return new URL(e).origin===new URL(t).origin}catch{return!1}}async function TV(e,t){return ZL(bV(await xV(e,t.protocol,{ignoreX402ResponseUrl:t.ignoreX402ResponseUrl}).catch(()=>[]),t.currency),t.config)!==void 0}function EV(e){return hT({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function DV(e,t){if(!LC(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:xS(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[_w]:lT({accepts:[fw(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function OV(e){let{host:t,hostname:n,protocol:r}=new URL(e);return r===`https:`||!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function kV(e,t,n,r){let i=!1,a=t,o=OV(a),s={...n,redirect:`manual`,headers:XT(n.headers)};o.host&&NV(s.headers,o.host);for(let t=0;t<=20;t++){let{protocol:n,hostname:c}=new URL(o.url),l=[`localhost`,`127.0.0.1`,`[::1]`].includes(c);i||=n!==`https:`&&!(n===`http:`&&l);let u=await e(o.url,s),d=u.headers.get(`location`);if(!r||!d||![301,302,303,307,308].includes(u.status))return{insecureTransport:i,init:s,logicalUrl:a,response:u,target:o};if(t===20)throw TypeError(`Too many redirects`);await u.body?.cancel().catch(()=>{});let f=new URL(d,a),p=new URL(a),m=XT(s.headers);if(f.origin!==p.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];let h=(s.method??(s.body?`POST`:`GET`)).toUpperCase(),g=u.status===303&&h!==`GET`&&h!==`HEAD`||(u.status===301||u.status===302)&&h===`POST`;if(g)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];a=f.href,o=OV(a),o.host&&NV(m,o.host);let _={...s};g&&(delete _.body,_.method=`GET`),s={..._,headers:m,redirect:`manual`}}throw TypeError(`Too many redirects`)}function AV(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&MV(i),OV(i.href)}function jV(e,t){let n=new URL(e),r=new URL(t||e),i=new URL(OV(e).url);return r.origin!==n.origin&&r.origin!==i.origin&&MV(r),OV(r.href)}function MV(e){throw new z({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function NV(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function PV(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function FV(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new z({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 z({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function IV(e,t){let n=t.toLowerCase();return e.find(e=>{let t=mV(e.id)?.toLowerCase(),r=mV(e.name)?.toLowerCase();return t===n||r===n})}const LV=vb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:iV,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (disables payment retries)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await tR(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=dj(),i={"User-Agent":e.options.userAgent??`mppx/${iV}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=QL(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure??!1,u=l?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,d=OV(o),f=d.url;d.host&&(i.Host=d.host);try{let r=kA(e.options.methodOpt),a=yR(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&SA(o,s,t);let p=await kV(u,o,s,e.options.location??!1),m=p.response;if((l||p.insecureTransport)&&m.status===402)return e.error({code:`INSECURE_PAYMENT`,message:`Payment requires verified HTTPS (except loopback HTTP). Use HTTPS and omit --insecure.`,exitCode:2});if(m.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&m.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${m.status}`,exitCode:22});CA(m,c),await fV(m);return}let h;for(let i=0;;i++){let l=m.url?new URL(m.url):void 0,g=d.host!==void 0&&l?.hostname===`127.0.0.1`,_=await xV(m,e.options.protocol,{ignoreX402ResponseUrl:g});if(_.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let v=bV(_,e.options.currency);if(e.options.currency&&v.length===0){let t=_.map(yV).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let y=$L(n?.config)?.length?v:await fL(v,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),b=h?y.findIndex(e=>CV(e)===h.key):-1;b>0&&y.unshift(...y.splice(b,1));let x=ZL(y,n?.config);if(!x){let t=y.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:S,plugin:C,method:w}=x,T=LC(S),ee=T?jV(p.logicalUrl,(PV(S)??m.url)||p.logicalUrl):AV(o,d,p.logicalUrl);if(!T)try{BT(S,new URL(p.logicalUrl||o),void 0)}catch(t){return e.error({code:`UNTRUSTED_PROOF_REALM`,message:t.message,exitCode:1})}let te=DV(S,m),E=S.request.currency??``,D=S.request.decimals??6,O,A;C&&(A=await C.setup({challenge:S,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),E=A.tokenSymbol,D=A.tokenDecimals,O=A.explorerUrl);let ne=!e.options.silent&&e.options.confirm,j=new Set;{CA(m,S.method===`tempo`&&S.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(S))e.has(n)||r===void 0||t.push([n,EA(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:E,tokenDecimals:D,explorerUrl:O},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(S.request))e.has(n)||i===void 0||t.push([n,wA(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=S.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=TA(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,wA(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)j.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||ne){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
267
- `);t(` ${X.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${l}${e}\n`)}}}if(ne&&(t(`
268
- `),!await NA(`Proceed with ${S.intent}?`,!0))){t(`Aborted.
269
- `);return}}let re=process.env.MPPX_PRIVATE_KEY?.trim()||!jA(nj(e.options.account));if(Ok(S)&&re&&!w&&!(C&&n?.config.plugins?.includes(C))){try{await bz({challenge:S,challengeResponse:te,credentialContext:await YL(S,n?.config.extensions,A?.credentialContext),endpoint:p.logicalUrl,fetch:u,fetchInput:ee.url,init:{...p.init,redirect:`manual`},info:t,methodOptions:r,options:{account:e.options.account,fail:e.options.fail,include:e.options.include,network:e.options.network,rpcUrl:e.options.rpcUrl,session:e.options.session,silent:e.options.silent,verbose:e.options.verbose},registry:a})}catch(e){return lz(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:w&&Ok(S)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let M=w&&Ok(S)?void 0:await YL(S,n?.config.extensions,A?.credentialContext),N,ie;if(w&&Ok(S)){let e=te;N=await JE({methods:[w],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await YL(e,n?.config.extensions,A?.credentialContext);return rR(S,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return u(t,n)}}).fetch(ee.url,{...p.init,context:M,redirect:`manual`})}else{if(h?.key===CV(S))ie=h.credential;else if(A?.createCredential)ie=await A.createCredential(te,M);else if(A)ie=await JE({methods:A.methods,polyfill:!1,transport:EV(S)}).createCredential(te,M);else if(w)ie=await JE({methods:[w],polyfill:!1,transport:EV(S)}).createCredential(te,M);else throw Error(`unreachable`);let n=T?vw:US(S),r={...XT(p.init.headers),[n]:ie};T&&NV(r,ee.host),C?.prepareCredentialRequest?.({challenge:S,credential:ie,headers:r});let i={...p.init,redirect:`manual`,headers:r};e.options.verbose>=2&&SA(ee.url,i,t),N=await u(ee.url,i)}if(h=ie===void 0?void 0:{credential:ie,key:CV(S)},N.status===402&&!(w&&Ok(S))&&i+1<3&&wV(N.url,p.response.url)){let t=t=>TV(t,{config:n?.config,currency:e.options.currency,ignoreX402ResponseUrl:g,protocol:e.options.protocol}),r=new Response(null,{headers:N.headers,status:N.status,statusText:N.statusText});if(Object.defineProperty(r,"url",{value:N.url}),await t(r.clone())){await N.body?.cancel().catch(()=>{}),m=r;continue}if(e.options.protocol!==`mpp`&&!g){let e=await SV(N,1048576);if(e.complete&&await t(e.response.clone())){m=e.response;continue}N=e.response}}if(e.options.fail&&N.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${N.status}`,exitCode:22});if(N.status===402){let n=await N.text();t(`${X.bold(X.red(`Payment Rejected`))}\n`);try{let e=JSON.parse(n),r=[];for(let[t,n]of Object.entries(e))n!==void 0&&r.push([t,DA(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(CA(N,c),!(ie&&await C?.handleResponse?.({challenge:S,credential:ie,response:N,fetchUrl:f,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:ne,confirm:NA,tokenSymbol:E,tokenDecimals:D,explorerUrl:O,shownKeys:j}))){let n=N.headers.get(q.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(k.toString(n));t(`\n${X.bold(X.green(`Payment Receipt`))}\n`);let r=[],i=e.channelId,a=e.reference,o=i&&a&&i===a,s=new Set([`acceptedCumulative`,`spent`]);for(let[t,n]of Object.entries(e)){if(n===void 0||j.has(t)||t===`reference`&&o)continue;let e=C?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${PA(BigInt(n),E,D)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&O?r.push([t,OA(`${O}/tx/${n}`,n)]):r.push([t,String(n)]):r.push([t,e])}r.sort(([e],[t])=>e.localeCompare(t));let c=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(c))} ${n}\n`);t(`
270
- `)}catch{}await fV(N)}return}}catch(t){if(t instanceof z)throw t;let n=t instanceof Error?t.cause:void 0,r=n instanceof Error?n:void 0;if(r&&`code`in r){let t=r.code;return t===`ENOTFOUND`?e.error({code:`DNS_ERROR`,message:`Could not resolve host "${s}". Check the URL and try again.`,exitCode:6}):t===`ECONNREFUSED`?e.error({code:`CONNECTION_REFUSED`,message:`Connection refused by "${s}". Is the server running?`,retryable:!0,exitCode:7}):t===`ECONNRESET`?e.error({code:`CONNECTION_RESET`,message:`Connection to "${s}" was reset.`,retryable:!0,exitCode:56}):t===`ETIMEDOUT`?e.error({code:`CONNECTION_TIMEOUT`,message:`Connection to "${s}" timed out.`,retryable:!0,exitCode:28}):t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?e.error({code:`TLS_ERROR`,message:`TLS certificate error for "${s}". Use --insecure to skip verification.`,exitCode:60}):e.error({code:`REQUEST_FAILED`,message:`Request to "${s}" failed: ${r.message}`})}{let n=t instanceof Error?t.message:String(t);return e.error({code:`REQUEST_FAILED`,message:r?`Request failed: ${n} (Cause: ${r.message})`:`Request failed: ${n}`})}}}}),RV=vb(`account`,{description:`Manage accounts (create, default, delete, export, fund, list, view)`}).command(`create`,{description:`Create new account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({address:p.string(),name:p.string()}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=uV(e),n=e.options.account;if(!n){if((await rj().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 MA(`Account name`);if(!r)return;n=r}}let r=rj(n);for(;await r.get();){if(t)return e.error({code:`ACCOUNT_EXISTS`,message:`Account "${n}" already exists.`,exitCode:1});process.stderr.write(`${X.dim(`Account "${n}" already exists.`)}\n\n`);let i=await MA(`Enter different name`);if(!i)return;n=i,r=rj(n)}let i=_e(),a=L(i);await r.set(i),(await rj().list()).length===1&&tj().set(n);let o=ye.blockExplorers?.default?.url,s=o?OA(`${o}/address/${a.address}`,a.address):a.address,c=IA(e.options),l=FA(e.options.rpcUrl,{network:c});return LA({network:c,rpcUrl:l}).then(e=>M({chain:e,transport:I(l)})).then(e=>import(`viem/tempo`).then(({Actions:t})=>t.faucet.fund(e,{account:a}).catch(()=>{}))),dV(e,{address:a.address,name:n},()=>{console.log(`Account "${n}" saved to keychain.`),console.log(X.dim(`Address ${s}`)),console.log(X.dim(`Fund testnet tokens: mppx account fund --account ${n} --network testnet`))})}}).command(`default`,{description:`Set default account`,options:p.object({account:p.string().describe(`Account name`)}),output:p.object({name:p.string()}),alias:{account:`a`},async run(e){let t=e.options.account;return jA(t)?NL(t)?(tj().set(t),dV(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 rj(t).get()?(tj().set(t),dV(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69})}}).command(`delete`,{description:`Delete account`,options:p.object({account:p.string().describe(`Account name`),yes:p.boolean().optional().describe(`DANGER!! Skip confirmation prompts`)}),output:p.object({defaultAccount:p.string().optional(),name:p.string()}),alias:{account:`a`},async run(e){let t=rj(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=L(n),i=await HA(r.address,{includeTestnet:!1});if(!e.options.yes){if(uV(e))return e.error({code:`CONFIRMATION_REQUIRED`,message:`Pass --yes to delete an account in structured mode.`,exitCode:2});let t=ye.blockExplorers?.default?.url,n=t?OA(`${t}/address/${r.address}`,r.address):r.address;process.stderr.write(X.dim(`Delete account "${e.options.account}"\n`)),process.stderr.write(X.dim(` Address ${n}\n`));for(let e=0;e<i.length;e++)process.stderr.write(X.dim(` ${e===0?`Balance`:` `} ${i[e]}\n`));if(process.stderr.write(X.dim(`This action cannot be undone
265
+ `]:[],s=o.length,l=!0);for(let e of a){let n=mA(e);n?.type===`payment-receipt`&&!t&&(t=n.data)}},d=i.body.pipeThrough(new TransformStream({transform(e,t){u(a.decode(e,{stream:!0}),!1),t.enqueue(e)},flush(){u(a.decode(),!0)}})),f=new Response(d,{headers:i.headers,status:i.status,statusText:i.statusText});return Object.defineProperty(f,"url",{value:i.url}),f},receipt:()=>t}}PM();const CH={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function wH(e){let t=CH[e.severity],n=e.detail?`${e.label} (${e.detail})`:e.label;console.log(` ${t} ${n}`),e.hint&&e.severity!==`pass`&&console.log(X.dim(` → ${e.hint}`))}function TH(e){console.log(`\n${X.bold(e)}`)}function EH(e,t){for(let n of e)wH(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`suggested`?t.suggested++:n.severity===`skip`&&t.skipped++}Rx(),PM();const DH=vb(`validate`,{description:`Validate an MPP server implementation end-to-end`,args:p.object({url:p.string().describe(`Base URL of the MPP server to validate`)}),options:p.object({endpoint:p.string().optional().describe(`Endpoint to test (METHOD:path). Skips discovery.`),body:p.string().optional().describe(`Request body. With --endpoint, used directly. In discovery mode, JSON with / keys is a per-path mapping.`),query:p.array(p.string()).optional().describe(`Query parameter (key=value, repeatable)`),header:p.array(p.string()).optional().describe(`Request header (key:value, repeatable)`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity level`),yes:p.boolean().default(!1).describe(`Auto-approve mainnet payments`),outputJson:p.boolean().default(!1).describe(`Output results as JSON (auto-enabled in known agent environments)`)}),alias:{endpoint:`e`,header:`H`,verbose:`v`,yes:`y`,outputJson:`j`},async run(e){if(e.options.outputJson||hM()){let t=await rH({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,payment:hH});console.log(JSON.stringify(t,null,2));let n=t.endpoints.length===0&&!e.options.endpoint;(t.summary.failed>0||!t.discovery.found||n)&&process.exit(1);return}let t=e.args.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``);console.log(`\n${X.bold(`mppx validate`)} ${X.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,suggested:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of nH({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=>EH(e,n),payment:hH}))switch(t.phase){case`discovery`:if(TH(`Discovery (/openapi.json)`),EH(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=tH.split(`
266
+ `);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,TH(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),EH(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),EH(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}OH(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function OH(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function kH(e){return jH(e)?e.offers:[e]}function AH(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=MH(t.amount)??MH(i.amount)??null,o=MH(t.currency)??MH(i.currency),s=MH(e.description)??MH(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 jH(e){return`offers`in e&&!(`_canonicalRequest`in e)}function MH(e){return typeof e==`string`?e:void 0}var NH=z((()=>{})),PH=it({generate:()=>FH,generateProxy:()=>IH});function FH(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=>RH(e,r));return LH({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function IH(e){let t=e.routes.map(t=>({...t,path:zH(e.basePath,t.path)}));return LH({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function LH(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`]=ik.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 RH(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:kH(t).map(AH)},...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:sS(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:AH(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function zH(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var BH=z((()=>{lS(),uk(),NH()}));Rx(),sC(),DO(),bE(),AT(),WT(),qT(),Gx(),aS(),ZC(),HT(),Uw(),Zj(),JM(),PM();const VH=`0.22.0`,HH=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),UH=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),WH=p.object({message:p.string(),path:p.string(),severity:p.string()}),GH=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),KH=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function qH(e){return e.format===`json`&&e.formatExplicit}function JH(e,t,n){if(qH(e))return e.ok(t);n()}async function YH(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function XH(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function ZH(e){return typeof e==`string`?e:void 0}function QH(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function $H(e){let t=QH(e);return{...ZH(e.description)?{description:ZH(e.description)}:{},id:ZH(e.id)??ZH(e.name)??`unknown`,...ZH(e.name)?{name:ZH(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...ZH(e.status)?{status:ZH(e.status)}:{},...ZH(e.serviceUrl)||ZH(e.url)?{url:ZH(e.serviceUrl)??ZH(e.url)}:{}}}function eU(e){return{...ZH(e.description)?{description:ZH(e.description)}:{},method:ZH(e.method)??`GET`,path:ZH(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function tU(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=ZH(t.amount),r=ZH(t.currency),i=ZH(t.method),a=ZH(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function nU(e){return e.request.currency??e.request.asset}function rU(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=nU(e);return typeof t==`string`&&t.toLowerCase()===n})}async function iU(e,t,n={}){let r=()=>DT().getChallenges(e),i=()=>UT().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[]}async function aU(e,t){let n=[],r=0,i=e.body?.getReader(),a=!0;if(i)for(;;){let{done:e,value:o}=await i.read();if(e)break;if(n.push(o),r+=o.byteLength,r>t){a=!1;break}}let o=a?i?new Blob(n):null:new ReadableStream({start(e){for(let t of n)e.enqueue(t)},async pull(e){let{done:t,value:n}=await i.read();t?e.close():e.enqueue(n)},cancel(e){return i.cancel(e)}}),s=new Response(o,{headers:e.headers,status:e.status,statusText:e.statusText});return Object.defineProperty(s,"url",{value:e.url}),{complete:a,response:s}}function oU(e){if(!YC(e))return`mpp:${e.id}`;let{description:t,id:n,request:r,...i}=e,{description:a,...o}=r.resource??{};return`x402:${CS({...i,id:``,request:{...r,...r.resource?{resource:o}:{}}})}`}function sU(e,t){if(!e||!t)return!0;try{return new URL(e).origin===new URL(t).origin}catch{return!1}}async function cU(e,t){return Rz(rU(await iU(e,t.protocol,{ignoreX402ResponseUrl:t.ignoreX402ResponseUrl}).catch(()=>[]),t.currency),t.config)!==void 0}function lU(e){return GT({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function uU(e,t){if(!YC(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:CS(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[ww]:RT({accepts:[yw(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function dU(e){let{host:t,hostname:n,protocol:r}=new URL(e);return r===`https:`||!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function fU(e,t,n,r){let i=!1,a=t,o=dU(a),s={...n,redirect:`manual`,headers:OD(n.headers)};o.host&&gU(s.headers,o.host);for(let t=0;t<=20;t++){let{protocol:n,hostname:c}=new URL(o.url),l=[`localhost`,`127.0.0.1`,`[::1]`].includes(c);i||=n!==`https:`&&!(n===`http:`&&l);let u=await e(o.url,s),d=u.headers.get(`location`);if(!r||!d||![301,302,303,307,308].includes(u.status))return{insecureTransport:i,init:s,logicalUrl:a,response:u,target:o};if(t===20)throw TypeError(`Too many redirects`);await u.body?.cancel().catch(()=>{});let f=new URL(d,a),p=new URL(a),m=OD(s.headers);if(f.origin!==p.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];let h=(s.method??(s.body?`POST`:`GET`)).toUpperCase(),g=u.status===303&&h!==`GET`&&h!==`HEAD`||(u.status===301||u.status===302)&&h===`POST`;if(g)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(m))t.toLowerCase()===e&&delete m[t];a=f.href,o=dU(a),o.host&&gU(m,o.host);let _={...s};g&&(delete _.body,_.method=`GET`),s={..._,headers:m,redirect:`manual`}}throw TypeError(`Too many redirects`)}function pU(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&hU(i),dU(i.href)}function mU(e,t){let n=new URL(e),r=new URL(t||e),i=new URL(dU(e).url);return r.origin!==n.origin&&r.origin!==i.origin&&hU(r),dU(r.href)}function hU(e){throw new B({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function gU(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function _U(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function vU(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new B({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 B({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function yU(e,t){let n=t.toLowerCase();return e.find(e=>{let t=ZH(e.id)?.toLowerCase(),r=ZH(e.name)?.toLowerCase();return t===n||r===n})}const bU=vb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:VH,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (disables payment retries)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await Hz(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=XM(),i={"User-Agent":e.options.userAgent??`mppx/${VH}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=zz(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure??!1,u=l?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,d=dU(o),f=d.url;d.host&&(i.Host=d.host);try{let r=mM(e.options.methodOpt),a=oB(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&sM(o,s,t);let p=await fU(u,o,s,e.options.location??!1),m=p.response;if((l||p.insecureTransport)&&m.status===402)return e.error({code:`INSECURE_PAYMENT`,message:`Payment requires verified HTTPS (except loopback HTTP). Use HTTPS and omit --insecure.`,exitCode:2});if(m.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&m.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${m.status}`,exitCode:22});cM(m,c),await YH(m);return}let h;for(let i=0;;i++){let l=m.url?new URL(m.url):void 0,g=d.host!==void 0&&l?.hostname===`127.0.0.1`,_=await iU(m,e.options.protocol,{ignoreX402ResponseUrl:g});if(_.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let v=rU(_,e.options.currency);if(e.options.currency&&v.length===0){let t=_.map(nU).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let y=Bz(n?.config)?.length?v:await $R(v,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),b=h?y.findIndex(e=>oU(e)===h.key):-1;b>0&&y.unshift(...y.splice(b,1));let x=Rz(y,n?.config);if(!x){let t=y.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:S,plugin:C,method:w}=x,T=YC(S),E=T?mU(p.logicalUrl,(_U(S)??m.url)||p.logicalUrl):pU(o,d,p.logicalUrl);if(!T)try{gE(S,new URL(p.logicalUrl||o),void 0)}catch(t){return e.error({code:`UNTRUSTED_PROOF_REALM`,message:t.message,exitCode:1})}let ee=uU(S,m),D=S.request.currency??``,O=S.request.decimals??6,k,A;C&&(A=await C.setup({challenge:S,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),D=A.tokenSymbol,O=A.tokenDecimals,k=A.explorerUrl);let j=!e.options.silent&&e.options.confirm,M=new Set;{cM(m,S.method===`tempo`&&S.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(S))e.has(n)||r===void 0||t.push([n,dM(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:D,tokenDecimals:O,explorerUrl:k},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(S.request))e.has(n)||i===void 0||t.push([n,lM(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=S.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=uM(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,lM(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)M.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||j){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
267
+ `);t(` ${X.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${l}${e}\n`)}}}if(j&&(t(`
268
+ `),!await vM(`Proceed with ${S.intent}?`,!0))){t(`Aborted.
269
+ `);return}}let ne=process.env.MPPX_PRIVATE_KEY?.trim()||!gM(VM(e.options.account));if(pj(S)&&ne&&!w&&!(C&&n?.config.plugins?.includes(C))){try{await sV({challenge:S,challengeResponse:ee,credentialContext:await Iz(S,n?.config.extensions,A?.credentialContext),endpoint:p.logicalUrl,fetch:u,fetchInput:E.url,init:{...p.init,redirect:`manual`},info:t,methodOptions:r,options:{account:e.options.account,fail:e.options.fail,include:e.options.include,network:e.options.network,rpcUrl:e.options.rpcUrl,session:e.options.session,silent:e.options.silent,verbose:e.options.verbose},registry:a})}catch(e){return XB(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:w&&pj(S)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let N=w&&pj(S)?void 0:await Iz(S,n?.config.extensions,A?.credentialContext),P,re;if(w&&pj(S)){let e=ee;P=await jO({methods:[w],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await Iz(e,n?.config.extensions,A?.credentialContext);return Wz(S,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return u(t,n)}}).fetch(E.url,{...p.init,context:N,redirect:`manual`})}else{if(h?.key===oU(S))re=h.credential;else if(A?.createCredential)re=await A.createCredential(ee,N);else if(A)re=await jO({methods:A.methods,polyfill:!1,transport:lU(S)}).createCredential(ee,N);else if(w)re=await jO({methods:[w],polyfill:!1,transport:lU(S)}).createCredential(ee,N);else throw Error(`unreachable`);let n=T?Tw:GS(S),r={...OD(p.init.headers),[n]:re};T&&gU(r,E.host),C?.prepareCredentialRequest?.({challenge:S,credential:re,headers:r});let i={...p.init,redirect:`manual`,headers:r};e.options.verbose>=2&&sM(E.url,i,t),P=await u(E.url,i)}if(h=re===void 0?void 0:{credential:re,key:oU(S)},P.status===402&&!(w&&pj(S))&&i+1<3&&sU(P.url,p.response.url)){let t=t=>cU(t,{config:n?.config,currency:e.options.currency,ignoreX402ResponseUrl:g,protocol:e.options.protocol}),r=new Response(null,{headers:P.headers,status:P.status,statusText:P.statusText});if(Object.defineProperty(r,"url",{value:P.url}),await t(r.clone())){await P.body?.cancel().catch(()=>{}),m=r;continue}if(e.options.protocol!==`mpp`&&!g){let e=await aU(P,1048576);if(e.complete&&await t(e.response.clone())){m=e.response;continue}P=e.response}}if(e.options.fail&&P.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${P.status}`,exitCode:22});if(P.status===402){let n=await P.text();t(`${X.bold(X.red(`Payment Rejected`))}\n`);try{let e=JSON.parse(n),r=[];for(let[t,n]of Object.entries(e))n!==void 0&&r.push([t,fM(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(cM(P,c),!(re&&await C?.handleResponse?.({challenge:S,credential:re,response:P,fetchUrl:f,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:j,confirm:vM,tokenSymbol:D,tokenDecimals:O,explorerUrl:k,shownKeys:M}))){let n=P.headers.get(q.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(te.toString(n));t(`\n${X.bold(X.green(`Payment Receipt`))}\n`);let r=[],i=e.channelId,a=e.reference,o=i&&a&&i===a,s=new Set([`acceptedCumulative`,`spent`]);for(let[t,n]of Object.entries(e)){if(n===void 0||M.has(t)||t===`reference`&&o)continue;let e=C?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${yM(BigInt(n),D,O)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&k?r.push([t,pM(`${k}/tx/${n}`,n)]):r.push([t,String(n)]):r.push([t,e])}r.sort(([e],[t])=>e.localeCompare(t));let c=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(c))} ${n}\n`);t(`
270
+ `)}catch{}await YH(P)}return}}catch(t){if(t instanceof B)throw t;let n=t instanceof Error?t.cause:void 0,r=n instanceof Error?n:void 0;if(r&&`code`in r){let t=r.code;return t===`ENOTFOUND`?e.error({code:`DNS_ERROR`,message:`Could not resolve host "${s}". Check the URL and try again.`,exitCode:6}):t===`ECONNREFUSED`?e.error({code:`CONNECTION_REFUSED`,message:`Connection refused by "${s}". Is the server running?`,retryable:!0,exitCode:7}):t===`ECONNRESET`?e.error({code:`CONNECTION_RESET`,message:`Connection to "${s}" was reset.`,retryable:!0,exitCode:56}):t===`ETIMEDOUT`?e.error({code:`CONNECTION_TIMEOUT`,message:`Connection to "${s}" timed out.`,retryable:!0,exitCode:28}):t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?e.error({code:`TLS_ERROR`,message:`TLS certificate error for "${s}". Use --insecure to skip verification.`,exitCode:60}):e.error({code:`REQUEST_FAILED`,message:`Request to "${s}" failed: ${r.message}`})}{let n=t instanceof Error?t.message:String(t);return e.error({code:`REQUEST_FAILED`,message:r?`Request failed: ${n} (Cause: ${r.message})`:`Request failed: ${n}`})}}}}),xU=vb(`account`,{description:`Manage accounts (create, default, delete, export, fund, list, view)`}).command(`create`,{description:`Create new account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({address:p.string(),name:p.string()}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=qH(e),n=e.options.account;if(!n){if((await HM().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 _M(`Account name`);if(!r)return;n=r}}let r=HM(n);for(;await r.get();){if(t)return e.error({code:`ACCOUNT_EXISTS`,message:`Account "${n}" already exists.`,exitCode:1});process.stderr.write(`${X.dim(`Account "${n}" already exists.`)}\n\n`);let i=await _M(`Enter different name`);if(!i)return;n=i,r=HM(n)}let i=ge(),a=R(i);await r.set(i),(await HM().list()).length===1&&BM().set(n);let o=ve.blockExplorers?.default?.url,s=o?pM(`${o}/address/${a.address}`,a.address):a.address,c=xM(e.options),l=bM(e.options.rpcUrl,{network:c});return SM({network:c,rpcUrl:l}).then(e=>N({chain:e,transport:L(l)})).then(e=>import(`viem/tempo`).then(({Actions:t})=>t.faucet.fund(e,{account:a}).catch(()=>{}))),JH(e,{address:a.address,name:n},()=>{console.log(`Account "${n}" saved to keychain.`),console.log(X.dim(`Address ${s}`)),console.log(X.dim(`Fund testnet tokens: mppx account fund --account ${n} --network testnet`))})}}).command(`default`,{description:`Set default account`,options:p.object({account:p.string().describe(`Account name`)}),output:p.object({name:p.string()}),alias:{account:`a`},async run(e){let t=e.options.account;return gM(t)?bz(t)?(BM().set(t),JH(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 HM(t).get()?(BM().set(t),JH(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69})}}).command(`delete`,{description:`Delete account`,options:p.object({account:p.string().describe(`Account name`),yes:p.boolean().optional().describe(`DANGER!! Skip confirmation prompts`)}),output:p.object({defaultAccount:p.string().optional(),name:p.string()}),alias:{account:`a`},async run(e){let t=HM(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=R(n),i=await DM(r.address,{includeTestnet:!1});if(!e.options.yes){if(qH(e))return e.error({code:`CONFIRMATION_REQUIRED`,message:`Pass --yes to delete an account in structured mode.`,exitCode:2});let t=ve.blockExplorers?.default?.url,n=t?pM(`${t}/address/${r.address}`,r.address):r.address;process.stderr.write(X.dim(`Delete account "${e.options.account}"\n`)),process.stderr.write(X.dim(` Address ${n}\n`));for(let e=0;e<i.length;e++)process.stderr.write(X.dim(` ${e===0?`Balance`:` `} ${i[e]}\n`));if(process.stderr.write(X.dim(`This action cannot be undone
271
271
 
272
- `)),!await NA(`Confirm delete?`)){console.log(`Canceled`);return}}await t.delete();let a=tj().get(),o;if(a===e.options.account){let e=await rj().list();e.length>0?(o=e[0],tj().set(o)):tj().clear()}return dV(e,{defaultAccount:o,name:e.options.account},()=>{o&&console.log(`Default account set to "${o}"`),console.log(`Account "${e.options.account}" deleted`)})}}).command(`fund`,{description:`Fund account with testnet tokens`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({account:p.string(),chain:p.string(),transactions:p.array(p.string())}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=uV(e),n=nj(e.options.account),r=await rj(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=L(r),a=IA(e.options),o=FA(e.options.rpcUrl,{network:a}),s=await LA({network:a,rpcUrl:o}),c=M({chain:s,transport:I(o)});t||console.log(`Funding "${n}" on ${RA(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?OA(`${o}/tx/${e}`,X.gray(e)):e;console.log(` ${t}`)}let{waitForTransactionReceipt:l}=await import(`viem/actions`);return await Promise.all(a.map(e=>l(c,{hash:e}))),dV(e,{account:n,chain:RA(s),transactions:[...a]},()=>{console.log(`Funded successfully`)})}catch(n){let r=n instanceof Error?n.message:String(n);return t?e.error({code:`FUNDING_FAILED`,message:r,exitCode:1}):e.error({code:`FUNDING_FAILED`,message:`Funding failed: ${r}`,exitCode:1})}}}).command(`list`,{description:`List all accounts`,output:p.object({accounts:p.array(aV)}),async run(e){let t=tj().get(),n=(await rj().list()).sort(),r=[];for(let e of n){let t=await rj(e).get();t&&r.push({name:e,address:L(t).address})}let i=ML();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 dV(e,{accounts:[]},()=>{console.log(`No accounts found.`)});let a=ye.blockExplorers?.default?.url,o=Math.max(...r.map(e=>e.name.length+ +(e.name===t)));return dV(e,{accounts:r.map(e=>({...e,...e.name===t?{isDefault:!0}:void 0}))},()=>{for(let e of r){let n=e.name===t,r=n?`${e.name}${X.dim(`*`)}`:e.name,i=e.name.length+ +!!n,s=a?OA(`${a}/address/${e.address}`,e.address):e.address,c=e.source?` ${X.dim(`(${e.source})`)}`:``;console.log(`${r}${` `.repeat(o-i+2)}${X.dim(s)}${c}`)}})}}).command(`export`,{description:`Export the private key for a local account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`)}),output:p.object({privateKey:p.string()}),alias:{account:`a`},async run(e){let t=nj(e.options.account);if(jA(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 rj(t).get();return n?dV(e,{privateKey:n},()=>{console.log(n)}):e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}}).command(`view`,{description:`View account address`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:oV,alias:{account:`a`,rpcUrl:`r`},async run(e){let t=nj(e.options.account);if(jA(t)){let n=NL(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=FA(e.options.rpcUrl,{network:e.options.network}),a=await LA({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?OA(`${o}/address/${r}`,r):r,c=await HA(r,a&&i?{chain:a,rpcUrl:i}:void 0);return dV(e,{address:r,balances:c,name:t,type:`${n.wallet_type} (tempo wallet)`},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`),console.log(`${X.dim(`Type`)} ${n.wallet_type} ${X.dim(`(tempo wallet)`)}`)})}let n=await rj(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=L(n),i=FA(e.options.rpcUrl,{network:e.options.network}),a=await LA({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?OA(`${o}/address/${r.address}`,r.address):r.address,c=await HA(r.address,a&&i?{chain:a,rpcUrl:i}:void 0);return dV(e,{address:r.address,balances:c,name:t},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`)})}}),zV=vb(`sign`,{description:`Sign a payment challenge and output the Authorization header`,usage:[{suffix:`--challenge <value> [options]`},{prefix:`echo <challenge> |`,suffix:`[options]`}],options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),challenge:p.string().optional().describe(`WWW-Authenticate challenge value`),config:p.string().optional().describe(`Path to config file`),dryRun:p.boolean().optional().describe(`Validate and parse the challenge without signing`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`)}),output:p.object({authorization:p.string()}),alias:{account:`a`,challenge:`C`,config:`c`,methodOpt:`M`,rpcUrl:`r`},async run(e){let t=e.options.challenge||(pV()?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=RS(t)}catch(t){return e.error({code:`INVALID_CHALLENGE`,message:`Failed to parse challenge: ${t instanceof Error?t.message:t}`,exitCode:2})}if(e.options.dryRun){process.stderr.write(`Challenge is valid.
273
- `);return}let r=n.filter(e=>!TS(e));if(n.length>0&&r.length===0)return e.error({code:`LEGACY_UNICODE_ESCAPED_CHALLENGE`,message:new Zx().message,exitCode:2});let i=await tR(e.options.config),a=ZL(r,i?.config);if(!a){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:o,plugin:s,method:c}=a,l=kA(e.options.methodOpt),u=xS(o),d=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:u}}),f;s&&(f=await s.setup({challenge:o,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:l}));let p=await YL(o,i?.config.extensions,f?.credentialContext),m;if(f)m=f.createCredential?await f.createCredential(d,p):await JE({methods:f.methods,polyfill:!1}).createCredential(d,p);else if(c)m=await JE({methods:[c],polyfill:!1}).createCredential(d,p);else return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method: ${o.method}/${o.intent}. Add it to mppx.config.ts using defineConfig().`,exitCode:2});return dV(e,{authorization:m},()=>{console.log(m)})}}),BV=vb(`init`,{description:`Create an mppx.config.ts file in the current directory`,options:p.object({force:p.boolean().optional().describe(`Overwrite existing config file`)}),output:p.object({file:p.string()}),alias:{force:`f`},async run(e){let n=process.cwd(),r=`mppx.config${(()=>{if(t.existsSync(c.join(n,`tsconfig.json`)))return`.ts`;try{if(JSON.parse(t.readFileSync(c.join(n,`package.json`),`utf-8`)).type===`module`)return`.mjs`}catch{}return`.js`})()}`,i=c.join(n,r);return t.existsSync(i)&&!e.options.force?e.error({code:`CONFIG_EXISTS`,message:`${r} already exists. Use --force to overwrite.`,exitCode:1}):(t.writeFileSync(i,`import { defineConfig } from 'mppx/cli'
272
+ `)),!await vM(`Confirm delete?`)){console.log(`Canceled`);return}}await t.delete();let a=BM().get(),o;if(a===e.options.account){let e=await HM().list();e.length>0?(o=e[0],BM().set(o)):BM().clear()}return JH(e,{defaultAccount:o,name:e.options.account},()=>{o&&console.log(`Default account set to "${o}"`),console.log(`Account "${e.options.account}" deleted`)})}}).command(`fund`,{description:`Fund account with testnet tokens`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({account:p.string(),chain:p.string(),transactions:p.array(p.string())}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=qH(e),n=VM(e.options.account),r=await HM(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=R(r),a=xM(e.options),o=bM(e.options.rpcUrl,{network:a}),s=await SM({network:a,rpcUrl:o}),c=N({chain:s,transport:L(o)});t||console.log(`Funding "${n}" on ${CM(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?pM(`${o}/tx/${e}`,X.gray(e)):e;console.log(` ${t}`)}let{waitForTransactionReceipt:l}=await import(`viem/actions`);return await Promise.all(a.map(e=>l(c,{hash:e}))),JH(e,{account:n,chain:CM(s),transactions:[...a]},()=>{console.log(`Funded successfully`)})}catch(n){let r=n instanceof Error?n.message:String(n);return t?e.error({code:`FUNDING_FAILED`,message:r,exitCode:1}):e.error({code:`FUNDING_FAILED`,message:`Funding failed: ${r}`,exitCode:1})}}}).command(`list`,{description:`List all accounts`,output:p.object({accounts:p.array(HH)}),async run(e){let t=BM().get(),n=(await HM().list()).sort(),r=[];for(let e of n){let t=await HM(e).get();t&&r.push({name:e,address:R(t).address})}let i=yz();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 JH(e,{accounts:[]},()=>{console.log(`No accounts found.`)});let a=ve.blockExplorers?.default?.url,o=Math.max(...r.map(e=>e.name.length+ +(e.name===t)));return JH(e,{accounts:r.map(e=>({...e,...e.name===t?{isDefault:!0}:void 0}))},()=>{for(let e of r){let n=e.name===t,r=n?`${e.name}${X.dim(`*`)}`:e.name,i=e.name.length+ +!!n,s=a?pM(`${a}/address/${e.address}`,e.address):e.address,c=e.source?` ${X.dim(`(${e.source})`)}`:``;console.log(`${r}${` `.repeat(o-i+2)}${X.dim(s)}${c}`)}})}}).command(`export`,{description:`Export the private key for a local account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`)}),output:p.object({privateKey:p.string()}),alias:{account:`a`},async run(e){let t=VM(e.options.account);if(gM(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 HM(t).get();return n?JH(e,{privateKey:n},()=>{console.log(n)}):e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}}).command(`view`,{description:`View account address`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:UH,alias:{account:`a`,rpcUrl:`r`},async run(e){let t=VM(e.options.account);if(gM(t)){let n=bz(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=bM(e.options.rpcUrl,{network:e.options.network}),a=await SM({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?pM(`${o}/address/${r}`,r):r,c=await DM(r,a&&i?{chain:a,rpcUrl:i}:void 0);return JH(e,{address:r,balances:c,name:t,type:`${n.wallet_type} (tempo wallet)`},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`),console.log(`${X.dim(`Type`)} ${n.wallet_type} ${X.dim(`(tempo wallet)`)}`)})}let n=await HM(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=R(n),i=bM(e.options.rpcUrl,{network:e.options.network}),a=await SM({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?pM(`${o}/address/${r.address}`,r.address):r.address,c=await DM(r.address,a&&i?{chain:a,rpcUrl:i}:void 0);return JH(e,{address:r.address,balances:c,name:t},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`)})}}),SU=vb(`sign`,{description:`Sign a payment challenge and output the Authorization header`,usage:[{suffix:`--challenge <value> [options]`},{prefix:`echo <challenge> |`,suffix:`[options]`}],options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),challenge:p.string().optional().describe(`WWW-Authenticate challenge value`),config:p.string().optional().describe(`Path to config file`),dryRun:p.boolean().optional().describe(`Validate and parse the challenge without signing`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`)}),output:p.object({authorization:p.string()}),alias:{account:`a`,challenge:`C`,config:`c`,methodOpt:`M`,rpcUrl:`r`},async run(e){let t=e.options.challenge||(XH()?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=BS(t)}catch(t){return e.error({code:`INVALID_CHALLENGE`,message:`Failed to parse challenge: ${t instanceof Error?t.message:t}`,exitCode:2})}if(e.options.dryRun){process.stderr.write(`Challenge is valid.
273
+ `);return}let r=n.filter(e=>!DS(e));if(n.length>0&&r.length===0)return e.error({code:`LEGACY_UNICODE_ESCAPED_CHALLENGE`,message:new Qx().message,exitCode:2});let i=await Hz(e.options.config),a=Rz(r,i?.config);if(!a){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:o,plugin:s,method:c}=a,l=mM(e.options.methodOpt),u=CS(o),d=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:u}}),f;s&&(f=await s.setup({challenge:o,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:l}));let p=await Iz(o,i?.config.extensions,f?.credentialContext),m;if(f)m=f.createCredential?await f.createCredential(d,p):await jO({methods:f.methods,polyfill:!1}).createCredential(d,p);else if(c)m=await jO({methods:[c],polyfill:!1}).createCredential(d,p);else return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method: ${o.method}/${o.intent}. Add it to mppx.config.ts using defineConfig().`,exitCode:2});return JH(e,{authorization:m},()=>{console.log(m)})}}),CU=vb(`init`,{description:`Create an mppx.config.ts file in the current directory`,options:p.object({force:p.boolean().optional().describe(`Overwrite existing config file`)}),output:p.object({file:p.string()}),alias:{force:`f`},async run(e){let n=process.cwd(),r=`mppx.config${(()=>{if(t.existsSync(c.join(n,`tsconfig.json`)))return`.ts`;try{if(JSON.parse(t.readFileSync(c.join(n,`package.json`),`utf-8`)).type===`module`)return`.mjs`}catch{}return`.js`})()}`,i=c.join(n,r);return t.existsSync(i)&&!e.options.force?e.error({code:`CONFIG_EXISTS`,message:`${r} already exists. Use --force to overwrite.`,exitCode:1}):(t.writeFileSync(i,`import { defineConfig } from 'mppx/cli'
274
274
 
275
275
  export default defineConfig({
276
276
  methods: [],
277
277
  plugins: [],
278
278
  })
279
- `),dV(e,{file:i},()=>{console.log(`Created ${r}`)}))}}),VV=vb(`services`,{description:`Browse the MPP services registry`}).command(`list`,{description:`List registered MPP services`,options:p.object({query:p.string().optional().describe(`Filter by id, name, category, tag, or description`)}),output:p.object({services:p.array(cV)}),alias:{query:`q`},async run(e){let t=e.options.query?.toLowerCase(),n=await FV(),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(gV).sort((e,t)=>e.id.localeCompare(t.id));return dV(e,{services:r},()=>{if(r.length===0){console.log(`No services found.`);return}let e=Math.max(...r.map(e=>e.id.length)),t=Math.max(...r.map(e=>String(e.paidEndpoints).length));for(let n of r){let r=n.name&&n.name!==n.id?` ${n.name}`:``,i=n.url?` ${X.dim(n.url)}`:``;console.log(`${n.id.padEnd(e)} ${String(n.paidEndpoints).padStart(t)} paid${r}${i}`)}})}}).command(`show`,{description:`Show one registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({service:p.record(p.string(),p.unknown())}),async run(e){let t=IV(await FV(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=gV(t),r=hV(t);return dV(e,{service:t},()=>{console.log(`${n.name??n.id} ${X.dim(`(${n.id})`)}`),n.description&&console.log(n.description),n.url&&console.log(`${X.dim(`URL`)} ${OA(n.url,n.url)}`),n.status&&console.log(`${X.dim(`Status`)} ${n.status}`),console.log(`${X.dim(`Endpoints`)} ${r.length} (${n.paidEndpoints} paid)`);let e=t.docs,i=e&&mV(e.homepage);i&&console.log(`${X.dim(`Docs`)} ${OA(i,i)}`)})}}).command(`endpoints`,{description:`List endpoints for a registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({endpoints:p.array(lV),service:cV}),async run(e){let t=IV(await FV(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=gV(t),r=hV(t).map(_V);return dV(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=vV(n.payment),i=n.description?` ${X.dim(n.description)}`:``;console.log(`${n.method.padEnd(e)} ${n.path.padEnd(t)} ${r}${i}`)}})}}),HV=vb(`discover`,{description:`Discovery tooling`}).command(`generate`,{description:`Generate a static OpenAPI discovery document from a module`,args:p.object({module:p.string().describe(`Path to a module that default-exports a discovery config`)}),options:p.object({output:p.string().optional().describe(`Write output to a file instead of stdout`)}),output:p.record(p.string(),p.unknown()),alias:{output:`o`},async run(e){let n=c.resolve(e.args.module);if(!t.existsSync(n))return e.error({code:`MODULE_NOT_FOUND`,message:`Module not found: ${n}`,exitCode:1});let r;try{r=await import(n)}catch(t){return e.error({code:`MODULE_IMPORT_FAILED`,message:`Failed to import module: ${t.message}`,exitCode:1})}let i=r.default??r,a;if(typeof i.openapi==`string`)a=i;else{let{generate:t}=await Promise.resolve().then(()=>(rV(),ZB)),n=i.mppx;if(!n)return e.error({code:`INVALID_MODULE`,message:"Module must default-export an OpenAPI document (with `openapi` key) or an object with `mppx` (server instance) and `routes`.",exitCode:1});a=t(n,i)}let o=JSON.stringify(a,null,2);if(e.options.output){let n=c.resolve(e.options.output);return t.writeFileSync(n,`${o}\n`),process.stderr.write(`Wrote ${n}\n`),dV(e,a,()=>{})}return dV(e,a,()=>{console.log(o)})}}).command(`validate`,{description:`Validate an OpenAPI discovery document from a file or URL`,args:p.object({input:p.string().describe(`Path or URL to a discovery document`)}),output:p.object({errorCount:p.number(),issues:p.array(sV),valid:p.boolean(),warningCount:p.number()}),async run(e){let n=e.args.input,r;if(/^https?:\/\//.test(n)){let t=new AbortController,i=setTimeout(()=>t.abort(),3e4),a;try{a=await globalThis.fetch(n,{signal:t.signal})}catch(t){clearTimeout(i);let n=t instanceof DOMException&&t.name===`AbortError`?`Request timed out after 30s`:t.message;return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: ${n}`,exitCode:1})}if(clearTimeout(i),!a.ok)return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: HTTP ${a.status}`,exitCode:1});let o=10485760,s=a.headers.get(`content-length`);if(s&&Number(s)>o||(r=await a.text(),r.length>o))return e.error({code:`DISCOVERY_TOO_LARGE`,message:`Discovery document exceeds 10 MB limit`,exitCode:1})}else{let i=c.resolve(n);if(!t.existsSync(i))return e.error({code:`DISCOVERY_NOT_FOUND`,message:`Discovery document not found: ${i}`,exitCode:1});r=t.readFileSync(i,`utf-8`)}let i;try{i=JSON.parse(r)}catch(t){return e.error({code:`DISCOVERY_INVALID_JSON`,message:`Invalid discovery JSON: ${t.message}`,exitCode:1})}let a=DD(i);if(!uV(e))for(let e of a)console.log(`[${e.severity}] ${e.path}: ${e.message}`);let o=a.filter(e=>e.severity===`error`).length,s=a.filter(e=>e.severity===`warning`).length;return o>0?e.error({code:`DISCOVERY_INVALID`,message:`Discovery document has ${o} error(s) and ${s} warning(s).`,exitCode:1}):dV(e,{errorCount:o,issues:a,valid:!0,warningCount:s},()=>{console.log(s>0?`Discovery document is valid with ${s} warning(s).`:`Discovery document is valid.`)})}}),UV=p.object({address:p.string(),id:p.string(),livemode:p.boolean(),network:p.string(),supportedTokens:p.array(p.object({contractAddress:p.string(),currency:p.string()}))}),WV=vb(`stripe`,{description:`Stripe machine payments tooling`}).command(`address`,{description:`Create a Stripe crypto deposit address and print its public address`,usage:[{suffix:`[--network tempo|base|solana] [--env [path]] [--secret-key <key>] [options]`}],options:p.object({customer:p.string().optional().describe(`Scope the address to a Stripe customer (cus_...); it then only accepts their funds`),env:p.string().optional().describe(`Write <NETWORK>_DEPOSIT_ADDRESS to this env file instead of printing (default path: .env)`),live:p.boolean().optional().describe(`Use the Stripe CLI's live mode key instead of its test mode key`),network:p.enum([`tempo`,`base`,`solana`]).default(`tempo`).describe(`Network to create the address on`),projectName:p.string().optional().describe(`Stripe CLI project to read the key from (env: STRIPE_PROJECT_NAME, default: default)`),secretKey:p.string().optional().describe(`Stripe secret key (sk_...); else STRIPE_SECRET_KEY, else the Stripe CLI's login`),stripeAccount:p.string().optional().describe(`Connected account to create the address for (acct_...)`)}),output:UV,alias:{network:`n`},async run(e){let{customer:t,env:n,live:r,network:i,projectName:a,secretKey:o,stripeAccount:s}=e.options;if(n&&t)return e.error({code:`INVALID_OPTIONS`,message:`--env can't be combined with --customer: that address only accepts the customer's funds.`,exitCode:2});let c=Sz({live:r,projectName:a,secretKey:o});if(!c)return e.error({code:`MISSING_STRIPE_SECRET_KEY`,message:`No Stripe key found. Pass --secret-key <sk_...>, set STRIPE_SECRET_KEY, or run \`stripe login\` so mppx can read the Stripe CLI's ${r?`live`:`test`} mode key.`,exitCode:2});let l=new URLSearchParams({network:i});t&&l.set(`customer`,t);let u=await globalThis.fetch(new URL(`/v1/crypto/deposit_addresses`,process.env.MPPX_STRIPE_API_URL??`https://api.stripe.com`),{method:`POST`,headers:{Authorization:`Bearer ${c.key}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":OD,...s?{"Stripe-Account":s}:{}},body:l}),d=await u.json().catch(()=>({}));if(!u.ok||!d.address){let t=d.error?.code&&/^[a-z_]+$/.test(d.error.code)?`, ${d.error.code}`:``,n=`HTTP ${u.status}${t}`,r=u.status===401||u.status===403,i=c.source===`stripe-cli`?`the Stripe CLI's login`:c.source===`flag`?`--secret-key`:`STRIPE_SECRET_KEY`,a=r&&c.key.startsWith(`rk_`)?`Stripe refused the restricted key (rk_...) from ${i} for crypto deposit addresses (${n}). Pass a secret key with --secret-key <sk_...> or STRIPE_SECRET_KEY.`:r&&c.source===`stripe-cli`?`Stripe refused the key from the Stripe CLI's login (${n}). Run \`stripe login\` again, or pass --secret-key <sk_...>.`:`Stripe could not create a deposit address (${n}).`;return e.error({code:`STRIPE_REQUEST_FAILED`,message:a,exitCode:1})}if(!Oz(i,d.address))return e.error({code:`STRIPE_INVALID_ADDRESS`,message:`Stripe returned a deposit address that isn't a valid ${i} address.`,exitCode:1});let f={address:d.address,id:d.id??``,livemode:d.livemode??!1,network:d.network??i,supportedTokens:(d.supported_tokens??[]).map(e=>({contractAddress:e.token_contract_address,currency:e.token_currency}))};if(n){let t=`${i.toUpperCase()}_DEPOSIT_ADDRESS`;return Az(n,t,f.address),console.error(`Wrote ${t} to ${n}`),dV(e,f,()=>{})}return dV(e,f,()=>console.log(f.address))}});LV.command(RV),LV.command(HV),LV.command(BV),LV.command(VV),LV.command(fz),LV.command(zV),LV.command(WV),LV.command(WB);const GV=LV.serve.bind(LV);LV.serve=(e=process.argv.slice(2),t)=>GV(Nz(e),t);export{LV as default,AV as resolveMppCredentialTarget,jV as resolveX402CredentialTarget};
279
+ `),JH(e,{file:i},()=>{console.log(`Created ${r}`)}))}}),wU=vb(`services`,{description:`Browse the MPP services registry`}).command(`list`,{description:`List registered MPP services`,options:p.object({query:p.string().optional().describe(`Filter by id, name, category, tag, or description`)}),output:p.object({services:p.array(GH)}),alias:{query:`q`},async run(e){let t=e.options.query?.toLowerCase(),n=await vU(),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($H).sort((e,t)=>e.id.localeCompare(t.id));return JH(e,{services:r},()=>{if(r.length===0){console.log(`No services found.`);return}let e=Math.max(...r.map(e=>e.id.length)),t=Math.max(...r.map(e=>String(e.paidEndpoints).length));for(let n of r){let r=n.name&&n.name!==n.id?` ${n.name}`:``,i=n.url?` ${X.dim(n.url)}`:``;console.log(`${n.id.padEnd(e)} ${String(n.paidEndpoints).padStart(t)} paid${r}${i}`)}})}}).command(`show`,{description:`Show one registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({service:p.record(p.string(),p.unknown())}),async run(e){let t=yU(await vU(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=$H(t),r=QH(t);return JH(e,{service:t},()=>{console.log(`${n.name??n.id} ${X.dim(`(${n.id})`)}`),n.description&&console.log(n.description),n.url&&console.log(`${X.dim(`URL`)} ${pM(n.url,n.url)}`),n.status&&console.log(`${X.dim(`Status`)} ${n.status}`),console.log(`${X.dim(`Endpoints`)} ${r.length} (${n.paidEndpoints} paid)`);let e=t.docs,i=e&&ZH(e.homepage);i&&console.log(`${X.dim(`Docs`)} ${pM(i,i)}`)})}}).command(`endpoints`,{description:`List endpoints for a registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({endpoints:p.array(KH),service:GH}),async run(e){let t=yU(await vU(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=$H(t),r=QH(t).map(eU);return JH(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=tU(n.payment),i=n.description?` ${X.dim(n.description)}`:``;console.log(`${n.method.padEnd(e)} ${n.path.padEnd(t)} ${r}${i}`)}})}}),TU=vb(`discover`,{description:`Discovery tooling`}).command(`generate`,{description:`Generate a static OpenAPI discovery document from a module`,args:p.object({module:p.string().describe(`Path to a module that default-exports a discovery config`)}),options:p.object({output:p.string().optional().describe(`Write output to a file instead of stdout`)}),output:p.record(p.string(),p.unknown()),alias:{output:`o`},async run(e){let n=c.resolve(e.args.module);if(!t.existsSync(n))return e.error({code:`MODULE_NOT_FOUND`,message:`Module not found: ${n}`,exitCode:1});let r;try{r=await import(n)}catch(t){return e.error({code:`MODULE_IMPORT_FAILED`,message:`Failed to import module: ${t.message}`,exitCode:1})}let i=r.default??r,a;if(typeof i.openapi==`string`)a=i;else{let{generate:t}=await Promise.resolve().then(()=>(BH(),PH)),n=i.mppx;if(!n)return e.error({code:`INVALID_MODULE`,message:"Module must default-export an OpenAPI document (with `openapi` key) or an object with `mppx` (server instance) and `routes`.",exitCode:1});a=t(n,i)}let o=JSON.stringify(a,null,2);if(e.options.output){let n=c.resolve(e.options.output);return t.writeFileSync(n,`${o}\n`),process.stderr.write(`Wrote ${n}\n`),JH(e,a,()=>{})}return JH(e,a,()=>{console.log(o)})}}).command(`validate`,{description:`Validate an OpenAPI discovery document from a file or URL`,args:p.object({input:p.string().describe(`Path or URL to a discovery document`)}),output:p.object({errorCount:p.number(),issues:p.array(WH),valid:p.boolean(),warningCount:p.number()}),async run(e){let n=e.args.input,r;if(/^https?:\/\//.test(n)){let t=new AbortController,i=setTimeout(()=>t.abort(),3e4),a;try{a=await globalThis.fetch(n,{signal:t.signal})}catch(t){clearTimeout(i);let n=t instanceof DOMException&&t.name===`AbortError`?`Request timed out after 30s`:t.message;return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: ${n}`,exitCode:1})}if(clearTimeout(i),!a.ok)return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: HTTP ${a.status}`,exitCode:1});let o=10485760,s=a.headers.get(`content-length`);if(s&&Number(s)>o||(r=await a.text(),r.length>o))return e.error({code:`DISCOVERY_TOO_LARGE`,message:`Discovery document exceeds 10 MB limit`,exitCode:1})}else{let i=c.resolve(n);if(!t.existsSync(i))return e.error({code:`DISCOVERY_NOT_FOUND`,message:`Discovery document not found: ${i}`,exitCode:1});r=t.readFileSync(i,`utf-8`)}let i;try{i=JSON.parse(r)}catch(t){return e.error({code:`DISCOVERY_INVALID_JSON`,message:`Invalid discovery JSON: ${t.message}`,exitCode:1})}let a=dk(i);if(!qH(e))for(let e of a)console.log(`[${e.severity}] ${e.path}: ${e.message}`);let o=a.filter(e=>e.severity===`error`).length,s=a.filter(e=>e.severity===`warning`).length;return o>0?e.error({code:`DISCOVERY_INVALID`,message:`Discovery document has ${o} error(s) and ${s} warning(s).`,exitCode:1}):JH(e,{errorCount:o,issues:a,valid:!0,warningCount:s},()=>{console.log(s>0?`Discovery document is valid with ${s} warning(s).`:`Discovery document is valid.`)})}}),EU=p.object({address:p.string(),id:p.string(),livemode:p.boolean(),network:p.string(),supportedTokens:p.array(p.object({contractAddress:p.string(),currency:p.string()}))}),DU=vb(`stripe`,{description:`Stripe machine payments tooling`}).command(`address`,{description:`Create a Stripe crypto deposit address and print its public address`,usage:[{suffix:`[--network tempo|base|solana] [--env [path]] [--secret-key <key>] [options]`}],options:p.object({customer:p.string().optional().describe(`Scope the address to a Stripe customer (cus_...); it then only accepts their funds`),env:p.string().optional().describe(`Write <NETWORK>_DEPOSIT_ADDRESS to this env file instead of printing (default path: .env)`),live:p.boolean().optional().describe(`Use the Stripe CLI's live mode key instead of its test mode key`),network:p.enum([`tempo`,`base`,`solana`]).default(`tempo`).describe(`Network to create the address on`),projectName:p.string().optional().describe(`Stripe CLI project to read the key from (env: STRIPE_PROJECT_NAME, default: default)`),secretKey:p.string().optional().describe(`Stripe secret key (sk_...); else STRIPE_SECRET_KEY, else the Stripe CLI's login`),stripeAccount:p.string().optional().describe(`Connected account to create the address for (acct_...)`)}),output:EU,alias:{network:`n`},async run(e){let{customer:t,env:n,live:r,network:i,projectName:a,secretKey:o,stripeAccount:s}=e.options;if(n&&t)return e.error({code:`INVALID_OPTIONS`,message:`--env can't be combined with --customer: that address only accepts the customer's funds.`,exitCode:2});let c=lV({live:r,projectName:a,secretKey:o});if(!c)return e.error({code:`MISSING_STRIPE_SECRET_KEY`,message:`No Stripe key found. Pass --secret-key <sk_...>, set STRIPE_SECRET_KEY, or run \`stripe login\` so mppx can read the Stripe CLI's ${r?`live`:`test`} mode key.`,exitCode:2});let l=new URLSearchParams({network:i});t&&l.set(`customer`,t);let u=await globalThis.fetch(new URL(`/v1/crypto/deposit_addresses`,process.env.MPPX_STRIPE_API_URL??`https://api.stripe.com`),{method:`POST`,headers:{Authorization:`Bearer ${c.key}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":fk,...s?{"Stripe-Account":s}:{}},body:l}),d=await u.json().catch(()=>({}));if(!u.ok||!d.address){let t=d.error?.code&&/^[a-z_]+$/.test(d.error.code)?`, ${d.error.code}`:``,n=`HTTP ${u.status}${t}`,r=u.status===401||u.status===403,i=c.source===`stripe-cli`?`the Stripe CLI's login`:c.source===`flag`?`--secret-key`:`STRIPE_SECRET_KEY`,a=r&&c.key.startsWith(`rk_`)?`Stripe refused the restricted key (rk_...) from ${i} for crypto deposit addresses (${n}). Pass a secret key with --secret-key <sk_...> or STRIPE_SECRET_KEY.`:r&&c.source===`stripe-cli`?`Stripe refused the key from the Stripe CLI's login (${n}). Run \`stripe login\` again, or pass --secret-key <sk_...>.`:`Stripe could not create a deposit address (${n}).`;return e.error({code:`STRIPE_REQUEST_FAILED`,message:a,exitCode:1})}if(!hV(i,d.address))return e.error({code:`STRIPE_INVALID_ADDRESS`,message:`Stripe returned a deposit address that isn't a valid ${i} address.`,exitCode:1});let f={address:d.address,id:d.id??``,livemode:d.livemode??!1,network:d.network??i,supportedTokens:(d.supported_tokens??[]).map(e=>({contractAddress:e.token_contract_address,currency:e.token_currency}))};if(n){let t=`${i.toUpperCase()}_DEPOSIT_ADDRESS`;return _V(n,t,f.address),console.error(`Wrote ${t} to ${n}`),JH(e,f,()=>{})}return JH(e,f,()=>console.log(f.address))}});bU.command(xU),bU.command(TU),bU.command(CU),bU.command(wU),bU.command($B),bU.command(SU),bU.command(DU),bU.command(DH);const OU=bU.serve.bind(bU);bU.serve=(e=process.argv.slice(2),t)=>OU(bV(e),t);export{bU as default,pU as resolveMppCredentialTarget,mU as resolveX402CredentialTarget};