mppx 0.13.3 → 0.13.5

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 (48) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/Errors.d.ts +63 -2
  3. package/dist/Errors.js +52 -2
  4. package/dist/Method.d.ts +10 -0
  5. package/dist/cli/cli.js +133 -133
  6. package/dist/cli/plugins/index.js +12 -12
  7. package/dist/cli/validate/helpers.d.ts +1 -0
  8. package/dist/cli/validate/helpers.js +2 -1
  9. package/dist/client/Mppx.d.ts +2 -0
  10. package/dist/client/Mppx.js +8 -10
  11. package/dist/client/internal/Fetch.js +107 -8
  12. package/dist/client/internal/MethodResponse.d.ts +6 -0
  13. package/dist/client/internal/MethodResponse.js +16 -0
  14. package/dist/client/internal/protocols/Mcp.js +36 -5
  15. package/dist/evm/server/Charge.js +3 -1
  16. package/dist/internal/version.d.ts +2 -2
  17. package/dist/internal/version.js +1 -1
  18. package/dist/internal/warnOnce.d.ts +3 -0
  19. package/dist/internal/warnOnce.js +9 -0
  20. package/dist/server/Mppx.d.ts +6 -1
  21. package/dist/server/Mppx.js +20 -16
  22. package/dist/server/Transport.js +10 -0
  23. package/dist/server/internal/challengeMeta.d.ts +5 -0
  24. package/dist/server/internal/challengeMeta.js +14 -0
  25. package/dist/tempo/Attribution.d.ts +24 -9
  26. package/dist/tempo/Attribution.js +25 -5
  27. package/dist/tempo/client/Charge.d.ts +116 -10
  28. package/dist/tempo/client/Charge.js +116 -22
  29. package/dist/tempo/client/Methods.d.ts +88 -9
  30. package/dist/tempo/index.d.ts +1 -0
  31. package/dist/tempo/index.js +1 -0
  32. package/dist/tempo/internal/fee-payer.js +4 -0
  33. package/dist/tempo/server/Charge.d.ts +11 -0
  34. package/dist/tempo/server/Charge.js +160 -29
  35. package/dist/tempo/server/Methods.d.ts +5 -0
  36. package/dist/tempo/server/Methods.js +18 -4
  37. package/dist/tempo/server/Subscription.js +2 -1
  38. package/dist/tempo/server/internal/fallback-store.d.ts +9 -0
  39. package/dist/tempo/server/internal/fallback-store.js +13 -0
  40. package/dist/tempo/server/internal/html.gen.js +1 -1
  41. package/dist/tempo/session/client/Transports.js +39 -12
  42. package/dist/tempo/session/precompile/Chain.d.ts +4 -0
  43. package/dist/tempo/session/precompile/Chain.js +4 -1
  44. package/dist/tempo/session/server/Session.js +12 -11
  45. package/dist/tempo/session/server/Settlement.d.ts +7 -0
  46. package/dist/tempo/session/server/Settlement.js +33 -8
  47. package/dist/x402/server/EvmCharge.js +10 -3
  48. 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}from"node:child_process";import{createHash as g,randomUUID as _}from"node:crypto";import*as v from"node:util";import*as y from"node:zlib";import*as b from"node:os";import x,{homedir as S}from"node:os";import*as C from"node:fs/promises";import w from"node:fs/promises";import{PassThrough as T}from"node:stream";import{fileURLToPath as ee,pathToFileURL as E}from"node:url";import*as D from"zod/v4";import{AbiParameters as O,Base64 as k,Bytes as te,Hash as ne,Hex as re,Json as A}from"ox";import{createClient as j,createTransport as ie,custom as ae,encodeFunctionData as oe,erc20Abi as se,formatUnits as ce,getAddress as M,hashTypedData as le,http as ue,isAddress as de,isAddressEqual as fe,parseAbi as pe,parseUnits as N,zeroAddress as me}from"viem";import{generatePrivateKey as he,parseAccount as ge,privateKeyToAccount as _e}from"viem/accounts";import{tempo as ve,tempoModerato as ye}from"viem/tempo/chains";import{z as be}from"zod/mini";import{createParser as xe}from"eventsource-parser";import*as P from"node:readline";import{ousd as Se,pathusd as Ce,usdce as we}from"viem/tokens";import{call as Te,prepareTransactionRequest as Ee,readContract as De,sendCallsSync as Oe,sendTransactionSync as ke,signTransaction as Ae,signTypedData as je,waitForTransactionReceipt as Me}from"viem/actions";import{Abis as Ne,Account as Pe,Actions as Fe,Addresses as Ie,TokenId as Le,Transaction as Re,withFeePayer as ze}from"viem/tempo";import*as Be from"viem/chains";import{tempo as Ve}from"viem/chains";import{Channel as He,KeyAuthorization as Ue,SignatureEnvelope as We,TempoAddress as Ge,TxEnvelopeTempo as Ke}from"ox/tempo";var qe=Object.defineProperty,Je=Object.getOwnPropertyDescriptor,Ye=Object.getOwnPropertyNames,Xe=Object.prototype.hasOwnProperty,F=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},Ze=(e,t)=>{let n={};for(var r in e)qe(n,r,{get:e[r],enumerable:!0});return t||qe(n,Symbol.toStringTag,{value:`Module`}),n},Qe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ye(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Xe.call(e,s)&&s!==n&&qe(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Je(t,s))||r.enumerable});return e},$e=(e,t,n)=>(Qe(e,t,`default`),n&&Qe(n,t,`default`));function et(){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 tt(){let e=et();return e===`pnpm`?`pnpx`:e===`bun`?`bunx`:`npx`}function nt(e){let t=et();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 rt=F((()=>{}));function it(e,t={}){if(bt())return;let n=ct(e,t);if(!n?.check||!n.current)return;let r=mt(n.key),i=ht(r),a=Date.now(),o=Math.max(0,t.interval??xt);if((!i||a-i.checkedAt>=o)&&_t(r,a,i?.latest,t.binary),!(!i?.latest||!st(i.latest,n.current)))return{current:n.current,latest:i.latest,name:n.name}}async function at(e,t={}){let n=ct(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||!ft(r)||gt(mt(n.key),{checkedAt:Date.now(),latest:r})}async function ot(e,t={}){let n=ct(e,t);if(!n?.install)throw Error(`No update installer is configured for '${e}'.`);let r=ht(mt(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 st(e,t){let n=ft(e),r=ft(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 ct(e,t){let n=lt(e),r=t.package??n?.name;if(r&&!pt(r))return;let i=t.version??n?.version,a=r?nt(r):void 0,o=t.check??(r?()=>dt(r):void 0),s=t.install??(a?()=>yt(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 lt(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`&&ut(n,e))return{name:n.name,version:n.version}}catch{}let n=c.dirname(r);if(n===r)return;r=n}}function ut(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 dt(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 ft(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 pt(e){return/^(?:@[A-Za-z0-9][A-Za-z0-9._~-]*\/)?[A-Za-z0-9][A-Za-z0-9._~-]*$/.test(e)}function mt(e){let t=process.env.XDG_CACHE_HOME||c.join(b.homedir(),`.cache`);return c.join(t,`incur`,`updates`,`${encodeURIComponent(e)}.json`)}function ht(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 gt(e,n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,JSON.stringify(n)+`
2
- `)}function _t(e,t,n,r){let i=vt(r);if(i)try{gt(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 vt(e){if(e)return{args:[St],command:process.execPath};let n=process.argv[1];if(n){if(n.startsWith(`/$bunfs/`))return{args:[St],command:process.execPath};try{if(t.realpathSync(n)===t.realpathSync(process.execPath))return{args:[St],command:process.execPath}}catch{}return{args:[...process.execArgv,n,St],command:process.execPath}}}function yt(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 bt(){return process.env.NO_UPDATE_NOTIFIER||process.env.npm_config_update_notifier===`false`?!0:!!(process.env.CI&&process.env.CI!==`false`)}var xt,St,Ct=F((()=>{rt(),xt=864e5,St=`--incur-update-check`}));async function wt(e=process.argv.slice(2)){if(e[0]!==`--incur-binary-apply`)return process.platform===`win32`&&It&&Lt&&Rt&&await At(process.execPath),!1;if(process.platform!==`win32`)throw Error(`${Ft} is only supported on Windows.`);if(e.length!==2||!e[1])throw Error(`Invalid ${Ft} arguments.`);let t=Number(e[1]);if(!Number.isSafeInteger(t)||t<=0)throw Error(`Invalid ${Ft} arguments.`);return await Tt(t),!0}async function Tt(e){let n=Et(process.execPath,e),r=!1;try{await Dt(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}': ${Nt(t)}`,{cause:e})}}throw await jt(n,i,a),i}await Mt(n.backup),await Mt(n.error),await Mt(n.staged),await Mt(n.helper)}function Et(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 Dt(e){let t=Date.now()+Pt;for(;Ot(e);){if(Date.now()>=t)throw Error(`Timed out waiting for update process ${e} to exit.`);await kt(100)}}function Ot(e){try{return process.kill(e,0),!0}catch(e){return e.code!==`ESRCH`}}function kt(e){return new Promise(t=>setTimeout(t,e))}async function At(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=>Mt(c.join(n,e))))}catch{}}async function jt(e,n,r){let i=[`Binary update failed: ${Nt(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 Mt(e){try{await t.promises.unlink(e)}catch{}}function Nt(e){return e instanceof Error?e.message:String(e)}var Pt,Ft,It,Lt,Rt,zt=F((()=>{Pt=6e4,v.promisify(y.gunzip),Ft=`--incur-binary-apply`,It=typeof __INCUR_BINARY_NAME__==`string`&&__INCUR_BINARY_NAME__?__INCUR_BINARY_NAME__:void 0,Lt=typeof __INCUR_BINARY_TARGET__==`string`&&__INCUR_BINARY_TARGET__?__INCUR_BINARY_TARGET__:void 0,Rt=typeof __INCUR_BINARY_VERSION__==`string`&&__INCUR_BINARY_VERSION__?__INCUR_BINARY_VERSION__:void 0}));function*Bt(e,t={}){if(!e)return;let n=Vt(t);for(let t of e.split(Xt))t&&(yield{segment:t,tokenCount:Ht(t,n)})}function Vt(e){return{defaultCharsPerToken:e.defaultCharsPerToken??Zt,languageConfigs:e.languageConfigs??en}}function Ht(e,{languageConfigs:t,defaultCharsPerToken:n}){if(Yt.whitespace.test(e))return+!!Yt.structuredWhitespace.test(e);let r=Ut(e,t);return r===void 0?Yt.cjk.test(e)?Gt(e):Yt.numeric.test(e)?Math.ceil(e.length/3):e.length<=Qt?1:Yt.punctuation.test(e)?Math.ceil(e.length/2):Math.ceil(e.length/n):Math.ceil(Wt(e)/r)}function Ut(e,t){for(let n of t)if(e.search(n.pattern)!==-1)return n.averageCharsPerToken}function Wt(e){return Array.from(e).length}function Gt(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/$t)}function Kt(e,t={}){if(!e)return 0;let n=0;for(let r of Bt(e,t))n+=r.tokenCount;return n}function qt(e,t=0,n,r={}){if(!e)return``;let i=Bt(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=Jt(e,l,t,o,s);n&&c.push(n),l+=t}return c.join(``)}function Jt(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 Yt,Xt,Zt,Qt,$t,en,tn=F((()=>{Yt={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:/[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_"-]/},Xt=RegExp(`(\\s+|${Yt.punctuation.source}+)`),Zt=6,Qt=3,$t=1.35,en=[{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 nn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rn(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function an(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 on(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=an(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 sn=F((()=>{}));function cn(e,t){switch(e){case`bash`:return _n(t);case`zsh`:return vn(t);case`fish`:return yn(t);case`nushell`:return bn(t)}}function ln(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=`--${rn(e)}`;n.startsWith(a)&&s.push({value:n,description:hn(t[e])})}if(e.alias)for(let[n,r]of Object.entries(e.alias)){let e=`-${r}`;if(e.startsWith(a)){let r=hn(t[n]);s.push({value:e,description:r})}}}if(i){let e=i.schema.shape;for(let t of Object.keys(e)){let n=`--${rn(t)}`;n.startsWith(a)&&!s.some(e=>e.value===n)&&s.push({value:n,description:hn(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=hn(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=dn(e,t);if(n){let e=pn(n,t.options);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!fn(n,t.options))return s}}if(i){let t=dn(e,{options:i.schema,alias:i.alias});if(t){let e=pn(t,i.schema);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!fn(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 un(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}from"node:child_process";import{createHash as g,randomUUID as _}from"node:crypto";import*as v from"node:util";import*as y from"node:zlib";import*as b from"node:os";import x,{homedir as S}from"node:os";import*as C from"node:fs/promises";import w from"node:fs/promises";import{PassThrough as T}from"node:stream";import{fileURLToPath as ee,pathToFileURL as E}from"node:url";import*as D from"zod/v4";import{AbiParameters as O,Base64 as k,Bytes as te,Hash as ne,Hex as re,Json as A}from"ox";import{createClient as j,createTransport as ie,custom as ae,encodeFunctionData as oe,erc20Abi as se,formatUnits as ce,getAddress as M,hashTypedData as le,http as ue,isAddress as de,isAddressEqual as fe,keccak256 as pe,parseAbi as me,parseUnits as N,zeroAddress as he}from"viem";import{generatePrivateKey as ge,parseAccount as _e,privateKeyToAccount as ve}from"viem/accounts";import{tempo as ye,tempoModerato as be}from"viem/tempo/chains";import{z as xe}from"zod/mini";import{createParser as P}from"eventsource-parser";import*as Se from"node:readline";import{ousd as Ce,pathusd as we,usdce as Te}from"viem/tokens";import{call as Ee,prepareTransactionRequest as De,readContract as Oe,sendCallsSync as ke,sendTransactionSync as Ae,signTransaction as je,signTypedData as Me,waitForTransactionReceipt as Ne}from"viem/actions";import{Abis as Pe,Account as Fe,Actions as Ie,Addresses as Le,TokenId as Re,Transaction as ze,withFeePayer as Be}from"viem/tempo";import*as Ve from"viem/chains";import{tempo as He}from"viem/chains";import{Channel as Ue,KeyAuthorization as We,SignatureEnvelope as Ge,TempoAddress as Ke,TxEnvelopeTempo as qe}from"ox/tempo";var Je=Object.defineProperty,Ye=Object.getOwnPropertyDescriptor,Xe=Object.getOwnPropertyNames,Ze=Object.prototype.hasOwnProperty,F=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},Qe=(e,t)=>{let n={};for(var r in e)Je(n,r,{get:e[r],enumerable:!0});return t||Je(n,Symbol.toStringTag,{value:`Module`}),n},$e=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Xe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ze.call(e,s)&&s!==n&&Je(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ye(t,s))||r.enumerable});return e},et=(e,t,n)=>($e(e,t,`default`),n&&$e(n,t,`default`));function tt(){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 nt(){let e=tt();return e===`pnpm`?`pnpx`:e===`bun`?`bunx`:`npx`}function rt(e){let t=tt();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 it=F((()=>{}));function at(e,t={}){if(xt())return;let n=lt(e,t);if(!n?.check||!n.current)return;let r=ht(n.key),i=gt(r),a=Date.now(),o=Math.max(0,t.interval??St);if((!i||a-i.checkedAt>=o)&&vt(r,a,i?.latest,t.binary),!(!i?.latest||!ct(i.latest,n.current)))return{current:n.current,latest:i.latest,name:n.name}}async function ot(e,t={}){let n=lt(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||!pt(r)||_t(ht(n.key),{checkedAt:Date.now(),latest:r})}async function st(e,t={}){let n=lt(e,t);if(!n?.install)throw Error(`No update installer is configured for '${e}'.`);let r=gt(ht(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 ct(e,t){let n=pt(e),r=pt(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 lt(e,t){let n=ut(e),r=t.package??n?.name;if(r&&!mt(r))return;let i=t.version??n?.version,a=r?rt(r):void 0,o=t.check??(r?()=>ft(r):void 0),s=t.install??(a?()=>bt(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 ut(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`&&dt(n,e))return{name:n.name,version:n.version}}catch{}let n=c.dirname(r);if(n===r)return;r=n}}function dt(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 ft(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 pt(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 mt(e){return/^(?:@[A-Za-z0-9][A-Za-z0-9._~-]*\/)?[A-Za-z0-9][A-Za-z0-9._~-]*$/.test(e)}function ht(e){let t=process.env.XDG_CACHE_HOME||c.join(b.homedir(),`.cache`);return c.join(t,`incur`,`updates`,`${encodeURIComponent(e)}.json`)}function gt(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 _t(e,n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,JSON.stringify(n)+`
2
+ `)}function vt(e,t,n,r){let i=yt(r);if(i)try{_t(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 yt(e){if(e)return{args:[Ct],command:process.execPath};let n=process.argv[1];if(n){if(n.startsWith(`/$bunfs/`))return{args:[Ct],command:process.execPath};try{if(t.realpathSync(n)===t.realpathSync(process.execPath))return{args:[Ct],command:process.execPath}}catch{}return{args:[...process.execArgv,n,Ct],command:process.execPath}}}function bt(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 xt(){return process.env.NO_UPDATE_NOTIFIER||process.env.npm_config_update_notifier===`false`?!0:!!(process.env.CI&&process.env.CI!==`false`)}var St,Ct,wt=F((()=>{it(),St=864e5,Ct=`--incur-update-check`}));async function Tt(e=process.argv.slice(2)){if(e[0]!==`--incur-binary-apply`)return process.platform===`win32`&&Lt&&Rt&&zt&&await jt(process.execPath),!1;if(process.platform!==`win32`)throw Error(`${It} is only supported on Windows.`);if(e.length!==2||!e[1])throw Error(`Invalid ${It} arguments.`);let t=Number(e[1]);if(!Number.isSafeInteger(t)||t<=0)throw Error(`Invalid ${It} arguments.`);return await Et(t),!0}async function Et(e){let n=Dt(process.execPath,e),r=!1;try{await Ot(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}': ${Pt(t)}`,{cause:e})}}throw await Mt(n,i,a),i}await Nt(n.backup),await Nt(n.error),await Nt(n.staged),await Nt(n.helper)}function Dt(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 Ot(e){let t=Date.now()+Ft;for(;kt(e);){if(Date.now()>=t)throw Error(`Timed out waiting for update process ${e} to exit.`);await At(100)}}function kt(e){try{return process.kill(e,0),!0}catch(e){return e.code!==`ESRCH`}}function At(e){return new Promise(t=>setTimeout(t,e))}async function jt(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=>Nt(c.join(n,e))))}catch{}}async function Mt(e,n,r){let i=[`Binary update failed: ${Pt(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 Nt(e){try{await t.promises.unlink(e)}catch{}}function Pt(e){return e instanceof Error?e.message:String(e)}var Ft,It,Lt,Rt,zt,Bt=F((()=>{Ft=6e4,v.promisify(y.gunzip),It=`--incur-binary-apply`,Lt=typeof __INCUR_BINARY_NAME__==`string`&&__INCUR_BINARY_NAME__?__INCUR_BINARY_NAME__:void 0,Rt=typeof __INCUR_BINARY_TARGET__==`string`&&__INCUR_BINARY_TARGET__?__INCUR_BINARY_TARGET__:void 0,zt=typeof __INCUR_BINARY_VERSION__==`string`&&__INCUR_BINARY_VERSION__?__INCUR_BINARY_VERSION__:void 0}));function*Vt(e,t={}){if(!e)return;let n=Ht(t);for(let t of e.split(Zt))t&&(yield{segment:t,tokenCount:Ut(t,n)})}function Ht(e){return{defaultCharsPerToken:e.defaultCharsPerToken??Qt,languageConfigs:e.languageConfigs??tn}}function Ut(e,{languageConfigs:t,defaultCharsPerToken:n}){if(Xt.whitespace.test(e))return+!!Xt.structuredWhitespace.test(e);let r=Wt(e,t);return r===void 0?Xt.cjk.test(e)?Kt(e):Xt.numeric.test(e)?Math.ceil(e.length/3):e.length<=$t?1:Xt.punctuation.test(e)?Math.ceil(e.length/2):Math.ceil(e.length/n):Math.ceil(Gt(e)/r)}function Wt(e,t){for(let n of t)if(e.search(n.pattern)!==-1)return n.averageCharsPerToken}function Gt(e){return Array.from(e).length}function Kt(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/en)}function qt(e,t={}){if(!e)return 0;let n=0;for(let r of Vt(e,t))n+=r.tokenCount;return n}function Jt(e,t=0,n,r={}){if(!e)return``;let i=Vt(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=Yt(e,l,t,o,s);n&&c.push(n),l+=t}return c.join(``)}function Yt(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 Xt,Zt,Qt,$t,en,tn,nn=F((()=>{Xt={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:/[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_"-]/},Zt=RegExp(`(\\s+|${Xt.punctuation.source}+)`),Qt=6,$t=3,en=1.35,tn=[{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 rn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function an(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function on(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 sn(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=on(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 cn=F((()=>{}));function ln(e,t){switch(e){case`bash`:return vn(t);case`zsh`:return yn(t);case`fish`:return bn(t);case`nushell`:return xn(t)}}function un(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=`--${an(e)}`;n.startsWith(a)&&s.push({value:n,description:gn(t[e])})}if(e.alias)for(let[n,r]of Object.entries(e.alias)){let e=`-${r}`;if(e.startsWith(a)){let r=gn(t[n]);s.push({value:e,description:r})}}}if(i){let e=i.schema.shape;for(let t of Object.keys(e)){let n=`--${an(t)}`;n.startsWith(a)&&!s.some(e=>e.value===n)&&s.push({value:n,description:gn(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=gn(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=fn(e,t);if(n){let e=mn(n,t.options);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!pn(n,t.options))return s}}if(i){let t=fn(e,{options:i.schema,alias:i.alias});if(t){let e=mn(t,i.schema);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!pn(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 dn(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 dn(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 fn(e,t){let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0||mn(n).constructor.name===`ZodBoolean`:!1}function pn(e,t){let n=t.shape[e];if(!n)return;let r=mn(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 mn(e){let t=e;for(;t._zod?.def?.innerType;)t=t._zod.def.innerType;return t}function hn(e){if(e)return e.description}function gn(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`)}function _n(e){let t=gn(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 fn(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 pn(e,t){let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0||hn(n).constructor.name===`ZodBoolean`:!1}function mn(e,t){let n=t.shape[e];if(!n)return;let r=hn(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 hn(e){let t=e;for(;t._zod?.def?.innerType;)t=t._zod.def.innerType;return t}function gn(e){if(e)return e.description}function _n(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`)}function vn(e){let t=_n(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 vn(e){let t=gn(e);return`#compdef ${e}
32
+ complete -o default -o bashdefault -o nosort -F _incur_complete_${t} ${e}`}function yn(e){let t=_n(e);return`#compdef ${e}
33
33
  _incur_complete_${t}() {
34
34
  local completions=("\${(@f)$(
35
35
  export _COMPLETE_INDEX=$(( CURRENT - 1 ))
@@ -40,62 +40,62 @@ _incur_complete_${t}() {
40
40
  _describe 'values' completions -S ''
41
41
  fi
42
42
  }
43
- compdef _incur_complete_${t} ${e}`}function yn(e){return`complete --keep-order --exclusive --command ${e} \\
44
- --arguments "(COMPLETE=fish ${e} -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))"`}function bn(e){return`# External completer for ${e}
43
+ compdef _incur_complete_${t} ${e}`}function bn(e){return`complete --keep-order --exclusive --command ${e} \\
44
+ --arguments "(COMPLETE=fish ${e} -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))"`}function xn(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_${gn(e)} = {|spans|
46
+ let _incur_complete_${_n(e)} = {|spans|
47
47
  COMPLETE=nushell ${e} -- ...$spans | from json
48
- }`}var xn=F((()=>{sn()}));function Sn(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 Cn,I,wn,Tn,En=F((()=>{Cn=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 Sn(this,e)}},I=class extends Cn{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}},wn=class extends Cn{name=`Incur.ValidationError`;fieldErrors;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.fieldErrors=e.fieldErrors??[]}},Tn=class extends Cn{name=`Incur.ParseError`;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0)}}}));function Dn(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);Mn.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}`);Mn.has(t)?s(t,i):r.set(t,i),o+=2}}else if(n.startsWith(`-`)&&n.length===2){let t=n[1],r=Nn[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 On(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 kn(e){return e.body!==null&&e.headers.get(`content-type`)===`application/x-ndjson`}async function*An(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 jn(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 Mn,Nn,Pn=F((()=>{Mn=new Set([`method`,`body`,`data`,`header`]),Nn={X:`method`,d:`data`,H:`header`}}));function Fn(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 In(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=>In(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=>In(e,t));let n={};for(let r of t)Ln(n,e,r,0);return n}function Ln(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 Ln(t,e,n,r+2),t});return}if(typeof a!=`object`||!a)return;(!e[i.key]||typeof e[i.key]!=`object`)&&(e[i.key]={}),Ln(e[i.key],a,n,r+1);return}}var Rn=F((()=>{}));function zn(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 Bn(e){return e===`true`||e===`false`||e===`null`}function Vn(e,t,n){if(t===`__proto__`){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0});return}e[t]=n}function Hn(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 Hn(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(Hn);if(e instanceof Set)return Array.from(e).map(Hn);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),Hn(t)]));if(qn(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&Vn(t,n,Hn(e[n]));return t}return null}function Un(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function Wn(e){return Array.isArray(e)}function Gn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Kn(e){return Object.keys(e).length===0}function qn(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Jn(e){return e.length===0||e.every(e=>Un(e))}function Yn(e){return e.length===0||e.every(e=>Wn(e))}function Xn(e){return e.length===0||e.every(e=>Gn(e))}function Zn(e){return/^[A-Z_][\w.]*$/i.test(e)}function Qn(e){return/^[A-Z_]\w*$/i.test(e)}function $n(e,t=Nr){return!(!e||e!==e.trim()||Bn(e)||er(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith(`-`))}function er(e){return Pr.test(e)||Fr.test(e)}function tr(e,t,n,r,i,a,o){if(r.keyFolding!==`safe`||!Gn(t))return;let{segments:s,tail:c,leafValue:l}=nr(e,t,o??r.flattenDepth);if(s.length<2||!s.every(e=>Qn(e)))return;let u=rr(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 nr(e,t,n){let r=[e],i=t;for(;r.length<n&&Gn(i);){let e=Object.keys(i);if(e.length!==1)break;let t=e[0],n=i[t];r.push(t),i=n}return!Gn(i)||Kn(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function rr(e){return e.join(`.`)}function ir(e,t){return e===null?jr:typeof e==`boolean`||typeof e==`number`?String(e):ar(e,t)}function ar(e,t=Nr){return $n(e,t)?e:`"${zn(e)}"`}function or(e){return Zn(e)?e:`"${zn(e)}"`}function sr(e,t=Nr){return e.map(e=>ir(e,t)).join(t)}function cr(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;if(n!=null&&(a+=or(n)),a+=`[${e}${i===Nr?``:i}]`,r){let e=r.map(e=>or(e));a+=`{${e.join(i)}}`}return a+=`:`,a}function*lr(e,t,n){if(Un(e)){let n=ir(e,t.delimiter);n!==``&&(yield n);return}Wn(e)?yield*fr(void 0,e,n,t):Gn(e)&&(yield*ur(e,n,t))}function*ur(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*dr(a,c,t,n,o,r,i,s)}function*dr(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=tr(e,t,i,r,a,o,l);if(s){let{foldedKey:e,remainder:t,leafValue:i,segmentCount:c}=s,u=or(e);if(t===void 0){if(Un(i)){yield Sr(n,`${u}: ${ir(i,r.delimiter)}`,r.indent);return}if(Wn(i)){yield*fr(e,i,n,r);return}if(Gn(i)&&Kn(i)){yield Sr(n,`${u}:`,r.indent);return}}if(Gn(t)){yield Sr(n,`${u}:`,r.indent);let i=l-c,s=o?`${o}.${e}`:e;yield*ur(t,n+1,r,a,s,i);return}}}let u=or(e);Un(t)?yield Sr(n,`${u}: ${ir(t,r.delimiter)}`,r.indent):Wn(t)?yield*fr(e,t,n,r):Gn(t)&&(yield Sr(n,`${u}:`,r.indent),Kn(t)||(yield*ur(t,n+1,r,a,c,l)))}function*fr(e,t,n,r){if(t.length===0){yield Sr(n,e==null?`[]`:`${or(e)}: []`,r.indent);return}if(Jn(t)){yield Sr(n,mr(t,r.delimiter,e),r.indent);return}if(Yn(t)&&t.every(e=>Jn(e))){yield*pr(e,t,n,r);return}if(Xn(t)){let i=gr(t);i?yield*hr(e,t,i,n,r):yield*yr(e,t,n,r);return}yield*yr(e,t,n,r)}function*pr(e,t,n,r){yield Sr(n,cr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)if(Jn(e)){let t=mr(e,r.delimiter);yield Cr(n+1,t,r.indent)}}function mr(e,t,n){let r=cr(e.length,{key:n,delimiter:t}),i=sr(e,t);return e.length===0?r:`${r} ${i}`}function*hr(e,t,n,r,i){yield Sr(r,cr(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*vr(t,n,r+1,i)}function gr(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&_r(e,n))return n}function _r(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)||!Un(n[e]))return!1}return!0}function*vr(e,t,n,r){for(let i of e)yield Sr(n,sr(t.map(e=>i[e]),r.delimiter),r.indent)}function*yr(e,t,n,r){yield Sr(n,cr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)yield*xr(e,n+1,r)}function*br(e,t,n){if(Kn(e)){yield Sr(t,`-`,n.indent);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(Wn(a)&&Xn(a)){let e=gr(a);if(e){yield Cr(t,cr(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indent),yield*vr(a,e,t+2,n),o.length>0&&(yield*ur(Object.fromEntries(o),t+1,n));return}}let s=or(i);if(Un(a))yield Cr(t,`${s}: ${ir(a,n.delimiter)}`,n.indent);else if(Wn(a)){if(a.length===0)yield Cr(t,`${s}: []`,n.indent);else if(Jn(a))yield Cr(t,`${s}${mr(a,n.delimiter)}`,n.indent);else{yield Cr(t,`${s}${cr(a.length,{delimiter:n.delimiter})}`,n.indent);for(let e of a)yield*xr(e,t+2,n)}}else Gn(a)&&(yield Cr(t,`${s}:`,n.indent),Kn(a)||(yield*ur(a,t+2,n)));o.length>0&&(yield*ur(Object.fromEntries(o),t+1,n))}function*xr(e,t,n){if(Un(e))yield Cr(t,ir(e,n.delimiter),n.indent);else if(Wn(e)){if(Jn(e))yield Cr(t,mr(e,n.delimiter),n.indent);else{yield Cr(t,cr(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*xr(r,t+1,n)}}else Gn(e)&&(yield*br(e,t,n))}function Sr(e,t,n){return` `.repeat(n*e)+t}function Cr(e,t,n){return Sr(e,`- `+t,n)}function wr(e,t){let n=t(``,e,[]);return Tr(n===void 0?e:Hn(n),t,[])}function Tr(e,t,n){return Gn(e)?Er(e,t,n):Wn(e)?Dr(e,t,n):e}function Er(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&&Vn(r,i,Tr(Hn(o),t,e))}return r}function Dr(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=Hn(s);r.push(Tr(c,t,o))}return r}function Or(e,t){return Array.from(kr(e,t)).join(`
50
- `)}function kr(e,t){let n=Hn(e),r=Ar(t);return lr(r.replacer?wr(n,r.replacer):n,r,0)}function Ar(e){return{indent:e?.indent??2,delimiter:e?.delimiter??Nr,keyFolding:e?.keyFolding??`off`,flattenDepth:e?.flattenDepth??1/0,replacer:e?.replacer}}var jr,Mr,Nr,Pr,Fr,Ir=F((()=>{jr=`null`,Mr={comma:`,`,tab:` `,pipe:`|`},Nr=Mr.comma,Pr=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,Fr=/^0\d+$/}));function Lr(e,t){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t,t)}function Rr(e){return JSON.parse(Lr(e))}var zr=F((()=>{}));function Br(e){if(e&&typeof e==`object`)switch(e[Jr]){case Wr:case qr:return!0}return!1}function Vr(e){if(e&&typeof e==`object`)switch(e[Jr]){case Hr:case Wr:case Kr:case qr:return!0}return!1}var Hr,Ur,Wr,Gr,Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,L=F((()=>{Hr=Symbol.for(`yaml.alias`),Ur=Symbol.for(`yaml.document`),Wr=Symbol.for(`yaml.map`),Gr=Symbol.for(`yaml.pair`),Kr=Symbol.for(`yaml.scalar`),qr=Symbol.for(`yaml.seq`),Jr=Symbol.for(`yaml.node.type`),Yr=e=>!!e&&typeof e==`object`&&e[Jr]===Hr,Xr=e=>!!e&&typeof e==`object`&&e[Jr]===Ur,Zr=e=>!!e&&typeof e==`object`&&e[Jr]===Wr,Qr=e=>!!e&&typeof e==`object`&&e[Jr]===Gr,$r=e=>!!e&&typeof e==`object`&&e[Jr]===Kr,ei=e=>!!e&&typeof e==`object`&&e[Jr]===qr,ti=e=>($r(e)||Br(e))&&!!e.anchor}));function ni(e,t){let n=oi(t);Xr(e)?ri(null,e.contents,n,Object.freeze([e]))===di&&(e.contents=null):ri(null,e,n,Object.freeze([]))}function ri(e,t,n,r){let i=si(e,t,n,r);if(Vr(i)||Qr(i))return ci(e,r,i),ri(e,i,n,r);if(typeof i!=`symbol`){if(Br(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=ri(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===li)return li;else i===di&&(t.items.splice(e,1),--e)}}else if(Qr(t)){r=Object.freeze(r.concat(t));let e=ri(`key`,t.key,n,r);if(e===li)return li;e===di&&(t.key=null);let i=ri(`value`,t.value,n,r);if(i===li)return li;i===di&&(t.value=null)}}return i}async function ii(e,t){let n=oi(t);Xr(e)?await ai(null,e.contents,n,Object.freeze([e]))===di&&(e.contents=null):await ai(null,e,n,Object.freeze([]))}async function ai(e,t,n,r){let i=await si(e,t,n,r);if(Vr(i)||Qr(i))return ci(e,r,i),ai(e,i,n,r);if(typeof i!=`symbol`){if(Br(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=await ai(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===li)return li;else i===di&&(t.items.splice(e,1),--e)}}else if(Qr(t)){r=Object.freeze(r.concat(t));let e=await ai(`key`,t.key,n,r);if(e===li)return li;e===di&&(t.key=null);let i=await ai(`value`,t.value,n,r);if(i===li)return li;i===di&&(t.value=null)}}return i}function oi(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 si(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(Zr(t))return n.Map?.(e,t,r);if(ei(t))return n.Seq?.(e,t,r);if(Qr(t))return n.Pair?.(e,t,r);if($r(t))return n.Scalar?.(e,t,r);if(Yr(t))return n.Alias?.(e,t,r)}function ci(e,t,n){let r=t[t.length-1];if(Br(r))r.items[e]=n;else if(Qr(r))e===`key`?r.key=n:r.value=n;else if(Xr(r))r.contents=n;else{let e=Yr(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var li,ui,di,fi=F((()=>{L(),li=Symbol(`break visit`),ui=Symbol(`skip children`),di=Symbol(`remove node`),ni.BREAK=li,ni.SKIP=ui,ni.REMOVE=di,ii.BREAK=li,ii.SKIP=ui,ii.REMOVE=di})),pi,mi,hi,gi=F((()=>{L(),fi(),pi={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},mi=e=>e.replace(/[!,[\]{}]/g,e=>pi[e]),hi=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+mi(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&&Vr(e.contents)){let t={};ni(e.contents,(e,n)=>{Vr(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
- `)}},hi.defaultYaml={explicit:!1,version:`1.2`},hi.defaultTags={"!!":`tag:yaml.org,2002:`}}));function _i(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 vi(e){let t=new Set;return ni(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function yi(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function bi(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=vi(e);let a=yi(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&($r(t.node)||Br(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 xi=F((()=>{L(),fi()}));function Si(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=Si(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=Si(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=Si(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=Si(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}var Ci=F((()=>{}));function wi(e,t,n){if(Array.isArray(e))return e.map((e,t)=>wi(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!ti(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 Ti=F((()=>{L()})),Ei,Di=F((()=>{Ci(),L(),Ti(),Ei=class{constructor(e){Object.defineProperty(this,Jr,{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(!Xr(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=wi(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?Si(i,{"":o},``,o):o}}}));function Oi(e,t,n){if(Yr(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Br(t)){let r=0;for(let i of t.items){let t=Oi(e,i,n);t>r&&(r=t)}return r}if(Qr(t)){let r=Oi(e,t.key,n),i=Oi(e,t.value,n);return Math.max(r,i)}return 1}var ki,Ai=F((()=>{xi(),fi(),L(),Di(),Ti(),ki=class extends Ei{constructor(e){super(Hr),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=[],ni(e,{Node:(e,t)=>{(Yr(t)||ti(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||=(wi(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=Oi(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(_i(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}}})),ji,R,Mi=F((()=>{L(),Di(),Ti(),ji=e=>!e||typeof e!=`function`&&typeof e!=`object`,R=class extends Ei{constructor(e){super(Kr),this.value=e}toJSON(e,t){return t?.keep?this.value:wi(this.value,e,t)}toString(){return String(this.value)}},R.BLOCK_FOLDED=`BLOCK_FOLDED`,R.BLOCK_LITERAL=`BLOCK_LITERAL`,R.PLAIN=`PLAIN`,R.QUOTE_DOUBLE=`QUOTE_DOUBLE`,R.QUOTE_SINGLE=`QUOTE_SINGLE`}));function Ni(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 Pi(e,t,n){if(Xr(e)&&(e=e.contents),Vr(e))return e;if(Qr(e)){let t=n.schema[Wr].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 ki(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=Fi+t.slice(2));let l=Ni(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new R(e);return c&&(c.node=t),t}l=e instanceof Map?o[Wr]:Symbol.iterator in Object(e)?o[qr]:o[Wr]}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 R(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}var Fi,Ii=F((()=>{Ai(),L(),Mi(),Fi=`tag:yaml.org,2002:`}));function Li(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 Pi(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var Ri,zi,Bi=F((()=>{Ii(),L(),Di(),Ri=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,zi=class extends Ei{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=>Vr(t)||Qr(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Ri(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(Br(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Li(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(Br(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&&$r(i)?i.value:i:Br(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!Qr(t))return!1;let n=t.value;return n==null||e&&$r(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 Br(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(Br(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,Li(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}}));function Vi(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Hi,Ui,Wi=F((()=>{Hi=e=>e.replace(/^(?!$)(?: $)?/gm,`#`),Ui=(e,t,n)=>e.endsWith(`
52
- `)?Vi(n,t):n.includes(`
48
+ }`}var Sn=F((()=>{cn()}));function Cn(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 wn,I,Tn,En,Dn=F((()=>{wn=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 Cn(this,e)}},I=class extends wn{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}},Tn=class extends wn{name=`Incur.ValidationError`;fieldErrors;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.fieldErrors=e.fieldErrors??[]}},En=class extends wn{name=`Incur.ParseError`;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0)}}}));function On(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);Nn.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}`);Nn.has(t)?s(t,i):r.set(t,i),o+=2}}else if(n.startsWith(`-`)&&n.length===2){let t=n[1],r=Pn[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 kn(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 An(e){return e.body!==null&&e.headers.get(`content-type`)===`application/x-ndjson`}async function*jn(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 Mn(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 Nn,Pn,Fn=F((()=>{Nn=new Set([`method`,`body`,`data`,`header`]),Pn={X:`method`,d:`data`,H:`header`}}));function In(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 Ln(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=>Ln(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=>Ln(e,t));let n={};for(let r of t)Rn(n,e,r,0);return n}function Rn(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 Rn(t,e,n,r+2),t});return}if(typeof a!=`object`||!a)return;(!e[i.key]||typeof e[i.key]!=`object`)&&(e[i.key]={}),Rn(e[i.key],a,n,r+1);return}}var zn=F((()=>{}));function Bn(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 Vn(e){return e===`true`||e===`false`||e===`null`}function Hn(e,t,n){if(t===`__proto__`){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0});return}e[t]=n}function Un(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 Un(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(Un);if(e instanceof Set)return Array.from(e).map(Un);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),Un(t)]));if(Jn(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&Hn(t,n,Un(e[n]));return t}return null}function Wn(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function Gn(e){return Array.isArray(e)}function Kn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qn(e){return Object.keys(e).length===0}function Jn(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Yn(e){return e.length===0||e.every(e=>Wn(e))}function Xn(e){return e.length===0||e.every(e=>Gn(e))}function Zn(e){return e.length===0||e.every(e=>Kn(e))}function Qn(e){return/^[A-Z_][\w.]*$/i.test(e)}function $n(e){return/^[A-Z_]\w*$/i.test(e)}function er(e,t=Pr){return!(!e||e!==e.trim()||Vn(e)||tr(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith(`-`))}function tr(e){return Fr.test(e)||Ir.test(e)}function nr(e,t,n,r,i,a,o){if(r.keyFolding!==`safe`||!Kn(t))return;let{segments:s,tail:c,leafValue:l}=rr(e,t,o??r.flattenDepth);if(s.length<2||!s.every(e=>$n(e)))return;let u=ir(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 rr(e,t,n){let r=[e],i=t;for(;r.length<n&&Kn(i);){let e=Object.keys(i);if(e.length!==1)break;let t=e[0],n=i[t];r.push(t),i=n}return!Kn(i)||qn(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function ir(e){return e.join(`.`)}function ar(e,t){return e===null?Mr:typeof e==`boolean`||typeof e==`number`?String(e):or(e,t)}function or(e,t=Pr){return er(e,t)?e:`"${Bn(e)}"`}function sr(e){return Qn(e)?e:`"${Bn(e)}"`}function cr(e,t=Pr){return e.map(e=>ar(e,t)).join(t)}function lr(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;if(n!=null&&(a+=sr(n)),a+=`[${e}${i===Pr?``:i}]`,r){let e=r.map(e=>sr(e));a+=`{${e.join(i)}}`}return a+=`:`,a}function*ur(e,t,n){if(Wn(e)){let n=ar(e,t.delimiter);n!==``&&(yield n);return}Gn(e)?yield*pr(void 0,e,n,t):Kn(e)&&(yield*dr(e,n,t))}function*dr(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*fr(a,c,t,n,o,r,i,s)}function*fr(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=nr(e,t,i,r,a,o,l);if(s){let{foldedKey:e,remainder:t,leafValue:i,segmentCount:c}=s,u=sr(e);if(t===void 0){if(Wn(i)){yield Cr(n,`${u}: ${ar(i,r.delimiter)}`,r.indent);return}if(Gn(i)){yield*pr(e,i,n,r);return}if(Kn(i)&&qn(i)){yield Cr(n,`${u}:`,r.indent);return}}if(Kn(t)){yield Cr(n,`${u}:`,r.indent);let i=l-c,s=o?`${o}.${e}`:e;yield*dr(t,n+1,r,a,s,i);return}}}let u=sr(e);Wn(t)?yield Cr(n,`${u}: ${ar(t,r.delimiter)}`,r.indent):Gn(t)?yield*pr(e,t,n,r):Kn(t)&&(yield Cr(n,`${u}:`,r.indent),qn(t)||(yield*dr(t,n+1,r,a,c,l)))}function*pr(e,t,n,r){if(t.length===0){yield Cr(n,e==null?`[]`:`${sr(e)}: []`,r.indent);return}if(Yn(t)){yield Cr(n,hr(t,r.delimiter,e),r.indent);return}if(Xn(t)&&t.every(e=>Yn(e))){yield*mr(e,t,n,r);return}if(Zn(t)){let i=_r(t);i?yield*gr(e,t,i,n,r):yield*br(e,t,n,r);return}yield*br(e,t,n,r)}function*mr(e,t,n,r){yield Cr(n,lr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)if(Yn(e)){let t=hr(e,r.delimiter);yield wr(n+1,t,r.indent)}}function hr(e,t,n){let r=lr(e.length,{key:n,delimiter:t}),i=cr(e,t);return e.length===0?r:`${r} ${i}`}function*gr(e,t,n,r,i){yield Cr(r,lr(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*yr(t,n,r+1,i)}function _r(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&vr(e,n))return n}function vr(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)||!Wn(n[e]))return!1}return!0}function*yr(e,t,n,r){for(let i of e)yield Cr(n,cr(t.map(e=>i[e]),r.delimiter),r.indent)}function*br(e,t,n,r){yield Cr(n,lr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)yield*Sr(e,n+1,r)}function*xr(e,t,n){if(qn(e)){yield Cr(t,`-`,n.indent);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(Gn(a)&&Zn(a)){let e=_r(a);if(e){yield wr(t,lr(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indent),yield*yr(a,e,t+2,n),o.length>0&&(yield*dr(Object.fromEntries(o),t+1,n));return}}let s=sr(i);if(Wn(a))yield wr(t,`${s}: ${ar(a,n.delimiter)}`,n.indent);else if(Gn(a)){if(a.length===0)yield wr(t,`${s}: []`,n.indent);else if(Yn(a))yield wr(t,`${s}${hr(a,n.delimiter)}`,n.indent);else{yield wr(t,`${s}${lr(a.length,{delimiter:n.delimiter})}`,n.indent);for(let e of a)yield*Sr(e,t+2,n)}}else Kn(a)&&(yield wr(t,`${s}:`,n.indent),qn(a)||(yield*dr(a,t+2,n)));o.length>0&&(yield*dr(Object.fromEntries(o),t+1,n))}function*Sr(e,t,n){if(Wn(e))yield wr(t,ar(e,n.delimiter),n.indent);else if(Gn(e)){if(Yn(e))yield wr(t,hr(e,n.delimiter),n.indent);else{yield wr(t,lr(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*Sr(r,t+1,n)}}else Kn(e)&&(yield*xr(e,t,n))}function Cr(e,t,n){return` `.repeat(n*e)+t}function wr(e,t,n){return Cr(e,`- `+t,n)}function Tr(e,t){let n=t(``,e,[]);return Er(n===void 0?e:Un(n),t,[])}function Er(e,t,n){return Kn(e)?Dr(e,t,n):Gn(e)?Or(e,t,n):e}function Dr(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&&Hn(r,i,Er(Un(o),t,e))}return r}function Or(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=Un(s);r.push(Er(c,t,o))}return r}function kr(e,t){return Array.from(Ar(e,t)).join(`
50
+ `)}function Ar(e,t){let n=Un(e),r=jr(t);return ur(r.replacer?Tr(n,r.replacer):n,r,0)}function jr(e){return{indent:e?.indent??2,delimiter:e?.delimiter??Pr,keyFolding:e?.keyFolding??`off`,flattenDepth:e?.flattenDepth??1/0,replacer:e?.replacer}}var Mr,Nr,Pr,Fr,Ir,Lr=F((()=>{Mr=`null`,Nr={comma:`,`,tab:` `,pipe:`|`},Pr=Nr.comma,Fr=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,Ir=/^0\d+$/}));function Rr(e,t){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t,t)}function zr(e){return JSON.parse(Rr(e))}var Br=F((()=>{}));function Vr(e){if(e&&typeof e==`object`)switch(e[Yr]){case Gr:case Jr:return!0}return!1}function Hr(e){if(e&&typeof e==`object`)switch(e[Yr]){case Ur:case Gr:case qr:case Jr:return!0}return!1}var Ur,Wr,Gr,Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,ni,L=F((()=>{Ur=Symbol.for(`yaml.alias`),Wr=Symbol.for(`yaml.document`),Gr=Symbol.for(`yaml.map`),Kr=Symbol.for(`yaml.pair`),qr=Symbol.for(`yaml.scalar`),Jr=Symbol.for(`yaml.seq`),Yr=Symbol.for(`yaml.node.type`),Xr=e=>!!e&&typeof e==`object`&&e[Yr]===Ur,Zr=e=>!!e&&typeof e==`object`&&e[Yr]===Wr,Qr=e=>!!e&&typeof e==`object`&&e[Yr]===Gr,$r=e=>!!e&&typeof e==`object`&&e[Yr]===Kr,ei=e=>!!e&&typeof e==`object`&&e[Yr]===qr,ti=e=>!!e&&typeof e==`object`&&e[Yr]===Jr,ni=e=>(ei(e)||Vr(e))&&!!e.anchor}));function ri(e,t){let n=si(t);Zr(e)?ii(null,e.contents,n,Object.freeze([e]))===fi&&(e.contents=null):ii(null,e,n,Object.freeze([]))}function ii(e,t,n,r){let i=ci(e,t,n,r);if(Hr(i)||$r(i))return li(e,r,i),ii(e,i,n,r);if(typeof i!=`symbol`){if(Vr(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=ii(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===ui)return ui;else i===fi&&(t.items.splice(e,1),--e)}}else if($r(t)){r=Object.freeze(r.concat(t));let e=ii(`key`,t.key,n,r);if(e===ui)return ui;e===fi&&(t.key=null);let i=ii(`value`,t.value,n,r);if(i===ui)return ui;i===fi&&(t.value=null)}}return i}async function ai(e,t){let n=si(t);Zr(e)?await oi(null,e.contents,n,Object.freeze([e]))===fi&&(e.contents=null):await oi(null,e,n,Object.freeze([]))}async function oi(e,t,n,r){let i=await ci(e,t,n,r);if(Hr(i)||$r(i))return li(e,r,i),oi(e,i,n,r);if(typeof i!=`symbol`){if(Vr(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=await oi(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===ui)return ui;else i===fi&&(t.items.splice(e,1),--e)}}else if($r(t)){r=Object.freeze(r.concat(t));let e=await oi(`key`,t.key,n,r);if(e===ui)return ui;e===fi&&(t.key=null);let i=await oi(`value`,t.value,n,r);if(i===ui)return ui;i===fi&&(t.value=null)}}return i}function si(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 ci(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(Qr(t))return n.Map?.(e,t,r);if(ti(t))return n.Seq?.(e,t,r);if($r(t))return n.Pair?.(e,t,r);if(ei(t))return n.Scalar?.(e,t,r);if(Xr(t))return n.Alias?.(e,t,r)}function li(e,t,n){let r=t[t.length-1];if(Vr(r))r.items[e]=n;else if($r(r))e===`key`?r.key=n:r.value=n;else if(Zr(r))r.contents=n;else{let e=Xr(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var ui,di,fi,pi=F((()=>{L(),ui=Symbol(`break visit`),di=Symbol(`skip children`),fi=Symbol(`remove node`),ri.BREAK=ui,ri.SKIP=di,ri.REMOVE=fi,ai.BREAK=ui,ai.SKIP=di,ai.REMOVE=fi})),mi,hi,gi,_i=F((()=>{L(),pi(),mi={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},hi=e=>e.replace(/[!,[\]{}]/g,e=>mi[e]),gi=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+hi(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&&Hr(e.contents)){let t={};ri(e.contents,(e,n)=>{Hr(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
+ `)}},gi.defaultYaml={explicit:!1,version:`1.2`},gi.defaultTags={"!!":`tag:yaml.org,2002:`}}));function vi(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 yi(e){let t=new Set;return ri(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function bi(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function xi(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=yi(e);let a=bi(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(ei(t.node)||Vr(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 Si=F((()=>{L(),pi()}));function Ci(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=Ci(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=Ci(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=Ci(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=Ci(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}var wi=F((()=>{}));function Ti(e,t,n){if(Array.isArray(e))return e.map((e,t)=>Ti(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!ni(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 Ei=F((()=>{L()})),Di,Oi=F((()=>{wi(),L(),Ei(),Di=class{constructor(e){Object.defineProperty(this,Yr,{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(!Zr(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=Ti(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?Ci(i,{"":o},``,o):o}}}));function ki(e,t,n){if(Xr(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Vr(t)){let r=0;for(let i of t.items){let t=ki(e,i,n);t>r&&(r=t)}return r}if($r(t)){let r=ki(e,t.key,n),i=ki(e,t.value,n);return Math.max(r,i)}return 1}var Ai,ji=F((()=>{Si(),pi(),L(),Oi(),Ei(),Ai=class extends Di{constructor(e){super(Ur),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=[],ri(e,{Node:(e,t)=>{(Xr(t)||ni(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||=(Ti(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=ki(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(vi(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}}})),Mi,R,Ni=F((()=>{L(),Oi(),Ei(),Mi=e=>!e||typeof e!=`function`&&typeof e!=`object`,R=class extends Di{constructor(e){super(qr),this.value=e}toJSON(e,t){return t?.keep?this.value:Ti(this.value,e,t)}toString(){return String(this.value)}},R.BLOCK_FOLDED=`BLOCK_FOLDED`,R.BLOCK_LITERAL=`BLOCK_LITERAL`,R.PLAIN=`PLAIN`,R.QUOTE_DOUBLE=`QUOTE_DOUBLE`,R.QUOTE_SINGLE=`QUOTE_SINGLE`}));function Pi(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 Fi(e,t,n){if(Zr(e)&&(e=e.contents),Hr(e))return e;if($r(e)){let t=n.schema[Gr].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 Ai(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=Ii+t.slice(2));let l=Pi(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new R(e);return c&&(c.node=t),t}l=e instanceof Map?o[Gr]:Symbol.iterator in Object(e)?o[Jr]:o[Gr]}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 R(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}var Ii,Li=F((()=>{ji(),L(),Ni(),Ii=`tag:yaml.org,2002:`}));function Ri(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 Fi(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var zi,Bi,Vi=F((()=>{Li(),L(),Oi(),zi=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,Bi=class extends Di{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=>Hr(t)||$r(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(zi(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(Vr(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Ri(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(Vr(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&&ei(i)?i.value:i:Vr(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!$r(t))return!1;let n=t.value;return n==null||e&&ei(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 Vr(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(Vr(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,Ri(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}}));function Hi(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Ui,Wi,Gi=F((()=>{Ui=e=>e.replace(/^(?!$)(?: $)?/gm,`#`),Wi=(e,t,n)=>e.endsWith(`
52
+ `)?Hi(n,t):n.includes(`
53
53
  `)?`
54
- `+Vi(n,t):(e.endsWith(` `)?``:` `)+n}));function Gi(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=Ki(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=Ki(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
54
+ `+Hi(n,t):(e.endsWith(` `)?``:` `)+n}));function Ki(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=qi(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=qi(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 Ki(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 qi,Ji,Yi,Xi=F((()=>{qi=`flow`,Ji=`block`,Yi=`quoted`}));function Zi(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 Qi(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(aa(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 qi(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 Ji,Yi,Xi,Zi=F((()=>{Ji=`flow`,Yi=`block`,Xi=`quoted`}));function Qi(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 $i(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(oa(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:Gi(o,a,Yi,ia(t,!1))}function $i(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
63
- `)||/[ \t]\n|\n[ \t]/.test(e))return Qi(e,t);let n=t.indent||(aa(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:Gi(r,n,qi,ia(t,!1))}function ea(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=Qi;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?$i:i&&!t?Qi:n?$i:Qi}return r(e,t)}function ta({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 ea(n,r);let l=r.indent||(r.forceBlockIndent||aa(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===R.BLOCK_FOLDED?!1:t===R.BLOCK_LITERAL||!Zi(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:Ki(o,a,Xi,aa(t,!1))}function ea(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
63
+ `)||/[ \t]\n|\n[ \t]/.test(e))return $i(e,t);let n=t.indent||(oa(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:Ki(r,n,Ji,aa(t,!1))}function ta(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=$i;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?ea:i&&!t?$i:n?ea:$i}return r(e,t)}function na({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 ta(n,r);let l=r.indent||(r.forceBlockIndent||oa(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===R.BLOCK_FOLDED?!1:t===R.BLOCK_LITERAL||!Qi(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(oa,`$&${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(sa,`$&${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=ia(r,!0);o!==`folded`&&t!==R.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=Gi(`${v}${e}${p}`,l,Ji,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function na(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 ea(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
72
- `)?ea(a,t):ta(e,t,n,r);if(!s&&!u&&i!==R.PLAIN&&a.includes(`
73
- `))return ta(e,t,n,r);if(aa(a)){if(c===``)return t.forceBlockIndent=!0,ta(e,t,n,r);if(s&&c===l)return ea(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 ea(a,t)}return s?d:Gi(d,c,qi,ia(t,!1))}function ra(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!==R.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=R.QUOTE_DOUBLE);let c=e=>{switch(e){case R.BLOCK_FOLDED:case R.BLOCK_LITERAL:return i||a?ea(o.value,t):ta(o,t,n,r);case R.QUOTE_DOUBLE:return Qi(o.value,t);case R.QUOTE_SINGLE:return $i(o.value,t);case R.PLAIN:return na(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 ia,aa,oa,sa=F((()=>{Mi(),Xi(),ia=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),aa=e=>/^(%|---|\.\.\.)/m.test(e);try{oa=RegExp(`(^|(?<!
70
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=aa(r,!0);o!==`folded`&&t!==R.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=Ki(`${v}${e}${p}`,l,Yi,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function ra(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 ta(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
72
+ `)?ta(a,t):na(e,t,n,r);if(!s&&!u&&i!==R.PLAIN&&a.includes(`
73
+ `))return na(e,t,n,r);if(oa(a)){if(c===``)return t.forceBlockIndent=!0,na(e,t,n,r);if(s&&c===l)return ta(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 ta(a,t)}return s?d:Ki(d,c,Ji,aa(t,!1))}function ia(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!==R.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=R.QUOTE_DOUBLE);let c=e=>{switch(e){case R.BLOCK_FOLDED:case R.BLOCK_LITERAL:return i||a?ta(o.value,t):na(o,t,n,r);case R.QUOTE_DOUBLE:return $i(o.value,t);case R.QUOTE_SINGLE:return ea(o.value,t);case R.PLAIN:return ra(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 aa,oa,sa,ca=F((()=>{Ni(),Zi(),aa=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),oa=e=>/^(%|---|\.\.\.)/m.test(e);try{sa=RegExp(`(^|(?<!
74
74
  ))
75
75
  +(?!
76
- |$)`,`g`)}catch{oa=/\n+(?!\n|$)/g}}));function ca(e,t){let n=Object.assign({blockQuote:!0,commentString:Hi,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 la(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($r(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 ua(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=($r(e)||Br(e))&&e.anchor;a&&_i(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 da(e,t,n,r){if(Qr(e))return e.toString(t,n,r);if(Yr(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=Vr(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=la(t.doc.schema.tags,a);let o=ua(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):$r(a)?ra(a,t,n,r):a.toString(t,n,r);return o?$r(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}var fa=F((()=>{xi(),L(),Wi(),sa()}));function pa({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=Vr(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(Br(e)||!Vr(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||Br(e)||($r(e)?e.type===R.BLOCK_FOLDED||e.type===R.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=da(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+=Ui(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=Ui(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=Ui(g,n.indent,l(f))));let _,v,y;Vr(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&&$r(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&ei(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=da(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?`
77
- `:``,v){let e=l(v);S+=`\n${Vi(e,n.indent)}`}x===``&&!n.inFlow?S===`
76
+ |$)`,`g`)}catch{sa=/\n+(?!\n|$)/g}}));function la(e,t){let n=Object.assign({blockQuote:!0,commentString:Ui,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 ua(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(ei(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 da(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(ei(e)||Vr(e))&&e.anchor;a&&vi(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 fa(e,t,n,r){if($r(e))return e.toString(t,n,r);if(Xr(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=Hr(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=ua(t.doc.schema.tags,a);let o=da(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):ei(a)?ia(a,t,n,r):a.toString(t,n,r);return o?ei(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}var pa=F((()=>{Si(),L(),Gi(),ca()}));function ma({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=Hr(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(Vr(e)||!Hr(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||Vr(e)||(ei(e)?e.type===R.BLOCK_FOLDED||e.type===R.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=fa(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+=Wi(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=Wi(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=Wi(g,n.indent,l(f))));let _,v,y;Hr(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&&ei(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&ti(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=fa(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?`
77
+ `:``,v){let e=l(v);S+=`\n${Hi(e,n.indent)}`}x===``&&!n.inFlow?S===`
78
78
  `&&y&&(S=`
79
79
 
80
- `):S+=`\n${n.indent}`}else if(!p&&Br(t)){let e=x[0],r=x.indexOf(`
80
+ `):S+=`\n${n.indent}`}else if(!p&&Vr(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+=Ui(g,n.indent,l(y)):h&&i&&i(),g}var ma=F((()=>{L(),Mi(),fa(),Wi()}));function ha(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var ga=F((()=>{}));function _a(e,t,n){let r=ya(e,n);if(ei(r))for(let n of r.items)va(e,t,n);else if(Array.isArray(r))for(let n of r)va(e,t,n);else va(e,t,r)}function va(e,t,n){let r=ya(e,n);if(!Zr(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 ya(e,t){return e&&Yr(t)?t.resolve(e.doc,e):t}var ba,xa,Sa,Ca=F((()=>{L(),Mi(),ba=`<<`,xa={identify:e=>e===ba||typeof e==`symbol`&&e.description===ba,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new R(Symbol(ba)),{addToJSMap:_a}),stringify:()=>ba},Sa=(e,t)=>(xa.identify(t)||$r(t)&&(!t.type||t.type===R.PLAIN)&&xa.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===xa.tag&&e.default)}));function wa(e,t,{key:n,value:r}){if(Vr(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(Sa(e,n))_a(e,t,r);else{let i=wi(n,``,e);if(t instanceof Map)t.set(i,wi(r,i,e));else if(t instanceof Set)t.add(i);else{let a=Ta(n,i,e),o=wi(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Ta(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(Vr(e)&&n?.doc){let t=ca(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)+`..."`),ha(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 Ea=F((()=>{ga(),Ca(),fa(),L(),Ti()}));function Da(e,t,n){let r=Pi(e,void 0,n),i=Pi(t,void 0,n);return new Oa(r,i)}var Oa,ka=F((()=>{Ii(),ma(),Ea(),L(),Oa=class e{constructor(e,t=null){Object.defineProperty(this,Jr,{value:Gr}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return Vr(n)&&(n=n.clone(t)),Vr(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return wa(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?pa(this,e,t,n):JSON.stringify(this)}}}));function Aa(e,t,n){return(t.inFlow??e.flow?Ma:ja)(e,t,n)}function ja({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(Vr(i))!d&&i.spaceBefore&&f.push(``),Na(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(Qr(i)){let e=Vr(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),Na(n,f,e.commentBefore,d))}d=!1;let s=da(i,u,()=>o=null,()=>d=!0);o&&(s+=Ui(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+=Wi(g,n.indent,l(y)):h&&i&&i(),g}var ha=F((()=>{L(),Ni(),pa(),Gi()}));function ga(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var _a=F((()=>{}));function va(e,t,n){let r=ba(e,n);if(ti(r))for(let n of r.items)ya(e,t,n);else if(Array.isArray(r))for(let n of r)ya(e,t,n);else ya(e,t,r)}function ya(e,t,n){let r=ba(e,n);if(!Qr(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 ba(e,t){return e&&Xr(t)?t.resolve(e.doc,e):t}var xa,Sa,Ca,wa=F((()=>{L(),Ni(),xa=`<<`,Sa={identify:e=>e===xa||typeof e==`symbol`&&e.description===xa,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new R(Symbol(xa)),{addToJSMap:va}),stringify:()=>xa},Ca=(e,t)=>(Sa.identify(t)||ei(t)&&(!t.type||t.type===R.PLAIN)&&Sa.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===Sa.tag&&e.default)}));function Ta(e,t,{key:n,value:r}){if(Hr(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(Ca(e,n))va(e,t,r);else{let i=Ti(n,``,e);if(t instanceof Map)t.set(i,Ti(r,i,e));else if(t instanceof Set)t.add(i);else{let a=Ea(n,i,e),o=Ti(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Ea(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(Hr(e)&&n?.doc){let t=la(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)+`..."`),ga(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 Da=F((()=>{_a(),wa(),pa(),L(),Ei()}));function Oa(e,t,n){let r=Fi(e,void 0,n),i=Fi(t,void 0,n);return new ka(r,i)}var ka,Aa=F((()=>{Li(),ha(),Da(),L(),ka=class e{constructor(e,t=null){Object.defineProperty(this,Yr,{value:Kr}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return Hr(n)&&(n=n.clone(t)),Hr(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return Ta(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?ma(this,e,t,n):JSON.stringify(this)}}}));function ja(e,t,n){return(t.inFlow??e.flow?Na:Ma)(e,t,n)}function Ma({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(Hr(i))!d&&i.spaceBefore&&f.push(``),Pa(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if($r(i)){let e=Hr(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),Pa(n,f,e.commentBefore,d))}d=!1;let s=fa(i,u,()=>o=null,()=>d=!0);o&&(s+=Wi(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
- `+Vi(l(e),c),s&&s()):d&&o&&o(),p}function Ma({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(Vr(i))i.spaceBefore&&d.push(``),Na(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(Qr(i)){let e=Vr(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),Na(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=Vr(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=da(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+=Ui(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 Na({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=Vi(t(r),e);n.push(i.trimStart())}}var Pa=F((()=>{L(),fa(),Wi()}));function Fa(e,t){let n=$r(t)?t.value:t;for(let r of e)if(Qr(r)&&(r.key===t||r.key===n||$r(r.key)&&r.key.value===n))return r}var Ia,La=F((()=>{Pa(),Ea(),Bi(),L(),ka(),Mi(),Ia=class extends zi{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(Wr,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(Da(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=Qr(e)?e:!e||typeof e!=`object`||!(`key`in e)?new Oa(e,e?.value):new Oa(e.key,e.value);let r=Fa(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);$r(r.value)&&ji(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=Fa(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=Fa(this.items,e)?.value;return(!t&&$r(n)?n.value:n)??void 0}has(e){return!!Fa(this.items,e)}set(e,t){this.add(new Oa(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)wa(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!Qr(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})),Aa(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}}})),Ra,za=F((()=>{L(),La(),Ra={collection:`map`,default:!0,nodeClass:Ia,tag:`tag:yaml.org,2002:map`,resolve(e,t){return Zr(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>Ia.from(e,t,n)}}));function Ba(e){let t=$r(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var Va,Ha=F((()=>{Ii(),Pa(),Bi(),L(),Mi(),Ti(),Va=class extends zi{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(qr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Ba(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=Ba(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&$r(r)?r.value:r}has(e){let t=Ba(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=Ba(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];$r(r)&&ji(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(wi(e,String(r++),t));return n}toString(e,t,n){return e?Aa(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(Pi(a,void 0,n))}}return i}}})),Ua,Wa=F((()=>{L(),Ha(),Ua={collection:`seq`,default:!0,nodeClass:Va,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return ei(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>Va.from(e,t,n)}})),Ga,Ka=F((()=>{sa(),Ga={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),ra(e,t,n,r)}}})),qa,Ja=F((()=>{Mi(),qa={identify:e=>e==null,createNode:()=>new R(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new R(null),stringify:({source:e},t)=>typeof e==`string`&&qa.test.test(e)?e:t.options.nullStr}})),Ya,Xa=F((()=>{Mi(),Ya={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new R(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&Ya.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}}}));function Za({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 Qa=F((()=>{})),$a,eo,to,no=F((()=>{Mi(),Qa(),$a={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:Za},eo={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():Za(e)}},to={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 R(parseFloat(e)),n=e.indexOf(`.`);return n!==-1&&e[e.length-1]===`0`&&(t.minFractionDigits=e.length-n-1),t},stringify:Za}}));function ro(e,t,n){let{value:r}=e;return io(r)&&r>=0?n+r.toString(t):Za(e)}var io,ao,oo,so,co,lo=F((()=>{Qa(),io=e=>typeof e==`bigint`||Number.isInteger(e),ao=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n),oo={identify:e=>io(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>ao(e,2,8,n),stringify:e=>ro(e,8,`0o`)},so={identify:io,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>ao(e,0,10,n),stringify:Za},co={identify:e=>io(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>ao(e,2,16,n),stringify:e=>ro(e,16,`0x`)}})),uo,fo=F((()=>{za(),Ja(),Wa(),Ka(),Xa(),no(),lo(),uo=[Ra,Ua,Ga,qa,Ya,oo,so,co,$a,eo,to]}));function po(e){return typeof e==`bigint`||Number.isInteger(e)}var mo,ho,go,_o=F((()=>{Mi(),za(),Wa(),mo=({value:e})=>JSON.stringify(e),ho=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:mo},{identify:e=>e==null,createNode:()=>new R(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:mo},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:mo},{identify:po,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})=>po(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:mo}],go=[Ra,Ua].concat(ho,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),vo,yo=F((()=>{Mi(),sa(),vo={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??=R.BLOCK_LITERAL,t!==R.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===R.BLOCK_LITERAL?`
87
- `:` `)}return ra({comment:e,type:t,value:s},r,i,a)}}}));function bo(e,t){if(ei(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!Qr(r)){if(Zr(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new Oa(new R(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]=Qr(r)?r:new Oa(r)}}else t(`Expected a sequence for this tag`);return e}function xo(e,t,n){let{replacer:r}=n,i=new Va(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(Da(o,s,n))}return i}var So,Co=F((()=>{L(),ka(),Mi(),Ha(),So={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:bo,createNode:xo}})),wo,To,Eo=F((()=>{L(),Ti(),La(),Ha(),Co(),wo=class e extends Va{constructor(){super(),this.add=Ia.prototype.add.bind(this),this.delete=Ia.prototype.delete.bind(this),this.get=Ia.prototype.get.bind(this),this.has=Ia.prototype.has.bind(this),this.set=Ia.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(Qr(e)?(r=wi(e.key,``,t),i=wi(e.value,r,t)):r=wi(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=xo(e,t,n),i=new this;return i.items=r.items,i}},wo.tag=`tag:yaml.org,2002:omap`,To={collection:`seq`,identify:e=>e instanceof Map,nodeClass:wo,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=bo(e,t),r=[];for(let{key:e}of n.items)$r(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new wo,n)},createNode:(e,t,n)=>wo.from(e,t,n)}}));function Do({value:e,source:t},n){return t&&(e?Oo:ko).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Oo,ko,Ao=F((()=>{Mi(),Oo={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 R(!0),stringify:Do},ko={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 R(!1),stringify:Do}})),jo,Mo,No,Po=F((()=>{Mi(),Qa(),jo={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:Za},Mo={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():Za(e)}},No={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 R(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:Za}}));function Fo(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 Io(e,t,n){let{value:r}=e;if(Lo(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return Za(e)}var Lo,Ro,zo,Bo,Vo,Ho=F((()=>{Qa(),Lo=e=>typeof e==`bigint`||Number.isInteger(e),Ro={identify:Lo,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Fo(e,2,2,n),stringify:e=>Io(e,2,`0b`)},zo={identify:Lo,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Fo(e,1,8,n),stringify:e=>Io(e,8,`0`)},Bo={identify:Lo,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Fo(e,0,10,n),stringify:Za},Vo={identify:Lo,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Fo(e,2,16,n),stringify:e=>Io(e,16,`0x`)}})),Uo,Wo,Go=F((()=>{L(),ka(),La(),Uo=class e extends Ia{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=Qr(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new Oa(e.key,null):new Oa(e,null),Fa(this.items,t.key)||this.items.push(t)}get(e,t){let n=Fa(this.items,e);return!t&&Qr(n)?$r(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=Fa(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Oa(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(Da(e,null,n));return i}},Uo.tag=`tag:yaml.org,2002:set`,Wo={collection:`map`,identify:e=>e instanceof Set,nodeClass:Uo,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>Uo.from(e,t,n),resolve(e,t){if(Zr(e)){if(e.hasAllNullValues(!0))return Object.assign(new Uo,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}}}));function Ko(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 qo(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return Za(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 Jo,Yo,Xo,Zo=F((()=>{Qa(),Jo={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})=>Ko(e,n),stringify:qo},Yo={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=>Ko(e,!1),stringify:qo},Xo={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(Xo.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=Ko(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$/,``)??``}})),Qo,$o=F((()=>{za(),Ja(),Wa(),Ka(),yo(),Ao(),Po(),Ho(),Ca(),Eo(),Co(),Go(),Zo(),Qo=[Ra,Ua,Ga,qa,Oo,ko,Ro,zo,Bo,Vo,jo,Mo,No,vo,xa,To,So,Wo,Jo,Yo,Xo]}));function es(e,t,n){let r=ts.get(t);if(r&&!e)return n&&!r.includes(xa)?r.concat(xa):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(ts.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(xa)),i.reduce((e,t)=>{let n=typeof t==`string`?ns[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(ns).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 ts,ns,rs,is=F((()=>{za(),Ja(),Wa(),Ka(),Xa(),no(),lo(),fo(),_o(),yo(),Ca(),Eo(),Co(),$o(),Go(),Zo(),ts=new Map([[`core`,uo],[`failsafe`,[Ra,Ua,Ga]],[`json`,go],[`yaml11`,Qo],[`yaml-1.1`,Qo]]),ns={binary:vo,bool:Ya,float:to,floatExp:eo,floatNaN:$a,floatTime:Yo,int:so,intHex:co,intOct:oo,intTime:Jo,map:Ra,merge:xa,null:qa,omap:To,pairs:So,seq:Ua,set:Wo,timestamp:Xo},rs={"tag:yaml.org,2002:binary":vo,"tag:yaml.org,2002:merge":xa,"tag:yaml.org,2002:omap":To,"tag:yaml.org,2002:pairs":So,"tag:yaml.org,2002:set":Wo,"tag:yaml.org,2002:timestamp":Xo}})),as,os,ss=F((()=>{L(),za(),Wa(),Ka(),is(),as=(e,t)=>e.key<t.key?-1:+(e.key>t.key),os=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?es(e,`compat`):e?es(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?rs:{},this.tags=es(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,Wr,{value:Ra}),Object.defineProperty(this,Kr,{value:Ga}),Object.defineProperty(this,qr,{value:Ua}),this.sortMapEntries=typeof a==`function`?a:a===!0?as:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}}));function cs(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=ca(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(Vi(t,``))}let o=!1,s=null;if(e.contents){if(Vr(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(Vi(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=da(e.contents,i,()=>s=null,t);s&&(c+=Ui(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(da(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
88
- `)?(n.push(`...`),n.push(Vi(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(Vi(a(t),``)))}return n.join(`
84
+ `+Hi(l(e),c),s&&s()):d&&o&&o(),p}function Na({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(Hr(i))i.spaceBefore&&d.push(``),Pa(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if($r(i)){let e=Hr(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),Pa(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=Hr(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=fa(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+=Wi(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 Pa({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=Hi(t(r),e);n.push(i.trimStart())}}var Fa=F((()=>{L(),pa(),Gi()}));function Ia(e,t){let n=ei(t)?t.value:t;for(let r of e)if($r(r)&&(r.key===t||r.key===n||ei(r.key)&&r.key.value===n))return r}var La,Ra=F((()=>{Fa(),Da(),Vi(),L(),Aa(),Ni(),La=class extends Bi{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(Gr,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(Oa(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=$r(e)?e:!e||typeof e!=`object`||!(`key`in e)?new ka(e,e?.value):new ka(e.key,e.value);let r=Ia(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);ei(r.value)&&Mi(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=Ia(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=Ia(this.items,e)?.value;return(!t&&ei(n)?n.value:n)??void 0}has(e){return!!Ia(this.items,e)}set(e,t){this.add(new ka(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)Ta(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!$r(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})),ja(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}}})),za,Ba=F((()=>{L(),Ra(),za={collection:`map`,default:!0,nodeClass:La,tag:`tag:yaml.org,2002:map`,resolve(e,t){return Qr(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>La.from(e,t,n)}}));function Va(e){let t=ei(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var Ha,Ua=F((()=>{Li(),Fa(),Vi(),L(),Ni(),Ei(),Ha=class extends Bi{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(Jr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Va(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=Va(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&ei(r)?r.value:r}has(e){let t=Va(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=Va(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];ei(r)&&Mi(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(Ti(e,String(r++),t));return n}toString(e,t,n){return e?ja(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(Fi(a,void 0,n))}}return i}}})),Wa,Ga=F((()=>{L(),Ua(),Wa={collection:`seq`,default:!0,nodeClass:Ha,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return ti(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>Ha.from(e,t,n)}})),Ka,qa=F((()=>{ca(),Ka={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),ia(e,t,n,r)}}})),Ja,Ya=F((()=>{Ni(),Ja={identify:e=>e==null,createNode:()=>new R(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new R(null),stringify:({source:e},t)=>typeof e==`string`&&Ja.test.test(e)?e:t.options.nullStr}})),Xa,Za=F((()=>{Ni(),Xa={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new R(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&Xa.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}}}));function Qa({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 $a=F((()=>{})),eo,to,no,ro=F((()=>{Ni(),$a(),eo={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:Qa},to={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():Qa(e)}},no={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 R(parseFloat(e)),n=e.indexOf(`.`);return n!==-1&&e[e.length-1]===`0`&&(t.minFractionDigits=e.length-n-1),t},stringify:Qa}}));function io(e,t,n){let{value:r}=e;return ao(r)&&r>=0?n+r.toString(t):Qa(e)}var ao,oo,so,co,lo,uo=F((()=>{$a(),ao=e=>typeof e==`bigint`||Number.isInteger(e),oo=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n),so={identify:e=>ao(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>oo(e,2,8,n),stringify:e=>io(e,8,`0o`)},co={identify:ao,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>oo(e,0,10,n),stringify:Qa},lo={identify:e=>ao(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>oo(e,2,16,n),stringify:e=>io(e,16,`0x`)}})),fo,po=F((()=>{Ba(),Ya(),Ga(),qa(),Za(),ro(),uo(),fo=[za,Wa,Ka,Ja,Xa,so,co,lo,eo,to,no]}));function mo(e){return typeof e==`bigint`||Number.isInteger(e)}var ho,go,_o,vo=F((()=>{Ni(),Ba(),Ga(),ho=({value:e})=>JSON.stringify(e),go=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:ho},{identify:e=>e==null,createNode:()=>new R(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:ho},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:ho},{identify:mo,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})=>mo(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:ho}],_o=[za,Wa].concat(go,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),yo,bo=F((()=>{Ni(),ca(),yo={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??=R.BLOCK_LITERAL,t!==R.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===R.BLOCK_LITERAL?`
87
+ `:` `)}return ia({comment:e,type:t,value:s},r,i,a)}}}));function xo(e,t){if(ti(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!$r(r)){if(Qr(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new ka(new R(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]=$r(r)?r:new ka(r)}}else t(`Expected a sequence for this tag`);return e}function So(e,t,n){let{replacer:r}=n,i=new Ha(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(Oa(o,s,n))}return i}var Co,wo=F((()=>{L(),Aa(),Ni(),Ua(),Co={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:xo,createNode:So}})),To,Eo,Do=F((()=>{L(),Ei(),Ra(),Ua(),wo(),To=class e extends Ha{constructor(){super(),this.add=La.prototype.add.bind(this),this.delete=La.prototype.delete.bind(this),this.get=La.prototype.get.bind(this),this.has=La.prototype.has.bind(this),this.set=La.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($r(e)?(r=Ti(e.key,``,t),i=Ti(e.value,r,t)):r=Ti(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=So(e,t,n),i=new this;return i.items=r.items,i}},To.tag=`tag:yaml.org,2002:omap`,Eo={collection:`seq`,identify:e=>e instanceof Map,nodeClass:To,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=xo(e,t),r=[];for(let{key:e}of n.items)ei(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new To,n)},createNode:(e,t,n)=>To.from(e,t,n)}}));function Oo({value:e,source:t},n){return t&&(e?ko:Ao).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var ko,Ao,jo=F((()=>{Ni(),ko={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 R(!0),stringify:Oo},Ao={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 R(!1),stringify:Oo}})),Mo,No,Po,Fo=F((()=>{Ni(),$a(),Mo={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:Qa},No={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():Qa(e)}},Po={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 R(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:Qa}}));function Io(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 Lo(e,t,n){let{value:r}=e;if(Ro(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return Qa(e)}var Ro,zo,Bo,Vo,Ho,Uo=F((()=>{$a(),Ro=e=>typeof e==`bigint`||Number.isInteger(e),zo={identify:Ro,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Io(e,2,2,n),stringify:e=>Lo(e,2,`0b`)},Bo={identify:Ro,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Io(e,1,8,n),stringify:e=>Lo(e,8,`0`)},Vo={identify:Ro,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Io(e,0,10,n),stringify:Qa},Ho={identify:Ro,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Io(e,2,16,n),stringify:e=>Lo(e,16,`0x`)}})),Wo,Go,Ko=F((()=>{L(),Aa(),Ra(),Wo=class e extends La{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=$r(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new ka(e.key,null):new ka(e,null),Ia(this.items,t.key)||this.items.push(t)}get(e,t){let n=Ia(this.items,e);return!t&&$r(n)?ei(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=Ia(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new ka(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(Oa(e,null,n));return i}},Wo.tag=`tag:yaml.org,2002:set`,Go={collection:`map`,identify:e=>e instanceof Set,nodeClass:Wo,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>Wo.from(e,t,n),resolve(e,t){if(Qr(e)){if(e.hasAllNullValues(!0))return Object.assign(new Wo,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}}}));function qo(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 Jo(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return Qa(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 Yo,Xo,Zo,Qo=F((()=>{$a(),Yo={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})=>qo(e,n),stringify:Jo},Xo={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=>qo(e,!1),stringify:Jo},Zo={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(Zo.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=qo(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$/,``)??``}})),$o,es=F((()=>{Ba(),Ya(),Ga(),qa(),bo(),jo(),Fo(),Uo(),wa(),Do(),wo(),Ko(),Qo(),$o=[za,Wa,Ka,Ja,ko,Ao,zo,Bo,Vo,Ho,Mo,No,Po,yo,Sa,Eo,Co,Go,Yo,Xo,Zo]}));function ts(e,t,n){let r=ns.get(t);if(r&&!e)return n&&!r.includes(Sa)?r.concat(Sa):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(ns.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(Sa)),i.reduce((e,t)=>{let n=typeof t==`string`?rs[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(rs).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 ns,rs,is,as=F((()=>{Ba(),Ya(),Ga(),qa(),Za(),ro(),uo(),po(),vo(),bo(),wa(),Do(),wo(),es(),Ko(),Qo(),ns=new Map([[`core`,fo],[`failsafe`,[za,Wa,Ka]],[`json`,_o],[`yaml11`,$o],[`yaml-1.1`,$o]]),rs={binary:yo,bool:Xa,float:no,floatExp:to,floatNaN:eo,floatTime:Xo,int:co,intHex:lo,intOct:so,intTime:Yo,map:za,merge:Sa,null:Ja,omap:Eo,pairs:Co,seq:Wa,set:Go,timestamp:Zo},is={"tag:yaml.org,2002:binary":yo,"tag:yaml.org,2002:merge":Sa,"tag:yaml.org,2002:omap":Eo,"tag:yaml.org,2002:pairs":Co,"tag:yaml.org,2002:set":Go,"tag:yaml.org,2002:timestamp":Zo}})),os,ss,cs=F((()=>{L(),Ba(),Ga(),qa(),as(),os=(e,t)=>e.key<t.key?-1:+(e.key>t.key),ss=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?ts(e,`compat`):e?ts(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?is:{},this.tags=ts(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,Gr,{value:za}),Object.defineProperty(this,qr,{value:Ka}),Object.defineProperty(this,Jr,{value:Wa}),this.sortMapEntries=typeof a==`function`?a:a===!0?os:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}}));function ls(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=la(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(Hi(t,``))}let o=!1,s=null;if(e.contents){if(Hr(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(Hi(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=fa(e.contents,i,()=>s=null,t);s&&(c+=Wi(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(fa(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
88
+ `)?(n.push(`...`),n.push(Hi(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(Hi(a(t),``)))}return n.join(`
89
89
  `)+`
90
- `}var ls=F((()=>{L(),fa(),Wi()}));function us(e){if(Br(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var ds,fs=F((()=>{Ai(),Bi(),L(),ka(),Ti(),ss(),ls(),xi(),Ci(),Ii(),gi(),ds=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Jr,{value:Ur});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 hi({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[Jr]:{value:Ur}});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=Vr(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){us(this.contents)&&this.contents.add(e)}addIn(e,t){us(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=vi(this);e.anchor=!t||n.has(t)?yi(t||`a`,n):t}return new ki(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}=bi(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=Pi(e,l,p);return o&&Br(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 Oa(r,i)}delete(e){return us(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ri(e)?this.contents!=null&&(this.contents=null,!0):us(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return Br(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Ri(e)?!t&&$r(this.contents)?this.contents.value:this.contents:Br(this.contents)?this.contents.getIn(e,t):void 0}has(e){return Br(this.contents)?this.contents.has(e):!1}hasIn(e){return Ri(e)?this.contents!==void 0:Br(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Li(this.schema,[e],t):us(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ri(e)?this.contents=t:this.contents==null?this.contents=Li(this.schema,Array.from(e),t):us(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 hi({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 hi({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 os(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=wi(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`?Si(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 cs(this,e)}}})),ps,ms,hs,gs,_s=F((()=>{ps=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},ms=class extends ps{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},hs=class extends ps{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},gs=(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 vs(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 ys=F((()=>{}));function bs(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(bs(t.key)||bs(t.value))return!0}return!1;default:return!0}}var xs=F((()=>{}));function Ss(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&bs(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}var Cs=F((()=>{xs()}));function ws(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||$r(e)&&$r(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var Ts=F((()=>{L()}));function Es({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??Ia)(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=vs(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`,Ds)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
93
- `+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||bs(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`,Ds);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&Ss(r.indent,u,i),n.atKey=!1,ws(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=vs(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&&Ss(r.indent,f,i),s=c.range[2];let l=new Oa(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 Oa(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 Ds,Os=F((()=>{ka(),La(),ys(),xs(),Cs(),Ts(),Ds=`All mapping items must start at the same column`}));function ks({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??Va)(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=vs(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&&Ss(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}var As=F((()=>{Ha(),ys(),Cs()}));function js(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 Ms=F((()=>{}));function Ns({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?Ia:Va))(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=vs(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&&bs(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];Qr(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],Fs(m)&&i(r.range,`BLOCK_IN_FLOW`,Ps)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);Fs(f)&&i(g.range,`BLOCK_IN_FLOW`,Ps),n.atKey=!1;let _=vs(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?Fs(m)&&i(v.range,`BLOCK_IN_FLOW`,Ps):_.comment&&(g.comment?g.comment+=`
97
- `+_.comment:g.comment=_.comment);let y=new Oa(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;ws(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new Ia(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=js(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 Ps,Fs,Is=F((()=>{L(),ka(),La(),Ha(),Ms(),ys(),xs(),Ts(),Ps=`Block collections are not allowed within flow collections`,Fs=e=>e&&(e.type===`block-map`||e.type===`block-seq`)}));function Ls(e,t,n,r,i,a){let o=n.type===`block-map`?Es(e,t,n,r,a):n.type===`block-seq`?ks(e,t,n,r,a):Ns(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function Rs(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===Ia.tagName&&s===`map`||o===Va.tagName&&s===`seq`)return Ls(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),Ls(e,t,n,i,o)}let l=Ls(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=Vr(u)?u:new R(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}var zs=F((()=>{L(),Mi(),La(),Ha(),Os(),As(),Is()}));function Bs(e,t,n){let r=t.offset,i=Vs(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?R.BLOCK_FOLDED:R.BLOCK_LITERAL,o=t.source?Hs(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 us=F((()=>{L(),pa(),Gi()}));function ds(e){if(Vr(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var fs,ps=F((()=>{ji(),Vi(),L(),Aa(),Ei(),cs(),us(),Si(),wi(),Li(),_i(),fs=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Yr,{value:Wr});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 gi({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[Yr]:{value:Wr}});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=Hr(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){ds(this.contents)&&this.contents.add(e)}addIn(e,t){ds(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=yi(this);e.anchor=!t||n.has(t)?bi(t||`a`,n):t}return new Ai(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}=xi(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=Fi(e,l,p);return o&&Vr(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 ka(r,i)}delete(e){return ds(this.contents)?this.contents.delete(e):!1}deleteIn(e){return zi(e)?this.contents!=null&&(this.contents=null,!0):ds(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return Vr(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return zi(e)?!t&&ei(this.contents)?this.contents.value:this.contents:Vr(this.contents)?this.contents.getIn(e,t):void 0}has(e){return Vr(this.contents)?this.contents.has(e):!1}hasIn(e){return zi(e)?this.contents!==void 0:Vr(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ri(this.schema,[e],t):ds(this.contents)&&this.contents.set(e,t)}setIn(e,t){zi(e)?this.contents=t:this.contents==null?this.contents=Ri(this.schema,Array.from(e),t):ds(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 gi({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 gi({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 ss(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=Ti(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`?Ci(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 ls(this,e)}}})),ms,hs,gs,_s,vs=F((()=>{ms=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},hs=class extends ms{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},gs=class extends ms{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},_s=(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 ys(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 bs=F((()=>{}));function xs(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(xs(t.key)||xs(t.value))return!0}return!1;default:return!0}}var Ss=F((()=>{}));function Cs(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&xs(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}var ws=F((()=>{Ss()}));function Ts(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||ei(e)&&ei(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var Es=F((()=>{L()}));function Ds({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??La)(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=ys(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`,Os)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
93
+ `+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||xs(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`,Os);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&Cs(r.indent,u,i),n.atKey=!1,Ts(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=ys(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&&Cs(r.indent,f,i),s=c.range[2];let l=new ka(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 ka(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 Os,ks=F((()=>{Aa(),Ra(),bs(),Ss(),ws(),Es(),Os=`All mapping items must start at the same column`}));function As({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??Ha)(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=ys(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&&Cs(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}var js=F((()=>{Ua(),bs(),ws()}));function Ms(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 Ns=F((()=>{}));function Ps({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?La:Ha))(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=ys(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&&xs(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];$r(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],Is(m)&&i(r.range,`BLOCK_IN_FLOW`,Fs)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);Is(f)&&i(g.range,`BLOCK_IN_FLOW`,Fs),n.atKey=!1;let _=ys(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?Is(m)&&i(v.range,`BLOCK_IN_FLOW`,Fs):_.comment&&(g.comment?g.comment+=`
97
+ `+_.comment:g.comment=_.comment);let y=new ka(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;Ts(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new La(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=Ms(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 Fs,Is,Ls=F((()=>{L(),Aa(),Ra(),Ua(),Ns(),bs(),Ss(),Es(),Fs=`Block collections are not allowed within flow collections`,Is=e=>e&&(e.type===`block-map`||e.type===`block-seq`)}));function Rs(e,t,n,r,i,a){let o=n.type===`block-map`?Ds(e,t,n,r,a):n.type===`block-seq`?As(e,t,n,r,a):Ps(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function zs(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===La.tagName&&s===`map`||o===Ha.tagName&&s===`seq`)return Rs(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),Rs(e,t,n,i,o)}let l=Rs(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=Hr(u)?u:new R(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}var Bs=F((()=>{L(),Ni(),Ra(),Ua(),ks(),js(),Ls()}));function Vs(e,t,n){let r=t.offset,i=Hs(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?R.BLOCK_FOLDED:R.BLOCK_LITERAL,o=t.source?Us(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
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===R.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
101
101
  `):t.length>c||r[0]===` `?(f===` `?f=`
@@ -110,149 +110,149 @@ $&`).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 Vs({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 Hs(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 Us=F((()=>{Mi()}));function Ws(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=R.PLAIN,c=Gs(a,l);break;case`single-quoted-scalar`:s=R.QUOTE_SINGLE,c=Ks(a,l);break;case`double-quoted-scalar`:s=R.QUOTE_DOUBLE,c=Js(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=js(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Gs(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}`),qs(e)}function Ks(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),qs(e.slice(1,-1)).replace(/''/g,`'`)}function qs(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 Hs({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 Us(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 Ws=F((()=>{Ni()}));function Gs(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=R.PLAIN,c=Ks(a,l);break;case`single-quoted-scalar`:s=R.QUOTE_SINGLE,c=qs(a,l);break;case`double-quoted-scalar`:s=R.QUOTE_DOUBLE,c=Ys(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=Ms(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Ks(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}`),Js(e)}function qs(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),Js(e.slice(1,-1)).replace(/''/g,`'`)}function Js(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 Js(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 Ys(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}=Ys(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=Zs[i];if(a)n+=a;else if(i===`
119
+ `){let{fold:t,offset:i}=Xs(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=Qs[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+=Xs(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+=Zs(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 Ys(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 Xs(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 Xs(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 Zs,Qs=F((()=>{Mi(),Ms(),Zs={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
128
- `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `}}));function $s(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?Bs(e,t,r):Ws(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[Kr]:c?ec(e.schema,i,c,n,r):t.type===`scalar`?tc(e,i,t,r):e.schema[Kr];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=$r(a)?a:new R(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new R(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 ec(e,t,n,r,i){if(n===`!`)return e[Kr];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[Kr])}function tc({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[Kr];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[Kr];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 nc=F((()=>{L(),Mi(),Us(),Qs()}));function rc(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 ic=F((()=>{}));function ac(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=sc(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=$s(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=Rs(cc,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??=oc(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&&(!$r(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 oc(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=$s(e,{type:`scalar`,offset:rc(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 sc({options:e},{offset:t,source:n,end:r},i){let a=new ki(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=js(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}var cc,lc=F((()=>{Ai(),L(),zs(),nc(),Ms(),ic(),cc={composeNode:ac,composeEmptyNode:oc}}));function uc(e,t,{offset:n,start:r,value:i,end:a},o){let s=Object.assign({_directives:t},e),c=new ds(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=vs(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?ac(l,i,u,o):oc(l,u.end,r,null,u,o);let d=c.contents.range[2],f=js(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,d,f.offset],c}var dc=F((()=>{fs(),lc(),Ms(),ys()}));function fc(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 pc(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 Zs(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 Qs,$s=F((()=>{Ni(),Ns(),Qs={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
128
+ `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `}}));function ec(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?Vs(e,t,r):Gs(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[qr]:c?tc(e.schema,i,c,n,r):t.type===`scalar`?nc(e,i,t,r):e.schema[qr];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=ei(a)?a:new R(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new R(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 tc(e,t,n,r,i){if(n===`!`)return e[qr];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[qr])}function nc({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[qr];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[qr];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 rc=F((()=>{L(),Ni(),Ws(),$s()}));function ic(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 ac=F((()=>{}));function oc(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=cc(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=ec(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=zs(lc,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??=sc(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&&(!ei(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 sc(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=ec(e,{type:`scalar`,offset:ic(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 cc({options:e},{offset:t,source:n,end:r},i){let a=new Ai(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=Ms(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}var lc,uc=F((()=>{ji(),L(),Bs(),rc(),Ns(),ac(),lc={composeNode:oc,composeEmptyNode:sc}}));function dc(e,t,{offset:n,start:r,value:i,end:a},o){let s=Object.assign({_directives:t},e),c=new fs(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=ys(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?oc(l,i,u,o):sc(l,u.end,r,null,u,o);let d=c.contents.range[2],f=Ms(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,d,f.offset],c}var fc=F((()=>{ps(),uc(),Ns(),bs()}));function pc(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 mc(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 mc,hc=F((()=>{gi(),fs(),_s(),L(),dc(),Ms(),mc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=fc(e);r?this.warnings.push(new hs(i,t,n)):this.errors.push(new ms(i,t,n))},this.directives=new hi({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=pc(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(Br(i)&&!i.flow&&i.items.length>0){let e=i.items[0];Qr(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:pc(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=fc(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=uc(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 ms(fc(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 ms(fc(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=js(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 ms(fc(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 ds(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 gc(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 ms([i,i+1],t,r)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return Ws(e,t,r);case`block-scalar`:return Bs({options:{strict:t}},e,r)}}return null}function _c(e,t){let{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:a=-1,type:o=`PLAIN`}=t,s=ra({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 hc,gc=F((()=>{_i(),ps(),vs(),L(),fc(),Ns(),hc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=pc(e);r?this.warnings.push(new gs(i,t,n)):this.errors.push(new hs(i,t,n))},this.directives=new gi({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=mc(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(Vr(i)&&!i.flow&&i.items.length>0){let e=i.items[0];$r(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:mc(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=pc(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=dc(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 hs(pc(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 hs(pc(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=Ms(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 hs(pc(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 fs(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 _c(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 hs([i,i+1],t,r)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return Gs(e,t,r);case`block-scalar`:return Vs({options:{strict:t}},e,r)}}return null}function vc(e,t){let{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:a=-1,type:o=`PLAIN`}=t,s=ia({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 bc(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 vc(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=ra({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`>`:yc(e,c);break;case`"`:xc(e,c,`double-quoted-scalar`);break;case`'`:xc(e,c,`single-quoted-scalar`);break;default:xc(e,c,`scalar`)}}function yc(e,t){let n=t.indexOf(`
134
+ `,i=[{type:`block-scalar-header`,offset:a,indent:r,source:t}];return xc(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 yc(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=ia({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`>`:bc(e,c);break;case`"`:Sc(e,c,`double-quoted-scalar`);break;case`'`:Sc(e,c,`single-quoted-scalar`);break;default:Sc(e,c,`scalar`)}}function bc(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}];bc(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 bc(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 xc(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 Sc=F((()=>{Us(),Qs(),_s(),sa()}));function Cc(e){switch(e.type){case`block-scalar`:{let t=``;for(let n of e.props)t+=Cc(n);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=wc(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=wc(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=wc(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 wc({start:e,key:t,sep:n,value:r}){let i=``;for(let t of e)i+=t.source;if(t&&(i+=Cc(t)),n)for(let e of n)i+=e.source;return r&&(i+=Cc(r)),i}var Tc,Ec=F((()=>{Tc=e=>`type`in e?Cc(e):wc(e)}));function Dc(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),Oc(Object.freeze([]),e,t)}function Oc(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=Oc(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===kc)return kc;else r===jc&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}var kc,Ac,jc,Mc=F((()=>{kc=Symbol(`break visit`),Ac=Symbol(`skip children`),jc=Symbol(`remove item`),Dc.BREAK=kc,Dc.SKIP=Ac,Dc.REMOVE=jc,Dc.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},Dc.parentCollection=(e,t)=>{let n=Dc.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`)}})),Nc=Ze({BOM:()=>``,DOCUMENT:()=>``,FLOW_END:()=>``,SCALAR:()=>``,createScalarToken:()=>_c,isCollection:()=>Ic,isScalar:()=>Lc,prettyToken:()=>Pc,resolveAsScalar:()=>gc,setScalarValue:()=>vc,stringify:()=>Tc,tokenType:()=>Fc,visit:()=>Dc});function Pc(e){switch(e){case``:return`<BOM>`;case``:return`<DOC>`;case``:return`<FLOW_END>`;case``:return`<SCALAR>`;default:return JSON.stringify(e)}}function Fc(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}];xc(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 xc(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 Sc(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 Cc=F((()=>{Ws(),$s(),vs(),ca()}));function wc(e){switch(e.type){case`block-scalar`:{let t=``;for(let n of e.props)t+=wc(n);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=Tc(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=Tc(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=Tc(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 Tc({start:e,key:t,sep:n,value:r}){let i=``;for(let t of e)i+=t.source;if(t&&(i+=wc(t)),n)for(let e of n)i+=e.source;return r&&(i+=wc(r)),i}var Ec,Dc=F((()=>{Ec=e=>`type`in e?wc(e):Tc(e)}));function Oc(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),kc(Object.freeze([]),e,t)}function kc(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=kc(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===Ac)return Ac;else r===Mc&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}var Ac,jc,Mc,Nc=F((()=>{Ac=Symbol(`break visit`),jc=Symbol(`skip children`),Mc=Symbol(`remove item`),Oc.BREAK=Ac,Oc.SKIP=jc,Oc.REMOVE=Mc,Oc.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},Oc.parentCollection=(e,t)=>{let n=Oc.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`)}})),Pc=Qe({BOM:()=>``,DOCUMENT:()=>``,FLOW_END:()=>``,SCALAR:()=>``,createScalarToken:()=>vc,isCollection:()=>Lc,isScalar:()=>Rc,prettyToken:()=>Fc,resolveAsScalar:()=>_c,setScalarValue:()=>yc,stringify:()=>Ec,tokenType:()=>Ic,visit:()=>Oc});function Fc(e){switch(e){case``:return`<BOM>`;case``:return`<DOC>`;case``:return`<FLOW_END>`;case``:return`<SCALAR>`;default:return JSON.stringify(e)}}function Ic(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 Ic,Lc,Rc=F((()=>{Sc(),Ec(),Mc(),Ic=e=>!!e&&`items`in e,Lc=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`)}));function zc(e){switch(e){case void 0:case` `:case`
142
- `:case`\r`:case` `:return!0;default:return!1}}var Bc,Vc,Hc,Uc,Wc,Gc,Kc=F((()=>{Rc(),Bc=new Set(`0123456789ABCDEFabcdef`),Vc=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),Hc=new Set(`,[]{}`),Uc=new Set(` ,[]{}
143
- \r `),Wc=e=>!e||Uc.has(e),Gc=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 Lc,Rc,zc=F((()=>{Cc(),Dc(),Nc(),Lc=e=>!!e&&`items`in e,Rc=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`)}));function Bc(e){switch(e){case void 0:case` `:case`
142
+ `:case`\r`:case` `:return!0;default:return!1}}var Vc,Hc,Uc,Wc,Gc,Kc,qc=F((()=>{zc(),Vc=new Set(`0123456789ABCDEFabcdef`),Hc=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),Uc=new Set(`,[]{}`),Wc=new Set(` ,[]{}
143
+ \r `),Gc=e=>!e||Wc.has(e),Kc=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===`...`)&&zc(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===`...`)&&zc(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&&!zc(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===`:`)&&zc(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(Wc),`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(`...`))&&zc(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(Wc),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||zc(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===`...`)&&Bc(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===`...`)&&Bc(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&&!Bc(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===`:`)&&Bc(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(Gc),`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(`...`))&&Bc(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(Gc),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||Bc(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=>zc(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=>Bc(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(zc(r)||e&&Hc.has(r))break;t=n}else if(zc(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(Bc(r)||e&&Uc.has(r))break;t=n}else if(Bc(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&&Hc.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&&Hc.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(Wc),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(zc(n)||t&&Hc.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(;!zc(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(Vc.has(t))t=this.buffer[++e];else if(t===`%`&&Bc.has(this.buffer[e+1])&&Bc.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&&Uc.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&&Uc.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(Gc),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(Bc(n)||t&&Uc.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(;!Bc(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(Hc.has(t))t=this.buffer[++e];else if(t===`%`&&Vc.has(this.buffer[e+1])&&Vc.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)}}})),qc,Jc=F((()=>{qc=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 Yc(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Xc(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 Zc(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 Qc(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 $c(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 el(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 tl(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!Yc(t.start,`explicit-key-ind`)&&!Yc(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,Zc(t.value)?t.value.end?el(t.value.end,t.sep):t.value.end=t.sep:el(t.start,t.sep),delete t.sep)}var nl,rl=F((()=>{Rc(),Kc(),nl=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 Gc,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=Fc(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`&&tl(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&&Xc(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`:Xc(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=$c(Qc(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)}}})),Jc,Yc=F((()=>{Jc=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 Xc(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Zc(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 Qc(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 $c(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 el(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 tl(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 nl(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!Xc(t.start,`explicit-key-ind`)&&!Xc(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,Qc(t.value)?t.value.end?tl(t.value.end,t.sep):t.value.end=t.sep:tl(t.start,t.sep),delete t.sep)}var rl,il=F((()=>{zc(),qc(),rl=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 Kc,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=Ic(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`&&nl(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&&Zc(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`:Zc(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=el($c(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)){el(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(Yc(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=$c(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(Yc(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(Zc(t.key)&&!Yc(t.sep,`newline`)){let e=$c(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]}):Yc(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&&!Yc(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)){el(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||Yc(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=$c(Qc(t));tl(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)){tl(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(Xc(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=el(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(Xc(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(Qc(t.key)&&!Xc(t.sep,`newline`)){let e=el(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]}):Xc(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&&!Xc(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)){tl(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||Xc(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=el($c(t));nl(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=$c(Qc(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=$c(Qc(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 il(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new qc||null,prettyErrors:t}}function al(e,t={}){let{lineCounter:n,prettyErrors:r}=il(t),i=new nl(n?.addNewLine),a=new mc(t),o=Array.from(a.compose(i.parse(e)));if(r&&n)for(let t of o)t.errors.forEach(gs(e,n)),t.warnings.forEach(gs(e,n));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function ol(e,t={}){let{lineCounter:n,prettyErrors:r}=il(t),i=new nl(n?.addNewLine),a=new mc(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 ms(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(gs(e,n)),o.warnings.forEach(gs(e,n))),o}function sl(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let i=ol(e,n);if(!i)return null;if(i.warnings.forEach(e=>ha(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 cl(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 Xr(e)&&!r?e.toString(n):new ds(e,r,n).toString(n)}var ll=F((()=>{hc(),fs(),_s(),ga(),L(),Jc(),rl()})),ul=Ze({Alias:()=>ki,CST:()=>Nc,Composer:()=>mc,Document:()=>ds,Lexer:()=>Gc,LineCounter:()=>qc,Pair:()=>Oa,Parser:()=>nl,Scalar:()=>R,Schema:()=>os,YAMLError:()=>ps,YAMLMap:()=>Ia,YAMLParseError:()=>ms,YAMLSeq:()=>Va,YAMLWarning:()=>hs,isAlias:()=>Yr,isCollection:()=>Br,isDocument:()=>Xr,isMap:()=>Zr,isNode:()=>Vr,isPair:()=>Qr,isScalar:()=>$r,isSeq:()=>ei,parse:()=>sl,parseAllDocuments:()=>al,parseDocument:()=>ol,stringify:()=>cl,visit:()=>ni,visitAsync:()=>ii}),dl=F((()=>{hc(),fs(),ss(),_s(),Ai(),L(),ka(),Mi(),La(),Ha(),Rc(),Kc(),Jc(),rl(),ll(),fi()})),fl=Ze({Alias:()=>ki,CST:()=>Nc,Composer:()=>mc,Document:()=>ds,Lexer:()=>Gc,LineCounter:()=>qc,Pair:()=>Oa,Parser:()=>nl,Scalar:()=>R,Schema:()=>os,YAMLError:()=>ps,YAMLMap:()=>Ia,YAMLParseError:()=>ms,YAMLSeq:()=>Va,YAMLWarning:()=>hs,default:()=>pl,isAlias:()=>Yr,isCollection:()=>Br,isDocument:()=>Xr,isMap:()=>Zr,isNode:()=>Vr,isPair:()=>Qr,isScalar:()=>$r,isSeq:()=>ei,parse:()=>sl,parseAllDocuments:()=>al,parseDocument:()=>ol,stringify:()=>cl,visit:()=>ni,visitAsync:()=>ii}),pl,ml=F((()=>{dl(),dl(),pl=ul}));async function hl(){return _l??=await Promise.resolve().then(()=>(ml(),fl)),_l}function gl(){return _l??=s(import.meta.url)(`yaml`),_l}var _l,vl=F((()=>{}));function yl(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 Lr(e,2)}return t===`yaml`?gl().stringify(e):t===`md`?El(e):t===`jsonl`?Array.isArray(e)?e.map(e=>Lr(e)).join(`
165
- `):Lr(e):bl(e)?String(e):Or(e)}function bl(e){return typeof e!=`object`||!e}function xl(e){return Object.values(e).every(bl)}function Sl(e){return Array.isArray(e)&&e.length>0&&e.every(e=>typeof e==`object`&&!!e&&!Array.isArray(e))}function Cl(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 wl(e){return Cl([`Key`,`Value`],Object.entries(e).map(([e,t])=>[e,String(t)]))}function Tl(e){let t=[...new Set(e.flatMap(Object.keys))];return Cl(t,e.map(e=>t.map(t=>String(e[t]??``))))}function El(e,t=[]){if(bl(e))return t.length===0?String(e):`## ${t.join(`.`)}\n\n${String(e)}`;if(Array.isArray(e)){if(Sl(e)){let n=Tl(e);return t.length===0?n:`## ${t.join(`.`)}\n\n${n}`}return El(String(e),t)}let n=e,r=Object.entries(n);return t.length===0&&xl(n)?wl(n):t.length>0||r.length>1||r.some(([,e])=>!bl(e))?r.map(([e,n])=>{let r=[...t,e];if(bl(n))return`## ${r.join(`.`)}\n\n${String(n)}`;if(Sl(n))return`## ${r.join(`.`)}\n\n${Tl(n)}`;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=n;return xl(e)?`## ${r.join(`.`)}\n\n${wl(e)}`:El(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=el($c(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=el($c(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 al(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Jc||null,prettyErrors:t}}function ol(e,t={}){let{lineCounter:n,prettyErrors:r}=al(t),i=new rl(n?.addNewLine),a=new hc(t),o=Array.from(a.compose(i.parse(e)));if(r&&n)for(let t of o)t.errors.forEach(_s(e,n)),t.warnings.forEach(_s(e,n));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function sl(e,t={}){let{lineCounter:n,prettyErrors:r}=al(t),i=new rl(n?.addNewLine),a=new hc(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 hs(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(_s(e,n)),o.warnings.forEach(_s(e,n))),o}function cl(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let i=sl(e,n);if(!i)return null;if(i.warnings.forEach(e=>ga(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 ll(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 Zr(e)&&!r?e.toString(n):new fs(e,r,n).toString(n)}var ul=F((()=>{gc(),ps(),vs(),_a(),L(),Yc(),il()})),dl=Qe({Alias:()=>Ai,CST:()=>Pc,Composer:()=>hc,Document:()=>fs,Lexer:()=>Kc,LineCounter:()=>Jc,Pair:()=>ka,Parser:()=>rl,Scalar:()=>R,Schema:()=>ss,YAMLError:()=>ms,YAMLMap:()=>La,YAMLParseError:()=>hs,YAMLSeq:()=>Ha,YAMLWarning:()=>gs,isAlias:()=>Xr,isCollection:()=>Vr,isDocument:()=>Zr,isMap:()=>Qr,isNode:()=>Hr,isPair:()=>$r,isScalar:()=>ei,isSeq:()=>ti,parse:()=>cl,parseAllDocuments:()=>ol,parseDocument:()=>sl,stringify:()=>ll,visit:()=>ri,visitAsync:()=>ai}),fl=F((()=>{gc(),ps(),cs(),vs(),ji(),L(),Aa(),Ni(),Ra(),Ua(),zc(),qc(),Yc(),il(),ul(),pi()})),pl=Qe({Alias:()=>Ai,CST:()=>Pc,Composer:()=>hc,Document:()=>fs,Lexer:()=>Kc,LineCounter:()=>Jc,Pair:()=>ka,Parser:()=>rl,Scalar:()=>R,Schema:()=>ss,YAMLError:()=>ms,YAMLMap:()=>La,YAMLParseError:()=>hs,YAMLSeq:()=>Ha,YAMLWarning:()=>gs,default:()=>ml,isAlias:()=>Xr,isCollection:()=>Vr,isDocument:()=>Zr,isMap:()=>Qr,isNode:()=>Hr,isPair:()=>$r,isScalar:()=>ei,isSeq:()=>ti,parse:()=>cl,parseAllDocuments:()=>ol,parseDocument:()=>sl,stringify:()=>ll,visit:()=>ri,visitAsync:()=>ai}),ml,hl=F((()=>{fl(),fl(),ml=dl}));async function gl(){return vl??=await Promise.resolve().then(()=>(hl(),pl)),vl}function _l(){return vl??=s(import.meta.url)(`yaml`),vl}var vl,yl=F((()=>{}));function bl(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 Rr(e,2)}return t===`yaml`?_l().stringify(e):t===`md`?Dl(e):t===`jsonl`?Array.isArray(e)?e.map(e=>Rr(e)).join(`
165
+ `):Rr(e):xl(e)?String(e):kr(e)}function xl(e){return typeof e!=`object`||!e}function Sl(e){return Object.values(e).every(xl)}function Cl(e){return Array.isArray(e)&&e.length>0&&e.every(e=>typeof e==`object`&&!!e&&!Array.isArray(e))}function wl(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 Tl(e){return wl([`Key`,`Value`],Object.entries(e).map(([e,t])=>[e,String(t)]))}function El(e){let t=[...new Set(e.flatMap(Object.keys))];return wl(t,e.map(e=>t.map(t=>String(e[t]??``))))}function Dl(e,t=[]){if(xl(e))return t.length===0?String(e):`## ${t.join(`.`)}\n\n${String(e)}`;if(Array.isArray(e)){if(Cl(e)){let n=El(e);return t.length===0?n:`## ${t.join(`.`)}\n\n${n}`}return Dl(String(e),t)}let n=e,r=Object.entries(n);return t.length===0&&Sl(n)?Tl(n):t.length>0||r.length>1||r.some(([,e])=>!xl(e))?r.map(([e,n])=>{let r=[...t,e];if(xl(n))return`## ${r.join(`.`)}\n\n${String(n)}`;if(Cl(n))return`## ${r.join(`.`)}\n\n${El(n)}`;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=n;return Sl(e)?`## ${r.join(`.`)}\n\n${Tl(e)}`:Dl(e,r)}return`## ${r.join(`.`)}\n\n${String(n)}`}).join(`
167
167
 
168
- `):wl(n)}var Dl=F((()=>{Ir(),zr(),vl()}));function Ol(e,t={}){let{args:n,options:r,alias:i,defaults:a}=t,o=kl(r,i),s=[],c={},l=0;for(;l<e.length;){let t=e[l];if(t.startsWith(`--no-`)&&t.length>5){let e=Al(t.slice(5),o);if(!e)throw new Tn({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=Al(e,o);if(!i)throw new Tn({message:`Unknown flag: --${e}`});Il(c,i,t.slice(n+1),r),l++}else{let n=Al(t.slice(2),o);if(!n)throw new Tn({message:`Unknown flag: ${t}`});if(Pl(n,r))c[n]=(c[n]??0)+1,l++;else if(Nl(n,r))c[n]=!0,l++;else{let i=e[l+1];if(i===void 0)throw new Tn({message:`Missing value for flag: ${t}`});Il(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 Tn({message:`Unknown flag: -${i}`});if(t!==n.length-1){if(Pl(a,r))c[a]=(c[a]??0)+1;else if(Nl(a,r))c[a]=!0;else throw new Tn({message:`Non-boolean flag -${i} must be last in a stacked alias`})}else if(Pl(a,r))c[a]=(c[a]??0)+1;else if(Nl(a,r))c[a]=!0;else{let t=e[l+1];if(t===void 0)throw new Tn({message:`Missing value for flag: -${i}`});Il(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(Fl(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?Ll(n,u):{},f=jl(a,r,o);if(r)for(let[e,t]of Object.entries(c))c[e]=Vl(t,e,r);let p={...f,...c};return{args:d,options:r?Ll(r,p):{}}}function kl(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=rn(e);t!==e&&i.set(t,e)}return{aliasToName:n,kebabToCamel:i,knownOptions:r}}function Al(e,t){let n=t.kebabToCamel.get(e)??e;return t.knownOptions.has(n)?n:void 0}function jl(e,t,n){if(e===void 0)return{};if(!nn(e))throw new Tn({message:`Invalid config section: expected an object of option defaults`});if(!t){let[t]=Object.keys(e);if(t)throw new Tn({message:`Unknown config option: ${t}`});return{}}let r={};for(let[t,i]of Object.entries(e)){let e=Al(t,n);if(!e)throw new Tn({message:`Unknown config option: ${t}`});r[e]=i}return r}function Ml(e){let t=e;for(;t.def?.innerType;)t=t.def.innerType;return t}function Nl(e,t){if(!t)return!1;let n=t.shape[e];return n?Ml(n).constructor.name===`ZodBoolean`:!1}function Pl(e,t){if(!t)return!1;let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0:!1}function Fl(e,t){if(!t)return!1;let n=t.shape[e];return n?Ml(n).constructor.name===`ZodArray`:!1}function Il(e,t,n,r){if(Fl(t,r)){let r=e[t];Array.isArray(r)?r.push(n):e[t]=[n]}else e[t]=n}function Ll(e,t){try{return e.parse(t)}catch(e){let n=e?.issues??e?.error?.issues??[],r=n.map(e=>({code:e.code,missing:!Rl(t,e.path??[]),path:(e.path??[]).join(`.`),expected:e.expected??``,received:e.received??``,message:e.message??``}));throw new wn({message:n.map(e=>e.message).join(`; `)||`Validation failed`,fieldErrors:r,cause:e instanceof Error?e:void 0})}}function Rl(e,t){if(t.length===0)return!0;let n=e;for(let e of t){if(!nn(n)&&!Array.isArray(n)||!(e in n))return!1;n=n[e]}return!0}function zl(e,t=Ul()){let n={};for(let[r,i]of Object.entries(e.shape)){let e=t[r];e!==void 0&&(n[r]=Bl(e,i))}return Ll(e,n)}function Bl(e,t){let n=Ml(t).constructor.name;return n===`ZodNumber`?Number(e):n===`ZodBoolean`?e===`true`||e===`1`:e}function Vl(e,t,n){let r=n.shape[t];if(!r)return e;let i=Ml(r).constructor.name;return i===`ZodNumber`&&typeof e==`string`?Number(e):i===`ZodBoolean`&&typeof e==`string`?e===`true`:e}function Hl(e,t,n,r={}){let i=kl(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=Al(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=Al(n.slice(2,r),i);e?Il(o,e,n.slice(r+1),t):a.push(n),s++}else{let r=Al(n.slice(2),i);if(!r)a.push(n),s++;else if(Pl(r,t))o[r]=(o[r]??0)+1,s++;else if(Nl(r,t))o[r]=!0,s++;else{let i=e[s+1];if(i===void 0)throw new Tn({message:`Missing value for flag: ${n}`});Il(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(Pl(c,t))o[c]=(o[c]??0)+1;else if(Nl(c,t))o[c]=!0;else throw new Tn({message:`Non-boolean flag -${a} must be last in a stacked alias`})}else if(Pl(c,t))o[c]=(o[c]??0)+1;else if(Nl(c,t))o[c]=!0;else{let n=e[s+1];if(n===void 0)throw new Tn({message:`Missing value for flag: -${a}`});Il(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]=Vl(n,e,t);return{parsed:Ll(t,o),rest:a}}function Ul(){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 Wl=F((()=>{En(),sn()}));async function Gl(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=Ol(n,{alias:e.alias,args:e.args,defaults:t.defaults,options:e.options});c=r.args,d=r.options}else if(_===`split`)c=Ol(n,{args:e.args}).args,d=e.options?Ll(e.options,r):{};else{let t=Kl(r,e);c=e.args?Ll(e.args,t.args):{},d=e.options?Ll(e.options,t.options):{}}let p=e.env?zl(e.env,u):{},C=e.run({agent:i,args:c,displayName:g,env:p,error:e=>({[Ql]:`error`,...e}),format:a,formatExplicit:o,globals:f,name:s,ok:(e,t={})=>({[Ql]:`ok`,data:e,cta:t.cta}),options:d,request:h,var:v,version:l});if(Jl(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(ql(w)){if(w[Ql]===`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?zl(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 wn?{ok:!1,error:{code:`VALIDATION_ERROR`,message:e.message,fieldErrors:e.fieldErrors}}:{ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof I?{retryable:e.retryable}:void 0},...e instanceof I&&e.exitCode!==void 0?{exitCode:e.exitCode}:void 0}}return y??{ok:!0,data:void 0}}function Kl(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 ql(e){return typeof e==`object`&&!!e&&Ql in e}function Jl(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e&&typeof e.next==`function`}function Yl(e){return e}function Xl(e){return eu.find(t=>t.name===e||t.aliases?.includes(e))}function Zl(e,t){return e.subcommands?.find(e=>e.name===t||e.aliases?.includes(t))}var Ql,$l,eu,tu=F((()=>{En(),Wl(),Ql=Symbol.for(`incur.sentinel`),$l=[`bash`,`fish`,`nushell`,`zsh`],eu=[{name:`completions`,description:`Generate shell completion script`,args:f.object({shell:f.enum($l).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
+ `):Tl(n)}var Ol=F((()=>{Lr(),Br(),yl()}));function kl(e,t={}){let{args:n,options:r,alias:i,defaults:a}=t,o=Al(r,i),s=[],c={},l=0;for(;l<e.length;){let t=e[l];if(t.startsWith(`--no-`)&&t.length>5){let e=jl(t.slice(5),o);if(!e)throw new En({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=jl(e,o);if(!i)throw new En({message:`Unknown flag: --${e}`});Ll(c,i,t.slice(n+1),r),l++}else{let n=jl(t.slice(2),o);if(!n)throw new En({message:`Unknown flag: ${t}`});if(Fl(n,r))c[n]=(c[n]??0)+1,l++;else if(Pl(n,r))c[n]=!0,l++;else{let i=e[l+1];if(i===void 0)throw new En({message:`Missing value for flag: ${t}`});Ll(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 En({message:`Unknown flag: -${i}`});if(t!==n.length-1){if(Fl(a,r))c[a]=(c[a]??0)+1;else if(Pl(a,r))c[a]=!0;else throw new En({message:`Non-boolean flag -${i} must be last in a stacked alias`})}else if(Fl(a,r))c[a]=(c[a]??0)+1;else if(Pl(a,r))c[a]=!0;else{let t=e[l+1];if(t===void 0)throw new En({message:`Missing value for flag: -${i}`});Ll(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(Il(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?Rl(n,u):{},f=Ml(a,r,o);if(r)for(let[e,t]of Object.entries(c))c[e]=Hl(t,e,r);let p={...f,...c};return{args:d,options:r?Rl(r,p):{}}}function Al(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=an(e);t!==e&&i.set(t,e)}return{aliasToName:n,kebabToCamel:i,knownOptions:r}}function jl(e,t){let n=t.kebabToCamel.get(e)??e;return t.knownOptions.has(n)?n:void 0}function Ml(e,t,n){if(e===void 0)return{};if(!rn(e))throw new En({message:`Invalid config section: expected an object of option defaults`});if(!t){let[t]=Object.keys(e);if(t)throw new En({message:`Unknown config option: ${t}`});return{}}let r={};for(let[t,i]of Object.entries(e)){let e=jl(t,n);if(!e)throw new En({message:`Unknown config option: ${t}`});r[e]=i}return r}function Nl(e){let t=e;for(;t.def?.innerType;)t=t.def.innerType;return t}function Pl(e,t){if(!t)return!1;let n=t.shape[e];return n?Nl(n).constructor.name===`ZodBoolean`:!1}function Fl(e,t){if(!t)return!1;let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0:!1}function Il(e,t){if(!t)return!1;let n=t.shape[e];return n?Nl(n).constructor.name===`ZodArray`:!1}function Ll(e,t,n,r){if(Il(t,r)){let r=e[t];Array.isArray(r)?r.push(n):e[t]=[n]}else e[t]=n}function Rl(e,t){try{return e.parse(t)}catch(e){let n=e?.issues??e?.error?.issues??[],r=n.map(e=>({code:e.code,missing:!zl(t,e.path??[]),path:(e.path??[]).join(`.`),expected:e.expected??``,received:e.received??``,message:e.message??``}));throw new Tn({message:n.map(e=>e.message).join(`; `)||`Validation failed`,fieldErrors:r,cause:e instanceof Error?e:void 0})}}function zl(e,t){if(t.length===0)return!0;let n=e;for(let e of t){if(!rn(n)&&!Array.isArray(n)||!(e in n))return!1;n=n[e]}return!0}function Bl(e,t=Wl()){let n={};for(let[r,i]of Object.entries(e.shape)){let e=t[r];e!==void 0&&(n[r]=Vl(e,i))}return Rl(e,n)}function Vl(e,t){let n=Nl(t).constructor.name;return n===`ZodNumber`?Number(e):n===`ZodBoolean`?e===`true`||e===`1`:e}function Hl(e,t,n){let r=n.shape[t];if(!r)return e;let i=Nl(r).constructor.name;return i===`ZodNumber`&&typeof e==`string`?Number(e):i===`ZodBoolean`&&typeof e==`string`?e===`true`:e}function Ul(e,t,n,r={}){let i=Al(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=jl(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=jl(n.slice(2,r),i);e?Ll(o,e,n.slice(r+1),t):a.push(n),s++}else{let r=jl(n.slice(2),i);if(!r)a.push(n),s++;else if(Fl(r,t))o[r]=(o[r]??0)+1,s++;else if(Pl(r,t))o[r]=!0,s++;else{let i=e[s+1];if(i===void 0)throw new En({message:`Missing value for flag: ${n}`});Ll(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(Fl(c,t))o[c]=(o[c]??0)+1;else if(Pl(c,t))o[c]=!0;else throw new En({message:`Non-boolean flag -${a} must be last in a stacked alias`})}else if(Fl(c,t))o[c]=(o[c]??0)+1;else if(Pl(c,t))o[c]=!0;else{let n=e[s+1];if(n===void 0)throw new En({message:`Missing value for flag: -${a}`});Ll(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]=Hl(n,e,t);return{parsed:Rl(t,o),rest:a}}function Wl(){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 Gl=F((()=>{Dn(),cn()}));async function Kl(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=kl(n,{alias:e.alias,args:e.args,defaults:t.defaults,options:e.options});c=r.args,d=r.options}else if(_===`split`)c=kl(n,{args:e.args}).args,d=e.options?Rl(e.options,r):{};else{let t=ql(r,e);c=e.args?Rl(e.args,t.args):{},d=e.options?Rl(e.options,t.options):{}}let p=e.env?Bl(e.env,u):{},C=e.run({agent:i,args:c,displayName:g,env:p,error:e=>({[$l]:`error`,...e}),format:a,formatExplicit:o,globals:f,name:s,ok:(e,t={})=>({[$l]:`ok`,data:e,cta:t.cta}),options:d,request:h,var:v,version:l});if(Yl(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(Jl(w)){if(w[$l]===`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?Bl(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 Tn?{ok:!1,error:{code:`VALIDATION_ERROR`,message:e.message,fieldErrors:e.fieldErrors}}:{ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof I?{retryable:e.retryable}:void 0},...e instanceof I&&e.exitCode!==void 0?{exitCode:e.exitCode}:void 0}}return y??{ok:!0,data:void 0}}function ql(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 Jl(e){return typeof e==`object`&&!!e&&$l in e}function Yl(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e&&typeof e.next==`function`}function Xl(e){return e}function Zl(e){return tu.find(t=>t.name===e||t.aliases?.includes(e))}function Ql(e,t){return e.subcommands?.find(e=>e.name===t||e.aliases?.includes(t))}var $l,eu,tu,nu=F((()=>{Dn(),Gl(),$l=Symbol.for(`incur.sentinel`),eu=[`bash`,`fish`,`nushell`,`zsh`],tu=[{name:`completions`,description:`Generate shell completion script`,args:f.object({shell:f.enum(eu).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:[Yl({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`)})}),Yl({name:`doctor`,description:`Validate MCP server startup and tool listing`})]},{name:`skills`,aliases:[`skill`],description:`Sync skill files to agents`,subcommands:[Yl({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`)})}),Yl({name:`list`,aliases:[`ls`],description:`List skills`})]}]}));function nu(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(...pu(c,r,a)),l.join(`
171
- `)}function ru(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=iu(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=au(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=su(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(...pu(f,i,o)),l){let e=ou(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??Ul();n.name in i&&r.push(`set: ${mu(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 iu(e,t){if(!t)return e;let n=[e];for(let[e,r]of Object.entries(t.shape)){let t=cu(r),i=(t.includes(`|`)?t:e)+(t===`array`?`...`:``);n.push(r._zod.optout===`optional`?`[${i}]`:`<${i}>`)}return n.join(` `)}function au(e){let t=[];for(let[n,r]of Object.entries(e.shape))t.push({name:n,description:r.description??``});return t}function ou(e){let t=[];for(let[n,r]of Object.entries(e.shape)){let e=du(r);t.push({name:n,description:r.description??``,defaultValue:e})}return t}function su(e,t){let n=[];for(let[r,i]of Object.entries(e.shape)){let e=cu(i),a=t?.[r],o=rn(r),s=e===`boolean`?``:` <${e}>`,c=a?`--${o}, -${a}${s}`:`--${o}${s}`,l=du(i);e===`boolean`&&l===!1&&(l=void 0);let u=fu(i);n.push({flag:c,description:i.description??``,defaultValue:l,deprecated:u})}return n}function cu(e){if(lu(e))return`count`;let t=uu(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 lu(e){let t=e;return typeof t?.meta==`function`&&t.meta()?.count===!0}function uu(e){return e instanceof f.ZodOptional?uu(e.unwrap()):e instanceof f.ZodDefault?uu(e.removeDefault()):e instanceof f.ZodNullable?uu(e.unwrap()):e}function du(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 du(e.unwrap())}function fu(e){return e?.meta?.()?.deprecated===!0||void 0}function pu(e=!1,t,n){let r=[];if(e){let e=eu.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=su(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 mu(e){return e.length<=4?`****`:`****${e.slice(-4)}`}var hu=F((()=>{tu(),sn(),Wl()}));function gu(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=>vu(e,t))}}function _u(e){let t=[e.description];for(let n of e.commands)t.push(` ${n.command}${n.description?` - ${n.description}`:``}`);return t.join(`
173
- `)}function vu(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 yu=F((()=>{}));async function bu(e,t={}){let n=[],r=t.exclude?c.resolve(t.exclude):void 0;async function i(e,t){let a=await C.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()){Cu(o.name,a),await i(a,[...t,o.name]);continue}if(!o.isFile()||a===r)continue;let s=wu.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}Cu(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 xu(){return globalThis[Symbol.for(Eu)]?.shift()}async function Su(e){return Promise.all(e.map(async({load:e,...t})=>({...t,command:await e()})))}function Cu(e,t){if(!Tu.test(e))throw Error(`Invalid filesystem command segment '${e}' from '${t}'. Use lowercase kebab-case names.`)}var wu,Tu,Eu,Du=F((()=>{wu=[`.cts`,`.cjs`,`.mts`,`.mjs`,`.ts`,`.js`],Tu=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Eu=`incur.fs.manifests`}));function Ou(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 ku=F((()=>{}));function Au(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(!Au(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(!Au(e[r],t[r]))return!1;return!0}return e===t}var ju=F((()=>{}));function Mu(e){return encodeURI(Nu(e))}function Nu(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var Pu=F((()=>{}));function Fu(e,t=Object.create(null),n=zu,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:Fu(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(Ru[i])continue;let a=`${r}/${Mu(i)}`,o=e[i];if(Array.isArray(o)){if(Iu[i]){let e=o.length;for(let r=0;r<e;r++)Fu(o[r],t,n,`${a}/${r}`)}}else if(Lu[i])for(let e in o)Fu(o[e],t,n,`${a}/${Mu(e)}`);else Fu(o,t,n,a)}return t}var Iu,Lu,Ru,zu,Bu=F((()=>{Pu(),Iu={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Lu={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Ru={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},zu=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 Vu(e){return e.test.bind(e)}function Hu(e){return e%4==0&&(e%100!=0||e%400==0)}function Uu(e){let t=e.match(Ju);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&Hu(n)?29:Yu[r])}function Wu(e,t){let n=t.match(Xu);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 Gu(e){let t=e.split(ud);return t.length==2&&Uu(t[0])&&Wu(!0,t[1])}function Ku(e){return dd.test(e)&&fd.test(e)}function qu(e){if(pd.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}var Ju,Yu,Xu,Zu,Qu,$u,ed,td,nd,rd,id,ad,od,sd,cd,ld,ud,dd,fd,pd,md=F((()=>{Ju=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Yu=[0,31,28,31,30,31,30,31,31,30,31,30,31],Xu=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Zu=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,Qu=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,$u=/^(?:(?:[^\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,ed=/^(?:(?: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,td=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,nd=/^(?:\/(?:[^~/]|~0|~1)*)*$/,rd=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,id=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,ad=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))},od=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,sd=/^((([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,cd=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)),ld={date:Uu,time:Wu.bind(void 0,!1),"date-time":Gu,duration:cd,uri:Ku,"uri-reference":Vu(Qu),"uri-template":Vu($u),url:Vu(ed),email:ad,hostname:Vu(Zu),ipv4:Vu(od),ipv6:Vu(sd),regex:qu,uuid:Vu(td),"json-pointer":Vu(nd),"json-pointer-uri-fragment":Vu(rd),"relative-json-pointer":Vu(id)},ud=/t|\s/i,dd=/\/|:/,fd=/^(?:[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,pd=/[^\\]\\Z/})),hd=F((()=>{}));function gd(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 _d=F((()=>{}));function vd(e,t,n=`2019-09`,r=Fu(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:C,else:w,format:T,properties:ee,patternProperties:E,additionalProperties:D,unevaluatedProperties:O,minProperties:k,maxProperties:te,propertyNames:ne,dependentRequired:re,dependentSchemas:A,dependencies:j,prefixItems:ie,items:ae,additionalItems:oe,unevaluatedItems:se,contains:ce,minContains:M,maxContains:le,minItems:ue,maxItems:de,uniqueItems:fe,minimum:pe,maximum:N,exclusiveMinimum:me,exclusiveMaximum:he,multipleOf:ge,minLength:_e,maxLength:ve,pattern:ye,__absolute_ref__:be,__absolute_recursive_ref__:xe}=t,P=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[xe]:a,u=`${s}/$recursiveRef`,d=vd(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||P.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[be||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw be&&be!==d&&(e+=` Absolute URI "${be}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
174
- - `)}`,Error(e)}let l=`${s}/$ref`,u=vd(e,t,n,r,i,a,o,l,c);if(u.valid||P.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:P.length===0,errors:P}}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||P.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)&&P.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&P.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?Au(e,h)||P.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&P.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=>Au(e,t))||P.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||P.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`;vd(e,v,n,r,i,a,o,t).valid&&P.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Se=[];if(y!==void 0){let t=`${s}/anyOf`,l=P.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=vd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);P.push(...f.errors),u||=f.valid,f.valid&&Se.push(d)}u?P.length=l:P.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=P.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=vd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);P.push(...f.errors),u&&=f.valid,f.valid&&Se.push(d)}u?P.length=l:P.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=P.length,u=x.filter((s,l)=>{let u=Object.create(c),d=vd(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return P.push(...d.errors),d.valid&&Se.push(u),d.valid}).length;u===1?P.length=l:P.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,...Se),S!==void 0){let t=`${s}/if`;if(vd(e,S,n,r,i,a,o,t,c).valid){if(C!==void 0){let l=vd(e,C,n,r,i,a,o,`${s}/then`,c);l.valid||P.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(w!==void 0){let l=vd(e,w,n,r,i,a,o,`${s}/else`,c);l.valid||P.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||P.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&&P.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),te!==void 0&&t.length>te&&P.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${te} properties.`}),ne!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${Mu(s)}`,c=vd(s,ne,n,r,i,a,e,t);c.valid||P.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(re!==void 0){let t=`${s}/dependantRequired`;for(let n in re)if(n in e){let r=re[n];for(let i of r)i in e||P.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(A!==void 0)for(let t in A){let l=`${s}/dependentSchemas`;if(t in e){let s=vd(e,A[t],n,r,i,a,o,`${l}/${Mu(t)}`,c);s.valid||P.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(j!==void 0){let t=`${s}/dependencies`;for(let s in j)if(s in e){let c=j[s];if(Array.isArray(c))for(let n of c)n in e||P.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=vd(e,c,n,r,i,a,o,`${t}/${Mu(s)}`);l.valid||P.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}/${Mu(s)}`,f=vd(e[s],ee[s],n,r,i,a,d,`${t}/${Mu(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,P.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&E!==void 0){let t=`${s}/patternProperties`;for(let s in E){let d=new RegExp(s,`u`),f=E[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${Mu(p)}`,h=vd(e[p],f,n,r,i,a,m,`${t}/${Mu(s)}`);h.valid?c[p]=l[p]=!0:(u=i,P.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}/${Mu(s)}`,f=vd(e[s],D,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,P.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}/${Mu(s)}`,u=vd(e[s],O,n,r,i,a,l,t);u.valid?c[s]=!0:P.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){de!==void 0&&e.length>de&&P.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${de}).`}),ue!==void 0&&e.length<ue&&P.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${ue}).`});let t=e.length,l=0,u=!1;if(ie!==void 0){let d=`${s}/prefixItems`,f=Math.min(ie.length,t);for(;l<f;l++){let t=vd(e[l],ie[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,P.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(ae!==void 0){let d=`${s}/items`;if(Array.isArray(ae)){let s=Math.min(ae.length,t);for(;l<s;l++){let t=vd(e[l],ae[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,P.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=vd(e[l],ae,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,P.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&oe!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=vd(e[l],oe,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,P.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(ce!==void 0){if(t===0&&M===void 0)P.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(M!==void 0&&t<M)P.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${M}).`});else{let l=`${s}/contains`,u=P.length,d=0;for(let s=0;s<t;s++){let t=vd(e[s],ce,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):P.push(...t.errors)}d>=(M||0)&&(P.length=u),M===void 0&&le===void 0&&d===0?P.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):M!==void 0&&d<M?P.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${M} items matching schema. Only ${d} items were found.`}):le!==void 0&&d>le&&P.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${le} items matching schema. ${d} items were found.`})}}if(!u&&se!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=vd(e[l],se,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||P.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(fe)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&&Au(r,t))&&(P.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`?(pe!==void 0&&(me===!0&&e<=pe||e<pe)&&P.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${me?`or equal to `:``} ${pe}.`}),N!==void 0&&(he===!0&&e>=N||e>N)&&P.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${he?`or equal to `:``} ${N}.`})):(pe!==void 0&&e<pe&&P.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${pe}.`}),N!==void 0&&e>N&&P.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${N}.`}),me!==void 0&&e<=me&&P.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${me}.`}),he!==void 0&&e>=he&&P.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${he}.`})),ge!==void 0){let t=e%ge;Math.abs(0-t)>=1.1920929e-7&&Math.abs(ge-t)>=1.1920929e-7&&P.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${ge}.`})}}else if(u===`string`){let t=_e===void 0&&ve===void 0?0:gd(e);_e!==void 0&&t<_e&&P.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${_e}).`}),ve!==void 0&&t>ve&&P.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${ve}).`}),ye!==void 0&&!new RegExp(ye,`u`).test(e)&&P.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),T!==void 0&&ld[T]&&!ld[T](e)&&P.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${T}".`})}return{valid:P.length===0,errors:P}}var yd=F((()=>{ju(),Bu(),md(),Pu(),_d()})),bd,xd=F((()=>{Bu(),yd(),bd=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Fu(e)}validate(e){return vd(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Fu(e,this.lookup)}}})),Sd=F((()=>{ju(),Bu(),md(),Pu(),hd(),_d(),yd(),xd()}));function Cd(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function wd({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 Td(e){return e.title!==void 0&&e.title!==``?e.title:`annotations`in e&&e.annotations?.title?e.annotations.title:e.name}function Ed(e){return gh[e]}function Dd(e){let t={};for(let n of e){let e=n.shape.method.value;t[e]=n}return t}function Od(e){return _h[e]}function kd(e){return vh[e]}function Ad(e){return Wf.parse(e)}function jd(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Md(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}function Nd(e,t){return D.safeParse(e,t)}function Pd(e){return e===`completed`||e===`failed`||e===`cancelled`}function Fd(e){if(!e)return;let{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}=e;return{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}}function Id(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ld(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]=Id(a)&&Id(i)?{...a,...i}:i}return n}async function Rd(e){let t=[];for await(let n of e)t.push(n);return t}async function zd(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 Bd(e){return Wf.parse(JSON.parse(e))}function Vd(e){return JSON.stringify(e)+`
175
- `}function Hd(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`),!jh.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 Ud(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 Wd(e){let t=Hd(e);return Ud(e,t.warnings),t.isValid}function Gd(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Kd(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...Gd(t.headers),...Gd(r.headers)}:t.headers}):e}function qd(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 Jd(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function Yd(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>Jd(e)).join(`, `)}:{success:!0,data:n.value}}function Xd(e){let t=qd(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 Zd(){let e=new Qg.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,$g.default)(e),e}function Qd(e,t){let n=t.getValidator(e);return{"~standard":{version:1,vendor:`mcp`,jsonSchema:{input:()=>e,output:()=>e},validate:e=>{let t=n(e);return t.valid?{value:t.data}:{issues:[{message:t.errorMessage}]}}}}}var $d,ef,tf,nf,rf,af,z,of,sf,cf,lf,B,V,uf,df,ff,pf,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,H,U,Tf,Ef,Df,Of,kf,Af,jf,Mf,Nf,Pf,Ff,If,Lf,Rf,zf,Bf,Vf,Hf,Uf,Wf,Gf,Kf,qf,Jf,Yf,Xf,Zf,Qf,$f,ep,tp,np,rp,ip,ap,op,sp,cp,lp,up,dp,fp,pp,mp,hp,gp,_p,vp,yp,bp,xp,Sp,Cp,wp,Tp,Ep,Dp,Op,kp,Ap,jp,Mp,Np,Pp,Fp,Ip,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp,$p,em,tm,nm,rm,im,am,om,sm,cm,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Am,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Bm,Vm,Hm,Um,Wm,Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,$m,eh,th,nh,rh,ih,ah,oh,sh,ch,lh,uh,dh,fh,ph,mh,hh,gh,_h,vh,yh,bh,xh,Sh,Ch,wh,Th,Eh,Dh,Oh,kh,Ah,jh,Mh,Nh,Ph,Fh,Ih,Lh,Rh,W,G,zh,Bh,Vh,Hh,Uh,Wh,Gh,Kh,qh,Jh,Yh,Xh,Zh,Qh,$h,eg,tg,ng,rg,ig,ag,og,sg,cg,lg,ug,dg,fg,pg,mg,hg,gg,_g,vg,yg,bg,xg,Sg,Cg,wg,Tg,Eg,Dg,Og,kg,Ag,jg,Mg,Ng,Pg,Fg,Ig,Lg,Rg,zg,Bg,Vg,Hg,Ug,Wg,Gg,Kg,qg,Jg,Yg,Xg,Zg,Qg,$g,e_,t_,n_=F((()=>{Sd(),$d=Object.create,ef=Object.defineProperty,tf=Object.getOwnPropertyDescriptor,nf=Object.getOwnPropertyNames,rf=Object.getPrototypeOf,af=Object.prototype.hasOwnProperty,z=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),of=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=nf(t),a=0,o=i.length,s;a<o;a++)s=i[a],!af.call(e,s)&&s!==n&&ef(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=tf(t,s))||r.enumerable});return e},sf=(e,t,n)=>(n=e==null?{}:$d(rf(e)),of(t||!e||!e.__esModule?ef(n,`default`,{value:e,enumerable:!0}):n,e)),cf=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}({}),lf=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)}},B=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}({}),V=class extends Error{constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`SdkError`}},uf=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(uf).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()}),df=D.looseObject({issuer:D.string(),authorization_endpoint:uf,token_endpoint:uf,registration_endpoint:uf.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:uf.optional(),revocation_endpoint:uf.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()}),ff=D.looseObject({issuer:D.string(),authorization_endpoint:uf,token_endpoint:uf,userinfo_endpoint:uf.optional(),jwks_uri:uf,registration_endpoint:uf.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:uf.optional(),op_tos_uri:uf.optional(),client_id_metadata_document_supported:D.boolean().optional()}),D.object({...ff.shape,...df.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()}),pf=uf.optional().or(D.literal(``).transform(()=>void 0)),mf=D.object({redirect_uris:D.array(uf),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:uf.optional(),logo_uri:pf,scope:D.string().optional(),contacts:D.array(D.string()).optional(),tos_uri:pf,policy_uri:D.string().optional(),jwks_uri:uf.optional(),jwks:D.any().optional(),software_id:D.string().optional(),software_version:D.string().optional(),software_statement:D.string().optional()}).strip(),hf=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(),mf.merge(hf),D.object({error:D.string(),error_description:D.string().optional()}).strip(),D.object({token:D.string(),token_type_hint:D.string().optional()}).strip(),gf=`2025-11-25`,_f=`2025-03-26`,vf=[gf,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],yf=`io.modelcontextprotocol/related-task`,bf=-32700,xf=-32600,Sf=-32601,Cf=-32602,wf=-32603,H=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}({}),U=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===H.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Tf(e.elicitations,n)}return new e(t,n,r)}},Tf=class extends U{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(H.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Ef=D.lazy(()=>D.union([D.string(),D.number(),D.boolean(),D.null(),D.record(D.string(),Ef),D.array(Ef)])),Df=D.record(D.string(),Ef),D.array(Ef),Of=D.union([D.string(),D.number().int()]),kf=D.string(),D.looseObject({ttl:D.number().optional(),pollInterval:D.number().optional()}),Af=D.object({ttl:D.number().optional()}),jf=D.object({taskId:D.string()}),Mf=D.looseObject({progressToken:Of.optional(),[yf]:jf.optional()}),Nf=D.object({_meta:Mf.optional()}),Pf=Nf.extend({task:Af.optional()}),Ff=D.object({method:D.string(),params:Nf.loose().optional()}),If=D.object({_meta:Mf.optional()}),Lf=D.object({method:D.string(),params:If.loose().optional()}),Rf=D.looseObject({_meta:Mf.optional()}),zf=D.union([D.string(),D.number().int()]),Bf=D.object({jsonrpc:D.literal(`2.0`),id:zf,...Ff.shape}).strict(),Vf=D.object({jsonrpc:D.literal(`2.0`),...Lf.shape}).strict(),Hf=D.object({jsonrpc:D.literal(`2.0`),id:zf,result:Rf}).strict(),Uf=D.object({jsonrpc:D.literal(`2.0`),id:zf.optional(),error:D.object({code:D.number().int(),message:D.string(),data:D.unknown().optional()})}).strict(),Wf=D.union([Bf,Vf,Hf,Uf]),D.union([Hf,Uf]),Gf=Rf.strict(),Kf=If.extend({requestId:zf.optional(),reason:D.string().optional()}),qf=Lf.extend({method:D.literal(`notifications/cancelled`),params:Kf}),Jf=D.object({src:D.string(),mimeType:D.string().optional(),sizes:D.array(D.string()).optional(),theme:D.enum([`light`,`dark`]).optional()}),Yf=D.object({icons:D.array(Jf).optional()}),Xf=D.object({name:D.string(),title:D.string().optional()}),Zf=Xf.extend({...Xf.shape,...Yf.shape,version:D.string(),websiteUrl:D.string().optional(),description:D.string().optional()}),Qf=D.intersection(D.object({applyDefaults:D.boolean().optional()}),Df),$f=D.preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,D.intersection(D.object({form:Qf.optional(),url:Df.optional()}),Df.optional())),ep=D.looseObject({list:Df.optional(),cancel:Df.optional(),requests:D.looseObject({sampling:D.looseObject({createMessage:Df.optional()}).optional(),elicitation:D.looseObject({create:Df.optional()}).optional()}).optional()}),tp=D.looseObject({list:Df.optional(),cancel:Df.optional(),requests:D.looseObject({tools:D.looseObject({call:Df.optional()}).optional()}).optional()}),np=D.object({experimental:D.record(D.string(),Df).optional(),sampling:D.object({context:Df.optional(),tools:Df.optional()}).optional(),elicitation:$f.optional(),roots:D.object({listChanged:D.boolean().optional()}).optional(),tasks:ep.optional(),extensions:D.record(D.string(),Df).optional()}),rp=Nf.extend({protocolVersion:D.string(),capabilities:np,clientInfo:Zf}),ip=Ff.extend({method:D.literal(`initialize`),params:rp}),ap=D.object({experimental:D.record(D.string(),Df).optional(),logging:Df.optional(),completions:Df.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:tp.optional(),extensions:D.record(D.string(),Df).optional()}),op=Rf.extend({protocolVersion:D.string(),capabilities:ap,serverInfo:Zf,instructions:D.string().optional()}),sp=Lf.extend({method:D.literal(`notifications/initialized`),params:If.optional()}),cp=Ff.extend({method:D.literal(`ping`),params:Nf.optional()}),lp=D.object({progress:D.number(),total:D.optional(D.number()),message:D.optional(D.string())}),up=D.object({...If.shape,...lp.shape,progressToken:Of}),dp=Lf.extend({method:D.literal(`notifications/progress`),params:up}),fp=Nf.extend({cursor:kf.optional()}),pp=Ff.extend({params:fp.optional()}),mp=Rf.extend({nextCursor:kf.optional()}),hp=D.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),gp=D.object({taskId:D.string(),status:hp,ttl:D.union([D.number(),D.null()]),createdAt:D.string(),lastUpdatedAt:D.string(),pollInterval:D.optional(D.number()),statusMessage:D.optional(D.string())}),_p=Rf.extend({task:gp}),vp=If.merge(gp),yp=Lf.extend({method:D.literal(`notifications/tasks/status`),params:vp}),bp=Ff.extend({method:D.literal(`tasks/get`),params:Nf.extend({taskId:D.string()})}),xp=Rf.merge(gp),Sp=Ff.extend({method:D.literal(`tasks/result`),params:Nf.extend({taskId:D.string()})}),Cp=Rf.loose(),wp=pp.extend({method:D.literal(`tasks/list`)}),Tp=mp.extend({tasks:D.array(gp)}),Ep=Ff.extend({method:D.literal(`tasks/cancel`),params:Nf.extend({taskId:D.string()})}),Dp=Rf.merge(gp),Op=D.object({uri:D.string(),mimeType:D.optional(D.string()),_meta:D.record(D.string(),D.unknown()).optional()}),kp=Op.extend({text:D.string()}),Ap=D.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),jp=Op.extend({blob:Ap}),Mp=D.enum([`user`,`assistant`]),Np=D.object({audience:D.array(Mp).optional(),priority:D.number().min(0).max(1).optional(),lastModified:D.iso.datetime({offset:!0}).optional()}),Pp=D.object({...Xf.shape,...Yf.shape,uri:D.string(),description:D.optional(D.string()),mimeType:D.optional(D.string()),size:D.optional(D.number()),annotations:Np.optional(),_meta:D.optional(D.looseObject({}))}),Fp=D.object({...Xf.shape,...Yf.shape,uriTemplate:D.string(),description:D.optional(D.string()),mimeType:D.optional(D.string()),annotations:Np.optional(),_meta:D.optional(D.looseObject({}))}),Ip=pp.extend({method:D.literal(`resources/list`)}),Lp=mp.extend({resources:D.array(Pp)}),Rp=pp.extend({method:D.literal(`resources/templates/list`)}),zp=mp.extend({resourceTemplates:D.array(Fp)}),Bp=Nf.extend({uri:D.string()}),Vp=Bp,Hp=Ff.extend({method:D.literal(`resources/read`),params:Vp}),Up=Rf.extend({contents:D.array(D.union([kp,jp]))}),Wp=Lf.extend({method:D.literal(`notifications/resources/list_changed`),params:If.optional()}),Gp=Bp,Kp=Ff.extend({method:D.literal(`resources/subscribe`),params:Gp}),qp=Bp,Jp=Ff.extend({method:D.literal(`resources/unsubscribe`),params:qp}),Yp=If.extend({uri:D.string()}),Xp=Lf.extend({method:D.literal(`notifications/resources/updated`),params:Yp}),Zp=D.object({name:D.string(),description:D.optional(D.string()),required:D.optional(D.boolean())}),Qp=D.object({...Xf.shape,...Yf.shape,description:D.optional(D.string()),arguments:D.optional(D.array(Zp)),_meta:D.optional(D.looseObject({}))}),$p=pp.extend({method:D.literal(`prompts/list`)}),em=mp.extend({prompts:D.array(Qp)}),tm=Nf.extend({name:D.string(),arguments:D.record(D.string(),D.string()).optional()}),nm=Ff.extend({method:D.literal(`prompts/get`),params:tm}),rm=D.object({type:D.literal(`text`),text:D.string(),annotations:Np.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),im=D.object({type:D.literal(`image`),data:Ap,mimeType:D.string(),annotations:Np.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),am=D.object({type:D.literal(`audio`),data:Ap,mimeType:D.string(),annotations:Np.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),om=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()}),sm=D.object({type:D.literal(`resource`),resource:D.union([kp,jp]),annotations:Np.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),cm=Pp.extend({type:D.literal(`resource_link`)}),lm=D.union([rm,im,am,cm,sm]),um=D.object({role:Mp,content:lm}),dm=Rf.extend({description:D.string().optional(),messages:D.array(um)}),fm=Lf.extend({method:D.literal(`notifications/prompts/list_changed`),params:If.optional()}),pm=D.object({title:D.string().optional(),readOnlyHint:D.boolean().optional(),destructiveHint:D.boolean().optional(),idempotentHint:D.boolean().optional(),openWorldHint:D.boolean().optional()}),mm=D.object({taskSupport:D.enum([`required`,`optional`,`forbidden`]).optional()}),hm=D.object({...Xf.shape,...Yf.shape,description:D.string().optional(),inputSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),Ef).optional(),required:D.array(D.string()).optional()}).catchall(D.unknown()),outputSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),Ef).optional(),required:D.array(D.string()).optional()}).catchall(D.unknown()).optional(),annotations:pm.optional(),execution:mm.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),gm=pp.extend({method:D.literal(`tools/list`)}),_m=mp.extend({tools:D.array(hm)}),vm=Rf.extend({content:D.array(lm).default([]),structuredContent:D.record(D.string(),D.unknown()).optional(),isError:D.boolean().optional()}),vm.or(Rf.extend({toolResult:D.unknown()})),ym=Pf.extend({name:D.string(),arguments:D.record(D.string(),D.unknown()).optional()}),bm=Ff.extend({method:D.literal(`tools/call`),params:ym}),xm=Lf.extend({method:D.literal(`notifications/tools/list_changed`),params:If.optional()}),D.object({autoRefresh:D.boolean().default(!0),debounceMs:D.number().int().nonnegative().default(300)}),Sm=D.enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Cm=Nf.extend({level:Sm}),wm=Ff.extend({method:D.literal(`logging/setLevel`),params:Cm}),Tm=If.extend({level:Sm,logger:D.string().optional(),data:D.unknown()}),Em=Lf.extend({method:D.literal(`notifications/message`),params:Tm}),Dm=D.object({name:D.string().optional()}),Om=D.object({hints:D.array(Dm).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()}),km=D.object({mode:D.enum([`auto`,`required`,`none`]).optional()}),Am=D.object({type:D.literal(`tool_result`),toolUseId:D.string().describe(`The unique identifier for the corresponding tool call.`),content:D.array(lm).default([]),structuredContent:D.object({}).loose().optional(),isError:D.boolean().optional(),_meta:D.record(D.string(),D.unknown()).optional()}),jm=D.discriminatedUnion(`type`,[rm,im,am]),Mm=D.discriminatedUnion(`type`,[rm,im,am,om,Am]),Nm=D.object({role:Mp,content:D.union([Mm,D.array(Mm)]),_meta:D.record(D.string(),D.unknown()).optional()}),Pm=Pf.extend({messages:D.array(Nm),modelPreferences:Om.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:Df.optional(),tools:D.array(hm).optional(),toolChoice:km.optional()}),Fm=Ff.extend({method:D.literal(`sampling/createMessage`),params:Pm}),Im=Rf.extend({model:D.string(),stopReason:D.optional(D.enum([`endTurn`,`stopSequence`,`maxTokens`]).or(D.string())),role:Mp,content:jm}),Lm=Rf.extend({model:D.string(),stopReason:D.optional(D.enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(D.string())),role:Mp,content:D.union([Mm,D.array(Mm)])}),Rm=D.object({type:D.literal(`boolean`),title:D.string().optional(),description:D.string().optional(),default:D.boolean().optional()}),zm=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()}),Bm=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()}),Vm=D.object({type:D.literal(`string`),title:D.string().optional(),description:D.string().optional(),enum:D.array(D.string()),default:D.string().optional()}),Hm=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()}),Um=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()}),Wm=D.union([Vm,Hm]),Gm=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()}),Km=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()}),qm=D.union([Gm,Km]),Jm=D.union([Um,Wm,qm]),Ym=D.union([Jm,Rm,zm,Bm]),Xm=Pf.extend({mode:D.literal(`form`).optional(),message:D.string(),requestedSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),Ym),required:D.array(D.string()).optional()})}),Zm=Pf.extend({mode:D.literal(`url`),message:D.string(),elicitationId:D.string(),url:D.string().url()}),Qm=D.union([Xm,Zm]),$m=Ff.extend({method:D.literal(`elicitation/create`),params:Qm}),eh=If.extend({elicitationId:D.string()}),th=Lf.extend({method:D.literal(`notifications/elicitation/complete`),params:eh}),nh=Rf.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())}),rh=D.object({type:D.literal(`ref/resource`),uri:D.string()}),ih=D.object({type:D.literal(`ref/prompt`),name:D.string()}),ah=Nf.extend({ref:D.union([ih,rh]),argument:D.object({name:D.string(),value:D.string()}),context:D.object({arguments:D.record(D.string(),D.string()).optional()}).optional()}),oh=Ff.extend({method:D.literal(`completion/complete`),params:ah}),sh=Rf.extend({completion:D.looseObject({values:D.array(D.string()).max(100),total:D.optional(D.number().int()),hasMore:D.optional(D.boolean())})}),ch=D.object({uri:D.string().startsWith(`file://`),name:D.string().optional(),_meta:D.record(D.string(),D.unknown()).optional()}),lh=Ff.extend({method:D.literal(`roots/list`),params:Nf.optional()}),uh=Rf.extend({roots:D.array(ch)}),dh=Lf.extend({method:D.literal(`notifications/roots/list_changed`),params:If.optional()}),fh=D.union([cp,ip,oh,wm,nm,$p,Ip,Rp,Hp,Kp,Jp,bm,gm,bp,Sp,wp,Ep]),ph=D.union([qf,dp,sp,dh,yp]),D.union([Gf,Im,Lm,nh,uh,xp,Tp,_p]),mh=D.union([cp,Fm,$m,lh,bp,Sp,wp,Ep]),hh=D.union([qf,dp,Em,Xp,Wp,xm,fm,yp,th]),D.union([Gf,op,sh,dm,em,Lp,zp,Up,vm,_m,xp,Tp,_p]),gh={ping:Gf,initialize:op,"completion/complete":sh,"logging/setLevel":Gf,"prompts/get":dm,"prompts/list":em,"resources/list":Lp,"resources/templates/list":zp,"resources/read":Up,"resources/subscribe":Gf,"resources/unsubscribe":Gf,"tools/call":D.union([vm,_p]),"tools/list":_m,"sampling/createMessage":D.union([Lm,_p]),"elicitation/create":D.union([nh,_p]),"roots/list":uh,"tasks/get":xp,"tasks/result":Rf,"tasks/list":Tp,"tasks/cancel":Dp},_h=Dd([...fh.options,...mh.options]),vh=Dd([...ph.options,...hh.options]),yh=e=>Bf.safeParse(e).success,bh=e=>Vf.safeParse(e).success,xh=e=>Hf.safeParse(e).success,Sh=e=>Uf.safeParse(e).success,Ch=e=>Pf.safeParse(e).success,wh=e=>ip.safeParse(e).success,Th=e=>sp.safeParse(e).success,Eh=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 U(H.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 U(H.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,_p,n);if(i.task)a=i.task.taskId,yield{type:`taskCreated`,task:i.task};else throw new U(H.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:a},n);if(yield{type:`taskStatus`,task:e},Pd(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 U(H.InternalError,`Task ${a} failed`)};break;case`cancelled`:yield{type:`error`,error:new U(H.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},xp,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},Tp,t)}async cancelTask(e,t){return this._requireHost.request({method:`tasks/cancel`,params:e},Dp,t)}async handleGetTask(e,t){let n=await this._requireTaskStore.getTask(e,t);if(!n)throw new U(H.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 U(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 U(H.InvalidParams,`Task not found: ${e}`);if(!Pd(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,[yf]:{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 U(H.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 U(H.InvalidParams,`Task not found: ${e}`);if(Pd(n.status))throw new U(H.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 U(H.InvalidParams,`Task not found after cancellation: ${e}`);return{_meta:{},...r}}catch(e){throw e instanceof U?e:new U(H.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,[yf]: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)?.[yf]?.taskId,r=Ch(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),xh(e)?n(e):n(new U(e.error.code,e.error.message,e.error.data)),!0):!1}shouldPreserveProgressHandler(e,t){if(xh(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,[yf]: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(Sh(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 U(H.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=yp.parse({method:`notifications/tasks/status`,params:o});await r?.notification(t),Pd(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 U(H.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Pd(o.status))throw new U(H.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=yp.parse({method:`notifications/tasks/status`,params:s});await r?.notification(t),Pd(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,[yf]: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`&&yh(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new U(H.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 U(H.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new U(H.InvalidRequest,`Request cancelled`))},{once:!0})})}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._host?.removeProgressHandler(t),this._taskProgressTokens.delete(e))}},Dh=class extends Eh{constructor(){super({})}processInboundRequest(e,t){let n=Ch(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`}}}},Oh=6e4,kh=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??vf,this._taskManager=e?.tasks?new Eh(e.tasks):new Dh,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=Od(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 V(B.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),xh(e)||Sh(e)?this._onresponse(e):yh(e)?this._onrequest(e,t):bh(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 V(B.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:H.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,Ed(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:H.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),xh(e)?i(e):i(U.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=Ed(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 V?e:new V(B.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Nd(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 V(B.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 V(B.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=Od(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=kd(e);this._notificationHandlers.set(e,e=>{let r=n.parse(e);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}},Ah=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 Bd(t)}catch(e){if(e instanceof SyntaxError)continue;throw e}}return null}clear(){this._buffer=void 0}},jh=/^[A-Za-z0-9._-]{1,128}$/,Mh=1e6,Nh=1e6,Ph=1e4,Fh=1e6,Ih=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,Mh,`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>Ph)throw Error(`Template contains too many expressions (max ${Ph})`);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,Nh,`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,Nh,`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,Nh,`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,Mh,`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,Fh,`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}},Lh=z((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})),Rh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Lh();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}}})),W=z((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=Lh(),n=Rh();var r=Lh();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=Rh();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=O(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=O(this.rhs,e,n),this}get names(){return D(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=O(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(k(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>E(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(te(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=O(this.condition,e,t),this}get names(){let e=super.names;return D(e,this.condition),this.else&&E(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=O(this.iteration,e,t),this}get names(){return E(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return D(D(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=O(this.iterable,e,t),this}get names(){return E(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&E(e,this.catch.names),this.finally&&E(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var ee=class extends m{render(e){return`finally`+super.render(e)}};ee.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
177
- `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new ee,this.code(n)),this._endBlockNode(T,ee)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function E(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function D(e,n){return n instanceof t._CodeOrName?E(e,n.names):e}function O(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function k(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function te(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ae(e)}`}e.not=te;let ne=ie(e.operators.AND);function re(...e){return e.reduce(ne)}e.and=re;let A=ie(e.operators.OR);function j(...e){return e.reduce(A)}e.or=j;function ie(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ae(n)} ${e} ${ae(r)}`}function ae(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),G=z((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=W(),n=Lh();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})),zh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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`)}})),Bh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=W(),n=G(),r=zh();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])}})),Vh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Bh(),n=W(),r=zh(),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)}})),Hh=z((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})),Uh=z((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})),Wh=z((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=Hh(),n=Uh(),r=Bh(),i=W(),a=G();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:[Xl({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`)})}),Xl({name:`doctor`,description:`Validate MCP server startup and tool listing`})]},{name:`skills`,aliases:[`skill`],description:`Sync skill files to agents`,subcommands:[Xl({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`)})}),Xl({name:`list`,aliases:[`ls`],description:`List skills`})]}]}));function ru(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(...mu(c,r,a)),l.join(`
171
+ `)}function iu(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=au(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=ou(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=cu(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(...mu(f,i,o)),l){let e=su(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??Wl();n.name in i&&r.push(`set: ${hu(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 au(e,t){if(!t)return e;let n=[e];for(let[e,r]of Object.entries(t.shape)){let t=lu(r),i=(t.includes(`|`)?t:e)+(t===`array`?`...`:``);n.push(r._zod.optout===`optional`?`[${i}]`:`<${i}>`)}return n.join(` `)}function ou(e){let t=[];for(let[n,r]of Object.entries(e.shape))t.push({name:n,description:r.description??``});return t}function su(e){let t=[];for(let[n,r]of Object.entries(e.shape)){let e=fu(r);t.push({name:n,description:r.description??``,defaultValue:e})}return t}function cu(e,t){let n=[];for(let[r,i]of Object.entries(e.shape)){let e=lu(i),a=t?.[r],o=an(r),s=e===`boolean`?``:` <${e}>`,c=a?`--${o}, -${a}${s}`:`--${o}${s}`,l=fu(i);e===`boolean`&&l===!1&&(l=void 0);let u=pu(i);n.push({flag:c,description:i.description??``,defaultValue:l,deprecated:u})}return n}function lu(e){if(uu(e))return`count`;let t=du(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 uu(e){let t=e;return typeof t?.meta==`function`&&t.meta()?.count===!0}function du(e){return e instanceof f.ZodOptional?du(e.unwrap()):e instanceof f.ZodDefault?du(e.removeDefault()):e instanceof f.ZodNullable?du(e.unwrap()):e}function fu(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 fu(e.unwrap())}function pu(e){return e?.meta?.()?.deprecated===!0||void 0}function mu(e=!1,t,n){let r=[];if(e){let e=tu.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=cu(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 hu(e){return e.length<=4?`****`:`****${e.slice(-4)}`}var gu=F((()=>{nu(),cn(),Gl()}));function _u(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=>yu(e,t))}}function vu(e){let t=[e.description];for(let n of e.commands)t.push(` ${n.command}${n.description?` - ${n.description}`:``}`);return t.join(`
173
+ `)}function yu(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 bu=F((()=>{}));async function xu(e,t={}){let n=[],r=t.exclude?c.resolve(t.exclude):void 0;async function i(e,t){let a=await C.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()){wu(o.name,a),await i(a,[...t,o.name]);continue}if(!o.isFile()||a===r)continue;let s=Tu.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}wu(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 Su(){return globalThis[Symbol.for(Du)]?.shift()}async function Cu(e){return Promise.all(e.map(async({load:e,...t})=>({...t,command:await e()})))}function wu(e,t){if(!Eu.test(e))throw Error(`Invalid filesystem command segment '${e}' from '${t}'. Use lowercase kebab-case names.`)}var Tu,Eu,Du,Ou=F((()=>{Tu=[`.cts`,`.cjs`,`.mts`,`.mjs`,`.ts`,`.js`],Eu=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Du=`incur.fs.manifests`}));function ku(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 Au=F((()=>{}));function ju(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(!ju(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(!ju(e[r],t[r]))return!1;return!0}return e===t}var Mu=F((()=>{}));function Nu(e){return encodeURI(Pu(e))}function Pu(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var Fu=F((()=>{}));function Iu(e,t=Object.create(null),n=Bu,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:Iu(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(zu[i])continue;let a=`${r}/${Nu(i)}`,o=e[i];if(Array.isArray(o)){if(Lu[i]){let e=o.length;for(let r=0;r<e;r++)Iu(o[r],t,n,`${a}/${r}`)}}else if(Ru[i])for(let e in o)Iu(o[e],t,n,`${a}/${Nu(e)}`);else Iu(o,t,n,a)}return t}var Lu,Ru,zu,Bu,Vu=F((()=>{Fu(),Lu={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Ru={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},zu={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},Bu=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 Hu(e){return e.test.bind(e)}function Uu(e){return e%4==0&&(e%100!=0||e%400==0)}function Wu(e){let t=e.match(Yu);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&Uu(n)?29:Xu[r])}function Gu(e,t){let n=t.match(Zu);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 Ku(e){let t=e.split(dd);return t.length==2&&Wu(t[0])&&Gu(!0,t[1])}function qu(e){return fd.test(e)&&pd.test(e)}function Ju(e){if(md.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}var Yu,Xu,Zu,Qu,$u,ed,td,nd,rd,id,ad,od,sd,cd,ld,ud,dd,fd,pd,md,hd=F((()=>{Yu=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Xu=[0,31,28,31,30,31,30,31,31,30,31,30,31],Zu=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Qu=/^(?=.{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,$u=/^(?:[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,ed=/^(?:(?:[^\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,td=/^(?:(?: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,nd=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,rd=/^(?:\/(?:[^~/]|~0|~1)*)*$/,id=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,ad=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,od=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))},sd=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,cd=/^((([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,ld=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)),ud={date:Wu,time:Gu.bind(void 0,!1),"date-time":Ku,duration:ld,uri:qu,"uri-reference":Hu($u),"uri-template":Hu(ed),url:Hu(td),email:od,hostname:Hu(Qu),ipv4:Hu(sd),ipv6:Hu(cd),regex:Ju,uuid:Hu(nd),"json-pointer":Hu(rd),"json-pointer-uri-fragment":Hu(id),"relative-json-pointer":Hu(ad)},dd=/t|\s/i,fd=/\/|:/,pd=/^(?:[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,md=/[^\\]\\Z/})),gd=F((()=>{}));function _d(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 vd=F((()=>{}));function yd(e,t,n=`2019-09`,r=Iu(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:C,else:w,format:T,properties:ee,patternProperties:E,additionalProperties:D,unevaluatedProperties:O,minProperties:k,maxProperties:te,propertyNames:ne,dependentRequired:re,dependentSchemas:A,dependencies:j,prefixItems:ie,items:ae,additionalItems:oe,unevaluatedItems:se,contains:ce,minContains:M,maxContains:le,minItems:ue,maxItems:de,uniqueItems:fe,minimum:pe,maximum:me,exclusiveMinimum:N,exclusiveMaximum:he,multipleOf:ge,minLength:_e,maxLength:ve,pattern:ye,__absolute_ref__:be,__absolute_recursive_ref__:xe}=t,P=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[xe]:a,u=`${s}/$recursiveRef`,d=yd(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||P.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[be||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw be&&be!==d&&(e+=` Absolute URI "${be}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
174
+ - `)}`,Error(e)}let l=`${s}/$ref`,u=yd(e,t,n,r,i,a,o,l,c);if(u.valid||P.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:P.length===0,errors:P}}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||P.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)&&P.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&P.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?ju(e,h)||P.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&P.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=>ju(e,t))||P.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||P.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`;yd(e,v,n,r,i,a,o,t).valid&&P.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Se=[];if(y!==void 0){let t=`${s}/anyOf`,l=P.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=yd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);P.push(...f.errors),u||=f.valid,f.valid&&Se.push(d)}u?P.length=l:P.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=P.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=yd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);P.push(...f.errors),u&&=f.valid,f.valid&&Se.push(d)}u?P.length=l:P.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=P.length,u=x.filter((s,l)=>{let u=Object.create(c),d=yd(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return P.push(...d.errors),d.valid&&Se.push(u),d.valid}).length;u===1?P.length=l:P.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,...Se),S!==void 0){let t=`${s}/if`;if(yd(e,S,n,r,i,a,o,t,c).valid){if(C!==void 0){let l=yd(e,C,n,r,i,a,o,`${s}/then`,c);l.valid||P.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(w!==void 0){let l=yd(e,w,n,r,i,a,o,`${s}/else`,c);l.valid||P.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||P.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&&P.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),te!==void 0&&t.length>te&&P.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${te} properties.`}),ne!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${Nu(s)}`,c=yd(s,ne,n,r,i,a,e,t);c.valid||P.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(re!==void 0){let t=`${s}/dependantRequired`;for(let n in re)if(n in e){let r=re[n];for(let i of r)i in e||P.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(A!==void 0)for(let t in A){let l=`${s}/dependentSchemas`;if(t in e){let s=yd(e,A[t],n,r,i,a,o,`${l}/${Nu(t)}`,c);s.valid||P.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(j!==void 0){let t=`${s}/dependencies`;for(let s in j)if(s in e){let c=j[s];if(Array.isArray(c))for(let n of c)n in e||P.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=yd(e,c,n,r,i,a,o,`${t}/${Nu(s)}`);l.valid||P.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}/${Nu(s)}`,f=yd(e[s],ee[s],n,r,i,a,d,`${t}/${Nu(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,P.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&E!==void 0){let t=`${s}/patternProperties`;for(let s in E){let d=new RegExp(s,`u`),f=E[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${Nu(p)}`,h=yd(e[p],f,n,r,i,a,m,`${t}/${Nu(s)}`);h.valid?c[p]=l[p]=!0:(u=i,P.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}/${Nu(s)}`,f=yd(e[s],D,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,P.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}/${Nu(s)}`,u=yd(e[s],O,n,r,i,a,l,t);u.valid?c[s]=!0:P.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){de!==void 0&&e.length>de&&P.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${de}).`}),ue!==void 0&&e.length<ue&&P.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${ue}).`});let t=e.length,l=0,u=!1;if(ie!==void 0){let d=`${s}/prefixItems`,f=Math.min(ie.length,t);for(;l<f;l++){let t=yd(e[l],ie[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,P.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(ae!==void 0){let d=`${s}/items`;if(Array.isArray(ae)){let s=Math.min(ae.length,t);for(;l<s;l++){let t=yd(e[l],ae[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,P.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=yd(e[l],ae,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,P.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&oe!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=yd(e[l],oe,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,P.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(ce!==void 0){if(t===0&&M===void 0)P.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(M!==void 0&&t<M)P.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${M}).`});else{let l=`${s}/contains`,u=P.length,d=0;for(let s=0;s<t;s++){let t=yd(e[s],ce,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):P.push(...t.errors)}d>=(M||0)&&(P.length=u),M===void 0&&le===void 0&&d===0?P.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):M!==void 0&&d<M?P.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${M} items matching schema. Only ${d} items were found.`}):le!==void 0&&d>le&&P.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${le} items matching schema. ${d} items were found.`})}}if(!u&&se!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=yd(e[l],se,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||P.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(fe)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&&ju(r,t))&&(P.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`?(pe!==void 0&&(N===!0&&e<=pe||e<pe)&&P.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${N?`or equal to `:``} ${pe}.`}),me!==void 0&&(he===!0&&e>=me||e>me)&&P.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${he?`or equal to `:``} ${me}.`})):(pe!==void 0&&e<pe&&P.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${pe}.`}),me!==void 0&&e>me&&P.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${me}.`}),N!==void 0&&e<=N&&P.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${N}.`}),he!==void 0&&e>=he&&P.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${he}.`})),ge!==void 0){let t=e%ge;Math.abs(0-t)>=1.1920929e-7&&Math.abs(ge-t)>=1.1920929e-7&&P.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${ge}.`})}}else if(u===`string`){let t=_e===void 0&&ve===void 0?0:_d(e);_e!==void 0&&t<_e&&P.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${_e}).`}),ve!==void 0&&t>ve&&P.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${ve}).`}),ye!==void 0&&!new RegExp(ye,`u`).test(e)&&P.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),T!==void 0&&ud[T]&&!ud[T](e)&&P.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${T}".`})}return{valid:P.length===0,errors:P}}var bd=F((()=>{Mu(),Vu(),hd(),Fu(),vd()})),xd,Sd=F((()=>{Vu(),bd(),xd=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Iu(e)}validate(e){return yd(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Iu(e,this.lookup)}}})),Cd=F((()=>{Mu(),Vu(),hd(),Fu(),gd(),vd(),bd(),Sd()}));function wd(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Td({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 Ed(e){return e.title!==void 0&&e.title!==``?e.title:`annotations`in e&&e.annotations?.title?e.annotations.title:e.name}function Dd(e){return _h[e]}function Od(e){let t={};for(let n of e){let e=n.shape.method.value;t[e]=n}return t}function kd(e){return vh[e]}function Ad(e){return yh[e]}function jd(e){return Gf.parse(e)}function Md(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Nd(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}function Pd(e,t){return D.safeParse(e,t)}function Fd(e){return e===`completed`||e===`failed`||e===`cancelled`}function Id(e){if(!e)return;let{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}=e;return{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}}function Ld(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rd(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]=Ld(a)&&Ld(i)?{...a,...i}:i}return n}async function zd(e){let t=[];for await(let n of e)t.push(n);return t}async function Bd(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 Vd(e){return Gf.parse(JSON.parse(e))}function Hd(e){return JSON.stringify(e)+`
175
+ `}function Ud(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`),!Mh.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 Wd(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 Gd(e){let t=Ud(e);return Wd(e,t.warnings),t.isValid}function Kd(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function qd(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...Kd(t.headers),...Kd(r.headers)}:t.headers}):e}function Jd(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 Yd(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function Xd(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>Yd(e)).join(`, `)}:{success:!0,data:n.value}}function Zd(e){let t=Jd(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 Qd(){let e=new $g.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,e_.default)(e),e}function $d(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 ef,tf,nf,rf,af,of,z,sf,cf,lf,uf,B,V,df,ff,pf,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Tf,H,U,Ef,Df,Of,kf,Af,jf,Mf,Nf,Pf,Ff,If,Lf,Rf,zf,Bf,Vf,Hf,Uf,Wf,Gf,Kf,qf,Jf,Yf,Xf,Zf,Qf,$f,ep,tp,np,rp,ip,ap,op,sp,cp,lp,up,dp,fp,pp,mp,hp,gp,_p,vp,yp,bp,xp,Sp,Cp,wp,Tp,Ep,Dp,Op,kp,Ap,jp,Mp,Np,Pp,Fp,Ip,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp,$p,em,tm,nm,rm,im,am,om,sm,cm,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Am,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Bm,Vm,Hm,Um,Wm,Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,$m,eh,th,nh,rh,ih,ah,oh,sh,ch,lh,uh,dh,fh,ph,mh,hh,gh,_h,vh,yh,bh,xh,Sh,Ch,wh,Th,Eh,Dh,Oh,kh,Ah,jh,Mh,Nh,Ph,Fh,Ih,Lh,Rh,zh,W,G,Bh,Vh,Hh,Uh,Wh,Gh,Kh,qh,Jh,Yh,Xh,Zh,Qh,$h,eg,tg,ng,rg,ig,ag,og,sg,cg,lg,ug,dg,fg,pg,mg,hg,gg,_g,vg,yg,bg,xg,Sg,Cg,wg,Tg,Eg,Dg,Og,kg,Ag,jg,Mg,Ng,Pg,Fg,Ig,Lg,Rg,zg,Bg,Vg,Hg,Ug,Wg,Gg,Kg,qg,Jg,Yg,Xg,Zg,Qg,$g,e_,t_,n_,r_=F((()=>{Cd(),ef=Object.create,tf=Object.defineProperty,nf=Object.getOwnPropertyDescriptor,rf=Object.getOwnPropertyNames,af=Object.getPrototypeOf,of=Object.prototype.hasOwnProperty,z=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),sf=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=rf(t),a=0,o=i.length,s;a<o;a++)s=i[a],!of.call(e,s)&&s!==n&&tf(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=nf(t,s))||r.enumerable});return e},cf=(e,t,n)=>(n=e==null?{}:ef(af(e)),sf(t||!e||!e.__esModule?tf(n,`default`,{value:e,enumerable:!0}):n,e)),lf=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}({}),uf=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)}},B=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}({}),V=class extends Error{constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`SdkError`}},df=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(df).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()}),ff=D.looseObject({issuer:D.string(),authorization_endpoint:df,token_endpoint:df,registration_endpoint:df.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:df.optional(),revocation_endpoint:df.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()}),pf=D.looseObject({issuer:D.string(),authorization_endpoint:df,token_endpoint:df,userinfo_endpoint:df.optional(),jwks_uri:df,registration_endpoint:df.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:df.optional(),op_tos_uri:df.optional(),client_id_metadata_document_supported:D.boolean().optional()}),D.object({...pf.shape,...ff.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()}),mf=df.optional().or(D.literal(``).transform(()=>void 0)),hf=D.object({redirect_uris:D.array(df),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:df.optional(),logo_uri:mf,scope:D.string().optional(),contacts:D.array(D.string()).optional(),tos_uri:mf,policy_uri:D.string().optional(),jwks_uri:df.optional(),jwks:D.any().optional(),software_id:D.string().optional(),software_version:D.string().optional(),software_statement:D.string().optional()}).strip(),gf=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(),hf.merge(gf),D.object({error:D.string(),error_description:D.string().optional()}).strip(),D.object({token:D.string(),token_type_hint:D.string().optional()}).strip(),_f=`2025-11-25`,vf=`2025-03-26`,yf=[_f,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],bf=`io.modelcontextprotocol/related-task`,xf=-32700,Sf=-32600,Cf=-32601,wf=-32602,Tf=-32603,H=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}({}),U=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===H.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Ef(e.elicitations,n)}return new e(t,n,r)}},Ef=class extends U{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(H.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Df=D.lazy(()=>D.union([D.string(),D.number(),D.boolean(),D.null(),D.record(D.string(),Df),D.array(Df)])),Of=D.record(D.string(),Df),D.array(Df),kf=D.union([D.string(),D.number().int()]),Af=D.string(),D.looseObject({ttl:D.number().optional(),pollInterval:D.number().optional()}),jf=D.object({ttl:D.number().optional()}),Mf=D.object({taskId:D.string()}),Nf=D.looseObject({progressToken:kf.optional(),[bf]:Mf.optional()}),Pf=D.object({_meta:Nf.optional()}),Ff=Pf.extend({task:jf.optional()}),If=D.object({method:D.string(),params:Pf.loose().optional()}),Lf=D.object({_meta:Nf.optional()}),Rf=D.object({method:D.string(),params:Lf.loose().optional()}),zf=D.looseObject({_meta:Nf.optional()}),Bf=D.union([D.string(),D.number().int()]),Vf=D.object({jsonrpc:D.literal(`2.0`),id:Bf,...If.shape}).strict(),Hf=D.object({jsonrpc:D.literal(`2.0`),...Rf.shape}).strict(),Uf=D.object({jsonrpc:D.literal(`2.0`),id:Bf,result:zf}).strict(),Wf=D.object({jsonrpc:D.literal(`2.0`),id:Bf.optional(),error:D.object({code:D.number().int(),message:D.string(),data:D.unknown().optional()})}).strict(),Gf=D.union([Vf,Hf,Uf,Wf]),D.union([Uf,Wf]),Kf=zf.strict(),qf=Lf.extend({requestId:Bf.optional(),reason:D.string().optional()}),Jf=Rf.extend({method:D.literal(`notifications/cancelled`),params:qf}),Yf=D.object({src:D.string(),mimeType:D.string().optional(),sizes:D.array(D.string()).optional(),theme:D.enum([`light`,`dark`]).optional()}),Xf=D.object({icons:D.array(Yf).optional()}),Zf=D.object({name:D.string(),title:D.string().optional()}),Qf=Zf.extend({...Zf.shape,...Xf.shape,version:D.string(),websiteUrl:D.string().optional(),description:D.string().optional()}),$f=D.intersection(D.object({applyDefaults:D.boolean().optional()}),Of),ep=D.preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,D.intersection(D.object({form:$f.optional(),url:Of.optional()}),Of.optional())),tp=D.looseObject({list:Of.optional(),cancel:Of.optional(),requests:D.looseObject({sampling:D.looseObject({createMessage:Of.optional()}).optional(),elicitation:D.looseObject({create:Of.optional()}).optional()}).optional()}),np=D.looseObject({list:Of.optional(),cancel:Of.optional(),requests:D.looseObject({tools:D.looseObject({call:Of.optional()}).optional()}).optional()}),rp=D.object({experimental:D.record(D.string(),Of).optional(),sampling:D.object({context:Of.optional(),tools:Of.optional()}).optional(),elicitation:ep.optional(),roots:D.object({listChanged:D.boolean().optional()}).optional(),tasks:tp.optional(),extensions:D.record(D.string(),Of).optional()}),ip=Pf.extend({protocolVersion:D.string(),capabilities:rp,clientInfo:Qf}),ap=If.extend({method:D.literal(`initialize`),params:ip}),op=D.object({experimental:D.record(D.string(),Of).optional(),logging:Of.optional(),completions:Of.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:np.optional(),extensions:D.record(D.string(),Of).optional()}),sp=zf.extend({protocolVersion:D.string(),capabilities:op,serverInfo:Qf,instructions:D.string().optional()}),cp=Rf.extend({method:D.literal(`notifications/initialized`),params:Lf.optional()}),lp=If.extend({method:D.literal(`ping`),params:Pf.optional()}),up=D.object({progress:D.number(),total:D.optional(D.number()),message:D.optional(D.string())}),dp=D.object({...Lf.shape,...up.shape,progressToken:kf}),fp=Rf.extend({method:D.literal(`notifications/progress`),params:dp}),pp=Pf.extend({cursor:Af.optional()}),mp=If.extend({params:pp.optional()}),hp=zf.extend({nextCursor:Af.optional()}),gp=D.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),_p=D.object({taskId:D.string(),status:gp,ttl:D.union([D.number(),D.null()]),createdAt:D.string(),lastUpdatedAt:D.string(),pollInterval:D.optional(D.number()),statusMessage:D.optional(D.string())}),vp=zf.extend({task:_p}),yp=Lf.merge(_p),bp=Rf.extend({method:D.literal(`notifications/tasks/status`),params:yp}),xp=If.extend({method:D.literal(`tasks/get`),params:Pf.extend({taskId:D.string()})}),Sp=zf.merge(_p),Cp=If.extend({method:D.literal(`tasks/result`),params:Pf.extend({taskId:D.string()})}),wp=zf.loose(),Tp=mp.extend({method:D.literal(`tasks/list`)}),Ep=hp.extend({tasks:D.array(_p)}),Dp=If.extend({method:D.literal(`tasks/cancel`),params:Pf.extend({taskId:D.string()})}),Op=zf.merge(_p),kp=D.object({uri:D.string(),mimeType:D.optional(D.string()),_meta:D.record(D.string(),D.unknown()).optional()}),Ap=kp.extend({text:D.string()}),jp=D.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Mp=kp.extend({blob:jp}),Np=D.enum([`user`,`assistant`]),Pp=D.object({audience:D.array(Np).optional(),priority:D.number().min(0).max(1).optional(),lastModified:D.iso.datetime({offset:!0}).optional()}),Fp=D.object({...Zf.shape,...Xf.shape,uri:D.string(),description:D.optional(D.string()),mimeType:D.optional(D.string()),size:D.optional(D.number()),annotations:Pp.optional(),_meta:D.optional(D.looseObject({}))}),Ip=D.object({...Zf.shape,...Xf.shape,uriTemplate:D.string(),description:D.optional(D.string()),mimeType:D.optional(D.string()),annotations:Pp.optional(),_meta:D.optional(D.looseObject({}))}),Lp=mp.extend({method:D.literal(`resources/list`)}),Rp=hp.extend({resources:D.array(Fp)}),zp=mp.extend({method:D.literal(`resources/templates/list`)}),Bp=hp.extend({resourceTemplates:D.array(Ip)}),Vp=Pf.extend({uri:D.string()}),Hp=Vp,Up=If.extend({method:D.literal(`resources/read`),params:Hp}),Wp=zf.extend({contents:D.array(D.union([Ap,Mp]))}),Gp=Rf.extend({method:D.literal(`notifications/resources/list_changed`),params:Lf.optional()}),Kp=Vp,qp=If.extend({method:D.literal(`resources/subscribe`),params:Kp}),Jp=Vp,Yp=If.extend({method:D.literal(`resources/unsubscribe`),params:Jp}),Xp=Lf.extend({uri:D.string()}),Zp=Rf.extend({method:D.literal(`notifications/resources/updated`),params:Xp}),Qp=D.object({name:D.string(),description:D.optional(D.string()),required:D.optional(D.boolean())}),$p=D.object({...Zf.shape,...Xf.shape,description:D.optional(D.string()),arguments:D.optional(D.array(Qp)),_meta:D.optional(D.looseObject({}))}),em=mp.extend({method:D.literal(`prompts/list`)}),tm=hp.extend({prompts:D.array($p)}),nm=Pf.extend({name:D.string(),arguments:D.record(D.string(),D.string()).optional()}),rm=If.extend({method:D.literal(`prompts/get`),params:nm}),im=D.object({type:D.literal(`text`),text:D.string(),annotations:Pp.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),am=D.object({type:D.literal(`image`),data:jp,mimeType:D.string(),annotations:Pp.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),om=D.object({type:D.literal(`audio`),data:jp,mimeType:D.string(),annotations:Pp.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),sm=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()}),cm=D.object({type:D.literal(`resource`),resource:D.union([Ap,Mp]),annotations:Pp.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),lm=Fp.extend({type:D.literal(`resource_link`)}),um=D.union([im,am,om,lm,cm]),dm=D.object({role:Np,content:um}),fm=zf.extend({description:D.string().optional(),messages:D.array(dm)}),pm=Rf.extend({method:D.literal(`notifications/prompts/list_changed`),params:Lf.optional()}),mm=D.object({title:D.string().optional(),readOnlyHint:D.boolean().optional(),destructiveHint:D.boolean().optional(),idempotentHint:D.boolean().optional(),openWorldHint:D.boolean().optional()}),hm=D.object({taskSupport:D.enum([`required`,`optional`,`forbidden`]).optional()}),gm=D.object({...Zf.shape,...Xf.shape,description:D.string().optional(),inputSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),Df).optional(),required:D.array(D.string()).optional()}).catchall(D.unknown()),outputSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),Df).optional(),required:D.array(D.string()).optional()}).catchall(D.unknown()).optional(),annotations:mm.optional(),execution:hm.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),_m=mp.extend({method:D.literal(`tools/list`)}),vm=hp.extend({tools:D.array(gm)}),ym=zf.extend({content:D.array(um).default([]),structuredContent:D.record(D.string(),D.unknown()).optional(),isError:D.boolean().optional()}),ym.or(zf.extend({toolResult:D.unknown()})),bm=Ff.extend({name:D.string(),arguments:D.record(D.string(),D.unknown()).optional()}),xm=If.extend({method:D.literal(`tools/call`),params:bm}),Sm=Rf.extend({method:D.literal(`notifications/tools/list_changed`),params:Lf.optional()}),D.object({autoRefresh:D.boolean().default(!0),debounceMs:D.number().int().nonnegative().default(300)}),Cm=D.enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),wm=Pf.extend({level:Cm}),Tm=If.extend({method:D.literal(`logging/setLevel`),params:wm}),Em=Lf.extend({level:Cm,logger:D.string().optional(),data:D.unknown()}),Dm=Rf.extend({method:D.literal(`notifications/message`),params:Em}),Om=D.object({name:D.string().optional()}),km=D.object({hints:D.array(Om).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()}),Am=D.object({mode:D.enum([`auto`,`required`,`none`]).optional()}),jm=D.object({type:D.literal(`tool_result`),toolUseId:D.string().describe(`The unique identifier for the corresponding tool call.`),content:D.array(um).default([]),structuredContent:D.object({}).loose().optional(),isError:D.boolean().optional(),_meta:D.record(D.string(),D.unknown()).optional()}),Mm=D.discriminatedUnion(`type`,[im,am,om]),Nm=D.discriminatedUnion(`type`,[im,am,om,sm,jm]),Pm=D.object({role:Np,content:D.union([Nm,D.array(Nm)]),_meta:D.record(D.string(),D.unknown()).optional()}),Fm=Ff.extend({messages:D.array(Pm),modelPreferences:km.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:Of.optional(),tools:D.array(gm).optional(),toolChoice:Am.optional()}),Im=If.extend({method:D.literal(`sampling/createMessage`),params:Fm}),Lm=zf.extend({model:D.string(),stopReason:D.optional(D.enum([`endTurn`,`stopSequence`,`maxTokens`]).or(D.string())),role:Np,content:Mm}),Rm=zf.extend({model:D.string(),stopReason:D.optional(D.enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(D.string())),role:Np,content:D.union([Nm,D.array(Nm)])}),zm=D.object({type:D.literal(`boolean`),title:D.string().optional(),description:D.string().optional(),default:D.boolean().optional()}),Bm=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()}),Vm=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()}),Hm=D.object({type:D.literal(`string`),title:D.string().optional(),description:D.string().optional(),enum:D.array(D.string()),default:D.string().optional()}),Um=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()}),Wm=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()}),Gm=D.union([Hm,Um]),Km=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()}),qm=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()}),Jm=D.union([Km,qm]),Ym=D.union([Wm,Gm,Jm]),Xm=D.union([Ym,zm,Bm,Vm]),Zm=Ff.extend({mode:D.literal(`form`).optional(),message:D.string(),requestedSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),Xm),required:D.array(D.string()).optional()})}),Qm=Ff.extend({mode:D.literal(`url`),message:D.string(),elicitationId:D.string(),url:D.string().url()}),$m=D.union([Zm,Qm]),eh=If.extend({method:D.literal(`elicitation/create`),params:$m}),th=Lf.extend({elicitationId:D.string()}),nh=Rf.extend({method:D.literal(`notifications/elicitation/complete`),params:th}),rh=zf.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())}),ih=D.object({type:D.literal(`ref/resource`),uri:D.string()}),ah=D.object({type:D.literal(`ref/prompt`),name:D.string()}),oh=Pf.extend({ref:D.union([ah,ih]),argument:D.object({name:D.string(),value:D.string()}),context:D.object({arguments:D.record(D.string(),D.string()).optional()}).optional()}),sh=If.extend({method:D.literal(`completion/complete`),params:oh}),ch=zf.extend({completion:D.looseObject({values:D.array(D.string()).max(100),total:D.optional(D.number().int()),hasMore:D.optional(D.boolean())})}),lh=D.object({uri:D.string().startsWith(`file://`),name:D.string().optional(),_meta:D.record(D.string(),D.unknown()).optional()}),uh=If.extend({method:D.literal(`roots/list`),params:Pf.optional()}),dh=zf.extend({roots:D.array(lh)}),fh=Rf.extend({method:D.literal(`notifications/roots/list_changed`),params:Lf.optional()}),ph=D.union([lp,ap,sh,Tm,rm,em,Lp,zp,Up,qp,Yp,xm,_m,xp,Cp,Tp,Dp]),mh=D.union([Jf,fp,cp,fh,bp]),D.union([Kf,Lm,Rm,rh,dh,Sp,Ep,vp]),hh=D.union([lp,Im,eh,uh,xp,Cp,Tp,Dp]),gh=D.union([Jf,fp,Dm,Zp,Gp,Sm,pm,bp,nh]),D.union([Kf,sp,ch,fm,tm,Rp,Bp,Wp,ym,vm,Sp,Ep,vp]),_h={ping:Kf,initialize:sp,"completion/complete":ch,"logging/setLevel":Kf,"prompts/get":fm,"prompts/list":tm,"resources/list":Rp,"resources/templates/list":Bp,"resources/read":Wp,"resources/subscribe":Kf,"resources/unsubscribe":Kf,"tools/call":D.union([ym,vp]),"tools/list":vm,"sampling/createMessage":D.union([Rm,vp]),"elicitation/create":D.union([rh,vp]),"roots/list":dh,"tasks/get":Sp,"tasks/result":zf,"tasks/list":Ep,"tasks/cancel":Op},vh=Od([...ph.options,...hh.options]),yh=Od([...mh.options,...gh.options]),bh=e=>Vf.safeParse(e).success,xh=e=>Hf.safeParse(e).success,Sh=e=>Uf.safeParse(e).success,Ch=e=>Wf.safeParse(e).success,wh=e=>Ff.safeParse(e).success,Th=e=>ap.safeParse(e).success,Eh=e=>cp.safeParse(e).success,Dh=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 U(H.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 U(H.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,vp,n);if(i.task)a=i.task.taskId,yield{type:`taskCreated`,task:i.task};else throw new U(H.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:a},n);if(yield{type:`taskStatus`,task:e},Fd(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 U(H.InternalError,`Task ${a} failed`)};break;case`cancelled`:yield{type:`error`,error:new U(H.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},Sp,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},Ep,t)}async cancelTask(e,t){return this._requireHost.request({method:`tasks/cancel`,params:e},Op,t)}async handleGetTask(e,t){let n=await this._requireTaskStore.getTask(e,t);if(!n)throw new U(H.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 U(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 U(H.InvalidParams,`Task not found: ${e}`);if(!Fd(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,[bf]:{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 U(H.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 U(H.InvalidParams,`Task not found: ${e}`);if(Fd(n.status))throw new U(H.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 U(H.InvalidParams,`Task not found after cancellation: ${e}`);return{_meta:{},...r}}catch(e){throw e instanceof U?e:new U(H.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,[bf]: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)?.[bf]?.taskId,r=wh(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),Sh(e)?n(e):n(new U(e.error.code,e.error.message,e.error.data)),!0):!1}shouldPreserveProgressHandler(e,t){if(Sh(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,[bf]: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(Ch(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 U(H.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=bp.parse({method:`notifications/tasks/status`,params:o});await r?.notification(t),Fd(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 U(H.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Fd(o.status))throw new U(H.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=bp.parse({method:`notifications/tasks/status`,params:s});await r?.notification(t),Fd(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,[bf]: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`&&bh(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new U(H.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 U(H.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new U(H.InvalidRequest,`Request cancelled`))},{once:!0})})}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._host?.removeProgressHandler(t),this._taskProgressTokens.delete(e))}},Oh=class extends Dh{constructor(){super({})}processInboundRequest(e,t){let n=wh(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`}}}},kh=6e4,Ah=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??yf,this._taskManager=e?.tasks?new Dh(e.tasks):new Oh,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=kd(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 V(B.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),Sh(e)||Ch(e)?this._onresponse(e):bh(e)?this._onrequest(e,t):xh(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 V(B.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:H.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,Dd(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:H.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),Sh(e)?i(e):i(U.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=Dd(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 V?e:new V(B.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Pd(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 V(B.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 V(B.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=kd(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=Ad(e);this._notificationHandlers.set(e,e=>{let r=n.parse(e);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}},jh=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 Vd(t)}catch(e){if(e instanceof SyntaxError)continue;throw e}}return null}clear(){this._buffer=void 0}},Mh=/^[A-Za-z0-9._-]{1,128}$/,Nh=1e6,Ph=1e6,Fh=1e4,Ih=1e6,Lh=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,Nh,`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>Fh)throw Error(`Template contains too many expressions (max ${Fh})`);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,Ph,`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,Ph,`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,Ph,`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,Nh,`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,Ih,`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}},Rh=z((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})),zh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Rh();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}}})),W=z((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=Rh(),n=zh();var r=Rh();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=zh();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=O(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=O(this.rhs,e,n),this}get names(){return D(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=O(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(k(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>E(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(te(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=O(this.condition,e,t),this}get names(){let e=super.names;return D(e,this.condition),this.else&&E(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=O(this.iteration,e,t),this}get names(){return E(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return D(D(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=O(this.iterable,e,t),this}get names(){return E(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&E(e,this.catch.names),this.finally&&E(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var ee=class extends m{render(e){return`finally`+super.render(e)}};ee.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
177
+ `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new ee,this.code(n)),this._endBlockNode(T,ee)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function E(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function D(e,n){return n instanceof t._CodeOrName?E(e,n.names):e}function O(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function k(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function te(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ae(e)}`}e.not=te;let ne=ie(e.operators.AND);function re(...e){return e.reduce(ne)}e.and=re;let A=ie(e.operators.OR);function j(...e){return e.reduce(A)}e.or=j;function ie(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ae(n)} ${e} ${ae(r)}`}function ae(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),G=z((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=W(),n=Rh();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})),Bh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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`)}})),Vh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=W(),n=G(),r=Bh();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])}})),Hh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Vh(),n=W(),r=Bh(),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)}})),Uh=z((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})),Wh=z((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})),Gh=z((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=Uh(),n=Wh(),r=Vh(),i=W(),a=G();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}}})),Gh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=W(),n=G();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)}`)}})),Kh=z((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=W(),n=G(),r=zh(),i=G();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})),qh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=W(),n=zh(),r=Kh(),i=Bh();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})),Jh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=W(),n=G();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})),Yh=z(((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}})),Xh=z(((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`)}})),Zh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=G(),n=Yh(),r=Xh(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),Qh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Vh(),n=Wh(),r=Uh(),i=Wh(),a=Gh(),o=qh(),s=Jh(),c=W(),l=zh(),u=Zh(),d=G(),f=Bh();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&k(e),E(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),te(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&k(e),D(e),O(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),ee(e)}function T(e,t){if(e.opts.jtd)return re(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);re(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function ee(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function E(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function D(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function O(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function k({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function te(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&ne(e),t.return((0,c._)`${l.default.errors} === 0`))}function ne({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 re(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(()=>de(e,`$ref`,h.all.$ref.definition));return}p.jtd||j(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)),A(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):A(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function A(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)&&de(e,n.keyword,n.definition,t.type)})}function j(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(ie(e,t),e.opts.allowUnionTypes||ae(e,t),oe(e,e.dataTypes))}function ie(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{ce(e.dataTypes,t)||le(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),M(e,t)}}function ae(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&le(e,`use allowUnionTypes to allow union type keyword`)}function oe(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=>se(t,e))&&le(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function se(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function ce(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function M(e,t){let n=[];for(let r of e.dataTypes)ce(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function le(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var ue=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`,N(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=ue;function de(e,t,n,r){let i=new ue(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 fe=/^\/(?:[^~]|~0|~1)*$/,pe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function N(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!fe.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=pe.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=N})),$h=z((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}}})),eg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Zh();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))}}})),tg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=W(),n=$h(),r=zh(),i=Zh(),a=G(),o=Qh();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),ng=z(((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}})),rg=z(((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}})),ig=z(((e,t)=>{let{isUUID:n}=rg(),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}})),ag=z(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=rg(),{SCHEMES:c,getSchemeHandler:l}=ig();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=_})),og=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ag();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),sg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Qh();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=W();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=$h(),i=eg(),a=Hh(),o=tg(),s=W(),c=Zh(),l=Wh(),u=G(),d=ng(),f=og(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=E(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(O.call(this,n,t),!t)return(0,u.eachItem)(n,e=>k.call(this,e)),this;ne.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]=A(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let ee={log(){},warn(){},error(){}};function E(e){if(e===!1)return ee;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let D=/^[a-z_$][a-z0-9_$:-]*$/i;function O(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!D.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function k(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?te.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function te(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function ne(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=A(t)),e.validateSchema=this.compile(t,!0))}let re={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function A(e){return{anyOf:[e,re]}}})),cg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),lg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=eg(),n=Kh(),r=W(),i=zh(),a=tg(),o=G(),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})),ug=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=cg(),n=lg();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),dg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),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})`)}}})),fg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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}))`)}}})),pg=z((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`})),mg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=pg();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}`)}}})),hg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Kh(),n=G(),r=W();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})`)}}}})),gg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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}`)}}})),_g=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Kh(),n=W(),r=G();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)}}}})),vg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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}`)}}})),yg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Yh();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),bg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Wh(),n=W(),r=G(),i=yg();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)})))}}}})),xg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=yg();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}`)}}})),Sg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=yg();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}`}}}})),Cg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=dg(),n=fg(),r=mg(),i=hg(),a=gg(),o=_g(),s=vg(),c=bg(),l=xg(),u=Sg();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]})),wg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=W(),n=G(),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})),Tg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=W(),n=G(),r=Kh(),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})),Eg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Tg();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Dg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=Kh(),i=wg();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)))}}})),Og=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();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)))}}}})),kg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=W(),n=G(),r=Kh();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}}})),Kh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=W(),n=G();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)}`)}})),qh=z((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=W(),n=G(),r=Bh(),i=G();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})),Jh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=W(),n=Bh(),r=qh(),i=Vh();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})),Yh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=W(),n=G();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})),Xh=z(((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}})),Zh=z(((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`)}})),Qh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=G(),n=Xh(),r=Zh(),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})),$h=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Hh(),n=Gh(),r=Wh(),i=Gh(),a=Kh(),o=Jh(),s=Yh(),c=W(),l=Bh(),u=Qh(),d=G(),f=Vh();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&k(e),E(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),te(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&k(e),D(e),O(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),ee(e)}function T(e,t){if(e.opts.jtd)return re(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);re(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function ee(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function E(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function D(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function O(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function k({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function te(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&ne(e),t.return((0,c._)`${l.default.errors} === 0`))}function ne({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 re(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(()=>de(e,`$ref`,h.all.$ref.definition));return}p.jtd||j(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)),A(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):A(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function A(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)&&de(e,n.keyword,n.definition,t.type)})}function j(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(ie(e,t),e.opts.allowUnionTypes||ae(e,t),oe(e,e.dataTypes))}function ie(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{ce(e.dataTypes,t)||le(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),M(e,t)}}function ae(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&le(e,`use allowUnionTypes to allow union type keyword`)}function oe(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=>se(t,e))&&le(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function se(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function ce(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function M(e,t){let n=[];for(let r of e.dataTypes)ce(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function le(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var ue=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`,me(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=ue;function de(e,t,n,r){let i=new ue(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 fe=/^\/(?:[^~]|~0|~1)*$/,pe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function me(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!fe.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=pe.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=me})),eg=z((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}}})),tg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qh();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))}}})),ng=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=W(),n=eg(),r=Bh(),i=Qh(),a=G(),o=$h();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}})),rg=z(((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}})),ig=z(((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}})),ag=z(((e,t)=>{let{isUUID:n}=ig(),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}})),og=z(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=ig(),{SCHEMES:c,getSchemeHandler:l}=ag();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=_})),sg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=og();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),cg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=$h();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=W();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=eg(),i=tg(),a=Uh(),o=ng(),s=W(),c=Qh(),l=Gh(),u=G(),d=rg(),f=sg(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=E(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(O.call(this,n,t),!t)return(0,u.eachItem)(n,e=>k.call(this,e)),this;ne.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]=A(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let ee={log(){},warn(){},error(){}};function E(e){if(e===!1)return ee;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let D=/^[a-z_$][a-z0-9_$:-]*$/i;function O(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!D.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function k(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?te.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function te(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function ne(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=A(t)),e.validateSchema=this.compile(t,!0))}let re={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function A(e){return{anyOf:[e,re]}}})),lg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),ug=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=tg(),n=qh(),r=W(),i=Bh(),a=ng(),o=G(),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})),dg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=lg(),n=ug();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),fg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),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})`)}}})),pg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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}))`)}}})),mg=z((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`})),hg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=mg();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}`)}}})),gg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qh(),n=G(),r=W();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})`)}}}})),_g=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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}`)}}})),vg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qh(),n=W(),r=G();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)}}}})),yg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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}`)}}})),bg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Xh();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),xg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Gh(),n=W(),r=G(),i=bg();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)})))}}}})),Sg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=bg();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}`)}}})),Cg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=bg();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}`}}}})),wg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=fg(),n=pg(),r=hg(),i=gg(),a=_g(),o=vg(),s=yg(),c=xg(),l=Sg(),u=Cg();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]})),Tg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=W(),n=G(),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})),Eg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=W(),n=G(),r=qh(),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})),Dg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Eg();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Og=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=qh(),i=Tg();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)))}}})),kg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();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)))}}}})),Ag=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=W(),n=G(),r=qh();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})),Ag=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();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)}}})),jg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Kh(),n=W(),r=zh(),i=G();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)}}}})),Mg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qh(),n=Kh(),r=G(),i=jg();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)}}}})),Ng=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Kh(),n=W(),r=G(),i=G();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())})})}}}})),Pg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();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`}}})),Fg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Kh().validateUnion,error:{message:`must match a schema in anyOf`}}})),Ig=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();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)})})}}}})),Lg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();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)})}}})),Rg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),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})),zg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();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`)}}})),Bg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=wg(),n=Eg(),r=Tg(),i=Dg(),a=Og(),o=kg(),s=Ag(),c=jg(),l=Mg(),u=Ng(),d=Pg(),f=Fg(),p=Ig(),m=Lg(),h=Rg(),g=zg();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=_})),Vg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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})`}}}}})),Hg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Vg().default]})),Ug=z((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`]})),Wg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ug(),n=Cg(),r=Bg(),i=Hg(),a=Ug();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Gg=z((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={}))})),Kg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=Gg(),r=tg(),i=eg(),a=G();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}}}}})),qg=z(((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}})),Jg=z(((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=sg(),r=Wg(),i=Kg(),a=qg(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=Qh();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=W();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=$h();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=eg();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Yg=z((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}}})),Xg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=Jg(),n=W(),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)})),Zg=z(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=Yg(),r=Xg(),i=W(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),Qg=Jg(),$g=sf(Zg(),1),e_=class{_ajv;constructor(e){this._ajv=e??Zd()}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)}}},t_=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft??`2020-12`}getValidator(e){let t=new bd(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 r_(){throw Error(`StdioServerTransport is not supported in this environment. Use StreamableHTTPServerTransport instead.`)}var i_,a_=F((()=>{n_(),i_={get stdin(){return r_()},get stdout(){return r_()}}})),o_=Ze({AjvJsonSchemaValidator:()=>e_,CfWorkerJsonSchemaValidator:()=>t_,DEFAULT_NEGOTIATED_PROTOCOL_VERSION:()=>_f,DEFAULT_REQUEST_TIMEOUT_MSEC:()=>Oh,ExperimentalMcpServerTasks:()=>T_,ExperimentalServerTasks:()=>E_,INTERNAL_ERROR:()=>wf,INVALID_PARAMS:()=>Cf,INVALID_REQUEST:()=>xf,InMemoryTaskMessageQueue:()=>w_,InMemoryTaskStore:()=>C_,JSONRPC_VERSION:()=>`2.0`,LATEST_PROTOCOL_VERSION:()=>gf,METHOD_NOT_FOUND:()=>Sf,McpServer:()=>O_,OAuthError:()=>lf,OAuthErrorCode:()=>cf,PARSE_ERROR:()=>bf,ProtocolError:()=>U,ProtocolErrorCode:()=>H,RELATED_TASK_META_KEY:()=>yf,ReadBuffer:()=>Ah,ResourceTemplate:()=>k_,SUPPORTED_PROTOCOL_VERSIONS:()=>vf,SdkError:()=>V,SdkErrorCode:()=>B,Server:()=>D_,StdioServerTransport:()=>M_,UriTemplate:()=>Ih,UrlElicitationRequiredError:()=>Tf,WebStandardStreamableHTTPServerTransport:()=>N_,assertClientRequestTaskCapability:()=>d_,assertCompleteRequestPrompt:()=>jd,assertCompleteRequestResourceTemplate:()=>Md,assertToolsCallTaskCapability:()=>u_,checkResourceAllowed:()=>wd,completable:()=>s_,createFetchWithInit:()=>Kd,deserializeMessage:()=>Bd,fromJsonSchema:()=>x_,getDisplayName:()=>Td,hostHeaderValidationResponse:()=>b_,isCompletable:()=>c_,isInitializeRequest:()=>wh,isInitializedNotification:()=>Th,isJSONRPCErrorResponse:()=>Sh,isJSONRPCNotification:()=>bh,isJSONRPCRequest:()=>yh,isJSONRPCResultResponse:()=>xh,isTaskAugmentedRequestParams:()=>Ch,isTerminal:()=>Pd,localhostAllowedHostnames:()=>y_,parseJSONRPCMessage:()=>Ad,resourceUrlFromServerUrl:()=>Cd,serializeMessage:()=>Vd,takeResult:()=>zd,toArrayAsync:()=>Rd,validateHostHeader:()=>v_});function s_(e,t){return Object.defineProperty(e,S_,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function c_(e){return!!e&&typeof e==`object`&&S_ in e}function l_(e){return e[S_]?.complete}function u_(e,t,n){if(!e)throw new V(B.CapabilityNotSupported,`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw new V(B.CapabilityNotSupported,`${n} does not support task creation for tools/call (required for ${t})`)}function d_(e,t,n){if(!e)throw new V(B.CapabilityNotSupported,`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw new V(B.CapabilityNotSupported,`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw new V(B.CapabilityNotSupported,`${n} does not support task creation for elicitation/create (required for ${t})`)}}function f_(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 p_(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await Yd(t,n);if(!a.success)throw new U(H.InvalidParams,`Invalid arguments for prompt ${e}: ${a.error}`);return r(a.data,i)}}{let e=n;return async(t,n)=>e(n)}}function m_(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}function h_(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function g_(e){return e?.type===`optional`}function __(e){return g_(e)?e.def?.innerType??e:e}function v_(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 y_(){return[`localhost`,`127.0.0.1`,`[::1]`]}function b_(e,t){let n=v_(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 x_(e,t){return Qd(e,t??(P_??=new t_))}var S_,C_,w_,T_,E_,D_,O_,k_,A_,j_,M_,N_,P_,F_=F((()=>{n_(),a_(),S_=Symbol.for(`mcp.completable`),C_=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(Pd(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(Pd(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(),Pd(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}))}},w_=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}},T_=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)}},E_=class{constructor(e){this._server=e}get _module(){return this._server.taskManager}requestStream(e,t){let n=Ed(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 V(B.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 V(B.CapabilityNotSupported,`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw new V(B.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},Cp,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)}},D_=class extends kh{_clientCapabilities;_clientVersion;_capabilities;_instructions;_jsonSchemaValidator;_experimental;oninitialized;constructor(e,t){if(super({...t,tasks:Fd(t?.capabilities?.tasks)}),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new t_,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=Nd(Sm,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 E_(this)},this._experimental}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Sm.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 V(B.AlreadyConnected,`Cannot register capabilities after connecting to transport`);let t=!!this._capabilities.logging;this._capabilities=Ld(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}setRequestHandler(e,t){return e===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=Nd(bm,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new U(H.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=Nd(_p,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new U(H.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=Nd(vm,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new U(H.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 V(B.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw new V(B.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw new V(B.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw new V(B.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 V(B.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw new V(B.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 V(B.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 V(B.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case`completion/complete`:if(!this._capabilities.completions)throw new V(B.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw new V(B.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw new V(B.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 V(B.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw new V(B.CapabilityNotSupported,`Server does not support tools (required for ${e})`)}}assertTaskCapability(e){d_(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){u_(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`},Gf)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new V(B.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 U(H.InvalidParams,`The last message must contain only tool_result content if any is present`);if(!o)throw new U(H.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 U(H.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},Lm,t):this._requestWithSchema({method:`sampling/createMessage`,params:e},Im,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw new V(B.CapabilityNotSupported,`Client does not support url elicitation.`);let n=e;return this._requestWithSchema({method:`elicitation/create`,params:n},nh,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw new V(B.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},nh,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new U(H.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof U?e:new U(H.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new V(B.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},uh,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`})}},O_=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_experimental;constructor(e,t){this.server=new D_(e,t)}get experimental(){return this._experimental||={tasks:new T_(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?qd(t.inputSchema,`input`):A_,annotations:t.annotations,execution:t.execution,_meta:t._meta};return t.outputSchema&&(n.outputSchema=qd(t.outputSchema,`output`)),n})})),this.server.setRequestHandler(`tools/call`,async(e,t)=>{let n=this._registeredTools[e.params.name];if(!n)throw new U(H.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new U(H.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 U(H.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new U(H.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 U&&e.code===H.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 Yd(e.inputSchema,t??{});if(!r.success)throw new U(H.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 U(H.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await Yd(e.outputSchema,t.structuredContent);if(!r.success)throw new U(H.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 U(H.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 jd(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Md(e),this.handleResourceCompletion(e,e.params.ref);default:throw new U(H.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new U(H.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new U(H.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return j_;let r=__(h_(n.argsSchema)?.[e.params.argument.name]);if(!c_(r))return j_;let i=l_(r);return i?m_(await i(e.params.argument.value,e.params.context)):j_}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 j_;throw new U(H.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?m_(await r(e.params.argument.value,e.params.context)):j_}_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 U(H.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 U(H.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?Xd(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 U(H.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new U(H.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:p_(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=p_(e,o,s)),t.enabled!==void 0&&(c.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=c,r){let e=h_(r);e&&Object.values(e).some(e=>c_(__(e)))&&this.setCompletionRequestHandler()}return c}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Wd(e);let l=c,u={title:t,description:n,inputSchema:r,outputSchema:i,annotations:a,execution:o,_meta:s,handler:c,executor:f_(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`&&Wd(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=f_(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()}},k_=class{_uriTemplate;constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new Ih(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},A_={type:`object`,properties:{}},j_={completion:{values:[],hasMore:!1}},M_=class{_readBuffer=new Ah;_started=!1;_closed=!1;constructor(e=i_.stdin,t=i_.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=Vd(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)})}},N_=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??vf}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=>Wf.parse(e)):[Wf.parse(a)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let s=o.some(e=>wh(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=>yh(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=>wh(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)yh(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)yh(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;yh(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((xh(e)||Sh(e))&&(n=e.id),n===void 0){if(xh(e)||Sh(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(xh(e)||Sh(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 I_(e,t,n,r={}){let i=R_(),a=await Promise.resolve().then(()=>(F_(),o_)),{fromJsonSchema:o,McpServer:s}=a,c=await L_(a,i),l=new s({name:e,...r.title?{title:r.title}:void 0,version:t},r.instructions?{instructions:r.instructions}:void 0);B_(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 L_(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 R_(){return Promise.resolve().then(()=>(F_(),o_)).then(e=>({module:e})).catch(e=>({error:e}))}async function z_(e,t,n={}){let r=[...n.middlewares??[],...e.middlewares??[],...e.command.middleware??[]],i=await Gl(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:Lr(a)}})}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}return{content:[{type:`text`,text:Lr(e)}]}}if(!i.ok){let t=gu(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${_u(t)}`:r}],...t?{_meta:{cta:t}}:void 0,isError:!0}}let a=i.data??null,o=Rr(a),s=gu(n.name??e.name,i.cta),c=Lr(o);return{content:[{type:`text`,text:s?`${c}\n\n${_u(s)}`:c}],...a!==null&&e.outputSchema?{structuredContent:o}:void 0,...s?{_meta:{cta:s}}:void 0}}function B_(e,t,n){let r=Y_(t,[],[],n.tools);if(r.length!==0){if((n.tools?.discovery??`progressive`)===`direct`){for(let t of r)V_(e,t,n);return}H_(e,r,n)}}function V_(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)=>z_(t,i?e[0]:{},U_(n,i?e[1]:e[0])))}function H_(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:iv},async e=>{let n=W_(t,e.query),r=n.slice(e.offset,e.offset+e.limit);return q_({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:iv},async e=>{let t=r.get(e.name);return t?q_({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}):J_(`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:rv,annotations:av},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?z_(i,e.arguments,U_(n,t)):J_(`Tool is not read-only: ${e.name}`):J_(`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:rv,annotations:ov},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?J_(`Tool is read-only: ${e.name}`):z_(i,e.arguments,U_(n,t)):J_(`Unknown tool: ${e.name}`)})}function U_(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 W_(e,t){let n=K_(t),r=n.split(` `).filter(Boolean);return e.map(e=>({tool:e,score:G_(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 G_(e,t,n){let r=K_(e.name),i=K_(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 K_(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,` `).trim()}function q_(e){return{content:[{type:`text`,text:Lr(e)}]}}function J_(e){return{...q_({error:e}),isError:!0}}function Y_(e,t,n=[],r){let i=Q_(X_(e,t,n),r);return ev(i),i.sort((e,t)=>e.name.localeCompare(t.name))}function X_(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(Z_(a.root,e,t)),r.push(...X_(a.commands,e,t))}else r.push(Z_(a,e,n))}return r}function Z_(e,t,n){let r=e.mcp===!1?void 0:e.mcp,i=e.output?tv(e.output):void 0;return{name:r?.name??t.join(`_`),description:r?.description??e.description,inputSchema:nv(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 Q_(e,t){if(!t)return e;let n=t.include?.map($_),r=t.exclude?.map($_)??[];return e.filter(e=>r.some(t=>t.test(e.name))?!1:!n||n.length===0||n.some(t=>t.test(e.name)))}function $_(e){let t=e.replace(/[|\\{}()[\]^$+?.]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function ev(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 tv(e){let t=Ou(e);if(t.type===`object`)return t}function nv(e,t){let n={},r=[];for(let i of[e,t]){if(!i)continue;let e=Ou(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 rv,iv,av,ov,sv=F((()=>{tu(),yu(),zr(),ku(),rv=f.object({name:f.string().min(1).describe(`Exact tool name.`),arguments:f.record(f.string(),f.unknown()).default({}).describe(`Arguments from its schema.`)}),iv={destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},av={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},ov={destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1}}));function cv(e){return lv(e,e,new Map)}function lv(e,t,n){if(Array.isArray(e))return e.map(e=>lv(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=uv(t,e);if(typeof i!=`object`||!i||Array.isArray(i)){let r=lv(i,t,n);return n.set(e,r),r}let a={};n.set(e,a);let o=lv(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]=lv(r[e],t,n);return i}function uv(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 dv=F((()=>{}));function fv(e,t={}){let n=gx.get(e);if(!n)throw Error(`No commands registered on this CLI instance`);let r={},i=yx.get(e);i&&hv(r,[],i);for(let[e,t]of n)pv(r,mv(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 pv(e,t,n){if(!(`_alias`in n)&&!(`_fetch`in n)){if(`_group`in n){n.root&&hv(e,t,n.root);for(let[r,i]of n.commands)pv(e,[...t,...mv(r)],i);return}hv(e,t,n)}}function mv(e){return e.split(/\s+/).filter(Boolean)}function hv(e,t,n){let r=n.args?Ou(n.args):void 0,i=n.options?Ou(n.options):void 0,a=n.output?Ou(n.output):void 0,o=Cv(r),s=new Set(wv(r)),c=_v(t),l=gv(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(Cv(i)))s.push({name:e,in:`query`,...wv(i).includes(e)?{required:!0}:void 0,schema:t});let l={operationId:Tv(t,c,r.args),...n.description?{summary:n.description}:void 0,...s.length?{parameters:s}:void 0,...yv(c,i),responses:bv(a)},u=e[r.path]??{};u[c]=l,e[r.path]=u}}function gv(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(Ev).join(`/`)}`})}return o.length===0&&o.push({args:[],path:`/${e.map(Ev).join(`/`)}`}),o}function _v(e){let t=e.map(vv).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 vv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`)}function yv(e,t){return!t||e===`get`||e===`delete`?{}:{requestBody:{required:wv(t).length>0,content:{"application/json":{schema:t}}}}}function bv(e){return{200:{description:`Command completed successfully.`,content:{"application/json":{schema:{type:`object`,required:[`ok`,`data`,`meta`],properties:{ok:{const:!0},data:e??{},meta:Sv()}}}}},400:xv(`Validation error.`),500:xv(`Command failed.`)}}function xv(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:Sv()}}}}}}function Sv(){return{type:`object`,required:[`command`,`duration`],properties:{command:{type:`string`},duration:{type:`string`}}}}function Cv(e){return e?.properties??{}}function wv(e){return e?.required??[]}function Tv(e,t,n){return`${t}${[...e,...n.length?[n.join(` `)]:[]].join(` `).replace(/(?:^|[\s_-]+)(\w)/g,(e,t)=>t.toUpperCase())}`}function Ev(e){return e.startsWith(`{`)&&e.endsWith(`}`)?e:encodeURIComponent(e)}async function Dv(e,t={}){if(typeof e!=`string`&&!(e instanceof URL))return e;let n=await fetch(Ov(e,t.baseUrl));if(!n.ok)throw Error(`Failed to fetch OpenAPI spec from ${e}: ${n.status}`);return await n.json()}function Ov(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 kv(e,t,n={}){let r=cv(structuredClone(e)),i=new Map,a=jv(r.paths??{}),o=zv(a),{config:s}=n;s?.compact&&Pv(a);for(let{method:e,operation:c,path:l}of a){let a=Bv({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=Lv([...(c.parameters??[]).filter(e=>e.in===`header`),...s?.security===!1?[]:Mv(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?Xv(t.schema):f.string();t.description&&(n=n.describe(t.description)),e[t.name]=Zv(n)}v=f.object(e)}let y={},b=new Set;for(let e of p){let t=e.schema?Xv(e.schema):f.string();e.required||(t=t.optional()),e.description&&(t=t.describe(e.description)),y[e.name]=Zv(t),b.add(e.name)}for(let[e,t]of Object.entries(g)){let n=Xv(t);_.has(e)||(n=n.optional()),y[e]=n,b.add(e)}for(let e of m){let t=Rv(e.optionName,b);e.optionName=t;let n=e.schema?Xv(e.schema):f.string();e.required||(n=n.optional()),n=n.describe(e.description??`${e.name} header`),y[t]=Zv(n),b.add(t)}let x=Object.keys(y).length>0?f.object(y):void 0;qv(i,a,{description:c.summary??c.description,mcp:{annotations:Av(e),...c.summary&&c.description&&c.summary!==c.description?{description:`${c.summary}\n\n${c.description}`}:void 0},args:v,options:x,run:Yv({basePath:n.basePath,fetch:t,forwardHeaders:s?.forwardHeaders,httpMethod:u,path:l,headerParams:m,pathParams:d,queryParams:p,bodyProps:g})})}return i}function Av(e){let t=[`get`,`head`,`options`,`trace`].includes(e);return{destructiveHint:!t,idempotentHint:t||e===`delete`||e===`put`,openWorldHint:!0,readOnlyHint:t}}function jv(e){let t=[];for(let[n,r]of Object.entries(e))for(let[e,i]of Object.entries(r))Qv.has(e)&&t.push({method:e,operation:i,path:n});return t}function Mv(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=Nv(t,e);r&&i.push(r)}return i}function Nv(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`&&$v.has(t.scheme?.toLowerCase()??``))return{description:t.description??`${e} authorization header`,in:`header`,name:`authorization`,required:!1,schema:{type:`string`}}}}function Pv(e){for(let{operation:t}of e){for(let e of t.parameters??[])e.schema&&=Fv(e.schema);let e=t.requestBody?.content?.[`application/json`];e?.schema&&(e.schema=Fv(e.schema))}}function Fv(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>ey&&delete r.pattern,typeof r.format==`string`&&ty.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=>Fv(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];Iv(n)&&(r[e]=Fv(n,t))}for(let e of[`$defs`,`patternProperties`,`properties`]){let n=r[e];if(!Iv(n))continue;let i={};for(let[e,r]of Object.entries(n))i[e]=Iv(r)?Fv(r,t):r;r[e]=i}return r}function Iv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lv(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 Rv(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 zv(e){let t=new Map,n=new Set;for(let{path:r}of e){t.set(r,(t.get(r)??0)+1);let e=Hv(r);for(let t=1;t<e.length;t++)n.add(`/${e.slice(0,t).join(`/`)}`)}return{parentPaths:n,pathOperations:t}}function Bv(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=Vv(a,i),s=o.length===0||r.parentPaths.has(Uv(a))||(r.pathOperations.get(a)??0)>1,c=Kv(o,i.summary??i.description);return[...c.length>0?c:[{name:`root`}],...s?[{name:t}]:[]]}function Vv(e,t){return e.split(`/`).map(e=>Wv(e,t)).filter(Gv)}function Hv(e){return Vv(e).map(e=>e.name)}function Uv(e){return`/${Hv(e).join(`/`)}`}function Wv(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 Gv(e){return e!==void 0}function Kv(e,t){return!t||e.length===0?e:e.map((n,r)=>r===e.length-1&&!n.description?{...n,description:t}:n)}function qv(e,t,n){let[r,...i]=t;if(r){if(i.length===0){e.set(r.name,n);return}qv(Jv(e,r).commands,i,n)}}function Jv(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 Yv(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=On(c),u=await jn(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 Xv(e){return f.fromJSONSchema(e)}function Zv(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 Qv,$v,ey,ty,ny=F((()=>{Ex(),Pn(),dv(),ku(),Qv=new Set([`delete`,`get`,`head`,`options`,`patch`,`post`,`put`,`trace`]),$v=new Set([`basic`,`bearer`]),ey=100,ty=new Set([`date`,`date-time`,`duration`,`time`])}));async function ry(e,t={}){let n=cy(e);await ly(n,`initialize`,{protocolVersion:hy,capabilities:{},clientInfo:{name:`incur`,version:t.version??`1.0.0`}}),n.initialized=!0,await ly(n,`notifications/initialized`);let r=(await ly(n,`tools/list`)).tools??[];return ay(r)?{discovery:`progressive`,tools:await oy(n),session:n}:{tools:r,session:n}}function iy(e){let t=new Map;for(let n of e.tools){let r=n.inputSchema?dy(n.inputSchema):void 0,i=fy(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 ly(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:py(i)}):my(i)}})}return t}function ay(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 oy(e){let t=[],n=0;for(;n!==void 0;){let r=await sy(e,`search_tools`,{query:``,limit:20,offset:n});for(let n of r.tools??[]){if(!n.name)continue;let r=await sy(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 sy(e,t,n){let r=await ly(e,`tools/call`,{name:t,arguments:n});if(r.isError)throw Error(py(r)||`MCP tool failed: ${t}`);return my(r)}function cy(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 ly(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`,hy);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`)?uy(l,i):JSON.parse(l);if(u.error)throw Error(u.error.message??`MCP request failed`);return u.result??{}}function uy(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
- `);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 dy(e){let t=e.properties??{},n=new Set(e.required??[]),r={};for(let[e,i]of Object.entries(t)){let t=Xv(i);n.has(e)||(t=t.optional()),typeof i.description==`string`&&(t=t.describe(i.description)),r[e]=Zv(t)}return Object.keys(r).length>0?f.object(r):void 0}function fy(e){if(!(!e||e.type!==`object`))try{return f.fromJSONSchema(e)}catch{return}}function py(e){return(Array.isArray(e.content)?e.content:[]).map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
186
- `)}function my(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 hy,gy=F((()=>{ny(),hy=`2025-06-18`}));function _y(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=vy(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 vy(e,t){let n=t.name?`${e} ${t.name}`:e;if(!t.args)return n;let r=t.args.shape,i=Ou(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 yy(e,t,n=new Map){if(!(n.size>0))return t.map(t=>Sy(e,t)).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})),jg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();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)}}})),Mg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qh(),n=W(),r=Bh(),i=G();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)}}}})),Ng=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=$h(),n=qh(),r=G(),i=Mg();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)}}}})),Pg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qh(),n=W(),r=G(),i=G();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())})})}}}})),Fg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();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`}}})),Ig=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:qh().validateUnion,error:{message:`must match a schema in anyOf`}}})),Lg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();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)})})}}}})),Rg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();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)})}}})),zg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),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})),Bg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();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`)}}})),Vg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Tg(),n=Dg(),r=Eg(),i=Og(),a=kg(),o=Ag(),s=jg(),c=Mg(),l=Ng(),u=Pg(),d=Fg(),f=Ig(),p=Lg(),m=Rg(),h=zg(),g=Bg();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=_})),Hg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();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})`}}}}})),Ug=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Hg().default]})),Wg=z((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`]})),Gg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=dg(),n=wg(),r=Vg(),i=Ug(),a=Wg();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Kg=z((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={}))})),qg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=Kg(),r=ng(),i=tg(),a=G();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}}}}})),Jg=z(((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}})),Yg=z(((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=cg(),r=Gg(),i=qg(),a=Jg(),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=$h();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=W();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=eg();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=tg();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Xg=z((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}}})),Zg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=Yg(),n=W(),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)})),Qg=z(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=Xg(),r=Zg(),i=W(),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})),$g=Yg(),e_=cf(Qg(),1),t_=class{_ajv;constructor(e){this._ajv=e??Qd()}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)}}},n_=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft??`2020-12`}getValidator(e){let t=new xd(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 i_(){throw Error(`StdioServerTransport is not supported in this environment. Use StreamableHTTPServerTransport instead.`)}var a_,o_=F((()=>{r_(),a_={get stdin(){return i_()},get stdout(){return i_()}}})),s_=Qe({AjvJsonSchemaValidator:()=>t_,CfWorkerJsonSchemaValidator:()=>n_,DEFAULT_NEGOTIATED_PROTOCOL_VERSION:()=>vf,DEFAULT_REQUEST_TIMEOUT_MSEC:()=>kh,ExperimentalMcpServerTasks:()=>E_,ExperimentalServerTasks:()=>D_,INTERNAL_ERROR:()=>Tf,INVALID_PARAMS:()=>wf,INVALID_REQUEST:()=>Sf,InMemoryTaskMessageQueue:()=>T_,InMemoryTaskStore:()=>w_,JSONRPC_VERSION:()=>`2.0`,LATEST_PROTOCOL_VERSION:()=>_f,METHOD_NOT_FOUND:()=>Cf,McpServer:()=>k_,OAuthError:()=>uf,OAuthErrorCode:()=>lf,PARSE_ERROR:()=>xf,ProtocolError:()=>U,ProtocolErrorCode:()=>H,RELATED_TASK_META_KEY:()=>bf,ReadBuffer:()=>jh,ResourceTemplate:()=>A_,SUPPORTED_PROTOCOL_VERSIONS:()=>yf,SdkError:()=>V,SdkErrorCode:()=>B,Server:()=>O_,StdioServerTransport:()=>N_,UriTemplate:()=>Lh,UrlElicitationRequiredError:()=>Ef,WebStandardStreamableHTTPServerTransport:()=>P_,assertClientRequestTaskCapability:()=>f_,assertCompleteRequestPrompt:()=>Md,assertCompleteRequestResourceTemplate:()=>Nd,assertToolsCallTaskCapability:()=>d_,checkResourceAllowed:()=>Td,completable:()=>c_,createFetchWithInit:()=>qd,deserializeMessage:()=>Vd,fromJsonSchema:()=>S_,getDisplayName:()=>Ed,hostHeaderValidationResponse:()=>x_,isCompletable:()=>l_,isInitializeRequest:()=>Th,isInitializedNotification:()=>Eh,isJSONRPCErrorResponse:()=>Ch,isJSONRPCNotification:()=>xh,isJSONRPCRequest:()=>bh,isJSONRPCResultResponse:()=>Sh,isTaskAugmentedRequestParams:()=>wh,isTerminal:()=>Fd,localhostAllowedHostnames:()=>b_,parseJSONRPCMessage:()=>jd,resourceUrlFromServerUrl:()=>wd,serializeMessage:()=>Hd,takeResult:()=>Bd,toArrayAsync:()=>zd,validateHostHeader:()=>y_});function c_(e,t){return Object.defineProperty(e,C_,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function l_(e){return!!e&&typeof e==`object`&&C_ in e}function u_(e){return e[C_]?.complete}function d_(e,t,n){if(!e)throw new V(B.CapabilityNotSupported,`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw new V(B.CapabilityNotSupported,`${n} does not support task creation for tools/call (required for ${t})`)}function f_(e,t,n){if(!e)throw new V(B.CapabilityNotSupported,`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw new V(B.CapabilityNotSupported,`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw new V(B.CapabilityNotSupported,`${n} does not support task creation for elicitation/create (required for ${t})`)}}function p_(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 m_(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await Xd(t,n);if(!a.success)throw new U(H.InvalidParams,`Invalid arguments for prompt ${e}: ${a.error}`);return r(a.data,i)}}{let e=n;return async(t,n)=>e(n)}}function h_(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}function g_(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function __(e){return e?.type===`optional`}function v_(e){return __(e)?e.def?.innerType??e:e}function y_(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 b_(){return[`localhost`,`127.0.0.1`,`[::1]`]}function x_(e,t){let n=y_(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 S_(e,t){return $d(e,t??(F_??=new n_))}var C_,w_,T_,E_,D_,O_,k_,A_,j_,M_,N_,P_,F_,I_=F((()=>{r_(),o_(),C_=Symbol.for(`mcp.completable`),w_=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(Fd(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(Fd(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(),Fd(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}))}},T_=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}},E_=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)}},D_=class{constructor(e){this._server=e}get _module(){return this._server.taskManager}requestStream(e,t){let n=Dd(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 V(B.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 V(B.CapabilityNotSupported,`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw new V(B.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},wp,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)}},O_=class extends Ah{_clientCapabilities;_clientVersion;_capabilities;_instructions;_jsonSchemaValidator;_experimental;oninitialized;constructor(e,t){if(super({...t,tasks:Id(t?.capabilities?.tasks)}),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new n_,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=Pd(Cm,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 D_(this)},this._experimental}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Cm.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 V(B.AlreadyConnected,`Cannot register capabilities after connecting to transport`);let t=!!this._capabilities.logging;this._capabilities=Rd(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}setRequestHandler(e,t){return e===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=Pd(xm,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new U(H.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=Pd(vp,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new U(H.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=Pd(ym,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new U(H.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 V(B.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw new V(B.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw new V(B.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw new V(B.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 V(B.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw new V(B.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 V(B.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 V(B.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case`completion/complete`:if(!this._capabilities.completions)throw new V(B.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw new V(B.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw new V(B.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 V(B.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw new V(B.CapabilityNotSupported,`Server does not support tools (required for ${e})`)}}assertTaskCapability(e){f_(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){d_(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`},Kf)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new V(B.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 U(H.InvalidParams,`The last message must contain only tool_result content if any is present`);if(!o)throw new U(H.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 U(H.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},Rm,t):this._requestWithSchema({method:`sampling/createMessage`,params:e},Lm,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw new V(B.CapabilityNotSupported,`Client does not support url elicitation.`);let n=e;return this._requestWithSchema({method:`elicitation/create`,params:n},rh,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw new V(B.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},rh,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new U(H.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof U?e:new U(H.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new V(B.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},dh,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`})}},k_=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_experimental;constructor(e,t){this.server=new O_(e,t)}get experimental(){return this._experimental||={tasks:new E_(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?Jd(t.inputSchema,`input`):j_,annotations:t.annotations,execution:t.execution,_meta:t._meta};return t.outputSchema&&(n.outputSchema=Jd(t.outputSchema,`output`)),n})})),this.server.setRequestHandler(`tools/call`,async(e,t)=>{let n=this._registeredTools[e.params.name];if(!n)throw new U(H.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new U(H.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 U(H.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new U(H.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 U&&e.code===H.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 Xd(e.inputSchema,t??{});if(!r.success)throw new U(H.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 U(H.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await Xd(e.outputSchema,t.structuredContent);if(!r.success)throw new U(H.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 U(H.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 Md(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Nd(e),this.handleResourceCompletion(e,e.params.ref);default:throw new U(H.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new U(H.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new U(H.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return M_;let r=v_(g_(n.argsSchema)?.[e.params.argument.name]);if(!l_(r))return M_;let i=u_(r);return i?h_(await i(e.params.argument.value,e.params.context)):M_}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 M_;throw new U(H.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?h_(await r(e.params.argument.value,e.params.context)):M_}_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 U(H.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 U(H.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?Zd(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 U(H.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new U(H.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:m_(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=m_(e,o,s)),t.enabled!==void 0&&(c.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=c,r){let e=g_(r);e&&Object.values(e).some(e=>l_(v_(e)))&&this.setCompletionRequestHandler()}return c}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Gd(e);let l=c,u={title:t,description:n,inputSchema:r,outputSchema:i,annotations:a,execution:o,_meta:s,handler:c,executor:p_(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`&&Gd(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=p_(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()}},A_=class{_uriTemplate;constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new Lh(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},j_={type:`object`,properties:{}},M_={completion:{values:[],hasMore:!1}},N_=class{_readBuffer=new jh;_started=!1;_closed=!1;constructor(e=a_.stdin,t=a_.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=Hd(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)})}},P_=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??yf}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=>Gf.parse(e)):[Gf.parse(a)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let s=o.some(e=>Th(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=>bh(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=>Th(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)bh(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)bh(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;bh(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((Sh(e)||Ch(e))&&(n=e.id),n===void 0){if(Sh(e)||Ch(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(Sh(e)||Ch(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 L_(e,t,n,r={}){let i=z_(),a=await Promise.resolve().then(()=>(I_(),s_)),{fromJsonSchema:o,McpServer:s}=a,c=await R_(a,i),l=new s({name:e,...r.title?{title:r.title}:void 0,version:t},r.instructions?{instructions:r.instructions}:void 0);V_(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 R_(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 z_(){return Promise.resolve().then(()=>(I_(),s_)).then(e=>({module:e})).catch(e=>({error:e}))}async function B_(e,t,n={}){let r=[...n.middlewares??[],...e.middlewares??[],...e.command.middleware??[]],i=await Kl(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:Rr(a)}})}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}return{content:[{type:`text`,text:Rr(e)}]}}if(!i.ok){let t=_u(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${vu(t)}`:r}],...t?{_meta:{cta:t}}:void 0,isError:!0}}let a=i.data??null,o=zr(a),s=_u(n.name??e.name,i.cta),c=Rr(o);return{content:[{type:`text`,text:s?`${c}\n\n${vu(s)}`:c}],...a!==null&&e.outputSchema?{structuredContent:o}:void 0,...s?{_meta:{cta:s}}:void 0}}function V_(e,t,n){let r=X_(t,[],[],n.tools);if(r.length!==0){if((n.tools?.discovery??`progressive`)===`direct`){for(let t of r)H_(e,t,n);return}U_(e,r,n)}}function H_(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)=>B_(t,i?e[0]:{},W_(n,i?e[1]:e[0])))}function U_(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:av},async e=>{let n=G_(t,e.query),r=n.slice(e.offset,e.offset+e.limit);return J_({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:av},async e=>{let t=r.get(e.name);return t?J_({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}):Y_(`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:iv,annotations:ov},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?B_(i,e.arguments,W_(n,t)):Y_(`Tool is not read-only: ${e.name}`):Y_(`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:iv,annotations:sv},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?Y_(`Tool is read-only: ${e.name}`):B_(i,e.arguments,W_(n,t)):Y_(`Unknown tool: ${e.name}`)})}function W_(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 G_(e,t){let n=q_(t),r=n.split(` `).filter(Boolean);return e.map(e=>({tool:e,score:K_(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 K_(e,t,n){let r=q_(e.name),i=q_(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 q_(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,` `).trim()}function J_(e){return{content:[{type:`text`,text:Rr(e)}]}}function Y_(e){return{...J_({error:e}),isError:!0}}function X_(e,t,n=[],r){let i=$_(Z_(e,t,n),r);return tv(i),i.sort((e,t)=>e.name.localeCompare(t.name))}function Z_(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(Q_(a.root,e,t)),r.push(...Z_(a.commands,e,t))}else r.push(Q_(a,e,n))}return r}function Q_(e,t,n){let r=e.mcp===!1?void 0:e.mcp,i=e.output?nv(e.output):void 0;return{name:r?.name??t.join(`_`),description:r?.description??e.description,inputSchema:rv(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 $_(e,t){if(!t)return e;let n=t.include?.map(ev),r=t.exclude?.map(ev)??[];return e.filter(e=>r.some(t=>t.test(e.name))?!1:!n||n.length===0||n.some(t=>t.test(e.name)))}function ev(e){let t=e.replace(/[|\\{}()[\]^$+?.]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function tv(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 nv(e){let t=ku(e);if(t.type===`object`)return t}function rv(e,t){let n={},r=[];for(let i of[e,t]){if(!i)continue;let e=ku(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 iv,av,ov,sv,cv=F((()=>{nu(),bu(),Br(),Au(),iv=f.object({name:f.string().min(1).describe(`Exact tool name.`),arguments:f.record(f.string(),f.unknown()).default({}).describe(`Arguments from its schema.`)}),av={destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},ov={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},sv={destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1}}));function lv(e){return uv(e,e,new Map)}function uv(e,t,n){if(Array.isArray(e))return e.map(e=>uv(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=dv(t,e);if(typeof i!=`object`||!i||Array.isArray(i)){let r=uv(i,t,n);return n.set(e,r),r}let a={};n.set(e,a);let o=uv(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]=uv(r[e],t,n);return i}function dv(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 fv=F((()=>{}));function pv(e,t={}){let n=_x.get(e);if(!n)throw Error(`No commands registered on this CLI instance`);let r={},i=bx.get(e);i&&gv(r,[],i);for(let[e,t]of n)mv(r,hv(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 mv(e,t,n){if(!(`_alias`in n)&&!(`_fetch`in n)){if(`_group`in n){n.root&&gv(e,t,n.root);for(let[r,i]of n.commands)mv(e,[...t,...hv(r)],i);return}gv(e,t,n)}}function hv(e){return e.split(/\s+/).filter(Boolean)}function gv(e,t,n){let r=n.args?ku(n.args):void 0,i=n.options?ku(n.options):void 0,a=n.output?ku(n.output):void 0,o=wv(r),s=new Set(Tv(r)),c=vv(t),l=_v(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(wv(i)))s.push({name:e,in:`query`,...Tv(i).includes(e)?{required:!0}:void 0,schema:t});let l={operationId:Ev(t,c,r.args),...n.description?{summary:n.description}:void 0,...s.length?{parameters:s}:void 0,...bv(c,i),responses:xv(a)},u=e[r.path]??{};u[c]=l,e[r.path]=u}}function _v(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(Dv).join(`/`)}`})}return o.length===0&&o.push({args:[],path:`/${e.map(Dv).join(`/`)}`}),o}function vv(e){let t=e.map(yv).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 yv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`)}function bv(e,t){return!t||e===`get`||e===`delete`?{}:{requestBody:{required:Tv(t).length>0,content:{"application/json":{schema:t}}}}}function xv(e){return{200:{description:`Command completed successfully.`,content:{"application/json":{schema:{type:`object`,required:[`ok`,`data`,`meta`],properties:{ok:{const:!0},data:e??{},meta:Cv()}}}}},400:Sv(`Validation error.`),500:Sv(`Command failed.`)}}function Sv(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:Cv()}}}}}}function Cv(){return{type:`object`,required:[`command`,`duration`],properties:{command:{type:`string`},duration:{type:`string`}}}}function wv(e){return e?.properties??{}}function Tv(e){return e?.required??[]}function Ev(e,t,n){return`${t}${[...e,...n.length?[n.join(` `)]:[]].join(` `).replace(/(?:^|[\s_-]+)(\w)/g,(e,t)=>t.toUpperCase())}`}function Dv(e){return e.startsWith(`{`)&&e.endsWith(`}`)?e:encodeURIComponent(e)}async function Ov(e,t={}){if(typeof e!=`string`&&!(e instanceof URL))return e;let n=await fetch(kv(e,t.baseUrl));if(!n.ok)throw Error(`Failed to fetch OpenAPI spec from ${e}: ${n.status}`);return await n.json()}function kv(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 Av(e,t,n={}){let r=lv(structuredClone(e)),i=new Map,a=Mv(r.paths??{}),o=Bv(a),{config:s}=n;s?.compact&&Fv(a);for(let{method:e,operation:c,path:l}of a){let a=Vv({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=Rv([...(c.parameters??[]).filter(e=>e.in===`header`),...s?.security===!1?[]:Nv(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?Zv(t.schema):f.string();t.description&&(n=n.describe(t.description)),e[t.name]=Qv(n)}v=f.object(e)}let y={},b=new Set;for(let e of p){let t=e.schema?Zv(e.schema):f.string();e.required||(t=t.optional()),e.description&&(t=t.describe(e.description)),y[e.name]=Qv(t),b.add(e.name)}for(let[e,t]of Object.entries(g)){let n=Zv(t);_.has(e)||(n=n.optional()),y[e]=n,b.add(e)}for(let e of m){let t=zv(e.optionName,b);e.optionName=t;let n=e.schema?Zv(e.schema):f.string();e.required||(n=n.optional()),n=n.describe(e.description??`${e.name} header`),y[t]=Qv(n),b.add(t)}let x=Object.keys(y).length>0?f.object(y):void 0;Jv(i,a,{description:c.summary??c.description,mcp:{annotations:jv(e),...c.summary&&c.description&&c.summary!==c.description?{description:`${c.summary}\n\n${c.description}`}:void 0},args:v,options:x,run:Xv({basePath:n.basePath,fetch:t,forwardHeaders:s?.forwardHeaders,httpMethod:u,path:l,headerParams:m,pathParams:d,queryParams:p,bodyProps:g})})}return i}function jv(e){let t=[`get`,`head`,`options`,`trace`].includes(e);return{destructiveHint:!t,idempotentHint:t||e===`delete`||e===`put`,openWorldHint:!0,readOnlyHint:t}}function Mv(e){let t=[];for(let[n,r]of Object.entries(e))for(let[e,i]of Object.entries(r))$v.has(e)&&t.push({method:e,operation:i,path:n});return t}function Nv(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=Pv(t,e);r&&i.push(r)}return i}function Pv(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`&&ey.has(t.scheme?.toLowerCase()??``))return{description:t.description??`${e} authorization header`,in:`header`,name:`authorization`,required:!1,schema:{type:`string`}}}}function Fv(e){for(let{operation:t}of e){for(let e of t.parameters??[])e.schema&&=Iv(e.schema);let e=t.requestBody?.content?.[`application/json`];e?.schema&&(e.schema=Iv(e.schema))}}function Iv(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>ty&&delete r.pattern,typeof r.format==`string`&&ny.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=>Iv(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];Lv(n)&&(r[e]=Iv(n,t))}for(let e of[`$defs`,`patternProperties`,`properties`]){let n=r[e];if(!Lv(n))continue;let i={};for(let[e,r]of Object.entries(n))i[e]=Lv(r)?Iv(r,t):r;r[e]=i}return r}function Lv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rv(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 zv(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 Bv(e){let t=new Map,n=new Set;for(let{path:r}of e){t.set(r,(t.get(r)??0)+1);let e=Uv(r);for(let t=1;t<e.length;t++)n.add(`/${e.slice(0,t).join(`/`)}`)}return{parentPaths:n,pathOperations:t}}function Vv(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=Hv(a,i),s=o.length===0||r.parentPaths.has(Wv(a))||(r.pathOperations.get(a)??0)>1,c=qv(o,i.summary??i.description);return[...c.length>0?c:[{name:`root`}],...s?[{name:t}]:[]]}function Hv(e,t){return e.split(`/`).map(e=>Gv(e,t)).filter(Kv)}function Uv(e){return Hv(e).map(e=>e.name)}function Wv(e){return`/${Uv(e).join(`/`)}`}function Gv(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 Kv(e){return e!==void 0}function qv(e,t){return!t||e.length===0?e:e.map((n,r)=>r===e.length-1&&!n.description?{...n,description:t}:n)}function Jv(e,t,n){let[r,...i]=t;if(r){if(i.length===0){e.set(r.name,n);return}Jv(Yv(e,r).commands,i,n)}}function Yv(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 Xv(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=kn(c),u=await Mn(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 Zv(e){return f.fromJSONSchema(e)}function Qv(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 $v,ey,ty,ny,ry=F((()=>{Dx(),Fn(),fv(),Au(),$v=new Set([`delete`,`get`,`head`,`options`,`patch`,`post`,`put`,`trace`]),ey=new Set([`basic`,`bearer`]),ty=100,ny=new Set([`date`,`date-time`,`duration`,`time`])}));async function iy(e,t={}){let n=ly(e);await uy(n,`initialize`,{protocolVersion:gy,capabilities:{},clientInfo:{name:`incur`,version:t.version??`1.0.0`}}),n.initialized=!0,await uy(n,`notifications/initialized`);let r=(await uy(n,`tools/list`)).tools??[];return oy(r)?{discovery:`progressive`,tools:await sy(n),session:n}:{tools:r,session:n}}function ay(e){let t=new Map;for(let n of e.tools){let r=n.inputSchema?fy(n.inputSchema):void 0,i=py(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 uy(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:my(i)}):hy(i)}})}return t}function oy(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 sy(e){let t=[],n=0;for(;n!==void 0;){let r=await cy(e,`search_tools`,{query:``,limit:20,offset:n});for(let n of r.tools??[]){if(!n.name)continue;let r=await cy(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 cy(e,t,n){let r=await uy(e,`tools/call`,{name:t,arguments:n});if(r.isError)throw Error(my(r)||`MCP tool failed: ${t}`);return hy(r)}function ly(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 uy(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`,gy);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`)?dy(l,i):JSON.parse(l);if(u.error)throw Error(u.error.message??`MCP request failed`);return u.result??{}}function dy(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
+ `);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 fy(e){let t=e.properties??{},n=new Set(e.required??[]),r={};for(let[e,i]of Object.entries(t)){let t=Zv(i);n.has(e)||(t=t.optional()),typeof i.description==`string`&&(t=t.describe(i.description)),r[e]=Qv(t)}return Object.keys(r).length>0?f.object(r):void 0}function py(e){if(!(!e||e.type!==`object`))try{return f.fromJSONSchema(e)}catch{return}}function my(e){return(Array.isArray(e.content)?e.content:[]).map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
186
+ `)}function hy(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 gy,_y=F((()=>{ry(),gy=`2025-06-18`}));function vy(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=yy(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 yy(e,t){let n=t.name?`${e} ${t.name}`:e;if(!t.args)return n;let r=t.args.shape,i=ku(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 by(e,t,n=new Map){if(!(n.size>0))return t.map(t=>Cy(e,t)).join(`
188
188
 
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(Sy(e,a,t?3:2))}return r.join(`
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(Cy(e,a,t?3:2))}return r.join(`
190
190
 
191
- `)}function by(e,t,n,r=new Map){if(n===0)return[{dir:``,content:xy(e,e,t,r,e)}];let i=new Map;for(let r of t){if(!r.name){let t=Ty(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:xy(e,o?`${e} ${o}`:e,i,r,o||void 0)}})}function xy(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${gl().stringify({name:Ty(t),description:c,requires_bin:e,command:t},{lineWidth:0}).trimEnd()}\n---`}\n\n${n.map(t=>Sy(e,t)).join(`
191
+ `)}function xy(e,t,n,r=new Map){if(n===0)return[{dir:``,content:Sy(e,e,t,r,e)}];let i=new Map;for(let r of t){if(!r.name){let t=Ey(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:Sy(e,o?`${e} ${o}`:e,i,r,o||void 0)}})}function Sy(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${_l().stringify({name:Ey(t),description:c,requires_bin:e,command:t},{lineWidth:0}).trimEnd()}\n---`}\n\n${n.map(t=>Cy(e,t)).join(`
192
192
 
193
193
  ---
194
194
 
195
- `)}`}function Sy(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=Ou(t.args),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e];return`| \`${e}\` | \`${Ey(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=Ou(t.env),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e],i=Ey(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=Ou(t.options).properties,r=Object.entries(e).map(([e,t])=>{let r=n?.[e],i=Ey(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=Ou(t.output),n=wy(e);if(n)i.push(`${s} Output\n\n${n}`);else{let t=Ey(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 Cy(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=ku(t.args),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e];return`| \`${e}\` | \`${Dy(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=ku(t.env),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e],i=Dy(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=ku(t.options).properties,r=Object.entries(e).map(([e,t])=>{let r=n?.[e],i=Dy(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=ku(t.output),n=Ty(e);if(n)i.push(`${s} Output\n\n${n}`);else{let t=Dy(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 Cy(e){let t=e.map(e=>({name:e.name,description:e.description,hint:e.hint,args:e.args?Ou(e.args):void 0,env:e.env?Ou(e.env):void 0,options:e.options?Ou(e.options):void 0,output:e.output?Ou(e.output):void 0}));return g(`sha256`).update(JSON.stringify(t)).digest(`hex`).slice(0,16)}function wy(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=Ey(a),s=r.has(e)?`yes`:`no`,c=a.description??``;if(i.push(`| \`${n}\` | \`${o}\` | ${s} | ${c} |`),a.type===`object`&&a.properties){let e=wy(a,n);if(e){let t=e.split(`
203
- `);i.push(...t.slice(2))}}if(a.type===`array`&&a.items){let e=a.items;if(e.type===`object`&&e.properties){let t=wy(e,`${n}[]`);if(t){let e=t.split(`
202
+ `)}function wy(e){let t=e.map(e=>({name:e.name,description:e.description,hint:e.hint,args:e.args?ku(e.args):void 0,env:e.env?ku(e.env):void 0,options:e.options?ku(e.options):void 0,output:e.output?ku(e.output):void 0}));return g(`sha256`).update(JSON.stringify(t)).digest(`hex`).slice(0,16)}function Ty(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=Dy(a),s=r.has(e)?`yes`:`no`,c=a.description??``;if(i.push(`| \`${n}\` | \`${o}\` | ${s} | ${c} |`),a.type===`object`&&a.properties){let e=Ty(a,n);if(e){let t=e.split(`
203
+ `);i.push(...t.slice(2))}}if(a.type===`array`&&a.items){let e=a.items;if(e.type===`object`&&e.properties){let t=Ty(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 Ty(e){return e.toLowerCase().replace(/[^a-z0-9-]+/g,`-`).replace(/-{2,}/g,`-`).replace(/^-|-$/g,``)}function Ey(e){if(!e)return`unknown`;let t=e.type;return t?t===`integer`?`number`:t:`unknown`}var Dy=F((()=>{vl(),ku()}));async function Oy(e,t={}){let n=tt(),r=t.command??Ay(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 Iy(s,[...c,`add-mcp`,...a]);o.push(...l.split(`
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`))&&ky(e,r)&&o.push(`Amp`),{command:r,agents:o}}function ky(e,t){let n=d(S(),`.config`,`amp`,`settings.json`),s={};if(r(n))try{s=JSON.parse(a(n,`utf-8`))}catch{return!1}let[c,...l]=Fy(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 Ay(e,t){return My(e)?`${e} --mcp`:`${t} ${Py(e)} --mcp`}function jy(){let e=(process.argv[1]?.replace(/\\/g,`/`))?.match(/^(.+)\/node_modules\/(.+)$/);return e?{root:e[1],entry:e[2]}:null}function My(e){let t=process.argv[1];if(!t)return!1;let n=jy();if(n)return!n.entry.startsWith(`.bin/`)&&!Ny(n.root,e);let r=t.replace(/\\/g,`/`).split(`/`).pop();return r===e||r===`${e}.cmd`||r===`${e}.ps1`}function Ny(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 Py(e){let t=jy();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 Fy(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 Iy(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 Ly=F((()=>{rt()}));function Ry(){return Jy.filter(e=>e.detect())}function zy(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??Ry(),l=[],u=[];for(let n of Vy(e)){let e=c.join(o,n.name);Uy(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(Wy(s)!==Wy(e))try{Uy(s),t.mkdirSync(c.dirname(s),{recursive:!0});let n=Wy(c.dirname(s)),r=Wy(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 By(e,t={}){let n=t.global!==!1,r=t.cwd||process.cwd(),i=n?K:r;Uy(c.join(i,`.agents`,`skills`,e));for(let t of Ry()){if(t.universal)continue;let i=n?t.globalSkillsDir:c.join(r,t.projectSkillsDir);Uy(c.join(i,e))}}function Vy(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:Hy(e?.[1]??a.name),dir:i})}r(i)}}r(e);let i=c.join(e,`SKILL.md`);if(t.existsSync(i)){let r=Hy(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 Hy(e){return e.trim().replace(/[/\\]/g,`-`).replace(/\.\./g,``).slice(0,255)}function Uy(e){try{t.lstatSync(e).isSymbolicLink()?t.unlinkSync(e):t.rmSync(e,{recursive:!0,force:!0})}catch{}}function Wy(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,Gy,Ky,qy,Jy,Yy=F((()=>{K=b.homedir(),Gy=process.env.XDG_CONFIG_HOME||c.join(K,`.config`),Ky=process.env.CLAUDE_CONFIG_DIR?.trim()||c.join(K,`.claude`),qy=process.env.CODEX_HOME?.trim()||c.join(K,`.codex`),Jy=[{name:`Amp`,globalSkillsDir:c.join(Gy,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(Gy,`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(qy,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(qy)},{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(Gy,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.kimi`))},{name:`OpenCode`,globalSkillsDir:c.join(Gy,`opencode`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(Gy,`opencode`))},{name:`Claude Code`,globalSkillsDir:c.join(Ky,`skills`),projectSkillsDir:`.claude/skills`,universal:!1,detect:()=>t.existsSync(Ky)},{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(Gy,`goose`,`skills`),projectSkillsDir:`.goose/skills`,universal:!1,detect:()=>t.existsSync(c.join(Gy,`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(Gy,`crush`,`skills`),projectSkillsDir:`.crush/skills`,universal:!1,detect:()=>t.existsSync(c.join(Gy,`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 Xy(e,t,n={}){let{depth:r=1,description:i,global:a=!0}=n,o=n.cwd??(a?$y():process.cwd());await hl();let s=new Map;i&&s.set(e,i);let c=by(e,ix(t,[],s,n.rootCommand),r,s),u=await w.mkdtemp(l.join(x.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 w.mkdir(l.dirname(n),{recursive:!0}),await w.writeFile(n,`${t.content}\n`);let i=lx(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 w.glob(n,{cwd:o}))try{let n=await w.readFile(l.resolve(o,i),`utf8`),a=lx(n),s=t===`_root`?a.name??e:l.basename(l.dirname(i)),c=l.join(u,s,`SKILL.md`);await w.mkdir(l.dirname(c),{recursive:!0}),await w.writeFile(c,n),r.some(e=>e.name===s)||r.push({name:s,description:a.description,external:!0})}catch{}}let{paths:i,agents:s}=zy(u,{global:a,cwd:o}),d=new Set(i.map(e=>l.basename(e))),f=nb(e);if(f?.skills)for(let e of f.skills)d.has(e)||By(e,{global:a,cwd:o});return tb(e,Cy(ix(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 w.rm(u,{recursive:!0,force:!0})}}async function Zy(e,t,n={}){let{depth:r=1,description:i}=n,a=n.cwd??process.cwd();await hl();let o=new Map;i&&o.set(e,i);let s=by(e,ix(t,[],o,n.rootCommand),r,o),c=[],u=rb(e,{cwd:a});for(let t of s){let n=lx(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 w.glob(n,{cwd:a}))try{let n=lx(await w.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 Qy(e,t={}){return rb(e,t).size>0}function $y(){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 eb(e){let t=process.env.XDG_DATA_HOME||l.join(x.homedir(),`.local`,`share`);return l.join(t,`incur`,`${e}.json`)}function tb(e,t,r,i){let a=eb(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 nb(e){try{return JSON.parse(n.readFileSync(eb(e),`utf-8`))}catch{return}}function rb(e,t={}){let n=nb(e);if(!n?.skills?.length)return new Set;if(n.paths?.length){let e=n.paths.filter(e=>ib(e)).map(e=>l.basename(e));return new Set(e)}let r=t.cwd??process.cwd(),i=[l.join(x.homedir(),`.agents`,`skills`),l.join(r,`.agents`,`skills`)],a=n.skills.filter(e=>i.some(t=>ib(l.join(t,e))));return new Set(a)}function ib(e){return n.existsSync(l.join(e,`SKILL.md`))}function ab(e){return nb(e)?.hash}var ob=F((()=>{Ex(),Yy(),vl(),Dy()}));function sb(e,t){let n=typeof e==`string`?e:e.name,r=typeof e==`string`?t??{}:e,i=r.version??Rt,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:Bb(o),c=o===void 0?void 0:Vb(o),l=new Map,u=[],d=[],f=lb(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 kv(await Dv(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(zb(t))return d.push((async()=>{let n=iy(await ry(t.mcp)),r={_group:!0,description:t.description,commands:n,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0};Kb(e,r,Cx.get(p)),l.set(e,r)})()),p;if(t&&`fetch`in t&&Rb(t.fetch)){let n=Bb(t.fetch);return t.openapi?(d.push((async()=>{let r=await kv(await Dv(t.openapi,{baseUrl:Vb(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};Kb(e,i,Cx.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(Kb(e,t,Cx.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=yx.get(e),r=e,i=gx.get(r),a=Sx.get(r),o=vx.get(r),s=_x.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(()=>{Kb(r.name,c,Cx.get(p))})):Kb(r.name,c,Cx.get(p)),l.set(r.name,c),n){let t=wx.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=Cx.get(p);return fb(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=xu();return d.push((async()=>{let n=t?await Su(t):await Pb(await Nb(e));for(let e of n){if(!Fb(e.command))throw Error(`Expected the default export from '${e.file}' to be created with \`Cli.command()\`.`);Ib(l,e.segments,e.command,e.file,Cx.get(p))}})()),p},async serve(e=process.argv.slice(2),t={}){if(await wt(e))return;d.length>0&&await Promise.all(d);let o=Cx.get(p);return cb(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&&yx.set(p,a),a&&r.aliases&&wx.set(p,r.aliases),r.options&&bx.set(p,r.options),r.config!==void 0&&xx.set(p,!0),r.outputPolicy&&Sx.set(p,r.outputPolicy),r.globals){Cx.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 vx.set(p,u),gx.set(p,l),_x.set(p,d),p}async function cb(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=fx(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=_b(n,{configFlag:l})}catch(e){let t=e instanceof Error?e.message:String(e);d(s?qb({code:`UNKNOWN`,message:t}):yl({code:`UNKNOWN`,message:t},`toon`)),a(1);return}let{fullOutput:m,format:h,formatExplicit:g,filterOutput:_,tokenLimit:v,tokenOffset:y,tokenCount:b,llms:x,llmsFull:S,mcp:C,help:w,update:T,updateCheck:ee,version:E,schema:D,configPath:O,configDisabled:k,rest:te}=p;s=o&&!g;let ne={...typeof r.update==`object`?r.update:void 0,binary:Lt!==void 0,version:r.version},re={},A=te;function j(e){if(!r.globals)return!0;try{let t=Hl(te,r.globals.schema,r.globals.alias,{validate:e});return e&&(re=t.parsed),A=t.rest,!0}catch(e){let t=e instanceof Error?e.message:String(e);return d(s?qb({code:`UNKNOWN`,message:t}):yl({code:`UNKNOWN`,message:t},`toon`)),a(1),!1}}if(!j(!1))return;if(h===`yaml`&&await hl(),ee){if(r.update!==!1)try{await at(e,ne)}catch{}return}if(T&&!w){try{let t=await ot(e,ne);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(yl(t,h))}catch(e){let t={code:`UPDATE_FAILED`,message:e instanceof Error?e.message:String(e)};d(s?qb(t):yl(t,h)),a(1)}return}if(C){await I_(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 ie=process.env.COMPLETE;if(ie){let a=n.indexOf(`--`),o=a===-1?n:n.slice(a+1);if(o.length===0)i([e,...r.aliases??[]].map(e=>cn(ie,e)).join(`
211
- `));else{let e=Number(process.env._COMPLETE_INDEX??o.length-1),n=ln(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 eu)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=Xl(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=un(ie,n);c&&i(c)}return}let ae;if(!x&&!S&&!D&&!w&&!T&&!ee&&!E){let n=wb(A,e,`skills`)!==-1,i=wb(A,e,`mcp`)!==-1;if(!n&&!i){let n=ab(e);n&&Qy(e,{cwd:r.sync?.cwd})&&Cy(ix(t,[],new Map,r.rootCommand))!==n&&(ae={description:`Skills are out of date:`,commands:[{command:process.env.npm_config_user_agent||process.env.npm_execpath?`${tt()} ${Py(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 A){let t=n.get(e);if(!t)break;let r=Gb(n,t);if(Hb(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=ix(n,s,t,o);d(yy(i.length>0?`${e} ${i.join(` `)}`:e,r,t));return}d(yl(tx(n,i,r.globals?.schema,o),h));return}if(!g||h===`md`){let t=ix(n,s,new Map,o);d(_y(i.length>0?`${e} ${i.join(` `)}`:e,t,a));return}d(yl($b(n,i,r.globals?.schema,o),h));return}let oe=wb(A,e,`completions`);if(oe!==-1){let t=A[oe+1];if(w||!t){let t=Xl(`completions`);d(ru(`${e} completions`,{args:t.args,description:t.description,hideGlobalOptions:!0,hint:t.hint?.(e)}));return}if(!$l.includes(t)){d(qb({code:`INVALID_SHELL`,message:`Unknown shell '${t}'. Supported: ${$l.join(`, `)}`})),a(1);return}d([e,...r.aliases??[]].map(e=>cn(t,e)).join(`
212
- `));return}let se=wb(A,e,`skills`);if(se!==-1){let o=Xl(`skills`),c=A[se+1],l=c?Zl(o,c):void 0;if(c&&!l){let t=on(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(qb({code:`COMMAND_NOT_FOUND`,message:r})),d(Jb(l))):d(yl({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(Tb(e,o));return}if(l?.name===`list`){if(w){d(Eb(e,o,`list`));return}try{let n=await Zy(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(yl({code:`LIST_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(w){d(Eb(e,o,`add`));return}let u=A.slice(se+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 Xy(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(yl(e,g?h:`toon`))}}catch(e){d(yl({code:`SYNC_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}let ce=wb(A,e,`mcp`);if(ce!==-1){let o=Xl(`mcp`),c=A[ce+1],l=c?Zl(o,c):void 0;if(c&&!l){let t=on(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(qb({code:`COMMAND_NOT_FOUND`,message:r})),d(Jb(l))):d(yl({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(Tb(e,o));return}if(w){d(Eb(e,o,l.name));return}if(l.name===`doctor`){let n=await Db(e,t,r);d(yl(n,g?h:`toon`)),n.ok||a(1);return}let u=A.slice(ce+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 Oy(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(yl({name:t,command:n.command,agents:n.agents},g?h:`toon`))}catch(e){d(yl({code:`MCP_ADD_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(E&&!w&&r.version){d(r.version);return}if(A.length===0){if(r.rootCommand&&s&&r.rootCommand.args&&Xb(r.rootCommand.args)){let n=r.rootCommand;await f(),d(ru(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:cx(n.examples),usage:n.usage,commands:t.size>0?Cb(t):void 0,root:!0}));return}if(!(r.rootCommand||r.rootFetch)){await f(),d(nu(e,{aliases:r.aliases,configFlag:l,description:r.description,globals:r.globals,version:r.version,commands:Cb(t),root:!0}));return}}let M=A.length===0&&r.rootCommand?{command:r.rootCommand,path:e,rest:[]}:A.length===0&&r.rootFetch?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:[]}:gb(t,A);if(w&&`fetchGateway`in M){let n=M.path===e?e:`${e} ${M.path}`;M.path===e&&t.size>0?d(nu(e,{aliases:r.aliases,configFlag:l,description:r.description,version:r.version,commands:Cb(t),root:!0})):d(Mb(n,M.fetchGateway.description));return}if(w){if(`help`in M||`error`in M){let n=`help`in M?`${e} ${M.path}`:e,i=`help`in M?M.description:r.description,a=`help`in M?M.commands:t,o=n===e;if(o&&r.rootCommand&&a.size>0){let t=r.rootCommand;d(ru(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:cx(t.examples),usage:t.usage,commands:Cb(a),root:!0}))}else d(nu(n,{aliases:o?r.aliases:void 0,configFlag:l,description:i,globals:r.globals,version:o?r.version:void 0,commands:Cb(a),root:o}))}else if(`command`in M){let n=M.command,i=M.path===e,a=i?e:`${e} ${M.path}`,o=`commands`in M&&M.commands&&M.commands.size>0?Cb(M.commands):i&&r.rootCommand&&t.size>0?Cb(t):void 0;d(ru(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:cx(n.examples),usage:n.usage,commands:o,root:i}))}return}if(D){if(`help`in M){d(nu(`${e} ${M.path}`,{configFlag:l,description:M.description,globals:r.globals,commands:Cb(M.commands)}));return}if(`error`in M){let t=M.path?`${e} ${M.path}`:e,n=on(M.error,M.commands.keys()),r=n?` Did you mean '${n}'?`:``;d(`Error: '${M.error}' is not a command for '${t}'.${r}`),a(1);return}if(`fetchGateway`in M){d(`--schema is not supported for fetch commands.`),a(1);return}let t=M.command,n=g?h:`toon`,i={};t.args&&(i.args=Ou(t.args)),t.env&&(i.env=Ou(t.env)),t.options&&(i.options=Ou(t.options)),t.output&&(i.output=Ou(t.output)),r.globals?.schema&&(i.globals=Ou(r.globals.schema)),d(yl(i,n));return}if(`help`in M){d(nu(`${e} ${M.path}`,{configFlag:l,description:M.description,globals:r.globals,commands:Cb(M.commands)}));return}let le;if(s&&r.update!==!1){let t=it(e,ne);t&&(le={description:`Update available for ${t.name}:`,commands:[{command:`${u} --update`,description:`upgrade from ${t.current} to ${t.latest}`}]})}let ue=Yb(ae,le),de=performance.now(),fe=`command`in M&&M.command.format,pe=g?h:fe||r.format||`toon`;pe===`yaml`&&await hl();let N=`error`in M&&!M.path&&(()=>{let e=[...M.commands.keys()];for(let t of eu)e.push(t.name);return on(M.error,e)!==void 0})(),me=`error`in M&&r.rootFetch&&!M.path&&!N?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:A}:`error`in M&&r.rootCommand&&!M.path&&!N?{command:r.rootCommand,path:e,rest:A}:M,he=`outputPolicy`in M&&M.outputPolicy||r.outputPolicy,ge=!(s&&!g&&he===`agent-only`),_e=_?Fn(_):void 0;function ve(e){if(v==null&&y==null)return{text:e,truncated:!1};let t=Kt(e),n=y??0,r=v==null?t:n+v;if(n===0&&r>=t)return{text:e,truncated:!1};let i=qt(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 ye(e){if(_e&&e.ok&&e.data!=null&&(e={...e,data:In(e.data,_e)}),ue){let t=e.meta.cta;e={...e,meta:{...e.meta,cta:t?{description:t.description,commands:[...t.commands,...ue.commands]}:ue}}}if(b){let t=e.ok?e.data:e.error,n=t==null?``:yl(t,pe);return d(String(Kt(n)))}let t=e.meta.cta;if(s&&!m){e.ok&&e.data!=null&&ge?d(ve(yl(e.data,pe)).text):e.ok||d(qb(e.error)),t&&d(Jb(t));return}if(m){if(v!=null||y!=null){let t=ve(e.ok&&e.data!=null?yl(e.data,pe):e.ok?``:yl(e.error,pe));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(yl(n,pe))}}return d(yl(e,pe))}let n=e.ok?e.data:e.error,r=yl(n,pe);if(!t){r&&d(ve(r).text);return}d(ve(yl(typeof n==`object`&&n?{...n,cta:t}:{data:n,cta:t},pe)).text)}if(`error`in me){let t=me.path?`${e} ${me.path} --help`:`${e} --help`,r=me.path?`${e} ${me.path}`:e,i=`commands`in me?[...me.commands.keys()]:[];if(!me.path)for(let e of eu)i.push(e.name);let o=on(me.error,i),c=o?` Did you mean '${o}'?`:``,l=`'${me.error}' is not a command for '${r}'.${c}`,u=[];if(o){let t=n.map(e=>e===me.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(qb({code:`COMMAND_NOT_FOUND`,message:l})),d(Jb(ue?{...f,commands:[...f.commands,...ue.commands]}:f)),a(1);return}ye({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:l},meta:{command:me.error,cta:f,duration:`${Math.round(performance.now()-de)}ms`}}),a(1);return}if(`fetchGateway`in me){if(!j(!0))return;let{fetchGateway:t,path:n,rest:i}=me,o=[...r.middlewares??[],...me.middlewares??[]],c=async()=>{let r=Dn(i);t.basePath&&(r.path=t.basePath+r.path);let o=On(r),c=await t.fetch(o);if(kn(c)){await Qb(An(c),{name:e,path:n,start:de,format:pe,formatExplicit:g,human:s,renderOutput:ge,fullOutput:m,truncate:ve,write:ye,writeln:d,exit:a});return}let l=await jn(c);l.ok?ye({ok:!0,data:l.data,meta:{command:n,duration:`${Math.round(performance.now()-de)}ms`}}):(ye({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()-de)}ms`}}),a(1))};try{let t=r.envSchema?zl(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=>({[Tx]:`error`,...e}),format:pe,formatExplicit:g,globals:re,name:e,set(e,t){i[e]=t},var:i,version:r.version},d=e=>{if(!Zb(e)||e[Tx]!==`error`)return;let t=e,r=gu(u,t.cta);ye({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()-de)}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){ye({ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:n,duration:`${Math.round(performance.now()-de)}ms`}}),a(e instanceof I?e.exitCode??1:1)}return}let{command:be,path:xe,rest:P}=me;if(!j(!0))return;let Se=[...r.middlewares??[],...`middlewares`in M?M.middlewares??[]:[],...be.middleware??[]];s&&dx(P,be.options,be.alias);let Ce;if(c)try{Ce=await vb(e,xe,{configDisabled:k,configPath:O,files:r.config?.files,loader:r.config?.loader})}catch(e){ye({ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:xe,duration:`${Math.round(performance.now()-de)}ms`}}),a(e instanceof I?e.exitCode??1:1);return}let we=await Gl(be,{agent:!s,argv:P,defaults:Ce,displayName:u,env:r.envSchema,envSource:r.env,format:pe,formatExplicit:g,globals:re,inputOptions:{},middlewares:Se,name:e,path:xe,vars:r.vars,version:r.version}),Te=`${Math.round(performance.now()-de)}ms`;if(`stream`in we){await Qb(we.stream,{name:u,path:xe,start:de,format:pe,formatExplicit:g,human:s,renderOutput:ge,fullOutput:m,truncate:ve,write:ye,writeln:d,exit:a});return}if(we.ok){let e=gu(u,we.cta);ye({ok:!0,data:we.data,meta:{command:xe,duration:Te,...e?{cta:e}:void 0}})}else{let e=gu(u,we.cta);if(s&&!g&&we.error.fieldErrors){d(mb(u,xe,be,new wn({message:we.error.message,fieldErrors:we.error.fieldErrors}),r.env,l)),a(1);return}ye({ok:!1,error:{code:we.error.code,message:we.error.message,...we.error.retryable===void 0?void 0:{retryable:we.error.retryable},...we.error.fieldErrors?{fieldErrors:we.error.fieldErrors}:void 0},meta:{command:xe,duration:Te,...e?{cta:e}:void 0}}),a(we.exitCode??1)}}function lb(e,t,n={}){let r;async function i(r,i,a){let{fromJsonSchema:o,McpServer:s,WebStandardStreamableHTTPServerTransport:c}=await Promise.resolve().then(()=>(F_(),o_)),l=new s({name:e,...n.title?{title:n.title}:void 0,version:t},n.instructions?{instructions:n.instructions}:void 0);B_(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 ub(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 db(e,t,n){let r={name:e,description:n.description};return gx.set(r,t),n.rootCommand&&yx.set(r,n.rootCommand),fv(r,{title:e,...n.version?{version:n.version}:void 0,...n.description?{description:n.description}:void 0})}async function fb(e,t,n,r={}){let i=performance.now(),a=new URL(n.url),o=a.pathname.split(`/`).filter(Boolean);if(n.method===`GET`&&ub(o)){let n=db(e,t,r),i=o[0]===`openapi.yml`||o[0]===`openapi.yaml`;return new Response(i?(await hl()).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 hl();let n=new Map,i=ix(t,[],n,r.rootCommand);if(o[2]===`index.json`&&o.length===3){let t=by(e,i,1,n).map(t=>{let n=t.content.match(/^---\n([\s\S]*?)\n---/),r=n?gl().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=by(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(Lr(e),{status:t,headers:{"content-type":`application/json`}})}if(o.length===0)return r.rootCommand?pb(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=gb(t,o);if(`error`in l){let t=l.path?`${e} ${l.path}`:e,n=on(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 pb(d,u,f,s,n,i,{...r,groupMiddlewares:p})}async function pb(e,t,n,r,i,a,o){function s(e,t){return new Response(Lr(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 Gl(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(gu(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(Zb(s)&&s[Tx]===`error`){a.enqueue(n.encode(Lr(i(s))+`
216
- `)),a.close();return}let t=Zb(s)&&s[Tx]===`ok`?gu(o.name??e,s.cta):void 0;a.enqueue(n.encode(Lr({type:`done`,ok:!0,meta:r(t)})+`
217
- `)),a.close();return}if(Zb(s)&&s[Tx]===`error`){a.enqueue(n.encode(Lr(i(s))+`
218
- `)),await t.return(void 0),a.close();return}a.enqueue(n.encode(Lr({type:`chunk`,data:s})+`
219
- `))}catch(e){a.enqueue(n.encode(Lr({type:`error`,ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof I?{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=gu(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=gu(o.name??e,d.cta);return s({ok:!0,data:d.data,meta:{command:e,duration:f,...p?{cta:p}:void 0}},200)}function mb(e,t,n,r,i,a){let o=[];for(let e of r.fieldErrors){let t=(()=>{let t=hb(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(ru(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:cx(n.examples),usage:n.usage})),o.join(`
221
- `)}function hb(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:`--${rn(n)}${e}`}}return e.env?.shape[n]?{kind:`environment variable`,label:`${n}${r.length>0?`.${r.join(`.`)}`:``}`}:{kind:`argument`,label:`<${t}>`}}function gb(e,t){let[n,...r]=t;if(!n||!e.has(n))return{error:n??`(none)`,path:``,commands:e,rest:r};let i=Gb(e,e.get(n)),a=[n],o=r,s,c=[];if(Ub(i)){let e=i.outputPolicy??s;return{fetchGateway:i,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}for(;Hb(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&&!on(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=Gb(i.commands,t);if(a.push(e),o=o.slice(1),i=n,Ub(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 _b(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(!hx.has(e[t+1]))throw new Tn({message:`Invalid format: "${e[t+1]}". Expected one of: ${[...hx].join(`, `)}`});d=e[t+1],f=!0,t++}else if(b&&C===b){let n=e[t+1];if(n===void 0)throw new Tn({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 Tn({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 Tn({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 Tn({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 vb(e,t,n={}){if(n.configDisabled)return;let{loader:r}=n,i;i=n.configPath?yb(n.configPath):await bb(n.files??[`${e}.json`]);let a;if(r){let e=await r(i);if(e===void 0)return;if(!nn(e))throw new Tn({message:`Config loader must return a plain object or undefined`});a=e}else{if(!i)return;let e=await xb(i,!!n.configPath);if(!e)return;a=e}return Sb(a,e,t)}function yb(e){return e.startsWith(`~/`)||e===`~`?c.join(b.homedir(),e.slice(1)):c.resolve(process.cwd(),e)}async function bb(e){for(let t of e){let e=yb(t);try{return await C.access(e,C.constants.R_OK),e}catch{}}}async function xb(e,t){let n;try{n=await C.readFile(e,`utf8`)}catch(n){if(n.code===`ENOENT`){if(t)throw new Tn({message:`Config file not found: ${e}`});return}throw n}let r;try{r=JSON.parse(n)}catch(t){throw new Tn({message:`Invalid JSON config file: ${e}`,cause:t instanceof Error?t:void 0})}if(!nn(r))throw new Tn({message:`Invalid config file: expected a top-level object in ${e}`});return r}function Sb(e,t,n){let r=n===t?[]:n.split(` `),i=e;for(let e of r){if(!nn(i))return;let t=i.commands;if(!nn(t)||(i=t[e],i===void 0))return}if(!nn(i))throw new Tn({message:`Invalid config section for '${n}': expected an object`});let a=i.options;if(a!==void 0){if(!nn(a))throw new Tn({message:`Invalid config 'options' for '${n}': expected an object`});return Object.keys(a).length>0?a:void 0}}function Cb(e){let t=[];for(let[n,r]of e)Wb(r)||t.push({name:n,description:r.description});return t.sort((e,t)=>e.name.localeCompare(t.name))}function wb(e,t,n){return Xl(e[0])?.name===n?0:e[0]===t&&Xl(e[1])?.name===n?1:-1}function Tb(e,t){return nu(`${e} ${t.name}`,{aliases:t.aliases,description:t.description,commands:t.subcommands?.map(e=>({name:e.name,description:e.description}))})}function Eb(e,t,n){let r=Zl(t,n);return ru(`${e} ${t.name} ${n}`,{alias:r?.alias,aliases:r?.aliases,description:r?.description,hideGlobalOptions:!0,options:r?.options})}async function Db(e,t,n){let r=[],i=[],a=new T,o=new T,s=[];o.on(`data`,e=>s.push(e.toString()));let c,l=I_(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(`${Lr({jsonrpc:`2.0`,id:1,method:`initialize`,params:{protocolVersion:`2024-11-05`,capabilities:{},clientInfo:{name:`incur-doctor`,version:`1.0.0`}}})}\n`),a.write(`${Lr({jsonrpc:`2.0`,id:2,method:`tools/list`,params:{}})}\n`),await Ob(s,()=>u),a.end(),await l,c)return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_SERVER_FAILED`,message:Ab(c)}]};let d;try{d=kb(s)}catch(e){return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_RESPONSE_PARSE_FAILED`,message:Ab(e)}]}}let f=d.find(e=>e.id===1);f?f.error&&i.push({code:`MCP_INITIALIZE_FAILED`,message:jb(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:jb(p.error)}):!nn(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(nn).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 Ob(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 kb(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(!nn(r))throw Error(`Expected JSON-RPC response object.`);t.push(r)}return t}function Ab(e){return e instanceof Error?e.message:String(e)}function jb(e){return nn(e)&&typeof e.message==`string`?e.message:Lr(e)}function Mb(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 Nb(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 C.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 Pb(e){let t=await bu(e.directory,{exclude:e.exclude});return Promise.all(t.map(async e=>({...e,command:(await import(E(e.file).href)).default})))}function Fb(e){return typeof e==`object`&&!!e&&e[mx]===!0}function Ib(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(Hb(c)&&!c.root)c.root=n,c.description??=n.description;else throw Lb(t,r);Kb(t.join(` `),n,i);for(let e of n.aliases??[]){if(a.has(e))throw Lb([...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(Wb(c)||Ub(c))throw Lb(t,r);if(Hb(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 Lb(e,t){return Error(`Filesystem command '${e.join(` `)}' from '${t}' conflicts with an existing command or alias.`)}function Rb(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 zb(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 Bb(e){return typeof e==`function`?e:e.fetch}function Vb(e){return typeof e==`function`?void 0:e.url}function Hb(e){return`_group`in e}function Ub(e){return`_fetch`in e}function Wb(e){return`_alias`in e}function Gb(e,t){return Wb(t)?e.get(t.target):t}function Kb(e,t,n){if(!(!n||Ub(t)||Wb(t))){if(Hb(t)){t.root&&Kb(e,t.root,n);for(let[r,i]of t.commands)Kb(`${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 qb(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 Jb(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 Yb(...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 Xb(e){return Object.values(e.shape).some(e=>e._zod.optout!==`optional`)}function Zb(e){return typeof e==`object`&&!!e&&Tx in e}async function Qb(e,t){let n=t.format===`jsonl`;if(n||!t.formatExplicit&&t.format===`toon`)try{let r;for(;;){let{value:i,done:a}=await e.next();if(a){r=i;break}if(Zb(i)){let e=i;if(e[Tx]===`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(qb({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}}n?t.writeln(Lr({type:`chunk`,data:i})):t.renderOutput&&t.writeln(t.truncate(yl(i,t.format)).text)}if(Zb(r)&&r[Tx]===`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(qb({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}let i=Zb(r)&&r[Tx]===`ok`?gu(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(Jb(i))}catch(e){n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof I?{retryable:e.retryable}:void 0}})):t.writeln(qb({code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)})),t.exit(e instanceof I?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(Zb(i)){let e=i;if(e[Tx]===`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(Zb(r)&&r[Tx]===`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=Zb(r)&&r[Tx]===`ok`?gu(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 I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof I?{retryable:e.retryable}:void 0},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e instanceof I?e.exitCode??1:1)}}}function $b(e,t=[],n,r){let i=ex(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:Ou(n)}:void 0}}function ex(e,t){let n=[];for(let[r,i]of e){if(Wb(i))continue;let e=[...t,r];if(Hb(i)){if(i.root){let t={name:e.join(` `)};i.root.description&&(t.description=i.root.description),n.push(t)}n.push(...ex(i.commands,e))}else{let t={name:e.join(` `)};Ub(i),i.description&&(t.description=i.description),n.push(t)}}return n}function tx(e,t=[],n,r){let i=nx(e,t);return r&&t.length>0&&i.push(rx(t,r)),{version:`incur.v1`,commands:i.sort((e,t)=>e.name.localeCompare(t.name)),...n?{globals:Ou(n)}:void 0}}function nx(e,t){let n=[];for(let[r,i]of e){if(Wb(i))continue;let e=[...t,r];if(Ub(i)){let t={name:e.join(` `)};i.description&&(t.description=i.description),n.push(t)}else Hb(i)?(i.root&&n.push(rx(e,i.root)),n.push(...nx(i.commands,e))):n.push(rx(e,i))}return n}function rx(e,t){let n={name:e.join(` `)};t.description&&(n.description=t.description);let r=ux(t.args,t.env,t.options),i=t.output?Ou(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=cx(t.examples);if(a){let t=e.join(` `);n.examples=a.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function ix(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),ox(r)&&(e.hint=sx(e.hint)),r.options&&(e.options=r.options),r.output&&(e.output=r.output);let t=cx(r.examples);t&&(e.examples=t),i.push(e)}for(let[r,a]of e){if(Wb(a))continue;let e=[...t,r];if(Ub(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 Hb(a)?(a.description&&n.set(e.join(` `),a.description),a.root&&i.push(ax(e,a.root)),i.push(...ix(a.commands,e,n))):i.push(ax(e,a))}return i.sort((e,t)=>(e.name??``).localeCompare(t.name??``))}function ax(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),ox(t)&&(n.hint=sx(n.hint)),t.options&&(n.options=t.options),t.output&&(n.output=t.output);let r=cx(t.examples);if(r){let t=e.join(` `);n.examples=r.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function ox(e){return e.destructive===!0||e.mcp!==!1&&e.mcp?.annotations?.destructiveHint===!0}function sx(e){return e?e.includes(px)?e:`${e} ${px}`:px}function cx(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 lx(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return{};let n=gl().parse(t[1]);return!n||typeof n!=`object`?{}:n}function ux(e,t,n){if(!e&&!t&&!n)return;let r={};return e&&(r.args=Ou(e)),t&&(r.env=Ou(t)),n&&(r.options=Ou(n)),r}function dx(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 fx(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 px,mx,hx,gx,_x,vx,yx,bx,xx,Sx,Cx,wx,Tx,Ex=F((()=>{tn(),zt(),xn(),En(),Pn(),Rn(),Dl(),hu(),tu(),yu(),Du(),sn(),zr(),rt(),Ct(),vl(),sv(),gy(),ny(),Wl(),ku(),Dy(),Ly(),ob(),px=`Confirm with the user before executing this destructive command.`,mx=Symbol.for(`incur.fileCommand`),hx=new Set([`toon`,`json`,`yaml`,`md`,`jsonl`]),gx=new WeakMap,_x=new WeakMap,vx=new WeakMap,yx=new WeakMap,bx=new WeakMap,xx=new WeakMap,Sx=new WeakMap,Cx=new WeakMap,wx=new WeakMap,Tx=Symbol.for(`incur.sentinel`)})),Dx=F((()=>{zt(),Ex(),xn(),En(),Dl(),hu(),sv(),Pn(),ny(),Wl(),ku(),Dy(),vl(),Ly(),ob()}));function Ox(e,t){if(!(!e||typeof e!=`object`))return e[t]}var q,kx,Ax,jx,Mx,Nx,Px=F((()=>{q={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},kx={payment:`Payment`},Ax={evm:`evm`,stripe:`stripe`,tempo:`tempo`},jx={charge:`charge`,session:`session`,subscription:`subscription`},Mx={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},Nx={v1:`v1`,v2:`v2`}}));function Fx(e){let t=k.toString(e);return JSON.parse(t)}function Ix(e,t){return e.schema.request.parse(t)}function Lx(e){let t=A.canonicalize(e);return k.fromString(t,{pad:!1,url:!0})}var Rx=F((()=>{})),J=Ze({address:()=>Gx,amount:()=>Bx,datetime:()=>Vx,datetimeInput:()=>Hx,hash:()=>Kx,period:()=>qx,signature:()=>Jx,toDate:()=>Ux,toDatetimeString:()=>Wx,unwrapOptional:()=>Yx});import*as zx from"zod/mini";$e(J,zx);function Bx(){return be.string().check(be.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function Vx(){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 Hx(e=`Invalid ISO 8601 datetime`){return be.pipe(be.union([Vx(),be.custom(e=>e instanceof Date)]),be.transform(Ux)).check(be.refine(e=>Number.isFinite(e.getTime()),e))}function Ux(e){return e instanceof Date?e:new Date(e)}function Wx(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function Gx(){return be.string().check(be.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function Kx(){return be.string().check(be.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function qx(){return be.string().check(be.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function Jx(){return be.string().check(be.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function Yx(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}var Xx=F((()=>{}));function Zx(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=fS(o)?void 0:o,f=e.expires?Wx(e.expires):void 0,p=e.opaque??(i===void 0?void 0:Lx(i)),m=u?pS({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return hS.parse({id:m,realm:c,method:a,intent:s,request:l,...n&&{description:n},...r&&{digest:r},...f&&{expires:f},...d!==void 0&&{header:d},...i!==void 0&&{meta:i},...p!==void 0&&{opaque:p}})}function Qx(e){let t=[$x(`id`,e.id),$x(`realm`,e.realm),$x(`method`,e.method),$x(`intent`,e.intent),$x(`request`,Lx(e.request))];e.description!==void 0&&t.push($x(`description`,e.description)),e.digest!==void 0&&t.push($x(`digest`,e.digest)),e.expires!==void 0&&t.push($x(`expires`,e.expires));let n=e.header;return n!==void 0&&!fS(n)&&t.push($x(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push($x(`opaque`,Lx(e.meta))):t.push($x(`opaque`,e.opaque)),`${kx.payment} ${t.join(`, `)}`}function $x(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function eS(e,t){let n=tS(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=nS(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>mS)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return Zx({...a,request:Fx(r),...i&&{opaque:i}},t)}function tS(e){let t=kx.payment,[n]=oS(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 nS(e){let t=Object.create(null),n=0;for(;n<e.length;){for(;n<e.length&&/[\s,]/.test(e[n]??``);)n++;if(n>=e.length)break;let r=n;for(;n<e.length&&/[A-Za-z0-9_-]/.test(e[n]??``);)n++;let i=e.slice(r,n).toLowerCase();if(!i)throw Error(`Malformed auth-param.`);for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]!==`=`)break;for(n++;n<e.length&&/\s/.test(e[n]??``);)n++;let[a,o]=rS(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function rS(e,t){if(e[t]===`"`)return iS(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function iS(e,t){let n=t,r=!1,i=t,a;for(;n<e.length;){let o=e[n];if(n++,r){a??=[];let t=o===`u`?e.slice(n,n+4):void 0;t&&/^[0-9A-Fa-f]{4}$/.test(t)?(a.push(String.fromCharCode(Number.parseInt(t,16))),n+=4):a.push(o),i=n,r=!1;continue}if(o===`\\`){a??=[],a.push(e.slice(i,n-1)),i=n,r=!0;continue}if(o===`"`)return[a?[...a,e.slice(i,n-1)].join(``):e.slice(t,n-1),n]}throw Error(`Unterminated quoted-string.`)}function aS(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 oS(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(!aS(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 sS(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return cS(e.headers,t)}function cS(e,t){let n=e.get(q.wwwAuthenticate);if(!n)throw Error(`Missing ${q.wwwAuthenticate} header.`);return lS(n,t)}function lS(e,t){let n=oS(e,kx.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return eS(e.slice(r,a).replace(/,\s*$/,``),t)})}function uS(e){let t=[e.realm,e.method,e.intent,Lx(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!fS(n)&&t.push(n),t.push(e.opaque??(e.meta?Lx(e.meta):``)),t.join(`|`)}function dS(e){return e.header??q.authorization}function fS(e){return e?.toLowerCase()===q.authorization.toLowerCase()}function pS(e,t){let n=uS(e),r=te.fromString(t.secretKey),i=te.fromString(n),a=ne.hmac256(r,i,{as:`Bytes`});return k.fromBytes(a,{url:!0,pad:!1})}var mS,hS,gS=F((()=>{Px(),Rx(),Xx(),mS=16384,hS=J.object({description:J.optional(J.string()),digest:J.optional(J.string().check(J.regex(/^sha-256=/,`Invalid digest format`))),expires:J.optional(Vx()),header:J.optional(J.string().check(J.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:J.string().check(J.minLength(1)),intent:J.string(),method:J.string(),meta:J.optional(J.record(J.string(),J.string())),opaque:J.optional(J.string()),realm:J.string(),request:J.record(J.string(),J.unknown())})})),_S,vS,Y,yS,bS=F((()=>{_S=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...e&&{challengeId:e}}}},vS=class extends _S{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}.`)}},Y=class extends _S{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,reason:n}=e;super(n?`Payment verification failed: ${n}.`:`Payment verification failed.`,{details:t})}},yS=class extends _S{name=`PaymentExpiredError`;title=`Payment Expired`;type=`https://paymentauth.org/problems/payment-expired`;constructor(e={}){let{expires:t}=e;super(t?`Payment expired at ${t}.`:`Payment has expired.`)}}}));function xS(e,t){if(!e)throw new vS({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new vS({...t&&{id:t},reason:`malformed expires timestamp`});if(new Date(e)<new Date)throw new yS({expires:e})}var SS=F((()=>{bS()}));function CS(e){return Object.defineProperty(e,TS,{value:!0}),e}function wS(e){return!!e?.[TS]}var TS,ES=F((()=>{TS=Symbol.for(`mppx.x402.challenge`)}));function DS(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=NS(n)}return t}function OS(e,t){let n=DS(e),r=BS(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[NS(e)]??1,index:t}));return{definition:r,entries:i,header:AS(i),keys:n}}function kS(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)=>RS(e,t))}function AS(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${WS(n)}`}).join(`, `)}function jS(e,t,n){let r=MS(e,t,n)[0];if(r)return{challenge:r.challenge,method:r.method}}function MS(e,t,n){let r=new Map;for(let e of t){let t=NS(e),n=r.get(t);n?n.push(e):r.set(t,[e])}return e.flatMap((e,t)=>{let i=r.get(NS(e));if(!i)return[];let a=PS(e,n);return!a||a.q<=0?[]:i.filter(t=>t.canHandleChallenge?.({challenge:e})??!0).map(n=>({challenge:e,index:t,match:a,method:n}))}).sort((e,t)=>LS(e.challenge)-LS(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function NS(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function PS(e,t){let n;for(let r of t){if(!FS(e,r))continue;let t={...r,specificity:IS(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 FS(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function IS(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function LS(e){return+!!wS(e)}function RS(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}`);GS(r,`method`),GS(i,`intent`);let a=1;for(let t of zS(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=HS(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function zS(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function BS(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>NS(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]=VS(t,`payment preference "${e}"`)}return a}function VS(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return US(e,t)}function HS(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 US(Number(e),t)}function US(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 WS(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function GS(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}var KS=F((()=>{ES()}));function qS(e){let t=e.match(RegExp(`^${kx.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new QS;try{let e=k.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=JS(r);return{challenge:hS.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Fx(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new $S}}function JS(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!YS(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:Lx(e)}}function YS(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function XS(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function ZS(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:Lx(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:Lx(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=k.fromString(s,{pad:!1,url:!0});return`${kx.payment} ${c}`}var QS,$S,eC=F((()=>{gS(),Px(),Rx(),QS=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},$S=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}}})),tC,nC,rC=F((()=>{tC=`org.paymentauth/credential`,nC=`org.paymentauth/payment-required`}));function iC(e){let{extensions:t,resource:n,...r}=e;return vC.parse(r)}var aC,oC,sC,cC,lC,uC,dC,fC,pC,mC,hC,gC,_C,vC,yC,bC,xC,SC,CC,wC,TC,EC,DC=F((()=>{Xx(),aC=`charge`,oC=[`exact`],sC=`eip155:`,cC=`x402:`,lC=`PAYMENT-REQUIRED`,uC=`PAYMENT-SIGNATURE`,dC=`PAYMENT-RESPONSE`,fC=J.string().check(J.minLength(1)),pC=J.number().check(J.refine(e=>e>0,`Must be positive`)),mC=J.string().check(J.regex(/^\d+$/,`Invalid atomic amount`)),hC=Gx(),gC=J.string().check(J.regex(RegExp(`^${sC}\\d+$`),`Invalid EVM CAIP-2 network`)),_C=J.object({description:J.optional(J.string()),iconUrl:J.optional(J.string()),mimeType:J.optional(J.string()),serviceName:J.optional(J.string()),tags:J.optional(J.array(J.string())),url:fC}),J.discriminatedUnion(`type`,[J.object({name:fC,type:J.literal(`eip3009`),version:fC}),J.object({name:J.optional(J.string()),type:J.literal(`permit2`),version:J.optional(J.string())})]),vC=J.object({amount:mC,asset:fC,extra:J.optional(J.record(J.string(),J.unknown())),maxTimeoutSeconds:pC,network:gC,payTo:fC,scheme:J.enum(oC)}),yC=J.object({info:J.record(J.string(),J.unknown()),schema:J.record(J.string(),J.unknown())}),bC=J.record(J.string(),yC),xC=J.object({accepts:J.array(vC).check(J.minLength(1)),error:J.optional(J.string()),extensions:J.optional(bC),resource:_C,x402Version:J.literal(2)}),SC=J.object({authorization:J.object({from:hC,nonce:Kx(),to:hC,validAfter:mC,validBefore:mC,value:mC}),signature:Jx()}),CC=J.object({permit2Authorization:J.object({deadline:mC,from:hC,nonce:mC,permitted:J.object({amount:mC,token:hC}),spender:hC,witness:J.object({to:hC,validAfter:mC})}),signature:Jx()}),wC=J.union([SC,CC]),TC=J.object({accepted:vC,extensions:J.optional(bC),payload:wC,resource:J.optional(_C),x402Version:J.literal(2)}),J.object({extensions:J.optional(bC),extra:J.optional(J.record(J.string(),J.unknown())),invalidMessage:J.optional(J.string()),invalidReason:J.optional(J.string()),isValid:J.boolean(),payer:J.optional(J.string())}),EC=J.object({amount:J.optional(mC),errorMessage:J.optional(J.string()),errorReason:J.optional(J.string()),extensions:J.optional(bC),extra:J.optional(J.record(J.string(),J.unknown())),network:fC,payer:J.optional(J.string()),success:J.boolean(),transaction:J.string()})}));function OC(e,t,n){let r=new Headers(e.headers);for(let e of kC)e===q.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}var kC,AC=F((()=>{Px(),DC(),kC=[q.authorization,lC,dC,uC]}));function jC(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 MC(e){let t=jC(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 NC(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 PC(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){let t=hS.safeParse(e);if(!t.success)return;n.push(t.data)}let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function FC(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:PC(e.error.data):PC(e.result?._meta?.[nC])}function IC(e,t){return!e||e.id!==t?[]:FC(e)?.challenges??[]}async function LC(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=!1,i,a=xe({onEvent(e){if(!(r||!e.data)&&(r=!0,!(e.event&&e.event!==`message`)))try{i=NC(JSON.parse(e.data))}catch{}}});try{for(;;){if(r)return i;let{done:e,value:o}=await t.read();if(e)return a.feed(n.decode()),a.reset({consume:!0}),i;a.feed(n.decode(o,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}function RC(e){let t=BC.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(t.includes(`application/json`))return e.clone().json().then(NC).catch(()=>void 0);if(t.includes(`text/event-stream`))return LC(e)})();return BC.set(e,n),n}function zC(){return{getChallenges(e,t){let n=MC(t);return e.status===402||n===void 0?[]:RC(e).then(e=>IC(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=qS(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,[tC]:r}}})}}}}var BC,VC=F((()=>{gS(),eC(),rC(),AC(),BC=new WeakMap}));function HC(){return{getChallenges(e){return e.status!==402||!e.headers.has(q.wwwAuthenticate)?[]:sS(e)},setCredential(e,t,n){return OC(e,n?.challenge?dS(n.challenge):q.authorization,t)}}}var UC=F((()=>{gS(),Px(),AC()}));function WC(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 GC}}}}var GC,KC=F((()=>{GC=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}}}));function qC(e){try{let t=JSON.parse(k.toString(e));return $C(t)}catch{throw new GC}}var JC,YC,XC,ZC,QC,$C,ew=F((()=>{KC(),DC(),JC=WC(xC),YC=WC(TC),XC=WC(EC),ZC=JC.encode,JC.decode,QC=YC.encode,YC.decode,XC.encode,XC.decode,$C=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new GC;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new GC;let n=_C.parse(t.resource),r=t.extensions===void 0?void 0:bC.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}}}));function tw(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(lC);if(!t)return[];let n=qC(t);return n.accepts.flatMap((e,t)=>{let r=vC.safeParse(e);if(!r.success)return[];let i=r.data;return CS(Zx({id:`${cC}${t}`,intent:aC,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return OC(e,uC,t)}}}var nw=F((()=>{gS(),ew(),ES(),DC(),AC()}));function rw(e){return e}function iw(){let e=[HC(),tw(),zC()],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 rw({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 aw=F((()=>{VC(),UC(),AC(),nw()}));function ow(e,t){return lw.set(e,t),e}function sw(e){return lw.has(e)}function cw(e,t){return Promise.resolve(lw.get(e)?.(t))}var lw,uw=F((()=>{lw=new WeakMap}));function dw(e,t){return gw.set(e,t),e}function fw(e){gw.delete(e)}function pw(e,t,n){gw.has(e)&&_w.set(t,n)}function mw(e){return _w.get(e)}function hw(e,t){return Promise.resolve(gw.get(e)?.(t)??t.response)}var gw,_w,vw=F((()=>{gw=new WeakMap,_w=new WeakMap}));async function yw(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 bw(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=rT,methods:a,onChallenge:o,orderChallenges:s,transport:c=iw()}=e,l=e.eventDispatcher??Cw(),u=t??OS(a),d=Ww(r),f=async(e,t,r)=>{let p=Uw(e,t?.headers),m=p.has(q.acceptPayment),h=Yw(p,u),g=Vw(e,t,p),_=Bw(e,t,p,h.header,m,n),v=await d(Gw(_.input),_.init),y=Hw(_.init,await g);if(!await c.isPaymentRequired(v,y))return v;let b=t?.context,{context:x,orderChallenges:S,...C}=y??{},w,T,ee,E;try{for(let n=0;n<i;n++){T=await c.getChallenges(v,y);let i=(await Xw(MS(T,a,h.entries),S??s))[0];if(!i){if(await yw(E,{challenges:T,response:v,status:`rejected`}),n>0)return v;throw Error(`No method found for challenges: ${T.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let u=i.challenge;w=u,ee=i.method,w.expires&&xS(w.expires,w.id);let p=tT(v,_.input,_.input),m=E,g=Qx(u),x=m?.method===i.method&&m?.key===g,D=!1;if(m){let e=await yw(m,{challenges:T,response:v,status:x?`pending`:`rejected`});D=x&&!e}E=D?m:void 0;let O=Ow(async n=>{if(n===void 0&&D&&m)return m.promise;D&&m&&(await yw(m,{status:`rejected`}),E=void 0);let r=n??b;if(!sw(i.method))return Jw(u,i.method,r);let a={prepare:()=>cw(i.method,{challenge:u,context:r,fetch:d,input:p,signal:Kw(e,t)})},o=a.prepare().then(()=>Jw(u,i.method,r,a));return E={attempt:a,key:n===void 0?g:void 0,method:i.method,promise:o},o}),k=await l.emit(`challenge.received`,kw({challenge:u,challenges:T,createCredential:O,init:t,input:e,method:i.method,response:v}))??(o?await o(w,{createCredential:O}):void 0)??await O(),te=E;te&&await te.promise.catch(()=>void 0)!==k&&(await yw(te,{status:`rejected`}),E=void 0),qw(k),await l.emit(`credential.created`,Aw({challenge:u,credential:k,init:t,input:e,method:i.method,response:v})),v=await d(p,{...c.setCredential({...C,headers:_.headers},k,{challenge:u}),redirect:`manual`});let ne=await c.isPaymentRequired(v,y);if(ne||(await yw(te,{response:v,status:v.status>=300&&v.status<400?`pending`:v.ok?`accepted`:`rejected`}),E=void 0),v.ok&&ww(l,`payment.response`)&&await l.emit(`payment.response`,jw({challenge:u,credential:k,init:t,input:e,method:i.method,response:v})),!ne)return v.ok?hw(i.method,{challenge:u,credential:k,fetch:d,headers:_.headers,input:p,...r?{refetch:()=>f(Gw(_.input),t,!1)}:{},response:v,signal:Kw(e,t)}):v}T=void 0;try{T=await c.getChallenges(v,y)}catch{}return await yw(E,{challenges:T,response:v,status:`rejected`}),v}catch(n){throw await yw(E,{challenges:T,response:v,status:`rejected`}),await l.emit(`payment.failed`,Mw({challenge:w,challenges:T,error:n,init:t,input:e,method:ee,response:v})),n}},p=(e,t)=>f(e,t,!0);return p[nT]=d,p}function xw(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);iT||=globalThis.fetch,globalThis.fetch=bw({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??($w()?`same-origin`:`always`),fetch:globalThis.fetch})}function Sw(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 Cw(){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 Tw(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await Dw(e[`*`],t,n),r}case`credential.created`:await Ew(e[`credential.created`],n),await Dw(e[`*`],t,n);return;case`payment.failed`:await Ew(e[`payment.failed`],n),await Dw(e[`*`],t,n);return;case`payment.response`:await Ew(e[`payment.response`],n),await Dw(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 aT.set(t,t=>e[t].size>0||e[`*`].size>0),t}function ww(e,t){return aT.get(e)?.(t)??!0}async function Tw(e,t){try{return await e(t)}catch{return}}async function Ew(e,t){for(let n of e)try{await n(t)}catch{}}async function Dw(e,t,n){await Ew(e,Object.freeze({name:t,payload:n}))}function Ow(e){let t;return n=>(t??=e(n),t)}function kw(e){return Object.freeze({challenge:Lw(e.challenge),challenges:e.challenges.map(e=>Lw(e)),createCredential:e.createCredential,init:Nw(e.init),input:Pw(e.input),method:Fw(e.method),response:Iw(e.response)})}function Aw(e){return Object.freeze({challenge:Lw(e.challenge),credential:e.credential,init:Nw(e.init),input:Pw(e.input),method:Fw(e.method),...e.response===void 0?{}:{response:Iw(e.response)}})}function jw(e){return Object.freeze({challenge:Lw(e.challenge),credential:e.credential,init:Nw(e.init),input:Pw(e.input),method:Fw(e.method),response:Iw(e.response)})}function Mw(e){return Object.freeze({...e.challenge?{challenge:Lw(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>Lw(e))}:{},error:e.error,init:Nw(e.init),input:Pw(e.input),...e.method?{method:Fw(e.method)}:{},...e.response===void 0?{}:{response:Iw(e.response)}})}function Nw(e){if(e)return zw({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function Pw(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function Fw(e){return zw(Object.assign({},e))}function Iw(e){return e instanceof Response?e.clone():Lw(e)}function Lw(e){try{return Rw(structuredClone(e))}catch{return zw(e)}}function Rw(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Rw(t);return e}function zw(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function Bw(e,t,n,r,i,a){let o=!!r&&!i&&Zw(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 Vw(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 Hw(e,t){return t===void 0?e:{...e,body:t}}function Uw(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function Ww(e){let t=e;for(;t[nT];)t=t[nT];return t}function Gw(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Kw(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function qw(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
224
- `))throw Error(`Credential header value contains illegal newline characters`)}async function Jw(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&&pw(t,a,r),t.createCredential(a)}function Yw(e,t){let n=e.get(q.acceptPayment);if(!n)return t;try{return{...t,entries:kS(n),header:n}}catch{return t}}async function Xw(e,t){return t?t(e):e}function Zw(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=eT(e);return t===`same-origin`?!$w()||n.origin===globalThis.location.origin:t.origins.some(e=>Qw(n,e))}function Qw(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e.hostname.endsWith(n)||e.hostname===t.slice(2)}return e.origin===new URL(t).origin}function $w(){return globalThis.location!==void 0}function eT(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,$w()?globalThis.location.href:void 0)}function tT(e,t,n){if(!e.url)return t;let r=new URL(e.url),i=eT(n);if(r.origin!==i.origin)throw Error(`Refusing to send payment credential across redirect from ${i.origin} to ${r.origin}`);return e.url}var nT,rT,iT,aT,oT=F((()=>{gS(),Px(),SS(),KS(),aw(),uw(),vw(),nT=Symbol.for(`mppx.fetch.wrapper`),rT=3,aT=new WeakMap}));Dx(),oT();function sT(){let e=new Uint8Array(64);return crypto.getRandomValues(e),Object.freeze({created:Math.floor(Date.now()/1e3),nonce:k.fromBytes(e,{pad:!1,url:!0})})}function cT(...e){return{protocol:`composed`,async sign(t,n=sT()){for(let r of e)t=await r.sign(t,n);return t}}}function lT(e,t){return async(n,r)=>e(await t.sign(new Request(n,r)))}Px(),SS(),KS(),uw(),aw();const uT=new WeakMap;function dT(e){let{attestation:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=iw()}=e,c=Ww(e.fetch??globalThis.fetch),l=t?fT(t):void 0,u=l?lT(c,l):c,d=e.methods.flat(),f=OS(d,e.paymentPreferences),p=Cw(),m=r,h={acceptPayment:f,acceptPaymentPolicy:o,...(e.fetch||t)&&{fetch:u},eventDispatcher:p,...n!==void 0&&{maxPaymentRetries:n},...m&&{onChallenge:m},...i&&{orderChallenges:i},methods:d,transport:s},g=bw(h);a&&xw(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){let n=ET(e),r=await s.getChallenges(e,t?.request),a=Object.freeze(r.map(e=>DT(e))),o=AT(f.entries,t?.acceptPayment),c,l;try{let e=(await jT(MS(r,d,o),t?.orderChallenges??i))[0];if(!e)throw Error(`No method found for challenges: ${r.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${d.map(e=>`${e.name}.${e.intent}`).join(`, `)}`);let u=e.challenge;c=a[e.index],l=e.method,c.expires&&xS(c.expires,c.id);let f=c,m=l,h=xT(async e=>{try{f.expires&&xS(f.expires,f.id);let t=xT(t=>MT(f,m,t??e)),i=await p.emit(`challenge.received`,ST({challenge:f,challenges:r,createCredential:t,method:m,response:n}))??await t();return qw(i),await p.emit(`credential.created`,CT({challenge:f,credential:i,method:m,response:n})),i}catch(e){throw await p.emit(`payment.failed`,wT({challenge:f,challenges:r,error:e,method:m,response:n})),e}}),g=Object.freeze({challenge:f,challenges:a,createCredential:h,method:TT(m),setCredential(e,t){return qw(t),s.setCredential(e,t,{challenge:u})}});return uT.set(g,m),g}catch(e){throw await p.emit(`payment.failed`,wT({challenge:c,challenges:r,error:e,method:l,response:n})),e}}async function S(e,t,n){let{maxRedirects:r=20,requirePayment:i=!1,...a}=n??{},d=await gT({acceptPayment:f.header,acceptPaymentPolicy:o,fetch:c,init:t,input:e,maxRedirects:r,signer:l}),p=_T(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}),h=uT.get(m)??m.method,g=xT(async e=>(sw(h)&&await cw(h,{challenge:m.challenge,context:e,fetch:u,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(_T(d.replayRequest,d.body),t);return u(d.replayRequest.url,{...n,redirect:`manual`})}});return Object.freeze({payment:_,request:d.request,response:d.response,redirects:d.redirects})}return{fetch:g,rawFetch:c,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)).createCredential(t)}}}function fT(e){let t=Object.values(e);if(t.length===0)throw TypeError(`Mppx client attestation must configure at least one signer.`);return cT(...t)}const pT=new Set([301,302,303,307,308]),mT=[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`,`transfer-encoding`],hT=[`authorization`,`cookie`,`cookie2`,`host`,`payment-authorization`,`payment-signature`,`proxy-authorization`,`x-payment`];async function gT(e){let{acceptPayment:t,acceptPaymentPolicy:n,fetch:r,init:i,input:a,maxRedirects:o,signer:s}=e;if(!Number.isInteger(o)||o<0)throw TypeError(`maxRedirects must be a non-negative integer.`);let c=new Request(a,{...i,redirect:`manual`}),l=c.headers.has(q.acceptPayment),u=await vT(c,i?.body),d=[];for(;;){c=yT(c,t,l,n);let e=s?await s.sign(c.clone()):c.clone(),i=await r(e);if(i.type===`opaqueredirect`||i.status===0)throw Error(`prepareRequest requires a runtime that exposes manual redirect responses.`);if(!pT.has(i.status))return{body:u,replayRequest:c,request:e,response:i,redirects:Object.freeze(d)};let a=i.headers.get(`location`);if(!a)return{body:u,replayRequest:c,request:e,response:i,redirects:Object.freeze(d)};if(d.length>=o)throw await i.body?.cancel(),Error(`Payment request exceeded ${o} redirects.`);let f=new URL(c.url),p=new URL(a,f);if(f.protocol===`https:`&&p.protocol!==`https:`)throw await i.body?.cancel(),Error(`Payment request refused HTTPS downgrade redirect to ${p.href}`);let m=new Headers(c.headers),h=c.method;if((i.status===301||i.status===302)&&h===`POST`||i.status===303&&h!==`GET`&&h!==`HEAD`){h=`GET`,u=void 0;for(let e of mT)m.delete(e)}if(f.origin!==p.origin)for(let e of[...m.keys()]){let t=m.get(e)??``;(hT.includes(e)||t.startsWith(`Payment `))&&m.delete(e)}d.push(Object.freeze({from:f.href,status:i.status,to:p.href})),await i.body?.cancel(),c=new Request(p,bT(c,m,h,u))}}function _T(e,t){return bT(e,new Headers(e.headers),e.method,t)}async function vT(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 yT(e,t,n,r){if(n)return e;let i=new Headers(e.headers);return i.delete(q.acceptPayment),t&&Zw(e,r)&&i.set(q.acceptPayment,t),new Request(e,{headers:i})}function bT(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 xT(e){let t;return n=>(t??=e(n),t)}function ST(e){return Object.freeze({challenge:DT(e.challenge),challenges:e.challenges.map(e=>DT(e)),createCredential:e.createCredential,method:TT(e.method),response:ET(e.response)})}function CT(e){return Object.freeze({challenge:DT(e.challenge),credential:e.credential,method:TT(e.method),response:ET(e.response)})}function wT(e){return Object.freeze({...e.challenge?{challenge:DT(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>DT(e))}:{},error:e.error,...e.method?{method:TT(e.method)}:{},response:ET(e.response)})}function TT(e){return kT(Object.assign({},e))}function ET(e){if(e instanceof Response)try{return e.clone()}catch{return new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText})}return DT(e)}function DT(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 OT(t)}catch{return kT(e)}}function OT(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))OT(t);return e}function kT(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function AT(e,t){return t?typeof t==`string`?kS(t):t:e}async function jT(e,t){return t?t(e):e}async function MT(e,t,n){let r=t.context&&n!==void 0?t.context.parse(n):void 0;return t.createCredential(r===void 0?{challenge:e}:{challenge:e,context:r})}function NT(){return J.string().check(J.regex(PT,`Invalid URI or path`))}var PT,FT,IT,LT,RT,zT,BT,VT,HT,UT=F((()=>{Xx(),PT=/^([a-zA-Z][a-zA-Z\d+.-]*:\/\/\S+|\/\S*)$/,FT=new Set([`amount`,`currency`,`description`,`intent`,`method`]),IT=J.looseObject({amount:J.optional(J.union([J.null(),J.string().check(J.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:J.optional(J.string()),description:J.optional(J.string()),intent:J.optional(J.string()),method:J.optional(J.string())}),LT=J.pipe(J.looseObject({amount:J.optional(J.union([J.null(),J.string().check(J.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:J.optional(J.string()),description:J.optional(J.string()),intent:J.optional(J.string()),method:J.optional(J.string()),offers:J.optional(J.array(IT).check(J.minLength(1)))}).check(J.refine(e=>e.offers===void 0||Object.keys(e).every(e=>e===`offers`||!FT.has(e)),`Cannot mix offers with flat payment info fields`)),J.transform(e=>{if(e.offers)return{offers:e.offers};let t={};for(let[n,r]of Object.entries(e))n!==`offers`&&(FT.has(n)||r!==void 0)&&(t[n]=r);return{offers:[t]}})),RT=J.looseObject({apiReference:J.optional(NT()),homepage:J.optional(NT()),llms:J.optional(NT())}),zT=J.looseObject({categories:J.optional(J.array(J.string())),docs:J.optional(RT)}),BT=J.looseObject({"x-payment-info":J.optional(LT),requestBody:J.optional(J.unknown()),responses:J.optional(J.record(J.string(),J.unknown())),summary:J.optional(J.string())}),VT=J.looseObject({delete:J.optional(BT),get:J.optional(BT),head:J.optional(BT),options:J.optional(BT),patch:J.optional(BT),post:J.optional(BT),put:J.optional(BT),trace:J.optional(BT)}),HT=J.looseObject({openapi:J.string(),info:J.looseObject({title:J.string(),version:J.string()}),"x-service-info":J.optional(zT),paths:J.optional(J.record(J.string(),VT))})}));UT();function WT(e){let t=[],n=HT.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=LT.safeParse(o);if(!s.success){for(let e of s.error.issues){let n=e.path.length>0?`.${e.path.map(String).join(`.`)}`:``;t.push({message:e.message,path:`${a}.x-payment-info${n}`,severity:`error`})}continue}let c=n.responses;(!c||!(`402`in c))&&t.push({message:`Operation with x-payment-info MUST have a 402 response`,path:`${a}.responses`,severity:`error`});let l=r.toUpperCase();!n.requestBody&&(l===`POST`||l===`PUT`||l===`PATCH`)&&t.push({message:`Operation with x-payment-info has no requestBody`,path:a,severity:`warning`})}return t}function GT(e){return e}function KT(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}var qT=F((()=>{}));function JT(e){return J.refine(e=>{let{amount:t,decimals:n}=e;return N(t,n)>0n},e)}function YT(e){let{periodCount:t,periodUnit:n}=e;try{let e=$T[n];return e!==void 0&&BigInt(t)*e<=QT}catch{return!1}}var XT,ZT,QT,$T,eE,tE,nE,rE,iE,aE,oE,sE,cE,lE=F((()=>{Px(),qT(),Xx(),XT=[`push`,`pull`],ZT=J.object({amount:Bx(),memo:J.optional(Kx()),recipient:J.pipe(J.string(),J.transform(e=>e))}),QT=(1n<<64n)-1n,$T={dev_second:1n,day:86400n,week:604800n},eE=J.pipe(Gx(),J.transform(e=>e.toLowerCase())),tE=J.object({accessKeyAddress:eE,keyType:J.enum([`p256`,`secp256k1`,`webAuthn`])}),nE=J.object({accessKey:J.optional(tE),chainId:J.optional(J.number())}),rE=Hx(`subscriptionExpires must be a valid date`).check(J.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),iE=J.enum([`dev_second`,`day`,`week`]),aE=J.pipe(J.union([J.string(),J.bigint(),J.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),J.transform(e=>e.toString())).check(J.regex(/^[1-9]\d*$/,`Invalid periodCount`),J.refine(e=>{try{return BigInt(e)<=QT}catch{return!1}},`periodCount exceeds uint64`)),oE=GT({name:`tempo`,intent:`charge`,schema:{credential:{payload:J.discriminatedUnion(`type`,[J.object({hash:Kx(),type:J.literal(`hash`)}),J.object({signature:Jx(),type:J.literal(`transaction`)}),J.object({signature:Jx(),type:J.literal(`proof`)})])},request:J.pipe(J.object({machineTokenEnabled:J.optional(J.boolean()),amount:Bx(),chainId:J.optional(J.number()),currency:J.string(),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),feePayer:J.optional(J.pipe(J.union([J.boolean(),J.custom()]),J.transform(e=>typeof e==`object`||e))),memo:J.optional(J.never()),recipient:J.optional(J.string()),splits:J.optional(J.array(ZT).check(J.minLength(1),J.maxLength(10))),supportedModes:J.optional(J.array(J.enum(XT)).check(J.minLength(1)))}).check(J.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=N(e,t),i=n.reduce((e,n)=>e+N(n.amount,t),0n);return n.every(e=>N(e.amount,t)>0n)&&i<r},`Invalid splits`)),J.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,...c})=>({...c,amount:N(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==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:N(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s}}}:{}})))}}),sE=GT({name:`tempo`,intent:`session`,schema:{credential:{payload:J.discriminatedUnion(`action`,[J.object({action:J.literal(`open`),authorizedSigner:J.optional(J.string()),channelId:Kx(),cumulativeAmount:Bx(),descriptor:J.optional(J.custom()),signature:Jx(),transaction:Jx(),type:J.literal(`transaction`)}),J.object({action:J.literal(`topUp`),additionalDeposit:Bx(),channelId:Kx(),descriptor:J.optional(J.custom()),transaction:Jx(),type:J.literal(`transaction`)}),J.object({action:J.literal(`voucher`),channelId:Kx(),cumulativeAmount:Bx(),descriptor:J.optional(J.custom()),signature:Jx()}),J.object({action:J.literal(`close`),channelId:Kx(),closeSignature:Jx(),cumulativeAmount:Bx(),descriptor:J.optional(J.custom()),signature:Jx()})])},request:J.pipe(J.object({amount:Bx(),chainId:J.optional(J.number()),channelId:J.optional(Kx()),currency:J.string(),decimals:J.number(),escrowContract:J.optional(J.string()),feePayer:J.optional(J.pipe(J.union([J.boolean(),J.custom()]),J.transform(e=>typeof e==`object`||e))),feeToken:J.optional(Gx()),minVoucherDelta:J.optional(Bx()),operator:J.optional(Gx()),recipient:J.optional(J.string()),sessionProtocol:J.optional(J.enum([Nx.v2,Nx.v1])),sessionSnapshot:J.optional(J.custom()),suggestedDeposit:J.optional(Bx()),unitType:J.string()}).check(J.refine(({amount:e,decimals:t})=>N(e,t)>0n,`Session amount must be greater than 0`)),J.transform(({amount:e,chainId:t,channelId:n,decimals:r,escrowContract:i,feePayer:a,feeToken:o,minVoucherDelta:s,operator:c,sessionProtocol:l,sessionSnapshot:u,suggestedDeposit:d,...f})=>({...f,amount:N(e,r).toString(),...d?{suggestedDeposit:N(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:N(s,r).toString()},...t!==void 0&&{chainId:t},...a!==void 0&&{feePayer:a},...o!==void 0&&{feeToken:o},...c!==void 0&&{operator:c},...l!==void 0&&{[Mx.sessionProtocol]:l},...u!==void 0&&{[Mx.sessionSnapshot]:u}}})))}}),cE=GT({name:`tempo`,intent:`subscription`,schema:{credential:{payload:J.object({signature:Jx(),type:J.literal(`keyAuthorization`)})},request:J.pipe(J.object({amount:Bx(),accessKey:J.optional(tE),chainId:J.optional(J.number()),currency:eE,decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:J.optional(nE),periodCount:aE,periodUnit:iE,recipient:eE,subscriptionExpires:rE}).check(JT(`Subscription amount must be greater than 0`),J.refine(YT,`Subscription period exceeds uint64`)),J.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:N(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}})}));function uE(e){return e>=0n&&e<=kE}function dE(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return uE(t)?t:void 0}function fE(e){return pE(e),e}function pE(e){if(!uE(e))throw Error(`Value ${e} is outside uint96 bounds.`)}function mE(e){return typeof e==`object`&&!!e}function hE(e){return typeof e==`string`&&AE.has(e)}function gE(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!hE(t.action))}function _E(e,t=`No session credential context available.`){if(!gE(e))throw Error(t);return e}function vE(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function yE(e){return mE(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function bE(e){return mE(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 xE(e){let t=k.toString(e),n=JSON.parse(t);if(!bE(n))throw Error(`Invalid session receipt.`);return n}function SE(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function CE(e){let t=`message`,n=[];for(let r of e.split(`
205
+ `)}`}function Ey(e){return e.toLowerCase().replace(/[^a-z0-9-]+/g,`-`).replace(/-{2,}/g,`-`).replace(/^-|-$/g,``)}function Dy(e){if(!e)return`unknown`;let t=e.type;return t?t===`integer`?`number`:t:`unknown`}var Oy=F((()=>{yl(),Au()}));async function ky(e,t={}){let n=nt(),r=t.command??jy(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 Ly(s,[...c,`add-mcp`,...a]);o.push(...l.split(`
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`))&&Ay(e,r)&&o.push(`Amp`),{command:r,agents:o}}function Ay(e,t){let n=d(S(),`.config`,`amp`,`settings.json`),s={};if(r(n))try{s=JSON.parse(a(n,`utf-8`))}catch{return!1}let[c,...l]=Iy(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 jy(e,t){return Ny(e)?`${e} --mcp`:`${t} ${Fy(e)} --mcp`}function My(){let e=(process.argv[1]?.replace(/\\/g,`/`))?.match(/^(.+)\/node_modules\/(.+)$/);return e?{root:e[1],entry:e[2]}:null}function Ny(e){let t=process.argv[1];if(!t)return!1;let n=My();if(n)return!n.entry.startsWith(`.bin/`)&&!Py(n.root,e);let r=t.replace(/\\/g,`/`).split(`/`).pop();return r===e||r===`${e}.cmd`||r===`${e}.ps1`}function Py(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 Fy(e){let t=My();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 Iy(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 Ly(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 Ry=F((()=>{it()}));function zy(){return Yy.filter(e=>e.detect())}function By(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??zy(),l=[],u=[];for(let n of Hy(e)){let e=c.join(o,n.name);Wy(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(Gy(s)!==Gy(e))try{Wy(s),t.mkdirSync(c.dirname(s),{recursive:!0});let n=Gy(c.dirname(s)),r=Gy(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 Vy(e,t={}){let n=t.global!==!1,r=t.cwd||process.cwd(),i=n?K:r;Wy(c.join(i,`.agents`,`skills`,e));for(let t of zy()){if(t.universal)continue;let i=n?t.globalSkillsDir:c.join(r,t.projectSkillsDir);Wy(c.join(i,e))}}function Hy(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:Uy(e?.[1]??a.name),dir:i})}r(i)}}r(e);let i=c.join(e,`SKILL.md`);if(t.existsSync(i)){let r=Uy(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 Uy(e){return e.trim().replace(/[/\\]/g,`-`).replace(/\.\./g,``).slice(0,255)}function Wy(e){try{t.lstatSync(e).isSymbolicLink()?t.unlinkSync(e):t.rmSync(e,{recursive:!0,force:!0})}catch{}}function Gy(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,Ky,qy,Jy,Yy,Xy=F((()=>{K=b.homedir(),Ky=process.env.XDG_CONFIG_HOME||c.join(K,`.config`),qy=process.env.CLAUDE_CONFIG_DIR?.trim()||c.join(K,`.claude`),Jy=process.env.CODEX_HOME?.trim()||c.join(K,`.codex`),Yy=[{name:`Amp`,globalSkillsDir:c.join(Ky,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(Ky,`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(Jy,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(Jy)},{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(Ky,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.kimi`))},{name:`OpenCode`,globalSkillsDir:c.join(Ky,`opencode`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(Ky,`opencode`))},{name:`Claude Code`,globalSkillsDir:c.join(qy,`skills`),projectSkillsDir:`.claude/skills`,universal:!1,detect:()=>t.existsSync(qy)},{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(Ky,`goose`,`skills`),projectSkillsDir:`.goose/skills`,universal:!1,detect:()=>t.existsSync(c.join(Ky,`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(Ky,`crush`,`skills`),projectSkillsDir:`.crush/skills`,universal:!1,detect:()=>t.existsSync(c.join(Ky,`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 Zy(e,t,n={}){let{depth:r=1,description:i,global:a=!0}=n,o=n.cwd??(a?eb():process.cwd());await gl();let s=new Map;i&&s.set(e,i);let c=xy(e,ax(t,[],s,n.rootCommand),r,s),u=await w.mkdtemp(l.join(x.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 w.mkdir(l.dirname(n),{recursive:!0}),await w.writeFile(n,`${t.content}\n`);let i=ux(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 w.glob(n,{cwd:o}))try{let n=await w.readFile(l.resolve(o,i),`utf8`),a=ux(n),s=t===`_root`?a.name??e:l.basename(l.dirname(i)),c=l.join(u,s,`SKILL.md`);await w.mkdir(l.dirname(c),{recursive:!0}),await w.writeFile(c,n),r.some(e=>e.name===s)||r.push({name:s,description:a.description,external:!0})}catch{}}let{paths:i,agents:s}=By(u,{global:a,cwd:o}),d=new Set(i.map(e=>l.basename(e))),f=rb(e);if(f?.skills)for(let e of f.skills)d.has(e)||Vy(e,{global:a,cwd:o});return nb(e,wy(ax(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 w.rm(u,{recursive:!0,force:!0})}}async function Qy(e,t,n={}){let{depth:r=1,description:i}=n,a=n.cwd??process.cwd();await gl();let o=new Map;i&&o.set(e,i);let s=xy(e,ax(t,[],o,n.rootCommand),r,o),c=[],u=ib(e,{cwd:a});for(let t of s){let n=ux(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 w.glob(n,{cwd:a}))try{let n=ux(await w.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 $y(e,t={}){return ib(e,t).size>0}function eb(){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 tb(e){let t=process.env.XDG_DATA_HOME||l.join(x.homedir(),`.local`,`share`);return l.join(t,`incur`,`${e}.json`)}function nb(e,t,r,i){let a=tb(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 rb(e){try{return JSON.parse(n.readFileSync(tb(e),`utf-8`))}catch{return}}function ib(e,t={}){let n=rb(e);if(!n?.skills?.length)return new Set;if(n.paths?.length){let e=n.paths.filter(e=>ab(e)).map(e=>l.basename(e));return new Set(e)}let r=t.cwd??process.cwd(),i=[l.join(x.homedir(),`.agents`,`skills`),l.join(r,`.agents`,`skills`)],a=n.skills.filter(e=>i.some(t=>ab(l.join(t,e))));return new Set(a)}function ab(e){return n.existsSync(l.join(e,`SKILL.md`))}function ob(e){return rb(e)?.hash}var sb=F((()=>{Dx(),Xy(),yl(),Oy()}));function cb(e,t){let n=typeof e==`string`?e:e.name,r=typeof e==`string`?t??{}:e,i=r.version??zt,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:Vb(o),c=o===void 0?void 0:Hb(o),l=new Map,u=[],d=[],f=ub(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 Av(await Ov(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(Bb(t))return d.push((async()=>{let n=ay(await iy(t.mcp)),r={_group:!0,description:t.description,commands:n,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0};qb(e,r,wx.get(p)),l.set(e,r)})()),p;if(t&&`fetch`in t&&zb(t.fetch)){let n=Vb(t.fetch);return t.openapi?(d.push((async()=>{let r=await Av(await Ov(t.openapi,{baseUrl:Hb(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};qb(e,i,wx.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(qb(e,t,wx.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=bx.get(e),r=e,i=_x.get(r),a=Cx.get(r),o=yx.get(r),s=vx.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(()=>{qb(r.name,c,wx.get(p))})):qb(r.name,c,wx.get(p)),l.set(r.name,c),n){let t=Tx.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=wx.get(p);return pb(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=Su();return d.push((async()=>{let n=t?await Cu(t):await Fb(await Pb(e));for(let e of n){if(!Ib(e.command))throw Error(`Expected the default export from '${e.file}' to be created with \`Cli.command()\`.`);Lb(l,e.segments,e.command,e.file,wx.get(p))}})()),p},async serve(e=process.argv.slice(2),t={}){if(await Tt(e))return;d.length>0&&await Promise.all(d);let o=wx.get(p);return lb(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&&bx.set(p,a),a&&r.aliases&&Tx.set(p,r.aliases),r.options&&xx.set(p,r.options),r.config!==void 0&&Sx.set(p,!0),r.outputPolicy&&Cx.set(p,r.outputPolicy),r.globals){wx.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 yx.set(p,u),_x.set(p,l),vx.set(p,d),p}async function lb(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=px(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=vb(n,{configFlag:l})}catch(e){let t=e instanceof Error?e.message:String(e);d(s?Jb({code:`UNKNOWN`,message:t}):bl({code:`UNKNOWN`,message:t},`toon`)),a(1);return}let{fullOutput:m,format:h,formatExplicit:g,filterOutput:_,tokenLimit:v,tokenOffset:y,tokenCount:b,llms:x,llmsFull:S,mcp:C,help:w,update:T,updateCheck:ee,version:E,schema:D,configPath:O,configDisabled:k,rest:te}=p;s=o&&!g;let ne={...typeof r.update==`object`?r.update:void 0,binary:Rt!==void 0,version:r.version},re={},A=te;function j(e){if(!r.globals)return!0;try{let t=Ul(te,r.globals.schema,r.globals.alias,{validate:e});return e&&(re=t.parsed),A=t.rest,!0}catch(e){let t=e instanceof Error?e.message:String(e);return d(s?Jb({code:`UNKNOWN`,message:t}):bl({code:`UNKNOWN`,message:t},`toon`)),a(1),!1}}if(!j(!1))return;if(h===`yaml`&&await gl(),ee){if(r.update!==!1)try{await ot(e,ne)}catch{}return}if(T&&!w){try{let t=await st(e,ne);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(bl(t,h))}catch(e){let t={code:`UPDATE_FAILED`,message:e instanceof Error?e.message:String(e)};d(s?Jb(t):bl(t,h)),a(1)}return}if(C){await L_(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 ie=process.env.COMPLETE;if(ie){let a=n.indexOf(`--`),o=a===-1?n:n.slice(a+1);if(o.length===0)i([e,...r.aliases??[]].map(e=>ln(ie,e)).join(`
211
+ `));else{let e=Number(process.env._COMPLETE_INDEX??o.length-1),n=un(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 tu)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=Zl(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=dn(ie,n);c&&i(c)}return}let ae;if(!x&&!S&&!D&&!w&&!T&&!ee&&!E){let n=Tb(A,e,`skills`)!==-1,i=Tb(A,e,`mcp`)!==-1;if(!n&&!i){let n=ob(e);n&&$y(e,{cwd:r.sync?.cwd})&&wy(ax(t,[],new Map,r.rootCommand))!==n&&(ae={description:`Skills are out of date:`,commands:[{command:process.env.npm_config_user_agent||process.env.npm_execpath?`${nt()} ${Fy(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 A){let t=n.get(e);if(!t)break;let r=Kb(n,t);if(Ub(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=ax(n,s,t,o);d(by(i.length>0?`${e} ${i.join(` `)}`:e,r,t));return}d(bl(nx(n,i,r.globals?.schema,o),h));return}if(!g||h===`md`){let t=ax(n,s,new Map,o);d(vy(i.length>0?`${e} ${i.join(` `)}`:e,t,a));return}d(bl(ex(n,i,r.globals?.schema,o),h));return}let oe=Tb(A,e,`completions`);if(oe!==-1){let t=A[oe+1];if(w||!t){let t=Zl(`completions`);d(iu(`${e} completions`,{args:t.args,description:t.description,hideGlobalOptions:!0,hint:t.hint?.(e)}));return}if(!eu.includes(t)){d(Jb({code:`INVALID_SHELL`,message:`Unknown shell '${t}'. Supported: ${eu.join(`, `)}`})),a(1);return}d([e,...r.aliases??[]].map(e=>ln(t,e)).join(`
212
+ `));return}let se=Tb(A,e,`skills`);if(se!==-1){let o=Zl(`skills`),c=A[se+1],l=c?Ql(o,c):void 0;if(c&&!l){let t=sn(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(Jb({code:`COMMAND_NOT_FOUND`,message:r})),d(Yb(l))):d(bl({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(Eb(e,o));return}if(l?.name===`list`){if(w){d(Db(e,o,`list`));return}try{let n=await Qy(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(bl({code:`LIST_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(w){d(Db(e,o,`add`));return}let u=A.slice(se+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 Zy(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(bl(e,g?h:`toon`))}}catch(e){d(bl({code:`SYNC_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}let ce=Tb(A,e,`mcp`);if(ce!==-1){let o=Zl(`mcp`),c=A[ce+1],l=c?Ql(o,c):void 0;if(c&&!l){let t=sn(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(Jb({code:`COMMAND_NOT_FOUND`,message:r})),d(Yb(l))):d(bl({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(Eb(e,o));return}if(w){d(Db(e,o,l.name));return}if(l.name===`doctor`){let n=await Ob(e,t,r);d(bl(n,g?h:`toon`)),n.ok||a(1);return}let u=A.slice(ce+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 ky(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(bl({name:t,command:n.command,agents:n.agents},g?h:`toon`))}catch(e){d(bl({code:`MCP_ADD_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(E&&!w&&r.version){d(r.version);return}if(A.length===0){if(r.rootCommand&&s&&r.rootCommand.args&&Zb(r.rootCommand.args)){let n=r.rootCommand;await f(),d(iu(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:lx(n.examples),usage:n.usage,commands:t.size>0?wb(t):void 0,root:!0}));return}if(!(r.rootCommand||r.rootFetch)){await f(),d(ru(e,{aliases:r.aliases,configFlag:l,description:r.description,globals:r.globals,version:r.version,commands:wb(t),root:!0}));return}}let M=A.length===0&&r.rootCommand?{command:r.rootCommand,path:e,rest:[]}:A.length===0&&r.rootFetch?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:[]}:_b(t,A);if(w&&`fetchGateway`in M){let n=M.path===e?e:`${e} ${M.path}`;M.path===e&&t.size>0?d(ru(e,{aliases:r.aliases,configFlag:l,description:r.description,version:r.version,commands:wb(t),root:!0})):d(Nb(n,M.fetchGateway.description));return}if(w){if(`help`in M||`error`in M){let n=`help`in M?`${e} ${M.path}`:e,i=`help`in M?M.description:r.description,a=`help`in M?M.commands:t,o=n===e;if(o&&r.rootCommand&&a.size>0){let t=r.rootCommand;d(iu(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:lx(t.examples),usage:t.usage,commands:wb(a),root:!0}))}else d(ru(n,{aliases:o?r.aliases:void 0,configFlag:l,description:i,globals:r.globals,version:o?r.version:void 0,commands:wb(a),root:o}))}else if(`command`in M){let n=M.command,i=M.path===e,a=i?e:`${e} ${M.path}`,o=`commands`in M&&M.commands&&M.commands.size>0?wb(M.commands):i&&r.rootCommand&&t.size>0?wb(t):void 0;d(iu(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:lx(n.examples),usage:n.usage,commands:o,root:i}))}return}if(D){if(`help`in M){d(ru(`${e} ${M.path}`,{configFlag:l,description:M.description,globals:r.globals,commands:wb(M.commands)}));return}if(`error`in M){let t=M.path?`${e} ${M.path}`:e,n=sn(M.error,M.commands.keys()),r=n?` Did you mean '${n}'?`:``;d(`Error: '${M.error}' is not a command for '${t}'.${r}`),a(1);return}if(`fetchGateway`in M){d(`--schema is not supported for fetch commands.`),a(1);return}let t=M.command,n=g?h:`toon`,i={};t.args&&(i.args=ku(t.args)),t.env&&(i.env=ku(t.env)),t.options&&(i.options=ku(t.options)),t.output&&(i.output=ku(t.output)),r.globals?.schema&&(i.globals=ku(r.globals.schema)),d(bl(i,n));return}if(`help`in M){d(ru(`${e} ${M.path}`,{configFlag:l,description:M.description,globals:r.globals,commands:wb(M.commands)}));return}let le;if(s&&r.update!==!1){let t=at(e,ne);t&&(le={description:`Update available for ${t.name}:`,commands:[{command:`${u} --update`,description:`upgrade from ${t.current} to ${t.latest}`}]})}let ue=Xb(ae,le),de=performance.now(),fe=`command`in M&&M.command.format,pe=g?h:fe||r.format||`toon`;pe===`yaml`&&await gl();let me=`error`in M&&!M.path&&(()=>{let e=[...M.commands.keys()];for(let t of tu)e.push(t.name);return sn(M.error,e)!==void 0})(),N=`error`in M&&r.rootFetch&&!M.path&&!me?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:A}:`error`in M&&r.rootCommand&&!M.path&&!me?{command:r.rootCommand,path:e,rest:A}:M,he=`outputPolicy`in M&&M.outputPolicy||r.outputPolicy,ge=!(s&&!g&&he===`agent-only`),_e=_?In(_):void 0;function ve(e){if(v==null&&y==null)return{text:e,truncated:!1};let t=qt(e),n=y??0,r=v==null?t:n+v;if(n===0&&r>=t)return{text:e,truncated:!1};let i=Jt(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 ye(e){if(_e&&e.ok&&e.data!=null&&(e={...e,data:Ln(e.data,_e)}),ue){let t=e.meta.cta;e={...e,meta:{...e.meta,cta:t?{description:t.description,commands:[...t.commands,...ue.commands]}:ue}}}if(b){let t=e.ok?e.data:e.error,n=t==null?``:bl(t,pe);return d(String(qt(n)))}let t=e.meta.cta;if(s&&!m){e.ok&&e.data!=null&&ge?d(ve(bl(e.data,pe)).text):e.ok||d(Jb(e.error)),t&&d(Yb(t));return}if(m){if(v!=null||y!=null){let t=ve(e.ok&&e.data!=null?bl(e.data,pe):e.ok?``:bl(e.error,pe));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(bl(n,pe))}}return d(bl(e,pe))}let n=e.ok?e.data:e.error,r=bl(n,pe);if(!t){r&&d(ve(r).text);return}d(ve(bl(typeof n==`object`&&n?{...n,cta:t}:{data:n,cta:t},pe)).text)}if(`error`in N){let t=N.path?`${e} ${N.path} --help`:`${e} --help`,r=N.path?`${e} ${N.path}`:e,i=`commands`in N?[...N.commands.keys()]:[];if(!N.path)for(let e of tu)i.push(e.name);let o=sn(N.error,i),c=o?` Did you mean '${o}'?`:``,l=`'${N.error}' is not a command for '${r}'.${c}`,u=[];if(o){let t=n.map(e=>e===N.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(Jb({code:`COMMAND_NOT_FOUND`,message:l})),d(Yb(ue?{...f,commands:[...f.commands,...ue.commands]}:f)),a(1);return}ye({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:l},meta:{command:N.error,cta:f,duration:`${Math.round(performance.now()-de)}ms`}}),a(1);return}if(`fetchGateway`in N){if(!j(!0))return;let{fetchGateway:t,path:n,rest:i}=N,o=[...r.middlewares??[],...N.middlewares??[]],c=async()=>{let r=On(i);t.basePath&&(r.path=t.basePath+r.path);let o=kn(r),c=await t.fetch(o);if(An(c)){await $b(jn(c),{name:e,path:n,start:de,format:pe,formatExplicit:g,human:s,renderOutput:ge,fullOutput:m,truncate:ve,write:ye,writeln:d,exit:a});return}let l=await Mn(c);l.ok?ye({ok:!0,data:l.data,meta:{command:n,duration:`${Math.round(performance.now()-de)}ms`}}):(ye({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()-de)}ms`}}),a(1))};try{let t=r.envSchema?Bl(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=>({[Ex]:`error`,...e}),format:pe,formatExplicit:g,globals:re,name:e,set(e,t){i[e]=t},var:i,version:r.version},d=e=>{if(!Qb(e)||e[Ex]!==`error`)return;let t=e,r=_u(u,t.cta);ye({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()-de)}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){ye({ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:n,duration:`${Math.round(performance.now()-de)}ms`}}),a(e instanceof I?e.exitCode??1:1)}return}let{command:be,path:xe,rest:P}=N;if(!j(!0))return;let Se=[...r.middlewares??[],...`middlewares`in M?M.middlewares??[]:[],...be.middleware??[]];s&&fx(P,be.options,be.alias);let Ce;if(c)try{Ce=await yb(e,xe,{configDisabled:k,configPath:O,files:r.config?.files,loader:r.config?.loader})}catch(e){ye({ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:xe,duration:`${Math.round(performance.now()-de)}ms`}}),a(e instanceof I?e.exitCode??1:1);return}let we=await Kl(be,{agent:!s,argv:P,defaults:Ce,displayName:u,env:r.envSchema,envSource:r.env,format:pe,formatExplicit:g,globals:re,inputOptions:{},middlewares:Se,name:e,path:xe,vars:r.vars,version:r.version}),Te=`${Math.round(performance.now()-de)}ms`;if(`stream`in we){await $b(we.stream,{name:u,path:xe,start:de,format:pe,formatExplicit:g,human:s,renderOutput:ge,fullOutput:m,truncate:ve,write:ye,writeln:d,exit:a});return}if(we.ok){let e=_u(u,we.cta);ye({ok:!0,data:we.data,meta:{command:xe,duration:Te,...e?{cta:e}:void 0}})}else{let e=_u(u,we.cta);if(s&&!g&&we.error.fieldErrors){d(hb(u,xe,be,new Tn({message:we.error.message,fieldErrors:we.error.fieldErrors}),r.env,l)),a(1);return}ye({ok:!1,error:{code:we.error.code,message:we.error.message,...we.error.retryable===void 0?void 0:{retryable:we.error.retryable},...we.error.fieldErrors?{fieldErrors:we.error.fieldErrors}:void 0},meta:{command:xe,duration:Te,...e?{cta:e}:void 0}}),a(we.exitCode??1)}}function ub(e,t,n={}){let r;async function i(r,i,a){let{fromJsonSchema:o,McpServer:s,WebStandardStreamableHTTPServerTransport:c}=await Promise.resolve().then(()=>(I_(),s_)),l=new s({name:e,...n.title?{title:n.title}:void 0,version:t},n.instructions?{instructions:n.instructions}:void 0);V_(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 db(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 fb(e,t,n){let r={name:e,description:n.description};return _x.set(r,t),n.rootCommand&&bx.set(r,n.rootCommand),pv(r,{title:e,...n.version?{version:n.version}:void 0,...n.description?{description:n.description}:void 0})}async function pb(e,t,n,r={}){let i=performance.now(),a=new URL(n.url),o=a.pathname.split(`/`).filter(Boolean);if(n.method===`GET`&&db(o)){let n=fb(e,t,r),i=o[0]===`openapi.yml`||o[0]===`openapi.yaml`;return new Response(i?(await gl()).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 gl();let n=new Map,i=ax(t,[],n,r.rootCommand);if(o[2]===`index.json`&&o.length===3){let t=xy(e,i,1,n).map(t=>{let n=t.content.match(/^---\n([\s\S]*?)\n---/),r=n?_l().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=xy(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(Rr(e),{status:t,headers:{"content-type":`application/json`}})}if(o.length===0)return r.rootCommand?mb(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=_b(t,o);if(`error`in l){let t=l.path?`${e} ${l.path}`:e,n=sn(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 mb(d,u,f,s,n,i,{...r,groupMiddlewares:p})}async function mb(e,t,n,r,i,a,o){function s(e,t){return new Response(Rr(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 Kl(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(_u(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(Qb(s)&&s[Ex]===`error`){a.enqueue(n.encode(Rr(i(s))+`
216
+ `)),a.close();return}let t=Qb(s)&&s[Ex]===`ok`?_u(o.name??e,s.cta):void 0;a.enqueue(n.encode(Rr({type:`done`,ok:!0,meta:r(t)})+`
217
+ `)),a.close();return}if(Qb(s)&&s[Ex]===`error`){a.enqueue(n.encode(Rr(i(s))+`
218
+ `)),await t.return(void 0),a.close();return}a.enqueue(n.encode(Rr({type:`chunk`,data:s})+`
219
+ `))}catch(e){a.enqueue(n.encode(Rr({type:`error`,ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof I?{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=_u(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=_u(o.name??e,d.cta);return s({ok:!0,data:d.data,meta:{command:e,duration:f,...p?{cta:p}:void 0}},200)}function hb(e,t,n,r,i,a){let o=[];for(let e of r.fieldErrors){let t=(()=>{let t=gb(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(iu(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:lx(n.examples),usage:n.usage})),o.join(`
221
+ `)}function gb(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:`--${an(n)}${e}`}}return e.env?.shape[n]?{kind:`environment variable`,label:`${n}${r.length>0?`.${r.join(`.`)}`:``}`}:{kind:`argument`,label:`<${t}>`}}function _b(e,t){let[n,...r]=t;if(!n||!e.has(n))return{error:n??`(none)`,path:``,commands:e,rest:r};let i=Kb(e,e.get(n)),a=[n],o=r,s,c=[];if(Wb(i)){let e=i.outputPolicy??s;return{fetchGateway:i,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}for(;Ub(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&&!sn(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=Kb(i.commands,t);if(a.push(e),o=o.slice(1),i=n,Wb(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 vb(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(!gx.has(e[t+1]))throw new En({message:`Invalid format: "${e[t+1]}". Expected one of: ${[...gx].join(`, `)}`});d=e[t+1],f=!0,t++}else if(b&&C===b){let n=e[t+1];if(n===void 0)throw new En({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 En({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 En({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 En({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 yb(e,t,n={}){if(n.configDisabled)return;let{loader:r}=n,i;i=n.configPath?bb(n.configPath):await xb(n.files??[`${e}.json`]);let a;if(r){let e=await r(i);if(e===void 0)return;if(!rn(e))throw new En({message:`Config loader must return a plain object or undefined`});a=e}else{if(!i)return;let e=await Sb(i,!!n.configPath);if(!e)return;a=e}return Cb(a,e,t)}function bb(e){return e.startsWith(`~/`)||e===`~`?c.join(b.homedir(),e.slice(1)):c.resolve(process.cwd(),e)}async function xb(e){for(let t of e){let e=bb(t);try{return await C.access(e,C.constants.R_OK),e}catch{}}}async function Sb(e,t){let n;try{n=await C.readFile(e,`utf8`)}catch(n){if(n.code===`ENOENT`){if(t)throw new En({message:`Config file not found: ${e}`});return}throw n}let r;try{r=JSON.parse(n)}catch(t){throw new En({message:`Invalid JSON config file: ${e}`,cause:t instanceof Error?t:void 0})}if(!rn(r))throw new En({message:`Invalid config file: expected a top-level object in ${e}`});return r}function Cb(e,t,n){let r=n===t?[]:n.split(` `),i=e;for(let e of r){if(!rn(i))return;let t=i.commands;if(!rn(t)||(i=t[e],i===void 0))return}if(!rn(i))throw new En({message:`Invalid config section for '${n}': expected an object`});let a=i.options;if(a!==void 0){if(!rn(a))throw new En({message:`Invalid config 'options' for '${n}': expected an object`});return Object.keys(a).length>0?a:void 0}}function wb(e){let t=[];for(let[n,r]of e)Gb(r)||t.push({name:n,description:r.description});return t.sort((e,t)=>e.name.localeCompare(t.name))}function Tb(e,t,n){return Zl(e[0])?.name===n?0:e[0]===t&&Zl(e[1])?.name===n?1:-1}function Eb(e,t){return ru(`${e} ${t.name}`,{aliases:t.aliases,description:t.description,commands:t.subcommands?.map(e=>({name:e.name,description:e.description}))})}function Db(e,t,n){let r=Ql(t,n);return iu(`${e} ${t.name} ${n}`,{alias:r?.alias,aliases:r?.aliases,description:r?.description,hideGlobalOptions:!0,options:r?.options})}async function Ob(e,t,n){let r=[],i=[],a=new T,o=new T,s=[];o.on(`data`,e=>s.push(e.toString()));let c,l=L_(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(`${Rr({jsonrpc:`2.0`,id:1,method:`initialize`,params:{protocolVersion:`2024-11-05`,capabilities:{},clientInfo:{name:`incur-doctor`,version:`1.0.0`}}})}\n`),a.write(`${Rr({jsonrpc:`2.0`,id:2,method:`tools/list`,params:{}})}\n`),await kb(s,()=>u),a.end(),await l,c)return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_SERVER_FAILED`,message:jb(c)}]};let d;try{d=Ab(s)}catch(e){return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_RESPONSE_PARSE_FAILED`,message:jb(e)}]}}let f=d.find(e=>e.id===1);f?f.error&&i.push({code:`MCP_INITIALIZE_FAILED`,message:Mb(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:Mb(p.error)}):!rn(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(rn).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 kb(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 Ab(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(!rn(r))throw Error(`Expected JSON-RPC response object.`);t.push(r)}return t}function jb(e){return e instanceof Error?e.message:String(e)}function Mb(e){return rn(e)&&typeof e.message==`string`?e.message:Rr(e)}function Nb(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 Pb(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 C.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 Fb(e){let t=await xu(e.directory,{exclude:e.exclude});return Promise.all(t.map(async e=>({...e,command:(await import(E(e.file).href)).default})))}function Ib(e){return typeof e==`object`&&!!e&&e[hx]===!0}function Lb(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(Ub(c)&&!c.root)c.root=n,c.description??=n.description;else throw Rb(t,r);qb(t.join(` `),n,i);for(let e of n.aliases??[]){if(a.has(e))throw Rb([...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(Gb(c)||Wb(c))throw Rb(t,r);if(Ub(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 Rb(e,t){return Error(`Filesystem command '${e.join(` `)}' from '${t}' conflicts with an existing command or alias.`)}function zb(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 Bb(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 Vb(e){return typeof e==`function`?e:e.fetch}function Hb(e){return typeof e==`function`?void 0:e.url}function Ub(e){return`_group`in e}function Wb(e){return`_fetch`in e}function Gb(e){return`_alias`in e}function Kb(e,t){return Gb(t)?e.get(t.target):t}function qb(e,t,n){if(!(!n||Wb(t)||Gb(t))){if(Ub(t)){t.root&&qb(e,t.root,n);for(let[r,i]of t.commands)qb(`${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 Jb(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 Yb(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 Xb(...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 Zb(e){return Object.values(e.shape).some(e=>e._zod.optout!==`optional`)}function Qb(e){return typeof e==`object`&&!!e&&Ex in e}async function $b(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(Qb(i)){let e=i;if(e[Ex]===`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(Jb({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}}n?t.writeln(Rr({type:`chunk`,data:i})):t.renderOutput&&t.writeln(t.truncate(bl(i,t.format)).text)}if(Qb(r)&&r[Ex]===`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(Jb({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}let i=Qb(r)&&r[Ex]===`ok`?_u(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(Yb(i))}catch(e){n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof I?{retryable:e.retryable}:void 0}})):t.writeln(Jb({code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)})),t.exit(e instanceof I?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(Qb(i)){let e=i;if(e[Ex]===`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(Qb(r)&&r[Ex]===`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=Qb(r)&&r[Ex]===`ok`?_u(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 I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof I?{retryable:e.retryable}:void 0},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e instanceof I?e.exitCode??1:1)}}}function ex(e,t=[],n,r){let i=tx(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:ku(n)}:void 0}}function tx(e,t){let n=[];for(let[r,i]of e){if(Gb(i))continue;let e=[...t,r];if(Ub(i)){if(i.root){let t={name:e.join(` `)};i.root.description&&(t.description=i.root.description),n.push(t)}n.push(...tx(i.commands,e))}else{let t={name:e.join(` `)};Wb(i),i.description&&(t.description=i.description),n.push(t)}}return n}function nx(e,t=[],n,r){let i=rx(e,t);return r&&t.length>0&&i.push(ix(t,r)),{version:`incur.v1`,commands:i.sort((e,t)=>e.name.localeCompare(t.name)),...n?{globals:ku(n)}:void 0}}function rx(e,t){let n=[];for(let[r,i]of e){if(Gb(i))continue;let e=[...t,r];if(Wb(i)){let t={name:e.join(` `)};i.description&&(t.description=i.description),n.push(t)}else Ub(i)?(i.root&&n.push(ix(e,i.root)),n.push(...rx(i.commands,e))):n.push(ix(e,i))}return n}function ix(e,t){let n={name:e.join(` `)};t.description&&(n.description=t.description);let r=dx(t.args,t.env,t.options),i=t.output?ku(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=lx(t.examples);if(a){let t=e.join(` `);n.examples=a.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function ax(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),sx(r)&&(e.hint=cx(e.hint)),r.options&&(e.options=r.options),r.output&&(e.output=r.output);let t=lx(r.examples);t&&(e.examples=t),i.push(e)}for(let[r,a]of e){if(Gb(a))continue;let e=[...t,r];if(Wb(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 Ub(a)?(a.description&&n.set(e.join(` `),a.description),a.root&&i.push(ox(e,a.root)),i.push(...ax(a.commands,e,n))):i.push(ox(e,a))}return i.sort((e,t)=>(e.name??``).localeCompare(t.name??``))}function ox(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),sx(t)&&(n.hint=cx(n.hint)),t.options&&(n.options=t.options),t.output&&(n.output=t.output);let r=lx(t.examples);if(r){let t=e.join(` `);n.examples=r.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function sx(e){return e.destructive===!0||e.mcp!==!1&&e.mcp?.annotations?.destructiveHint===!0}function cx(e){return e?e.includes(mx)?e:`${e} ${mx}`:mx}function lx(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 ux(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return{};let n=_l().parse(t[1]);return!n||typeof n!=`object`?{}:n}function dx(e,t,n){if(!e&&!t&&!n)return;let r={};return e&&(r.args=ku(e)),t&&(r.env=ku(t)),n&&(r.options=ku(n)),r}function fx(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 px(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 mx,hx,gx,_x,vx,yx,bx,xx,Sx,Cx,wx,Tx,Ex,Dx=F((()=>{nn(),Bt(),Sn(),Dn(),Fn(),zn(),Ol(),gu(),nu(),bu(),Ou(),cn(),Br(),it(),wt(),yl(),cv(),_y(),ry(),Gl(),Au(),Oy(),Ry(),sb(),mx=`Confirm with the user before executing this destructive command.`,hx=Symbol.for(`incur.fileCommand`),gx=new Set([`toon`,`json`,`yaml`,`md`,`jsonl`]),_x=new WeakMap,vx=new WeakMap,yx=new WeakMap,bx=new WeakMap,xx=new WeakMap,Sx=new WeakMap,Cx=new WeakMap,wx=new WeakMap,Tx=new WeakMap,Ex=Symbol.for(`incur.sentinel`)})),Ox=F((()=>{Bt(),Dx(),Sn(),Dn(),Ol(),gu(),cv(),Fn(),ry(),Gl(),Au(),Oy(),yl(),Ry(),sb()}));function kx(e,t){if(!(!e||typeof e!=`object`))return e[t]}var q,Ax,jx,Mx,Nx,Px,Fx=F((()=>{q={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Ax={payment:`Payment`},jx={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Mx={charge:`charge`,session:`session`,subscription:`subscription`},Nx={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},Px={v1:`v1`,v2:`v2`}}));function Ix(e){let t=k.toString(e);return JSON.parse(t)}function Lx(e,t){return e.schema.request.parse(t)}function Rx(e){let t=A.canonicalize(e);return k.fromString(t,{pad:!1,url:!0})}var zx=F((()=>{})),J=Qe({address:()=>Kx,amount:()=>Vx,datetime:()=>Hx,datetimeInput:()=>Ux,hash:()=>qx,period:()=>Jx,signature:()=>Yx,toDate:()=>Wx,toDatetimeString:()=>Gx,unwrapOptional:()=>Xx});import*as Bx from"zod/mini";et(J,Bx);function Vx(){return xe.string().check(xe.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function Hx(){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 Ux(e=`Invalid ISO 8601 datetime`){return xe.pipe(xe.union([Hx(),xe.custom(e=>e instanceof Date)]),xe.transform(Wx)).check(xe.refine(e=>Number.isFinite(e.getTime()),e))}function Wx(e){return e instanceof Date?e:new Date(e)}function Gx(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function Kx(){return xe.string().check(xe.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function qx(){return xe.string().check(xe.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function Jx(){return xe.string().check(xe.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function Yx(){return xe.string().check(xe.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function Xx(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}var Zx=F((()=>{}));function Qx(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=pS(o)?void 0:o,f=e.expires?Gx(e.expires):void 0,p=e.opaque??(i===void 0?void 0:Rx(i)),m=u?mS({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return gS.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 $x(e){let t=[eS(`id`,e.id),eS(`realm`,e.realm),eS(`method`,e.method),eS(`intent`,e.intent),eS(`request`,Rx(e.request))];e.description!==void 0&&t.push(eS(`description`,e.description)),e.digest!==void 0&&t.push(eS(`digest`,e.digest)),e.expires!==void 0&&t.push(eS(`expires`,e.expires));let n=e.header;return n!==void 0&&!pS(n)&&t.push(eS(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(eS(`opaque`,Rx(e.meta))):t.push(eS(`opaque`,e.opaque)),`${Ax.payment} ${t.join(`, `)}`}function eS(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function tS(e,t){let n=nS(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=rS(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>hS)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return Qx({...a,request:Ix(r),...i&&{opaque:i}},t)}function nS(e){let t=Ax.payment,[n]=sS(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 rS(e){let t=Object.create(null),n=0;for(;n<e.length;){for(;n<e.length&&/[\s,]/.test(e[n]??``);)n++;if(n>=e.length)break;let r=n;for(;n<e.length&&/[A-Za-z0-9_-]/.test(e[n]??``);)n++;let i=e.slice(r,n).toLowerCase();if(!i)throw Error(`Malformed auth-param.`);for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]!==`=`)break;for(n++;n<e.length&&/\s/.test(e[n]??``);)n++;let[a,o]=iS(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function iS(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=t,a;for(;n<e.length;){let o=e[n];if(n++,r){a??=[];let t=o===`u`?e.slice(n,n+4):void 0;t&&/^[0-9A-Fa-f]{4}$/.test(t)?(a.push(String.fromCharCode(Number.parseInt(t,16))),n+=4):a.push(o),i=n,r=!1;continue}if(o===`\\`){a??=[],a.push(e.slice(i,n-1)),i=n,r=!0;continue}if(o===`"`)return[a?[...a,e.slice(i,n-1)].join(``):e.slice(t,n-1),n]}throw Error(`Unterminated quoted-string.`)}function oS(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 sS(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(!oS(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 cS(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 uS(n,t)}function uS(e,t){let n=sS(e,Ax.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return tS(e.slice(r,a).replace(/,\s*$/,``),t)})}function dS(e){let t=[e.realm,e.method,e.intent,Rx(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!pS(n)&&t.push(n),t.push(e.opaque??(e.meta?Rx(e.meta):``)),t.join(`|`)}function fS(e){return e.header??q.authorization}function pS(e){return e?.toLowerCase()===q.authorization.toLowerCase()}function mS(e,t){let n=dS(e),r=te.fromString(t.secretKey),i=te.fromString(n),a=ne.hmac256(r,i,{as:`Bytes`});return k.fromBytes(a,{url:!0,pad:!1})}var hS,gS,_S=F((()=>{Fx(),zx(),Zx(),hS=16384,gS=J.object({description:J.optional(J.string()),digest:J.optional(J.string().check(J.regex(/^sha-256=/,`Invalid digest format`))),expires:J.optional(Hx()),header:J.optional(J.string().check(J.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:J.string().check(J.minLength(1)),intent:J.string(),method:J.string(),meta:J.optional(J.record(J.string(),J.string())),opaque:J.optional(J.string()),realm:J.string(),request:J.record(J.string(),J.unknown())})})),vS,yS,Y,bS,xS,SS=F((()=>{vS=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details,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},...e&&{challengeId:e}}}},yS=class extends vS{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}.`)}},Y=class extends vS{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,reason:n}=e;super(n?`Payment verification failed: ${n}.`:`Payment verification failed.`,{details:t})}},bS=class extends vS{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.`)}},xS=class extends vS{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}}}));function CS(e,t){if(!e)throw new yS({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new yS({...t&&{id:t},reason:`malformed expires timestamp`});if(new Date(e)<new Date)throw new bS({expires:e})}var wS=F((()=>{SS()}));function TS(e){return Object.defineProperty(e,DS,{value:!0}),e}function ES(e){return!!e?.[DS]}var DS,OS=F((()=>{DS=Symbol.for(`mppx.x402.challenge`)}));function kS(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=FS(n)}return t}function AS(e,t){let n=kS(e),r=HS(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[FS(e)]??1,index:t}));return{definition:r,entries:i,header:MS(i),keys:n}}function jS(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)=>BS(e,t))}function MS(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${KS(n)}`}).join(`, `)}function NS(e,t,n){let r=PS(e,t,n)[0];if(r)return{challenge:r.challenge,method:r.method}}function PS(e,t,n){let r=new Map;for(let e of t){let t=FS(e),n=r.get(t);n?n.push(e):r.set(t,[e])}return e.flatMap((e,t)=>{let i=r.get(FS(e));if(!i)return[];let a=IS(e,n);return!a||a.q<=0?[]:i.filter(t=>t.canHandleChallenge?.({challenge:e})??!0).map(n=>({challenge:e,index:t,match:a,method:n}))}).sort((e,t)=>zS(e.challenge)-zS(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function FS(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function IS(e,t){let n;for(let r of t){if(!LS(e,r))continue;let t={...r,specificity:RS(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 LS(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function RS(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function zS(e){return+!!ES(e)}function BS(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}`);qS(r,`method`),qS(i,`intent`);let a=1;for(let t of VS(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=WS(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function VS(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function HS(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>FS(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]=US(t,`payment preference "${e}"`)}return a}function US(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return GS(e,t)}function WS(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 GS(Number(e),t)}function GS(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 KS(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function qS(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}var JS=F((()=>{OS()}));function YS(e){let t=e.match(RegExp(`^${Ax.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new eC;try{let e=k.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=XS(r);return{challenge:gS.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Ix(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new tC}}function XS(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!ZS(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:Rx(e)}}function ZS(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function QS(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function $S(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:Rx(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:Rx(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=k.fromString(s,{pad:!1,url:!0});return`${Ax.payment} ${c}`}var eC,tC,nC=F((()=>{_S(),Fx(),zx(),eC=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},tC=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}}})),rC,iC,aC=F((()=>{rC=`org.paymentauth/credential`,iC=`org.paymentauth/payment-required`}));function oC(e){let{extensions:t,resource:n,...r}=e;return bC.parse(r)}var sC,cC,lC,uC,dC,fC,pC,mC,hC,gC,_C,vC,yC,bC,xC,SC,CC,wC,TC,EC,DC,OC,kC=F((()=>{Zx(),sC=`charge`,cC=[`exact`],lC=`eip155:`,uC=`x402:`,dC=`PAYMENT-REQUIRED`,fC=`PAYMENT-SIGNATURE`,pC=`PAYMENT-RESPONSE`,mC=J.string().check(J.minLength(1)),hC=J.number().check(J.refine(e=>e>0,`Must be positive`)),gC=J.string().check(J.regex(/^\d+$/,`Invalid atomic amount`)),_C=Kx(),vC=J.string().check(J.regex(RegExp(`^${lC}\\d+$`),`Invalid EVM CAIP-2 network`)),yC=J.object({description:J.optional(J.string()),iconUrl:J.optional(J.string()),mimeType:J.optional(J.string()),serviceName:J.optional(J.string()),tags:J.optional(J.array(J.string())),url:mC}),J.discriminatedUnion(`type`,[J.object({name:mC,type:J.literal(`eip3009`),version:mC}),J.object({name:J.optional(J.string()),type:J.literal(`permit2`),version:J.optional(J.string())})]),bC=J.object({amount:gC,asset:mC,extra:J.optional(J.record(J.string(),J.unknown())),maxTimeoutSeconds:hC,network:vC,payTo:mC,scheme:J.enum(cC)}),xC=J.object({info:J.record(J.string(),J.unknown()),schema:J.record(J.string(),J.unknown())}),SC=J.record(J.string(),xC),CC=J.object({accepts:J.array(bC).check(J.minLength(1)),error:J.optional(J.string()),extensions:J.optional(SC),resource:yC,x402Version:J.literal(2)}),wC=J.object({authorization:J.object({from:_C,nonce:qx(),to:_C,validAfter:gC,validBefore:gC,value:gC}),signature:Yx()}),TC=J.object({permit2Authorization:J.object({deadline:gC,from:_C,nonce:gC,permitted:J.object({amount:gC,token:_C}),spender:_C,witness:J.object({to:_C,validAfter:gC})}),signature:Yx()}),EC=J.union([wC,TC]),DC=J.object({accepted:bC,extensions:J.optional(SC),payload:EC,resource:J.optional(yC),x402Version:J.literal(2)}),J.object({extensions:J.optional(SC),extra:J.optional(J.record(J.string(),J.unknown())),invalidMessage:J.optional(J.string()),invalidReason:J.optional(J.string()),isValid:J.boolean(),payer:J.optional(J.string())}),OC=J.object({amount:J.optional(gC),errorMessage:J.optional(J.string()),errorReason:J.optional(J.string()),extensions:J.optional(SC),extra:J.optional(J.record(J.string(),J.unknown())),network:mC,payer:J.optional(J.string()),success:J.boolean(),transaction:J.string()})}));function AC(e,t,n){let r=new Headers(e.headers);for(let e of jC)e===q.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}var jC,MC=F((()=>{Fx(),kC(),jC=[q.authorization,dC,pC,fC]}));function NC(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 PC(e){let t=NC(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 FC(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 IC(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){let t=gS.safeParse(e);if(!t.success)return;n.push(t.data)}let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function LC(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:IC(e.error.data):IC(e.result?._meta?.[iC])}function RC(e,t){return!e||e.id!==t?[]:LC(e)?.challenges??[]}async function zC(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=P({onEvent(e){if(!(i||!e.data)&&(i=!0,!(e.event&&e.event!==`message`)))try{a=FC(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()),o.reset({consume:!0}),a;if(r+=s.byteLength,r>UC)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function BC(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 FC(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>UC)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function VC(e){let t=WC.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>UC)){if(t.includes(`application/json`))return BC(e);if(t.includes(`text/event-stream`))return zC(e)}})();return WC.set(e,n),n}function HC(){return{getChallenges(e,t){let n=PC(t);return e.status===402||n===void 0?[]:VC(e).then(e=>RC(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=YS(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,[rC]:r}}})}}}}var UC,WC,GC=F((()=>{_S(),nC(),aC(),MC(),UC=1048576,WC=new WeakMap}));function KC(){return{getChallenges(e){return e.status!==402||!e.headers.has(q.wwwAuthenticate)?[]:cS(e)},setCredential(e,t,n){return AC(e,n?.challenge?fS(n.challenge):q.authorization,t)}}}var qC=F((()=>{_S(),Fx(),MC()}));function JC(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 YC}}}}var YC,XC=F((()=>{YC=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}}}));function ZC(e){try{let t=JSON.parse(k.toString(e));return rw(t)}catch{throw new YC}}var QC,$C,ew,tw,nw,rw,iw=F((()=>{XC(),kC(),QC=JC(CC),$C=JC(DC),ew=JC(OC),tw=QC.encode,QC.decode,nw=$C.encode,$C.decode,ew.encode,ew.decode,rw=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new YC;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new YC;let n=yC.parse(t.resource),r=t.extensions===void 0?void 0:SC.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}}}));function aw(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(dC);if(!t)return[];let n=ZC(t);return n.accepts.flatMap((e,t)=>{let r=bC.safeParse(e);if(!r.success)return[];let i=r.data;return TS(Qx({id:`${uC}${t}`,intent:sC,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return AC(e,fC,t)}}}var ow=F((()=>{_S(),iw(),OS(),kC(),MC()}));function sw(e){return e}function cw(){let e=[KC(),aw(),HC()],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 sw({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 lw=F((()=>{GC(),qC(),MC(),ow()}));function uw(e,t){return pw.set(e,t),e}function dw(e){return pw.has(e)}function fw(e,t){return Promise.resolve(pw.get(e)?.(t))}var pw,mw=F((()=>{pw=new WeakMap}));function hw(e,t){return Sw.set(e,t),e}function gw(e){Sw.delete(e)}function _w(e,t,n){Sw.has(e)&&Cw.set(t,n)}function vw(e){return Cw.get(e)}function yw(e,t){return Promise.resolve(Sw.get(e)?.(t)??t.response)}function bw(e,t){return ww.set(e,t),e}function xw(e,t){try{return ww.get(e)?.(t)}catch{return}}var Sw,Cw,ww,Tw=F((()=>{Sw=new WeakMap,Cw=new WeakMap,ww=new WeakMap}));async function Ew(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},pT);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>fT){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(mT,`true`);let s=new Response(new Blob(n).slice(0,fT),{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 Dw(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 Ow(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=dT,methods:a,onChallenge:o,orderChallenges:s,transport:c=cw()}=e,l=e.eventDispatcher??jw(),u=t??AS(a),d=Qw(r),f=async(e,t,r)=>{let p=Zw(e,t?.headers),m=p.has(q.acceptPayment),h=rT(p,u),g=Yw(e,t,p),_=Jw(e,t,p,h.header,m,n),v=await d($w(_.input),_.init),y=Xw(_.init,await g);if(!await c.isPaymentRequired(v,y))return v;let b=t?.context,{context:x,orderChallenges:S,...C}=y??{},w,T,ee,E,D;try{for(let n=0;n<i;n++){T=await c.getChallenges(v,y);let i=(await iT(PS(T,a,h.entries),S??s))[0];if(!i){if(await Dw(E,{challenges:T,response:v,status:`rejected`}),n>0)return v;throw Error(`No method found for challenges: ${T.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let u=i.challenge;w=u,ee=i.method,w.expires&&CS(w.expires,w.id);let p=lT(v,_.input,_.input),m=E,g=$x(u),x=m?.method===i.method&&m?.key===g,O=!1;if(m){let e=await Dw(m,{challenges:T,response:v,status:x?`pending`:`rejected`});O=x&&!e}E=O?m:void 0;let k=Iw(async n=>{if(n===void 0&&O&&m)return m.promise;O&&m&&(await Dw(m,{status:`rejected`}),E=void 0);let r=n??b;if(!dw(i.method))return nT(u,i.method,r);let a={prepare:()=>fw(i.method,{challenge:u,context:r,fetch:d,input:p,signal:eT(e,t)})},o=a.prepare().then(()=>nT(u,i.method,r,a));return E={attempt:a,key:n===void 0?g:void 0,method:i.method,promise:o},o}),te=await l.emit(`challenge.received`,Lw({challenge:u,challenges:T,createCredential:k,init:t,input:e,method:i.method,response:v}))??(o?await o(w,{createCredential:k}):void 0)??await k(),ne=E;ne&&await ne.promise.catch(()=>void 0)!==te&&(await Dw(ne,{status:`rejected`}),E=void 0),tT(te),await l.emit(`credential.created`,Rw({challenge:u,credential:te,init:t,input:e,method:i.method,response:v}));let re=e=>new xS({cause:e,challenge:u,credential:te,transactionHash:xw(i.method,te)});try{v=await d(p,{...c.setCredential({...C,headers:_.headers},te,{challenge:u}),redirect:`manual`})}catch(e){throw D=re(e),e}let A=await c.isPaymentRequired(v,y);if(A||(await Dw(ne,{response:v,status:v.status>=300&&v.status<400?`pending`:v.ok?`accepted`:`rejected`}),E=void 0),v.ok&&Mw(l,`payment.response`)&&await l.emit(`payment.response`,zw({challenge:u,credential:te,init:t,input:e,method:i.method,response:v})),!A){if(v.status>=500&&Mw(l,`payment.failed`)){try{v=await Ew(v)}catch(e){throw D=re(e),v=new Response(null,{headers:v.headers,status:v.status,statusText:v.statusText}),e}await l.emit(`payment.failed`,Bw({challenge:u,challenges:T,error:re(),init:t,input:e,method:i.method,response:v}))}return v.ok?yw(i.method,{challenge:u,credential:te,fetch:d,headers:_.headers,input:p,...r?{refetch:()=>f($w(_.input),t,!1)}:{},response:v,signal:eT(e,t)}):v}}T=void 0;try{T=await c.getChallenges(v,y)}catch{}return await Dw(E,{challenges:T,response:v,status:`rejected`}),v}catch(n){throw await Dw(E,{challenges:T,response:v,status:`rejected`}),await l.emit(`payment.failed`,Bw({challenge:w,challenges:T,error:D??n,init:t,input:e,method:ee,response:v})),n}},p=(e,t)=>f(e,t,!0);return p[uT]=d,p}function kw(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);hT||=globalThis.fetch,globalThis.fetch=Ow({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??(sT()?`same-origin`:`always`),fetch:globalThis.fetch})}function Aw(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 jw(){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 Nw(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await Fw(e[`*`],t,n),r}case`credential.created`:await Pw(e[`credential.created`],n),await Fw(e[`*`],t,n);return;case`payment.failed`:await Pw(e[`payment.failed`],n),await Fw(e[`*`],t,n);return;case`payment.response`:await Pw(e[`payment.response`],n),await Fw(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 gT.set(t,t=>e[t].size>0||e[`*`].size>0),t}function Mw(e,t){return gT.get(e)?.(t)??!0}async function Nw(e,t){try{return await e(t)}catch{return}}async function Pw(e,t){for(let n of e)try{await n(t)}catch{}}async function Fw(e,t,n){await Pw(e,Object.freeze({name:t,payload:n}))}function Iw(e){let t;return n=>(t??=e(n),t)}function Lw(e){return Object.freeze({challenge:Gw(e.challenge),challenges:e.challenges.map(e=>Gw(e)),createCredential:e.createCredential,init:Vw(e.init),input:Hw(e.input),method:Uw(e.method),response:Ww(e.response)})}function Rw(e){return Object.freeze({challenge:Gw(e.challenge),credential:e.credential,init:Vw(e.init),input:Hw(e.input),method:Uw(e.method),...e.response===void 0?{}:{response:Ww(e.response)}})}function zw(e){return Object.freeze({challenge:Gw(e.challenge),credential:e.credential,init:Vw(e.init),input:Hw(e.input),method:Uw(e.method),response:Ww(e.response)})}function Bw(e){return Object.freeze({...e.challenge?{challenge:Gw(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>Gw(e))}:{},error:e.error,init:Vw(e.init),input:Hw(e.input),...e.method?{method:Uw(e.method)}:{},...e.response===void 0?{}:{response:Ww(e.response)}})}function Vw(e){if(e)return qw({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function Hw(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function Uw(e){return qw(Object.assign({},e))}function Ww(e){return e instanceof Response?e.clone():Gw(e)}function Gw(e){try{return Kw(structuredClone(e))}catch{return qw(e)}}function Kw(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Kw(t);return e}function qw(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function Jw(e,t,n,r,i,a){let o=!!r&&!i&&aT(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 Yw(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 Xw(e,t){return t===void 0?e:{...e,body:t}}function Zw(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function Qw(e){let t=e;for(;t[uT];)t=t[uT];return t}function $w(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function eT(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function tT(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
224
+ `))throw Error(`Credential header value contains illegal newline characters`)}async function nT(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&&_w(t,a,r),t.createCredential(a)}function rT(e,t){let n=e.get(q.acceptPayment);if(!n)return t;try{return{...t,entries:jS(n),header:n}}catch{return t}}async function iT(e,t){return t?t(e):e}function aT(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=cT(e);return t===`same-origin`?!sT()||n.origin===globalThis.location.origin:t.origins.some(e=>oT(n,e))}function oT(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 sT(){return globalThis.location!==void 0}function cT(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,sT()?globalThis.location.href:void 0)}function lT(e,t,n){if(!e.url)return t;let r=new URL(e.url),i=cT(n);if(r.origin!==i.origin)throw Error(`Refusing to send payment credential across redirect from ${i.origin} to ${r.origin}`);return e.url}var uT,dT,fT,pT,mT,hT,gT,_T=F((()=>{_S(),Fx(),SS(),wS(),JS(),lw(),mw(),Tw(),uT=Symbol.for(`mppx.fetch.wrapper`),dT=3,fT=65536,pT=2e3,mT=`Mppx-Body-Truncated`,gT=new WeakMap}));Ox(),_T();function vT(){let e=new Uint8Array(64);return crypto.getRandomValues(e),Object.freeze({created:Math.floor(Date.now()/1e3),nonce:k.fromBytes(e,{pad:!1,url:!0})})}function yT(...e){return{protocol:`composed`,async sign(t,n=vT()){for(let r of e)t=await r.sign(t,n);return t}}}function bT(e,t){return async(n,r)=>e(await t.sign(new Request(n,r)))}Fx(),wS(),JS(),mw(),lw();const xT=new WeakMap;function ST(e){let{attestation:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=cw()}=e,c=Qw(e.fetch??globalThis.fetch),l=t?CT(t):void 0,u=l?bT(c,l):c,d=e.methods.flat(),f=AS(d,e.paymentPreferences),p=jw(),m=r,h={acceptPayment:f,acceptPaymentPolicy:o,...(e.fetch||t)&&{fetch:u},eventDispatcher:p,...n!==void 0&&{maxPaymentRetries:n},...m&&{onChallenge:m},...i&&{orderChallenges:i},methods:d,transport:s},g=Ow(h);a&&kw(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){let n=LT(e),r=await s.getChallenges(e,t?.request),a=Object.freeze(r.map(e=>RT(e))),o=VT(f.entries,t?.acceptPayment),c,l;try{let e=(await HT(PS(r,d,o),t?.orderChallenges??i))[0];if(!e)throw Error(`No method found for challenges: ${r.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${d.map(e=>`${e.name}.${e.intent}`).join(`, `)}`);let u=e.challenge;c=a[e.index],l=e.method,c.expires&&CS(c.expires,c.id);let f=c,m=l,h=MT(async e=>{try{f.expires&&CS(f.expires,f.id);let t=MT(t=>UT(f,m,t??e)),i=await p.emit(`challenge.received`,NT({challenge:f,challenges:r,createCredential:t,method:m,response:n}))??await t();return tT(i),await p.emit(`credential.created`,PT({challenge:f,credential:i,method:m,response:n})),i}catch(e){throw await p.emit(`payment.failed`,FT({challenge:f,challenges:r,error:e,method:m,response:n})),e}}),g=Object.freeze({challenge:f,challenges:a,createCredential:h,method:IT(m),setCredential(e,t){return tT(t),s.setCredential(e,t,{challenge:u})}});return xT.set(g,m),g}catch(e){throw await p.emit(`payment.failed`,FT({challenge:c,challenges:r,error:e,method:l,response:n})),e}}async function S(e,t,n){let{maxRedirects:r=20,requirePayment:i=!1,...a}=n??{},d=await DT({acceptPayment:f.header,acceptPaymentPolicy:o,fetch:c,init:t,input:e,maxRedirects:r,signer:l}),p=OT(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}),h=xT.get(m)??m.method,g=MT(async e=>(dw(h)&&await fw(h,{challenge:m.challenge,context:e,fetch:u,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(OT(d.replayRequest,d.body),t);return u(d.replayRequest.url,{...n,redirect:`manual`})}});return Object.freeze({payment:_,request:d.request,response:d.response,redirects:d.redirects})}return{fetch:g,rawFetch:c,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)).createCredential(t)}}}function CT(e){let t=Object.values(e);if(t.length===0)throw TypeError(`Mppx client attestation must configure at least one signer.`);return yT(...t)}const wT=new Set([301,302,303,307,308]),TT=[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`,`transfer-encoding`],ET=[`authorization`,`cookie`,`cookie2`,`host`,`payment-authorization`,`payment-signature`,`proxy-authorization`,`x-payment`];async function DT(e){let{acceptPayment:t,acceptPaymentPolicy:n,fetch:r,init:i,input:a,maxRedirects:o,signer:s}=e;if(!Number.isInteger(o)||o<0)throw TypeError(`maxRedirects must be a non-negative integer.`);let c=new Request(a,{...i,redirect:`manual`}),l=c.headers.has(q.acceptPayment),u=await kT(c,i?.body),d=[];for(;;){c=AT(c,t,l,n);let e=s?await s.sign(c.clone()):c.clone(),i=await r(e);if(i.type===`opaqueredirect`||i.status===0)throw Error(`prepareRequest requires a runtime that exposes manual redirect responses.`);if(!wT.has(i.status))return{body:u,replayRequest:c,request:e,response:i,redirects:Object.freeze(d)};let a=i.headers.get(`location`);if(!a)return{body:u,replayRequest:c,request:e,response:i,redirects:Object.freeze(d)};if(d.length>=o)throw await i.body?.cancel(),Error(`Payment request exceeded ${o} redirects.`);let f=new URL(c.url),p=new URL(a,f);if(f.protocol===`https:`&&p.protocol!==`https:`)throw await i.body?.cancel(),Error(`Payment request refused HTTPS downgrade redirect to ${p.href}`);let m=new Headers(c.headers),h=c.method;if((i.status===301||i.status===302)&&h===`POST`||i.status===303&&h!==`GET`&&h!==`HEAD`){h=`GET`,u=void 0;for(let e of TT)m.delete(e)}if(f.origin!==p.origin)for(let e of[...m.keys()]){let t=m.get(e)??``;(ET.includes(e)||t.startsWith(`Payment `))&&m.delete(e)}d.push(Object.freeze({from:f.href,status:i.status,to:p.href})),await i.body?.cancel(),c=new Request(p,jT(c,m,h,u))}}function OT(e,t){return jT(e,new Headers(e.headers),e.method,t)}async function kT(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 AT(e,t,n,r){if(n)return e;let i=new Headers(e.headers);return i.delete(q.acceptPayment),t&&aT(e,r)&&i.set(q.acceptPayment,t),new Request(e,{headers:i})}function jT(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 MT(e){let t;return n=>(t??=e(n),t)}function NT(e){return Object.freeze({challenge:RT(e.challenge),challenges:e.challenges.map(e=>RT(e)),createCredential:e.createCredential,method:IT(e.method),response:LT(e.response)})}function PT(e){return Object.freeze({challenge:RT(e.challenge),credential:e.credential,method:IT(e.method),response:LT(e.response)})}function FT(e){return Object.freeze({...e.challenge?{challenge:RT(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>RT(e))}:{},error:e.error,...e.method?{method:IT(e.method)}:{},response:LT(e.response)})}function IT(e){return BT(Object.assign({},e))}function LT(e){return e instanceof Response?e.body===null?e.clone():new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText}):RT(e)}function RT(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 zT(t)}catch{return BT(e)}}function zT(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))zT(t);return e}function BT(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function VT(e,t){return t?typeof t==`string`?jS(t):t:e}async function HT(e,t){return t?t(e):e}async function UT(e,t,n){let r=t.context&&n!==void 0?t.context.parse(n):void 0;return t.createCredential(r===void 0?{challenge:e}:{challenge:e,context:r})}function WT(){return J.string().check(J.regex(GT,`Invalid URI or path`))}var GT,KT,qT,JT,YT,XT,ZT,QT,$T,eE=F((()=>{Zx(),GT=/^([a-zA-Z][a-zA-Z\d+.-]*:\/\/\S+|\/\S*)$/,KT=new Set([`amount`,`currency`,`description`,`intent`,`method`]),qT=J.looseObject({amount:J.optional(J.union([J.null(),J.string().check(J.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:J.optional(J.string()),description:J.optional(J.string()),intent:J.optional(J.string()),method:J.optional(J.string())}),JT=J.pipe(J.looseObject({amount:J.optional(J.union([J.null(),J.string().check(J.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:J.optional(J.string()),description:J.optional(J.string()),intent:J.optional(J.string()),method:J.optional(J.string()),offers:J.optional(J.array(qT).check(J.minLength(1)))}).check(J.refine(e=>e.offers===void 0||Object.keys(e).every(e=>e===`offers`||!KT.has(e)),`Cannot mix offers with flat payment info fields`)),J.transform(e=>{if(e.offers)return{offers:e.offers};let t={};for(let[n,r]of Object.entries(e))n!==`offers`&&(KT.has(n)||r!==void 0)&&(t[n]=r);return{offers:[t]}})),YT=J.looseObject({apiReference:J.optional(WT()),homepage:J.optional(WT()),llms:J.optional(WT())}),XT=J.looseObject({categories:J.optional(J.array(J.string())),docs:J.optional(YT)}),ZT=J.looseObject({"x-payment-info":J.optional(JT),requestBody:J.optional(J.unknown()),responses:J.optional(J.record(J.string(),J.unknown())),summary:J.optional(J.string())}),QT=J.looseObject({delete:J.optional(ZT),get:J.optional(ZT),head:J.optional(ZT),options:J.optional(ZT),patch:J.optional(ZT),post:J.optional(ZT),put:J.optional(ZT),trace:J.optional(ZT)}),$T=J.looseObject({openapi:J.string(),info:J.looseObject({title:J.string(),version:J.string()}),"x-service-info":J.optional(XT),paths:J.optional(J.record(J.string(),QT))})}));eE();function tE(e){let t=[],n=$T.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=JT.safeParse(o);if(!s.success){for(let e of s.error.issues){let n=e.path.length>0?`.${e.path.map(String).join(`.`)}`:``;t.push({message:e.message,path:`${a}.x-payment-info${n}`,severity:`error`})}continue}let c=n.responses;(!c||!(`402`in c))&&t.push({message:`Operation with x-payment-info MUST have a 402 response`,path:`${a}.responses`,severity:`error`});let l=r.toUpperCase();!n.requestBody&&(l===`POST`||l===`PUT`||l===`PATCH`)&&t.push({message:`Operation with x-payment-info has no requestBody`,path:a,severity:`warning`})}return t}function nE(e){return e}function rE(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}var iE=F((()=>{}));function aE(e){return J.refine(e=>{let{amount:t,decimals:n}=e;return N(t,n)>0n},e)}function oE(e){let{periodCount:t,periodUnit:n}=e;try{let e=uE[n];return e!==void 0&&BigInt(t)*e<=lE}catch{return!1}}var sE,cE,lE,uE,dE,fE,pE,mE,hE,gE,_E,vE,yE,bE=F((()=>{Fx(),iE(),Zx(),sE=[`push`,`pull`],cE=J.object({amount:Vx(),memo:J.optional(qx()),recipient:J.pipe(J.string(),J.transform(e=>e))}),lE=(1n<<64n)-1n,uE={dev_second:1n,day:86400n,week:604800n},dE=J.pipe(Kx(),J.transform(e=>e.toLowerCase())),fE=J.object({accessKeyAddress:dE,keyType:J.enum([`p256`,`secp256k1`,`webAuthn`])}),pE=J.object({accessKey:J.optional(fE),chainId:J.optional(J.number())}),mE=Ux(`subscriptionExpires must be a valid date`).check(J.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),hE=J.enum([`dev_second`,`day`,`week`]),gE=J.pipe(J.union([J.string(),J.bigint(),J.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),J.transform(e=>e.toString())).check(J.regex(/^[1-9]\d*$/,`Invalid periodCount`),J.refine(e=>{try{return BigInt(e)<=lE}catch{return!1}},`periodCount exceeds uint64`)),_E=nE({name:`tempo`,intent:`charge`,schema:{credential:{payload:J.discriminatedUnion(`type`,[J.object({hash:qx(),type:J.literal(`hash`)}),J.object({signature:Yx(),type:J.literal(`transaction`)}),J.object({signature:Yx(),type:J.literal(`proof`)})])},request:J.pipe(J.object({machineTokenEnabled:J.optional(J.boolean()),amount:Vx(),chainId:J.optional(J.number()),currency:J.string(),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),feePayer:J.optional(J.pipe(J.union([J.boolean(),J.custom()]),J.transform(e=>typeof e==`object`||e))),memo:J.optional(J.never()),recipient:J.optional(J.string()),splits:J.optional(J.array(cE).check(J.minLength(1),J.maxLength(10))),supportedModes:J.optional(J.array(J.enum(sE)).check(J.minLength(1)))}).check(J.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=N(e,t),i=n.reduce((e,n)=>e+N(n.amount,t),0n);return n.every(e=>N(e.amount,t)>0n)&&i<r},`Invalid splits`)),J.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,...c})=>({...c,amount:N(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==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:N(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s}}}:{}})))}}),vE=nE({name:`tempo`,intent:`session`,schema:{credential:{payload:J.discriminatedUnion(`action`,[J.object({action:J.literal(`open`),authorizedSigner:J.optional(J.string()),channelId:qx(),cumulativeAmount:Vx(),descriptor:J.optional(J.custom()),signature:Yx(),transaction:Yx(),type:J.literal(`transaction`)}),J.object({action:J.literal(`topUp`),additionalDeposit:Vx(),channelId:qx(),descriptor:J.optional(J.custom()),transaction:Yx(),type:J.literal(`transaction`)}),J.object({action:J.literal(`voucher`),channelId:qx(),cumulativeAmount:Vx(),descriptor:J.optional(J.custom()),signature:Yx()}),J.object({action:J.literal(`close`),channelId:qx(),closeSignature:Yx(),cumulativeAmount:Vx(),descriptor:J.optional(J.custom()),signature:Yx()})])},request:J.pipe(J.object({amount:Vx(),chainId:J.optional(J.number()),channelId:J.optional(qx()),currency:J.string(),decimals:J.number(),escrowContract:J.optional(J.string()),feePayer:J.optional(J.pipe(J.union([J.boolean(),J.custom()]),J.transform(e=>typeof e==`object`||e))),feeToken:J.optional(Kx()),minVoucherDelta:J.optional(Vx()),operator:J.optional(Kx()),recipient:J.optional(J.string()),sessionProtocol:J.optional(J.enum([Px.v2,Px.v1])),sessionSnapshot:J.optional(J.custom()),suggestedDeposit:J.optional(Vx()),unitType:J.string()}).check(J.refine(({amount:e,decimals:t})=>N(e,t)>0n,`Session amount must be greater than 0`)),J.transform(({amount:e,chainId:t,channelId:n,decimals:r,escrowContract:i,feePayer:a,feeToken:o,minVoucherDelta:s,operator:c,sessionProtocol:l,sessionSnapshot:u,suggestedDeposit:d,...f})=>({...f,amount:N(e,r).toString(),...d?{suggestedDeposit:N(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:N(s,r).toString()},...t!==void 0&&{chainId:t},...a!==void 0&&{feePayer:a},...o!==void 0&&{feeToken:o},...c!==void 0&&{operator:c},...l!==void 0&&{[Nx.sessionProtocol]:l},...u!==void 0&&{[Nx.sessionSnapshot]:u}}})))}}),yE=nE({name:`tempo`,intent:`subscription`,schema:{credential:{payload:J.object({signature:Yx(),type:J.literal(`keyAuthorization`)})},request:J.pipe(J.object({amount:Vx(),accessKey:J.optional(fE),chainId:J.optional(J.number()),currency:dE,decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:J.optional(pE),periodCount:gE,periodUnit:hE,recipient:dE,subscriptionExpires:mE}).check(aE(`Subscription amount must be greater than 0`),J.refine(oE,`Subscription period exceeds uint64`)),J.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:N(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}})}));function xE(e){return e>=0n&&e<=BE}function SE(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return xE(t)?t:void 0}function CE(e){return wE(e),e}function wE(e){if(!xE(e))throw Error(`Value ${e} is outside uint96 bounds.`)}function TE(e){return typeof e==`object`&&!!e}function EE(e){return typeof e==`string`&&VE.has(e)}function DE(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!EE(t.action))}function OE(e,t=`No session credential context available.`){if(!DE(e))throw Error(t);return e}function kE(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function AE(e){return TE(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function jE(e){return TE(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 ME(e){let t=k.toString(e),n=JSON.parse(t);if(!jE(n))throw Error(`Invalid session receipt.`);return n}function NE(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function PE(e){let t=`message`,n=[];for(let r of e.split(`
225
225
  `))r.startsWith(`event: `)?t=r.slice(7).trim():r.startsWith(`data: `)?n.push(r.slice(6)):r===`data:`&&n.push(``);if(n.length===0)return null;let r=n.join(`
226
- `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=wE(r);return yE(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=wE(r);return bE(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function wE(e){try{return JSON.parse(e)}catch{return null}}function TE(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function EE(){return JSON.stringify({mpp:`payment-close-request`})}function DE(e){let t=OE(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`&&bE(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`&&yE(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&bE(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function OE(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}var kE,AE,jE,ME=F((()=>{kE=(1n<<96n)-1n,AE=new Set([`open`,`topUp`,`voucher`,`close`]),jE=`0x4d50500000000000000000000000000000000000`}));function NE(e){return BE.encode(e)}function PE(e){return BE.decode(e)}var FE,IE,LE,RE,zE,BE,VE=F((()=>{KC(),Xx(),FE=J.custom(e=>typeof e==`string`&&de(e,{strict:!1})),IE=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),LE=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),RE=J.object({authorizedSigner:FE,expiringNonceHash:IE,operator:FE,payee:FE,payer:FE,salt:IE,token:FE}),zE=J.object({acceptedCumulative:J.string(),chainId:J.number(),channelId:IE,closeRequestedAt:J.optional(J.string()),deposit:J.string(),descriptor:RE,escrow:FE,highestVoucher:J.optional(J.object({channelId:IE,cumulativeAmount:J.string(),signature:LE})),requiredCumulative:J.string(),settled:J.string(),spent:J.string(),units:J.optional(J.number())}),BE=WC(zE)}));function HE(e){return{status:`active`,...e}}function UE(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?JE(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?JE(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:KE(e.challengeId,t.snapshot),effects:[]}:JE(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?JE(e,t):{state:oD({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:qE(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:JE(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?JE(e,t):{state:lD(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?GE({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):JE(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:JE(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?JE(e,t):{state:qE(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}]}:JE(e,t);case`settled`:return e.status===`settling`?{state:qE(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:JE(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:JE(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:JE(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?JE(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`?JE(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function WE(e,t){let n=UE(e.state,t);return e.state=n.state,n}function GE(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 KE(e,t){return HE({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function qE(e,t,n,r){return HE({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function JE(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function YE(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function XE(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`);YE({cumulativeAmount:i,maxVoucherCumulative:n}),YE({cumulativeAmount:a,maxVoucherCumulative:n})}function ZE(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;XE({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function QE(e,t){return typeof e==`bigint`?e:N(e,t)}function $E(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(tD(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 eD(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;YE({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 tD(e,t){YE({cumulativeAmount:e,maxVoucherCumulative:t??null})}function nD(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 rD(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function iD(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!uE(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>rD({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function aD(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=dE(r),s=dE(a.spent);return o===void 0||s===void 0||!uE(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function oD(e){return HE({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 sD(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:hD}}function cD(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=ZE({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&WE(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function lD(e,t){return HE({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function uD(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=dE(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 dD(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 UE(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function fD(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 pD(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 mD(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(EE()),e.waitForCloseReady()))(),a=BigInt(i.spent);iD({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=>aD({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(TE(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}var hD,gD=F((()=>{ME(),VE(),hD={status:`idle`}}));function _D(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=eO.CLOSED,r=null}if(a.type===`open`&&(i=eO.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 vD(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function yD(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=QE(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 bD(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:lD(s,u)}:i?{channel:u,state:oD({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function xD(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=vD(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,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:fE(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function SD(e){return e.method===Ax.tempo&&e.intent===jx.session}function CD(e){return SD(e)&&Ox(e.request.methodDetails,Mx.sessionProtocol)===Nx.v2}function wD(e){return Ox(e.request.methodDetails,Mx.sessionSnapshot)}function TD(e,t,n){let r=e instanceof Request?e.headers:void 0;return{...t,headers:{...Sw(r),...Sw(t?.headers),[q.authorization]:n}}}function ED(e){try{let t=typeof location>`u`?void 0:location.href,n=e instanceof Request?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function DD(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function OD(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 kD(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);let r=await AD({challenge:e.challenge,context:{action:`topUp`,channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,input:e.input,signal:e.signal});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(q.paymentReceipt);return i?xE(i):void 0}async function AD(e){let t=async t=>e.fetch(ED(e.input),{method:`POST`,...e.signal?{signal:e.signal}:{},headers:{[q.authorization]:await e.createSessionCredential(t,e.context)}}),n=await t(e.challenge);if(n.status!==402)return n;let r=sS(n).find(CD);return r?t(r):n}async function jD(e){let t=MD({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,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,TD(e.input,e.init,t))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(q.paymentReceipt)&&await l(),u}function MD(e){let t=sS(e.response).find(CD);if(!t)return;let n=wD(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function ND(e){if(!e.lastUrl)throw Error(`Cannot close session: no URL available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or call fetch()/sse() before close().`);let t=e.target.challenge,n=e.signedCloseAmount,r=async(r,i=!1)=>{t=r,n=(i?e.resolveSignedCloseAmount?.(r):void 0)??e.signedCloseAmount;let a=await e.createSessionCredential(r,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(e.lastUrl,{method:`POST`,headers:{[q.authorization]:a}})},i=await r(e.target.challenge);if(i.status===402){let t=sS(i).find(CD);t&&(e.setChallenge?.(t),i=await r(t,!0))}if(!i.ok){let e=await OD(i),t=i.headers.get(q.wwwAuthenticate)??``;throw Error(`Close request failed with status ${i.status}${e?`: ${e}`:``}${t?` [${q.wwwAuthenticate}: ${t}]`:``}`)}let a=i.headers.get(q.paymentReceipt);if(!a)return;let o=xE(a);if(!o.txHash||!re.validate(o.txHash,{strict:!0})||re.size(o.txHash)!==32||!aD({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:e.getMinimumSpent?.()??0n,receipt:o}))throw Error(`Session close response included a mismatched payment receipt.`);return o}async function PD(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Sw(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!SE(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),FD(e,c,{onReceipt:r,signal:o},n)}function FD(e,t,n,r){if(!SE(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let i=r.getChallenge();return ID({onNeedVoucher:t=>VD({challenge:i,driver:r,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*ID(e){for await(let t of LD(e))t.data!==void 0&&(yield t.data)}async function*LD(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=RD(r,a);if(!t)break;let n=t.index+t.length,i=r.slice(0,t.index),o=r.slice(0,n);if(r=r.slice(n),!i.trim())continue;let s=CE(i.replace(/\r\n|\r/g,`
227
- `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,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 RD(e,t){for(let n=0;n<e.length;n++){let r=zD(e,n,t);if(!r)continue;let i=zD(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function zD(e,t,n){return e[t]===`
226
+ `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=FE(r);return AE(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=FE(r);return jE(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function FE(e){try{return JSON.parse(e)}catch{return null}}function IE(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function LE(){return JSON.stringify({mpp:`payment-close-request`})}function RE(e){let t=zE(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`&&jE(t.data)?{mpp:`payment-close-ready`,data:t.data}:t.mpp===`payment-error`&&typeof t.status==`number`&&typeof t.message==`string`?{mpp:`payment-error`,status:t.status,message:t.message}:t.mpp===`payment-need-voucher`&&AE(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&jE(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function zE(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}var BE,VE,HE,UE=F((()=>{BE=(1n<<96n)-1n,VE=new Set([`open`,`topUp`,`voucher`,`close`]),HE=`0x4d50500000000000000000000000000000000000`}));function WE(e){return ZE.encode(e)}function GE(e){return ZE.decode(e)}var KE,qE,JE,YE,XE,ZE,QE=F((()=>{XC(),Zx(),KE=J.custom(e=>typeof e==`string`&&de(e,{strict:!1})),qE=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),JE=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),YE=J.object({authorizedSigner:KE,expiringNonceHash:qE,operator:KE,payee:KE,payer:KE,salt:qE,token:KE}),XE=J.object({acceptedCumulative:J.string(),chainId:J.number(),channelId:qE,closeRequestedAt:J.optional(J.string()),deposit:J.string(),descriptor:YE,escrow:KE,highestVoucher:J.optional(J.object({channelId:qE,cumulativeAmount:J.string(),signature:JE})),requiredCumulative:J.string(),settled:J.string(),spent:J.string(),units:J.optional(J.number())}),ZE=JC(XE)}));function $E(e){return{status:`active`,...e}}function eD(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?aD(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?aD(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:rD(e.challengeId,t.snapshot),effects:[]}:aD(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?aD(e,t):{state:_D({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:iD(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:aD(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?aD(e,t):{state:bD(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?nD({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):aD(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:aD(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?aD(e,t):{state:iD(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}]}:aD(e,t);case`settled`:return e.status===`settling`?{state:iD(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:aD(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:aD(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:aD(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?aD(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`?aD(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function tD(e,t){let n=eD(e.state,t);return e.state=n.state,n}function nD(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 rD(e,t){return $E({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function iD(e,t,n,r){return $E({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function aD(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function oD(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function sD(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`);oD({cumulativeAmount:i,maxVoucherCumulative:n}),oD({cumulativeAmount:a,maxVoucherCumulative:n})}function cD(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;sD({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function lD(e,t){return typeof e==`bigint`?e:N(e,t)}function uD(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(fD(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 dD(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;oD({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 fD(e,t){oD({cumulativeAmount:e,maxVoucherCumulative:t??null})}function pD(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 mD(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function hD(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!xE(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>mD({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function gD(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=SE(r),s=SE(a.spent);return o===void 0||s===void 0||!xE(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function _D(e){return $E({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 vD(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:ED}}function yD(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=cD({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&tD(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function bD(e,t){return $E({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function xD(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=SE(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 SD(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 eD(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function CD(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 wD(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 TD(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(LE()),e.waitForCloseReady()))(),a=BigInt(i.spent);hD({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=>gD({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(IE(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}var ED,DD=F((()=>{UE(),QE(),ED={status:`idle`}}));function OD(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=dO.CLOSED,r=null}if(a.type===`open`&&(i=dO.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 kD(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function AD(e){let{amount:t,assertVoucherWithinLocalLimit:n,channel:r,decimals:i,lastChallenge:a,lastUrl:o}=e;if(!r?.opened)throw Error(`Cannot top up session: no open channel.`);if(!a)throw Error(`Cannot top up session: no challenge available. Make a request first.`);if(!o)throw Error(`Cannot top up session: no URL available. Call fetch(), sse(), or ws() first.`);let s=lD(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 jD(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:bD(s,u)}:i?{channel:u,state:_D({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function MD(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=kD(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,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:CE(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function ND(e){return e.method===jx.tempo&&e.intent===Mx.session}function PD(e){return ND(e)&&kx(e.request.methodDetails,Nx.sessionProtocol)===Px.v2}function FD(e){return kx(e.request.methodDetails,Nx.sessionSnapshot)}function ID(e,t,n){let r=e instanceof Request?e.headers:void 0;return{...t,headers:{...Aw(r),...Aw(t?.headers),[q.authorization]:n}}}function LD(e){try{let t=typeof location>`u`?void 0:location.href,n=e instanceof Request?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function RD(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function zD(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 BD(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);let r=await VD({challenge:e.challenge,context:{action:`topUp`,channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,input:e.input,signal:e.signal});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(q.paymentReceipt);return i?ME(i):void 0}async function VD(e){let t=async t=>e.fetch(LD(e.input),{method:`POST`,...e.signal?{signal:e.signal}:{},headers:{[q.authorization]:await e.createSessionCredential(t,e.context)}}),n=await t(e.challenge);if(n.status!==402)return n;let r=cS(n).find(PD);return r?t(r):n}async function HD(e){let t=UD({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,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,ID(e.input,e.init,t))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(q.paymentReceipt)&&await l(),u}function UD(e){let t=cS(e.response).find(PD);if(!t)return;let n=FD(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function WD(e){if(!e.lastUrl)throw Error(`Cannot close session: no URL available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or call fetch()/sse() before close().`);let t=e.target.challenge,n=e.signedCloseAmount,r=async(r,i=!1)=>{t=r,n=(i?e.resolveSignedCloseAmount?.(r):void 0)??e.signedCloseAmount;let a=await e.createSessionCredential(r,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(e.lastUrl,{method:`POST`,headers:{[q.authorization]:a}})},i=await r(e.target.challenge);if(i.status===402){let t=cS(i).find(PD);t&&(e.setChallenge?.(t),i=await r(t,!0))}if(!i.ok){let e=await zD(i),t=i.headers.get(q.wwwAuthenticate)??``;throw Error(`Close request failed with status ${i.status}${e?`: ${e}`:``}${t?` [${q.wwwAuthenticate}: ${t}]`:``}`)}let a=i.headers.get(q.paymentReceipt);if(!a)return;let o=ME(a);if(!o.txHash||!re.validate(o.txHash,{strict:!0})||re.size(o.txHash)!==32||!gD({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:e.getMinimumSpent?.()??0n,receipt:o}))throw Error(`Session close response included a mismatched payment receipt.`);return o}async function GD(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Aw(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!NE(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),KD(e,c,{onReceipt:r,signal:o},n)}function KD(e,t,n,r){if(!NE(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let i=r.getChallenge();return qD({onNeedVoucher:t=>QD({challenge:i,driver:r,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*qD(e){for await(let t of JD(e))t.data!==void 0&&(yield t.data)}async function*JD(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=YD(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=PE(i.replace(/\r\n|\r/g,`
227
+ `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,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 YD(e,t){for(let n=0;n<e.length;n++){let r=XD(e,n,t);if(!r)continue;let i=XD(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function XD(e,t,n){return e[t]===`
228
228
  `?1:e[t]===`\r`?e[t+1]===`
229
- `?2:t+1===e.length&&!n?0:1:0}function BD(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=LD({...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 VD(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await xD({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await AD({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function HD(e){let t=new URL(e.input.toString()),n=DD(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=sS(r).find(CD);if(!i)throw Error(`No payment challenge received from HTTP endpoint for this WebSocket URL. The server may not require payment or did not advertise a challenge.`);return{challenge:i,httpUrl:n,wsUrl:t}}async function UD(e){let t=await HD(e);return{...t,credential:await e.createSessionCredential(t.challenge,{})}}function WD(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:qS(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:vE(t)}}function GD(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function KD(e){if(!GD(e))return`received mismatched payment-close-ready frame`;let t=dE(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 qD(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!GD(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!aD({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function JD(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=new i(a,r?.protocols),s=WD({challenge:t,credential:n,socket:o});e.setSocketSession(s);let c=_D(o),l=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(o.readyState===eO.CONNECTING||o.readyState===eO.OPEN)&&o.close(tO,t)};return o.addEventListener(`close`,t=>{s.socket=null,s.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),c.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),o.addEventListener(`error`,()=>{c.emit(`error`,{type:`error`})}),o.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await XD({driver:e,failSocketFlow:l,managedEmit:c.emit,message:n,rawSocket:o,socketState:s})}),r?.signal?.addEventListener(`abort`,()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),o.close()},{once:!0}),await YD(o,c.emit,a),o.send(TE(n)),await e.waitForReceipt(),c.socket}function YD(e,t,n){return new Promise((r,i)=>{let a=()=>{e.removeEventListener(`error`,o),t(`open`,{type:`open`}),r()},o=()=>{e.removeEventListener(`open`,a),i(Error(`WebSocket connection to ${n} failed to open.`))};e.addEventListener(`open`,a,{once:!0}),e.addEventListener(`error`,o,{once:!0})})}async function XD(e){let t=DE(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`:ZD(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 QD(e,t.data);return;case`payment-receipt`:$D(e,t.data);return}}function ZD(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=KD({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 QD(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+nO&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await xD({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(TE(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function $D(e,t){let n=qD({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}var eO,tO,nO,rO=F((()=>{gS(),oT(),Px(),eC(),ME(),gD(),eO={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},tO=3008,nO=5e3})),iO,aO,oO,sO,cO,lO=F((()=>{iO={mainnet:4217,testnet:42431},aO={ousd:Se(iO.mainnet).address,usdc:M(we(iO.mainnet).address),pathUsd:Ce(iO.mainnet).address},oO={[iO.mainnet]:aO.usdc,[iO.testnet]:aO.pathUsd},sO=Object.freeze({[iO.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[iO.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})}),iO.mainnet,iO.testnet,cO={[iO.mainnet]:`https://rpc.tempo.xyz`,[iO.testnet]:`https://rpc.moderato.tempo.xyz`}})),uO=Ze({chainName:()=>EO,confirm:()=>xO,decodeMemo:()=>mO,fetchBalanceLines:()=>AO,fetchTokenInfo:()=>kO,fmtBalance:()=>SO,fmtChallengeValue:()=>hO,fmtRequestValue:()=>pO,isAgentEnvironment:()=>vO,isTempoAccount:()=>yO,isTestnet:()=>OO,link:()=>gO,mainnetTokens:()=>FO,networkRpcUrls:()=>MO,parseMethodOpts:()=>_O,pathUsd:()=>NO,pc:()=>X,printRequestHeaders:()=>dO,printResponseHeaders:()=>fO,prompt:()=>bO,resolveChain:()=>TO,resolveFundingNetwork:()=>wO,resolveRpcUrl:()=>CO,testnetTokens:()=>IO,usdc:()=>PO});function dO(e,t,n){let{pathname:r,host:i}=new URL(e);n(`> ${(t.method??`GET`).toUpperCase()} ${r} HTTP/1.1\n`),n(`> Host: ${i}\n`);for(let[e,r]of Object.entries(t.headers??{}))n(`> ${e}: ${r}\n`);n(`>
230
- `)}function fO(e,t){if(!t.include&&t.verbose<2||t.silent)return;let n=`HTTP/1.1 ${e.status} ${e.statusText}`,r=t.verbose>=2?process.stderr:process.stdout,i=t.verbose>=2?`< `:``;r.write(`${i}${n}\n`);for(let[t,n]of e.headers)r.write(`${i}${t}: ${n}\n`);r.write(t.verbose>=2?`<
229
+ `?2:t+1===e.length&&!n?0:1:0}function ZD(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=JD({...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 QD(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await MD({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await VD({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function $D(e){let t=new URL(e.input.toString()),n=RD(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=cS(r).find(PD);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 eO(e){e.signal?.throwIfAborted();let t=await $D(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function tO(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:YS(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:kE(t)}}function nO(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function rO(e){if(!nO(e))return`received mismatched payment-close-ready frame`;let t=SE(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 iO(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!nO(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!gD({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function aO(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=tO({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=OD(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===dO.CONNECTING||s.readyState===dO.OPEN)&&s.close(fO,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 sO({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await oO(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(IE(n)),await e.waitForReceipt(),l.socket}function oO(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 sO(e){let t=RE(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`:cO(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 lO(e,t.data);return;case`payment-receipt`:uO(e,t.data);return}}function cO(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=rO({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 lO(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+pO&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await MD({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(IE(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function uO(e,t){let n=iO({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}var dO,fO,pO,mO=F((()=>{_S(),_T(),Fx(),nC(),UE(),DD(),dO={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},fO=3008,pO=5e3})),hO,gO,_O,vO,yO,bO=F((()=>{hO={mainnet:4217,testnet:42431},gO={ousd:Ce(hO.mainnet).address,usdc:M(Te(hO.mainnet).address),pathUsd:we(hO.mainnet).address},_O={[hO.mainnet]:gO.usdc,[hO.testnet]:gO.pathUsd},vO=Object.freeze({[hO.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[hO.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})}),hO.mainnet,hO.testnet,yO={[hO.mainnet]:`https://rpc.tempo.xyz`,[hO.testnet]:`https://rpc.moderato.tempo.xyz`}})),xO=Qe({chainName:()=>LO,confirm:()=>MO,decodeMemo:()=>TO,fetchBalanceLines:()=>VO,fetchTokenInfo:()=>BO,fmtBalance:()=>NO,fmtChallengeValue:()=>EO,fmtRequestValue:()=>wO,isAgentEnvironment:()=>kO,isTempoAccount:()=>AO,isTestnet:()=>zO,link:()=>DO,mainnetTokens:()=>KO,networkRpcUrls:()=>UO,parseMethodOpts:()=>OO,pathUsd:()=>WO,pc:()=>X,printRequestHeaders:()=>SO,printResponseHeaders:()=>CO,prompt:()=>jO,resolveChain:()=>IO,resolveFundingNetwork:()=>FO,resolveRpcUrl:()=>PO,testnetTokens:()=>qO,usdc:()=>GO});function SO(e,t,n){let{pathname:r,host:i}=new URL(e);n(`> ${(t.method??`GET`).toUpperCase()} ${r} HTTP/1.1\n`),n(`> Host: ${i}\n`);for(let[e,r]of Object.entries(t.headers??{}))n(`> ${e}: ${r}\n`);n(`>
230
+ `)}function CO(e,t){if(!t.include&&t.verbose<2||t.silent)return;let n=`HTTP/1.1 ${e.status} ${e.statusText}`,r=t.verbose>=2?process.stderr:process.stdout,i=t.verbose>=2?`< `:``;r.write(`${i}${n}\n`);for(let[t,n]of e.headers)r.write(`${i}${t}: ${n}\n`);r.write(t.verbose>=2?`<
231
231
  `:`
232
- `)}function pO(e,t,n){if(jO.has(e)&&typeof t==`string`)return`${t} ${X.dim(`(${SO(BigInt(t),n.tokenSymbol,n.tokenDecimals)})`)}`;if(e===`chainId`&&typeof t==`number`){let e=EO({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?gO(`${n.explorerUrl}/address/${t}`,t):t:typeof t==`string`&&/^https?:\/\//.test(t)?X.link(t,t):String(t)}function mO(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 hO(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 gO(e,t){return X.link(e,t)}function _O(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 vO(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 yO(e){return e.startsWith(`tempo:`)}function bO(e){let t=P.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 xO(e,t=!1){let n=P.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 SO(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?X.dim(X.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):X.dim(t);return`${a?`${o}.${a}`:o} ${s}`}function CO(e,t={}){return e??(t.network?MO[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}function wO(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 TO(e={}){let t=CO(e.rpcUrl,{network:e.network});if(!t)return ve;let{getChainId:n}=await import(`viem/actions`),r=await n(j({transport:ue(t)})),i=Object.values(await import(`viem/tempo/chains`)).filter(e=>typeof e==`object`&&!!e&&`id`in e&&e.id===r),a=i.find(e=>`serializers`in e&&e.serializers)??i[0];if(!a)throw Error(`Unknown chain ID ${r} from RPC ${t}`);return a}function EO(e){return{[ve.id]:`mainnet`,[ye.id]:`testnet`}[e.id]??e.name}function DO(e){return typeof e==`bigint`?e:e.amount}function OO(e){return e.id!==ve.id}async function kO(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(DO).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 AO(e,t){if(t?.chain){let n=j({chain:t.chain,transport:ue(t.rpcUrl)}),r=t.chain.blockExplorers?.default?.url,i=X.dim(`(${EO(t.chain)})`);return OO(t.chain)?(await Promise.all(IO.map(t=>kO(n,t,e)))).filter(e=>e.balance>0n).map(e=>`${SO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`):(await Promise.all(FO.map(t=>kO(n,t,e)))).map(e=>`${SO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`)}let n=j({chain:ve,transport:ue(CO())}),r=ve.blockExplorers?.default?.url,i=(await Promise.all(FO.map(t=>kO(n,t,e)))).map(e=>SO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token}));if(t?.includeTestnet!==!1){let t=j({chain:ye,transport:ue()}),n=ye.blockExplorers?.default?.url,r=await Promise.all(IO.map(n=>kO(t,n,e)));for(let e of r)e.balance>0n&&i.push(`${SO(e.balance,e.symbol,e.decimals,{explorerUrl:n,token:e.token})} ${X.dim(`(testnet)`)}`)}return i}var X,jO,MO,NO,PO,FO,IO,LO=F((()=>{lO(),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}}})(),jO=new Set([`amount`,`suggestedDeposit`,`minVoucherDelta`]),MO={mainnet:cO[iO.mainnet],testnet:cO[iO.testnet]},NO=`0x20c0000000000000000000000000000000000000`,PO=`0x20C000000000000000000000b9537d11c60E8b50`,FO=[NO,PO],IO=[`0x20c0000000000000000000000000000000000000`,`0x20c0000000000000000000000000000000000001`,`0x20c0000000000000000000000000000000000002`,`0x20c0000000000000000000000000000000000003`]}));function RO(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:XO}function zO(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function BO(e){return new I({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 VO(e){if(e&&zO(e,`secret-tool`))throw BO(e)}function HO(e,t){return new Promise(n=>{m.execFile(e,t,{timeout:RO()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function UO(){let e=c.join(process.env.XDG_CONFIG_HOME||c.join(b.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 WO(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:UO().get())}function GO(e=`main`){let t=YO;return{async list(){let e=b.platform();if(e===`darwin`){let{stdout:e,error:n}=await HO(`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 HO(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(VO(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=b.platform();if(n===`darwin`){let{stdout:n,error:r}=await HO(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await HO(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return VO(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=b.platform();if(r===`darwin`){await HO(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await HO(`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(),RO());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(zO(e,`secret-tool`)?BO(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=b.platform();if(n===`darwin`){await HO(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await HO(`secret-tool`,[`clear`,`service`,t,`account`,e]);VO(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function KO(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=WO(e),i=await GO(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function qO(e){let t=WO(e);if(!process.env.MPPX_PRIVATE_KEY?.trim()&&yO(t))throw new I({code:`UNSUPPORTED_ACCOUNT`,message:`Persistent sessions require an mppx account or MPPX_PRIVATE_KEY.`,exitCode:2});return KO(e).catch(e=>{throw new I({code:`ACCOUNT_NOT_FOUND`,message:e instanceof Error?e.message:`No account found.`,exitCode:69,...e instanceof Error&&{cause:e}})})}async function JO(e){return(await KO(e)).account}var YO,XO,ZO=F((()=>{LO(),YO=`mppx`,XO=1e4}));rO(),ZO();const QO=[[`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 $O(e=process.env){return QO.find(([t])=>e[t])?.[1]}const ek=Symbol(`mppx.x402.asset`);function tk(e){return{[ek]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function nk(e,t){let n=e(t.chainId);return tk({address:n.address,decimals:n.decimals,network:fk(t.chainId),transfer:mk(t.transfer,n)})}const rk={USDC:tk({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},ik={USDC:tk({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},ak={USDC:tk({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:tk({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},ok={USDC:tk({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function sk(e){return typeof e!=`object`||!e?!1:e[ek]===!0}function ck(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function lk(e){return typeof e==`string`}function uk(e,t){if(sk(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(ck(e)){let n=e.addresses[pk(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function dk(e,t,n){let r=uk(e,n);return r?M(r.address)===M(t):!1}function fk(e){return`eip155:${e}`}function pk(e){return Number(e.slice(7))}function mk(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 hk=Ze({base:()=>rk,baseSepolia:()=>ik,celo:()=>ak,celoSepolia:()=>ok,define:()=>tk,fromToken:()=>nk,isAsset:()=>sk,isRawAddress:()=>lk,isToken:()=>ck,matches:()=>dk,resolve:()=>uk,toChainId:()=>pk,toNetwork:()=>fk}),gk=Ze({base:()=>_k,baseSepolia:()=>vk,celo:()=>yk,celoSepolia:()=>bk});const _k=8453,vk=84532,yk=42220,bk=11142220;Rx();function xk(e){let t=[Lx(e.accepted),Lx(e.resource),Lx(e.extensions)].join(`|`);return ne.sha256(te.fromString(t),{as:`Hex`})}ew(),DC();async function Sk(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=iC(n);if(Ek(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?Ok(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:M(t.address),nonce:i?.mppx?xk({accepted:r,extensions:i,resource:n.resource}):Ak(),to:M(r.payTo),validAfter:(c-600).toString(),validBefore:(c+r.maxTimeoutSeconds).toString(),value:r.amount},u=await t.signTypedData({domain:{chainId:Tk(r.network),name:o,verifyingContract:M(r.asset),version:s},message:{...l,value:BigInt(l.value),validAfter:BigInt(l.validAfter),validBefore:BigInt(l.validBefore)},primaryType:`TransferWithAuthorization`,types:wk});return QC({accepted:r,...i?{extensions:i}:{},payload:{authorization:l,signature:u},...n.resource?{resource:n.resource}:{},x402Version:2})}function Ck(e){let t=e.challenge.request,n;try{n=iC(t),Ek(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 wk={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 Tk(e){return Number(e.slice(sC.length))}function Ek(e,t){let n=Tk(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=>lk(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=M(t.asset);if(!r.some(n=>dk(n,e,t.network)))throw Error(`x402 exact currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`x402 exact amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=Dk(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>N(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function Dk(e,t){let n=e.currencies??e.assets,r=M(t.asset),i=n?.find(e=>dk(e,r,t.network)),a=i?uk(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function Ok(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:kk()}}}:e}function kk(){return jk().slice(2)}function Ak(){return jk()}function jk(){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(``)}`}Xx();const Mk=[`authorization`],Nk=J.string().check(J.regex(/^\d+$/,`Invalid atomic amount`));J.object({name:J.string().check(J.minLength(1)),version:J.string().check(J.minLength(1))});const Pk=J.object({chainId:J.number(),credentialTypes:J.optional(J.array(J.enum(Mk)).check(J.minLength(1))),decimals:J.optional(J.number()),permit2Address:J.optional(Gx()),splits:J.optional(J.array(J.object({amount:Nk,recipient:Gx()})))});J.object({amount:Nk,currency:Gx(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:Pk,recipient:Gx()});const Fk=J.object({amount:Bx(),chainId:J.number(),currency:Gx(),credentialTypes:J.optional(J.array(J.enum(Mk)).check(J.minLength(1))),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),permit2Address:J.optional(Gx()),recipient:Gx(),splits:J.optional(J.array(J.object({amount:Nk,recipient:Gx()})))}),Ik=J.object({from:Gx(),nonce:Kx(),signature:Jx(),to:Gx(),type:J.literal(`authorization`),validAfter:Nk,validBefore:Nk,value:Nk}),Lk={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 Rk(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function zk(e){return ne.keccak256(te.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function Bk(e){return`eip155:${e}`}function Vk(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}qT(),Xx();const Hk=GT({name:`evm`,intent:`charge`,schema:{credential:{payload:Ik},request:J.pipe(Fk,J.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...c})=>({...c,amount:N(e,i).toString(),currency:M(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:M(a)}:{},...s?{splits:s}:{}},recipient:M(o)})))}});eC(),qT(),ES(),Xx();function Uk(e){return KT(Hk,{canHandleChallenge({challenge:t}){return!Wk(t)||Ck({challenge:t,config:e})},context:J.object({account:J.optional(J.custom())}),async createCredential({challenge:t,context:n}){if(Wk(t))return Sk({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(Gk(e,i),!i.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(i.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`);let a=Kk(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return ZS(XS({challenge:t,payload:{from:M(r.address),nonce:zk(t),signature:await r.signTypedData({domain:Rk({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:M(r.address),nonce:zk(t),to:M(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Lk}),to:M(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:Vk({address:M(r.address),chainId:i.methodDetails.chainId})}))}})}function Wk(e){return wS(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function Gk(e,t){let n=t.methodDetails.chainId,r=Bk(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=>lk(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=M(t.currency);if(!i.some(t=>dk(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=qk(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>N(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function Kk(e,t){let n=e.currencies??e.assets,r=M(t.currency),i=Bk(t.methodDetails.chainId),a=n?.find(e=>dk(e,r,i)),o=a?uk(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;throw Error(`EVM authorization requires token name and version.`)}function qk(e,t){let n=e.currencies??e.assets,r=M(t.currency),i=Bk(t.methodDetails.chainId),a=n?.find(e=>dk(e,r,i)),o=a?uk(a,i):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function Jk(e){return[Jk.charge(e)]}(function(e){e.charge=Uk,e.assets=hk,e.chains=gk})(Jk||={});function Yk(e){return e}var Xk=F((()=>{}));ES(),Xk();function Zk(){return Yk({method:`evm`,supports:e=>e.method===`evm`&&!wS(e),async setup({challenge:e}){let t=e.request,n=t.methodDetails,r=n?.chainId,i=r?Qk(r):void 0,a=t.currency,o=await JO(),s=[...Object.values(rk),...Object.values(ik),...Object.values(ak),...Object.values(ok)],c=a??``;if(i&&a)try{let e=j({chain:i,transport:ue()}),t=await De(e,{address:a,abi:se,functionName:`symbol`});t&&(c=t)}catch{}return{tokenSymbol:c,tokenDecimals:n?.decimals??6,explorerUrl:i?.blockExplorers?.default?.url,methods:[...Jk({account:o,currencies:s})]}}})}function Qk(e){return Object.values(Be).find(t=>t.id===e)}function $k(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}Xx();const eA=J.object({customer:J.optional(J.string().check(J.minLength(1))),hooks:J.optional(J.object({inputs:J.object({tax:J.object({calculation:J.string().check(J.minLength(1))})})})),metadata:J.optional(J.record(J.string(),J.string())),receipt_email:J.optional(J.string().check(J.minLength(1)))}),tA=J.custom(e=>typeof e==`function`),nA=J.union([eA,tA]);qT(),Xx();const rA=GT({name:`stripe`,intent:`charge`,schema:{credential:{payload:J.object({externalId:J.optional(J.string()),spt:J.string()})},request:J.pipe(J.object({amount:Bx(),currency:J.string(),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),metadata:J.optional(J.record(J.string(),J.string())),networkId:J.string(),paymentIntentOptions:J.optional(nA),paymentMethodTypes:J.array(J.string()).check(J.minLength(1)),recipient:J.optional(J.string())}),J.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:$k(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});eC(),qT(),Xx();function iA(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return KT(rA,{context:J.object({paymentMethod:J.optional(J.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 ZS({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function aA(e){return[iA(e)]}(function(e){e.charge=iA})(aA||={}),Dx(),LO(),Xk();function oA(){return Yk({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=cA(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 I({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:[aA.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=sA(a),l=process.env.MPPX_STRIPE_SPT_URL?process.env.MPPX_STRIPE_SPT_URL:c?`https://api.stripe.com/v1/test_helpers/shared_payment/granted_tokens`:`https://api.stripe.com/v1/shared_payment/issued_tokens`;if(r){let e=c?`seller_details[network_id]`:`seller_details[network_business_profile]`;s.set(e,r)}if(o)for(let[e,t]of Object.entries(o))s.set(`metadata[${e}]`,t);let u={Authorization:`Basic ${btoa(`${a}:`)}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":`2026-07-29.preview`},d=await globalThis.fetch(l,{method:`POST`,headers:u,body:s});if(!d.ok){let a=await d.json();if(c&&(o||r)&&a.error.message.includes(`Received unknown parameter`)){let r=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()});if(d=await globalThis.fetch(l,{method:`POST`,headers:u,body:r}),!d.ok){let e=await d.json();throw new I({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${e.error.message}`,exitCode:77})}}else throw new I({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&&sA(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function sA(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function cA(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 lA(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 ge(r)}}var uA=F((()=>{}));function dA(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}var fA=F((()=>{}));function pA(e,t={}){return ue(e.url,{fetchFn:e.fetch,fetchOptions:{headers:dA(e)},...t})}function mA(e){let{chain:t,getClient:n,remoteFeePayer:r,rpcUrl:i}=e;return n?!t?.serializers&&!r?n:async e=>{let i=await n(e),a=i;if(r&&i.transport.key!==`feePayer`){let e=i.request.bind(i),t=ze(ae({request:t=>e(t)},{retryCount:0}),pA(r,{retryCount:i.transport.retryCount}))({account:i.account,chain:i.chain,pollingInterval:i.pollingInterval,retryCount:0}),n=ie({...t.config,retryCount:0},t.value);a=Object.assign({},i,{request:n.request,transport:{...n.config,...n.value}})}return!t?.serializers||a.chain?.serializers?.transaction?a:Object.assign({},a,{chain:{...t,...e.chainId===void 0?{}:{id:e.chainId},...a.chain,formatters:a.chain?.formatters??t.formatters,prepareTransactionRequest:a.chain?.prepareTransactionRequest??t.prepareTransactionRequest,serializers:a.chain?.serializers?.transaction?a.chain.serializers:t.serializers}})}:({chainId:e})=>{if(!i)throw Error("No `rpcUrl` provided.");let n=e||Number(Object.keys(i)[0]),a=i[n];if(!a)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let o=r?ze(ue(a),pA(r)):ue(a);return j({chain:_A[n]??{...t,id:n},transport:o})}}function hA(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 gA(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}var _A,vA=F((()=>{fA(),_A={[ve.id]:ve,[ye.id]:ye}}));function yA(e){let t=ne.keccak256(te.fromString(e),{as:`Hex`});return re.toBytes(re.slice(t,0,10))}function bA(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(re.toBytes(SA),0),i[4]=CA,i.set(yA(t),5),n&&i.set(yA(n),15),i.set(xA(r),25),re.fromBytes(i)}function xA(e){let t=ne.keccak256(te.fromString(e),{as:`Hex`});return re.toBytes(re.slice(t,0,7))}var SA,CA,wA=F((()=>{SA=re.slice(ne.keccak256(te.fromString(`mpp`),{as:`Hex`}),0,4),CA=1}));function TA(e,t){return Ge.resolve(e).toLowerCase()===Ge.resolve(t).toLowerCase()}var EA=F((()=>{}));async function DA(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t,s=a.filter(e=>!TA(e,i)),c=await Promise.allSettled([De(e,Fe.token.getBalance.call(e,{account:n,token:i})),...s.map(t=>De(e,Fe.token.getBalance.call(e,{account:n,token:t})))]),l=c[0];if(!(l.status===`fulfilled`&&l.value>=r)){for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let a=n.value;if(a<=0n)continue;let l=s[t];try{let t=await Fe.dex.getBuyQuote(e,{tokenIn:l,tokenOut:i,amountOut:r});if(a>=t){let n=t+t*BigInt(Math.round(o*100))/kA;return[Fe.token.approve.call(e,{amount:n,spender:Ie.stablecoinDex,token:l}),Fe.dex.buy.call({tokenIn:l,tokenOut:i,amountOut:r,maxAmountIn:n})]}}catch{}}throw new jA({currency:i})}}function OA(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...t.filter(t=>!e.tokenIn.some(e=>TA(e,t)))]:t,slippage:e.slippage??1}:!1}var kA,AA,jA,MA=F((()=>{EA(),lO(),kA=10000n,AA=[aO.pathUsd,aO.usdc],jA=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}}}));function NA(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:e.amount,memo:e.memo,recipient:e.recipient}))]}var PA=F((()=>{}));function FA(e,t,n){t&&(n&&!n.some(e=>TA(e,t))||e.some(e=>TA(e,t))||e.push(t))}async function IA(e,t,n){try{return(await Fe.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function LA(e){let t=e.chain?.feeToken;if(t)return Le.toAddress(t);let n=e.chain?.id;return n?oO[n]:void 0}function RA(e){let t=[];return FA(t,aO.pathUsd),FA(t,oO[e]),t}async function zA(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])FA(o,e,n);if(FA(o,await Fe.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),FA(o,LA(i),n),!a)for(let e of r??[])FA(o,e,n);for(let e of o)if(await IA(i,t,e))return e;return o[0]}var BA=F((()=>{EA(),lO()}));function VA(e){if(e!==void 0)return sO[e]}function HA(e){let t=VA(e.chainId);return!!t&&de(e.currency,{strict:!1})&&fe(e.currency,t.token)}function UA(e){let t=VA(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:Ne.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:oe({abi:GA,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 WA(e,t){let n=UA(t);if(n)try{return await De(e,Fe.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}}var GA,KA=F((()=>{lO(),GA=pe([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`])}));function qA(e){return{name:`MPP`,version:`3`,chainId:e}}function JA(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function YA(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:qA(n),types:QA,primaryType:ZA,message:JA({account:t,challengeId:r,realm:i})}}function XA(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}var ZA,QA,$A=F((()=>{ZA=`Proof`,QA={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]}}));function ej(e={}){let{clientId:t}=e,n=mA({chain:ve,getClient:e.getClient,rpcUrl:cO}),r=lA({account:e.account});return KT(oE,{context:tj,async createCredential({challenge:i,context:a}){let o=i.request.methodDetails?.chainId;if(e.expectedChainId!==void 0&&o!==void 0&&o!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${o}.`);(o!==void 0||e.allowedChainIds?.length===0)&&gA(e.allowedChainIds,o);let s=o??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),c=await n({chainId:s});hA(c,s);let l=s??c.chain?.id;if(gA(e.allowedChainIds,l),l===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:u}=i,{amount:d,methodDetails:f}=u,p=f?.supportedModes??[`pull`,`push`],m=r(c,a),h=async t=>await e.resolveAccount?.({account:m,chainId:l,operation:t})??m;if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!u.recipient||!t.has(u.recipient.toLowerCase()))throw Error(`Unexpected primary recipient: ${u.recipient}`);let n=f?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(BigInt(d)===0n){let e=await h({kind:`signPaymentProof`});return ZS({challenge:i,payload:{signature:await je(c,{account:e,...YA({account:e.address,chainId:l,challengeId:i.id,realm:i.realm})}),type:`proof`},source:XA({address:e.address,chainId:l})})}let g=u.currency,_=HA({chainId:l,currency:g}),v=bA({challengeId:i.id,clientId:t,serverId:i.realm}),y=NA({amount:d,methodDetails:{...f,memo:v},recipient:u.recipient}),b=y.map(e=>Fe.token.transfer.call(c,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:g})),x=OA(a?.autoSwap??e.autoSwap,AA),S=f?.machineTokenEnabled===!0?UA({chainId:l,currency:g,transfers:y}):void 0,C=m,w;if(S){let e=await(async()=>{try{return await h({calls:S.calls,kind:`executeCalls`})}catch{return}})();e&&(w=await WA(c,{account:e.address,chainId:l,currency:g,transfers:y}),w&&(C=e))}let T;w||(C=await h({kind:`executeCalls`,...x?{}:{calls:b}}),T=x?await DA(c,{account:C.address,amountOut:BigInt(d),tokenOut:g,tokenIn:x.tokenIn,slippage:x.slippage}):void 0);let ee=w?.calls??[...T??[],...b],E=RA(l),D=w||_?await zA({account:C.address,allowedTokens:E,candidateTokens:E,client:c,prioritizeCandidates:!0}):void 0,O=(()=>{let t=a?.mode??e.mode;if(t){if(!p.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=C.type===`json-rpc`?`push`:`pull`;return p.includes(n)?n:p[0]})(),k=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!i.expires)return e;let t=Math.floor(new Date(i.expires).getTime()/1e3);return Math.min(e,t)})();if(O===`push`){let{receipts:e}=C.type===`local`?{receipts:[await ke(c,{account:C,calls:ee,...D?{feeToken:D}:{},nonceKey:`expiring`,validBefore:k})]}:await Oe(c,{account:C,...D?{capabilities:{feeToken:D}}:{},calls:ee,experimental_fallback:ee.length===1,forceAtomic:ee.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return ZS({challenge:i,payload:{hash:t,type:`hash`},source:XA({address:C.address,chainId:l})})}let te=await Ee(c,{account:C,calls:ee,...D?{feeToken:D}:{},nonceKey:`expiring`,validBefore:k});if(te.gas=(te.gas??0n)+5000n,f?.feePayer){let e=te;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return ZS({challenge:i,payload:{signature:await Ae(c,te),type:`transaction`},source:XA({address:C.address,chainId:l})})}})}var tj,nj=F((()=>{eC(),qT(),uA(),vA(),Xx(),wA(),MA(),PA(),lO(),BA(),KA(),$A(),lE(),tj=J.object({account:J.optional(J.custom()),autoSwap:J.optional(J.custom()),mode:J.optional(J.enum(XT))})}));function rj(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function ij(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 aj(e){return Ke.encodeForSigning(e)}function oj(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function sj(e,t){return ne.keccak256(re.concat(aj(e),t.sender))}var cj=F((()=>{ME()})),lj,uj,dj,fj,pj=F((()=>{lj=[{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`}],uj=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],dj={name:`descriptor`,type:`tuple`,components:lj},fj=[{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:[dj,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[dj,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[dj,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[dj],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[dj],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[dj],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:lj},{name:`state`,type:`tuple`,components:uj}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:uj}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:uj}]},{type:`function`,name:`computeChannelId`,stateMutability:`view`,inputs:[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`getVoucherDigest`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`domainSeparator`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`authorizedSigner`,type:`address`},{name:`salt`,type:`bytes32`},{name:`expiringNonceHash`,type:`bytes32`},{name:`deposit`,type:`uint96`}]},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`cumulativeAmount`,type:`uint96`},{name:`deltaPaid`,type:`uint96`},{name:`newSettled`,type:`uint96`}]},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`additionalDeposit`,type:`uint96`},{name:`newDeposit`,type:`uint96`}]},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`closeGraceEnd`,type:`uint256`}]},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`settledToPayee`,type:`uint96`},{name:`refundedToPayer`,type:`uint96`}]},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0}]}]}));function mj(e,t){return{name:Sj,version:Cj,chainId:t,verifyingContract:e}}function hj(e,t){return He.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function gj(e,t,n){return e.toLowerCase()===He.address.toLowerCase()?hj(t,n):le({domain:mj(e,t),types:wj,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function _j(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function vj(e,t){return Pe.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function yj(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===He.address.toLowerCase())try{return await vj(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return je(e,{account:t,domain:mj(r,i),types:wj,primaryType:`Voucher`,message:n})})(),o=We.from(a);if(!_j(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return We.serialize(o)}async function bj(e,t,n,r,i){let a=await je(e,{account:t,domain:mj(r,i),types:Tj,primaryType:`CloseAuthorization`,message:n}),o=We.from(a);if(!_j(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return We.serialize(o)}function xj(e,t,n,r){try{let i=We.from(n.signature);if(!_j(i.type)||We.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=gj(e,t,n),o=We.extractAddress({payload:a,signature:i});return We.verify(i,{address:o,payload:a})&&TA(o,r)}catch{return!1}}var Sj,Cj,wj,Tj,Ej=F((()=>{EA(),Sj=`TIP20 Channel Reserve`,Cj=`1`,wj={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},Tj={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]}}));function Dj(e){return typeof e==`object`&&!!e}function Oj(e){return typeof e==`string`&&de(e,{strict:!1})?e:void 0}function kj(e){return Oj(e.accessKeyAddress)}function Aj(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(re.random(8))%e)}function jj(e){return kj(e)??e.address}async function Mj(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return Ee(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function Nj(e,t){return await Ae(e,t)}function Pj(e,t,n=!1){let r=e.request.methodDetails,i=Dj(r)?Oj(r.escrowContract)??Oj(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!Ij(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!Ij(i,a)?i:a}function Fj(e,t,n,r){return ZS({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function Ij(e,t){return e.toLowerCase()===t.toLowerCase()}async function Lj(e,t,n,r,i,a=jE){let o=ij({...n,chainId:i,escrow:a}),s=fE(r),c=await yj(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function Rj(e,t,n,r,i,a=jE){let o=await Lj(e,t,n,r,i,a),s=await bj(e,t,{channelId:o.channelId,cumulativeAmount:fE(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function zj(e,t,n){let r=jj(t),i=n.escrow??`0x4d50500000000000000000000000000000000000`,a=n.operator??`0x0000000000000000000000000000000000000000`,o=re.random(32),s=fE(n.deposit),c=fE(n.initialAmount),l=oe({abi:fj,functionName:`open`,args:[n.payee,a,n.token,s,o,r]}),u=await Nj(e,await Mj(e,{account:t,calls:[...n.prefixCalls??[],{to:i,data:l}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),d=Re.deserialize(u),f={authorizedSigner:r,expiringNonceHash:sj(oj({...n.feePayer?{feePayer:!0}:{},transaction:d}),{sender:t.address}),operator:a,payee:n.payee,payer:t.address,salt:o,token:n.token},p=ij({...f,chainId:n.chainId,escrow:i});return{action:`open`,type:`transaction`,channelId:p,transaction:u,signature:await yj(e,t,{channelId:p,cumulativeAmount:c},i,n.chainId),descriptor:f,cumulativeAmount:c.toString(),authorizedSigner:f.authorizedSigner}}async function Bj(e,t,n,r,i,a,o=jE,s=[],c=n.token){let l=ij({...n,chainId:i,escrow:o}),u=fE(r);return{action:`topUp`,type:`transaction`,channelId:l,transaction:await Nj(e,await Mj(e,{account:t,calls:[...s,{to:o,data:oe({abi:fj,functionName:`topUp`,args:[n,u]})}],feePayer:a,feeToken:c,validAfter:Aj()})),descriptor:n,additionalDeposit:u.toString()}}var Vj=F((()=>{eC(),cj(),pj(),ME(),Ej()}));function Hj(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Uj(e){return Hj({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function Wj(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Uj(t),t)},delete(t){e.delete(t)}}}function Gj(e){return{...e,cumulativeAmount:e.cumulativeAmount.toString(),deposit:e.deposit.toString()}}function Kj(e){return{...e,cumulativeAmount:BigInt(e.cumulativeAmount),deposit:BigInt(e.deposit)}}var qj=F((()=>{}));function Jj(e){if(e<0n||e>Zj)throw new Y({reason:`amount exceeds uint96 range`})}async function Yj(e,t,n=jE,r){return Xj(await De(e,{address:n,abi:fj,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function Xj(e){return Jj(e.settled),Jj(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}var Zj,Qj=F((()=>{bS(),pj(),ME(),Zj=2n**96n-1n}));function $j(e){return`cumulativeAmount`in e}function eM(e){if($j(e))return BigInt(e.cumulativeAmount)}async function tM(e,t){t.opened?await e.store.set(t):await e.store.delete(Uj(t)),e.notifyUpdate(t)}async function nM(e,t,n){let r=eM(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 tM(e,i))}function rM(e){return e?.action!==void 0}function iM(e){return rM(e)&&e.descriptor!==void 0}function aM(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 N(i,t)}function oM(e,t,n,r){let i=aM(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function sM(e){return typeof e==`object`&&!!e}function cM(e){return typeof e==`string`&&de(e,{strict:!1})?e:void 0}function lM(e){let t=e.request.methodDetails;return sM(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:cM(t.escrowContract),escrow:cM(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:cM(t.feeToken),operator:cM(t.operator),sessionSnapshot:Ox(t,Mx.sessionSnapshot)}:{}}function uM(e,t){if(typeof e==`string`&&de(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function dM(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function fM(e){return typeof e==`string`?e:void 0}async function pM(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=lM(n);(o.chainId!==void 0||i?.length===0)&&gA(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});hA(c,s);let l=s??c.chain?.id;if(gA(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=Pj(n,r,t),d=uM(n.request.recipient,`recipient`),f=uM(n.request.currency,`currency`);return{amount:dM(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:Hj({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:fM(n.request.suggestedDeposit),token:f}}async function mM(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=Yj}=e,o=ij({...r,chainId:i.chainId,escrow:i.escrow});hM({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 hM(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(!Ij(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!Ij(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!Ij(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!Ij(rj(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function gM(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function _M(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=aM(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function vM(e){let{account:t,client:n,readChannelState:r,snapshot:i}=e,a=i.highestVoucher;if(!a)throw Error(`session snapshot is missing its highest signed voucher`);if(a.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let o=BigInt(i.acceptedCumulative),s=BigInt(a.cumulativeAmount),c=BigInt(i.requiredCumulative),l=BigInt(i.deposit),u=BigInt(i.settled),d=BigInt(i.spent);if(s!==o)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(d>o)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(u>l)throw Error(`session snapshot settled amount exceeds deposit`);if(!xj(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},rj(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await mM({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:jj(t),token:i.descriptor.token},readChannelState:r}),p=[o,c,f.state.settled].reduce((e,t)=>t>e?t:e,0n);if(p>f.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:f.channelId,cumulativeAmount:p,deposit:f.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:d}}function yM(e,t){return Ij(e.address,t.payer)?Ij(jj(e),rj(t)):!1}function bM(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(rM(r)){if(!iM(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=gM({context:r,snapshot:o.snapshot});return!n&&s&&yM(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&yM(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 xM(e,t,n=!1){switch(e.type){case`open`:return CM(e,t,n);case`recover`:return wM(e,t);case`voucher`:return TM(e,t);case`manual`:return EM(e,t,n)}}async function SM(e,t){if(e)return await DA(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage})}async function CM(e,t,n){let{account:r,resolved:i}=e,a=$E({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await zj(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 SM(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await tM(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function wM(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await mM({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:jj(n),token:o.token}}),l=_M({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`);tD(l,a);let u=await Lj(o.client,n,s,l,o.chainId,o.escrow);return await tM(t,{channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function TM(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;tD(a,e.maxDeposit);let o=await Lj(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await tM(t,r),o}async function EM(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=ij({...s,chainId:o.chainId,escrow:o.escrow});hM({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:jj(r),token:o.token});let l=await DM({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await nM(t,o.key,l),l}async function DM(e,t){switch(e.context.action){case`open`:return OM(e);case`topUp`:return kM(e,t);case`voucher`:return AM(e);case`close`:return jM(e)}}async function OM(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=oM(r,i,`cumulativeAmount`,`open`),c=await Lj(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 kM(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=oM(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:Bj(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await SM(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function AM(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Lj(a.client,t,i,oM(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function jM(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Rj(a.client,t,i,oM(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}var MM,NM,PM,FM=F((()=>{Px(),vA(),Xx(),MA(),Qj(),cj(),Ej(),Vj(),qj(),gD(),MM=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),NM=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),PM=J.object({account:J.optional(J.custom()),autoSwap:J.optional(J.custom()),action:J.optional(J.enum([`open`,`topUp`,`voucher`,`close`])),channelId:J.optional(NM),cumulativeAmount:J.optional(Bx()),cumulativeAmountRaw:J.optional(J.string()),transaction:J.optional(MM),descriptor:J.optional(J.custom()),additionalDeposit:J.optional(Bx()),additionalDepositRaw:J.optional(J.string()),depositRaw:J.optional(J.string())})}));async function IM(e,t){let n=BM.get(e)??new Map;BM.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 LM(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function RM(e,t,n){try{let r=e.response?.headers.get(q.paymentReceipt);if(r){let e=xE(r);if(e.challengeId===t.id&&LM(n,e))return!0}}catch{}return e.challenges?.some(e=>CD(e)?LM(n,wD(e)):!1)??!1}function zM(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a=6,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=mA({chain:Ve,getClient:c,rpcUrl:cO}),m=lA({account:t}),h=l===void 0?void 0:N(l,a),g=u===void 0?void 0:N(u,a),_=i??Wj(),v={store:_,notifyUpdate:e=>d?.(e)},y=async(e,t,n)=>{let r=m(e.client,t),i=t?.action?t.descriptor:n?.descriptor??gM({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:rj(i)}:{}}})??r},b=async(e,t,n)=>bM({account:await y(e,t,n),entry:n,context:t,decimals:a,maxDeposit:h,resolved:e}),x=KT(sE,{canHandleChallenge:({challenge:e})=>CD(e),context:PM,async createCredential(e){let{challenge:t,context:i}=e,a=await pM({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:p}),c=mw(e),l=()=>{};try{let e=!rM(i)&&i?.descriptor===void 0;e&&(l=await IM(_,a.key),c&&(await _.get(a.key))?.opened&&await c.prepare());let n=await _.get(a.key),o=await b(a,i,n);if(!e&&c&&o.type===`open`){l=await IM(_,a.key);let e=await _.get(a.key);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await _.get(a.key)),o=await b(a,i,n))}let s,u=c&&o.type===`open`?{store:{get:e=>_.get(e),async set(e){s=e},delete:e=>_.delete(e)},notifyUpdate(){}}:v,d=await Fj(t,await xM(o,u,OA(i?.autoSwap??r,AA)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||RM(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await _.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await _.set(e),v.notifyUpdate(e))}return!0}finally{l()}}}else l();return d}catch(e){throw l(),e}}}),S=async({challenge:e,channel:t,deposit:n,fetch:r,input:i,requiredCumulative:a,signal:o})=>{let s=t.deposit>n?t.deposit:n,c=eD({deposit:s,maxDeposit:h,requiredCumulative:a,suggestedDeposit:e.request.suggestedDeposit===void 0?void 0:BigInt(e.request.suggestedDeposit),topUpAmount:g});c>0n&&await kD({additionalDeposit:c,challenge:e,channel:t,channelId:t.channelId,createSessionCredential:(e,t)=>x.createCredential({challenge:e,context:t}),fetch:r,input:i,signal:o});let l=s+c;if(l===t.deposit)return;let u=await _.get(Uj(t)),d=u?.channelId.toLowerCase()===t.channelId.toLowerCase()?u:t,f={...d,deposit:d.deposit>l?d.deposit:l};await _.set(f),v.notifyUpdate(f)};return ow(x,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!CD(e))return;let c=t===void 0?void 0:PM.parse(t);if(rM(c))return;let l=await pM({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:p}),u=await _.get(l.key);if(!u?.opened)return;let d=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,f=u.cumulativeAmount+vE(e),m=d?BigInt(d.requiredCumulative):f,h=m>f?m:f,g=d?BigInt(d.deposit):u.deposit,v=g>u.deposit?g:u.deposit;h<=v&&v===u.deposit||!yM(await y(l,c,u),u.descriptor)||await S({challenge:e,channel:u,deposit:v,fetch:r,input:i,requiredCumulative:h,signal:a})}),dw(x,async({challenge:e,credential:t,fetch:r,headers:i,input:a,refetch:c,response:l,signal:u})=>{if(!CD(e))return l;if(!SE(l))return _E(qS(t).payload).action===`open`&&i.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await c?.()??l:l;let d=(await pM({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:p})).key,f=await _.get(d),m={assertVoucherWithinLocalLimit:e=>tD(e,h),createSessionCredential:(e,t)=>x.createCredential({challenge:e,context:t}),fetch:r,getChannel:()=>f??null,async topUpIfNeeded({deposit:t,requiredCumulative:n,signal:i}){f&&await S({challenge:e,channel:f,deposit:f.deposit>t?f.deposit:t,fetch:r,input:a,requiredCumulative:n,signal:i})}};return BD({onNeedVoucher:(t,n)=>VD({challenge:e,driver:m,input:a,signal:n},t),onReceipt(){},response:l,signal:u})})}var BM,VM=F((()=>{uw(),vw(),Px(),eC(),qT(),uA(),vA(),MA(),lO(),lE(),cj(),ME(),Vj(),qj(),FM(),gD(),BM=new WeakMap}));function HM(e,t){WM.set(e,t)}function UM(e){let t=WM.get(e);if(!t)throw Error(`Session manager internals are unavailable.`);return t}var WM,GM=F((()=>{WM=new WeakMap}));function KM(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 qM(e){let t=KM(`close-ready`),n=KM(`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 JM=F((()=>{}));function YM(e){return e.method===Ax.tempo&&e.intent===jx.charge}function XM(e){if(!YM(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function ZM(e,t,n){if(!n)return t;let r={...Sw(e instanceof Request?e.headers:void 0),...Sw(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===q.paymentSession.toLowerCase())?t:{...t,headers:{...r,[q.paymentSession]:n}}}function QM(e,t){return e===void 0?t:{...PM.parse(e),...t}}function $M(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:N(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:N(e.topUpAmount,t),WebSocket:n}}function eN(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&gA(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=$M(e),i=mA({chain:Ve,getClient:e.client?()=>e.client:e.getClient,rpcUrl:cO}),a=lA({account:e.account}),o=sD(),s=e.credentialContext===void 0?void 0:QM(e.credentialContext,{}),c=qM({getSocketSession:()=>o.socketSession}),l=e.channelStore??Wj(),u=new Set,d;async function f(e){let t=await l.get(e);if(t?.opened&&!u.has(t.channelId))return t}let p={async get(e){let t=await f(e);return t&&d&&(d.seenExisting.add(e),!d.committed&&!d.created.has(e)&&(d.resumed??=t)),t},async set(e){let t=Uj(e);e.opened&&u.delete(e.channelId),d?.trackCreates&&!d.seenExisting.has(t)&&d.created.set(t,e),await l.set(e)},delete:e=>l.delete(e)};async function m(e){let t=Uj(e);u.add(e.channelId),d?.seenExisting.delete(t),d?.resumed===e&&(d.resumed=void 0),await Promise.resolve(l.delete(t)).catch(()=>void 0)}async function h(){let e=d;if(e?.created.size){for(let[t,n]of e.created)u.add(n.channelId),await Promise.resolve(l.delete(t)).catch(()=>void 0);e.created.clear(),await ie(e.committed??e.previous)}}function g(e){let t=Ox(e.request.methodDetails,Mx.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=d;if(!n?.created.size||!o.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&o.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=fD({channel:o.channel,spent:o.spent,state:o.state}),!0;return!1}function _(e){return WE(o,e)}function v(){let e=o.state.status===`active`?o.state:d?.committed?.state??d?.previous.state;return e?.status===`active`?e.units:0}function y(e){let t=d,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit||(t.resumed=void 0,t.committed=fD({channel:o.channel,spent:o.spent,state:o.state}))}let b=zM({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:p,onChannelUpdate(e){e.channelId!==o.channel?.channelId&&(o.spent=0n),o.channel=e,o.lastChallenge&&_({type:`activated`,challengeId:o.lastChallenge.id,entry:e,spent:o.spent.toString(),units:v()}),y(e)}});fw(b);let x=ej({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),S=bw({fetch:r.fetch,methods:[b],onChallenge:async(e,t)=>{if(!SD(e))return;let n=d,r=n&&n.challengesReceived>0&&e.id===o.lastChallenge?.id,i=r&&Qx(e)===Qx(o.lastChallenge);n&&n.challengesReceived++,!i&&(g(e)||(n?.created.size?await h():r&&await ie(n.committed??n.previous)),o.lastChallenge=e,_({type:`challengeReceived`,challengeId:e.id}))}});function C(e,t){return b.createCredential({challenge:e,context:QM(s,t)})}function w(e){cD({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:o})}function T(e=o.state.status===`active`?o.state.units:0){!o.channel||!o.lastChallenge||o.state.status!==`active`&&o.state.status!==`withdrawable`&&o.state.status!==`closeRequested`&&_({type:`activated`,challengeId:o.lastChallenge.id,entry:o.channel,spent:o.spent.toString(),units:e})}async function ee(t){let n=t.headers.get(q.paymentSessionSnapshot);if(!n)return;let r=PE(n);gA(e.allowedChainIds,r.chainId);let s=await i({chainId:r.chainId});hA(s,r.chainId);let c=a(s),{entry:l,spent:u}=await vM({account:await e.resolveAccount?.({account:c,chainId:r.chainId,operation:{authority:rj(r.descriptor),kind:`authorizePaymentChannel`}})??c,client:s,snapshot:r});return ne(l.cumulativeAmount),await Promise.resolve(p.set(l)).catch(()=>void 0),o.channel=l,o.spent=u,l}async function E(t,n){if(!e.bootstrap||o.channel?.opened)return;let i=t instanceof Request?t.headers:void 0,{body:a,method:s,...c}=n??{},l=t instanceof Request?t.url:t,u={...c,method:`HEAD`,headers:{...Sw(i),...Sw(n?.headers),[q.acceptPayment]:`${Ax.tempo}/${jx.charge}`}};try{let e=await r.fetch(l,u);if(e.status!==402)return await ee(e);let t=sS(e).find(YM);if(!t||!XM(t))return;let n=await x.createCredential({challenge:t,context:{}}),i=await r.fetch(l,{...u,headers:{...Sw(u.headers),[q.authorization]:n}});return i.ok?await ee(i):void 0}catch{return}}function D(e,t){let n=o.socketSession;return uD({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:o.channel?.channelId===t?o.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:o.spent,tickCost:n?.tickCost})}function O(e,t){let n=wD(t);if(!n)return;if(ij({...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 k(e,t){let n=O(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(o.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>o.spent&&(o.spent=i),n}function te(e,t=e.challenge,n=!1){let r=(n?k(e,t):O(e.channel,t))?.acceptedCumulative??D(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return ne(r),r.toString()}function ne(e){YE({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}async function re(e){let{knownDeposit:t,...n}=e,i=await kD({...n,channel:o.channel,createSessionCredential:C,fetch:r.fetch});w(i);let a=bD({additionalDeposit:e.additionalDeposit,channel:o.channel,channelId:e.channelId,challengeId:o.lastChallenge?.id,currentState:o.state,knownDeposit:t,receipt:i,spent:o.spent});return a?.channel&&o.lastChallenge&&(await p.set(a.channel),_({type:`activated`,challengeId:o.lastChallenge.id,entry:a.channel,spent:o.spent.toString(),units:v()}),y(a.channel)),i}async function A(e){let t=o.channel?.channelId===e.channelId?o.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=eD({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 re({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})}async function j(e,t){let n=dD({channel:o.channel,channelId:e,challengeId:o.lastChallenge?.id,cumulativeAmount:t,spent:o.spent,state:o.state});n&&o.channel&&(_({type:`activated`,challengeId:n.challengeId,entry:o.channel,spent:n.spent,units:n.units}),await l.set(o.channel))}async function ie(e){let t=pD(e,o.channel);o.channel=t.channel,o.spent=t.spent,o.state=t.state,o.channel?.opened&&await l.set(o.channel)}function ae(e){let t=e.headers.get(q.paymentReceipt),n=t?xE(t):null;return w(n),Object.assign(e,{receipt:n,challenge:o.lastChallenge,channelId:o.channel?.channelId??null,cumulative:o.channel?.cumulativeAmount??0n})}async function oe(e,t){if(d)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);o.lastUrl=e;let n=fD({channel:o.channel,spent:o.spent,state:o.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};d=i;try{await E(e,t),i.trackCreates=!0;let a=ZM(e,t,o.channel?.opened?o.channel.channelId:void 0);s&&(a={...a,context:s});let c=!n.channel?.opened;async function l(){let n=i.resumed;return!c||!n?!1:(c=!1,await m(n),a=ZM(e,t,void 0),!0)}for(;;){let t;try{t=await S(e,a)}catch(e){if(i.created.size?await h():await ie(i.committed??n),await l())continue;throw e}let s=ae(t),c=!1;if(s.status===402){let t=await jD({input:e,init:a,response:s,createSessionCredential:C,fetch:r.fetch,getChannel:()=>o.channel,restoreCumulative:j,setChallenge(e){o.lastChallenge=e},topUpIfNeeded:A});t&&(c=!0,s=ae(t))}if(!c&&!s.ok&&!s.receipt){if(i.created.size?await h():await ie(i.committed??n),await l())continue;return s}return s}}finally{d=void 0}}async function se(e){let t=await ND({createSessionCredential:C,fetch:r.fetch,getMinimumSpent:()=>o.spent,lastUrl:o.lastUrl,resolveSignedCloseAmount:t=>te(e,t,!0),signedCloseAmount:te(e),setChallenge(e){o.lastChallenge=e},target:e});return t&&(T(),_({type:`closeStarted`}),_({type:`closed`,receipt:t})),t}let ce={createSessionCredential:C,doFetch:oe,fetch:r.fetch,getChannel:()=>o.channel,getChallenge:()=>o.lastChallenge,assertVoucherWithinLocalLimit:ne,acceptReceipt(e){w(e)},topUpIfNeeded:A},M={get channelId(){return o.channel?.channelId},get cumulative(){return o.channel?.cumulativeAmount??0n},get opened(){return o.channel?.opened??!1},get state(){return o.state},fetch:oe,async topUp(e){let t=yD({amount:e,assertVoucherWithinLocalLimit:ne,channel:o.channel,decimals:r.decimals,lastChallenge:o.lastChallenge,lastUrl:o.lastUrl});return re({additionalDeposit:t.additionalDeposit,challenge:t.challenge,channelId:t.channelId,input:t.input})},async sse(e,t){return PD(e,t,ce)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=DD(e),i=t?.signal?{signal:t.signal}:void 0;await E(n,i);let a=o.channel?.opened?o.channel.channelId:void 0,{challenge:s,credential:l,httpUrl:u,wsUrl:d}=await UD({async createSessionCredential(e,i){return o.lastChallenge=e,await cw(b,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),C(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){o.lastUrl=e.toString()},probeInit:ZM(n,i,a),signal:t?.signal});return o.lastChallenge=s,JD({challenge:s,credential:l,httpUrl:u,WebSocket:r.WebSocket,wsUrl:d,options:t,createSessionCredential:C,getChannel:()=>o.channel,setSocketSession(e){o.socketSession=e},async refreshChallenge(){let e=await HD({fetch:r.fetch,input:u,probeInit:ZM(u,i,o.channel?.opened?o.channel.channelId:void 0),signal:t?.signal});return o.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:ne,acceptReceipt:w,rejectCloseReady:c.rejectCloseReady,rejectReceipt:c.rejectReceipt,settleCloseReady:c.settleCloseReady,settleReceipt:c.settleReceipt,topUpIfNeeded:A,waitForReceipt:c.waitForReceipt})},async close(){let e=o.socketSession,t=nD({channel:o.channel,currentSocket:e,lastChallenge:o.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===eO.OPEN){let r=await mD({activeSocket:n,createSessionCredential:C,currentSocket:e,spent:o.spent,target:t,waitForCloseReady:c.waitForCloseReady,waitForReceipt:c.waitForReceipt});return T(),_({type:`closeStarted`}),_({type:`closed`,receipt:r}),r}return se(t)}};return HM(M,{consumeSseResponse(e,t,n){return FD(e,t,n,ce)},rehydrate({channel:e,challenge:t,input:n,spent:r}){if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!SD(t))throw Error(`Cannot restore session: challenge is not tempo/session.`);if(r<0n)throw Error(`Cannot restore session: spent must not be negative.`);if(r>e.cumulativeAmount)throw Error(`Cannot restore session: spent exceeds local voucher state.`);ne(e.cumulativeAmount);let i=O(e,t),a=i&&i.spent>r?i.spent:r;o.lastUrl=n,o.lastChallenge=t,o.channel=e,o.spent=a,_({type:`challengeReceived`,challengeId:t.id}),_({type:`activated`,challengeId:t.id,entry:e,spent:a.toString(),units:0})}}),M}var tN=F((()=>{gS(),oT(),uw(),vw(),Px(),uA(),vA(),nj(),lO(),qj(),FM(),VM(),cj(),ME(),VE(),GM(),JM(),gD(),rO(),(function(e){e.serializeSnapshot=NE,e.deserializeSnapshot=PE})(eN||={})}));function nN(e){return e instanceof Date?e:new Date(e)}function rN(e){let t=e.getTime();if(!Number.isFinite(t))throw new Y({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new Y({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new Y({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function iN(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=CN[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>SN)throw new Y({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new Y({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function aN(e){let{challengeExpires:t,request:n}=e;iN(n);let r=rN(nN(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new Y({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function oN(e){let t=yN(e.currency,`currency`),n=yN(e.recipient,`recipient`);return[{address:t,selector:xN,recipients:[n]}]}function sN(e){try{let t=re.fromBytes(k.toBytes(e));if(re.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function cN(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=uN({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:Ue.getSignPayload(o)}),c=We.from(s);if(c.type===`keychain`||c.type===`multisig`)throw new Y({reason:`keyAuthorization must use a primitive signature`});return Ue.from(o,{signature:s})}function lN(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new Y({reason:`invalid keyAuthorization payload`});let o=dN(i.signature),s=fN(o);if(pN({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==sN(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return mN(o,a),gN(hN(o),a),_N(o.scopes,a),{authorization:o,source:{address:vN(o,s),chainId:r}}}function uN(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return Ue.from({address:yN(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:rN(nN(i.subscriptionExpires)),limits:[{token:yN(i.currency,`currency`),limit:BigInt(i.amount),period:iN(i)}],scopes:oN(i),type:t.keyType,witness:sN(n)})}function dN(e){try{return Ue.deserialize(e)}catch(e){throw e instanceof Ue.InvalidSignatureTypeError?new Y({reason:`keyAuthorization must use a primitive signature`}):new Y({reason:`invalid keyAuthorization payload`})}}function fN(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function pN(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new Y({reason:`keyAuthorization chainId mismatch`});if(t){if(!fe(n.address,yN(t.accessKeyAddress,`accessKeyAddress`)))throw new Y({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new Y({reason:`keyAuthorization key type mismatch`})}}function mN(e,t){if(aN({request:t}),e.expiry!==rN(nN(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function hN(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new Y({reason:`keyAuthorization must contain exactly one token limit`});return t}function gN(e,t){if(!fe(e.token,yN(t.currency,`currency`)))throw new Y({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new Y({reason:`keyAuthorization amount mismatch`});if(e.period!==iN(t))throw new Y({reason:`keyAuthorization period mismatch`})}function _N(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=yN(t.currency,`currency`),r=yN(t.recipient,`recipient`),i=new Set;for(let t of e){if(!fe(t.address,n))throw new Y({reason:`keyAuthorization call target mismatch`});let e=bN(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new Y({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new Y({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!fe(t.recipients[0],r))throw new Y({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new Y({reason:`keyAuthorization must allow transferWithMemo`})}function vN(e,t){let n=Ue.getSignPayload(e);try{let e=We.extractAddress({payload:n,signature:t});if(!We.verify(t,{address:e,payload:n}))throw new Y({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof Y?e:new Y({reason:`keyAuthorization signature is invalid`})}}function yN(e,t){if(!de(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function bN(e){return typeof e==`string`?e.toLowerCase():``}var xN,SN,CN,wN=F((()=>{bS(),xN=`0x95777d59`,SN=(1n<<64n)-1n,CN={dev_second:1n,day:86400n,week:604800n}}));function TN(e={}){let t=mA({chain:ve,getClient:e.getClient,rpcUrl:cO}),n=lA({account:e.account});return KT(cE,{context:ON,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??iO.testnet,o=await t({chainId:a}),s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");DN(r.request),await e.validateRequest?.(r.request);let l=await EN(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=lN({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:Ue.serialize(l),type:`keyAuthorization`},request:r.request});if(!fe(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return ZS({challenge:r,payload:{signature:Ue.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function EN(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await cN({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:rN(nN(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:re.fromNumber(BigInt(o.amount)),period:iN(o)}],scopes:oN(o),witness:sN(i)}]});return Ue.fromRpc(c.keyAuthorization)}function DN(e){iN(e),rN(nN(e.subscriptionExpires))}var ON,kN=F((()=>{eC(),qT(),uA(),vA(),Xx(),lO(),lE(),wN(),ON=J.object({accessKey:J.optional(J.custom()),account:J.optional(J.custom())})}));function AN(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[ej(e),jN(n)]}var jN,MN=F((()=>{VM(),tN(),nj(),kN(),jN=Object.assign(zM,{manager:eN}),(function(e){e.charge=ej,e.common=AN,e.session=jN,e.subscription=TN})(AN||={})})),NN=F((()=>{nj(),MN(),kN(),VM(),tN()})),PN=Ze({orderTempoChargeChallengesByBalance:()=>IN,readTempoKeystore:()=>nP,resolveTempoAccount:()=>rP,tempo:()=>LN});async function FN(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}async function IN(e,t){let n=[],r=[];for(let[t,i]of e.entries())WN(i)&&(n.push(t),r.push(i));if(r.length<2)return[...e];let i=await GN(t).catch(()=>void 0);if(!i)return[...e];let a=await Promise.all(r.map(async(e,t)=>({challenge:e,index:t,score:await KN(e,i)})));a.sort((e,t)=>dP.indexOf(e.score)-dP.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 LN(){let e;return Yk({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:t,options:n,methodOpts:r}){let i=WO(n.account),a=t.request,o=a.currency,s=UN(r),c=XN({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()||(yO(i)?void 0:await GO(i).get());if(!h&&yO(i)&&iP()){m=!0;let e=rP(i);if(e){let r=CO(n.rpcUrl,{network:n.network});p=j({chain:await TO({network:n.network,rpcUrl:r}),transport:ue(r)}),JN({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let i=o?await kO(p,o,e.wallet_address).catch(()=>void 0):void 0;l=i?.symbol??o??``,u=i?.decimals??a.decimals??6}}else if(h)f=_e(h);else{let e=oP();if(e){let t=await GO(e).get();t&&(f=_e(t))}if(!f)throw n.account?new I({code:`ACCOUNT_NOT_FOUND`,message:`Account "${i}" not found.`,exitCode:69}):new I({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!m&&f){let e=CO(n.rpcUrl,{network:n.network});p=j({chain:await TO({network:n.network,rpcUrl:e}),transport:ue(e)}),JN({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let r=o?await kO(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 aP(t)}};if(!f||!p)throw new I({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let g=AN({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??(OO(p.chain)?`10`:void 0);if(!n)throw new I({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=QN(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 yj(p,f,c,i,a);return ZS({challenge:t,payload:{action:o,channelId:n,...o===`close`?{closeSignature:await bj(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=qS(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?``:`
232
+ `)}function wO(e,t,n){if(HO.has(e)&&typeof t==`string`)return`${t} ${X.dim(`(${NO(BigInt(t),n.tokenSymbol,n.tokenDecimals)})`)}`;if(e===`chainId`&&typeof t==`number`){let e=LO({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?DO(`${n.explorerUrl}/address/${t}`,t):t:typeof t==`string`&&/^https?:\/\//.test(t)?X.link(t,t):String(t)}function TO(e){try{let t=e.replace(/^0x0*/,``);if(!t)return;let n=Uint8Array.from(t.match(/.{1,2}/g).map(e=>Number.parseInt(e,16))),r=new TextDecoder().decode(n);return/^[\x20-\x7e]+$/.test(r)?r:void 0}catch{return}}function EO(e,t){if(e===`realm`&&typeof t==`string`)try{let e=new URL(t.includes(`://`)?t:`https://${t}`);return X.link(e.href,t)}catch{}return String(t)}function DO(e,t){return X.link(e,t)}function OO(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 kO(e=process.env){if(e.CLAUDECODE)return!0;for(let[t,n]of Object.entries(e))if(n&&(t===`CODEX`||t.startsWith(`CODEX_`)))return!0;return!1}function AO(e){return e.startsWith(`tempo:`)}function jO(e){let t=Se.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 MO(e,t=!1){let n=Se.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 NO(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 PO(e,t={}){return e??(t.network?UO[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}function FO(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 IO(e={}){let t=PO(e.rpcUrl,{network:e.network});if(!t)return ye;let{getChainId:n}=await import(`viem/actions`),r=await n(j({transport:ue(t)})),i=Object.values(await import(`viem/tempo/chains`)).filter(e=>typeof e==`object`&&!!e&&`id`in e&&e.id===r),a=i.find(e=>`serializers`in e&&e.serializers)??i[0];if(!a)throw Error(`Unknown chain ID ${r} from RPC ${t}`);return a}function LO(e){return{[ye.id]:`mainnet`,[be.id]:`testnet`}[e.id]??e.name}function RO(e){return typeof e==`bigint`?e:e.amount}function zO(e){return e.id!==ye.id}async function BO(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(RO).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 VO(e,t){if(t?.chain){let n=j({chain:t.chain,transport:ue(t.rpcUrl)}),r=t.chain.blockExplorers?.default?.url,i=X.dim(`(${LO(t.chain)})`);return zO(t.chain)?(await Promise.all(qO.map(t=>BO(n,t,e)))).filter(e=>e.balance>0n).map(e=>`${NO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`):(await Promise.all(KO.map(t=>BO(n,t,e)))).map(e=>`${NO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`)}let n=j({chain:ye,transport:ue(PO())}),r=ye.blockExplorers?.default?.url,i=(await Promise.all(KO.map(t=>BO(n,t,e)))).map(e=>NO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token}));if(t?.includeTestnet!==!1){let t=j({chain:be,transport:ue()}),n=be.blockExplorers?.default?.url,r=await Promise.all(qO.map(n=>BO(t,n,e)));for(let e of r)e.balance>0n&&i.push(`${NO(e.balance,e.symbol,e.decimals,{explorerUrl:n,token:e.token})} ${X.dim(`(testnet)`)}`)}return i}var X,HO,UO,WO,GO,KO,qO,JO=F((()=>{bO(),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}}})(),HO=new Set([`amount`,`suggestedDeposit`,`minVoucherDelta`]),UO={mainnet:yO[hO.mainnet],testnet:yO[hO.testnet]},WO=`0x20c0000000000000000000000000000000000000`,GO=`0x20C000000000000000000000b9537d11c60E8b50`,KO=[WO,GO],qO=[`0x20c0000000000000000000000000000000000000`,`0x20c0000000000000000000000000000000000001`,`0x20c0000000000000000000000000000000000002`,`0x20c0000000000000000000000000000000000003`]}));function YO(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:sk}function XO(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function ZO(e){return new I({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 QO(e){if(e&&XO(e,`secret-tool`))throw ZO(e)}function $O(e,t){return new Promise(n=>{m.execFile(e,t,{timeout:YO()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function ek(){let e=c.join(process.env.XDG_CONFIG_HOME||c.join(b.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 tk(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:ek().get())}function nk(e=`main`){let t=ok;return{async list(){let e=b.platform();if(e===`darwin`){let{stdout:e,error:n}=await $O(`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 $O(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(QO(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=b.platform();if(n===`darwin`){let{stdout:n,error:r}=await $O(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await $O(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return QO(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=b.platform();if(r===`darwin`){await $O(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await $O(`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(),YO());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(XO(e,`secret-tool`)?ZO(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=b.platform();if(n===`darwin`){await $O(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await $O(`secret-tool`,[`clear`,`service`,t,`account`,e]);QO(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function rk(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=tk(e),i=await nk(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function ik(e){let t=tk(e);if(!process.env.MPPX_PRIVATE_KEY?.trim()&&AO(t))throw new I({code:`UNSUPPORTED_ACCOUNT`,message:`Persistent sessions require an mppx account or MPPX_PRIVATE_KEY.`,exitCode:2});return rk(e).catch(e=>{throw new I({code:`ACCOUNT_NOT_FOUND`,message:e instanceof Error?e.message:`No account found.`,exitCode:69,...e instanceof Error&&{cause:e}})})}async function ak(e){return(await rk(e)).account}var ok,sk,ck=F((()=>{JO(),ok=`mppx`,sk=1e4}));mO(),ck();const lk=[[`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 uk(e=process.env){return lk.find(([t])=>e[t])?.[1]}const dk=Symbol(`mppx.x402.asset`);function fk(e){return{[dk]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function pk(e,t){let n=e(t.chainId);return fk({address:n.address,decimals:n.decimals,network:Ck(t.chainId),transfer:Tk(t.transfer,n)})}const mk={USDC:fk({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},hk={USDC:fk({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},gk={USDC:fk({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:fk({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},_k={USDC:fk({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function vk(e){return typeof e!=`object`||!e?!1:e[dk]===!0}function yk(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function bk(e){return typeof e==`string`}function xk(e,t){if(vk(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(yk(e)){let n=e.addresses[wk(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function Sk(e,t,n){let r=xk(e,n);return r?M(r.address)===M(t):!1}function Ck(e){return`eip155:${e}`}function wk(e){return Number(e.slice(7))}function Tk(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 Ek=Qe({base:()=>mk,baseSepolia:()=>hk,celo:()=>gk,celoSepolia:()=>_k,define:()=>fk,fromToken:()=>pk,isAsset:()=>vk,isRawAddress:()=>bk,isToken:()=>yk,matches:()=>Sk,resolve:()=>xk,toChainId:()=>wk,toNetwork:()=>Ck}),Dk=Qe({base:()=>Ok,baseSepolia:()=>kk,celo:()=>Ak,celoSepolia:()=>jk});const Ok=8453,kk=84532,Ak=42220,jk=11142220;zx();function Mk(e){let t=[Rx(e.accepted),Rx(e.resource),Rx(e.extensions)].join(`|`);return ne.sha256(te.fromString(t),{as:`Hex`})}iw(),kC();async function Nk(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=oC(n);if(Lk(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?zk(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:M(t.address),nonce:i?.mppx?Mk({accepted:r,extensions:i,resource:n.resource}):Vk(),to:M(r.payTo),validAfter:(c-600).toString(),validBefore:(c+r.maxTimeoutSeconds).toString(),value:r.amount},u=await t.signTypedData({domain:{chainId:Ik(r.network),name:o,verifyingContract:M(r.asset),version:s},message:{...l,value:BigInt(l.value),validAfter:BigInt(l.validAfter),validBefore:BigInt(l.validBefore)},primaryType:`TransferWithAuthorization`,types:Fk});return nw({accepted:r,...i?{extensions:i}:{},payload:{authorization:l,signature:u},...n.resource?{resource:n.resource}:{},x402Version:2})}function Pk(e){let t=e.challenge.request,n;try{n=oC(t),Lk(e.config,n)}catch{return!1}if(!t.resource||(n.extra?.assetTransferMethod??`eip3009`)!==`eip3009`)return!1;let r=n.extra?.name,i=n.extra?.version;return typeof r==`string`&&typeof i==`string`}const Fk={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 Ik(e){return Number(e.slice(lC.length))}function Lk(e,t){let n=Ik(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=>bk(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=M(t.asset);if(!r.some(n=>Sk(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=Rk(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>N(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function Rk(e,t){let n=e.currencies??e.assets,r=M(t.asset),i=n?.find(e=>Sk(e,r,t.network)),a=i?xk(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function zk(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:Bk()}}}:e}function Bk(){return Hk().slice(2)}function Vk(){return Hk()}function Hk(){let e=globalThis.crypto;if(!e?.getRandomValues)throw Error(`x402 exact requires crypto randomness.`);let t=e.getRandomValues(new Uint8Array(32));return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}Zx();const Uk=[`authorization`],Wk=J.string().check(J.regex(/^\d+$/,`Invalid atomic amount`));J.object({name:J.string().check(J.minLength(1)),version:J.string().check(J.minLength(1))});const Gk=J.object({chainId:J.number(),credentialTypes:J.optional(J.array(J.enum(Uk)).check(J.minLength(1))),decimals:J.optional(J.number()),permit2Address:J.optional(Kx()),splits:J.optional(J.array(J.object({amount:Wk,recipient:Kx()})))});J.object({amount:Wk,currency:Kx(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:Gk,recipient:Kx()});const Kk=J.object({amount:Vx(),chainId:J.number(),currency:Kx(),credentialTypes:J.optional(J.array(J.enum(Uk)).check(J.minLength(1))),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),permit2Address:J.optional(Kx()),recipient:Kx(),splits:J.optional(J.array(J.object({amount:Wk,recipient:Kx()})))}),qk=J.object({from:Kx(),nonce:qx(),signature:Yx(),to:Kx(),type:J.literal(`authorization`),validAfter:Wk,validBefore:Wk,value:Wk}),Jk={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 Yk(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function Xk(e){return ne.keccak256(te.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function Zk(e){return`eip155:${e}`}function Qk(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}iE(),Zx();const $k=nE({name:`evm`,intent:`charge`,schema:{credential:{payload:qk},request:J.pipe(Kk,J.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...c})=>({...c,amount:N(e,i).toString(),currency:M(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:M(a)}:{},...s?{splits:s}:{}},recipient:M(o)})))}});nC(),iE(),OS(),Zx();function eA(e){return rE($k,{canHandleChallenge({challenge:t}){return!tA(t)||Pk({challenge:t,config:e})},context:J.object({account:J.optional(J.custom())}),async createCredential({challenge:t,context:n}){if(tA(t))return Nk({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(nA(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=rA(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return $S(QS({challenge:t,payload:{from:M(r.address),nonce:Xk(t),signature:await r.signTypedData({domain:Yk({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:M(r.address),nonce:Xk(t),to:M(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Jk}),to:M(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:Qk({address:M(r.address),chainId:i.methodDetails.chainId})}))}})}function tA(e){return ES(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function nA(e,t){let n=t.methodDetails.chainId,r=Zk(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=>bk(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=M(t.currency);if(!i.some(t=>Sk(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=iA(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>N(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function rA(e,t){let n=e.currencies??e.assets,r=M(t.currency),i=Zk(t.methodDetails.chainId),a=n?.find(e=>Sk(e,r,i)),o=a?xk(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;throw Error(`EVM authorization requires token name and version.`)}function iA(e,t){let n=e.currencies??e.assets,r=M(t.currency),i=Zk(t.methodDetails.chainId),a=n?.find(e=>Sk(e,r,i)),o=a?xk(a,i):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function aA(e){return[aA.charge(e)]}(function(e){e.charge=eA,e.assets=Ek,e.chains=Dk})(aA||={});function oA(e){return e}var sA=F((()=>{}));OS(),sA();function cA(){return oA({method:`evm`,supports:e=>e.method===`evm`&&!ES(e),async setup({challenge:e}){let t=e.request,n=t.methodDetails,r=n?.chainId,i=r?lA(r):void 0,a=t.currency,o=await ak(),s=[...Object.values(mk),...Object.values(hk),...Object.values(gk),...Object.values(_k)],c=a??``;if(i&&a)try{let e=j({chain:i,transport:ue()}),t=await Oe(e,{address:a,abi:se,functionName:`symbol`});t&&(c=t)}catch{}return{tokenSymbol:c,tokenDecimals:n?.decimals??6,explorerUrl:i?.blockExplorers?.default?.url,methods:[...aA({account:o,currencies:s})]}}})}function lA(e){return Object.values(Ve).find(t=>t.id===e)}function uA(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}Zx();const dA=J.object({customer:J.optional(J.string().check(J.minLength(1))),hooks:J.optional(J.object({inputs:J.object({tax:J.object({calculation:J.string().check(J.minLength(1))})})})),metadata:J.optional(J.record(J.string(),J.string())),receipt_email:J.optional(J.string().check(J.minLength(1)))}),fA=J.custom(e=>typeof e==`function`),pA=J.union([dA,fA]);iE(),Zx();const mA=nE({name:`stripe`,intent:`charge`,schema:{credential:{payload:J.object({externalId:J.optional(J.string()),spt:J.string()})},request:J.pipe(J.object({amount:Vx(),currency:J.string(),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),metadata:J.optional(J.record(J.string(),J.string())),networkId:J.string(),paymentIntentOptions:J.optional(pA),paymentMethodTypes:J.array(J.string()).check(J.minLength(1)),recipient:J.optional(J.string())}),J.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:uA(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});nC(),iE(),Zx();function hA(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return rE(mA,{context:J.object({paymentMethod:J.optional(J.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 $S({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function gA(e){return[hA(e)]}(function(e){e.charge=hA})(gA||={}),Ox(),JO(),sA();function _A(){return oA({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=yA(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 I({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:[gA.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=vA(a),l=process.env.MPPX_STRIPE_SPT_URL?process.env.MPPX_STRIPE_SPT_URL:c?`https://api.stripe.com/v1/test_helpers/shared_payment/granted_tokens`:`https://api.stripe.com/v1/shared_payment/issued_tokens`;if(r){let e=c?`seller_details[network_id]`:`seller_details[network_business_profile]`;s.set(e,r)}if(o)for(let[e,t]of Object.entries(o))s.set(`metadata[${e}]`,t);let u={Authorization:`Basic ${btoa(`${a}:`)}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":`2026-07-29.preview`},d=await globalThis.fetch(l,{method:`POST`,headers:u,body:s});if(!d.ok){let a=await d.json();if(c&&(o||r)&&a.error.message.includes(`Received unknown parameter`)){let r=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()});if(d=await globalThis.fetch(l,{method:`POST`,headers:u,body:r}),!d.ok){let e=await d.json();throw new I({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${e.error.message}`,exitCode:77})}}else throw new I({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&&vA(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function vA(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function yA(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 bA(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 xA=F((()=>{}));function SA(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}var CA=F((()=>{}));function wA(e,t={}){return ue(e.url,{fetchFn:e.fetch,fetchOptions:{headers:SA(e)},...t})}function TA(e){let{chain:t,getClient:n,remoteFeePayer:r,rpcUrl:i}=e;return n?!t?.serializers&&!r?n:async e=>{let i=await n(e),a=i;if(r&&i.transport.key!==`feePayer`){let e=i.request.bind(i),t=Be(ae({request:t=>e(t)},{retryCount:0}),wA(r,{retryCount:i.transport.retryCount}))({account:i.account,chain:i.chain,pollingInterval:i.pollingInterval,retryCount:0}),n=ie({...t.config,retryCount:0},t.value);a=Object.assign({},i,{request:n.request,transport:{...n.config,...n.value}})}return!t?.serializers||a.chain?.serializers?.transaction?a:Object.assign({},a,{chain:{...t,...e.chainId===void 0?{}:{id:e.chainId},...a.chain,formatters:a.chain?.formatters??t.formatters,prepareTransactionRequest:a.chain?.prepareTransactionRequest??t.prepareTransactionRequest,serializers:a.chain?.serializers?.transaction?a.chain.serializers:t.serializers}})}:({chainId:e})=>{if(!i)throw Error("No `rpcUrl` provided.");let n=e||Number(Object.keys(i)[0]),a=i[n];if(!a)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let o=r?Be(ue(a),wA(r)):ue(a);return j({chain:OA[n]??{...t,id:n},transport:o})}}function EA(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 DA(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}var OA,kA=F((()=>{CA(),OA={[ye.id]:ye,[be.id]:be}}));function AA(e){let t=ne.keccak256(te.fromString(e),{as:`Hex`});return re.toBytes(re.slice(t,0,10))}function jA(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(re.toBytes(NA),0),i[4]=PA,i.set(AA(t),5),n&&i.set(AA(n),15),i.set(MA(r),25),re.fromBytes(i)}function MA(e){let t=ne.keccak256(te.fromString(e),{as:`Hex`});return re.toBytes(re.slice(t,0,7))}var NA,PA,FA=F((()=>{NA=re.slice(ne.keccak256(te.fromString(`mpp`),{as:`Hex`}),0,4),PA=1}));function IA(e,t){return Ke.resolve(e).toLowerCase()===Ke.resolve(t).toLowerCase()}var LA=F((()=>{}));async function RA(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t,s=a.filter(e=>!IA(e,i)),c=await Promise.allSettled([Oe(e,Ie.token.getBalance.call(e,{account:n,token:i})),...s.map(t=>Oe(e,Ie.token.getBalance.call(e,{account:n,token:t})))]),l=c[0];if(!(l.status===`fulfilled`&&l.value>=r)){for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let a=n.value;if(a<=0n)continue;let l=s[t];try{let t=await Ie.dex.getBuyQuote(e,{tokenIn:l,tokenOut:i,amountOut:r});if(a>=t){let n=t+t*BigInt(Math.round(o*100))/BA;return[Ie.token.approve.call(e,{amount:n,spender:Le.stablecoinDex,token:l}),Ie.dex.buy.call({tokenIn:l,tokenOut:i,amountOut:r,maxAmountIn:n})]}}catch{}}throw new HA({currency:i})}}function zA(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...t.filter(t=>!e.tokenIn.some(e=>IA(e,t)))]:t,slippage:e.slippage??1}:!1}var BA,VA,HA,UA=F((()=>{LA(),bO(),BA=10000n,VA=[gO.pathUsd,gO.usdc],HA=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}}}));function WA(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:e.amount,memo:e.memo,recipient:e.recipient}))]}var GA=F((()=>{}));function KA(e,t,n){t&&(n&&!n.some(e=>IA(e,t))||e.some(e=>IA(e,t))||e.push(t))}async function qA(e,t,n){try{return(await Ie.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function JA(e){let t=e.chain?.feeToken;if(t)return Re.toAddress(t);let n=e.chain?.id;return n?_O[n]:void 0}function YA(e){let t=[];return KA(t,gO.pathUsd),KA(t,_O[e]),t}async function XA(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])KA(o,e,n);if(KA(o,await Ie.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),KA(o,JA(i),n),!a)for(let e of r??[])KA(o,e,n);for(let e of o)if(await qA(i,t,e))return e;return o[0]}var ZA=F((()=>{LA(),bO()}));function QA(e){if(e!==void 0)return vO[e]}function $A(e){let t=QA(e.chainId);return!!t&&de(e.currency,{strict:!1})&&fe(e.currency,t.token)}function ej(e){let t=QA(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:Pe.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:oe({abi:nj,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 tj(e,t){let n=ej(t);if(n)try{return await Oe(e,Ie.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await Ee(e,{account:t.account,calls:n.calls}),n)}catch{return}}var nj,rj=F((()=>{bO(),nj=me([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`])}));function ij(e){return{name:`MPP`,version:`3`,chainId:e}}function aj(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function oj(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:ij(n),types:lj,primaryType:cj,message:aj({account:t,challengeId:r,realm:i})}}function sj(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}var cj,lj,uj=F((()=>{cj=`Proof`,lj={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]}}));function dj(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.`);let n={maxAmount:pj(e.maxAmount,e.decimals),maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=TA({chain:ye,getClient:e.getClient,rpcUrl:yO}),i=bA({account:e.account}),a=rE(_E,{canHandleChallenge({challenge:t}){try{return mj(e,n,t.request),!0}catch{return!1}},context:hj,async createCredential({challenge:a,context:o}){mj(e,n,a.request);let s=a.request.methodDetails?.chainId??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),c=await r({chainId:s});EA(c,s);let l=s??c.chain?.id;if(DA(e.allowedChainIds,l),l===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:u}=a,{amount:d,methodDetails:f}=u,p=f?.supportedModes??[`pull`,`push`],m=i(c,o),h=async t=>await e.resolveAccount?.({account:m,chainId:l,operation:t})??m;if(BigInt(d)===0n){let e=await h({kind:`signPaymentProof`});return $S({challenge:a,payload:{signature:await Me(c,{account:e,...oj({account:e.address,chainId:l,challengeId:a.id,realm:a.realm})}),type:`proof`},source:sj({address:e.address,chainId:l})})}let g=u.currency,_=$A({chainId:l,currency:g}),v=jA({challengeId:a.id,clientId:t,serverId:a.realm}),y=WA({amount:d,methodDetails:{...f,memo:v},recipient:u.recipient}),b=y.map(e=>Ie.token.transfer.call(c,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:g})),x=zA(o?.autoSwap??e.autoSwap,VA),S=f?.machineTokenEnabled===!0?ej({chainId:l,currency:g,transfers:y}):void 0,C=m,w;if(S){let e=await(async()=>{try{return await h({calls:S.calls,kind:`executeCalls`})}catch{return}})();e&&(w=await tj(c,{account:e.address,chainId:l,currency:g,transfers:y}),w&&(C=e))}let T;w||(C=await h({kind:`executeCalls`,...x?{}:{calls:b}}),T=x?await RA(c,{account:C.address,amountOut:BigInt(d),tokenOut:g,tokenIn:x.tokenIn,slippage:x.slippage}):void 0);let ee=w?.calls??[...T??[],...b],E=YA(l),D=w||_?await XA({account:C.address,allowedTokens:E,candidateTokens:E,client:c,prioritizeCandidates:!0}):void 0,O=(()=>{let t=o?.mode??e.mode;if(t){if(!p.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=C.type===`json-rpc`?`push`:`pull`;return p.includes(n)?n:p[0]})(),k=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!a.expires)return e;let t=Math.floor(new Date(a.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(O===`push`){let{receipts:e}=C.type===`local`?{receipts:[await Ae(c,{account:C,calls:ee,...D?{feeToken:D}:{},nonceKey:`expiring`,validBefore:k})]}:await ke(c,{account:C,...D?{capabilities:{feeToken:D}}:{},calls:ee,experimental_fallback:ee.length===1,forceAtomic:ee.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return $S({challenge:a,payload:{hash:t,type:`hash`},source:sj({address:C.address,chainId:l})})}let te=await De(c,{account:C,calls:ee,...D?{feeToken:D}:{},nonceKey:`expiring`,validBefore:k});if(te.gas=(te.gas??0n)+5000n,f?.feePayer){let e=te;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return $S({challenge:a,payload:{signature:await je(c,te),type:`transaction`},source:sj({address:C.address,chainId:l})})}}),o=new Map,s=async t=>{mj(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,s=o.get(i);return s||(s=a.createCredential(t).finally(()=>o.delete(i)),o.set(i,s)),s};return bw({...a,createCredential:s},fj)}function fj(e){let t=_E.schema.credential.payload.safeParse(YS(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(qe.serializedType))return;let i=qe.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&qe.serialize(i)===r)return pe(r)}function pj(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 N(e,t)}}function mj(e,t,n){let{amount:r,methodDetails:i,recipient:a}=n,o=i?.chainId;if(e.expectedChainId!==void 0&&o!==void 0&&o!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${o}.`);if((o!==void 0||e.allowedChainIds?.length===0)&&DA(e.allowedChainIds,o),e.currencies&&!e.currencies.some(e=>e.toLowerCase()===n.currency.toLowerCase()))throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!a||!t.has(a.toLowerCase()))throw Error(`Unexpected primary recipient: ${a}`);let n=i?.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&&BigInt(r)>t.maxAtomicAmount)throw Error(`Tempo charge amount exceeds maxAtomicAmount.`);if(t.maxAmount!==void 0&&BigInt(r)>t.maxAmount)throw Error(`Tempo charge amount exceeds maxAmount.`)}var hj,gj=F((()=>{Tw(),nC(),iE(),xA(),kA(),Zx(),FA(),UA(),GA(),bO(),ZA(),rj(),uj(),bE(),hj=J.object({account:J.optional(J.custom()),autoSwap:J.optional(J.custom()),mode:J.optional(J.enum(sE))})}));function _j(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function vj(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 yj(e){return qe.encodeForSigning(e)}function bj(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function xj(e,t){return ne.keccak256(re.concat(yj(e),t.sender))}var Sj=F((()=>{UE()})),Cj,wj,Tj,Ej,Dj=F((()=>{Cj=[{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`}],wj=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],Tj={name:`descriptor`,type:`tuple`,components:Cj},Ej=[{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:[Tj,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[Tj,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[Tj,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[Tj],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[Tj],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[Tj],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:Cj},{name:`state`,type:`tuple`,components:wj}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:wj}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:wj}]},{type:`function`,name:`computeChannelId`,stateMutability:`view`,inputs:[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`getVoucherDigest`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`domainSeparator`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`authorizedSigner`,type:`address`},{name:`salt`,type:`bytes32`},{name:`expiringNonceHash`,type:`bytes32`},{name:`deposit`,type:`uint96`}]},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`cumulativeAmount`,type:`uint96`},{name:`deltaPaid`,type:`uint96`},{name:`newSettled`,type:`uint96`}]},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`additionalDeposit`,type:`uint96`},{name:`newDeposit`,type:`uint96`}]},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`closeGraceEnd`,type:`uint256`}]},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`settledToPayee`,type:`uint96`},{name:`refundedToPayer`,type:`uint96`}]},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0}]}]}));function Oj(e,t){return{name:Ij,version:Lj,chainId:t,verifyingContract:e}}function kj(e,t){return Ue.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function Aj(e,t,n){return e.toLowerCase()===Ue.address.toLowerCase()?kj(t,n):le({domain:Oj(e,t),types:Rj,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function jj(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function Mj(e,t){return Fe.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function Nj(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===Ue.address.toLowerCase())try{return await Mj(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return Me(e,{account:t,domain:Oj(r,i),types:Rj,primaryType:`Voucher`,message:n})})(),o=Ge.from(a);if(!jj(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return Ge.serialize(o)}async function Pj(e,t,n,r,i){let a=await Me(e,{account:t,domain:Oj(r,i),types:zj,primaryType:`CloseAuthorization`,message:n}),o=Ge.from(a);if(!jj(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return Ge.serialize(o)}function Fj(e,t,n,r){try{let i=Ge.from(n.signature);if(!jj(i.type)||Ge.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=Aj(e,t,n),o=Ge.extractAddress({payload:a,signature:i});return Ge.verify(i,{address:o,payload:a})&&IA(o,r)}catch{return!1}}var Ij,Lj,Rj,zj,Bj=F((()=>{LA(),Ij=`TIP20 Channel Reserve`,Lj=`1`,Rj={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},zj={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]}}));function Vj(e){return typeof e==`object`&&!!e}function Hj(e){return typeof e==`string`&&de(e,{strict:!1})?e:void 0}function Uj(e){return Hj(e.accessKeyAddress)}function Wj(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(re.random(8))%e)}function Gj(e){return Uj(e)??e.address}async function Kj(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return De(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function qj(e,t){return await je(e,t)}function Jj(e,t,n=!1){let r=e.request.methodDetails,i=Vj(r)?Hj(r.escrowContract)??Hj(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!Xj(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!Xj(i,a)?i:a}function Yj(e,t,n,r){return $S({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function Xj(e,t){return e.toLowerCase()===t.toLowerCase()}async function Zj(e,t,n,r,i,a=HE){let o=vj({...n,chainId:i,escrow:a}),s=CE(r),c=await Nj(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function Qj(e,t,n,r,i,a=HE){let o=await Zj(e,t,n,r,i,a),s=await Pj(e,t,{channelId:o.channelId,cumulativeAmount:CE(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function $j(e,t,n){let r=Gj(t),i=n.escrow??`0x4d50500000000000000000000000000000000000`,a=n.operator??`0x0000000000000000000000000000000000000000`,o=re.random(32),s=CE(n.deposit),c=CE(n.initialAmount),l=oe({abi:Ej,functionName:`open`,args:[n.payee,a,n.token,s,o,r]}),u=await qj(e,await Kj(e,{account:t,calls:[...n.prefixCalls??[],{to:i,data:l}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),d=ze.deserialize(u),f={authorizedSigner:r,expiringNonceHash:xj(bj({...n.feePayer?{feePayer:!0}:{},transaction:d}),{sender:t.address}),operator:a,payee:n.payee,payer:t.address,salt:o,token:n.token},p=vj({...f,chainId:n.chainId,escrow:i});return{action:`open`,type:`transaction`,channelId:p,transaction:u,signature:await Nj(e,t,{channelId:p,cumulativeAmount:c},i,n.chainId),descriptor:f,cumulativeAmount:c.toString(),authorizedSigner:f.authorizedSigner}}async function eM(e,t,n,r,i,a,o=HE,s=[],c=n.token){let l=vj({...n,chainId:i,escrow:o}),u=CE(r);return{action:`topUp`,type:`transaction`,channelId:l,transaction:await qj(e,await Kj(e,{account:t,calls:[...s,{to:o,data:oe({abi:Ej,functionName:`topUp`,args:[n,u]})}],feePayer:a,feeToken:c,validAfter:Wj()})),descriptor:n,additionalDeposit:u.toString()}}var tM=F((()=>{nC(),Sj(),Dj(),UE(),Bj()}));function nM(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function rM(e){return nM({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function iM(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(rM(t),t)},delete(t){e.delete(t)}}}function aM(e){return{...e,cumulativeAmount:e.cumulativeAmount.toString(),deposit:e.deposit.toString()}}function oM(e){return{...e,cumulativeAmount:BigInt(e.cumulativeAmount),deposit:BigInt(e.deposit)}}var sM=F((()=>{}));function cM(e){if(e<0n||e>dM)throw new Y({reason:`amount exceeds uint96 range`})}async function lM(e,t,n=HE,r){return uM(await Oe(e,{address:n,abi:Ej,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function uM(e){return cM(e.settled),cM(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}var dM,fM=F((()=>{SS(),Dj(),UE(),dM=2n**96n-1n}));function pM(e){return`cumulativeAmount`in e}function mM(e){if(pM(e))return BigInt(e.cumulativeAmount)}async function hM(e,t){t.opened?await e.store.set(t):await e.store.delete(rM(t)),e.notifyUpdate(t)}async function gM(e,t,n){let r=mM(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 hM(e,i))}function _M(e){return e?.action!==void 0}function vM(e){return _M(e)&&e.descriptor!==void 0}function yM(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 N(i,t)}function bM(e,t,n,r){let i=yM(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function xM(e){return typeof e==`object`&&!!e}function SM(e){return typeof e==`string`&&de(e,{strict:!1})?e:void 0}function CM(e){let t=e.request.methodDetails;return xM(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:SM(t.escrowContract),escrow:SM(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:SM(t.feeToken),operator:SM(t.operator),sessionSnapshot:kx(t,Nx.sessionSnapshot)}:{}}function wM(e,t){if(typeof e==`string`&&de(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function TM(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function EM(e){return typeof e==`string`?e:void 0}async function DM(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=CM(n);(o.chainId!==void 0||i?.length===0)&&DA(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});EA(c,s);let l=s??c.chain?.id;if(DA(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=Jj(n,r,t),d=wM(n.request.recipient,`recipient`),f=wM(n.request.currency,`currency`);return{amount:TM(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:nM({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:EM(n.request.suggestedDeposit),token:f}}async function OM(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=lM}=e,o=vj({...r,chainId:i.chainId,escrow:i.escrow});kM({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 kM(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(!Xj(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!Xj(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!Xj(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!Xj(_j(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function AM(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function jM(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=yM(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function MM(e){let{account:t,client:n,readChannelState:r,snapshot:i}=e,a=i.highestVoucher;if(!a)throw Error(`session snapshot is missing its highest signed voucher`);if(a.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let o=BigInt(i.acceptedCumulative),s=BigInt(a.cumulativeAmount),c=BigInt(i.requiredCumulative),l=BigInt(i.deposit),u=BigInt(i.settled),d=BigInt(i.spent);if(s!==o)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(d>o)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(u>l)throw Error(`session snapshot settled amount exceeds deposit`);if(!Fj(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},_j(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await OM({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:Gj(t),token:i.descriptor.token},readChannelState:r}),p=[o,c,f.state.settled].reduce((e,t)=>t>e?t:e,0n);if(p>f.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:f.channelId,cumulativeAmount:p,deposit:f.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:d}}function NM(e,t){return Xj(e.address,t.payer)?Xj(Gj(e),_j(t)):!1}function PM(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(_M(r)){if(!vM(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=AM({context:r,snapshot:o.snapshot});return!n&&s&&NM(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&NM(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 FM(e,t,n=!1){switch(e.type){case`open`:return LM(e,t,n);case`recover`:return RM(e,t);case`voucher`:return zM(e,t);case`manual`:return BM(e,t,n)}}async function IM(e,t){if(e)return await RA(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage})}async function LM(e,t,n){let{account:r,resolved:i}=e,a=uD({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await $j(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 IM(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await hM(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function RM(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await OM({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:Gj(n),token:o.token}}),l=jM({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`);fD(l,a);let u=await Zj(o.client,n,s,l,o.chainId,o.escrow);return await hM(t,{channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function zM(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;fD(a,e.maxDeposit);let o=await Zj(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await hM(t,r),o}async function BM(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=vj({...s,chainId:o.chainId,escrow:o.escrow});kM({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:Gj(r),token:o.token});let l=await VM({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await gM(t,o.key,l),l}async function VM(e,t){switch(e.context.action){case`open`:return HM(e);case`topUp`:return UM(e,t);case`voucher`:return WM(e);case`close`:return GM(e)}}async function HM(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=bM(r,i,`cumulativeAmount`,`open`),c=await Zj(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 UM(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=bM(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:eM(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await IM(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function WM(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Zj(a.client,t,i,bM(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function GM(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Qj(a.client,t,i,bM(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}var KM,qM,JM,YM=F((()=>{Fx(),kA(),Zx(),UA(),fM(),Sj(),Bj(),tM(),sM(),DD(),KM=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),qM=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),JM=J.object({account:J.optional(J.custom()),autoSwap:J.optional(J.custom()),action:J.optional(J.enum([`open`,`topUp`,`voucher`,`close`])),channelId:J.optional(qM),cumulativeAmount:J.optional(Vx()),cumulativeAmountRaw:J.optional(J.string()),transaction:J.optional(KM),descriptor:J.optional(J.custom()),additionalDeposit:J.optional(Vx()),additionalDepositRaw:J.optional(J.string()),depositRaw:J.optional(J.string())})}));async function XM(e,t){let n=eN.get(e)??new Map;eN.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 ZM(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function QM(e,t,n){try{let r=e.response?.headers.get(q.paymentReceipt);if(r){let e=ME(r);if(e.challengeId===t.id&&ZM(n,e))return!0}}catch{}return e.challenges?.some(e=>PD(e)?ZM(n,FD(e)):!1)??!1}function $M(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a=6,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=TA({chain:He,getClient:c,rpcUrl:yO}),m=bA({account:t}),h=l===void 0?void 0:N(l,a),g=u===void 0?void 0:N(u,a),_=i??iM(),v={store:_,notifyUpdate:e=>d?.(e)},y=async(e,t,n)=>{let r=m(e.client,t),i=t?.action?t.descriptor:n?.descriptor??AM({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:_j(i)}:{}}})??r},b=async(e,t,n)=>PM({account:await y(e,t,n),entry:n,context:t,decimals:a,maxDeposit:h,resolved:e}),x=rE(vE,{canHandleChallenge:({challenge:e})=>PD(e),context:JM,async createCredential(e){let{challenge:t,context:i}=e,a=await DM({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:p}),c=vw(e),l=()=>{};try{let e=!_M(i)&&i?.descriptor===void 0;e&&(l=await XM(_,a.key),c&&(await _.get(a.key))?.opened&&await c.prepare());let n=await _.get(a.key),o=await b(a,i,n);if(!e&&c&&o.type===`open`){l=await XM(_,a.key);let e=await _.get(a.key);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await _.get(a.key)),o=await b(a,i,n))}let s,u=c&&o.type===`open`?{store:{get:e=>_.get(e),async set(e){s=e},delete:e=>_.delete(e)},notifyUpdate(){}}:v,d=await Yj(t,await FM(o,u,zA(i?.autoSwap??r,VA)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||QM(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await _.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await _.set(e),v.notifyUpdate(e))}return!0}finally{l()}}}else l();return d}catch(e){throw l(),e}}}),S=async({challenge:e,channel:t,deposit:n,fetch:r,input:i,requiredCumulative:a,signal:o})=>{let s=t.deposit>n?t.deposit:n,c=dD({deposit:s,maxDeposit:h,requiredCumulative:a,suggestedDeposit:e.request.suggestedDeposit===void 0?void 0:BigInt(e.request.suggestedDeposit),topUpAmount:g});c>0n&&await BD({additionalDeposit:c,challenge:e,channel:t,channelId:t.channelId,createSessionCredential:(e,t)=>x.createCredential({challenge:e,context:t}),fetch:r,input:i,signal:o});let l=s+c;if(l===t.deposit)return;let u=await _.get(rM(t)),d=u?.channelId.toLowerCase()===t.channelId.toLowerCase()?u:t,f={...d,deposit:d.deposit>l?d.deposit:l};await _.set(f),v.notifyUpdate(f)};return uw(x,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!PD(e))return;let c=t===void 0?void 0:JM.parse(t);if(_M(c))return;let l=await DM({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:p}),u=await _.get(l.key);if(!u?.opened)return;let d=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,f=u.cumulativeAmount+kE(e),m=d?BigInt(d.requiredCumulative):f,h=m>f?m:f,g=d?BigInt(d.deposit):u.deposit,v=g>u.deposit?g:u.deposit;h<=v&&v===u.deposit||!NM(await y(l,c,u),u.descriptor)||await S({challenge:e,channel:u,deposit:v,fetch:r,input:i,requiredCumulative:h,signal:a})}),hw(x,async({challenge:e,credential:t,fetch:r,headers:i,input:a,refetch:c,response:l,signal:u})=>{if(!PD(e))return l;if(!NE(l))return OE(YS(t).payload).action===`open`&&i.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await c?.()??l:l;let d=(await DM({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:p})).key,f=await _.get(d),m={assertVoucherWithinLocalLimit:e=>fD(e,h),createSessionCredential:(e,t)=>x.createCredential({challenge:e,context:t}),fetch:r,getChannel:()=>f??null,async topUpIfNeeded({deposit:t,requiredCumulative:n,signal:i}){f&&await S({challenge:e,channel:f,deposit:f.deposit>t?f.deposit:t,fetch:r,input:a,requiredCumulative:n,signal:i})}};return ZD({onNeedVoucher:(t,n)=>QD({challenge:e,driver:m,input:a,signal:n},t),onReceipt(){},response:l,signal:u})})}var eN,tN=F((()=>{mw(),Tw(),Fx(),nC(),iE(),xA(),kA(),UA(),bO(),bE(),Sj(),UE(),tM(),sM(),YM(),DD(),eN=new WeakMap}));function nN(e,t){iN.set(e,t)}function rN(e){let t=iN.get(e);if(!t)throw Error(`Session manager internals are unavailable.`);return t}var iN,aN=F((()=>{iN=new WeakMap}));function oN(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 sN(e){let t=oN(`close-ready`),n=oN(`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 cN=F((()=>{}));function lN(e){return e.method===jx.tempo&&e.intent===Mx.charge}function uN(e){if(!lN(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function dN(e,t,n){if(!n)return t;let r={...Aw(e instanceof Request?e.headers:void 0),...Aw(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===q.paymentSession.toLowerCase())?t:{...t,headers:{...r,[q.paymentSession]:n}}}function fN(e,t){return e===void 0?t:{...JM.parse(e),...t}}function pN(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:N(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:N(e.topUpAmount,t),WebSocket:n}}function mN(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&DA(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=pN(e),i=TA({chain:He,getClient:e.client?()=>e.client:e.getClient,rpcUrl:yO}),a=bA({account:e.account}),o=vD(),s=e.credentialContext===void 0?void 0:fN(e.credentialContext,{}),c=sN({getSocketSession:()=>o.socketSession}),l=e.channelStore??iM(),u=new Set,d;async function f(e){let t=await l.get(e);if(t?.opened&&!u.has(t.channelId))return t}let p={async get(e){let t=await f(e);return t&&d&&(d.seenExisting.add(e),!d.committed&&!d.created.has(e)&&(d.resumed??=t)),t},async set(e){let t=rM(e);e.opened&&u.delete(e.channelId),d?.trackCreates&&!d.seenExisting.has(t)&&d.created.set(t,e),await l.set(e)},delete:e=>l.delete(e)};async function m(e){let t=rM(e);u.add(e.channelId),d?.seenExisting.delete(t),d?.resumed===e&&(d.resumed=void 0),await Promise.resolve(l.delete(t)).catch(()=>void 0)}async function h(){let e=d;if(e?.created.size){for(let[t,n]of e.created)u.add(n.channelId),await Promise.resolve(l.delete(t)).catch(()=>void 0);e.created.clear(),await ie(e.committed??e.previous)}}function g(e){let t=kx(e.request.methodDetails,Nx.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=d;if(!n?.created.size||!o.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&o.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=CD({channel:o.channel,spent:o.spent,state:o.state}),!0;return!1}function _(e){return tD(o,e)}function v(){let e=o.state.status===`active`?o.state:d?.committed?.state??d?.previous.state;return e?.status===`active`?e.units:0}function y(e){let t=d,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit||(t.resumed=void 0,t.committed=CD({channel:o.channel,spent:o.spent,state:o.state}))}let b=$M({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:p,onChannelUpdate(e){e.channelId!==o.channel?.channelId&&(o.spent=0n),o.channel=e,o.lastChallenge&&_({type:`activated`,challengeId:o.lastChallenge.id,entry:e,spent:o.spent.toString(),units:v()}),y(e)}});gw(b);let x=dj({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),S=Ow({fetch:r.fetch,methods:[b],onChallenge:async(e,t)=>{if(!ND(e))return;let n=d,r=n&&n.challengesReceived>0&&e.id===o.lastChallenge?.id,i=r&&$x(e)===$x(o.lastChallenge);n&&n.challengesReceived++,!i&&(g(e)||(n?.created.size?await h():r&&await ie(n.committed??n.previous)),o.lastChallenge=e,_({type:`challengeReceived`,challengeId:e.id}))}});function C(e,t){return b.createCredential({challenge:e,context:fN(s,t)})}function w(e){yD({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:o})}function T(e=o.state.status===`active`?o.state.units:0){!o.channel||!o.lastChallenge||o.state.status!==`active`&&o.state.status!==`withdrawable`&&o.state.status!==`closeRequested`&&_({type:`activated`,challengeId:o.lastChallenge.id,entry:o.channel,spent:o.spent.toString(),units:e})}async function ee(t){let n=t.headers.get(q.paymentSessionSnapshot);if(!n)return;let r=GE(n);DA(e.allowedChainIds,r.chainId);let s=await i({chainId:r.chainId});EA(s,r.chainId);let c=a(s),{entry:l,spent:u}=await MM({account:await e.resolveAccount?.({account:c,chainId:r.chainId,operation:{authority:_j(r.descriptor),kind:`authorizePaymentChannel`}})??c,client:s,snapshot:r});return ne(l.cumulativeAmount),await Promise.resolve(p.set(l)).catch(()=>void 0),o.channel=l,o.spent=u,l}async function E(t,n){if(!e.bootstrap||o.channel?.opened)return;let i=t instanceof Request?t.headers:void 0,{body:a,method:s,...c}=n??{},l=t instanceof Request?t.url:t,u={...c,method:`HEAD`,headers:{...Aw(i),...Aw(n?.headers),[q.acceptPayment]:`${jx.tempo}/${Mx.charge}`}};try{let e=await r.fetch(l,u);if(e.status!==402)return await ee(e);let t=cS(e).find(lN);if(!t||!uN(t))return;let n=await x.createCredential({challenge:t,context:{}}),i=await r.fetch(l,{...u,headers:{...Aw(u.headers),[q.authorization]:n}});return i.ok?await ee(i):void 0}catch{return}}function D(e,t){let n=o.socketSession;return xD({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:o.channel?.channelId===t?o.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:o.spent,tickCost:n?.tickCost})}function O(e,t){let n=FD(t);if(!n)return;if(vj({...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 k(e,t){let n=O(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(o.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>o.spent&&(o.spent=i),n}function te(e,t=e.challenge,n=!1){let r=(n?k(e,t):O(e.channel,t))?.acceptedCumulative??D(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return ne(r),r.toString()}function ne(e){oD({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}async function re(e){let{knownDeposit:t,...n}=e,i=await BD({...n,channel:o.channel,createSessionCredential:C,fetch:r.fetch});w(i);let a=jD({additionalDeposit:e.additionalDeposit,channel:o.channel,channelId:e.channelId,challengeId:o.lastChallenge?.id,currentState:o.state,knownDeposit:t,receipt:i,spent:o.spent});return a?.channel&&o.lastChallenge&&(await p.set(a.channel),_({type:`activated`,challengeId:o.lastChallenge.id,entry:a.channel,spent:o.spent.toString(),units:v()}),y(a.channel)),i}async function A(e){let t=o.channel?.channelId===e.channelId?o.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=dD({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 re({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})}async function j(e,t){let n=SD({channel:o.channel,channelId:e,challengeId:o.lastChallenge?.id,cumulativeAmount:t,spent:o.spent,state:o.state});n&&o.channel&&(_({type:`activated`,challengeId:n.challengeId,entry:o.channel,spent:n.spent,units:n.units}),await l.set(o.channel))}async function ie(e){let t=wD(e,o.channel);o.channel=t.channel,o.spent=t.spent,o.state=t.state,o.channel?.opened&&await l.set(o.channel)}function ae(e){let t=e.headers.get(q.paymentReceipt),n=t?ME(t):null;return w(n),Object.assign(e,{receipt:n,challenge:o.lastChallenge,channelId:o.channel?.channelId??null,cumulative:o.channel?.cumulativeAmount??0n})}async function oe(e,t){if(d)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);o.lastUrl=e;let n=CD({channel:o.channel,spent:o.spent,state:o.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};d=i;try{await E(e,t),i.trackCreates=!0;let a=dN(e,t,o.channel?.opened?o.channel.channelId:void 0);s&&(a={...a,context:s});let c=!n.channel?.opened;async function l(){let n=i.resumed;return!c||!n?!1:(c=!1,await m(n),a=dN(e,t,void 0),!0)}for(;;){let t;try{t=await S(e,a)}catch(e){if(i.created.size?await h():await ie(i.committed??n),await l())continue;throw e}let s=ae(t),c=!1;if(s.status===402){let t=await HD({input:e,init:a,response:s,createSessionCredential:C,fetch:r.fetch,getChannel:()=>o.channel,restoreCumulative:j,setChallenge(e){o.lastChallenge=e},topUpIfNeeded:A});t&&(c=!0,s=ae(t))}if(!c&&!s.ok&&!s.receipt){if(i.created.size?await h():await ie(i.committed??n),await l())continue;return s}return s}}finally{d=void 0}}async function se(e){let t=await WD({createSessionCredential:C,fetch:r.fetch,getMinimumSpent:()=>o.spent,lastUrl:o.lastUrl,resolveSignedCloseAmount:t=>te(e,t,!0),signedCloseAmount:te(e),setChallenge(e){o.lastChallenge=e},target:e});return t&&(T(),_({type:`closeStarted`}),_({type:`closed`,receipt:t})),t}let ce={createSessionCredential:C,doFetch:oe,fetch:r.fetch,getChannel:()=>o.channel,getChallenge:()=>o.lastChallenge,assertVoucherWithinLocalLimit:ne,acceptReceipt(e){w(e)},topUpIfNeeded:A},M={get channelId(){return o.channel?.channelId},get cumulative(){return o.channel?.cumulativeAmount??0n},get opened(){return o.channel?.opened??!1},get state(){return o.state},fetch:oe,async topUp(e){let t=AD({amount:e,assertVoucherWithinLocalLimit:ne,channel:o.channel,decimals:r.decimals,lastChallenge:o.lastChallenge,lastUrl:o.lastUrl});return re({additionalDeposit:t.additionalDeposit,challenge:t.challenge,channelId:t.channelId,input:t.input})},async sse(e,t){return GD(e,t,ce)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=RD(e),i=t?.signal?{signal:t.signal}:void 0;await E(n,i);let a=o.channel?.opened?o.channel.channelId:void 0,{challenge:s,credential:l,httpUrl:u,wsUrl:d}=await eO({async createSessionCredential(e,i){return o.lastChallenge=e,await fw(b,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),C(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){o.lastUrl=e.toString()},probeInit:dN(n,i,a),signal:t?.signal});return o.lastChallenge=s,aO({challenge:s,credential:l,httpUrl:u,WebSocket:r.WebSocket,wsUrl:d,options:t,createSessionCredential:C,getChannel:()=>o.channel,setSocketSession(e){o.socketSession=e},async refreshChallenge(){let e=await $D({fetch:r.fetch,input:u,probeInit:dN(u,i,o.channel?.opened?o.channel.channelId:void 0),signal:t?.signal});return o.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:ne,acceptReceipt:w,rejectCloseReady:c.rejectCloseReady,rejectReceipt:c.rejectReceipt,settleCloseReady:c.settleCloseReady,settleReceipt:c.settleReceipt,topUpIfNeeded:A,waitForReceipt:c.waitForReceipt})},async close(){let e=o.socketSession,t=pD({channel:o.channel,currentSocket:e,lastChallenge:o.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===dO.OPEN){let r=await TD({activeSocket:n,createSessionCredential:C,currentSocket:e,spent:o.spent,target:t,waitForCloseReady:c.waitForCloseReady,waitForReceipt:c.waitForReceipt});return T(),_({type:`closeStarted`}),_({type:`closed`,receipt:r}),r}return se(t)}};return nN(M,{consumeSseResponse(e,t,n){return KD(e,t,n,ce)},rehydrate({channel:e,challenge:t,input:n,spent:r}){if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!ND(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.`);ne(e.cumulativeAmount);let i=O(e,t),a=i&&i.spent>r?i.spent:r;o.lastUrl=n,o.lastChallenge=t,o.channel=e,o.spent=a,_({type:`challengeReceived`,challengeId:t.id}),_({type:`activated`,challengeId:t.id,entry:e,spent:a.toString(),units:0})}}),M}var hN=F((()=>{_S(),_T(),mw(),Tw(),Fx(),xA(),kA(),gj(),bO(),sM(),YM(),tN(),Sj(),UE(),QE(),aN(),cN(),DD(),mO(),(function(e){e.serializeSnapshot=WE,e.deserializeSnapshot=GE})(mN||={})}));function gN(e){return e instanceof Date?e:new Date(e)}function _N(e){let t=e.getTime();if(!Number.isFinite(t))throw new Y({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new Y({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new Y({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function vN(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=LN[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>IN)throw new Y({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new Y({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function yN(e){let{challengeExpires:t,request:n}=e;vN(n);let r=_N(gN(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new Y({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function bN(e){let t=NN(e.currency,`currency`),n=NN(e.recipient,`recipient`);return[{address:t,selector:FN,recipients:[n]}]}function xN(e){try{let t=re.fromBytes(k.toBytes(e));if(re.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function SN(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=wN({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:We.getSignPayload(o)}),c=Ge.from(s);if(c.type===`keychain`||c.type===`multisig`)throw new Y({reason:`keyAuthorization must use a primitive signature`});return We.from(o,{signature:s})}function CN(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new Y({reason:`invalid keyAuthorization payload`});let o=TN(i.signature),s=EN(o);if(DN({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==xN(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return ON(o,a),AN(kN(o),a),jN(o.scopes,a),{authorization:o,source:{address:MN(o,s),chainId:r}}}function wN(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return We.from({address:NN(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:_N(gN(i.subscriptionExpires)),limits:[{token:NN(i.currency,`currency`),limit:BigInt(i.amount),period:vN(i)}],scopes:bN(i),type:t.keyType,witness:xN(n)})}function TN(e){try{return We.deserialize(e)}catch(e){throw e instanceof We.InvalidSignatureTypeError?new Y({reason:`keyAuthorization must use a primitive signature`}):new Y({reason:`invalid keyAuthorization payload`})}}function EN(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function DN(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new Y({reason:`keyAuthorization chainId mismatch`});if(t){if(!fe(n.address,NN(t.accessKeyAddress,`accessKeyAddress`)))throw new Y({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new Y({reason:`keyAuthorization key type mismatch`})}}function ON(e,t){if(yN({request:t}),e.expiry!==_N(gN(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function kN(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new Y({reason:`keyAuthorization must contain exactly one token limit`});return t}function AN(e,t){if(!fe(e.token,NN(t.currency,`currency`)))throw new Y({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new Y({reason:`keyAuthorization amount mismatch`});if(e.period!==vN(t))throw new Y({reason:`keyAuthorization period mismatch`})}function jN(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=NN(t.currency,`currency`),r=NN(t.recipient,`recipient`),i=new Set;for(let t of e){if(!fe(t.address,n))throw new Y({reason:`keyAuthorization call target mismatch`});let e=PN(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new Y({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new Y({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!fe(t.recipients[0],r))throw new Y({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new Y({reason:`keyAuthorization must allow transferWithMemo`})}function MN(e,t){let n=We.getSignPayload(e);try{let e=Ge.extractAddress({payload:n,signature:t});if(!Ge.verify(t,{address:e,payload:n}))throw new Y({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof Y?e:new Y({reason:`keyAuthorization signature is invalid`})}}function NN(e,t){if(!de(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function PN(e){return typeof e==`string`?e.toLowerCase():``}var FN,IN,LN,RN=F((()=>{SS(),FN=`0x95777d59`,IN=(1n<<64n)-1n,LN={dev_second:1n,day:86400n,week:604800n}}));function zN(e={}){let t=TA({chain:ye,getClient:e.getClient,rpcUrl:yO}),n=bA({account:e.account});return rE(yE,{context:HN,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??hO.testnet,o=await t({chainId:a}),s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");VN(r.request),await e.validateRequest?.(r.request);let l=await BN(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=CN({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:We.serialize(l),type:`keyAuthorization`},request:r.request});if(!fe(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return $S({challenge:r,payload:{signature:We.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function BN(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await SN({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:_N(gN(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:re.fromNumber(BigInt(o.amount)),period:vN(o)}],scopes:bN(o),witness:xN(i)}]});return We.fromRpc(c.keyAuthorization)}function VN(e){vN(e),_N(gN(e.subscriptionExpires))}var HN,UN=F((()=>{nC(),iE(),xA(),kA(),Zx(),bO(),bE(),RN(),HN=J.object({accessKey:J.optional(J.custom()),account:J.optional(J.custom())})}));function WN(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[dj(e),GN(n)]}var GN,KN=F((()=>{tN(),hN(),gj(),UN(),GN=Object.assign($M,{manager:mN}),(function(e){e.charge=dj,e.common=WN,e.session=GN,e.subscription=zN})(WN||={})})),qN=F((()=>{gj(),KN(),UN(),tN(),hN()})),JN=Qe({orderTempoChargeChallengesByBalance:()=>XN,readTempoKeystore:()=>gP,resolveTempoAccount:()=>_P,tempo:()=>ZN});async function YN(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}async function XN(e,t){let n=[],r=[];for(let[t,i]of e.entries())iP(i)&&(n.push(t),r.push(i));if(r.length<2)return[...e];let i=await aP(t).catch(()=>void 0);if(!i)return[...e];let a=await Promise.all(r.map(async(e,t)=>({challenge:e,index:t,score:await oP(e,i)})));a.sort((e,t)=>TP.indexOf(e.score)-TP.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 ZN(){let e;return oA({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:t,options:n,methodOpts:r}){let i=tk(n.account),a=t.request,o=a.currency,s=rP(r),c=uP({autoSwap:s.autoSwap??n.autoSwap,payWith:s.payWith??n.payWith,slippage:s.slippage??n.slippage,tokenIn:s.tokenIn}),l=o??``,u=a.decimals??6,d,f,p,m=!1,h=process.env.MPPX_PRIVATE_KEY?.trim()||(AO(i)?void 0:await nk(i).get());if(!h&&AO(i)&&vP()){m=!0;let e=_P(i);if(e){let r=PO(n.rpcUrl,{network:n.network});p=j({chain:await IO({network:n.network,rpcUrl:r}),transport:ue(r)}),cP({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let i=o?await BO(p,o,e.wallet_address).catch(()=>void 0):void 0;l=i?.symbol??o??``,u=i?.decimals??a.decimals??6}}else if(h)f=ve(h);else{let e=bP();if(e){let t=await nk(e).get();t&&(f=ve(t))}if(!f)throw n.account?new I({code:`ACCOUNT_NOT_FOUND`,message:`Account "${i}" not found.`,exitCode:69}):new I({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!m&&f){let e=PO(n.rpcUrl,{network:n.network});p=j({chain:await IO({network:n.network,rpcUrl:e}),transport:ue(e)}),cP({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let r=o?await BO(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 yP(t)}};if(!f||!p)throw new I({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let g=WN({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??(zO(p.chain)?`10`:void 0);if(!n)throw new I({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=fP(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 Nj(p,f,c,i,a);return $S({challenge:t,payload:{action:o,channelId:n,...o===`close`?{closeSignature:await Pj(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=YS(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?``:`
233
233
  `}${X.dim(`Channel opened ${h.payload.channelId}`)}${t}\n`)}else m(`${l?``:`
234
- `}${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));zN(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&$N(v,S),s>=1&&RN(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
235
- `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await BN(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 FN(C),v&&y&&b&&(l&&m(`
236
- `),l&&!await t.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await VN({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 RN(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(`(${SO(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,gO(`${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(`
237
- `)}function zN(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 BN(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 HN():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{RN(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
234
+ `}${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));$N(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&pP(v,S),s>=1&&QN(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
235
+ `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await eP(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 YN(C),v&&y&&b&&(l&&m(`
236
+ `),l&&!await t.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await tP({channelId:v,cumulativeAmount:S,escrowContract:y,chainId:b,fetchUrl:a,fetchInit:o,session:e,info:m,verbose:s,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,confirmEnabled:l}))),!0},formatReceiptField(e,t){(e===`reference`||e===`txHash`)&&typeof t==`string`&&t.startsWith(`0x`)}})}function QN(e,t){t.info(`${t.prefix??``}${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(`(${NO(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,DO(`${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(`
237
+ `)}function $N(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 eP(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 nP():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{QN(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
238
238
 
239
239
  `})}catch{}o=``;continue}if(e.length===0)u(`
240
240
  `);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(`
241
- `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await VN({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 VN(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:{...Sw(e.fetchInit.headers),Authorization:t}});if(n.ok){if(eP(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(gO(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${SO(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 HN(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 UN(e){return qN(lP,e,uP)}function WN(e){return e.method===`tempo`&&e.intent===`charge`}async function GN(e){let t=WO(e.options.account),n=process.env.MPPX_PRIVATE_KEY?.trim()||(yO(t)?void 0:await GO(t).get()),r;if(n)r=_e(n).address;else if(yO(t)&&iP())r=rP(t)?.wallet_address;else{let e=oP();if(e){let t=await GO(e).get();t&&(r=_e(t).address)}}if(!r)return;let i=CO(e.options.rpcUrl,{network:e.options.network}),a=j({chain:await TO({network:e.options.network,rpcUrl:i}),transport:ue(i)});return{account:r,client:a}}async function KN(e,t){let n=e.request,r=n.currency,i=n.amount;if(typeof r!=`string`||typeof i!=`string`)return`unsupported`;let a=n.methodDetails?.chainId;if(a&&t.client.chain?.id&&a!==t.client.chain.id)return`unsupported`;let o=BigInt(i);if(o===0n)return`payable`;let s=await Fe.token.getBalance(t.client,{account:t.account,token:r}).then(e=>e.amount).catch(()=>void 0);return s===void 0?`unknownBalance`:s>=o?`payable`:`insufficientBalance`}function qN(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 JN(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new I({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function YN(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function XN(e){let t=YN(e.tokenIn)??YN(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 ZN(){return c.join(process.env.XDG_CONFIG_HOME||c.join(b.homedir(),`.config`),`mppx`,`channels`)}function QN(e){try{let n=t.readFileSync(c.join(ZN(),e),`utf-8`).trim();return n?BigInt(n):void 0}catch{return}}function $N(e,n){let r=ZN();t.mkdirSync(r,{recursive:!0}),t.writeFileSync(c.join(r,e),n.toString(),`utf-8`)}function eP(e){try{t.unlinkSync(c.join(ZN(),e))}catch{}}function tP(){return b.platform()===`darwin`?c.join(b.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):c.join(process.env.XDG_DATA_HOME||c.join(b.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function nP(){try{let e=t.readFileSync(tP(),`utf-8`),n=[],r;for(let t of e.split(`
242
- `)){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 rP(e){let t=nP();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 iP(){if(fP!==void 0)return fP;try{m.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),fP=!0}catch{fP=!1}return fP}async function aP(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 oP(){let e=UO();if(yO(e.get())&&!iP()&&b.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]===sP&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}var sP,cP,lP,uP,dP,fP,pP=F((()=>{Dx(),oT(),Px(),eC(),NN(),ME(),Ej(),ZO(),LO(),Xk(),sP=`mppx`,cP=p.union([p.boolean(),p.literal(`true`).transform(()=>!0),p.literal(`false`).transform(()=>!1)]),lP=p.object({allowCustomEscrow:p.optional(cP),autoSwap:p.optional(cP),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())}),uP=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`],dP=[`payable`,`unknownBalance`,`insufficientBalance`,`unsupported`]}));ES(),ZO(),Xk();const mP=[...Object.entries(rk),...Object.entries(ik),...Object.entries(ak),...Object.entries(ok)];function hP(){return Yk({method:`evm`,supports:gP,async setup({challenge:e,options:t}){let n=e.request,r=n.network?_P(pk(n.network)):void 0,i=n.network&&n.asset?mP.find(([,e])=>dk(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`?tk({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await JO(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...Jk({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function gP(e){if(!wS(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 _P(e){return Object.values(Be).find(t=>t.id===e)}gS(),KS(),pP();const vP=[LN(),oA(),Zk(),hP()];async function yP(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 bP(e,t){let n=t?.plugins?.find(t=>wP(t,e));if(n)return{plugin:n};let r=CP(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=vP.find(t=>wP(t,e));return a?{plugin:a}:{}}function xP(e,t){let n=CP(t);if(n?.length){let r=jS(e,n,OS(n,t?.paymentPreferences).entries);if(r){let e=t?.plugins?.find(e=>wP(e,r.challenge));return{challenge:r.challenge,...e?{plugin:e}:{method:r.method}}}return}for(let n of e){let e=bP(n,t);if(e.plugin||e.method)return{challenge:n,...e}}}function SP(e){let t=CP(e);if(t?.length)return OS(t,e?.paymentPreferences).header}function CP(e){return Array.isArray(e?.methods)?e.methods.flat():void 0}function wP(e,t){return e.supports?e.supports(t):e.method===t.method}async function TP(e){let t=EP(e);if(!t)return;let n=await import(t);return{config:n.default??n,path:t}}function EP(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 DP(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}return Qx({...t,request:n,id:e.id,expires:e.expires})}if(n(t)!==n(e))throw Error(`Payment request changed on retry. Run the command again to approve the new payment.`)}pP(),gS(),Vj(),GM(),tN(),rO();function OP(e){return e??globalThis.fetch.bind(globalThis)}function kP(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(Pj(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Error(`Close challenge changed the session escrow.`);let r=wD(e);if(r&&r.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Close challenge changed the session channel.`)}async function AP(e){kP(e.challenge,e.channel);let t=OP(e.fetch),n,r=async(r,i)=>{n&&=(await e.onChallenge?.(n),void 0);let a=await t(r,i);if(a.status!==402)return a;let o=sS(a).find(SD);if(!o)throw Error(`Refreshed close response did not include tempo/session.`);return kP(o,e.channel),n=o,a},i=eN({...e.manager,bootstrap:!1,escrow:e.channel.escrow,fetch:r});UM(i).rehydrate(e);let a=await i.close();if(!a)throw Error(`Session close response did not include a payment receipt.`);return{manager:i,receipt:a}}gS(),Vj(),qj(),rO(),cj(),Xx();var jP=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}},MP=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 NP=J.object({channelId:Kx(),cumulativeAmount:J.string(),deposit:J.string(),descriptor:J.object({payer:Gx(),payee:Gx(),operator:Gx(),token:Gx(),salt:Kx(),authorizedSigner:Gx(),expiringNonceHash:Kx()}),escrow:Gx(),chainId:J.number(),opened:J.boolean()}),PP=J.object({name:J.optional(J.string()),address:Gx()}),FP=J.object({method:J.literal(`tempo`),intent:J.literal(`session`),status:J.literal(`success`),timestamp:J.string(),reference:J.string(),challengeId:J.string(),channelId:Kx(),acceptedCumulative:J.string(),spent:J.string(),units:J.optional(J.number()),txHash:J.optional(Kx())}),IP=J.object({version:J.literal(1),method:J.literal(`tempo`),intent:J.literal(`session`),status:J.enum([`opening`,`open`,`closing`,`stale`]),channel:NP,account:PP,endpoint:J.string(),challenge:hS,receipt:J.optional(FP),spent:J.string(),units:J.number(),createdAt:J.string(),updatedAt:J.string()}),LP=J.object({version:J.literal(1),channelId:Kx()}),RP=J.object({version:J.literal(1),scope:J.string(),hostname:J.string(),pid:J.number(),token:J.string(),createdAt:J.string()});function zP(e,t,n,r){let i=e.safeParse(t);if(!i.success)throw Z(n,r,i.error);return i.data}function BP(e){let t=XP(e);return[t.payer,t.payee,t.token,t.escrow,t.chainId].join(`:`)}function VP(e){return{payer:e.descriptor.payer,payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId}}function HP(e={}){let t=e.stateRoot??WP(),n={root:t,channels:c.join(t,`channels`),locks:c.join(t,`locks`),preferred:c.join(t,`preferred`)},r=e.hostname??b.hostname(),i=e.pid??process.pid,a=e.now??(()=>new Date),o=e.isProcessAlive??SF;async function s(){for(let e of[n.root,n.channels,n.locks,n.preferred])await C.mkdir(e,{recursive:!0,mode:448}),await C.chmod(e,448)}async function l(e){let t=JP(e),r=GP(n,t),i=await pF(r);if(i===void 0)return;let a=iF(i,r);if(a.channel.channelId.toLowerCase()!==t)throw Z(r,`Session filename does not match its channel ID.`);return aF(a)}async function u(){let e;try{e=await C.readdir(n.channels,{withFileTypes:!0})}catch(e){if(wF(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);JP(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=eF(e.channel),r=JP(t.channelId),i=GP(n,r),o=await pF(i),c=o===void 0?void 0:iF(o,i);c&&oF(c,e,i);let l=nF(e.challenge,i);cF(l,t,i);let u=e.receipt?rF(e.receipt,t.channelId,i):void 0,d=c?Kj(c.channel):void 0,f=fF(t.cumulativeAmount,d?.cumulativeAmount??0n),p=fF(e.spent??0n,u?BigInt(u.spent):0n,c?BigInt(c.spent):0n);if(p>f)throw Z(i,`Session spend exceeds the locally authorized cumulative amount.`);let m=tF(Gj({...t,cumulativeAmount:f}),i),h=dF(c?.updatedAt,a(),i),g=uF(c?.receipt,u),_=$P(e.account,i),v=iF({version:1,method:`tempo`,intent:`session`,status:e.status,channel:m,account:{..._.name===void 0?c?.account.name===void 0?{}:{name:c.account.name}:{name:_.name},address:_.address},endpoint:QP(e.endpoint,i),challenge:l,...g!==void 0&&{receipt:g},spent:p.toString(),units:Math.max(c?.units??0,e.units??0,u?.units??0),createdAt:c?.createdAt??h,updatedAt:h},i);return await mF(i,v),aF(v)}async function f(e){let t=qP(n,e),r=await pF(t);if(r===void 0)return;let{channelId:i}=zP(LP,r,t,`Preferred session is invalid.`),a=await l(i);if(!a)throw Z(t,`Preferred session ${i} does not exist.`);return lF(a.channel,e,t),i}async function p(e,t){let r=JP(t),i=await l(r),a=qP(n,e);if(!i)throw Z(a,`Session ${r} does not exist.`);lF(i.channel,e,a),await mF(a,{version:1,channelId:r})}async function m(e,t){let r=qP(n,e),i=t===void 0?void 0:JP(t),a=await pF(r);if(a===void 0)return;let o=zP(LP,a,r,`Preferred session is invalid.`).channelId;i&&o.toLowerCase()!==i||await bF(r,`Unable to clear preferred session.`)}async function h(e){let t=JP(e),r=await l(t);r&&(await m(VP(r.channel),t),await bF(GP(n,t),`Unable to remove session.`))}async function g(e){await s();let t=KP(n,e);for(let n=0;n<3;n++){let n={version:1,scope:e,hostname:r,pid:i,token:_(),createdAt:a().toISOString()};try{if(await hF(t,n),await vF(_F(t))){await yF(t,n);continue}return{async release(){await yF(t,n)}}}catch(e){if(!wF(e,`EEXIST`))throw e}let s=await pF(t);if(s===void 0)continue;let c=zP(RP,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 MP(e,c);await gF(t,c)}let c=await pF(t);throw c===void 0?Z(t,`Unable to acquire session lock.`):new MP(e,zP(RP,c,t,`Session lock is invalid.`))}async function v(e){return g(BP(e))}return{root:t,get:l,list:u,upsert:d,remove:h,getPreferred:f,setPreferred:p,clearPreferred:m,acquire:v}}function UP(e,t){let n=ZP(t.scope),r=t.selection===`auto`||t.selection===`new`?void 0:JP(t.selection);function i(e){if(e.toLowerCase()!==n)throw new jP(`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 jP(`Session ${i} does not exist.`);if(lF(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(Uj(n)),lF(n,t.scope),r&&r.toLowerCase()!==n.channelId.toLowerCase())throw new jP(`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 WP(){let e=process.env.XDG_STATE_HOME||c.join(b.homedir(),`.local`,`state`);return c.join(e,`mppx`,`sessions`,`v1`)}function GP(e,t){return c.join(e.channels,`${t}.json`)}function KP(e,t){let n=g(`sha256`).update(t).digest(`hex`);return c.join(e.locks,`${n}.lock`)}function qP(e,t){let n=g(`sha256`).update(BP(t)).digest(`hex`);return c.join(e.preferred,`${n}.json`)}function JP(e){return zP(Kx(),e,void 0,`Invalid session channel ID: ${e}.`).toLowerCase()}function YP(e,t,n){return zP(Gx(),e,n,`Invalid ${t}.`).toLowerCase()}function XP(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<0)throw new jP(`Invalid session chain ID.`);return{payer:YP(e.payer,`session payer`),payee:YP(e.payee,`session payee`),token:YP(e.token,`session token`),escrow:YP(e.escrow,`session escrow`),chainId:e.chainId}}function ZP(e){let t=XP(e);return[t.payee,t.token,t.escrow,t.chainId].join(`:`)}function QP(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 $P(e,t){return zP(PP,e,t,`Session account is invalid.`)}function eF(e){return Kj(tF(Gj(e)))}function tF(e,t){return zP(NP,e,t,`Stored session channel is invalid.`)}function nF(e,t){let n=hS.safeParse(e);if(!n.success||!SD(n.data))throw Z(t,`Stored session challenge is invalid.`);return n.data}function rF(e,t,n){let r=zP(FP,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 iF(e,t){let n=zP(IP,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?rF(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=QP(n.endpoint,t);if(u!==n.endpoint)throw Z(t,`Stored session endpoint contains a fragment.`);let d=nF(n.challenge,t);return cF(d,Kj(a),t),{...i,account:o,channel:a,endpoint:u,challenge:d,...s&&{receipt:s}}}function aF(e){return{version:1,status:e.status,channel:Kj(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 oF(e,t,n){let r=eF(t.channel),i=$P(t.account,n),a=Kj(e.channel);if(JSON.stringify(sF(r))!==JSON.stringify(sF(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 sF(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 cF(e,t,n){if(ij({...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=YP(e.request.recipient,`challenge recipient`,n),i=YP(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(Pj(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Z(n,`Session challenge escrow does not match the channel.`);if(CF(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 lF(e,t,n){let r=XP(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 uF(e,t){return e?t&&Date.parse(t.timestamp)>=Date.parse(e.timestamp)?t:e:t}function dF(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 fF(...e){return e.reduce((e,t)=>t>e?t:e,0n)}async function pF(e){let t;try{t=await C.readFile(e,`utf8`)}catch(t){if(wF(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 mF(e,t){await C.mkdir(c.dirname(e),{recursive:!0,mode:448}),await C.chmod(c.dirname(e),448);let n=`${e}.tmp-${process.pid}-${_()}`,r;try{r=await C.open(n,`wx`,384),await r.writeFile(`${JSON.stringify(t,null,2)}\n`,`utf8`),await r.sync(),await r.close(),r=void 0,await C.rename(n,e),await C.chmod(e,384),await xF(c.dirname(e))}catch(t){throw await r?.close().catch(()=>void 0),await C.unlink(n).catch(()=>void 0),t instanceof jP?t:Z(e,`Unable to write session state.`,t)}}async function hF(e,t){let n;try{n=await C.open(e,`wx`,384),await n.writeFile(`${JSON.stringify(t)}\n`,`utf8`),await n.sync(),await n.close(),n=void 0,await xF(c.dirname(e))}catch(t){throw await n?.close().catch(()=>void 0),n&&await C.unlink(e).catch(()=>void 0),t}}async function gF(e,t){let n=_F(e);try{await C.link(e,n)}catch(t){if(wF(t,`EEXIST`)||wF(t,`ENOENT`))return;throw Z(e,`Unable to claim dead lock.`,t)}try{let r=await pF(n);if(r===void 0||zP(RP,r,n,`Session lock is invalid.`).token!==t.token)return;await bF(e,`Unable to reclaim dead lock.`)}finally{await bF(n,`Unable to release dead lock claim.`)}}function _F(e){return`${e}.reclaim`}async function vF(e){try{return await C.access(e),!0}catch(t){if(wF(t,`ENOENT`))return!1;throw Z(e,`Unable to inspect session lock.`,t)}}async function yF(e,t){let n=await pF(e);n!==void 0&&zP(RP,n,e,`Session lock is invalid.`).token===t.token&&await bF(e,`Unable to release session lock.`)}async function bF(e,t){try{await C.unlink(e),await xF(c.dirname(e))}catch(n){if(!wF(n,`ENOENT`))throw Z(e,t,n)}}async function xF(e){let t=await C.open(e,`r`);try{await t.sync()}finally{await t.close()}}function SF(e){try{return process.kill(e,0),!0}catch(e){if(wF(e,`ESRCH`))return!1;if(wF(e,`EPERM`))return!0;throw e}}function CF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wF(e,t){return e instanceof Error&&`code`in e&&e.code===t}function Z(e,t,n){return new jP(t,{...n!==void 0&&{cause:n},file:e})}Dx(),oT(),FM(),Qj(),cj(),ZO(),LO();const TF=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()}),EF=p.object({channelId:p.string(),status:p.enum([`closed`,`already-closed`]),spent:p.string(),txHash:p.string().optional()}),DF=p.object({closed:p.array(EF),failed:p.array(p.object({channelId:p.string(),message:p.string()}))});function OF(e){return e===`mainnet`?ve.id:ye.id}function kF(e){if(e===ve.id)return`mainnet`;if(e===ye.id)return`testnet`}function AF(e){let t={};for(let n of e??[]){let e=n.indexOf(`:`);if(e===-1)throw new I({code:`INVALID_HEADER`,message:`Invalid header format: ${n}`,exitCode:2});t[n.slice(0,e).trim()]=n.slice(e+1).trim()}return t}function jF(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 MF(e,t){throw e instanceof I?e:e instanceof MP?new I({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e instanceof jP?new I({code:e.code,message:e.message,exitCode:65,cause:e}):new I({code:t,message:e instanceof Error?e.message:String(e),exitCode:75,...e instanceof Error&&{cause:e}})}async function NF(e,t){let n=await qO(t??e.account.name);if(!yM(n.account,e.channel.descriptor))throw new I({code:`SESSION_ACCOUNT_MISMATCH`,message:`Account ${n.account.address} cannot sign for session ${e.channel.channelId}.`,exitCode:2});return n}async function PF(e,t){if(t.network&&OF(t.network)!==e)throw new I({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, not ${t.network}.`,exitCode:2});let n=t.network??kF(e),r=CO(t.rpcUrl,{network:n}),i=await TO({network:n,rpcUrl:r});if(i.id!==e)throw new I({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, but RPC is chainId ${i.id}.`,exitCode:2});return j({chain:i,transport:ue(r)})}const FF=sb(`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(TF)}),alias:{account:`a`},async run(e){try{let t=(await HP().list()).filter(t=>!(e.options.account&&t.account.name!==e.options.account||e.options.network&&t.channel.chainId!==OF(e.options.network))).map(jF),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(``),IF(n);return}catch(e){return MF(e,`SESSION_LIST_FAILED`)}}}).command(`view`,{description:`View a persistent payment session`,args:p.object({channelId:p.string().describe(`Full session channel ID`)}),output:TF,async run(e){try{let t=await HP().get(e.args.channelId);if(!t)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e.args.channelId} was not found.`,exitCode:2});let n=jF(t);if(e.format===`json`&&e.formatExplicit)return e.ok(n);IF(n);return}catch(e){return MF(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([EF,DF]),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=HP();async function n(e,n={}){let r=await t.get(e);if(!r)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let i=VP(r.channel),a=await t.acquire(i);try{let r=await t.get(e);if(!r)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let a=await NF(r,n.account),o=await PF(r.channel.chainId,n);if(ij({...r.channel.descriptor,escrow:r.channel.escrow,chainId:r.channel.chainId}).toLowerCase()!==r.channel.channelId.toLowerCase())throw new I({code:`SESSION_STATE_INVALID`,message:`Stored descriptor does not derive the session channel ID.`,exitCode:65});if((await Yj(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=QP(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=AF(n.headers),f=u.challenge,p=await AP({channel:u.channel,challenge:u.challenge,fetch:async(e,t)=>globalThis.fetch(e,{...t,headers:{...d,...Sw(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:UP(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===OF(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 MF(e,`SESSION_CLOSE_FAILED`)}}});function IF(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}`)}Dx(),FM(),GM(),tN(),ME(),ZO(),LO();function LF(e,t){if(t&&e!==`auto`&&t.toLowerCase()!==e.toLowerCase())throw new I({code:`SESSION_SELECTION_CONFLICT`,message:`--session and -M channel= select different sessions.`,exitCode:2});let n=t??e;if(n===`auto`||n===`new`)return n;if(/^0x[0-9a-fA-F]{64}$/.test(n))return n.toLowerCase();throw new I({code:`INVALID_SESSION`,message:`Session must be auto, new, or a 32-byte channel ID.`,exitCode:2})}function RF(e){let t=e.allowCustomEscrow;if(t!==void 0){if(t===`true`)return!0;if(t===`false`)return!1;throw new I({code:`INVALID_ALLOW_CUSTOM_ESCROW`,message:`allowCustomEscrow must be true or false.`,exitCode:2})}}function zF(e,t,n,r){if(t.deposit!==void 0)return t.deposit;let i=e.request.suggestedDeposit;return typeof i==`string`?ce(BigInt(i),r):n?`10`:void 0}function BF(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 VF(e,t){return e.channel.channelId.toLowerCase()===t.toLowerCase()}function HF(e){if(e.trim()!==`[DONE]`){if(e.length===0){process.stdout.write(`
243
- `);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 UF(e){let{options:t}=e,n=await qO(t.account),r=CO(t.rpcUrl,{network:t.network}),i=await TO({network:t.network,rpcUrl:r}),a=j({chain:i,transport:ue(r)}),o=RF(e.methodOptions),s=await pM({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new I({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let{decimals:c}=await kO(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=LF(t.session,e.methodOptions.channel),d=e.registry??HP(),f=await d.acquire(l).catch(e=>{throw e instanceof MP?new I({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=u===`auto`?await d.getPreferred(l):u===`new`?void 0:u,s=r?await d.get(r):void 0;if(r&&!s)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&u!==`auto`&&(s.status!==`open`||!s.channel.opened||BP(VP(s.channel))!==BP(l)||!yM(n.account,s.channel.descriptor)))throw new I({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let f=s?.status===`open`&&s.channel.opened?s:void 0,p=f?`open`:`opening`,m=e.challenge,h=f?.receipt,g=f?.spent??0n,_=f?.units??0,v=QP(e.endpoint),y={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},b=UP(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=eN({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:b,credentialContext:e.credentialContext,decimals:c,maxDeposit:zF(e.challenge,e.methodOptions,OO(i),c),fetch:async(t,n)=>w?(w=!1,e.challengeResponse):e.fetch(t,n)});f&&UM(T).rehydrate({channel:f.channel,challenge:e.challenge,input:e.fetchInput,spent:f.spent});let{onReceipt:ee,...E}=C,D=await T.fetch(e.fetchInput,E);if(t.fail&&D.status>=400)throw new I({code:`HTTP_ERROR`,message:`HTTP error ${D.status}`,exitCode:22});if(D.status===402)throw new I({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});fO(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=BF(D.receipt,{challenge:m,channelId:O,cumulative:T.cumulative})??h,SE(D)){let t=UM(T).consumeSseResponse(e.fetchInput,D,{onReceipt:ee,signal:e.init.signal??void 0});for await(let e of t)HF(e)}else process.stdout.write(Buffer.from(await D.arrayBuffer()));let k=await d.get(O);if(!k||!VF(k,O))throw Error(`Session ${O} was not persisted.`);if(h){let e=BF(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()}}LO();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 WF(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function GF(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}const KF={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function qF(e){let t=KF[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 JF(e){console.log(`\n${X.bold(e)}`)}function YF(e,t){for(let n of e)qF(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`suggested`?t.suggested++:n.severity===`skip`&&t.skipped++}async function XF(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{return await fetch(e,{...t,signal:r.signal})}finally{clearTimeout(i)}}function ZF(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const QF=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function $F(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function eI(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function tI(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!QF.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 nI(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 rI(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 iI(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await XF(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 aI(e){let t=new URL(`/llms.txt`,e).href,n=`llms.txt found and nonempty`;try{let e=await XF(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 oI(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=lI(i.parameters);for(let[a,o]of Object.entries(i)){if(!QF.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=uI(r,lI(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 sI(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=fI(o,e,s),!o||o.type!==`object`)return;let c=pI(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function cI(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=dI(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 lI(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 uI(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 dI(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 fI(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 pI(e,t,n){let r=fI(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]=pI(i,t,n))}return a}default:return null}}gS(),Px(),ew(),LO();const mI=Object.values(Be);function hI(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&mI.find(e=>e.id===t.chainId)?.testnet===!0}async function gI(e,t,n,r){let i=[],a;try{a=cI(e,t,r?.query)}catch(e){return i.push($(`Request URL valid`,e.message)),{results:i}}let o=rI(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 XF(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?sI(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 XF(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(GF(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(GF(`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=DI(c);if(!l)return u.length>0?(i.push(GF(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(GF(`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(`${kx.payment} `))return i.push(GF(`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=sS(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(WF(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0)return i.push($(`Challenge parseable`,`No Payment challenges found in header`)),{results:i};let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push(Q(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=new URL(e).hostname;_I(d,i),vI(d,i),yI(d,i),bI(d,p,i);let m=d.length>1;for(let e of d){let t=e.request;xI(e,t,i,m)}if(n)for(let e of d)console.log(X.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function _I(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 vI(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 yI(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(WF(`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 bI(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 xI(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===Ax.tempo?SI(t,i,n,e):e.method===Ax.stripe?CI(t,i,n):e.method===Ax.evm&&wI(e,t,i,n)}function SI(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if($F(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.`)),$F(e.currency)){let e=hI(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.`));TI(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function CI(e,t,n){TI(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 wI(e,t,n,r){if($F(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.`)),$F(t.currency)){let t=hI(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.`));TI(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 TI(e,t,n,r){eI(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 EI(e,t,n){let r=[],i=cI(e,t,n?.query),a={[q.authorization]:`${kx.payment} dGhpcyBpcyBnYXJiYWdl`},o;n?.body&&(o=n.body,a[`content-type`]=`application/json`);try{let e=await XF(i,{method:t.method,headers:a,body:o??null});e.status===402?(r.push(Q(`Malformed credential returns 402`,`not 500`)),e.headers.get(q.wwwAuthenticate)?.startsWith(`${kx.payment} `)?r.push(Q(`Error response includes fresh challenge`)):r.push(WF(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the Authorization header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(WF(`Malformed credential returns 402`,`Got ${e.status}`,`When the Authorization header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function DI(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=qC(n);t.push(Q(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(WF(`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 OI=[`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(`
244
- `);Xx();const kI={fundingCurrency:J.optional(J.string()),method:J.string(),reference:J.string(),externalId:J.optional(J.string()),subscriptionId:J.optional(J.string()),status:J.literal(`success`),timestamp:Vx()};J.object(kI);const AI=J.looseObject(kI);function jI(e){let t=k.toString(e);return MI(JSON.parse(t))}function MI(e){return AI.parse(e)}gS(),Px(),NN(),lO(),rO(),ZO(),LO();async function NI(e,t,n){try{n||console.log(X.dim(` Provisioning testnet wallet and funding via faucet...`));let t=he(),r=_e(t),i=j({chain:ye,transport:ue()});if(SD(e)){let{chainId:t,operator:n}=e.request.methodDetails??{};if(t===ye.id&&typeof n==`string`&&de(n)&&n!==me){let e=await Fe.faucet.fund(i,{account:n});await Promise.all(e.map(e=>Me(i,{hash:e})))}}let a=await Fe.faucet.fund(i,{account:r});await Promise.all(a.map(e=>Me(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 Fe.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:[...AN({account:r})]}}catch(e){t&&console.log(X.dim(` Provisioning failed: ${e.message}`));return}}async function PI(){let e=WO(),{isTempoAccount:t}=await Promise.resolve().then(()=>(LO(),uO)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(pP(),PN));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await JO()).address}catch{return}}function FI(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 II(e,t,n){let r=j({chain:e,transport:ue()}),[i,a,o]=await Promise.all([n?De(r,{address:t,abi:se,functionName:`balanceOf`,args:[n]}):0n,De(r,{address:t,abi:se,functionName:`decimals`}),De(r,{address:t,abi:se,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,decimals:a,symbol:o??void 0}}function LI(e){return Object.values(Be).find(t=>t.id===e)}function RI(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function zI(e){switch(e.method){case Ax.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 BI(e,t,n,r){let i=[],a=cI(e,t,r.query),o=rI(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await XF(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(GF(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=sS(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=[];bI(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 TP().catch(()=>void 0),p=l.find(e=>{if(e.method!==Ax.tempo||CP(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!==iO.mainnet});if(p){let e=await NI(p,n,r.silent);if(e)try{await GI(i,await dT({methods:e.methods,polyfill:!1,async onChallenge(e,{createCredential:t}){DP(p,e);let n=await t(await yP(e,f?.config.extensions));return i.push(Q(`Payment: submitted`,`ephemeral testnet wallet`)),n},fetch:(e,t)=>XF(e,t??{},3e4)}).fetch(a,{method:t.method,headers:o,body:s??null}),n,ye)}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??FI(n),g=h?.startsWith(`sk_test_`)||h?.startsWith(`rk_test_`),_=new Set([Ax.tempo,Ax.evm,Ax.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 Ax.tempo:case Ax.evm:await VI(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,options:r});break;case Ax.stripe:await HI(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 VI(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=eI(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,{plugin:g,method:_}=bP(e,l?.config);if(!g&&!_){r.push(GF(t,zI(e)));return}let v;if(!_){try{v=await PI()}catch{}if(!v){r.push(GF(t,`no wallet configured. Run "mppx account create" to create one.`));return}}let y;if(e.method===Ax.tempo){let e=f?.chainId??(_?void 0:ve.id);e!==void 0&&(y=e===ye.id?ye:LI(e))}else if(e.method===Ax.evm){let e=f?.chainId;e&&(y=LI(e))}if(p&&h&&!y){r.push(GF(t,`unable to resolve payment chain and verify token decimals`));return}let b;if(p&&h&&y)try{let n;if(e.method===Ax.tempo){let e=await kO(j({chain:y,transport:ue()}),h,v??me,{requireDecimals:!0});n=e.balance,m=e.decimals,b=e.symbol}else{let e=await II(y,h,v);n=e.balance,m=e.decimals,b=e.symbol}if(v&&n<p){let e=RI(p,m),i=RI(n,m),a=b??`tokens`;r.push(GF(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(GF(t,`unable to verify token balance and decimals from the payment chain`));return}let x=p?RI(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(GF(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 xO(` ${X.yellow(`Pay`)} ${w}. Continue?`,!1)){r.push(GF(t,`declined`));return}let T,ee,E;if(g)try{let t=await g.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});T=t.methods,ee=t.createCredential,E=t.credentialContext}catch(e){r.push(GF(t,e.message));return}else T=[_];if(_&&SD(e)){let n=!0,u=dT({methods:[_],polyfill:!1,async onChallenge(n,{createCredential:i}){let a=await yP(n,l?.config.extensions);DP(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]:Qx(e)}})):XF(t,r??{},3e4)});try{await GI(r,await u.fetch(i,{method:a.method,headers:o,body:s??null}),c,y)}catch(e){r.push($(t,e.message))}return}let D=await UI(e,T,ee,t,r,l?.config.extensions,E);D&&(g?.prepareCredentialRequest?.({challenge:e,credential:D,headers:o}),await WI(r,i,a,D,o,s,c,y,dS(e)))}async function HI(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}=bP(e,l?.config);if(!f&&!p){r.push(GF(t,`no Stripe payment method available`));return}let m=!!(f&&!l?.config.plugins?.includes(f)&&n.isStripeTestKey),h=e.request,g=eI(h.amount)?BigInt(h.amount):void 0,_=h.decimals??2,v=h.currency,y=g?RI(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(GF(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 xO(` ${X.yellow(`Pay`)} ${x}. Continue?`,!1)){r.push(GF(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(GF(t,e.message));return}else S=[p];let T=await UI(e,S,C,t,r,l?.config.extensions,w);if(T){if(f?.prepareCredentialRequest?.({challenge:e,credential:T,headers:o}),m){let n=await XF(i,{method:a.method,headers:{...o,[dS(e)]:T},body:s??null},3e4);n.status>=200&&n.status<300?r.push(Q(`${t}: successful`,`HTTP ${n.status}`)):r.push(GF(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await WI(r,i,a,T,o,s,c,void 0,dS(e))}}async function UI(e,t,n,r,i,a,o){let s=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:Qx(e)}});try{let c=await yP(e,a,o),l;return l=n?await n(s,c):await dT({methods:t,polyfill:!1}).createCredential(s,c),i.push(Q(`${r}: submitted`)),l}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(GF(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function WI(e,t,n,r,i,a,o,s,c=q.authorization){let l;try{l=await XF(t,{method:n.method,headers:{...i,[c]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}return GI(e,l,o,s)}async function GI(e,t,n,r){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(WF(`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 i=t.headers.get(q.paymentReceipt);if(!i)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=jI(i);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(WF(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(WF(`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(WF(`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))}}let a=t.headers.get(`content-type`)??``,o=await t.text().catch(()=>``);if(o.length>0)e.push(Q(`Response body non-empty`,`${a.split(`;`)[0]}, ${ZF(o.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(WF(`Response body empty -- data may be in headers only`,n.map(([e])=>e).join(`, `))):e.push(WF(`Response body empty`))}if(a?e.push(Q(`Content-Type header set`,a.split(`;`)[0])):e.push(WF(`Content-Type header set`)),i)try{let t=jI(i);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}async function*KI(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await ZI(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=nI(e.body,i.path),!a&&r.doc&&(a=sI(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await gI(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(XI),h=p.some(e=>!XI(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 EI(t,i,{body:u,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults,a=await BI(t,i,n,{body:u,query:e.query,extraHeaders:e.headers,yes:e.yes,silent:!r,interactive:e.interactive,...r&&{onResults:r}});yield{phase:`payment`,endpoint:i,results:a,succeeded:a.some(e=>e.severity===`pass`&&e.label===`Payment: successful`)}}}}async function qI(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of KI(e))switch(t.phase){case`discovery`:n=t.discovery;break;case`endpoint`:i={method:t.endpoint.method,path:t.endpoint.path,challenge:[],errorHandling:[],payment:[]},r.push(i);break;case`challenge`:i&&(i.challenge=t.results),t.isMpp&&(t.isTestnet&&(a=!0),t.isMainnet&&(o=!0));break;case`errorHandling`:i&&(i.errorHandling=t.results);break;case`payment`:i&&(i.payment=t.results)}let s={passed:0,failed:0,warnings:0,suggested:0,skipped:0};if(n)for(let e of n.checks)e.severity===`pass`?s.passed++:e.severity===`fail`?s.failed++:e.severity===`warn`?s.warnings++:e.severity===`suggested`?s.suggested++:e.severity===`skip`&&s.skipped++;for(let e of r)for(let t of[...e.challenge,...e.errorHandling,...e.payment])t.severity===`pass`?s.passed++:t.severity===`fail`?s.failed++:t.severity===`warn`?s.warnings++:t.severity===`suggested`?s.suggested++:t.severity===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=JI(r,n,{sawTestnet:a,sawMainnet:o});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function JI(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(OI);let a=n.sawMainnet,o=n.sawTestnet,s=i.some(e=>e.label.includes(`[stripe]`)&&e.label.includes(`livemode`));return a&&!o?r.push(`Validate your testnet server to test without real funds (Tempo wallets are automatically provisioned).`):o&&!a&&r.push(`Validate your mainnet server to confirm real payments work end-to-end.`),s&&r.push(`Validate your testmode Stripe server to test card payments end-to-end (auto-pays with test card).`),r}const YI=Object.values(Be);function XI(e){return YI.find(t=>t.id===e)?.testnet===!0}async function ZI(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await aI(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 iI(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=WT(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=tI(t.endpoint);e&&r.push(e)}else if(i){r=oI(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=eI(t.amount)?BigInt(t.amount):e,i=eI(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}}Dx(),LO();const QI=sb(`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||vO()){let t=await qI({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!1});console.log(JSON.stringify(t,null,2));let n=t.endpoints.length===0&&!e.options.endpoint;(t.summary.failed>0||!t.discovery.found||n)&&process.exit(1);return}let t=e.args.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``);console.log(`\n${X.bold(`mppx validate`)} ${X.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,suggested:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of KI({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=>YF(e,n)}))switch(t.phase){case`discovery`:if(JF(`Discovery (/openapi.json)`),YF(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=OI.split(`
245
- `);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++,JF(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),YF(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`)),YF(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}$I(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function $I(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 eL(e){return nL(e)?e.offers:[e]}function tL(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=rL(t.amount)??rL(i.amount)??null,o=rL(t.currency)??rL(i.currency),s=rL(e.description)??rL(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 nL(e){return`offers`in e&&!(`_canonicalRequest`in e)}function rL(e){return typeof e==`string`?e:void 0}var iL=F((()=>{})),aL=Ze({generate:()=>oL,generateProxy:()=>sL});function oL(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=>lL(e,r));return cL({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function sL(e){let t=e.routes.map(t=>({...t,path:uL(e.basePath,t.path)}));return cL({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function cL(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`]=LT.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 lL(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:eL(t).map(tL)},...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:Ix(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:tL(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function uL(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var dL=F((()=>{Rx(),UT(),iL()}));Dx(),gS(),oT(),UC(),nw(),aw(),Px(),rO(),ew(),ES(),DC(),ZO(),LO();const fL=`0.13.3`,pL=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),mL=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),hL=p.object({message:p.string(),path:p.string(),severity:p.string()}),gL=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),_L=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function vL(e){return e.format===`json`&&e.formatExplicit}function yL(e,t,n){if(vL(e))return e.ok(t);n()}async function bL(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 xL(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function SL(e){return typeof e==`string`?e:void 0}function CL(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function wL(e){let t=CL(e);return{...SL(e.description)?{description:SL(e.description)}:{},id:SL(e.id)??SL(e.name)??`unknown`,...SL(e.name)?{name:SL(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...SL(e.status)?{status:SL(e.status)}:{},...SL(e.serviceUrl)||SL(e.url)?{url:SL(e.serviceUrl)??SL(e.url)}:{}}}function TL(e){return{...SL(e.description)?{description:SL(e.description)}:{},method:SL(e.method)??`GET`,path:SL(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function EL(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=SL(t.amount),r=SL(t.currency),i=SL(t.method),a=SL(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function DL(e){return e.request.currency??e.request.asset}function OL(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=DL(e);return typeof t==`string`&&t.toLowerCase()===n})}async function kL(e,t,n={}){let r=()=>HC().getChallenges(e),i=()=>tw().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}function AL(e){return rw({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function jL(e,t){if(!wS(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:Qx(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[lC]:ZC({accepts:[iC(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function ML(e){let{host:t,hostname:n}=new URL(e);return!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function NL(e,t,n,r){let i=t,a=ML(i),o={...n,redirect:`manual`,headers:Sw(n.headers)};a.host&&IL(o.headers,a.host);for(let t=0;t<=20;t++){let n=await e(a.url,o),s=n.headers.get(`location`);if(!r||!s||![301,302,303,307,308].includes(n.status))return{init:o,logicalUrl:i,response:n,target:a};if(t===20)throw TypeError(`Too many redirects`);await n.body?.cancel().catch(()=>{});let c=new URL(s,i),l=new URL(i),u=Sw(o.headers);if(c.origin!==l.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];let d=(o.method??(o.body?`POST`:`GET`)).toUpperCase(),f=n.status===303&&d!==`GET`&&d!==`HEAD`||(n.status===301||n.status===302)&&d===`POST`;if(f)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];i=c.href,a=ML(i),a.host&&IL(u,a.host);let p={...o};f&&(delete p.body,p.method=`GET`),o={...p,headers:u,redirect:`manual`}}throw TypeError(`Too many redirects`)}function PL(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&FL(i),ML(i.href)}function FL(e){throw new I({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function IL(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function LL(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function RL(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new I({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new I({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function zL(e,t){let n=t.toLowerCase();return e.find(e=>{let t=SL(e.id)?.toLowerCase(),r=SL(e.name)?.toLowerCase();return t===n||r===n})}const BL=sb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:fL,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 (true for localhost/.local)`),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 TP(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=$O(),i={"User-Agent":e.options.userAgent??`mppx/${fL}${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=SP(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||s===`localhost`||s.endsWith(`.localhost`)||s.endsWith(`.local`)?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,u=ML(o),d=u.url;u.host&&(i.Host=u.host);try{let r=_O(e.options.methodOpt),a=HP(),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&&dO(o,s,t);let f=await NL(l,o,s,e.options.location??!1),p=f.response;if(p.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&&p.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${p.status}`,exitCode:22});fO(p,c),await bL(p);return}let m=p.url?new URL(p.url):void 0,h=u.host!==void 0&&m?.hostname===`127.0.0.1`,g=await kL(p,e.options.protocol,{ignoreX402ResponseUrl:h});if(g.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 _=OL(g,e.options.currency);if(e.options.currency&&_.length===0){let t=g.map(DL).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 v=CP(n?.config)?.length?_:await IN(_,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),y=xP(v,n?.config);if(!y){let t=v.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:b,plugin:x,method:S}=y,C=wS(b),w=C?void 0:PL(o,u,f.logicalUrl),T=jL(b,p),ee=b.request.currency??``,E=b.request.decimals??6,D,O;x&&(O=await x.setup({challenge:b,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),ee=O.tokenSymbol,E=O.tokenDecimals,D=O.explorerUrl);let te=!e.options.silent&&e.options.confirm,ne=new Set;{fO(p,b.method===`tempo`&&b.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(b))e.has(n)||r===void 0||t.push([n,hO(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:ee,tokenDecimals:E,explorerUrl:D},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(b.request))e.has(n)||i===void 0||t.push([n,pO(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=b.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=mO(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,pO(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)ne.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||te){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
241
+ `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await tP({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 tP(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:{...Aw(e.fetchInit.headers),Authorization:t}});if(n.ok){if(mP(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(DO(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${NO(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 nP(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 rP(e){return sP(CP,e,wP)}function iP(e){return e.method===`tempo`&&e.intent===`charge`}async function aP(e){let t=tk(e.options.account),n=process.env.MPPX_PRIVATE_KEY?.trim()||(AO(t)?void 0:await nk(t).get()),r;if(n)r=ve(n).address;else if(AO(t)&&vP())r=_P(t)?.wallet_address;else{let e=bP();if(e){let t=await nk(e).get();t&&(r=ve(t).address)}}if(!r)return;let i=PO(e.options.rpcUrl,{network:e.options.network}),a=j({chain:await IO({network:e.options.network,rpcUrl:i}),transport:ue(i)});return{account:r,client:a}}async function oP(e,t){let n=e.request,r=n.currency,i=n.amount;if(typeof r!=`string`||typeof i!=`string`)return`unsupported`;let a=n.methodDetails?.chainId;if(a&&t.client.chain?.id&&a!==t.client.chain.id)return`unsupported`;let o=BigInt(i);if(o===0n)return`payable`;let s=await Ie.token.getBalance(t.client,{account:t.account,token:r}).then(e=>e.amount).catch(()=>void 0);return s===void 0?`unknownBalance`:s>=o?`payable`:`insufficientBalance`}function sP(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 cP(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new I({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function lP(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function uP(e){let t=lP(e.tokenIn)??lP(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 dP(){return c.join(process.env.XDG_CONFIG_HOME||c.join(b.homedir(),`.config`),`mppx`,`channels`)}function fP(e){try{let n=t.readFileSync(c.join(dP(),e),`utf-8`).trim();return n?BigInt(n):void 0}catch{return}}function pP(e,n){let r=dP();t.mkdirSync(r,{recursive:!0}),t.writeFileSync(c.join(r,e),n.toString(),`utf-8`)}function mP(e){try{t.unlinkSync(c.join(dP(),e))}catch{}}function hP(){return b.platform()===`darwin`?c.join(b.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):c.join(process.env.XDG_DATA_HOME||c.join(b.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function gP(){try{let e=t.readFileSync(hP(),`utf-8`),n=[],r;for(let t of e.split(`
242
+ `)){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 _P(e){let t=gP();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 vP(){if(EP!==void 0)return EP;try{m.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),EP=!0}catch{EP=!1}return EP}async function yP(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 bP(){let e=ek();if(AO(e.get())&&!vP()&&b.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]===xP&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}var xP,SP,CP,wP,TP,EP,DP=F((()=>{Ox(),_T(),Fx(),nC(),qN(),UE(),Bj(),ck(),JO(),sA(),xP=`mppx`,SP=p.union([p.boolean(),p.literal(`true`).transform(()=>!0),p.literal(`false`).transform(()=>!1)]),CP=p.object({allowCustomEscrow:p.optional(SP),autoSwap:p.optional(SP),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())}),wP=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`],TP=[`payable`,`unknownBalance`,`insufficientBalance`,`unsupported`]}));OS(),ck(),sA();const OP=[...Object.entries(mk),...Object.entries(hk),...Object.entries(gk),...Object.entries(_k)];function kP(){return oA({method:`evm`,supports:AP,async setup({challenge:e,options:t}){let n=e.request,r=n.network?jP(wk(n.network)):void 0,i=n.network&&n.asset?OP.find(([,e])=>Sk(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`?fk({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await ak(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...aA({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function AP(e){if(!ES(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 jP(e){return Object.values(Ve).find(t=>t.id===e)}_S(),JS(),DP();const MP=[ZN(),_A(),cA(),kP()];async function NP(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 PP(e,t){let n=t?.plugins?.find(t=>RP(t,e));if(n)return{plugin:n};let r=LP(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=MP.find(t=>RP(t,e));return a?{plugin:a}:{}}function FP(e,t){let n=LP(t);if(n?.length){let r=NS(e,n,AS(n,t?.paymentPreferences).entries);if(r){let e=t?.plugins?.find(e=>RP(e,r.challenge));return{challenge:r.challenge,...e?{plugin:e}:{method:r.method}}}return}for(let n of e){let e=PP(n,t);if(e.plugin||e.method)return{challenge:n,...e}}}function IP(e){let t=LP(e);if(t?.length)return AS(t,e?.paymentPreferences).header}function LP(e){return Array.isArray(e?.methods)?e.methods.flat():void 0}function RP(e,t){return e.supports?e.supports(t):e.method===t.method}async function zP(e){let t=BP(e);if(!t)return;let n=await import(t);return{config:n.default??n,path:t}}function BP(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 VP(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}return $x({...t,request:n,id:e.id,expires:e.expires})}if(n(t)!==n(e))throw Error(`Payment request changed on retry. Run the command again to approve the new payment.`)}DP(),_S(),tM(),aN(),hN(),mO();function HP(e){return e??globalThis.fetch.bind(globalThis)}function UP(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(Jj(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Error(`Close challenge changed the session escrow.`);let r=FD(e);if(r&&r.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Close challenge changed the session channel.`)}async function WP(e){UP(e.challenge,e.channel);let t=HP(e.fetch),n,r=async(r,i)=>{n&&=(await e.onChallenge?.(n),void 0);let a=await t(r,i);if(a.status!==402)return a;let o=cS(a).find(ND);if(!o)throw Error(`Refreshed close response did not include tempo/session.`);return UP(o,e.channel),n=o,a},i=mN({...e.manager,bootstrap:!1,escrow:e.channel.escrow,fetch:r});rN(i).rehydrate(e);let a=await i.close();if(!a)throw Error(`Session close response did not include a payment receipt.`);return{manager:i,receipt:a}}_S(),tM(),sM(),mO(),Sj(),Zx();var GP=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}},KP=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 qP=J.object({channelId:qx(),cumulativeAmount:J.string(),deposit:J.string(),descriptor:J.object({payer:Kx(),payee:Kx(),operator:Kx(),token:Kx(),salt:qx(),authorizedSigner:Kx(),expiringNonceHash:qx()}),escrow:Kx(),chainId:J.number(),opened:J.boolean()}),JP=J.object({name:J.optional(J.string()),address:Kx()}),YP=J.object({method:J.literal(`tempo`),intent:J.literal(`session`),status:J.literal(`success`),timestamp:J.string(),reference:J.string(),challengeId:J.string(),channelId:qx(),acceptedCumulative:J.string(),spent:J.string(),units:J.optional(J.number()),txHash:J.optional(qx())}),XP=J.object({version:J.literal(1),method:J.literal(`tempo`),intent:J.literal(`session`),status:J.enum([`opening`,`open`,`closing`,`stale`]),channel:qP,account:JP,endpoint:J.string(),challenge:gS,receipt:J.optional(YP),spent:J.string(),units:J.number(),createdAt:J.string(),updatedAt:J.string()}),ZP=J.object({version:J.literal(1),channelId:qx()}),QP=J.object({version:J.literal(1),scope:J.string(),hostname:J.string(),pid:J.number(),token:J.string(),createdAt:J.string()});function $P(e,t,n,r){let i=e.safeParse(t);if(!i.success)throw Z(n,r,i.error);return i.data}function eF(e){let t=uF(e);return[t.payer,t.payee,t.token,t.escrow,t.chainId].join(`:`)}function tF(e){return{payer:e.descriptor.payer,payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId}}function nF(e={}){let t=e.stateRoot??iF(),n={root:t,channels:c.join(t,`channels`),locks:c.join(t,`locks`),preferred:c.join(t,`preferred`)},r=e.hostname??b.hostname(),i=e.pid??process.pid,a=e.now??(()=>new Date),o=e.isProcessAlive??IF;async function s(){for(let e of[n.root,n.channels,n.locks,n.preferred])await C.mkdir(e,{recursive:!0,mode:448}),await C.chmod(e,448)}async function l(e){let t=cF(e),r=aF(n,t),i=await DF(r);if(i===void 0)return;let a=vF(i,r);if(a.channel.channelId.toLowerCase()!==t)throw Z(r,`Session filename does not match its channel ID.`);return yF(a)}async function u(){let e;try{e=await C.readdir(n.channels,{withFileTypes:!0})}catch(e){if(RF(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);cF(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=mF(e.channel),r=cF(t.channelId),i=aF(n,r),o=await DF(i),c=o===void 0?void 0:vF(o,i);c&&bF(c,e,i);let l=gF(e.challenge,i);SF(l,t,i);let u=e.receipt?_F(e.receipt,t.channelId,i):void 0,d=c?oM(c.channel):void 0,f=EF(t.cumulativeAmount,d?.cumulativeAmount??0n),p=EF(e.spent??0n,u?BigInt(u.spent):0n,c?BigInt(c.spent):0n);if(p>f)throw Z(i,`Session spend exceeds the locally authorized cumulative amount.`);let m=hF(aM({...t,cumulativeAmount:f}),i),h=TF(c?.updatedAt,a(),i),g=wF(c?.receipt,u),_=pF(e.account,i),v=vF({version:1,method:`tempo`,intent:`session`,status:e.status,channel:m,account:{..._.name===void 0?c?.account.name===void 0?{}:{name:c.account.name}:{name:_.name},address:_.address},endpoint:fF(e.endpoint,i),challenge:l,...g!==void 0&&{receipt:g},spent:p.toString(),units:Math.max(c?.units??0,e.units??0,u?.units??0),createdAt:c?.createdAt??h,updatedAt:h},i);return await OF(i,v),yF(v)}async function f(e){let t=sF(n,e),r=await DF(t);if(r===void 0)return;let{channelId:i}=$P(ZP,r,t,`Preferred session is invalid.`),a=await l(i);if(!a)throw Z(t,`Preferred session ${i} does not exist.`);return CF(a.channel,e,t),i}async function p(e,t){let r=cF(t),i=await l(r),a=sF(n,e);if(!i)throw Z(a,`Session ${r} does not exist.`);CF(i.channel,e,a),await OF(a,{version:1,channelId:r})}async function m(e,t){let r=sF(n,e),i=t===void 0?void 0:cF(t),a=await DF(r);if(a===void 0)return;let o=$P(ZP,a,r,`Preferred session is invalid.`).channelId;i&&o.toLowerCase()!==i||await PF(r,`Unable to clear preferred session.`)}async function h(e){let t=cF(e),r=await l(t);r&&(await m(tF(r.channel),t),await PF(aF(n,t),`Unable to remove session.`))}async function g(e){await s();let t=oF(n,e);for(let n=0;n<3;n++){let n={version:1,scope:e,hostname:r,pid:i,token:_(),createdAt:a().toISOString()};try{if(await kF(t,n),await MF(jF(t))){await NF(t,n);continue}return{async release(){await NF(t,n)}}}catch(e){if(!RF(e,`EEXIST`))throw e}let s=await DF(t);if(s===void 0)continue;let c=$P(QP,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 KP(e,c);await AF(t,c)}let c=await DF(t);throw c===void 0?Z(t,`Unable to acquire session lock.`):new KP(e,$P(QP,c,t,`Session lock is invalid.`))}async function v(e){return g(eF(e))}return{root:t,get:l,list:u,upsert:d,remove:h,getPreferred:f,setPreferred:p,clearPreferred:m,acquire:v}}function rF(e,t){let n=dF(t.scope),r=t.selection===`auto`||t.selection===`new`?void 0:cF(t.selection);function i(e){if(e.toLowerCase()!==n)throw new GP(`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 GP(`Session ${i} does not exist.`);if(CF(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(rM(n)),CF(n,t.scope),r&&r.toLowerCase()!==n.channelId.toLowerCase())throw new GP(`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 iF(){let e=process.env.XDG_STATE_HOME||c.join(b.homedir(),`.local`,`state`);return c.join(e,`mppx`,`sessions`,`v1`)}function aF(e,t){return c.join(e.channels,`${t}.json`)}function oF(e,t){let n=g(`sha256`).update(t).digest(`hex`);return c.join(e.locks,`${n}.lock`)}function sF(e,t){let n=g(`sha256`).update(eF(t)).digest(`hex`);return c.join(e.preferred,`${n}.json`)}function cF(e){return $P(qx(),e,void 0,`Invalid session channel ID: ${e}.`).toLowerCase()}function lF(e,t,n){return $P(Kx(),e,n,`Invalid ${t}.`).toLowerCase()}function uF(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<0)throw new GP(`Invalid session chain ID.`);return{payer:lF(e.payer,`session payer`),payee:lF(e.payee,`session payee`),token:lF(e.token,`session token`),escrow:lF(e.escrow,`session escrow`),chainId:e.chainId}}function dF(e){let t=uF(e);return[t.payee,t.token,t.escrow,t.chainId].join(`:`)}function fF(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 pF(e,t){return $P(JP,e,t,`Session account is invalid.`)}function mF(e){return oM(hF(aM(e)))}function hF(e,t){return $P(qP,e,t,`Stored session channel is invalid.`)}function gF(e,t){let n=gS.safeParse(e);if(!n.success||!ND(n.data))throw Z(t,`Stored session challenge is invalid.`);return n.data}function _F(e,t,n){let r=$P(YP,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 vF(e,t){let n=$P(XP,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?_F(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=fF(n.endpoint,t);if(u!==n.endpoint)throw Z(t,`Stored session endpoint contains a fragment.`);let d=gF(n.challenge,t);return SF(d,oM(a),t),{...i,account:o,channel:a,endpoint:u,challenge:d,...s&&{receipt:s}}}function yF(e){return{version:1,status:e.status,channel:oM(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 bF(e,t,n){let r=mF(t.channel),i=pF(t.account,n),a=oM(e.channel);if(JSON.stringify(xF(r))!==JSON.stringify(xF(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 xF(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 SF(e,t,n){if(vj({...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=lF(e.request.recipient,`challenge recipient`,n),i=lF(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(Jj(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Z(n,`Session challenge escrow does not match the channel.`);if(LF(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 CF(e,t,n){let r=uF(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 wF(e,t){return e?t&&Date.parse(t.timestamp)>=Date.parse(e.timestamp)?t:e:t}function TF(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 EF(...e){return e.reduce((e,t)=>t>e?t:e,0n)}async function DF(e){let t;try{t=await C.readFile(e,`utf8`)}catch(t){if(RF(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 OF(e,t){await C.mkdir(c.dirname(e),{recursive:!0,mode:448}),await C.chmod(c.dirname(e),448);let n=`${e}.tmp-${process.pid}-${_()}`,r;try{r=await C.open(n,`wx`,384),await r.writeFile(`${JSON.stringify(t,null,2)}\n`,`utf8`),await r.sync(),await r.close(),r=void 0,await C.rename(n,e),await C.chmod(e,384),await FF(c.dirname(e))}catch(t){throw await r?.close().catch(()=>void 0),await C.unlink(n).catch(()=>void 0),t instanceof GP?t:Z(e,`Unable to write session state.`,t)}}async function kF(e,t){let n;try{n=await C.open(e,`wx`,384),await n.writeFile(`${JSON.stringify(t)}\n`,`utf8`),await n.sync(),await n.close(),n=void 0,await FF(c.dirname(e))}catch(t){throw await n?.close().catch(()=>void 0),n&&await C.unlink(e).catch(()=>void 0),t}}async function AF(e,t){let n=jF(e);try{await C.link(e,n)}catch(t){if(RF(t,`EEXIST`)||RF(t,`ENOENT`))return;throw Z(e,`Unable to claim dead lock.`,t)}try{let r=await DF(n);if(r===void 0||$P(QP,r,n,`Session lock is invalid.`).token!==t.token)return;await PF(e,`Unable to reclaim dead lock.`)}finally{await PF(n,`Unable to release dead lock claim.`)}}function jF(e){return`${e}.reclaim`}async function MF(e){try{return await C.access(e),!0}catch(t){if(RF(t,`ENOENT`))return!1;throw Z(e,`Unable to inspect session lock.`,t)}}async function NF(e,t){let n=await DF(e);n!==void 0&&$P(QP,n,e,`Session lock is invalid.`).token===t.token&&await PF(e,`Unable to release session lock.`)}async function PF(e,t){try{await C.unlink(e),await FF(c.dirname(e))}catch(n){if(!RF(n,`ENOENT`))throw Z(e,t,n)}}async function FF(e){let t=await C.open(e,`r`);try{await t.sync()}finally{await t.close()}}function IF(e){try{return process.kill(e,0),!0}catch(e){if(RF(e,`ESRCH`))return!1;if(RF(e,`EPERM`))return!0;throw e}}function LF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function RF(e,t){return e instanceof Error&&`code`in e&&e.code===t}function Z(e,t,n){return new GP(t,{...n!==void 0&&{cause:n},file:e})}Ox(),_T(),YM(),fM(),Sj(),ck(),JO();const zF=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()}),BF=p.object({channelId:p.string(),status:p.enum([`closed`,`already-closed`]),spent:p.string(),txHash:p.string().optional()}),VF=p.object({closed:p.array(BF),failed:p.array(p.object({channelId:p.string(),message:p.string()}))});function HF(e){return e===`mainnet`?ye.id:be.id}function UF(e){if(e===ye.id)return`mainnet`;if(e===be.id)return`testnet`}function WF(e){let t={};for(let n of e??[]){let e=n.indexOf(`:`);if(e===-1)throw new I({code:`INVALID_HEADER`,message:`Invalid header format: ${n}`,exitCode:2});t[n.slice(0,e).trim()]=n.slice(e+1).trim()}return t}function GF(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 KF(e,t){throw e instanceof I?e:e instanceof KP?new I({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e instanceof GP?new I({code:e.code,message:e.message,exitCode:65,cause:e}):new I({code:t,message:e instanceof Error?e.message:String(e),exitCode:75,...e instanceof Error&&{cause:e}})}async function qF(e,t){let n=await ik(t??e.account.name);if(!NM(n.account,e.channel.descriptor))throw new I({code:`SESSION_ACCOUNT_MISMATCH`,message:`Account ${n.account.address} cannot sign for session ${e.channel.channelId}.`,exitCode:2});return n}async function JF(e,t){if(t.network&&HF(t.network)!==e)throw new I({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, not ${t.network}.`,exitCode:2});let n=t.network??UF(e),r=PO(t.rpcUrl,{network:n}),i=await IO({network:n,rpcUrl:r});if(i.id!==e)throw new I({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, but RPC is chainId ${i.id}.`,exitCode:2});return j({chain:i,transport:ue(r)})}const YF=cb(`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(zF)}),alias:{account:`a`},async run(e){try{let t=(await nF().list()).filter(t=>!(e.options.account&&t.account.name!==e.options.account||e.options.network&&t.channel.chainId!==HF(e.options.network))).map(GF),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(``),XF(n);return}catch(e){return KF(e,`SESSION_LIST_FAILED`)}}}).command(`view`,{description:`View a persistent payment session`,args:p.object({channelId:p.string().describe(`Full session channel ID`)}),output:zF,async run(e){try{let t=await nF().get(e.args.channelId);if(!t)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e.args.channelId} was not found.`,exitCode:2});let n=GF(t);if(e.format===`json`&&e.formatExplicit)return e.ok(n);XF(n);return}catch(e){return KF(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([BF,VF]),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=nF();async function n(e,n={}){let r=await t.get(e);if(!r)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let i=tF(r.channel),a=await t.acquire(i);try{let r=await t.get(e);if(!r)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let a=await qF(r,n.account),o=await JF(r.channel.chainId,n);if(vj({...r.channel.descriptor,escrow:r.channel.escrow,chainId:r.channel.chainId}).toLowerCase()!==r.channel.channelId.toLowerCase())throw new I({code:`SESSION_STATE_INVALID`,message:`Stored descriptor does not derive the session channel ID.`,exitCode:65});if((await lM(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=fF(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=WF(n.headers),f=u.challenge,p=await WP({channel:u.channel,challenge:u.challenge,fetch:async(e,t)=>globalThis.fetch(e,{...t,headers:{...d,...Aw(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:rF(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===HF(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 KF(e,`SESSION_CLOSE_FAILED`)}}});function XF(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}`)}Ox(),YM(),aN(),hN(),UE(),ck(),JO();function ZF(e,t){if(t&&e!==`auto`&&t.toLowerCase()!==e.toLowerCase())throw new I({code:`SESSION_SELECTION_CONFLICT`,message:`--session and -M channel= select different sessions.`,exitCode:2});let n=t??e;if(n===`auto`||n===`new`)return n;if(/^0x[0-9a-fA-F]{64}$/.test(n))return n.toLowerCase();throw new I({code:`INVALID_SESSION`,message:`Session must be auto, new, or a 32-byte channel ID.`,exitCode:2})}function QF(e){let t=e.allowCustomEscrow;if(t!==void 0){if(t===`true`)return!0;if(t===`false`)return!1;throw new I({code:`INVALID_ALLOW_CUSTOM_ESCROW`,message:`allowCustomEscrow must be true or false.`,exitCode:2})}}function $F(e,t,n,r){if(t.deposit!==void 0)return t.deposit;let i=e.request.suggestedDeposit;return typeof i==`string`?ce(BigInt(i),r):n?`10`:void 0}function eI(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 tI(e,t){return e.channel.channelId.toLowerCase()===t.toLowerCase()}function nI(e){if(e.trim()!==`[DONE]`){if(e.length===0){process.stdout.write(`
243
+ `);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 rI(e){let{options:t}=e,n=await ik(t.account),r=PO(t.rpcUrl,{network:t.network}),i=await IO({network:t.network,rpcUrl:r}),a=j({chain:i,transport:ue(r)}),o=QF(e.methodOptions),s=await DM({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new I({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let{decimals:c}=await BO(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=ZF(t.session,e.methodOptions.channel),d=e.registry??nF(),f=await d.acquire(l).catch(e=>{throw e instanceof KP?new I({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=u===`auto`?await d.getPreferred(l):u===`new`?void 0:u,s=r?await d.get(r):void 0;if(r&&!s)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&u!==`auto`&&(s.status!==`open`||!s.channel.opened||eF(tF(s.channel))!==eF(l)||!NM(n.account,s.channel.descriptor)))throw new I({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let f=s?.status===`open`&&s.channel.opened?s:void 0,p=f?`open`:`opening`,m=e.challenge,h=f?.receipt,g=f?.spent??0n,_=f?.units??0,v=fF(e.endpoint),y={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},b=rF(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=mN({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:b,credentialContext:e.credentialContext,decimals:c,maxDeposit:$F(e.challenge,e.methodOptions,zO(i),c),fetch:async(t,n)=>w?(w=!1,e.challengeResponse):e.fetch(t,n)});f&&rN(T).rehydrate({channel:f.channel,challenge:e.challenge,input:e.fetchInput,spent:f.spent});let{onReceipt:ee,...E}=C,D=await T.fetch(e.fetchInput,E);if(t.fail&&D.status>=400)throw new I({code:`HTTP_ERROR`,message:`HTTP error ${D.status}`,exitCode:22});if(D.status===402)throw new I({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});CO(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=eI(D.receipt,{challenge:m,channelId:O,cumulative:T.cumulative})??h,NE(D)){let t=rN(T).consumeSseResponse(e.fetchInput,D,{onReceipt:ee,signal:e.init.signal??void 0});for await(let e of t)nI(e)}else process.stdout.write(Buffer.from(await D.arrayBuffer()));let k=await d.get(O);if(!k||!tI(k,O))throw Error(`Session ${O} was not persisted.`);if(h){let e=eI(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()}}JO();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 iI(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function aI(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}const oI={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function sI(e){let t=oI[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 cI(e){console.log(`\n${X.bold(e)}`)}function lI(e,t){for(let n of e)sI(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`suggested`?t.suggested++:n.severity===`skip`&&t.skipped++}async function uI(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{return await fetch(e,{...t,redirect:`error`,signal:r.signal})}finally{clearTimeout(i)}}function dI(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const fI=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function pI(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function mI(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function hI(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!fI.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 gI(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 _I(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 vI(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await uI(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 yI(e){let t=new URL(`/llms.txt`,e).href,n=`llms.txt found and nonempty`;try{let e=await uI(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 bI(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=CI(i.parameters);for(let[a,o]of Object.entries(i)){if(!fI.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=wI(r,CI(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 xI(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=EI(o,e,s),!o||o.type!==`object`)return;let c=DI(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function SI(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=TI(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 CI(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 wI(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 TI(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 EI(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 DI(e,t,n){let r=EI(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]=DI(i,t,n))}return a}default:return null}}_S(),Fx(),iw(),JO();const OI=Object.values(Ve);function kI(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&OI.find(e=>e.id===t.chainId)?.testnet===!0}async function AI(e,t,n,r){let i=[],a;try{a=SI(e,t,r?.query)}catch(e){return i.push($(`Request URL valid`,e.message)),{results:i}}let o=_I(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 uI(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?xI(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 uI(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(aI(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(aI(`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=VI(c);if(!l)return u.length>0?(i.push(aI(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(aI(`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(`${Ax.payment} `))return i.push(aI(`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=cS(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(iI(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0)return i.push($(`Challenge parseable`,`No Payment challenges found in header`)),{results:i};let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push(Q(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=new URL(e).hostname;jI(d,i),MI(d,i),NI(d,i),PI(d,p,i);let m=d.length>1;for(let e of d){let t=e.request;FI(e,t,i,m)}if(n)for(let e of d)console.log(X.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function jI(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 MI(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 NI(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(iI(`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 PI(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 FI(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===jx.tempo?II(t,i,n,e):e.method===jx.stripe?LI(t,i,n):e.method===jx.evm&&RI(e,t,i,n)}function II(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if(pI(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.`)),pI(e.currency)){let e=kI(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.`));zI(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function LI(e,t,n){zI(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 RI(e,t,n,r){if(pI(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.`)),pI(t.currency)){let t=kI(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.`));zI(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 zI(e,t,n,r){mI(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 BI(e,t,n){let r=[],i=SI(e,t,n?.query),a={[q.authorization]:`${Ax.payment} dGhpcyBpcyBnYXJiYWdl`},o;n?.body&&(o=n.body,a[`content-type`]=`application/json`);try{let e=await uI(i,{method:t.method,headers:a,body:o??null});e.status===402?(r.push(Q(`Malformed credential returns 402`,`not 500`)),e.headers.get(q.wwwAuthenticate)?.startsWith(`${Ax.payment} `)?r.push(Q(`Error response includes fresh challenge`)):r.push(iI(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the Authorization header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(iI(`Malformed credential returns 402`,`Got ${e.status}`,`When the Authorization header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function VI(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=ZC(n);t.push(Q(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(iI(`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 HI=[`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(`
244
+ `);Zx();const UI={fundingCurrency:J.optional(J.string()),method:J.string(),reference:J.string(),externalId:J.optional(J.string()),subscriptionId:J.optional(J.string()),status:J.literal(`success`),timestamp:Hx()};J.object(UI);const WI=J.looseObject(UI);function GI(e){let t=k.toString(e);return KI(JSON.parse(t))}function KI(e){return WI.parse(e)}_S(),Fx(),qN(),bO(),mO(),ck(),JO();async function qI(e,t,n){try{n||console.log(X.dim(` Provisioning testnet wallet and funding via faucet...`));let t=ge(),r=ve(t),i=j({chain:be,transport:ue()});if(ND(e)){let{chainId:t,operator:n}=e.request.methodDetails??{};if(t===be.id&&typeof n==`string`&&de(n)&&n!==he){let e=await Ie.faucet.fund(i,{account:n});await Promise.all(e.map(e=>Ne(i,{hash:e})))}}let a=await Ie.faucet.fund(i,{account:r});await Promise.all(a.map(e=>Ne(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 Ie.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:[...WN({account:r})]}}catch(e){t&&console.log(X.dim(` Provisioning failed: ${e.message}`));return}}async function JI(){let e=tk(),{isTempoAccount:t}=await Promise.resolve().then(()=>(JO(),xO)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(DP(),JN));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await ak()).address}catch{return}}function YI(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 XI(e,t,n){let r=j({chain:e,transport:ue()}),[i,a,o]=await Promise.all([n?Oe(r,{address:t,abi:se,functionName:`balanceOf`,args:[n]}):0n,Oe(r,{address:t,abi:se,functionName:`decimals`}),Oe(r,{address:t,abi:se,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,decimals:a,symbol:o??void 0}}function ZI(e){return Object.values(Ve).find(t=>t.id===e)}function QI(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function $I(e){switch(e.method){case jx.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 eL(e,t,n,r){let i=[],a=SI(e,t,r.query),o=_I(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await uI(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(aI(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=cS(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=[];PI(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 zP().catch(()=>void 0),p=l.find(e=>{if(e.method!==jx.tempo||LP(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!==hO.mainnet});if(p){let e=await qI(p,n,r.silent);if(e)try{await aL(i,await ST({methods:e.methods,polyfill:!1,async onChallenge(e,{createCredential:t}){VP(p,e);let n=await t(await NP(e,f?.config.extensions));return i.push(Q(`Payment: submitted`,`ephemeral testnet wallet`)),n},fetch:(e,t)=>uI(e,t??{},3e4)}).fetch(a,{method:t.method,headers:o,body:s??null}),n,be)}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??YI(n),g=h?.startsWith(`sk_test_`)||h?.startsWith(`rk_test_`),_=new Set([jx.tempo,jx.evm,jx.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 jx.tempo:case jx.evm:await tL(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,options:r});break;case jx.stripe:await nL(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 tL(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=mI(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,{plugin:g,method:_}=PP(e,l?.config);if(!g&&!_){r.push(aI(t,$I(e)));return}let v;if(!_){try{v=await JI()}catch{}if(!v){r.push(aI(t,`no wallet configured. Run "mppx account create" to create one.`));return}}let y;if(e.method===jx.tempo){let e=f?.chainId??(_?void 0:ye.id);e!==void 0&&(y=e===be.id?be:ZI(e))}else if(e.method===jx.evm){let e=f?.chainId;e&&(y=ZI(e))}if(p&&h&&!y){r.push(aI(t,`unable to resolve payment chain and verify token decimals`));return}let b;if(p&&h&&y)try{let n;if(e.method===jx.tempo){let e=await BO(j({chain:y,transport:ue()}),h,v??he,{requireDecimals:!0});n=e.balance,m=e.decimals,b=e.symbol}else{let e=await XI(y,h,v);n=e.balance,m=e.decimals,b=e.symbol}if(v&&n<p){let e=QI(p,m),i=QI(n,m),a=b??`tokens`;r.push(aI(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(aI(t,`unable to verify token balance and decimals from the payment chain`));return}let x=p?QI(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(aI(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 MO(` ${X.yellow(`Pay`)} ${w}. Continue?`,!1)){r.push(aI(t,`declined`));return}let T,ee,E;if(g)try{let t=await g.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});T=t.methods,ee=t.createCredential,E=t.credentialContext}catch(e){r.push(aI(t,e.message));return}else T=[_];if(_&&ND(e)){let n=!0,u=ST({methods:[_],polyfill:!1,async onChallenge(n,{createCredential:i}){let a=await NP(n,l?.config.extensions);VP(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]:$x(e)}})):uI(t,r??{},3e4)});try{await aL(r,await u.fetch(i,{method:a.method,headers:o,body:s??null}),c,y)}catch(e){r.push($(t,e.message))}return}let D=await rL(e,T,ee,t,r,l?.config.extensions,E);D&&(g?.prepareCredentialRequest?.({challenge:e,credential:D,headers:o}),await iL(r,i,a,D,o,s,c,y,fS(e)))}async function nL(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}=PP(e,l?.config);if(!f&&!p){r.push(aI(t,`no Stripe payment method available`));return}let m=!!(f&&!l?.config.plugins?.includes(f)&&n.isStripeTestKey),h=e.request,g=mI(h.amount)?BigInt(h.amount):void 0,_=h.decimals??2,v=h.currency,y=g?QI(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(aI(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 MO(` ${X.yellow(`Pay`)} ${x}. Continue?`,!1)){r.push(aI(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(aI(t,e.message));return}else S=[p];let T=await rL(e,S,C,t,r,l?.config.extensions,w);if(T){if(f?.prepareCredentialRequest?.({challenge:e,credential:T,headers:o}),m){let n=await uI(i,{method:a.method,headers:{...o,[fS(e)]:T},body:s??null},3e4);n.status>=200&&n.status<300?r.push(Q(`${t}: successful`,`HTTP ${n.status}`)):r.push(aI(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await iL(r,i,a,T,o,s,c,void 0,fS(e))}}async function rL(e,t,n,r,i,a,o){let s=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:$x(e)}});try{let c=await NP(e,a,o),l;return l=n?await n(s,c):await ST({methods:t,polyfill:!1}).createCredential(s,c),i.push(Q(`${r}: submitted`)),l}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(aI(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function iL(e,t,n,r,i,a,o,s,c=q.authorization){let l;try{l=await uI(t,{method:n.method,headers:{...i,[c]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}return aL(e,l,o,s)}async function aL(e,t,n,r){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(iI(`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 i=t.headers.get(q.paymentReceipt);if(!i)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=GI(i);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(iI(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(iI(`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(iI(`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))}}let a=t.headers.get(`content-type`)??``,o=await t.text().catch(()=>``);if(o.length>0)e.push(Q(`Response body non-empty`,`${a.split(`;`)[0]}, ${dI(o.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(iI(`Response body empty -- data may be in headers only`,n.map(([e])=>e).join(`, `))):e.push(iI(`Response body empty`))}if(a?e.push(Q(`Content-Type header set`,a.split(`;`)[0])):e.push(iI(`Content-Type header set`)),i)try{let t=GI(i);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}async function*oL(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await dL(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=gI(e.body,i.path),!a&&r.doc&&(a=xI(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await AI(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(uL),h=p.some(e=>!uL(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 BI(t,i,{body:u,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults,a=await eL(t,i,n,{body:u,query:e.query,extraHeaders:e.headers,yes:e.yes,silent:!r,interactive:e.interactive,...r&&{onResults:r}});yield{phase:`payment`,endpoint:i,results:a,succeeded:a.some(e=>e.severity===`pass`&&e.label===`Payment: successful`)}}}}async function sL(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of oL(e))switch(t.phase){case`discovery`:n=t.discovery;break;case`endpoint`:i={method:t.endpoint.method,path:t.endpoint.path,challenge:[],errorHandling:[],payment:[]},r.push(i);break;case`challenge`:i&&(i.challenge=t.results),t.isMpp&&(t.isTestnet&&(a=!0),t.isMainnet&&(o=!0));break;case`errorHandling`:i&&(i.errorHandling=t.results);break;case`payment`:i&&(i.payment=t.results)}let s={passed:0,failed:0,warnings:0,suggested:0,skipped:0};if(n)for(let e of n.checks)e.severity===`pass`?s.passed++:e.severity===`fail`?s.failed++:e.severity===`warn`?s.warnings++:e.severity===`suggested`?s.suggested++:e.severity===`skip`&&s.skipped++;for(let e of r)for(let t of[...e.challenge,...e.errorHandling,...e.payment])t.severity===`pass`?s.passed++:t.severity===`fail`?s.failed++:t.severity===`warn`?s.warnings++:t.severity===`suggested`?s.suggested++:t.severity===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=cL(r,n,{sawTestnet:a,sawMainnet:o});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function cL(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(HI);let a=n.sawMainnet,o=n.sawTestnet,s=i.some(e=>e.label.includes(`[stripe]`)&&e.label.includes(`livemode`));return a&&!o?r.push(`Validate your testnet server to test without real funds (Tempo wallets are automatically provisioned).`):o&&!a&&r.push(`Validate your mainnet server to confirm real payments work end-to-end.`),s&&r.push(`Validate your testmode Stripe server to test card payments end-to-end (auto-pays with test card).`),r}const lL=Object.values(Ve);function uL(e){return lL.find(t=>t.id===e)?.testnet===!0}async function dL(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await yI(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 vI(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=tE(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=hI(t.endpoint);e&&r.push(e)}else if(i){r=bI(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=mI(t.amount)?BigInt(t.amount):e,i=mI(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}}Ox(),JO();const fL=cb(`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||kO()){let t=await sL({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!1});console.log(JSON.stringify(t,null,2));let n=t.endpoints.length===0&&!e.options.endpoint;(t.summary.failed>0||!t.discovery.found||n)&&process.exit(1);return}let t=e.args.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``);console.log(`\n${X.bold(`mppx validate`)} ${X.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,suggested:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of oL({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=>lI(e,n)}))switch(t.phase){case`discovery`:if(cI(`Discovery (/openapi.json)`),lI(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=HI.split(`
245
+ `);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++,cI(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),lI(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`)),lI(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}pL(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function pL(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 mL(e){return gL(e)?e.offers:[e]}function hL(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=_L(t.amount)??_L(i.amount)??null,o=_L(t.currency)??_L(i.currency),s=_L(e.description)??_L(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 gL(e){return`offers`in e&&!(`_canonicalRequest`in e)}function _L(e){return typeof e==`string`?e:void 0}var vL=F((()=>{})),yL=Qe({generate:()=>bL,generateProxy:()=>xL});function bL(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=>CL(e,r));return SL({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function xL(e){let t=e.routes.map(t=>({...t,path:wL(e.basePath,t.path)}));return SL({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function SL(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`]=JT.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 CL(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:mL(t).map(hL)},...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:Lx(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:hL(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function wL(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var TL=F((()=>{zx(),eE(),vL()}));Ox(),_S(),_T(),qC(),ow(),lw(),Fx(),mO(),iw(),OS(),kC(),ck(),JO();const EL=`0.13.5`,DL=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),OL=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),kL=p.object({message:p.string(),path:p.string(),severity:p.string()}),AL=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),jL=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function ML(e){return e.format===`json`&&e.formatExplicit}function NL(e,t,n){if(ML(e))return e.ok(t);n()}async function PL(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 FL(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function IL(e){return typeof e==`string`?e:void 0}function LL(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function RL(e){let t=LL(e);return{...IL(e.description)?{description:IL(e.description)}:{},id:IL(e.id)??IL(e.name)??`unknown`,...IL(e.name)?{name:IL(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...IL(e.status)?{status:IL(e.status)}:{},...IL(e.serviceUrl)||IL(e.url)?{url:IL(e.serviceUrl)??IL(e.url)}:{}}}function zL(e){return{...IL(e.description)?{description:IL(e.description)}:{},method:IL(e.method)??`GET`,path:IL(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function BL(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=IL(t.amount),r=IL(t.currency),i=IL(t.method),a=IL(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function VL(e){return e.request.currency??e.request.asset}function HL(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=VL(e);return typeof t==`string`&&t.toLowerCase()===n})}async function UL(e,t,n={}){let r=()=>KC().getChallenges(e),i=()=>aw().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}function WL(e){return sw({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function GL(e,t){if(!ES(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:$x(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[dC]:tw({accepts:[oC(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function KL(e){let{host:t,hostname:n}=new URL(e);return!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function qL(e,t,n,r){let i=t,a=KL(i),o={...n,redirect:`manual`,headers:Aw(n.headers)};a.host&&XL(o.headers,a.host);for(let t=0;t<=20;t++){let n=await e(a.url,o),s=n.headers.get(`location`);if(!r||!s||![301,302,303,307,308].includes(n.status))return{init:o,logicalUrl:i,response:n,target:a};if(t===20)throw TypeError(`Too many redirects`);await n.body?.cancel().catch(()=>{});let c=new URL(s,i),l=new URL(i),u=Aw(o.headers);if(c.origin!==l.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];let d=(o.method??(o.body?`POST`:`GET`)).toUpperCase(),f=n.status===303&&d!==`GET`&&d!==`HEAD`||(n.status===301||n.status===302)&&d===`POST`;if(f)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];i=c.href,a=KL(i),a.host&&XL(u,a.host);let p={...o};f&&(delete p.body,p.method=`GET`),o={...p,headers:u,redirect:`manual`}}throw TypeError(`Too many redirects`)}function JL(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&YL(i),KL(i.href)}function YL(e){throw new I({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function XL(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function ZL(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function QL(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new I({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new I({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function $L(e,t){let n=t.toLowerCase();return e.find(e=>{let t=IL(e.id)?.toLowerCase(),r=IL(e.name)?.toLowerCase();return t===n||r===n})}const eR=cb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:EL,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 (true for localhost/.local)`),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 zP(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=uk(),i={"User-Agent":e.options.userAgent??`mppx/${EL}${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=IP(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||s===`localhost`||s.endsWith(`.localhost`)||s.endsWith(`.local`)?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,u=KL(o),d=u.url;u.host&&(i.Host=u.host);try{let r=OO(e.options.methodOpt),a=nF(),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&&SO(o,s,t);let f=await qL(l,o,s,e.options.location??!1),p=f.response;if(p.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&&p.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${p.status}`,exitCode:22});CO(p,c),await PL(p);return}let m=p.url?new URL(p.url):void 0,h=u.host!==void 0&&m?.hostname===`127.0.0.1`,g=await UL(p,e.options.protocol,{ignoreX402ResponseUrl:h});if(g.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 _=HL(g,e.options.currency);if(e.options.currency&&_.length===0){let t=g.map(VL).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 v=LP(n?.config)?.length?_:await XN(_,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),y=FP(v,n?.config);if(!y){let t=v.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:b,plugin:x,method:S}=y,C=ES(b),w=C?void 0:JL(o,u,f.logicalUrl),T=GL(b,p),ee=b.request.currency??``,E=b.request.decimals??6,D,O;x&&(O=await x.setup({challenge:b,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),ee=O.tokenSymbol,E=O.tokenDecimals,D=O.explorerUrl);let te=!e.options.silent&&e.options.confirm,ne=new Set;{CO(p,b.method===`tempo`&&b.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(b))e.has(n)||r===void 0||t.push([n,EO(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:ee,tokenDecimals:E,explorerUrl:D},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(b.request))e.has(n)||i===void 0||t.push([n,wO(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=b.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=TO(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,wO(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)ne.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||te){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
246
246
  `);t(` ${X.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${l}${e}\n`)}}}if(te&&(t(`
247
- `),!await xO(`Proceed with ${b.intent}?`,!0))){t(`Aborted.
248
- `);return}}let re=process.env.MPPX_PRIVATE_KEY?.trim()||!yO(WO(e.options.account));if(SD(b)&&re&&!S){try{await UF({challenge:b,challengeResponse:T,credentialContext:await yP(b,n?.config.extensions,O?.credentialContext),endpoint:f.logicalUrl,fetch:l,fetchInput:w.url,init:{...f.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 MF(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:S&&SD(b)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let A=S&&SD(b)?void 0:await yP(b,n?.config.extensions,O?.credentialContext),j,ie;if(S&&SD(b)){let e=T;j=await dT({methods:[S],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await yP(e,n?.config.extensions,O?.credentialContext);return DP(b,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return l(t,n)}}).fetch(w.url,{...f.init,context:A,redirect:`manual`})}else{if(O?.createCredential)ie=await O.createCredential(T,A);else if(O)ie=await dT({methods:O.methods,polyfill:!1,transport:AL(b)}).createCredential(T,A);else if(S)ie=await dT({methods:[S],polyfill:!1,transport:AL(b)}).createCredential(T,A);else throw Error(`unreachable`);let n=C?uC:dS(b),r={...Sw(f.init.headers),[n]:ie},i=C?ML((LL(b)??p.url)||o):w;C&&IL(r,i.host),x?.prepareCredentialRequest?.({challenge:b,credential:ie,headers:r});let a={...f.init,redirect:`manual`,headers:r};e.options.verbose>=2&&dO(i.url,a,t),j=await l(i.url,a)}if(e.options.fail&&j.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${j.status}`,exitCode:22});if(j.status===402){let n=await j.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,String(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(fO(j,c),!(ie&&await x?.handleResponse?.({challenge:b,credential:ie,response:j,fetchUrl:d,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:te,confirm:xO,tokenSymbol:ee,tokenDecimals:E,explorerUrl:D,shownKeys:ne}))){let n=j.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||ne.has(t)||t===`reference`&&o)continue;let e=x?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${SO(BigInt(n),ee,E)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&D?r.push([t,gO(`${D}/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(`
249
- `)}catch{}await bL(j)}}catch(t){if(t instanceof I)throw t;let n=t instanceof Error?t.cause:void 0,r=n instanceof Error?n:void 0;if(r&&`code`in r){let t=r.code;return t===`ENOTFOUND`?e.error({code:`DNS_ERROR`,message:`Could not resolve host "${s}". Check the URL and try again.`,exitCode:6}):t===`ECONNREFUSED`?e.error({code:`CONNECTION_REFUSED`,message:`Connection refused by "${s}". Is the server running?`,retryable:!0,exitCode:7}):t===`ECONNRESET`?e.error({code:`CONNECTION_RESET`,message:`Connection to "${s}" was reset.`,retryable:!0,exitCode:56}):t===`ETIMEDOUT`?e.error({code:`CONNECTION_TIMEOUT`,message:`Connection to "${s}" timed out.`,retryable:!0,exitCode:28}):t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?e.error({code:`TLS_ERROR`,message:`TLS certificate error for "${s}". Use --insecure to skip verification.`,exitCode:60}):e.error({code:`REQUEST_FAILED`,message:`Request to "${s}" failed: ${r.message}`})}{let n=t instanceof Error?t.message:String(t);return e.error({code:`REQUEST_FAILED`,message:r?`Request failed: ${n} (Cause: ${r.message})`:`Request failed: ${n}`})}}}}),VL=sb(`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=vL(e),n=e.options.account;if(!n){if((await GO().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 bO(`Account name`);if(!r)return;n=r}}let r=GO(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 bO(`Enter different name`);if(!i)return;n=i,r=GO(n)}let i=he(),a=_e(i);await r.set(i),(await GO().list()).length===1&&UO().set(n);let o=ve.blockExplorers?.default?.url,s=o?gO(`${o}/address/${a.address}`,a.address):a.address,c=wO(e.options),l=CO(e.options.rpcUrl,{network:c});return TO({network:c,rpcUrl:l}).then(e=>j({chain:e,transport:ue(l)})).then(e=>import(`viem/tempo`).then(({Actions:t})=>t.faucet.fund(e,{account:a}).catch(()=>{}))),yL(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 yO(t)?rP(t)?(UO().set(t),yL(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 GO(t).get()?(UO().set(t),yL(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=GO(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=_e(n),i=await AO(r.address,{includeTestnet:!1});if(!e.options.yes){if(vL(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?gO(`${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
247
+ `),!await MO(`Proceed with ${b.intent}?`,!0))){t(`Aborted.
248
+ `);return}}let re=process.env.MPPX_PRIVATE_KEY?.trim()||!AO(tk(e.options.account));if(ND(b)&&re&&!S){try{await rI({challenge:b,challengeResponse:T,credentialContext:await NP(b,n?.config.extensions,O?.credentialContext),endpoint:f.logicalUrl,fetch:l,fetchInput:w.url,init:{...f.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 KF(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:S&&ND(b)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let A=S&&ND(b)?void 0:await NP(b,n?.config.extensions,O?.credentialContext),j,ie;if(S&&ND(b)){let e=T;j=await ST({methods:[S],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await NP(e,n?.config.extensions,O?.credentialContext);return VP(b,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return l(t,n)}}).fetch(w.url,{...f.init,context:A,redirect:`manual`})}else{if(O?.createCredential)ie=await O.createCredential(T,A);else if(O)ie=await ST({methods:O.methods,polyfill:!1,transport:WL(b)}).createCredential(T,A);else if(S)ie=await ST({methods:[S],polyfill:!1,transport:WL(b)}).createCredential(T,A);else throw Error(`unreachable`);let n=C?fC:fS(b),r={...Aw(f.init.headers),[n]:ie},i=C?KL((ZL(b)??p.url)||o):w;C&&XL(r,i.host),x?.prepareCredentialRequest?.({challenge:b,credential:ie,headers:r});let a={...f.init,redirect:`manual`,headers:r};e.options.verbose>=2&&SO(i.url,a,t),j=await l(i.url,a)}if(e.options.fail&&j.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${j.status}`,exitCode:22});if(j.status===402){let n=await j.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,String(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(CO(j,c),!(ie&&await x?.handleResponse?.({challenge:b,credential:ie,response:j,fetchUrl:d,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:te,confirm:MO,tokenSymbol:ee,tokenDecimals:E,explorerUrl:D,shownKeys:ne}))){let n=j.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||ne.has(t)||t===`reference`&&o)continue;let e=x?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${NO(BigInt(n),ee,E)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&D?r.push([t,DO(`${D}/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(`
249
+ `)}catch{}await PL(j)}}catch(t){if(t instanceof I)throw t;let n=t instanceof Error?t.cause:void 0,r=n instanceof Error?n:void 0;if(r&&`code`in r){let t=r.code;return t===`ENOTFOUND`?e.error({code:`DNS_ERROR`,message:`Could not resolve host "${s}". Check the URL and try again.`,exitCode:6}):t===`ECONNREFUSED`?e.error({code:`CONNECTION_REFUSED`,message:`Connection refused by "${s}". Is the server running?`,retryable:!0,exitCode:7}):t===`ECONNRESET`?e.error({code:`CONNECTION_RESET`,message:`Connection to "${s}" was reset.`,retryable:!0,exitCode:56}):t===`ETIMEDOUT`?e.error({code:`CONNECTION_TIMEOUT`,message:`Connection to "${s}" timed out.`,retryable:!0,exitCode:28}):t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?e.error({code:`TLS_ERROR`,message:`TLS certificate error for "${s}". Use --insecure to skip verification.`,exitCode:60}):e.error({code:`REQUEST_FAILED`,message:`Request to "${s}" failed: ${r.message}`})}{let n=t instanceof Error?t.message:String(t);return e.error({code:`REQUEST_FAILED`,message:r?`Request failed: ${n} (Cause: ${r.message})`:`Request failed: ${n}`})}}}}),tR=cb(`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=ML(e),n=e.options.account;if(!n){if((await nk().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 jO(`Account name`);if(!r)return;n=r}}let r=nk(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 jO(`Enter different name`);if(!i)return;n=i,r=nk(n)}let i=ge(),a=ve(i);await r.set(i),(await nk().list()).length===1&&ek().set(n);let o=ye.blockExplorers?.default?.url,s=o?DO(`${o}/address/${a.address}`,a.address):a.address,c=FO(e.options),l=PO(e.options.rpcUrl,{network:c});return IO({network:c,rpcUrl:l}).then(e=>j({chain:e,transport:ue(l)})).then(e=>import(`viem/tempo`).then(({Actions:t})=>t.faucet.fund(e,{account:a}).catch(()=>{}))),NL(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 AO(t)?_P(t)?(ek().set(t),NL(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 nk(t).get()?(ek().set(t),NL(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=nk(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=ve(n),i=await VO(r.address,{includeTestnet:!1});if(!e.options.yes){if(ML(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?DO(`${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
250
250
 
251
- `)),!await xO(`Confirm delete?`)){console.log(`Canceled`);return}}await t.delete();let a=UO().get(),o;if(a===e.options.account){let e=await GO().list();e.length>0?(o=e[0],UO().set(o)):UO().clear()}return yL(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=vL(e),n=WO(e.options.account),r=await GO(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=_e(r),a=wO(e.options),o=CO(e.options.rpcUrl,{network:a}),s=await TO({network:a,rpcUrl:o}),c=j({chain:s,transport:ue(o)});t||console.log(`Funding "${n}" on ${EO(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?gO(`${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}))),yL(e,{account:n,chain:EO(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(pL)}),async run(e){let t=UO().get(),n=(await GO().list()).sort(),r=[];for(let e of n){let t=await GO(e).get();t&&r.push({name:e,address:_e(t).address})}let i=nP();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 yL(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 yL(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?gO(`${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=WO(e.options.account);if(yO(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 GO(t).get();return n?yL(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:mL,alias:{account:`a`,rpcUrl:`r`},async run(e){let t=WO(e.options.account);if(yO(t)){let n=rP(t);if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69});let r=n.wallet_address,i=CO(e.options.rpcUrl,{network:e.options.network}),a=await TO({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?gO(`${o}/address/${r}`,r):r,c=await AO(r,a&&i?{chain:a,rpcUrl:i}:void 0);return yL(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 GO(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=_e(n),i=CO(e.options.rpcUrl,{network:e.options.network}),a=await TO({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?gO(`${o}/address/${r.address}`,r.address):r.address,c=await AO(r.address,a&&i?{chain:a,rpcUrl:i}:void 0);return yL(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}`)})}}),HL=sb(`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||(xL()?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=lS(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.
252
- `);return}let r=await TP(e.options.config),i=xP(n,r?.config);if(!i){let t=n.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:a,plugin:o,method:s}=i,c=_O(e.options.methodOpt),l=Qx(a),u=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:l}}),d;o&&(d=await o.setup({challenge:a,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:c}));let f=await yP(a,r?.config.extensions,d?.credentialContext),p;if(d)p=d.createCredential?await d.createCredential(u,f):await dT({methods:d.methods,polyfill:!1}).createCredential(u,f);else if(s)p=await dT({methods:[s],polyfill:!1}).createCredential(u,f);else return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method: ${a.method}/${a.intent}. Add it to mppx.config.ts using defineConfig().`,exitCode:2});return yL(e,{authorization:p},()=>{console.log(p)})}}),UL=sb(`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'
251
+ `)),!await MO(`Confirm delete?`)){console.log(`Canceled`);return}}await t.delete();let a=ek().get(),o;if(a===e.options.account){let e=await nk().list();e.length>0?(o=e[0],ek().set(o)):ek().clear()}return NL(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=ML(e),n=tk(e.options.account),r=await nk(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=ve(r),a=FO(e.options),o=PO(e.options.rpcUrl,{network:a}),s=await IO({network:a,rpcUrl:o}),c=j({chain:s,transport:ue(o)});t||console.log(`Funding "${n}" on ${LO(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?DO(`${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}))),NL(e,{account:n,chain:LO(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(DL)}),async run(e){let t=ek().get(),n=(await nk().list()).sort(),r=[];for(let e of n){let t=await nk(e).get();t&&r.push({name:e,address:ve(t).address})}let i=gP();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 NL(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 NL(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?DO(`${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=tk(e.options.account);if(AO(t))return e.error({code:`UNSUPPORTED_ACCOUNT`,message:`Account "${t}" is managed by Tempo wallet and does not expose a private key via mppx.`,exitCode:2});let n=await nk(t).get();return n?NL(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:OL,alias:{account:`a`,rpcUrl:`r`},async run(e){let t=tk(e.options.account);if(AO(t)){let n=_P(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=PO(e.options.rpcUrl,{network:e.options.network}),a=await IO({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?DO(`${o}/address/${r}`,r):r,c=await VO(r,a&&i?{chain:a,rpcUrl:i}:void 0);return NL(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 nk(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=ve(n),i=PO(e.options.rpcUrl,{network:e.options.network}),a=await IO({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?DO(`${o}/address/${r.address}`,r.address):r.address,c=await VO(r.address,a&&i?{chain:a,rpcUrl:i}:void 0);return NL(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}`)})}}),nR=cb(`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||(FL()?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=uS(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.
252
+ `);return}let r=await zP(e.options.config),i=FP(n,r?.config);if(!i){let t=n.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:a,plugin:o,method:s}=i,c=OO(e.options.methodOpt),l=$x(a),u=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:l}}),d;o&&(d=await o.setup({challenge:a,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:c}));let f=await NP(a,r?.config.extensions,d?.credentialContext),p;if(d)p=d.createCredential?await d.createCredential(u,f):await ST({methods:d.methods,polyfill:!1}).createCredential(u,f);else if(s)p=await ST({methods:[s],polyfill:!1}).createCredential(u,f);else return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method: ${a.method}/${a.intent}. Add it to mppx.config.ts using defineConfig().`,exitCode:2});return NL(e,{authorization:p},()=>{console.log(p)})}}),rR=cb(`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'
253
253
 
254
254
  export default defineConfig({
255
255
  methods: [],
256
256
  plugins: [],
257
257
  })
258
- `),yL(e,{file:i},()=>{console.log(`Created ${r}`)}))}}),WL=sb(`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(gL)}),alias:{query:`q`},async run(e){let t=e.options.query?.toLowerCase(),n=await RL(),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(wL).sort((e,t)=>e.id.localeCompare(t.id));return yL(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=zL(await RL(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=wL(t),r=CL(t);return yL(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`)} ${gO(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&&SL(e.homepage);i&&console.log(`${X.dim(`Docs`)} ${gO(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(_L),service:gL}),async run(e){let t=zL(await RL(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=wL(t),r=CL(t).map(TL);return yL(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=EL(n.payment),i=n.description?` ${X.dim(n.description)}`:``;console.log(`${n.method.padEnd(e)} ${n.path.padEnd(t)} ${r}${i}`)}})}}),GL=sb(`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(()=>(dL(),aL)),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`),yL(e,a,()=>{})}return yL(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(hL),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=WT(i);if(!vL(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}):yL(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.`)})}});BL.command(VL),BL.command(GL),BL.command(UL),BL.command(WL),BL.command(FF),BL.command(HL),BL.command(QI);export{BL as default,PL as resolveMppCredentialTarget};
258
+ `),NL(e,{file:i},()=>{console.log(`Created ${r}`)}))}}),iR=cb(`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(AL)}),alias:{query:`q`},async run(e){let t=e.options.query?.toLowerCase(),n=await QL(),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(RL).sort((e,t)=>e.id.localeCompare(t.id));return NL(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=$L(await QL(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=RL(t),r=LL(t);return NL(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`)} ${DO(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&&IL(e.homepage);i&&console.log(`${X.dim(`Docs`)} ${DO(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(jL),service:AL}),async run(e){let t=$L(await QL(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=RL(t),r=LL(t).map(zL);return NL(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=BL(n.payment),i=n.description?` ${X.dim(n.description)}`:``;console.log(`${n.method.padEnd(e)} ${n.path.padEnd(t)} ${r}${i}`)}})}}),aR=cb(`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(()=>(TL(),yL)),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`),NL(e,a,()=>{})}return NL(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(kL),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=tE(i);if(!ML(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}):NL(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.`)})}});eR.command(tR),eR.command(aR),eR.command(rR),eR.command(iR),eR.command(YF),eR.command(nR),eR.command(fL);export{eR as default,JL as resolveMppCredentialTarget};