mppx 0.17.4 → 0.17.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.
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 te}from"node:url";import*as E from"zod/v4";import{AbiParameters as D,Base64 as O,Bytes as k,Hash as ne,Hex as A,Json as j}from"ox";import{createClient as M,createTransport as re,custom as ie,encodeFunctionData as ae,erc20Abi as oe,formatUnits as se,getAbiItem as N,getAddress as ce,hashTypedData as le,http as P,isAddress as ue,isAddressEqual as de,keccak256 as fe,parseAbi as pe,parseEventLogs as me,parseUnits as he,zeroAddress as ge}from"viem";import{generatePrivateKey as _e,parseAccount as ve,privateKeyToAccount as ye}from"viem/accounts";import{tempo as be,tempoModerato as F}from"viem/tempo/chains";import*as xe from"zod/mini";import{call as Se,getBlockNumber as Ce,getLogs as we,prepareTransactionRequest as Te,readContract as Ee,sendCallsSync as De,sendRawTransactionSync 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{Channel as Be,KeyAuthorization as Ve,SignatureEnvelope as He,TempoAddress as Ue,TxEnvelopeTempo as We}from"ox/tempo";import*as Ge from"node:readline";import{ousd as Ke,pathusd as qe,usdce as Je}from"viem/tokens";import*as Ye from"viem/chains";import{tempo as Xe}from"viem/chains";var Ze=Object.defineProperty,Qe=Object.getOwnPropertyDescriptor,$e=Object.getOwnPropertyNames,et=Object.prototype.hasOwnProperty,I=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},tt=(e,t)=>{let n={};for(var r in e)Ze(n,r,{get:e[r],enumerable:!0});return t||Ze(n,Symbol.toStringTag,{value:`Module`}),n},nt=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=$e(t),a=0,o=i.length,s;a<o;a++)s=i[a],!et.call(e,s)&&s!==n&&Ze(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Qe(t,s))||r.enumerable});return e},rt=(e,t,n)=>(nt(e,t,`default`),n&&nt(n,t,`default`));function it(){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 at(){let e=it();return e===`pnpm`?`pnpx`:e===`bun`?`bunx`:`npx`}function ot(e){let t=it();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 st=I((()=>{}));function ct(e,t={}){if(wt())return;let n=ft(e,t);if(!n?.check||!n.current)return;let r=vt(n.key),i=yt(r),a=Date.now(),o=Math.max(0,t.interval??Tt);if((!i||a-i.checkedAt>=o)&&xt(r,a,i?.latest,t.binary),!(!i?.latest||!dt(i.latest,n.current)))return{current:n.current,latest:i.latest,name:n.name}}async function lt(e,t={}){let n=ft(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||!gt(r)||bt(vt(n.key),{checkedAt:Date.now(),latest:r})}async function ut(e,t={}){let n=ft(e,t);if(!n?.install)throw Error(`No update installer is configured for '${e}'.`);let r=yt(vt(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 dt(e,t){let n=gt(e),r=gt(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 ft(e,t){let n=pt(e),r=t.package??n?.name;if(r&&!_t(r))return;let i=t.version??n?.version,a=r?ot(r):void 0,o=t.check??(r?()=>ht(r):void 0),s=t.install??(a?()=>Ct(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 pt(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`&&mt(n,e))return{name:n.name,version:n.version}}catch{}let n=c.dirname(r);if(n===r)return;r=n}}function mt(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 ht(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 gt(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 _t(e){return/^(?:@[A-Za-z0-9][A-Za-z0-9._~-]*\/)?[A-Za-z0-9][A-Za-z0-9._~-]*$/.test(e)}function vt(e){let t=process.env.XDG_CACHE_HOME||c.join(b.homedir(),`.cache`);return c.join(t,`incur`,`updates`,`${encodeURIComponent(e)}.json`)}function yt(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 bt(e,n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,JSON.stringify(n)+`
2
- `)}function xt(e,t,n,r){let i=St(r);if(i)try{bt(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 St(e){if(e)return{args:[Et],command:process.execPath};let n=process.argv[1];if(n){if(n.startsWith(`/$bunfs/`))return{args:[Et],command:process.execPath};try{if(t.realpathSync(n)===t.realpathSync(process.execPath))return{args:[Et],command:process.execPath}}catch{}return{args:[...process.execArgv,n,Et],command:process.execPath}}}function Ct(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 wt(){return process.env.NO_UPDATE_NOTIFIER||process.env.npm_config_update_notifier===`false`?!0:!!(process.env.CI&&process.env.CI!==`false`)}var Tt,Et,Dt=I((()=>{st(),Tt=864e5,Et=`--incur-update-check`}));async function Ot(e=process.argv.slice(2)){if(e[0]!==`--incur-binary-apply`)return process.platform===`win32`&&Bt&&Vt&&Ht&&await Pt(process.execPath),!1;if(process.platform!==`win32`)throw Error(`${zt} is only supported on Windows.`);if(e.length!==2||!e[1])throw Error(`Invalid ${zt} arguments.`);let t=Number(e[1]);if(!Number.isSafeInteger(t)||t<=0)throw Error(`Invalid ${zt} arguments.`);return await kt(t),!0}async function kt(e){let n=At(process.execPath,e),r=!1;try{await jt(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}': ${Lt(t)}`,{cause:e})}}throw await Ft(n,i,a),i}await It(n.backup),await It(n.error),await It(n.staged),await It(n.helper)}function At(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 jt(e){let t=Date.now()+Rt;for(;Mt(e);){if(Date.now()>=t)throw Error(`Timed out waiting for update process ${e} to exit.`);await Nt(100)}}function Mt(e){try{return process.kill(e,0),!0}catch(e){return e.code!==`ESRCH`}}function Nt(e){return new Promise(t=>setTimeout(t,e))}async function Pt(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=>It(c.join(n,e))))}catch{}}async function Ft(e,n,r){let i=[`Binary update failed: ${Lt(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 It(e){try{await t.promises.unlink(e)}catch{}}function Lt(e){return e instanceof Error?e.message:String(e)}var Rt,zt,Bt,Vt,Ht,Ut=I((()=>{Rt=6e4,v.promisify(y.gunzip),zt=`--incur-binary-apply`,Bt=typeof __INCUR_BINARY_NAME__==`string`&&__INCUR_BINARY_NAME__?__INCUR_BINARY_NAME__:void 0,Vt=typeof __INCUR_BINARY_TARGET__==`string`&&__INCUR_BINARY_TARGET__?__INCUR_BINARY_TARGET__:void 0,Ht=typeof __INCUR_BINARY_VERSION__==`string`&&__INCUR_BINARY_VERSION__?__INCUR_BINARY_VERSION__:void 0}));function*Wt(e,t={}){if(!e)return;let n=Gt(t);for(let t of e.split(en))t&&(yield{segment:t,tokenCount:Kt(t,n)})}function Gt(e){return{defaultCharsPerToken:e.defaultCharsPerToken??tn,languageConfigs:e.languageConfigs??an}}function Kt(e,{languageConfigs:t,defaultCharsPerToken:n}){if($t.whitespace.test(e))return+!!$t.structuredWhitespace.test(e);let r=qt(e,t);return r===void 0?$t.cjk.test(e)?Yt(e):$t.numeric.test(e)?Math.ceil(e.length/3):e.length<=nn?1:$t.punctuation.test(e)?Math.ceil(e.length/2):Math.ceil(e.length/n):Math.ceil(Jt(e)/r)}function qt(e,t){for(let n of t)if(e.search(n.pattern)!==-1)return n.averageCharsPerToken}function Jt(e){return Array.from(e).length}function Yt(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/rn)}function Xt(e,t={}){if(!e)return 0;let n=0;for(let r of Wt(e,t))n+=r.tokenCount;return n}function Zt(e,t=0,n,r={}){if(!e)return``;let i=Wt(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=Qt(e,l,t,o,s);n&&c.push(n),l+=t}return c.join(``)}function Qt(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 $t,en,tn,nn,rn,an,on=I((()=>{$t={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:/[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_"-]/},en=RegExp(`(\\s+|${$t.punctuation.source}+)`),tn=6,nn=3,rn=1.35,an=[{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 sn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cn(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function ln(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 un(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=ln(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 dn=I((()=>{}));function fn(e,t){switch(e){case`bash`:return xn(t);case`zsh`:return Sn(t);case`fish`:return Cn(t);case`nushell`:return wn(t)}}function pn(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=`--${cn(e)}`;n.startsWith(a)&&s.push({value:n,description:yn(t[e])})}if(e.alias)for(let[n,r]of Object.entries(e.alias)){let e=`-${r}`;if(e.startsWith(a)){let r=yn(t[n]);s.push({value:e,description:r})}}}if(i){let e=i.schema.shape;for(let t of Object.keys(e)){let n=`--${cn(t)}`;n.startsWith(a)&&!s.some(e=>e.value===n)&&s.push({value:n,description:yn(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=yn(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=hn(e,t);if(n){let e=_n(n,t.options);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!gn(n,t.options))return s}}if(i){let t=hn(e,{options:i.schema,alias:i.alias});if(t){let e=_n(t,i.schema);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!gn(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 mn(e,t){switch(e){case`bash`:return t.map(e=>e.noSpace?`${e.value}\x01`:e.value).join(`\v`);case`zsh`:return t.map(e=>{let t=e.value.replaceAll(`:`,`\\:`);return e.description?`${t}:${e.description}`:t}).join(`
1
+ import{once as e}from"node:events";import*as t from"node:fs";import n,{existsSync as r,mkdirSync as i,readFileSync as a,writeFileSync as o}from"node:fs";import{createRequire as s}from"node:module";import*as c from"node:path";import l,{dirname as u,join as d}from"node:path";import{z as f,z as p}from"zod";import*as m from"node:child_process";import{execFile as h,execFileSync as g}from"node:child_process";import{createHash as _,randomUUID as v}from"node:crypto";import*as y from"node:util";import*as b from"node:zlib";import*as x from"node:os";import S,{homedir as C}from"node:os";import*as w from"node:fs/promises";import T from"node:fs/promises";import{PassThrough as E}from"node:stream";import{fileURLToPath as ee,pathToFileURL as D}from"node:url";import*as O from"zod/v4";import{AbiParameters as k,Base64 as A,Bytes as te,Hash as ne,Hex as j,Json as re}from"ox";import{createClient as M,createTransport as ie,custom as ae,encodeFunctionData as oe,erc20Abi as se,formatUnits as N,getAbiItem as ce,getAddress as le,hashTypedData as ue,http as de,isAddress as fe,isAddressEqual as pe,keccak256 as me,parseAbi as he,parseEventLogs as ge,parseUnits as _e,zeroAddress as ve}from"viem";import{generatePrivateKey as ye,parseAccount as be,privateKeyToAccount as xe}from"viem/accounts";import{tempo as P,tempoModerato as Se}from"viem/tempo/chains";import*as Ce from"zod/mini";import{call as we,getBlockNumber as Te,getLogs as Ee,prepareTransactionRequest as De,readContract as Oe,sendCallsSync as ke,sendRawTransactionSync as Ae,sendTransactionSync as je,signTransaction as Me,signTypedData as Ne,waitForTransactionReceipt as Pe}from"viem/actions";import{Abis as Fe,Account as Ie,Actions as Le,Addresses as Re,TokenId as ze,Transaction as Be,withFeePayer as Ve}from"viem/tempo";import{Channel as He,KeyAuthorization as Ue,SignatureEnvelope as We,TempoAddress as Ge,TxEnvelopeTempo as Ke}from"ox/tempo";import*as qe from"node:readline";import{ousd as Je,pathusd as Ye,usdce as Xe}from"viem/tokens";import*as Ze from"viem/chains";import{tempo as Qe}from"viem/chains";var $e=Object.defineProperty,et=Object.getOwnPropertyDescriptor,tt=Object.getOwnPropertyNames,nt=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}},rt=(e,t)=>{let n={};for(var r in e)$e(n,r,{get:e[r],enumerable:!0});return t||$e(n,Symbol.toStringTag,{value:`Module`}),n},it=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=tt(t),a=0,o=i.length,s;a<o;a++)s=i[a],!nt.call(e,s)&&s!==n&&$e(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=et(t,s))||r.enumerable});return e},at=(e,t,n)=>(it(e,t,`default`),n&&it(n,t,`default`));function ot(){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 st(){let e=ot();return e===`pnpm`?`pnpx`:e===`bun`?`bunx`:`npx`}function ct(e){let t=ot();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 lt=F((()=>{}));function ut(e,t={}){if(Et())return;let n=mt(e,t);if(!n?.check||!n.current)return;let r=bt(n.key),i=xt(r),a=Date.now(),o=Math.max(0,t.interval??Dt);if((!i||a-i.checkedAt>=o)&&Ct(r,a,i?.latest,t.binary),!(!i?.latest||!pt(i.latest,n.current)))return{current:n.current,latest:i.latest,name:n.name}}async function dt(e,t={}){let n=mt(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||!vt(r)||St(bt(n.key),{checkedAt:Date.now(),latest:r})}async function ft(e,t={}){let n=mt(e,t);if(!n?.install)throw Error(`No update installer is configured for '${e}'.`);let r=xt(bt(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 pt(e,t){let n=vt(e),r=vt(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 mt(e,t){let n=ht(e),r=t.package??n?.name;if(r&&!yt(r))return;let i=t.version??n?.version,a=r?ct(r):void 0,o=t.check??(r?()=>_t(r):void 0),s=t.install??(a?()=>Tt(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 ht(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`&&gt(n,e))return{name:n.name,version:n.version}}catch{}let n=c.dirname(r);if(n===r)return;r=n}}function gt(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 _t(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 vt(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 yt(e){return/^(?:@[A-Za-z0-9][A-Za-z0-9._~-]*\/)?[A-Za-z0-9][A-Za-z0-9._~-]*$/.test(e)}function bt(e){let t=process.env.XDG_CACHE_HOME||c.join(x.homedir(),`.cache`);return c.join(t,`incur`,`updates`,`${encodeURIComponent(e)}.json`)}function xt(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 St(e,n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,JSON.stringify(n)+`
2
+ `)}function Ct(e,t,n,r){let i=wt(r);if(i)try{St(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 wt(e){if(e)return{args:[Ot],command:process.execPath};let n=process.argv[1];if(n){if(n.startsWith(`/$bunfs/`))return{args:[Ot],command:process.execPath};try{if(t.realpathSync(n)===t.realpathSync(process.execPath))return{args:[Ot],command:process.execPath}}catch{}return{args:[...process.execArgv,n,Ot],command:process.execPath}}}function Tt(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 Et(){return process.env.NO_UPDATE_NOTIFIER||process.env.npm_config_update_notifier===`false`?!0:!!(process.env.CI&&process.env.CI!==`false`)}var Dt,Ot,kt=F((()=>{lt(),Dt=864e5,Ot=`--incur-update-check`}));async function At(e=process.argv.slice(2)){if(e[0]!==`--incur-binary-apply`)return process.platform===`win32`&&Ht&&Ut&&Wt&&await It(process.execPath),!1;if(process.platform!==`win32`)throw Error(`${Vt} is only supported on Windows.`);if(e.length!==2||!e[1])throw Error(`Invalid ${Vt} arguments.`);let t=Number(e[1]);if(!Number.isSafeInteger(t)||t<=0)throw Error(`Invalid ${Vt} arguments.`);return await jt(t),!0}async function jt(e){let n=Mt(process.execPath,e),r=!1;try{await Nt(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}': ${zt(t)}`,{cause:e})}}throw await Lt(n,i,a),i}await Rt(n.backup),await Rt(n.error),await Rt(n.staged),await Rt(n.helper)}function Mt(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 Nt(e){let t=Date.now()+Bt;for(;Pt(e);){if(Date.now()>=t)throw Error(`Timed out waiting for update process ${e} to exit.`);await Ft(100)}}function Pt(e){try{return process.kill(e,0),!0}catch(e){return e.code!==`ESRCH`}}function Ft(e){return new Promise(t=>setTimeout(t,e))}async function It(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=>Rt(c.join(n,e))))}catch{}}async function Lt(e,n,r){let i=[`Binary update failed: ${zt(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 Rt(e){try{await t.promises.unlink(e)}catch{}}function zt(e){return e instanceof Error?e.message:String(e)}var Bt,Vt,Ht,Ut,Wt,Gt=F((()=>{Bt=6e4,y.promisify(b.gunzip),Vt=`--incur-binary-apply`,Ht=typeof __INCUR_BINARY_NAME__==`string`&&__INCUR_BINARY_NAME__?__INCUR_BINARY_NAME__:void 0,Ut=typeof __INCUR_BINARY_TARGET__==`string`&&__INCUR_BINARY_TARGET__?__INCUR_BINARY_TARGET__:void 0,Wt=typeof __INCUR_BINARY_VERSION__==`string`&&__INCUR_BINARY_VERSION__?__INCUR_BINARY_VERSION__:void 0}));function*Kt(e,t={}){if(!e)return;let n=qt(t);for(let t of e.split(nn))t&&(yield{segment:t,tokenCount:Jt(t,n)})}function qt(e){return{defaultCharsPerToken:e.defaultCharsPerToken??rn,languageConfigs:e.languageConfigs??sn}}function Jt(e,{languageConfigs:t,defaultCharsPerToken:n}){if(tn.whitespace.test(e))return+!!tn.structuredWhitespace.test(e);let r=Yt(e,t);return r===void 0?tn.cjk.test(e)?Zt(e):tn.numeric.test(e)?Math.ceil(e.length/3):e.length<=an?1:tn.punctuation.test(e)?Math.ceil(e.length/2):Math.ceil(e.length/n):Math.ceil(Xt(e)/r)}function Yt(e,t){for(let n of t)if(e.search(n.pattern)!==-1)return n.averageCharsPerToken}function Xt(e){return Array.from(e).length}function Zt(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/on)}function Qt(e,t={}){if(!e)return 0;let n=0;for(let r of Kt(e,t))n+=r.tokenCount;return n}function $t(e,t=0,n,r={}){if(!e)return``;let i=Kt(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=en(e,l,t,o,s);n&&c.push(n),l+=t}return c.join(``)}function en(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 tn,nn,rn,an,on,sn,cn=F((()=>{tn={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:/[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_"-]/},nn=RegExp(`(\\s+|${tn.punctuation.source}+)`),rn=6,an=3,on=1.35,sn=[{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 ln(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function un(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function dn(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 fn(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=dn(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 pn=F((()=>{}));function mn(e,t){switch(e){case`bash`:return Cn(t);case`zsh`:return wn(t);case`fish`:return Tn(t);case`nushell`:return En(t)}}function hn(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=`--${un(e)}`;n.startsWith(a)&&s.push({value:n,description:xn(t[e])})}if(e.alias)for(let[n,r]of Object.entries(e.alias)){let e=`-${r}`;if(e.startsWith(a)){let r=xn(t[n]);s.push({value:e,description:r})}}}if(i){let e=i.schema.shape;for(let t of Object.keys(e)){let n=`--${un(t)}`;n.startsWith(a)&&!s.some(e=>e.value===n)&&s.push({value:n,description:xn(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=xn(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=_n(e,t);if(n){let e=yn(n,t.options);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!vn(n,t.options))return s}}if(i){let t=_n(e,{options:i.schema,alias:i.alias});if(t){let e=yn(t,i.schema);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!vn(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 gn(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 hn(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 gn(e,t){let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0||vn(n).constructor.name===`ZodBoolean`:!1}function _n(e,t){let n=t.shape[e];if(!n)return;let r=vn(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 vn(e){let t=e;for(;t._zod?.def?.innerType;)t=t._zod.def.innerType;return t}function yn(e){if(e)return e.description}function bn(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`)}function xn(e){let t=bn(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 _n(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 vn(e,t){let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0||bn(n).constructor.name===`ZodBoolean`:!1}function yn(e,t){let n=t.shape[e];if(!n)return;let r=bn(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 bn(e){let t=e;for(;t._zod?.def?.innerType;)t=t._zod.def.innerType;return t}function xn(e){if(e)return e.description}function Sn(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`)}function Cn(e){let t=Sn(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 Sn(e){let t=bn(e);return`#compdef ${e}
32
+ complete -o default -o bashdefault -o nosort -F _incur_complete_${t} ${e}`}function wn(e){let t=Sn(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 Cn(e){return`complete --keep-order --exclusive --command ${e} \\
44
- --arguments "(COMPLETE=fish ${e} -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))"`}function wn(e){return`# External completer for ${e}
43
+ compdef _incur_complete_${t} ${e}`}function Tn(e){return`complete --keep-order --exclusive --command ${e} \\
44
+ --arguments "(COMPLETE=fish ${e} -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))"`}function En(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_${bn(e)} = {|spans|
46
+ let _incur_complete_${Sn(e)} = {|spans|
47
47
  COMPLETE=nushell ${e} -- ...$spans | from json
48
- }`}var Tn=I((()=>{dn()}));function En(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 Dn,L,On,kn,An=I((()=>{Dn=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 En(this,e)}},L=class extends Dn{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}},On=class extends Dn{name=`Incur.ValidationError`;fieldErrors;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.fieldErrors=e.fieldErrors??[]}},kn=class extends Dn{name=`Incur.ParseError`;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0)}}}));function jn(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);In.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}`);In.has(t)?s(t,i):r.set(t,i),o+=2}}else if(n.startsWith(`-`)&&n.length===2){let t=n[1],r=Ln[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 Mn(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 Nn(e){return e.body!==null&&e.headers.get(`content-type`)===`application/x-ndjson`}async function*Pn(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 Fn(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 In,Ln,Rn=I((()=>{In=new Set([`method`,`body`,`data`,`header`]),Ln={X:`method`,d:`data`,H:`header`}}));function zn(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 Bn(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=>Bn(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=>Bn(e,t));let n={};for(let r of t)Vn(n,e,r,0);return n}function Vn(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 Vn(t,e,n,r+2),t});return}if(typeof a!=`object`||!a)return;(!e[i.key]||typeof e[i.key]!=`object`)&&(e[i.key]={}),Vn(e[i.key],a,n,r+1);return}}var Hn=I((()=>{}));function Un(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 Wn(e){return e===`true`||e===`false`||e===`null`}function Gn(e,t,n){if(t===`__proto__`){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0});return}e[t]=n}function Kn(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 Kn(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(Kn);if(e instanceof Set)return Array.from(e).map(Kn);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),Kn(t)]));if(Zn(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&Gn(t,n,Kn(e[n]));return t}return null}function qn(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function Jn(e){return Array.isArray(e)}function Yn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xn(e){return Object.keys(e).length===0}function Zn(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Qn(e){return e.length===0||e.every(e=>qn(e))}function $n(e){return e.length===0||e.every(e=>Jn(e))}function er(e){return e.length===0||e.every(e=>Yn(e))}function tr(e){return/^[A-Z_][\w.]*$/i.test(e)}function nr(e){return/^[A-Z_]\w*$/i.test(e)}function rr(e,t=Lr){return!(!e||e!==e.trim()||Wn(e)||ir(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith(`-`))}function ir(e){return Rr.test(e)||zr.test(e)}function ar(e,t,n,r,i,a,o){if(r.keyFolding!==`safe`||!Yn(t))return;let{segments:s,tail:c,leafValue:l}=or(e,t,o??r.flattenDepth);if(s.length<2||!s.every(e=>nr(e)))return;let u=sr(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 or(e,t,n){let r=[e],i=t;for(;r.length<n&&Yn(i);){let e=Object.keys(i);if(e.length!==1)break;let t=e[0],n=i[t];r.push(t),i=n}return!Yn(i)||Xn(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function sr(e){return e.join(`.`)}function cr(e,t){return e===null?Fr:typeof e==`boolean`||typeof e==`number`?String(e):lr(e,t)}function lr(e,t=Lr){return rr(e,t)?e:`"${Un(e)}"`}function ur(e){return tr(e)?e:`"${Un(e)}"`}function dr(e,t=Lr){return e.map(e=>cr(e,t)).join(t)}function fr(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;if(n!=null&&(a+=ur(n)),a+=`[${e}${i===Lr?``:i}]`,r){let e=r.map(e=>ur(e));a+=`{${e.join(i)}}`}return a+=`:`,a}function*pr(e,t,n){if(qn(e)){let n=cr(e,t.delimiter);n!==``&&(yield n);return}Jn(e)?yield*gr(void 0,e,n,t):Yn(e)&&(yield*mr(e,n,t))}function*mr(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*hr(a,c,t,n,o,r,i,s)}function*hr(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=ar(e,t,i,r,a,o,l);if(s){let{foldedKey:e,remainder:t,leafValue:i,segmentCount:c}=s,u=ur(e);if(t===void 0){if(qn(i)){yield Er(n,`${u}: ${cr(i,r.delimiter)}`,r.indent);return}if(Jn(i)){yield*gr(e,i,n,r);return}if(Yn(i)&&Xn(i)){yield Er(n,`${u}:`,r.indent);return}}if(Yn(t)){yield Er(n,`${u}:`,r.indent);let i=l-c,s=o?`${o}.${e}`:e;yield*mr(t,n+1,r,a,s,i);return}}}let u=ur(e);qn(t)?yield Er(n,`${u}: ${cr(t,r.delimiter)}`,r.indent):Jn(t)?yield*gr(e,t,n,r):Yn(t)&&(yield Er(n,`${u}:`,r.indent),Xn(t)||(yield*mr(t,n+1,r,a,c,l)))}function*gr(e,t,n,r){if(t.length===0){yield Er(n,e==null?`[]`:`${ur(e)}: []`,r.indent);return}if(Qn(t)){yield Er(n,vr(t,r.delimiter,e),r.indent);return}if($n(t)&&t.every(e=>Qn(e))){yield*_r(e,t,n,r);return}if(er(t)){let i=br(t);i?yield*yr(e,t,i,n,r):yield*Cr(e,t,n,r);return}yield*Cr(e,t,n,r)}function*_r(e,t,n,r){yield Er(n,fr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)if(Qn(e)){let t=vr(e,r.delimiter);yield Dr(n+1,t,r.indent)}}function vr(e,t,n){let r=fr(e.length,{key:n,delimiter:t}),i=dr(e,t);return e.length===0?r:`${r} ${i}`}function*yr(e,t,n,r,i){yield Er(r,fr(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*Sr(t,n,r+1,i)}function br(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&xr(e,n))return n}function xr(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)||!qn(n[e]))return!1}return!0}function*Sr(e,t,n,r){for(let i of e)yield Er(n,dr(t.map(e=>i[e]),r.delimiter),r.indent)}function*Cr(e,t,n,r){yield Er(n,fr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)yield*Tr(e,n+1,r)}function*wr(e,t,n){if(Xn(e)){yield Er(t,`-`,n.indent);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(Jn(a)&&er(a)){let e=br(a);if(e){yield Dr(t,fr(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indent),yield*Sr(a,e,t+2,n),o.length>0&&(yield*mr(Object.fromEntries(o),t+1,n));return}}let s=ur(i);if(qn(a))yield Dr(t,`${s}: ${cr(a,n.delimiter)}`,n.indent);else if(Jn(a)){if(a.length===0)yield Dr(t,`${s}: []`,n.indent);else if(Qn(a))yield Dr(t,`${s}${vr(a,n.delimiter)}`,n.indent);else{yield Dr(t,`${s}${fr(a.length,{delimiter:n.delimiter})}`,n.indent);for(let e of a)yield*Tr(e,t+2,n)}}else Yn(a)&&(yield Dr(t,`${s}:`,n.indent),Xn(a)||(yield*mr(a,t+2,n)));o.length>0&&(yield*mr(Object.fromEntries(o),t+1,n))}function*Tr(e,t,n){if(qn(e))yield Dr(t,cr(e,n.delimiter),n.indent);else if(Jn(e)){if(Qn(e))yield Dr(t,vr(e,n.delimiter),n.indent);else{yield Dr(t,fr(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*Tr(r,t+1,n)}}else Yn(e)&&(yield*wr(e,t,n))}function Er(e,t,n){return` `.repeat(n*e)+t}function Dr(e,t,n){return Er(e,`- `+t,n)}function Or(e,t){let n=t(``,e,[]);return kr(n===void 0?e:Kn(n),t,[])}function kr(e,t,n){return Yn(e)?Ar(e,t,n):Jn(e)?jr(e,t,n):e}function Ar(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&&Gn(r,i,kr(Kn(o),t,e))}return r}function jr(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=Kn(s);r.push(kr(c,t,o))}return r}function Mr(e,t){return Array.from(Nr(e,t)).join(`
50
- `)}function Nr(e,t){let n=Kn(e),r=Pr(t);return pr(r.replacer?Or(n,r.replacer):n,r,0)}function Pr(e){return{indent:e?.indent??2,delimiter:e?.delimiter??Lr,keyFolding:e?.keyFolding??`off`,flattenDepth:e?.flattenDepth??1/0,replacer:e?.replacer}}var Fr,Ir,Lr,Rr,zr,Br=I((()=>{Fr=`null`,Ir={comma:`,`,tab:` `,pipe:`|`},Lr=Ir.comma,Rr=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,zr=/^0\d+$/}));function Vr(e,t){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t,t)}function Hr(e){return JSON.parse(Vr(e))}var Ur=I((()=>{}));function Wr(e){if(e&&typeof e==`object`)switch(e[Qr]){case Jr:case Zr:return!0}return!1}function Gr(e){if(e&&typeof e==`object`)switch(e[Qr]){case Kr:case Jr:case Xr:case Zr:return!0}return!1}var Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,ni,ri,ii,ai,oi=I((()=>{Kr=Symbol.for(`yaml.alias`),qr=Symbol.for(`yaml.document`),Jr=Symbol.for(`yaml.map`),Yr=Symbol.for(`yaml.pair`),Xr=Symbol.for(`yaml.scalar`),Zr=Symbol.for(`yaml.seq`),Qr=Symbol.for(`yaml.node.type`),$r=e=>!!e&&typeof e==`object`&&e[Qr]===Kr,ei=e=>!!e&&typeof e==`object`&&e[Qr]===qr,ti=e=>!!e&&typeof e==`object`&&e[Qr]===Jr,ni=e=>!!e&&typeof e==`object`&&e[Qr]===Yr,ri=e=>!!e&&typeof e==`object`&&e[Qr]===Xr,ii=e=>!!e&&typeof e==`object`&&e[Qr]===Zr,ai=e=>(ri(e)||Wr(e))&&!!e.anchor}));function si(e,t){let n=di(t);ei(e)?ci(null,e.contents,n,Object.freeze([e]))===gi&&(e.contents=null):ci(null,e,n,Object.freeze([]))}function ci(e,t,n,r){let i=fi(e,t,n,r);if(Gr(i)||ni(i))return pi(e,r,i),ci(e,i,n,r);if(typeof i!=`symbol`){if(Wr(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=ci(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===mi)return mi;else i===gi&&(t.items.splice(e,1),--e)}}else if(ni(t)){r=Object.freeze(r.concat(t));let e=ci(`key`,t.key,n,r);if(e===mi)return mi;e===gi&&(t.key=null);let i=ci(`value`,t.value,n,r);if(i===mi)return mi;i===gi&&(t.value=null)}}return i}async function li(e,t){let n=di(t);ei(e)?await ui(null,e.contents,n,Object.freeze([e]))===gi&&(e.contents=null):await ui(null,e,n,Object.freeze([]))}async function ui(e,t,n,r){let i=await fi(e,t,n,r);if(Gr(i)||ni(i))return pi(e,r,i),ui(e,i,n,r);if(typeof i!=`symbol`){if(Wr(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=await ui(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===mi)return mi;else i===gi&&(t.items.splice(e,1),--e)}}else if(ni(t)){r=Object.freeze(r.concat(t));let e=await ui(`key`,t.key,n,r);if(e===mi)return mi;e===gi&&(t.key=null);let i=await ui(`value`,t.value,n,r);if(i===mi)return mi;i===gi&&(t.value=null)}}return i}function di(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 fi(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(ti(t))return n.Map?.(e,t,r);if(ii(t))return n.Seq?.(e,t,r);if(ni(t))return n.Pair?.(e,t,r);if(ri(t))return n.Scalar?.(e,t,r);if($r(t))return n.Alias?.(e,t,r)}function pi(e,t,n){let r=t[t.length-1];if(Wr(r))r.items[e]=n;else if(ni(r))e===`key`?r.key=n:r.value=n;else if(ei(r))r.contents=n;else{let e=$r(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var mi,hi,gi,_i=I((()=>{oi(),mi=Symbol(`break visit`),hi=Symbol(`skip children`),gi=Symbol(`remove node`),si.BREAK=mi,si.SKIP=hi,si.REMOVE=gi,li.BREAK=mi,li.SKIP=hi,li.REMOVE=gi})),vi,yi,bi,xi=I((()=>{oi(),_i(),vi={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},yi=e=>e.replace(/[!,[\]{}]/g,e=>vi[e]),bi=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+yi(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&&Gr(e.contents)){let t={};si(e.contents,(e,n)=>{Gr(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
- `)}},bi.defaultYaml={explicit:!1,version:`1.2`},bi.defaultTags={"!!":`tag:yaml.org,2002:`}}));function Si(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 Ci(e){let t=new Set;return si(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function wi(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function Ti(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=Ci(e);let a=wi(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(ri(t.node)||Wr(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 Ei=I((()=>{oi(),_i()}));function Di(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=Di(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=Di(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=Di(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=Di(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}var Oi=I((()=>{}));function ki(e,t,n){if(Array.isArray(e))return e.map((e,t)=>ki(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!ai(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 Ai=I((()=>{oi()})),ji,Mi=I((()=>{Oi(),oi(),Ai(),ji=class{constructor(e){Object.defineProperty(this,Qr,{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(!ei(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=ki(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?Di(i,{"":o},``,o):o}}}));function Ni(e,t,n){if($r(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Wr(t)){let r=0;for(let i of t.items){let t=Ni(e,i,n);t>r&&(r=t)}return r}if(ni(t)){let r=Ni(e,t.key,n),i=Ni(e,t.value,n);return Math.max(r,i)}return 1}var Pi,Fi=I((()=>{Ei(),_i(),oi(),Mi(),Ai(),Pi=class extends ji{constructor(e){super(Kr),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=[],si(e,{Node:(e,t)=>{($r(t)||ai(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||=(ki(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=Ni(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(Si(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}}})),Ii,R,Li=I((()=>{oi(),Mi(),Ai(),Ii=e=>!e||typeof e!=`function`&&typeof e!=`object`,R=class extends ji{constructor(e){super(Xr),this.value=e}toJSON(e,t){return t?.keep?this.value:ki(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 Ri(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 zi(e,t,n){if(ei(e)&&(e=e.contents),Gr(e))return e;if(ni(e)){let t=n.schema[Jr].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 Pi(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=Bi+t.slice(2));let l=Ri(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[Jr]:Symbol.iterator in Object(e)?o[Zr]:o[Jr]}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 Bi,Vi=I((()=>{Fi(),oi(),Li(),Bi=`tag:yaml.org,2002:`}));function Hi(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 zi(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var Ui,Wi,Gi=I((()=>{Vi(),oi(),Mi(),Ui=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,Wi=class extends ji{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=>Gr(t)||ni(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Ui(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(Wr(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Hi(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(Wr(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&&ri(i)?i.value:i:Wr(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ni(t))return!1;let n=t.value;return n==null||e&&ri(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 Wr(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(Wr(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,Hi(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}}));function Ki(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var qi,Ji,Yi=I((()=>{qi=e=>e.replace(/^(?!$)(?: $)?/gm,`#`),Ji=(e,t,n)=>e.endsWith(`
52
- `)?Ki(n,t):n.includes(`
48
+ }`}var Dn=F((()=>{pn()}));function On(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 kn,I,An,jn,Mn=F((()=>{kn=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 On(this,e)}},I=class extends kn{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}},An=class extends kn{name=`Incur.ValidationError`;fieldErrors;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.fieldErrors=e.fieldErrors??[]}},jn=class extends kn{name=`Incur.ParseError`;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0)}}}));function Nn(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);Rn.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}`);Rn.has(t)?s(t,i):r.set(t,i),o+=2}}else if(n.startsWith(`-`)&&n.length===2){let t=n[1],r=zn[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 Pn(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 Fn(e){return e.body!==null&&e.headers.get(`content-type`)===`application/x-ndjson`}async function*In(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 Ln(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 Rn,zn,Bn=F((()=>{Rn=new Set([`method`,`body`,`data`,`header`]),zn={X:`method`,d:`data`,H:`header`}}));function Vn(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 Hn(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=>Hn(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=>Hn(e,t));let n={};for(let r of t)Un(n,e,r,0);return n}function Un(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 Un(t,e,n,r+2),t});return}if(typeof a!=`object`||!a)return;(!e[i.key]||typeof e[i.key]!=`object`)&&(e[i.key]={}),Un(e[i.key],a,n,r+1);return}}var Wn=F((()=>{}));function Gn(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 Kn(e){return e===`true`||e===`false`||e===`null`}function qn(e,t,n){if(t===`__proto__`){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0});return}e[t]=n}function Jn(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 Jn(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(Jn);if(e instanceof Set)return Array.from(e).map(Jn);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),Jn(t)]));if($n(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&qn(t,n,Jn(e[n]));return t}return null}function Yn(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function Xn(e){return Array.isArray(e)}function Zn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qn(e){return Object.keys(e).length===0}function $n(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function er(e){return e.length===0||e.every(e=>Yn(e))}function tr(e){return e.length===0||e.every(e=>Xn(e))}function nr(e){return e.length===0||e.every(e=>Zn(e))}function rr(e){return/^[A-Z_][\w.]*$/i.test(e)}function ir(e){return/^[A-Z_]\w*$/i.test(e)}function ar(e,t=zr){return!(!e||e!==e.trim()||Kn(e)||or(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith(`-`))}function or(e){return Br.test(e)||Vr.test(e)}function sr(e,t,n,r,i,a,o){if(r.keyFolding!==`safe`||!Zn(t))return;let{segments:s,tail:c,leafValue:l}=cr(e,t,o??r.flattenDepth);if(s.length<2||!s.every(e=>ir(e)))return;let u=lr(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 cr(e,t,n){let r=[e],i=t;for(;r.length<n&&Zn(i);){let e=Object.keys(i);if(e.length!==1)break;let t=e[0],n=i[t];r.push(t),i=n}return!Zn(i)||Qn(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function lr(e){return e.join(`.`)}function ur(e,t){return e===null?Lr:typeof e==`boolean`||typeof e==`number`?String(e):dr(e,t)}function dr(e,t=zr){return ar(e,t)?e:`"${Gn(e)}"`}function fr(e){return rr(e)?e:`"${Gn(e)}"`}function pr(e,t=zr){return e.map(e=>ur(e,t)).join(t)}function mr(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;if(n!=null&&(a+=fr(n)),a+=`[${e}${i===zr?``:i}]`,r){let e=r.map(e=>fr(e));a+=`{${e.join(i)}}`}return a+=`:`,a}function*hr(e,t,n){if(Yn(e)){let n=ur(e,t.delimiter);n!==``&&(yield n);return}Xn(e)?yield*vr(void 0,e,n,t):Zn(e)&&(yield*gr(e,n,t))}function*gr(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*_r(a,c,t,n,o,r,i,s)}function*_r(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=sr(e,t,i,r,a,o,l);if(s){let{foldedKey:e,remainder:t,leafValue:i,segmentCount:c}=s,u=fr(e);if(t===void 0){if(Yn(i)){yield Or(n,`${u}: ${ur(i,r.delimiter)}`,r.indent);return}if(Xn(i)){yield*vr(e,i,n,r);return}if(Zn(i)&&Qn(i)){yield Or(n,`${u}:`,r.indent);return}}if(Zn(t)){yield Or(n,`${u}:`,r.indent);let i=l-c,s=o?`${o}.${e}`:e;yield*gr(t,n+1,r,a,s,i);return}}}let u=fr(e);Yn(t)?yield Or(n,`${u}: ${ur(t,r.delimiter)}`,r.indent):Xn(t)?yield*vr(e,t,n,r):Zn(t)&&(yield Or(n,`${u}:`,r.indent),Qn(t)||(yield*gr(t,n+1,r,a,c,l)))}function*vr(e,t,n,r){if(t.length===0){yield Or(n,e==null?`[]`:`${fr(e)}: []`,r.indent);return}if(er(t)){yield Or(n,br(t,r.delimiter,e),r.indent);return}if(tr(t)&&t.every(e=>er(e))){yield*yr(e,t,n,r);return}if(nr(t)){let i=Sr(t);i?yield*xr(e,t,i,n,r):yield*Tr(e,t,n,r);return}yield*Tr(e,t,n,r)}function*yr(e,t,n,r){yield Or(n,mr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)if(er(e)){let t=br(e,r.delimiter);yield kr(n+1,t,r.indent)}}function br(e,t,n){let r=mr(e.length,{key:n,delimiter:t}),i=pr(e,t);return e.length===0?r:`${r} ${i}`}function*xr(e,t,n,r,i){yield Or(r,mr(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*wr(t,n,r+1,i)}function Sr(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&Cr(e,n))return n}function Cr(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)||!Yn(n[e]))return!1}return!0}function*wr(e,t,n,r){for(let i of e)yield Or(n,pr(t.map(e=>i[e]),r.delimiter),r.indent)}function*Tr(e,t,n,r){yield Or(n,mr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)yield*Dr(e,n+1,r)}function*Er(e,t,n){if(Qn(e)){yield Or(t,`-`,n.indent);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(Xn(a)&&nr(a)){let e=Sr(a);if(e){yield kr(t,mr(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indent),yield*wr(a,e,t+2,n),o.length>0&&(yield*gr(Object.fromEntries(o),t+1,n));return}}let s=fr(i);if(Yn(a))yield kr(t,`${s}: ${ur(a,n.delimiter)}`,n.indent);else if(Xn(a)){if(a.length===0)yield kr(t,`${s}: []`,n.indent);else if(er(a))yield kr(t,`${s}${br(a,n.delimiter)}`,n.indent);else{yield kr(t,`${s}${mr(a.length,{delimiter:n.delimiter})}`,n.indent);for(let e of a)yield*Dr(e,t+2,n)}}else Zn(a)&&(yield kr(t,`${s}:`,n.indent),Qn(a)||(yield*gr(a,t+2,n)));o.length>0&&(yield*gr(Object.fromEntries(o),t+1,n))}function*Dr(e,t,n){if(Yn(e))yield kr(t,ur(e,n.delimiter),n.indent);else if(Xn(e)){if(er(e))yield kr(t,br(e,n.delimiter),n.indent);else{yield kr(t,mr(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*Dr(r,t+1,n)}}else Zn(e)&&(yield*Er(e,t,n))}function Or(e,t,n){return` `.repeat(n*e)+t}function kr(e,t,n){return Or(e,`- `+t,n)}function Ar(e,t){let n=t(``,e,[]);return jr(n===void 0?e:Jn(n),t,[])}function jr(e,t,n){return Zn(e)?Mr(e,t,n):Xn(e)?Nr(e,t,n):e}function Mr(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&&qn(r,i,jr(Jn(o),t,e))}return r}function Nr(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=Jn(s);r.push(jr(c,t,o))}return r}function Pr(e,t){return Array.from(Fr(e,t)).join(`
50
+ `)}function Fr(e,t){let n=Jn(e),r=Ir(t);return hr(r.replacer?Ar(n,r.replacer):n,r,0)}function Ir(e){return{indent:e?.indent??2,delimiter:e?.delimiter??zr,keyFolding:e?.keyFolding??`off`,flattenDepth:e?.flattenDepth??1/0,replacer:e?.replacer}}var Lr,Rr,zr,Br,Vr,Hr=F((()=>{Lr=`null`,Rr={comma:`,`,tab:` `,pipe:`|`},zr=Rr.comma,Br=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,Vr=/^0\d+$/}));function Ur(e,t){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t,t)}function Wr(e){return JSON.parse(Ur(e))}var Gr=F((()=>{}));function Kr(e){if(e&&typeof e==`object`)switch(e[ei]){case Xr:case $r:return!0}return!1}function qr(e){if(e&&typeof e==`object`)switch(e[ei]){case Jr:case Xr:case Qr:case $r:return!0}return!1}var Jr,Yr,Xr,Zr,Qr,$r,ei,ti,ni,ri,ii,ai,oi,si,L=F((()=>{Jr=Symbol.for(`yaml.alias`),Yr=Symbol.for(`yaml.document`),Xr=Symbol.for(`yaml.map`),Zr=Symbol.for(`yaml.pair`),Qr=Symbol.for(`yaml.scalar`),$r=Symbol.for(`yaml.seq`),ei=Symbol.for(`yaml.node.type`),ti=e=>!!e&&typeof e==`object`&&e[ei]===Jr,ni=e=>!!e&&typeof e==`object`&&e[ei]===Yr,ri=e=>!!e&&typeof e==`object`&&e[ei]===Xr,ii=e=>!!e&&typeof e==`object`&&e[ei]===Zr,ai=e=>!!e&&typeof e==`object`&&e[ei]===Qr,oi=e=>!!e&&typeof e==`object`&&e[ei]===$r,si=e=>(ai(e)||Kr(e))&&!!e.anchor}));function ci(e,t){let n=fi(t);ni(e)?li(null,e.contents,n,Object.freeze([e]))===_i&&(e.contents=null):li(null,e,n,Object.freeze([]))}function li(e,t,n,r){let i=pi(e,t,n,r);if(qr(i)||ii(i))return mi(e,r,i),li(e,i,n,r);if(typeof i!=`symbol`){if(Kr(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=li(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===hi)return hi;else i===_i&&(t.items.splice(e,1),--e)}}else if(ii(t)){r=Object.freeze(r.concat(t));let e=li(`key`,t.key,n,r);if(e===hi)return hi;e===_i&&(t.key=null);let i=li(`value`,t.value,n,r);if(i===hi)return hi;i===_i&&(t.value=null)}}return i}async function ui(e,t){let n=fi(t);ni(e)?await di(null,e.contents,n,Object.freeze([e]))===_i&&(e.contents=null):await di(null,e,n,Object.freeze([]))}async function di(e,t,n,r){let i=await pi(e,t,n,r);if(qr(i)||ii(i))return mi(e,r,i),di(e,i,n,r);if(typeof i!=`symbol`){if(Kr(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=await di(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===hi)return hi;else i===_i&&(t.items.splice(e,1),--e)}}else if(ii(t)){r=Object.freeze(r.concat(t));let e=await di(`key`,t.key,n,r);if(e===hi)return hi;e===_i&&(t.key=null);let i=await di(`value`,t.value,n,r);if(i===hi)return hi;i===_i&&(t.value=null)}}return i}function fi(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 pi(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(ri(t))return n.Map?.(e,t,r);if(oi(t))return n.Seq?.(e,t,r);if(ii(t))return n.Pair?.(e,t,r);if(ai(t))return n.Scalar?.(e,t,r);if(ti(t))return n.Alias?.(e,t,r)}function mi(e,t,n){let r=t[t.length-1];if(Kr(r))r.items[e]=n;else if(ii(r))e===`key`?r.key=n:r.value=n;else if(ni(r))r.contents=n;else{let e=ti(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var hi,gi,_i,vi=F((()=>{L(),hi=Symbol(`break visit`),gi=Symbol(`skip children`),_i=Symbol(`remove node`),ci.BREAK=hi,ci.SKIP=gi,ci.REMOVE=_i,ui.BREAK=hi,ui.SKIP=gi,ui.REMOVE=_i})),yi,bi,xi,Si=F((()=>{L(),vi(),yi={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},bi=e=>e.replace(/[!,[\]{}]/g,e=>yi[e]),xi=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+bi(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&&qr(e.contents)){let t={};ci(e.contents,(e,n)=>{qr(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
+ `)}},xi.defaultYaml={explicit:!1,version:`1.2`},xi.defaultTags={"!!":`tag:yaml.org,2002:`}}));function Ci(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 wi(e){let t=new Set;return ci(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function Ti(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function Ei(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=wi(e);let a=Ti(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(ai(t.node)||Kr(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 Di=F((()=>{L(),vi()}));function Oi(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=Oi(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=Oi(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=Oi(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=Oi(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}var ki=F((()=>{}));function Ai(e,t,n){if(Array.isArray(e))return e.map((e,t)=>Ai(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!si(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 ji=F((()=>{L()})),Mi,Ni=F((()=>{ki(),L(),ji(),Mi=class{constructor(e){Object.defineProperty(this,ei,{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(!ni(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=Ai(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?Oi(i,{"":o},``,o):o}}}));function Pi(e,t,n){if(ti(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Kr(t)){let r=0;for(let i of t.items){let t=Pi(e,i,n);t>r&&(r=t)}return r}if(ii(t)){let r=Pi(e,t.key,n),i=Pi(e,t.value,n);return Math.max(r,i)}return 1}var Fi,Ii=F((()=>{Di(),vi(),L(),Ni(),ji(),Fi=class extends Mi{constructor(e){super(Jr),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=[],ci(e,{Node:(e,t)=>{(ti(t)||si(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||=(Ai(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=Pi(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(Ci(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}}})),Li,R,Ri=F((()=>{L(),Ni(),ji(),Li=e=>!e||typeof e!=`function`&&typeof e!=`object`,R=class extends Mi{constructor(e){super(Qr),this.value=e}toJSON(e,t){return t?.keep?this.value:Ai(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 zi(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 Bi(e,t,n){if(ni(e)&&(e=e.contents),qr(e))return e;if(ii(e)){let t=n.schema[Xr].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 Fi(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=Vi+t.slice(2));let l=zi(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[Xr]:Symbol.iterator in Object(e)?o[$r]:o[Xr]}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 Vi,Hi=F((()=>{Ii(),L(),Ri(),Vi=`tag:yaml.org,2002:`}));function Ui(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 Bi(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var Wi,Gi,Ki=F((()=>{Hi(),L(),Ni(),Wi=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,Gi=class extends Mi{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=>qr(t)||ii(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Wi(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(Kr(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Ui(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(Kr(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&&ai(i)?i.value:i:Kr(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ii(t))return!1;let n=t.value;return n==null||e&&ai(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 Kr(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(Kr(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,Ui(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}}));function qi(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Ji,Yi,Xi=F((()=>{Ji=e=>e.replace(/^(?!$)(?: $)?/gm,`#`),Yi=(e,t,n)=>e.endsWith(`
52
+ `)?qi(n,t):n.includes(`
53
53
  `)?`
54
- `+Ki(n,t):(e.endsWith(` `)?``:` `)+n}));function Xi(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=Zi(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=Zi(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
54
+ `+qi(n,t):(e.endsWith(` `)?``:` `)+n}));function Zi(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 Zi(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,$i,ea,ta=I((()=>{Qi=`flow`,$i=`block`,ea=`quoted`}));function na(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 ra(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(ua(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 $i,ea,ta,na=F((()=>{$i=`flow`,ea=`block`,ta=`quoted`}));function ra(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 ia(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(da(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:Xi(o,a,ea,la(t,!1))}function ia(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
63
- `)||/[ \t]\n|\n[ \t]/.test(e))return ra(e,t);let n=t.indent||(ua(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:Xi(r,n,Qi,la(t,!1))}function aa(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=ra;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?ia:i&&!t?ra:n?ia:ra}return r(e,t)}function oa({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 aa(n,r);let l=r.indent||(r.forceBlockIndent||ua(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===R.BLOCK_FOLDED?!1:t===R.BLOCK_LITERAL||!na(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:Zi(o,a,ta,ua(t,!1))}function aa(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
63
+ `)||/[ \t]\n|\n[ \t]/.test(e))return ia(e,t);let n=t.indent||(da(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:Zi(r,n,$i,ua(t,!1))}function oa(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=ia;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?aa:i&&!t?ia:n?aa:ia}return r(e,t)}function sa({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 oa(n,r);let l=r.indent||(r.forceBlockIndent||da(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===R.BLOCK_FOLDED?!1:t===R.BLOCK_LITERAL||!ra(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(da,`$&${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(fa,`$&${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=la(r,!0);o!==`folded`&&t!==R.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=Xi(`${v}${e}${p}`,l,$i,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function sa(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 aa(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
72
- `)?aa(a,t):oa(e,t,n,r);if(!s&&!u&&i!==R.PLAIN&&a.includes(`
73
- `))return oa(e,t,n,r);if(ua(a)){if(c===``)return t.forceBlockIndent=!0,oa(e,t,n,r);if(s&&c===l)return aa(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 aa(a,t)}return s?d:Xi(d,c,Qi,la(t,!1))}function ca(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?aa(o.value,t):oa(o,t,n,r);case R.QUOTE_DOUBLE:return ra(o.value,t);case R.QUOTE_SINGLE:return ia(o.value,t);case R.PLAIN:return sa(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 la,ua,da,fa=I((()=>{Li(),ta(),la=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ua=e=>/^(%|---|\.\.\.)/m.test(e);try{da=RegExp(`(^|(?<!
70
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=ua(r,!0);o!==`folded`&&t!==R.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=Zi(`${v}${e}${p}`,l,ea,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function ca(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 oa(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
72
+ `)?oa(a,t):sa(e,t,n,r);if(!s&&!u&&i!==R.PLAIN&&a.includes(`
73
+ `))return sa(e,t,n,r);if(da(a)){if(c===``)return t.forceBlockIndent=!0,sa(e,t,n,r);if(s&&c===l)return oa(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 oa(a,t)}return s?d:Zi(d,c,$i,ua(t,!1))}function la(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?oa(o.value,t):sa(o,t,n,r);case R.QUOTE_DOUBLE:return ia(o.value,t);case R.QUOTE_SINGLE:return aa(o.value,t);case R.PLAIN:return ca(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 ua,da,fa,pa=F((()=>{Ri(),na(),ua=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),da=e=>/^(%|---|\.\.\.)/m.test(e);try{fa=RegExp(`(^|(?<!
74
74
  ))
75
75
  +(?!
76
- |$)`,`g`)}catch{da=/\n+(?!\n|$)/g}}));function pa(e,t){let n=Object.assign({blockQuote:!0,commentString:qi,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 ma(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(ri(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 ha(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(ri(e)||Wr(e))&&e.anchor;a&&Si(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 ga(e,t,n,r){if(ni(e))return e.toString(t,n,r);if($r(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=Gr(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=ma(t.doc.schema.tags,a);let o=ha(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):ri(a)?ca(a,t,n,r):a.toString(t,n,r);return o?ri(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}var _a=I((()=>{Ei(),oi(),Yi(),fa()}));function va({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=Gr(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(Wr(e)||!Gr(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||Wr(e)||(ri(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=ga(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+=Ji(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=Ji(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=Ji(g,n.indent,l(f))));let _,v,y;Gr(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&&ri(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&ii(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=ga(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?`
77
- `:``,v){let e=l(v);S+=`\n${Ki(e,n.indent)}`}x===``&&!n.inFlow?S===`
76
+ |$)`,`g`)}catch{fa=/\n+(?!\n|$)/g}}));function ma(e,t){let n=Object.assign({blockQuote:!0,commentString:Ji,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 ha(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(ai(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 ga(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(ai(e)||Kr(e))&&e.anchor;a&&Ci(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 _a(e,t,n,r){if(ii(e))return e.toString(t,n,r);if(ti(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=qr(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=ha(t.doc.schema.tags,a);let o=ga(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):ai(a)?la(a,t,n,r):a.toString(t,n,r);return o?ai(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}var va=F((()=>{Di(),L(),Xi(),pa()}));function ya({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=qr(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(Kr(e)||!qr(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||Kr(e)||(ai(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=_a(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+=Yi(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=Yi(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=Yi(g,n.indent,l(f))));let _,v,y;qr(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&&ai(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&oi(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=_a(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?`
77
+ `:``,v){let e=l(v);S+=`\n${qi(e,n.indent)}`}x===``&&!n.inFlow?S===`
78
78
  `&&y&&(S=`
79
79
 
80
- `):S+=`\n${n.indent}`}else if(!p&&Wr(t)){let e=x[0],r=x.indexOf(`
80
+ `):S+=`\n${n.indent}`}else if(!p&&Kr(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+=Ji(g,n.indent,l(y)):h&&i&&i(),g}var ya=I((()=>{oi(),Li(),_a(),Yi()}));function ba(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var xa=I((()=>{}));function Sa(e,t,n){let r=wa(e,n);if(ii(r))for(let n of r.items)Ca(e,t,n);else if(Array.isArray(r))for(let n of r)Ca(e,t,n);else Ca(e,t,r)}function Ca(e,t,n){let r=wa(e,n);if(!ti(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 wa(e,t){return e&&$r(t)?t.resolve(e.doc,e):t}var Ta,Ea,Da,Oa=I((()=>{oi(),Li(),Ta=`<<`,Ea={identify:e=>e===Ta||typeof e==`symbol`&&e.description===Ta,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new R(Symbol(Ta)),{addToJSMap:Sa}),stringify:()=>Ta},Da=(e,t)=>(Ea.identify(t)||ri(t)&&(!t.type||t.type===R.PLAIN)&&Ea.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===Ea.tag&&e.default)}));function ka(e,t,{key:n,value:r}){if(Gr(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(Da(e,n))Sa(e,t,r);else{let i=ki(n,``,e);if(t instanceof Map)t.set(i,ki(r,i,e));else if(t instanceof Set)t.add(i);else{let a=Aa(n,i,e),o=ki(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Aa(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(Gr(e)&&n?.doc){let t=pa(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)+`..."`),ba(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 ja=I((()=>{xa(),Oa(),_a(),oi(),Ai()}));function Ma(e,t,n){let r=zi(e,void 0,n),i=zi(t,void 0,n);return new Na(r,i)}var Na,Pa=I((()=>{Vi(),ya(),ja(),oi(),Na=class e{constructor(e,t=null){Object.defineProperty(this,Qr,{value:Yr}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return Gr(n)&&(n=n.clone(t)),Gr(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return ka(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?va(this,e,t,n):JSON.stringify(this)}}}));function Fa(e,t,n){return(t.inFlow??e.flow?La:Ia)(e,t,n)}function Ia({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(Gr(i))!d&&i.spaceBefore&&f.push(``),Ra(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(ni(i)){let e=Gr(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),Ra(n,f,e.commentBefore,d))}d=!1;let s=ga(i,u,()=>o=null,()=>d=!0);o&&(s+=Ji(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+=Yi(g,n.indent,l(y)):h&&i&&i(),g}var ba=F((()=>{L(),Ri(),va(),Xi()}));function xa(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var Sa=F((()=>{}));function Ca(e,t,n){let r=Ta(e,n);if(oi(r))for(let n of r.items)wa(e,t,n);else if(Array.isArray(r))for(let n of r)wa(e,t,n);else wa(e,t,r)}function wa(e,t,n){let r=Ta(e,n);if(!ri(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 Ta(e,t){return e&&ti(t)?t.resolve(e.doc,e):t}var Ea,Da,Oa,ka=F((()=>{L(),Ri(),Ea=`<<`,Da={identify:e=>e===Ea||typeof e==`symbol`&&e.description===Ea,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new R(Symbol(Ea)),{addToJSMap:Ca}),stringify:()=>Ea},Oa=(e,t)=>(Da.identify(t)||ai(t)&&(!t.type||t.type===R.PLAIN)&&Da.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===Da.tag&&e.default)}));function Aa(e,t,{key:n,value:r}){if(qr(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(Oa(e,n))Ca(e,t,r);else{let i=Ai(n,``,e);if(t instanceof Map)t.set(i,Ai(r,i,e));else if(t instanceof Set)t.add(i);else{let a=ja(n,i,e),o=Ai(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function ja(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(qr(e)&&n?.doc){let t=ma(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)+`..."`),xa(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 Ma=F((()=>{Sa(),ka(),va(),L(),ji()}));function Na(e,t,n){let r=Bi(e,void 0,n),i=Bi(t,void 0,n);return new Pa(r,i)}var Pa,Fa=F((()=>{Hi(),ba(),Ma(),L(),Pa=class e{constructor(e,t=null){Object.defineProperty(this,ei,{value:Zr}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return qr(n)&&(n=n.clone(t)),qr(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return Aa(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?ya(this,e,t,n):JSON.stringify(this)}}}));function Ia(e,t,n){return(t.inFlow??e.flow?Ra:La)(e,t,n)}function La({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(qr(i))!d&&i.spaceBefore&&f.push(``),za(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(ii(i)){let e=qr(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),za(n,f,e.commentBefore,d))}d=!1;let s=_a(i,u,()=>o=null,()=>d=!0);o&&(s+=Yi(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
- `+Ki(l(e),c),s&&s()):d&&o&&o(),p}function La({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(Gr(i))i.spaceBefore&&d.push(``),Ra(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(ni(i)){let e=Gr(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),Ra(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=Gr(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=ga(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+=Ji(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 Ra({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=Ki(t(r),e);n.push(i.trimStart())}}var za=I((()=>{oi(),_a(),Yi()}));function Ba(e,t){let n=ri(t)?t.value:t;for(let r of e)if(ni(r)&&(r.key===t||r.key===n||ri(r.key)&&r.key.value===n))return r}var Va,Ha=I((()=>{za(),ja(),Gi(),oi(),Pa(),Li(),Va=class extends Wi{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(Jr,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(Ma(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=ni(e)?e:!e||typeof e!=`object`||!(`key`in e)?new Na(e,e?.value):new Na(e.key,e.value);let r=Ba(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);ri(r.value)&&Ii(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=Ba(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=Ba(this.items,e)?.value;return(!t&&ri(n)?n.value:n)??void 0}has(e){return!!Ba(this.items,e)}set(e,t){this.add(new Na(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)ka(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!ni(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})),Fa(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}}})),Ua,Wa=I((()=>{oi(),Ha(),Ua={collection:`map`,default:!0,nodeClass:Va,tag:`tag:yaml.org,2002:map`,resolve(e,t){return ti(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>Va.from(e,t,n)}}));function Ga(e){let t=ri(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var Ka,qa=I((()=>{Vi(),za(),Gi(),oi(),Li(),Ai(),Ka=class extends Wi{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(Zr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Ga(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=Ga(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&ri(r)?r.value:r}has(e){let t=Ga(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=Ga(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];ri(r)&&Ii(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(ki(e,String(r++),t));return n}toString(e,t,n){return e?Fa(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(zi(a,void 0,n))}}return i}}})),Ja,Ya=I((()=>{oi(),qa(),Ja={collection:`seq`,default:!0,nodeClass:Ka,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return ii(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>Ka.from(e,t,n)}})),Xa,Za=I((()=>{fa(),Xa={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),ca(e,t,n,r)}}})),Qa,$a=I((()=>{Li(),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}})),eo,to=I((()=>{Li(),eo={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&&eo.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}}}));function no({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 ro=I((()=>{})),io,ao,oo,so=I((()=>{Li(),ro(),io={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:no},ao={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():no(e)}},oo={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:no}}));function co(e,t,n){let{value:r}=e;return lo(r)&&r>=0?n+r.toString(t):no(e)}var lo,uo,fo,po,mo,ho=I((()=>{ro(),lo=e=>typeof e==`bigint`||Number.isInteger(e),uo=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n),fo={identify:e=>lo(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>uo(e,2,8,n),stringify:e=>co(e,8,`0o`)},po={identify:lo,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>uo(e,0,10,n),stringify:no},mo={identify:e=>lo(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>uo(e,2,16,n),stringify:e=>co(e,16,`0x`)}})),go,_o=I((()=>{Wa(),$a(),Ya(),Za(),to(),so(),ho(),go=[Ua,Ja,Xa,Qa,eo,fo,po,mo,io,ao,oo]}));function vo(e){return typeof e==`bigint`||Number.isInteger(e)}var yo,bo,xo,So=I((()=>{Li(),Wa(),Ya(),yo=({value:e})=>JSON.stringify(e),bo=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:yo},{identify:e=>e==null,createNode:()=>new R(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:yo},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:yo},{identify:vo,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})=>vo(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:yo}],xo=[Ua,Ja].concat(bo,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),Co,wo=I((()=>{Li(),fa(),Co={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 ca({comment:e,type:t,value:s},r,i,a)}}}));function To(e,t){if(ii(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!ni(r)){if(ti(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new Na(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]=ni(r)?r:new Na(r)}}else t(`Expected a sequence for this tag`);return e}function Eo(e,t,n){let{replacer:r}=n,i=new Ka(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(Ma(o,s,n))}return i}var Do,Oo=I((()=>{oi(),Pa(),Li(),qa(),Do={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:To,createNode:Eo}})),ko,Ao,jo=I((()=>{oi(),Ai(),Ha(),qa(),Oo(),ko=class e extends Ka{constructor(){super(),this.add=Va.prototype.add.bind(this),this.delete=Va.prototype.delete.bind(this),this.get=Va.prototype.get.bind(this),this.has=Va.prototype.has.bind(this),this.set=Va.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(ni(e)?(r=ki(e.key,``,t),i=ki(e.value,r,t)):r=ki(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=Eo(e,t,n),i=new this;return i.items=r.items,i}},ko.tag=`tag:yaml.org,2002:omap`,Ao={collection:`seq`,identify:e=>e instanceof Map,nodeClass:ko,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=To(e,t),r=[];for(let{key:e}of n.items)ri(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new ko,n)},createNode:(e,t,n)=>ko.from(e,t,n)}}));function Mo({value:e,source:t},n){return t&&(e?No:Po).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var No,Po,Fo=I((()=>{Li(),No={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:Mo},Po={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:Mo}})),Io,Lo,Ro,zo=I((()=>{Li(),ro(),Io={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:no},Lo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():no(e)}},Ro={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:no}}));function Bo(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 Vo(e,t,n){let{value:r}=e;if(Ho(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return no(e)}var Ho,Uo,Wo,Go,Ko,qo=I((()=>{ro(),Ho=e=>typeof e==`bigint`||Number.isInteger(e),Uo={identify:Ho,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Bo(e,2,2,n),stringify:e=>Vo(e,2,`0b`)},Wo={identify:Ho,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Bo(e,1,8,n),stringify:e=>Vo(e,8,`0`)},Go={identify:Ho,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Bo(e,0,10,n),stringify:no},Ko={identify:Ho,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Bo(e,2,16,n),stringify:e=>Vo(e,16,`0x`)}})),Jo,Yo,Xo=I((()=>{oi(),Pa(),Ha(),Jo=class e extends Va{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=ni(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new Na(e.key,null):new Na(e,null),Ba(this.items,t.key)||this.items.push(t)}get(e,t){let n=Ba(this.items,e);return!t&&ni(n)?ri(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=Ba(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Na(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(Ma(e,null,n));return i}},Jo.tag=`tag:yaml.org,2002:set`,Yo={collection:`map`,identify:e=>e instanceof Set,nodeClass:Jo,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>Jo.from(e,t,n),resolve(e,t){if(ti(e)){if(e.hasAllNullValues(!0))return Object.assign(new Jo,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}}}));function Zo(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 no(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 $o,es,ts,ns=I((()=>{ro(),$o={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})=>Zo(e,n),stringify:Qo},es={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=>Zo(e,!1),stringify:Qo},ts={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(ts.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=Zo(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$/,``)??``}})),rs,is=I((()=>{Wa(),$a(),Ya(),Za(),wo(),Fo(),zo(),qo(),Oa(),jo(),Oo(),Xo(),ns(),rs=[Ua,Ja,Xa,Qa,No,Po,Uo,Wo,Go,Ko,Io,Lo,Ro,Co,Ea,Ao,Do,Yo,$o,es,ts]}));function as(e,t,n){let r=os.get(t);if(r&&!e)return n&&!r.includes(Ea)?r.concat(Ea):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(os.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(Ea)),i.reduce((e,t)=>{let n=typeof t==`string`?ss[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(ss).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 os,ss,cs,ls=I((()=>{Wa(),$a(),Ya(),Za(),to(),so(),ho(),_o(),So(),wo(),Oa(),jo(),Oo(),is(),Xo(),ns(),os=new Map([[`core`,go],[`failsafe`,[Ua,Ja,Xa]],[`json`,xo],[`yaml11`,rs],[`yaml-1.1`,rs]]),ss={binary:Co,bool:eo,float:oo,floatExp:ao,floatNaN:io,floatTime:es,int:po,intHex:mo,intOct:fo,intTime:$o,map:Ua,merge:Ea,null:Qa,omap:Ao,pairs:Do,seq:Ja,set:Yo,timestamp:ts},cs={"tag:yaml.org,2002:binary":Co,"tag:yaml.org,2002:merge":Ea,"tag:yaml.org,2002:omap":Ao,"tag:yaml.org,2002:pairs":Do,"tag:yaml.org,2002:set":Yo,"tag:yaml.org,2002:timestamp":ts}})),us,ds,fs=I((()=>{oi(),Wa(),Ya(),Za(),ls(),us=(e,t)=>e.key<t.key?-1:+(e.key>t.key),ds=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?as(e,`compat`):e?as(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?cs:{},this.tags=as(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,Jr,{value:Ua}),Object.defineProperty(this,Xr,{value:Xa}),Object.defineProperty(this,Zr,{value:Ja}),this.sortMapEntries=typeof a==`function`?a:a===!0?us:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}}));function ps(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=pa(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(Ki(t,``))}let o=!1,s=null;if(e.contents){if(Gr(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(Ki(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=ga(e.contents,i,()=>s=null,t);s&&(c+=Ji(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(ga(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
88
- `)?(n.push(`...`),n.push(Ki(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(Ki(a(t),``)))}return n.join(`
84
+ `+qi(l(e),c),s&&s()):d&&o&&o(),p}function Ra({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(qr(i))i.spaceBefore&&d.push(``),za(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(ii(i)){let e=qr(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),za(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=qr(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=_a(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+=Yi(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 za({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=qi(t(r),e);n.push(i.trimStart())}}var Ba=F((()=>{L(),va(),Xi()}));function Va(e,t){let n=ai(t)?t.value:t;for(let r of e)if(ii(r)&&(r.key===t||r.key===n||ai(r.key)&&r.key.value===n))return r}var Ha,Ua=F((()=>{Ba(),Ma(),Ki(),L(),Fa(),Ri(),Ha=class extends Gi{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(Xr,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(Na(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=ii(e)?e:!e||typeof e!=`object`||!(`key`in e)?new Pa(e,e?.value):new Pa(e.key,e.value);let r=Va(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);ai(r.value)&&Li(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=Va(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=Va(this.items,e)?.value;return(!t&&ai(n)?n.value:n)??void 0}has(e){return!!Va(this.items,e)}set(e,t){this.add(new Pa(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)Aa(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!ii(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})),Ia(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}}})),Wa,Ga=F((()=>{L(),Ua(),Wa={collection:`map`,default:!0,nodeClass:Ha,tag:`tag:yaml.org,2002:map`,resolve(e,t){return ri(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>Ha.from(e,t,n)}}));function Ka(e){let t=ai(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var qa,Ja=F((()=>{Hi(),Ba(),Ki(),L(),Ri(),ji(),qa=class extends Gi{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super($r,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Ka(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=Ka(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&ai(r)?r.value:r}has(e){let t=Ka(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=Ka(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];ai(r)&&Li(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(Ai(e,String(r++),t));return n}toString(e,t,n){return e?Ia(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(Bi(a,void 0,n))}}return i}}})),Ya,Xa=F((()=>{L(),Ja(),Ya={collection:`seq`,default:!0,nodeClass:qa,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return oi(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>qa.from(e,t,n)}})),Za,Qa=F((()=>{pa(),Za={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),la(e,t,n,r)}}})),$a,eo=F((()=>{Ri(),$a={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`&&$a.test.test(e)?e:t.options.nullStr}})),to,no=F((()=>{Ri(),to={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&&to.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}}}));function ro({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 io=F((()=>{})),ao,oo,so,co=F((()=>{Ri(),io(),ao={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:ro},oo={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():ro(e)}},so={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:ro}}));function lo(e,t,n){let{value:r}=e;return uo(r)&&r>=0?n+r.toString(t):ro(e)}var uo,fo,po,mo,ho,go=F((()=>{io(),uo=e=>typeof e==`bigint`||Number.isInteger(e),fo=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n),po={identify:e=>uo(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>fo(e,2,8,n),stringify:e=>lo(e,8,`0o`)},mo={identify:uo,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>fo(e,0,10,n),stringify:ro},ho={identify:e=>uo(e)&&e>=0,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=>lo(e,16,`0x`)}})),_o,vo=F((()=>{Ga(),eo(),Xa(),Qa(),no(),co(),go(),_o=[Wa,Ya,Za,$a,to,po,mo,ho,ao,oo,so]}));function yo(e){return typeof e==`bigint`||Number.isInteger(e)}var bo,xo,So,Co=F((()=>{Ri(),Ga(),Xa(),bo=({value:e})=>JSON.stringify(e),xo=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:bo},{identify:e=>e==null,createNode:()=>new R(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:bo},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:bo},{identify:yo,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})=>yo(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:bo}],So=[Wa,Ya].concat(xo,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),wo,To=F((()=>{Ri(),pa(),wo={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 la({comment:e,type:t,value:s},r,i,a)}}}));function Eo(e,t){if(oi(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!ii(r)){if(ri(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new Pa(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]=ii(r)?r:new Pa(r)}}else t(`Expected a sequence for this tag`);return e}function Do(e,t,n){let{replacer:r}=n,i=new qa(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(Na(o,s,n))}return i}var Oo,ko=F((()=>{L(),Fa(),Ri(),Ja(),Oo={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:Eo,createNode:Do}})),Ao,jo,Mo=F((()=>{L(),ji(),Ua(),Ja(),ko(),Ao=class e extends qa{constructor(){super(),this.add=Ha.prototype.add.bind(this),this.delete=Ha.prototype.delete.bind(this),this.get=Ha.prototype.get.bind(this),this.has=Ha.prototype.has.bind(this),this.set=Ha.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(ii(e)?(r=Ai(e.key,``,t),i=Ai(e.value,r,t)):r=Ai(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=Do(e,t,n),i=new this;return i.items=r.items,i}},Ao.tag=`tag:yaml.org,2002:omap`,jo={collection:`seq`,identify:e=>e instanceof Map,nodeClass:Ao,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=Eo(e,t),r=[];for(let{key:e}of n.items)ai(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new Ao,n)},createNode:(e,t,n)=>Ao.from(e,t,n)}}));function No({value:e,source:t},n){return t&&(e?Po:Fo).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Po,Fo,Io=F((()=>{Ri(),Po={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:No},Fo={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:No}})),Lo,Ro,zo,Bo=F((()=>{Ri(),io(),Lo={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:ro},Ro={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():ro(e)}},zo={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:ro}}));function Vo(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 Ho(e,t,n){let{value:r}=e;if(Uo(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return ro(e)}var Uo,Wo,Go,Ko,qo,Jo=F((()=>{io(),Uo=e=>typeof e==`bigint`||Number.isInteger(e),Wo={identify:Uo,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Vo(e,2,2,n),stringify:e=>Ho(e,2,`0b`)},Go={identify:Uo,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Vo(e,1,8,n),stringify:e=>Ho(e,8,`0`)},Ko={identify:Uo,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Vo(e,0,10,n),stringify:ro},qo={identify:Uo,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Vo(e,2,16,n),stringify:e=>Ho(e,16,`0x`)}})),Yo,Xo,Zo=F((()=>{L(),Fa(),Ua(),Yo=class e extends Ha{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=ii(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new Pa(e.key,null):new Pa(e,null),Va(this.items,t.key)||this.items.push(t)}get(e,t){let n=Va(this.items,e);return!t&&ii(n)?ai(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=Va(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Pa(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(Na(e,null,n));return i}},Yo.tag=`tag:yaml.org,2002:set`,Xo={collection:`map`,identify:e=>e instanceof Set,nodeClass:Yo,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>Yo.from(e,t,n),resolve(e,t){if(ri(e)){if(e.hasAllNullValues(!0))return Object.assign(new Yo,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 $o(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return ro(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 es,ts,ns,rs=F((()=>{io(),es={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:$o},ts={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:$o},ns={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(ns.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$/,``)??``}})),is,as=F((()=>{Ga(),eo(),Xa(),Qa(),To(),Io(),Bo(),Jo(),ka(),Mo(),ko(),Zo(),rs(),is=[Wa,Ya,Za,$a,Po,Fo,Wo,Go,Ko,qo,Lo,Ro,zo,wo,Da,jo,Oo,Xo,es,ts,ns]}));function os(e,t,n){let r=ss.get(t);if(r&&!e)return n&&!r.includes(Da)?r.concat(Da):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(ss.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(Da)),i.reduce((e,t)=>{let n=typeof t==`string`?cs[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(cs).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 ss,cs,ls,us=F((()=>{Ga(),eo(),Xa(),Qa(),no(),co(),go(),vo(),Co(),To(),ka(),Mo(),ko(),as(),Zo(),rs(),ss=new Map([[`core`,_o],[`failsafe`,[Wa,Ya,Za]],[`json`,So],[`yaml11`,is],[`yaml-1.1`,is]]),cs={binary:wo,bool:to,float:so,floatExp:oo,floatNaN:ao,floatTime:ts,int:mo,intHex:ho,intOct:po,intTime:es,map:Wa,merge:Da,null:$a,omap:jo,pairs:Oo,seq:Ya,set:Xo,timestamp:ns},ls={"tag:yaml.org,2002:binary":wo,"tag:yaml.org,2002:merge":Da,"tag:yaml.org,2002:omap":jo,"tag:yaml.org,2002:pairs":Oo,"tag:yaml.org,2002:set":Xo,"tag:yaml.org,2002:timestamp":ns}})),ds,fs,ps=F((()=>{L(),Ga(),Xa(),Qa(),us(),ds=(e,t)=>e.key<t.key?-1:+(e.key>t.key),fs=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?os(e,`compat`):e?os(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?ls:{},this.tags=os(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,Xr,{value:Wa}),Object.defineProperty(this,Qr,{value:Za}),Object.defineProperty(this,$r,{value:Ya}),this.sortMapEntries=typeof a==`function`?a:a===!0?ds:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}}));function ms(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=ma(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(qi(t,``))}let o=!1,s=null;if(e.contents){if(qr(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(qi(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=_a(e.contents,i,()=>s=null,t);s&&(c+=Yi(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(_a(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
88
+ `)?(n.push(`...`),n.push(qi(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(qi(a(t),``)))}return n.join(`
89
89
  `)+`
90
- `}var ms=I((()=>{oi(),_a(),Yi()}));function hs(e){if(Wr(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var gs,_s=I((()=>{Fi(),Gi(),oi(),Pa(),Ai(),fs(),ms(),Ei(),Oi(),Vi(),xi(),gs=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Qr,{value:qr});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 bi({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[Qr]:{value:qr}});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=Gr(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){hs(this.contents)&&this.contents.add(e)}addIn(e,t){hs(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=Ci(this);e.anchor=!t||n.has(t)?wi(t||`a`,n):t}return new Pi(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}=Ti(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=zi(e,l,p);return o&&Wr(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 Na(r,i)}delete(e){return hs(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ui(e)?this.contents!=null&&(this.contents=null,!0):hs(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return Wr(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Ui(e)?!t&&ri(this.contents)?this.contents.value:this.contents:Wr(this.contents)?this.contents.getIn(e,t):void 0}has(e){return Wr(this.contents)?this.contents.has(e):!1}hasIn(e){return Ui(e)?this.contents!==void 0:Wr(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Hi(this.schema,[e],t):hs(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ui(e)?this.contents=t:this.contents==null?this.contents=Hi(this.schema,Array.from(e),t):hs(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 bi({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 bi({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 ds(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=ki(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`?Di(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 ps(this,e)}}})),vs,ys,bs,xs,Ss=I((()=>{vs=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},ys=class extends vs{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},bs=class extends vs{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},xs=(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 Cs(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 ws=I((()=>{}));function Ts(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(Ts(t.key)||Ts(t.value))return!0}return!1;default:return!0}}var Es=I((()=>{}));function Ds(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&Ts(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}var Os=I((()=>{Es()}));function ks(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||ri(e)&&ri(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var As=I((()=>{oi()}));function js({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??Va)(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=Cs(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`,Ms)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
93
- `+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||Ts(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`,Ms);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&Ds(r.indent,u,i),n.atKey=!1,ks(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=Cs(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&&Ds(r.indent,f,i),s=c.range[2];let l=new Na(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 Na(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 Ms,Ns=I((()=>{Pa(),Ha(),ws(),Es(),Os(),As(),Ms=`All mapping items must start at the same column`}));function Ps({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??Ka)(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=Cs(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&&Ds(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}var Fs=I((()=>{qa(),ws(),Os()}));function Is(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 Ls=I((()=>{}));function Rs({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?Va:Ka))(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=Cs(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&&Ts(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];ni(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],Bs(m)&&i(r.range,`BLOCK_IN_FLOW`,zs)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);Bs(f)&&i(g.range,`BLOCK_IN_FLOW`,zs),n.atKey=!1;let _=Cs(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?Bs(m)&&i(v.range,`BLOCK_IN_FLOW`,zs):_.comment&&(g.comment?g.comment+=`
97
- `+_.comment:g.comment=_.comment);let y=new Na(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;ks(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new Va(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=Is(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 zs,Bs,Vs=I((()=>{oi(),Pa(),Ha(),qa(),Ls(),ws(),Es(),As(),zs=`Block collections are not allowed within flow collections`,Bs=e=>e&&(e.type===`block-map`||e.type===`block-seq`)}));function Hs(e,t,n,r,i,a){let o=n.type===`block-map`?js(e,t,n,r,a):n.type===`block-seq`?Ps(e,t,n,r,a):Rs(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function Us(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===Va.tagName&&s===`map`||o===Ka.tagName&&s===`seq`)return Hs(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),Hs(e,t,n,i,o)}let l=Hs(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=Gr(u)?u:new R(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}var Ws=I((()=>{oi(),Li(),Ha(),qa(),Ns(),Fs(),Vs()}));function Gs(e,t,n){let r=t.offset,i=Ks(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?qs(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 hs=F((()=>{L(),va(),Xi()}));function gs(e){if(Kr(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var _s,vs=F((()=>{Ii(),Ki(),L(),Fa(),ji(),ps(),hs(),Di(),ki(),Hi(),Si(),_s=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ei,{value:Yr});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 xi({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[ei]:{value:Yr}});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=qr(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){gs(this.contents)&&this.contents.add(e)}addIn(e,t){gs(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=wi(this);e.anchor=!t||n.has(t)?Ti(t||`a`,n):t}return new Fi(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}=Ei(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=Bi(e,l,p);return o&&Kr(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 Pa(r,i)}delete(e){return gs(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Wi(e)?this.contents!=null&&(this.contents=null,!0):gs(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return Kr(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Wi(e)?!t&&ai(this.contents)?this.contents.value:this.contents:Kr(this.contents)?this.contents.getIn(e,t):void 0}has(e){return Kr(this.contents)?this.contents.has(e):!1}hasIn(e){return Wi(e)?this.contents!==void 0:Kr(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ui(this.schema,[e],t):gs(this.contents)&&this.contents.set(e,t)}setIn(e,t){Wi(e)?this.contents=t:this.contents==null?this.contents=Ui(this.schema,Array.from(e),t):gs(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 xi({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 xi({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 fs(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=Ai(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`?Oi(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 ms(this,e)}}})),ys,bs,xs,Ss,Cs=F((()=>{ys=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},bs=class extends ys{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},xs=class extends ys{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},Ss=(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 ws(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 Ts=F((()=>{}));function Es(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(Es(t.key)||Es(t.value))return!0}return!1;default:return!0}}var Ds=F((()=>{}));function Os(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&Es(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}var ks=F((()=>{Ds()}));function As(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||ai(e)&&ai(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var js=F((()=>{L()}));function Ms({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??Ha)(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=ws(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`,Ns)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
93
+ `+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||Es(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`,Ns);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&Os(r.indent,u,i),n.atKey=!1,As(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=ws(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&&Os(r.indent,f,i),s=c.range[2];let l=new Pa(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 Pa(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 Ns,Ps=F((()=>{Fa(),Ua(),Ts(),Ds(),ks(),js(),Ns=`All mapping items must start at the same column`}));function Fs({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??qa)(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=ws(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&&Os(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}var Is=F((()=>{Ja(),Ts(),ks()}));function Ls(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 Rs=F((()=>{}));function zs({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?Ha:qa))(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=ws(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&&Es(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];ii(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],Vs(m)&&i(r.range,`BLOCK_IN_FLOW`,Bs)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);Vs(f)&&i(g.range,`BLOCK_IN_FLOW`,Bs),n.atKey=!1;let _=ws(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?Vs(m)&&i(v.range,`BLOCK_IN_FLOW`,Bs):_.comment&&(g.comment?g.comment+=`
97
+ `+_.comment:g.comment=_.comment);let y=new Pa(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;As(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new Ha(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=Ls(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 Bs,Vs,Hs=F((()=>{L(),Fa(),Ua(),Ja(),Rs(),Ts(),Ds(),js(),Bs=`Block collections are not allowed within flow collections`,Vs=e=>e&&(e.type===`block-map`||e.type===`block-seq`)}));function Us(e,t,n,r,i,a){let o=n.type===`block-map`?Ms(e,t,n,r,a):n.type===`block-seq`?Fs(e,t,n,r,a):zs(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function Ws(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===Ha.tagName&&s===`map`||o===qa.tagName&&s===`seq`)return Us(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),Us(e,t,n,i,o)}let l=Us(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=qr(u)?u:new R(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}var Gs=F((()=>{L(),Ri(),Ua(),Ja(),Ps(),Is(),Hs()}));function Ks(e,t,n){let r=t.offset,i=qs(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?Js(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,146 +110,148 @@ $&`).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 Ks({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 qs(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 Js=I((()=>{Li()}));function Ys(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=Xs(a,l);break;case`single-quoted-scalar`:s=R.QUOTE_SINGLE,c=Zs(a,l);break;case`double-quoted-scalar`:s=R.QUOTE_DOUBLE,c=$s(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=Is(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Xs(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 Zs(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 qs({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 Js(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 Ys=F((()=>{Ri()}));function Xs(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=Zs(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=ec(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=Ls(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Zs(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}`),$s(e)}function Qs(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),$s(e.slice(1,-1)).replace(/''/g,`'`)}function $s(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 $s(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 ec(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}=ec(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=nc[i];if(a)n+=a;else if(i===`
119
+ `){let{fold:t,offset:i}=tc(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=rc[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+=tc(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+=nc(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 ec(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 tc(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 tc(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 nc,rc=I((()=>{Li(),Ls(),nc={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
128
- `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `}}));function ic(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?Gs(e,t,r):Ys(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[Xr]:c?ac(e.schema,i,c,n,r):t.type===`scalar`?oc(e,i,t,r):e.schema[Xr];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=ri(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 ac(e,t,n,r,i){if(n===`!`)return e[Xr];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[Xr])}function oc({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[Xr];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[Xr];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 sc=I((()=>{oi(),Li(),Js(),rc()}));function cc(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 lc=I((()=>{}));function uc(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=fc(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=ic(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=Us(pc,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??=dc(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&&(!ri(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 dc(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=ic(e,{type:`scalar`,offset:cc(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 fc({options:e},{offset:t,source:n,end:r},i){let a=new Pi(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=Is(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}var pc,mc=I((()=>{Fi(),oi(),Ws(),sc(),Ls(),lc(),pc={composeNode:uc,composeEmptyNode:dc}}));function hc(e,t,{offset:n,start:r,value:i,end:a},o){let s=Object.assign({_directives:t},e),c=new gs(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Cs(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?uc(l,i,u,o):dc(l,u.end,r,null,u,o);let d=c.contents.range[2],f=Is(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,d,f.offset],c}var gc=I((()=>{_s(),mc(),Ls(),ws()}));function _c(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 vc(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 nc(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 rc,ic=F((()=>{Ri(),Rs(),rc={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
128
+ `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `}}));function ac(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?Ks(e,t,r):Xs(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?oc(e.schema,i,c,n,r):t.type===`scalar`?sc(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=ai(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 oc(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 sc({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 cc=F((()=>{L(),Ri(),Ys(),ic()}));function lc(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 uc=F((()=>{}));function dc(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=pc(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=ac(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=Ws(mc,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??=fc(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&&(!ai(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 fc(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=ac(e,{type:`scalar`,offset:lc(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 pc({options:e},{offset:t,source:n,end:r},i){let a=new Fi(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=Ls(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}var mc,hc=F((()=>{Ii(),L(),Gs(),cc(),Rs(),uc(),mc={composeNode:dc,composeEmptyNode:fc}}));function gc(e,t,{offset:n,start:r,value:i,end:a},o){let s=Object.assign({_directives:t},e),c=new _s(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=ws(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?dc(l,i,u,o):fc(l,u.end,r,null,u,o);let d=c.contents.range[2],f=Ls(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,d,f.offset],c}var _c=F((()=>{vs(),hc(),Rs(),Ts()}));function vc(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 yc(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 yc,bc=I((()=>{xi(),_s(),Ss(),oi(),gc(),Ls(),yc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=_c(e);r?this.warnings.push(new bs(i,t,n)):this.errors.push(new ys(i,t,n))},this.directives=new bi({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=vc(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(Wr(i)&&!i.flow&&i.items.length>0){let e=i.items[0];ni(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:vc(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=_c(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=hc(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 ys(_c(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 ys(_c(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=Is(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 ys(_c(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 gs(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 xc(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 ys([i,i+1],t,r)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return Ys(e,t,r);case`block-scalar`:return Gs({options:{strict:t}},e,r)}}return null}function Sc(e,t){let{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:a=-1,type:o=`PLAIN`}=t,s=ca({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 bc,xc=F((()=>{Si(),vs(),Cs(),L(),_c(),Rs(),bc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=vc(e);r?this.warnings.push(new xs(i,t,n)):this.errors.push(new bs(i,t,n))},this.directives=new xi({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=yc(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(Kr(i)&&!i.flow&&i.items.length>0){let e=i.items[0];ii(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:yc(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=vc(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=gc(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 bs(vc(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 bs(vc(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=Ls(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 bs(vc(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 _s(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 Sc(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 bs([i,i+1],t,r)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return Xs(e,t,r);case`block-scalar`:return Ks({options:{strict:t}},e,r)}}return null}function Cc(e,t){let{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:a=-1,type:o=`PLAIN`}=t,s=la({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 Tc(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 Cc(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=ca({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`>`:wc(e,c);break;case`"`:Ec(e,c,`double-quoted-scalar`);break;case`'`:Ec(e,c,`single-quoted-scalar`);break;default:Ec(e,c,`scalar`)}}function wc(e,t){let n=t.indexOf(`
134
+ `,i=[{type:`block-scalar-header`,offset:a,indent:r,source:t}];return Ec(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 wc(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=la({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`>`:Tc(e,c);break;case`"`:Dc(e,c,`double-quoted-scalar`);break;case`'`:Dc(e,c,`single-quoted-scalar`);break;default:Dc(e,c,`scalar`)}}function Tc(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}];Tc(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 Tc(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 Ec(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 Dc=I((()=>{Js(),rc(),Ss(),fa()}));function Oc(e){switch(e.type){case`block-scalar`:{let t=``;for(let n of e.props)t+=Oc(n);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=kc(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=kc(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=kc(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 kc({start:e,key:t,sep:n,value:r}){let i=``;for(let t of e)i+=t.source;if(t&&(i+=Oc(t)),n)for(let e of n)i+=e.source;return r&&(i+=Oc(r)),i}var Ac,jc=I((()=>{Ac=e=>`type`in e?Oc(e):kc(e)}));function Mc(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),Nc(Object.freeze([]),e,t)}function Nc(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=Nc(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===Pc)return Pc;else r===Ic&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}var Pc,Fc,Ic,Lc=I((()=>{Pc=Symbol(`break visit`),Fc=Symbol(`skip children`),Ic=Symbol(`remove item`),Mc.BREAK=Pc,Mc.SKIP=Fc,Mc.REMOVE=Ic,Mc.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},Mc.parentCollection=(e,t)=>{let n=Mc.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`)}})),Rc=tt({BOM:()=>``,DOCUMENT:()=>``,FLOW_END:()=>``,SCALAR:()=>``,createScalarToken:()=>Sc,isCollection:()=>Vc,isScalar:()=>Hc,prettyToken:()=>zc,resolveAsScalar:()=>xc,setScalarValue:()=>Cc,stringify:()=>Ac,tokenType:()=>Bc,visit:()=>Mc});function zc(e){switch(e){case``:return`<BOM>`;case``:return`<DOC>`;case``:return`<FLOW_END>`;case``:return`<SCALAR>`;default:return JSON.stringify(e)}}function Bc(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}];Ec(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 Ec(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 Dc(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 Oc=F((()=>{Ys(),ic(),Cs(),pa()}));function kc(e){switch(e.type){case`block-scalar`:{let t=``;for(let n of e.props)t+=kc(n);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=Ac(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=Ac(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=Ac(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 Ac({start:e,key:t,sep:n,value:r}){let i=``;for(let t of e)i+=t.source;if(t&&(i+=kc(t)),n)for(let e of n)i+=e.source;return r&&(i+=kc(r)),i}var jc,Mc=F((()=>{jc=e=>`type`in e?kc(e):Ac(e)}));function Nc(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),Pc(Object.freeze([]),e,t)}function Pc(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=Pc(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===Fc)return Fc;else r===Lc&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}var Fc,Ic,Lc,Rc=F((()=>{Fc=Symbol(`break visit`),Ic=Symbol(`skip children`),Lc=Symbol(`remove item`),Nc.BREAK=Fc,Nc.SKIP=Ic,Nc.REMOVE=Lc,Nc.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},Nc.parentCollection=(e,t)=>{let n=Nc.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`)}})),zc=rt({BOM:()=>``,DOCUMENT:()=>``,FLOW_END:()=>``,SCALAR:()=>``,createScalarToken:()=>Cc,isCollection:()=>Hc,isScalar:()=>Uc,prettyToken:()=>Bc,resolveAsScalar:()=>Sc,setScalarValue:()=>wc,stringify:()=>jc,tokenType:()=>Vc,visit:()=>Nc});function Bc(e){switch(e){case``:return`<BOM>`;case``:return`<DOC>`;case``:return`<FLOW_END>`;case``:return`<SCALAR>`;default:return JSON.stringify(e)}}function Vc(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 Vc,Hc,Uc=I((()=>{Dc(),jc(),Lc(),Vc=e=>!!e&&`items`in e,Hc=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`)}));function Wc(e){switch(e){case void 0:case` `:case`
142
- `:case`\r`:case` `:return!0;default:return!1}}var Gc,Kc,qc,Jc,Yc,Xc,Zc=I((()=>{Uc(),Gc=new Set(`0123456789ABCDEFabcdef`),Kc=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),qc=new Set(`,[]{}`),Jc=new Set(` ,[]{}
143
- \r `),Yc=e=>!e||Jc.has(e),Xc=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 Hc,Uc,Wc=F((()=>{Oc(),Mc(),Rc(),Hc=e=>!!e&&`items`in e,Uc=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`)}));function Gc(e){switch(e){case void 0:case` `:case`
142
+ `:case`\r`:case` `:return!0;default:return!1}}var Kc,qc,Jc,Yc,Xc,Zc,Qc=F((()=>{Wc(),Kc=new Set(`0123456789ABCDEFabcdef`),qc=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),Jc=new Set(`,[]{}`),Yc=new Set(` ,[]{}
143
+ \r `),Xc=e=>!e||Yc.has(e),Zc=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===`...`)&&Wc(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===`...`)&&Wc(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&&!Wc(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===`:`)&&Wc(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(Yc),`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(`...`))&&Wc(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(Yc),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||Wc(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===`...`)&&Gc(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===`...`)&&Gc(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&&!Gc(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===`:`)&&Gc(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(Xc),`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(`...`))&&Gc(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(Xc),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||Gc(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=>Wc(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=>Gc(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(Wc(r)||e&&qc.has(r))break;t=n}else if(Wc(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(Gc(r)||e&&Jc.has(r))break;t=n}else if(Gc(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&&qc.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&&qc.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(Yc),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(Wc(n)||t&&qc.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(;!Wc(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(Kc.has(t))t=this.buffer[++e];else if(t===`%`&&Gc.has(this.buffer[e+1])&&Gc.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&&Jc.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&&Jc.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(Xc),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(Gc(n)||t&&Jc.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(;!Gc(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(qc.has(t))t=this.buffer[++e];else if(t===`%`&&Kc.has(this.buffer[e+1])&&Kc.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,$c=I((()=>{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 el(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function tl(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 nl(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 rl(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 il(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 al(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 ol(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!el(t.start,`explicit-key-ind`)&&!el(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,nl(t.value)?t.value.end?al(t.value.end,t.sep):t.value.end=t.sep:al(t.start,t.sep),delete t.sep)}var sl,cl=I((()=>{Uc(),Zc(),sl=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 Xc,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=Bc(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`&&ol(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&&tl(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`:tl(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=il(rl(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)}}})),$c,el=F((()=>{$c=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 tl(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function nl(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 rl(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 il(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 al(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 ol(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 sl(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!tl(t.start,`explicit-key-ind`)&&!tl(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,rl(t.value)?t.value.end?ol(t.value.end,t.sep):t.value.end=t.sep:ol(t.start,t.sep),delete t.sep)}var cl,ll=F((()=>{Wc(),Qc(),cl=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 Zc,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=Vc(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`&&sl(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&&nl(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`:nl(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=al(il(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)){al(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(el(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=il(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(el(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(nl(t.key)&&!el(t.sep,`newline`)){let e=il(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]}):el(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&&!el(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)){al(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||el(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=il(rl(t));ol(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)){ol(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(tl(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=al(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(tl(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(rl(t.key)&&!tl(t.sep,`newline`)){let e=al(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]}):tl(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&&!tl(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)){ol(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||tl(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=al(il(t));sl(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=il(rl(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=il(rl(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 ll(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Qc||null,prettyErrors:t}}function ul(e,t={}){let{lineCounter:n,prettyErrors:r}=ll(t),i=new sl(n?.addNewLine),a=new yc(t),o=Array.from(a.compose(i.parse(e)));if(r&&n)for(let t of o)t.errors.forEach(xs(e,n)),t.warnings.forEach(xs(e,n));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function dl(e,t={}){let{lineCounter:n,prettyErrors:r}=ll(t),i=new sl(n?.addNewLine),a=new yc(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 ys(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(xs(e,n)),o.warnings.forEach(xs(e,n))),o}function fl(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let i=dl(e,n);if(!i)return null;if(i.warnings.forEach(e=>ba(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 pl(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 ei(e)&&!r?e.toString(n):new gs(e,r,n).toString(n)}var ml=I((()=>{bc(),_s(),Ss(),xa(),oi(),$c(),cl()})),hl=tt({Alias:()=>Pi,CST:()=>Rc,Composer:()=>yc,Document:()=>gs,Lexer:()=>Xc,LineCounter:()=>Qc,Pair:()=>Na,Parser:()=>sl,Scalar:()=>R,Schema:()=>ds,YAMLError:()=>vs,YAMLMap:()=>Va,YAMLParseError:()=>ys,YAMLSeq:()=>Ka,YAMLWarning:()=>bs,isAlias:()=>$r,isCollection:()=>Wr,isDocument:()=>ei,isMap:()=>ti,isNode:()=>Gr,isPair:()=>ni,isScalar:()=>ri,isSeq:()=>ii,parse:()=>fl,parseAllDocuments:()=>ul,parseDocument:()=>dl,stringify:()=>pl,visit:()=>si,visitAsync:()=>li}),gl=I((()=>{bc(),_s(),fs(),Ss(),Fi(),oi(),Pa(),Li(),Ha(),qa(),Uc(),Zc(),$c(),cl(),ml(),_i()})),_l=tt({Alias:()=>Pi,CST:()=>Rc,Composer:()=>yc,Document:()=>gs,Lexer:()=>Xc,LineCounter:()=>Qc,Pair:()=>Na,Parser:()=>sl,Scalar:()=>R,Schema:()=>ds,YAMLError:()=>vs,YAMLMap:()=>Va,YAMLParseError:()=>ys,YAMLSeq:()=>Ka,YAMLWarning:()=>bs,default:()=>vl,isAlias:()=>$r,isCollection:()=>Wr,isDocument:()=>ei,isMap:()=>ti,isNode:()=>Gr,isPair:()=>ni,isScalar:()=>ri,isSeq:()=>ii,parse:()=>fl,parseAllDocuments:()=>ul,parseDocument:()=>dl,stringify:()=>pl,visit:()=>si,visitAsync:()=>li}),vl,yl=I((()=>{gl(),gl(),vl=hl}));async function bl(){return Sl??=await Promise.resolve().then(()=>(yl(),_l)),Sl}function xl(){return Sl??=s(import.meta.url)(`yaml`),Sl}var Sl,Cl=I((()=>{}));function wl(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 Vr(e,2)}return t===`yaml`?xl().stringify(e):t===`md`?jl(e):t===`jsonl`?Array.isArray(e)?e.map(e=>Vr(e)).join(`
165
- `):Vr(e):Tl(e)?String(e):Mr(e)}function Tl(e){return typeof e!=`object`||!e}function El(e){return Object.values(e).every(Tl)}function Dl(e){return Array.isArray(e)&&e.length>0&&e.every(e=>typeof e==`object`&&!!e&&!Array.isArray(e))}function Ol(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 kl(e){return Ol([`Key`,`Value`],Object.entries(e).map(([e,t])=>[e,String(t)]))}function Al(e){let t=[...new Set(e.flatMap(Object.keys))];return Ol(t,e.map(e=>t.map(t=>String(e[t]??``))))}function jl(e,t=[]){if(Tl(e))return t.length===0?String(e):`## ${t.join(`.`)}\n\n${String(e)}`;if(Array.isArray(e)){if(Dl(e)){let n=Al(e);return t.length===0?n:`## ${t.join(`.`)}\n\n${n}`}return jl(String(e),t)}let n=e,r=Object.entries(n);return t.length===0&&El(n)?kl(n):t.length>0||r.length>1||r.some(([,e])=>!Tl(e))?r.map(([e,n])=>{let r=[...t,e];if(Tl(n))return`## ${r.join(`.`)}\n\n${String(n)}`;if(Dl(n))return`## ${r.join(`.`)}\n\n${Al(n)}`;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=n;return El(e)?`## ${r.join(`.`)}\n\n${kl(e)}`:jl(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=al(il(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=al(il(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 ul(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new $c||null,prettyErrors:t}}function dl(e,t={}){let{lineCounter:n,prettyErrors:r}=ul(t),i=new cl(n?.addNewLine),a=new bc(t),o=Array.from(a.compose(i.parse(e)));if(r&&n)for(let t of o)t.errors.forEach(Ss(e,n)),t.warnings.forEach(Ss(e,n));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function fl(e,t={}){let{lineCounter:n,prettyErrors:r}=ul(t),i=new cl(n?.addNewLine),a=new bc(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 bs(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(Ss(e,n)),o.warnings.forEach(Ss(e,n))),o}function pl(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let i=fl(e,n);if(!i)return null;if(i.warnings.forEach(e=>xa(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 ml(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 ni(e)&&!r?e.toString(n):new _s(e,r,n).toString(n)}var hl=F((()=>{xc(),vs(),Cs(),Sa(),L(),el(),ll()})),gl=rt({Alias:()=>Fi,CST:()=>zc,Composer:()=>bc,Document:()=>_s,Lexer:()=>Zc,LineCounter:()=>$c,Pair:()=>Pa,Parser:()=>cl,Scalar:()=>R,Schema:()=>fs,YAMLError:()=>ys,YAMLMap:()=>Ha,YAMLParseError:()=>bs,YAMLSeq:()=>qa,YAMLWarning:()=>xs,isAlias:()=>ti,isCollection:()=>Kr,isDocument:()=>ni,isMap:()=>ri,isNode:()=>qr,isPair:()=>ii,isScalar:()=>ai,isSeq:()=>oi,parse:()=>pl,parseAllDocuments:()=>dl,parseDocument:()=>fl,stringify:()=>ml,visit:()=>ci,visitAsync:()=>ui}),_l=F((()=>{xc(),vs(),ps(),Cs(),Ii(),L(),Fa(),Ri(),Ua(),Ja(),Wc(),Qc(),el(),ll(),hl(),vi()})),vl=rt({Alias:()=>Fi,CST:()=>zc,Composer:()=>bc,Document:()=>_s,Lexer:()=>Zc,LineCounter:()=>$c,Pair:()=>Pa,Parser:()=>cl,Scalar:()=>R,Schema:()=>fs,YAMLError:()=>ys,YAMLMap:()=>Ha,YAMLParseError:()=>bs,YAMLSeq:()=>qa,YAMLWarning:()=>xs,default:()=>yl,isAlias:()=>ti,isCollection:()=>Kr,isDocument:()=>ni,isMap:()=>ri,isNode:()=>qr,isPair:()=>ii,isScalar:()=>ai,isSeq:()=>oi,parse:()=>pl,parseAllDocuments:()=>dl,parseDocument:()=>fl,stringify:()=>ml,visit:()=>ci,visitAsync:()=>ui}),yl,bl=F((()=>{_l(),_l(),yl=gl}));async function xl(){return Cl??=await Promise.resolve().then(()=>(bl(),vl)),Cl}function Sl(){return Cl??=s(import.meta.url)(`yaml`),Cl}var Cl,wl=F((()=>{}));function Tl(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 Ur(e,2)}return t===`yaml`?Sl().stringify(e):t===`md`?Ml(e):t===`jsonl`?Array.isArray(e)?e.map(e=>Ur(e)).join(`
165
+ `):Ur(e):El(e)?String(e):Pr(e)}function El(e){return typeof e!=`object`||!e}function Dl(e){return Object.values(e).every(El)}function Ol(e){return Array.isArray(e)&&e.length>0&&e.every(e=>typeof e==`object`&&!!e&&!Array.isArray(e))}function kl(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 Al(e){return kl([`Key`,`Value`],Object.entries(e).map(([e,t])=>[e,String(t)]))}function jl(e){let t=[...new Set(e.flatMap(Object.keys))];return kl(t,e.map(e=>t.map(t=>String(e[t]??``))))}function Ml(e,t=[]){if(El(e))return t.length===0?String(e):`## ${t.join(`.`)}\n\n${String(e)}`;if(Array.isArray(e)){if(Ol(e)){let n=jl(e);return t.length===0?n:`## ${t.join(`.`)}\n\n${n}`}return Ml(String(e),t)}let n=e,r=Object.entries(n);return t.length===0&&Dl(n)?Al(n):t.length>0||r.length>1||r.some(([,e])=>!El(e))?r.map(([e,n])=>{let r=[...t,e];if(El(n))return`## ${r.join(`.`)}\n\n${String(n)}`;if(Ol(n))return`## ${r.join(`.`)}\n\n${jl(n)}`;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=n;return Dl(e)?`## ${r.join(`.`)}\n\n${Al(e)}`:Ml(e,r)}return`## ${r.join(`.`)}\n\n${String(n)}`}).join(`
167
167
 
168
- `):kl(n)}var Ml=I((()=>{Br(),Ur(),Cl()}));function Nl(e,t={}){let{args:n,options:r,alias:i,defaults:a}=t,o=Pl(r,i),s=[],c={},l=0;for(;l<e.length;){let t=e[l];if(t.startsWith(`--no-`)&&t.length>5){let e=Fl(t.slice(5),o);if(!e)throw new kn({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=Fl(e,o);if(!i)throw new kn({message:`Unknown flag: --${e}`});Vl(c,i,t.slice(n+1),r),l++}else{let n=Fl(t.slice(2),o);if(!n)throw new kn({message:`Unknown flag: ${t}`});if(zl(n,r))c[n]=(c[n]??0)+1,l++;else if(Rl(n,r))c[n]=!0,l++;else{let i=e[l+1];if(i===void 0)throw new kn({message:`Missing value for flag: ${t}`});Vl(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 kn({message:`Unknown flag: -${i}`});if(t!==n.length-1){if(zl(a,r))c[a]=(c[a]??0)+1;else if(Rl(a,r))c[a]=!0;else throw new kn({message:`Non-boolean flag -${i} must be last in a stacked alias`})}else if(zl(a,r))c[a]=(c[a]??0)+1;else if(Rl(a,r))c[a]=!0;else{let t=e[l+1];if(t===void 0)throw new kn({message:`Missing value for flag: -${i}`});Vl(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(Bl(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?Hl(n,u):{},f=Il(a,r,o);if(r)for(let[e,t]of Object.entries(c))c[e]=Kl(t,e,r);let p={...f,...c};return{args:d,options:r?Hl(r,p):{}}}function Pl(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=cn(e);t!==e&&i.set(t,e)}return{aliasToName:n,kebabToCamel:i,knownOptions:r}}function Fl(e,t){let n=t.kebabToCamel.get(e)??e;return t.knownOptions.has(n)?n:void 0}function Il(e,t,n){if(e===void 0)return{};if(!sn(e))throw new kn({message:`Invalid config section: expected an object of option defaults`});if(!t){let[t]=Object.keys(e);if(t)throw new kn({message:`Unknown config option: ${t}`});return{}}let r={};for(let[t,i]of Object.entries(e)){let e=Fl(t,n);if(!e)throw new kn({message:`Unknown config option: ${t}`});r[e]=i}return r}function Ll(e){let t=e;for(;t.def?.innerType;)t=t.def.innerType;return t}function Rl(e,t){if(!t)return!1;let n=t.shape[e];return n?Ll(n).constructor.name===`ZodBoolean`:!1}function zl(e,t){if(!t)return!1;let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0:!1}function Bl(e,t){if(!t)return!1;let n=t.shape[e];return n?Ll(n).constructor.name===`ZodArray`:!1}function Vl(e,t,n,r){if(Bl(t,r)){let r=e[t];Array.isArray(r)?r.push(n):e[t]=[n]}else e[t]=n}function Hl(e,t){try{return e.parse(t)}catch(e){let n=e?.issues??e?.error?.issues??[],r=n.map(e=>({code:e.code,missing:!Ul(t,e.path??[]),path:(e.path??[]).join(`.`),expected:e.expected??``,received:e.received??``,message:e.message??``}));throw new On({message:n.map(e=>e.message).join(`; `)||`Validation failed`,fieldErrors:r,cause:e instanceof Error?e:void 0})}}function Ul(e,t){if(t.length===0)return!0;let n=e;for(let e of t){if(!sn(n)&&!Array.isArray(n)||!(e in n))return!1;n=n[e]}return!0}function Wl(e,t=Jl()){let n={};for(let[r,i]of Object.entries(e.shape)){let e=t[r];e!==void 0&&(n[r]=Gl(e,i))}return Hl(e,n)}function Gl(e,t){let n=Ll(t).constructor.name;return n===`ZodNumber`?Number(e):n===`ZodBoolean`?e===`true`||e===`1`:e}function Kl(e,t,n){let r=n.shape[t];if(!r)return e;let i=Ll(r).constructor.name;return i===`ZodNumber`&&typeof e==`string`?Number(e):i===`ZodBoolean`&&typeof e==`string`?e===`true`:e}function ql(e,t,n,r={}){let i=Pl(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=Fl(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=Fl(n.slice(2,r),i);e?Vl(o,e,n.slice(r+1),t):a.push(n),s++}else{let r=Fl(n.slice(2),i);if(!r)a.push(n),s++;else if(zl(r,t))o[r]=(o[r]??0)+1,s++;else if(Rl(r,t))o[r]=!0,s++;else{let i=e[s+1];if(i===void 0)throw new kn({message:`Missing value for flag: ${n}`});Vl(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(zl(c,t))o[c]=(o[c]??0)+1;else if(Rl(c,t))o[c]=!0;else throw new kn({message:`Non-boolean flag -${a} must be last in a stacked alias`})}else if(zl(c,t))o[c]=(o[c]??0)+1;else if(Rl(c,t))o[c]=!0;else{let n=e[s+1];if(n===void 0)throw new kn({message:`Missing value for flag: -${a}`});Vl(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]=Kl(n,e,t);return{parsed:Hl(t,o),rest:a}}function Jl(){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 Yl=I((()=>{An(),dn()}));async function Xl(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=Nl(n,{alias:e.alias,args:e.args,defaults:t.defaults,options:e.options});c=r.args,d=r.options}else if(_===`split`)c=Nl(n,{args:e.args}).args,d=e.options?Hl(e.options,r):{};else{let t=Zl(r,e);c=e.args?Hl(e.args,t.args):{},d=e.options?Hl(e.options,t.options):{}}let p=e.env?Wl(e.env,u):{},C=e.run({agent:i,args:c,displayName:g,env:p,error:e=>({[ru]:`error`,...e}),format:a,formatExplicit:o,globals:f,name:s,ok:(e,t={})=>({[ru]:`ok`,data:e,cta:t.cta}),options:d,request:h,var:v,version:l});if($l(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[ru]===`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?Wl(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 On?{ok:!1,error:{code:`VALIDATION_ERROR`,message:e.message,fieldErrors:e.fieldErrors}}:{ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof L?{retryable:e.retryable}:void 0},...e instanceof L&&e.exitCode!==void 0?{exitCode:e.exitCode}:void 0}}return y??{ok:!0,data:void 0}}function Zl(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&&ru in e}function $l(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e&&typeof e.next==`function`}function eu(e){return e}function tu(e){return au.find(t=>t.name===e||t.aliases?.includes(e))}function nu(e,t){return e.subcommands?.find(e=>e.name===t||e.aliases?.includes(t))}var ru,iu,au,ou=I((()=>{An(),Yl(),ru=Symbol.for(`incur.sentinel`),iu=[`bash`,`fish`,`nushell`,`zsh`],au=[{name:`completions`,description:`Generate shell completion script`,args:f.object({shell:f.enum(iu).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
+ `):Al(n)}var Nl=F((()=>{Hr(),Gr(),wl()}));function Pl(e,t={}){let{args:n,options:r,alias:i,defaults:a}=t,o=Fl(r,i),s=[],c={},l=0;for(;l<e.length;){let t=e[l];if(t.startsWith(`--no-`)&&t.length>5){let e=Il(t.slice(5),o);if(!e)throw new jn({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=Il(e,o);if(!i)throw new jn({message:`Unknown flag: --${e}`});Hl(c,i,t.slice(n+1),r),l++}else{let n=Il(t.slice(2),o);if(!n)throw new jn({message:`Unknown flag: ${t}`});if(Bl(n,r))c[n]=(c[n]??0)+1,l++;else if(zl(n,r))c[n]=!0,l++;else{let i=e[l+1];if(i===void 0)throw new jn({message:`Missing value for flag: ${t}`});Hl(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 jn({message:`Unknown flag: -${i}`});if(t!==n.length-1){if(Bl(a,r))c[a]=(c[a]??0)+1;else if(zl(a,r))c[a]=!0;else throw new jn({message:`Non-boolean flag -${i} must be last in a stacked alias`})}else if(Bl(a,r))c[a]=(c[a]??0)+1;else if(zl(a,r))c[a]=!0;else{let t=e[l+1];if(t===void 0)throw new jn({message:`Missing value for flag: -${i}`});Hl(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(Vl(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?Ul(n,u):{},f=Ll(a,r,o);if(r)for(let[e,t]of Object.entries(c))c[e]=ql(t,e,r);let p={...f,...c};return{args:d,options:r?Ul(r,p):{}}}function Fl(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=un(e);t!==e&&i.set(t,e)}return{aliasToName:n,kebabToCamel:i,knownOptions:r}}function Il(e,t){let n=t.kebabToCamel.get(e)??e;return t.knownOptions.has(n)?n:void 0}function Ll(e,t,n){if(e===void 0)return{};if(!ln(e))throw new jn({message:`Invalid config section: expected an object of option defaults`});if(!t){let[t]=Object.keys(e);if(t)throw new jn({message:`Unknown config option: ${t}`});return{}}let r={};for(let[t,i]of Object.entries(e)){let e=Il(t,n);if(!e)throw new jn({message:`Unknown config option: ${t}`});r[e]=i}return r}function Rl(e){let t=e;for(;t.def?.innerType;)t=t.def.innerType;return t}function zl(e,t){if(!t)return!1;let n=t.shape[e];return n?Rl(n).constructor.name===`ZodBoolean`:!1}function Bl(e,t){if(!t)return!1;let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0:!1}function Vl(e,t){if(!t)return!1;let n=t.shape[e];return n?Rl(n).constructor.name===`ZodArray`:!1}function Hl(e,t,n,r){if(Vl(t,r)){let r=e[t];Array.isArray(r)?r.push(n):e[t]=[n]}else e[t]=n}function Ul(e,t){try{return e.parse(t)}catch(e){let n=e?.issues??e?.error?.issues??[],r=n.map(e=>({code:e.code,missing:!Wl(t,e.path??[]),path:(e.path??[]).join(`.`),expected:e.expected??``,received:e.received??``,message:e.message??``}));throw new An({message:n.map(e=>e.message).join(`; `)||`Validation failed`,fieldErrors:r,cause:e instanceof Error?e:void 0})}}function Wl(e,t){if(t.length===0)return!0;let n=e;for(let e of t){if(!ln(n)&&!Array.isArray(n)||!(e in n))return!1;n=n[e]}return!0}function Gl(e,t=Yl()){let n={};for(let[r,i]of Object.entries(e.shape)){let e=t[r];e!==void 0&&(n[r]=Kl(e,i))}return Ul(e,n)}function Kl(e,t){let n=Rl(t).constructor.name;return n===`ZodNumber`?Number(e):n===`ZodBoolean`?e===`true`||e===`1`:e}function ql(e,t,n){let r=n.shape[t];if(!r)return e;let i=Rl(r).constructor.name;return i===`ZodNumber`&&typeof e==`string`?Number(e):i===`ZodBoolean`&&typeof e==`string`?e===`true`:e}function Jl(e,t,n,r={}){let i=Fl(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=Il(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=Il(n.slice(2,r),i);e?Hl(o,e,n.slice(r+1),t):a.push(n),s++}else{let r=Il(n.slice(2),i);if(!r)a.push(n),s++;else if(Bl(r,t))o[r]=(o[r]??0)+1,s++;else if(zl(r,t))o[r]=!0,s++;else{let i=e[s+1];if(i===void 0)throw new jn({message:`Missing value for flag: ${n}`});Hl(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(Bl(c,t))o[c]=(o[c]??0)+1;else if(zl(c,t))o[c]=!0;else throw new jn({message:`Non-boolean flag -${a} must be last in a stacked alias`})}else if(Bl(c,t))o[c]=(o[c]??0)+1;else if(zl(c,t))o[c]=!0;else{let n=e[s+1];if(n===void 0)throw new jn({message:`Missing value for flag: -${a}`});Hl(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]=ql(n,e,t);return{parsed:Ul(t,o),rest:a}}function Yl(){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 Xl=F((()=>{Mn(),pn()}));async function Zl(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=Pl(n,{alias:e.alias,args:e.args,defaults:t.defaults,options:e.options});c=r.args,d=r.options}else if(_===`split`)c=Pl(n,{args:e.args}).args,d=e.options?Ul(e.options,r):{};else{let t=Ql(r,e);c=e.args?Ul(e.args,t.args):{},d=e.options?Ul(e.options,t.options):{}}let p=e.env?Gl(e.env,u):{},C=e.run({agent:i,args:c,displayName:g,env:p,error:e=>({[iu]:`error`,...e}),format:a,formatExplicit:o,globals:f,name:s,ok:(e,t={})=>({[iu]:`ok`,data:e,cta:t.cta}),options:d,request:h,var:v,version:l});if(eu(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($l(w)){if(w[iu]===`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?Gl(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 An?{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 $l(e){return typeof e==`object`&&!!e&&iu in e}function eu(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e&&typeof e.next==`function`}function tu(e){return e}function nu(e){return ou.find(t=>t.name===e||t.aliases?.includes(e))}function ru(e,t){return e.subcommands?.find(e=>e.name===t||e.aliases?.includes(t))}var iu,au,ou,su=F((()=>{Mn(),Xl(),iu=Symbol.for(`incur.sentinel`),au=[`bash`,`fish`,`nushell`,`zsh`],ou=[{name:`completions`,description:`Generate shell completion script`,args:f.object({shell:f.enum(au).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:[eu({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`)})}),eu({name:`doctor`,description:`Validate MCP server startup and tool listing`})]},{name:`skills`,aliases:[`skill`],description:`Sync skill files to agents`,subcommands:[eu({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`)})}),eu({name:`list`,aliases:[`ls`],description:`List skills`})]}]}));function su(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(...vu(c,r,a)),l.join(`
171
- `)}function cu(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=lu(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=uu(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=fu(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(...vu(f,i,o)),l){let e=du(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??Jl();n.name in i&&r.push(`set: ${yu(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 lu(e,t){if(!t)return e;let n=[e];for(let[e,r]of Object.entries(t.shape)){let t=pu(r),i=(t.includes(`|`)?t:e)+(t===`array`?`...`:``);n.push(r._zod.optout===`optional`?`[${i}]`:`<${i}>`)}return n.join(` `)}function uu(e){let t=[];for(let[n,r]of Object.entries(e.shape))t.push({name:n,description:r.description??``});return t}function du(e){let t=[];for(let[n,r]of Object.entries(e.shape)){let e=gu(r);t.push({name:n,description:r.description??``,defaultValue:e})}return t}function fu(e,t){let n=[];for(let[r,i]of Object.entries(e.shape)){let e=pu(i),a=t?.[r],o=cn(r),s=e===`boolean`?``:` <${e}>`,c=a?`--${o}, -${a}${s}`:`--${o}${s}`,l=gu(i);e===`boolean`&&l===!1&&(l=void 0);let u=_u(i);n.push({flag:c,description:i.description??``,defaultValue:l,deprecated:u})}return n}function pu(e){if(mu(e))return`count`;let t=hu(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 mu(e){let t=e;return typeof t?.meta==`function`&&t.meta()?.count===!0}function hu(e){return e instanceof f.ZodOptional?hu(e.unwrap()):e instanceof f.ZodDefault?hu(e.removeDefault()):e instanceof f.ZodNullable?hu(e.unwrap()):e}function gu(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 gu(e.unwrap())}function _u(e){return e?.meta?.()?.deprecated===!0||void 0}function vu(e=!1,t,n){let r=[];if(e){let e=au.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=fu(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 yu(e){return e.length<=4?`****`:`****${e.slice(-4)}`}var bu=I((()=>{ou(),dn(),Yl()}));function xu(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=>Cu(e,t))}}function Su(e){let t=[e.description];for(let n of e.commands)t.push(` ${n.command}${n.description?` - ${n.description}`:``}`);return t.join(`
173
- `)}function Cu(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 wu=I((()=>{}));async function Tu(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()){Ou(o.name,a),await i(a,[...t,o.name]);continue}if(!o.isFile()||a===r)continue;let s=ku.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}Ou(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 Eu(){return globalThis[Symbol.for(ju)]?.shift()}async function Du(e){return Promise.all(e.map(async({load:e,...t})=>({...t,command:await e()})))}function Ou(e,t){if(!Au.test(e))throw Error(`Invalid filesystem command segment '${e}' from '${t}'. Use lowercase kebab-case names.`)}var ku,Au,ju,Mu=I((()=>{ku=[`.cts`,`.cjs`,`.mts`,`.mjs`,`.ts`,`.js`],Au=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,ju=`incur.fs.manifests`}));function Nu(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 Pu=I((()=>{}));function Fu(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(!Fu(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(!Fu(e[r],t[r]))return!1;return!0}return e===t}var Iu=I((()=>{}));function Lu(e){return encodeURI(Ru(e))}function Ru(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var zu=I((()=>{}));function Bu(e,t=Object.create(null),n=Wu,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:Bu(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(Uu[i])continue;let a=`${r}/${Lu(i)}`,o=e[i];if(Array.isArray(o)){if(Vu[i]){let e=o.length;for(let r=0;r<e;r++)Bu(o[r],t,n,`${a}/${r}`)}}else if(Hu[i])for(let e in o)Bu(o[e],t,n,`${a}/${Lu(e)}`);else Bu(o,t,n,a)}return t}var Vu,Hu,Uu,Wu,Gu=I((()=>{zu(),Vu={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Hu={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Uu={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},Wu=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 Ku(e){return e.test.bind(e)}function qu(e){return e%4==0&&(e%100!=0||e%400==0)}function Ju(e){let t=e.match($u);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&qu(n)?29:ed[r])}function Yu(e,t){let n=t.match(td);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 Xu(e){let t=e.split(hd);return t.length==2&&Ju(t[0])&&Yu(!0,t[1])}function Zu(e){return gd.test(e)&&_d.test(e)}function Qu(e){if(vd.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}var $u,ed,td,nd,rd,id,ad,od,sd,cd,ld,ud,dd,fd,pd,md,hd,gd,_d,vd,yd=I((()=>{$u=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ed=[0,31,28,31,30,31,30,31,31,30,31,30,31],td=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,nd=/^(?=.{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,rd=/^(?:[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,id=/^(?:(?:[^\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,ad=/^(?:(?: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,od=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,sd=/^(?:\/(?:[^~/]|~0|~1)*)*$/,cd=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,ld=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,ud=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))},dd=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,fd=/^((([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,pd=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)),md={date:Ju,time:Yu.bind(void 0,!1),"date-time":Xu,duration:pd,uri:Zu,"uri-reference":Ku(rd),"uri-template":Ku(id),url:Ku(ad),email:ud,hostname:Ku(nd),ipv4:Ku(dd),ipv6:Ku(fd),regex:Qu,uuid:Ku(od),"json-pointer":Ku(sd),"json-pointer-uri-fragment":Ku(cd),"relative-json-pointer":Ku(ld)},hd=/t|\s/i,gd=/\/|:/,_d=/^(?:[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,vd=/[^\\]\\Z/})),bd=I((()=>{}));function xd(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 Sd=I((()=>{}));function Cd(e,t,n=`2019-09`,r=Bu(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:C,else:w,format:T,properties:ee,patternProperties:te,additionalProperties:E,unevaluatedProperties:D,minProperties:O,maxProperties:k,propertyNames:ne,dependentRequired:A,dependentSchemas:j,dependencies:M,prefixItems:re,items:ie,additionalItems:ae,unevaluatedItems:oe,contains:se,minContains:N,maxContains:ce,minItems:le,maxItems:P,uniqueItems:ue,minimum:de,maximum:fe,exclusiveMinimum:pe,exclusiveMaximum:me,multipleOf:he,minLength:ge,maxLength:_e,pattern:ve,__absolute_ref__:ye,__absolute_recursive_ref__:be}=t,F=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[be]:a,u=`${s}/$recursiveRef`,d=Cd(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||F.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[ye||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw ye&&ye!==d&&(e+=` Absolute URI "${ye}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
174
- - `)}`,Error(e)}let l=`${s}/$ref`,u=Cd(e,t,n,r,i,a,o,l,c);if(u.valid||F.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:F.length===0,errors:F}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||F.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&F.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&F.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?Fu(e,h)||F.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&F.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>Fu(e,t))||F.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||F.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){let t=`${s}/not`;Cd(e,v,n,r,i,a,o,t).valid&&F.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let xe=[];if(y!==void 0){let t=`${s}/anyOf`,l=F.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=Cd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);F.push(...f.errors),u||=f.valid,f.valid&&xe.push(d)}u?F.length=l:F.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${s}/allOf`,l=F.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=Cd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);F.push(...f.errors),u&&=f.valid,f.valid&&xe.push(d)}u?F.length=l:F.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(x!==void 0){let t=`${s}/oneOf`,l=F.length,u=x.filter((s,l)=>{let u=Object.create(c),d=Cd(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return F.push(...d.errors),d.valid&&xe.push(u),d.valid}).length;u===1?F.length=l:F.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...xe),S!==void 0){let t=`${s}/if`;if(Cd(e,S,n,r,i,a,o,t,c).valid){if(C!==void 0){let l=Cd(e,C,n,r,i,a,o,`${s}/then`,c);l.valid||F.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(w!==void 0){let l=Cd(e,w,n,r,i,a,o,`${s}/else`,c);l.valid||F.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||F.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(O!==void 0&&t.length<O&&F.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${O} properties.`}),k!==void 0&&t.length>k&&F.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${k} properties.`}),ne!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${Lu(s)}`,c=Cd(s,ne,n,r,i,a,e,t);c.valid||F.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(A!==void 0){let t=`${s}/dependantRequired`;for(let n in A)if(n in e){let r=A[n];for(let i of r)i in e||F.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(j!==void 0)for(let t in j){let l=`${s}/dependentSchemas`;if(t in e){let s=Cd(e,j[t],n,r,i,a,o,`${l}/${Lu(t)}`,c);s.valid||F.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(M!==void 0){let t=`${s}/dependencies`;for(let s in M)if(s in e){let c=M[s];if(Array.isArray(c))for(let n of c)n in e||F.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=Cd(e,c,n,r,i,a,o,`${t}/${Lu(s)}`);l.valid||F.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(ee!==void 0){let t=`${s}/properties`;for(let s in ee){if(!(s in e))continue;let d=`${o}/${Lu(s)}`,f=Cd(e[s],ee[s],n,r,i,a,d,`${t}/${Lu(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,F.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&te!==void 0){let t=`${s}/patternProperties`;for(let s in te){let d=new RegExp(s,`u`),f=te[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${Lu(p)}`,h=Cd(e[p],f,n,r,i,a,m,`${t}/${Lu(s)}`);h.valid?c[p]=l[p]=!0:(u=i,F.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&E!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${Lu(s)}`,f=Cd(e[s],E,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,F.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&D!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${Lu(s)}`,u=Cd(e[s],D,n,r,i,a,l,t);u.valid?c[s]=!0:F.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){P!==void 0&&e.length>P&&F.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${P}).`}),le!==void 0&&e.length<le&&F.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${le}).`});let t=e.length,l=0,u=!1;if(re!==void 0){let d=`${s}/prefixItems`,f=Math.min(re.length,t);for(;l<f;l++){let t=Cd(e[l],re[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,F.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(ie!==void 0){let d=`${s}/items`;if(Array.isArray(ie)){let s=Math.min(ie.length,t);for(;l<s;l++){let t=Cd(e[l],ie[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,F.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=Cd(e[l],ie,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,F.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ae!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=Cd(e[l],ae,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,F.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(se!==void 0){if(t===0&&N===void 0)F.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(N!==void 0&&t<N)F.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${N}).`});else{let l=`${s}/contains`,u=F.length,d=0;for(let s=0;s<t;s++){let t=Cd(e[s],se,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):F.push(...t.errors)}d>=(N||0)&&(F.length=u),N===void 0&&ce===void 0&&d===0?F.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):N!==void 0&&d<N?F.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${N} items matching schema. Only ${d} items were found.`}):ce!==void 0&&d>ce&&F.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${ce} items matching schema. ${d} items were found.`})}}if(!u&&oe!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=Cd(e[l],oe,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||F.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(ue)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&&Fu(r,t))&&(F.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(de!==void 0&&(pe===!0&&e<=de||e<de)&&F.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${pe?`or equal to `:``} ${de}.`}),fe!==void 0&&(me===!0&&e>=fe||e>fe)&&F.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${me?`or equal to `:``} ${fe}.`})):(de!==void 0&&e<de&&F.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${de}.`}),fe!==void 0&&e>fe&&F.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${fe}.`}),pe!==void 0&&e<=pe&&F.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${pe}.`}),me!==void 0&&e>=me&&F.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${me}.`})),he!==void 0){let t=e%he;Math.abs(0-t)>=1.1920929e-7&&Math.abs(he-t)>=1.1920929e-7&&F.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${he}.`})}}else if(u===`string`){let t=ge===void 0&&_e===void 0?0:xd(e);ge!==void 0&&t<ge&&F.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${ge}).`}),_e!==void 0&&t>_e&&F.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${_e}).`}),ve!==void 0&&!new RegExp(ve,`u`).test(e)&&F.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),T!==void 0&&md[T]&&!md[T](e)&&F.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${T}".`})}return{valid:F.length===0,errors:F}}var wd=I((()=>{Iu(),Gu(),yd(),zu(),Sd()})),Td,Ed=I((()=>{Gu(),wd(),Td=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Bu(e)}validate(e){return Cd(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Bu(e,this.lookup)}}})),Dd=I((()=>{Iu(),Gu(),yd(),zu(),bd(),Sd(),wd(),Ed()}));function Od(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function kd({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 Ad(e){return e.title!==void 0&&e.title!==``?e.title:`annotations`in e&&e.annotations?.title?e.annotations.title:e.name}function jd(e){return xh[e]}function Md(e){let t={};for(let n of e){let e=n.shape.method.value;t[e]=n}return t}function Nd(e){return Sh[e]}function Pd(e){return Ch[e]}function Fd(e){return Yf.parse(e)}function Id(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Ld(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}function Rd(e,t){return E.safeParse(e,t)}function zd(e){return e===`completed`||e===`failed`||e===`cancelled`}function Bd(e){if(!e)return;let{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}=e;return{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}}function Vd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Hd(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]=Vd(a)&&Vd(i)?{...a,...i}:i}return n}async function Ud(e){let t=[];for await(let n of e)t.push(n);return t}async function Wd(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 Gd(e){return Yf.parse(JSON.parse(e))}function Kd(e){return JSON.stringify(e)+`
175
- `}function qd(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`),!Ih.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 Jd(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 Yd(e){let t=qd(e);return Jd(e,t.warnings),t.isValid}function Xd(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Zd(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...Xd(t.headers),...Xd(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 $d(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function ef(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>$d(e)).join(`, `)}:{success:!0,data:n.value}}function tf(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 nf(){let e=new r_.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,i_.default)(e),e}function rf(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 af,of,sf,cf,lf,uf,z,df,ff,pf,mf,B,V,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Tf,Ef,Df,Of,kf,H,U,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,Bh,Vh,Hh,Uh,W,G,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_,i_,a_,o_,s_=I((()=>{Dd(),af=Object.create,of=Object.defineProperty,sf=Object.getOwnPropertyDescriptor,cf=Object.getOwnPropertyNames,lf=Object.getPrototypeOf,uf=Object.prototype.hasOwnProperty,z=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),df=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=cf(t),a=0,o=i.length,s;a<o;a++)s=i[a],!uf.call(e,s)&&s!==n&&of(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=sf(t,s))||r.enumerable});return e},ff=(e,t,n)=>(n=e==null?{}:af(lf(e)),df(t||!e||!e.__esModule?of(n,`default`,{value:e,enumerable:!0}):n,e)),pf=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}({}),mf=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`}},hf=E.url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:E.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),E.NEVER}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),E.looseObject({resource:E.string().url(),authorization_servers:E.array(hf).optional(),jwks_uri:E.string().url().optional(),scopes_supported:E.array(E.string()).optional(),bearer_methods_supported:E.array(E.string()).optional(),resource_signing_alg_values_supported:E.array(E.string()).optional(),resource_name:E.string().optional(),resource_documentation:E.string().optional(),resource_policy_uri:E.string().url().optional(),resource_tos_uri:E.string().url().optional(),tls_client_certificate_bound_access_tokens:E.boolean().optional(),authorization_details_types_supported:E.array(E.string()).optional(),dpop_signing_alg_values_supported:E.array(E.string()).optional(),dpop_bound_access_tokens_required:E.boolean().optional()}),gf=E.looseObject({issuer:E.string(),authorization_endpoint:hf,token_endpoint:hf,registration_endpoint:hf.optional(),scopes_supported:E.array(E.string()).optional(),response_types_supported:E.array(E.string()),response_modes_supported:E.array(E.string()).optional(),grant_types_supported:E.array(E.string()).optional(),token_endpoint_auth_methods_supported:E.array(E.string()).optional(),token_endpoint_auth_signing_alg_values_supported:E.array(E.string()).optional(),service_documentation:hf.optional(),revocation_endpoint:hf.optional(),revocation_endpoint_auth_methods_supported:E.array(E.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:E.array(E.string()).optional(),introspection_endpoint:E.string().optional(),introspection_endpoint_auth_methods_supported:E.array(E.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:E.array(E.string()).optional(),code_challenge_methods_supported:E.array(E.string()).optional(),client_id_metadata_document_supported:E.boolean().optional()}),_f=E.looseObject({issuer:E.string(),authorization_endpoint:hf,token_endpoint:hf,userinfo_endpoint:hf.optional(),jwks_uri:hf,registration_endpoint:hf.optional(),scopes_supported:E.array(E.string()).optional(),response_types_supported:E.array(E.string()),response_modes_supported:E.array(E.string()).optional(),grant_types_supported:E.array(E.string()).optional(),acr_values_supported:E.array(E.string()).optional(),subject_types_supported:E.array(E.string()),id_token_signing_alg_values_supported:E.array(E.string()),id_token_encryption_alg_values_supported:E.array(E.string()).optional(),id_token_encryption_enc_values_supported:E.array(E.string()).optional(),userinfo_signing_alg_values_supported:E.array(E.string()).optional(),userinfo_encryption_alg_values_supported:E.array(E.string()).optional(),userinfo_encryption_enc_values_supported:E.array(E.string()).optional(),request_object_signing_alg_values_supported:E.array(E.string()).optional(),request_object_encryption_alg_values_supported:E.array(E.string()).optional(),request_object_encryption_enc_values_supported:E.array(E.string()).optional(),token_endpoint_auth_methods_supported:E.array(E.string()).optional(),token_endpoint_auth_signing_alg_values_supported:E.array(E.string()).optional(),display_values_supported:E.array(E.string()).optional(),claim_types_supported:E.array(E.string()).optional(),claims_supported:E.array(E.string()).optional(),service_documentation:E.string().optional(),claims_locales_supported:E.array(E.string()).optional(),ui_locales_supported:E.array(E.string()).optional(),claims_parameter_supported:E.boolean().optional(),request_parameter_supported:E.boolean().optional(),request_uri_parameter_supported:E.boolean().optional(),require_request_uri_registration:E.boolean().optional(),op_policy_uri:hf.optional(),op_tos_uri:hf.optional(),client_id_metadata_document_supported:E.boolean().optional()}),E.object({..._f.shape,...gf.pick({code_challenge_methods_supported:!0}).shape}),E.object({access_token:E.string(),id_token:E.string().optional(),token_type:E.string(),expires_in:E.coerce.number().optional(),scope:E.string().optional(),refresh_token:E.string().optional()}).strip(),E.object({issued_token_type:E.literal(`urn:ietf:params:oauth:token-type:id-jag`),access_token:E.string(),token_type:E.string().optional(),expires_in:E.number().optional(),scope:E.string().optional()}).strip(),E.object({error:E.string(),error_description:E.string().optional(),error_uri:E.string().optional()}),vf=hf.optional().or(E.literal(``).transform(()=>void 0)),yf=E.object({redirect_uris:E.array(hf),token_endpoint_auth_method:E.string().optional(),grant_types:E.array(E.string()).optional(),response_types:E.array(E.string()).optional(),client_name:E.string().optional(),client_uri:hf.optional(),logo_uri:vf,scope:E.string().optional(),contacts:E.array(E.string()).optional(),tos_uri:vf,policy_uri:E.string().optional(),jwks_uri:hf.optional(),jwks:E.any().optional(),software_id:E.string().optional(),software_version:E.string().optional(),software_statement:E.string().optional()}).strip(),bf=E.object({client_id:E.string(),client_secret:E.string().optional(),client_id_issued_at:E.number().optional(),client_secret_expires_at:E.number().optional()}).strip(),yf.merge(bf),E.object({error:E.string(),error_description:E.string().optional()}).strip(),E.object({token:E.string(),token_type_hint:E.string().optional()}).strip(),xf=`2025-11-25`,Sf=`2025-03-26`,Cf=[xf,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],wf=`io.modelcontextprotocol/related-task`,Tf=-32700,Ef=-32600,Df=-32601,Of=-32602,kf=-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 Af(e.elicitations,n)}return new e(t,n,r)}},Af=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??[]}},jf=E.lazy(()=>E.union([E.string(),E.number(),E.boolean(),E.null(),E.record(E.string(),jf),E.array(jf)])),Mf=E.record(E.string(),jf),E.array(jf),Nf=E.union([E.string(),E.number().int()]),Pf=E.string(),E.looseObject({ttl:E.number().optional(),pollInterval:E.number().optional()}),Ff=E.object({ttl:E.number().optional()}),If=E.object({taskId:E.string()}),Lf=E.looseObject({progressToken:Nf.optional(),[wf]:If.optional()}),Rf=E.object({_meta:Lf.optional()}),zf=Rf.extend({task:Ff.optional()}),Bf=E.object({method:E.string(),params:Rf.loose().optional()}),Vf=E.object({_meta:Lf.optional()}),Hf=E.object({method:E.string(),params:Vf.loose().optional()}),Uf=E.looseObject({_meta:Lf.optional()}),Wf=E.union([E.string(),E.number().int()]),Gf=E.object({jsonrpc:E.literal(`2.0`),id:Wf,...Bf.shape}).strict(),Kf=E.object({jsonrpc:E.literal(`2.0`),...Hf.shape}).strict(),qf=E.object({jsonrpc:E.literal(`2.0`),id:Wf,result:Uf}).strict(),Jf=E.object({jsonrpc:E.literal(`2.0`),id:Wf.optional(),error:E.object({code:E.number().int(),message:E.string(),data:E.unknown().optional()})}).strict(),Yf=E.union([Gf,Kf,qf,Jf]),E.union([qf,Jf]),Xf=Uf.strict(),Zf=Vf.extend({requestId:Wf.optional(),reason:E.string().optional()}),Qf=Hf.extend({method:E.literal(`notifications/cancelled`),params:Zf}),$f=E.object({src:E.string(),mimeType:E.string().optional(),sizes:E.array(E.string()).optional(),theme:E.enum([`light`,`dark`]).optional()}),ep=E.object({icons:E.array($f).optional()}),tp=E.object({name:E.string(),title:E.string().optional()}),np=tp.extend({...tp.shape,...ep.shape,version:E.string(),websiteUrl:E.string().optional(),description:E.string().optional()}),rp=E.intersection(E.object({applyDefaults:E.boolean().optional()}),Mf),ip=E.preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,E.intersection(E.object({form:rp.optional(),url:Mf.optional()}),Mf.optional())),ap=E.looseObject({list:Mf.optional(),cancel:Mf.optional(),requests:E.looseObject({sampling:E.looseObject({createMessage:Mf.optional()}).optional(),elicitation:E.looseObject({create:Mf.optional()}).optional()}).optional()}),op=E.looseObject({list:Mf.optional(),cancel:Mf.optional(),requests:E.looseObject({tools:E.looseObject({call:Mf.optional()}).optional()}).optional()}),sp=E.object({experimental:E.record(E.string(),Mf).optional(),sampling:E.object({context:Mf.optional(),tools:Mf.optional()}).optional(),elicitation:ip.optional(),roots:E.object({listChanged:E.boolean().optional()}).optional(),tasks:ap.optional(),extensions:E.record(E.string(),Mf).optional()}),cp=Rf.extend({protocolVersion:E.string(),capabilities:sp,clientInfo:np}),lp=Bf.extend({method:E.literal(`initialize`),params:cp}),up=E.object({experimental:E.record(E.string(),Mf).optional(),logging:Mf.optional(),completions:Mf.optional(),prompts:E.object({listChanged:E.boolean().optional()}).optional(),resources:E.object({subscribe:E.boolean().optional(),listChanged:E.boolean().optional()}).optional(),tools:E.object({listChanged:E.boolean().optional()}).optional(),tasks:op.optional(),extensions:E.record(E.string(),Mf).optional()}),dp=Uf.extend({protocolVersion:E.string(),capabilities:up,serverInfo:np,instructions:E.string().optional()}),fp=Hf.extend({method:E.literal(`notifications/initialized`),params:Vf.optional()}),pp=Bf.extend({method:E.literal(`ping`),params:Rf.optional()}),mp=E.object({progress:E.number(),total:E.optional(E.number()),message:E.optional(E.string())}),hp=E.object({...Vf.shape,...mp.shape,progressToken:Nf}),gp=Hf.extend({method:E.literal(`notifications/progress`),params:hp}),_p=Rf.extend({cursor:Pf.optional()}),vp=Bf.extend({params:_p.optional()}),yp=Uf.extend({nextCursor:Pf.optional()}),bp=E.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),xp=E.object({taskId:E.string(),status:bp,ttl:E.union([E.number(),E.null()]),createdAt:E.string(),lastUpdatedAt:E.string(),pollInterval:E.optional(E.number()),statusMessage:E.optional(E.string())}),Sp=Uf.extend({task:xp}),Cp=Vf.merge(xp),wp=Hf.extend({method:E.literal(`notifications/tasks/status`),params:Cp}),Tp=Bf.extend({method:E.literal(`tasks/get`),params:Rf.extend({taskId:E.string()})}),Ep=Uf.merge(xp),Dp=Bf.extend({method:E.literal(`tasks/result`),params:Rf.extend({taskId:E.string()})}),Op=Uf.loose(),kp=vp.extend({method:E.literal(`tasks/list`)}),Ap=yp.extend({tasks:E.array(xp)}),jp=Bf.extend({method:E.literal(`tasks/cancel`),params:Rf.extend({taskId:E.string()})}),Mp=Uf.merge(xp),Np=E.object({uri:E.string(),mimeType:E.optional(E.string()),_meta:E.record(E.string(),E.unknown()).optional()}),Pp=Np.extend({text:E.string()}),Fp=E.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Ip=Np.extend({blob:Fp}),Lp=E.enum([`user`,`assistant`]),Rp=E.object({audience:E.array(Lp).optional(),priority:E.number().min(0).max(1).optional(),lastModified:E.iso.datetime({offset:!0}).optional()}),zp=E.object({...tp.shape,...ep.shape,uri:E.string(),description:E.optional(E.string()),mimeType:E.optional(E.string()),size:E.optional(E.number()),annotations:Rp.optional(),_meta:E.optional(E.looseObject({}))}),Bp=E.object({...tp.shape,...ep.shape,uriTemplate:E.string(),description:E.optional(E.string()),mimeType:E.optional(E.string()),annotations:Rp.optional(),_meta:E.optional(E.looseObject({}))}),Vp=vp.extend({method:E.literal(`resources/list`)}),Hp=yp.extend({resources:E.array(zp)}),Up=vp.extend({method:E.literal(`resources/templates/list`)}),Wp=yp.extend({resourceTemplates:E.array(Bp)}),Gp=Rf.extend({uri:E.string()}),Kp=Gp,qp=Bf.extend({method:E.literal(`resources/read`),params:Kp}),Jp=Uf.extend({contents:E.array(E.union([Pp,Ip]))}),Yp=Hf.extend({method:E.literal(`notifications/resources/list_changed`),params:Vf.optional()}),Xp=Gp,Zp=Bf.extend({method:E.literal(`resources/subscribe`),params:Xp}),Qp=Gp,$p=Bf.extend({method:E.literal(`resources/unsubscribe`),params:Qp}),em=Vf.extend({uri:E.string()}),tm=Hf.extend({method:E.literal(`notifications/resources/updated`),params:em}),nm=E.object({name:E.string(),description:E.optional(E.string()),required:E.optional(E.boolean())}),rm=E.object({...tp.shape,...ep.shape,description:E.optional(E.string()),arguments:E.optional(E.array(nm)),_meta:E.optional(E.looseObject({}))}),im=vp.extend({method:E.literal(`prompts/list`)}),am=yp.extend({prompts:E.array(rm)}),om=Rf.extend({name:E.string(),arguments:E.record(E.string(),E.string()).optional()}),sm=Bf.extend({method:E.literal(`prompts/get`),params:om}),cm=E.object({type:E.literal(`text`),text:E.string(),annotations:Rp.optional(),_meta:E.record(E.string(),E.unknown()).optional()}),lm=E.object({type:E.literal(`image`),data:Fp,mimeType:E.string(),annotations:Rp.optional(),_meta:E.record(E.string(),E.unknown()).optional()}),um=E.object({type:E.literal(`audio`),data:Fp,mimeType:E.string(),annotations:Rp.optional(),_meta:E.record(E.string(),E.unknown()).optional()}),dm=E.object({type:E.literal(`tool_use`),name:E.string(),id:E.string(),input:E.record(E.string(),E.unknown()),_meta:E.record(E.string(),E.unknown()).optional()}),fm=E.object({type:E.literal(`resource`),resource:E.union([Pp,Ip]),annotations:Rp.optional(),_meta:E.record(E.string(),E.unknown()).optional()}),pm=zp.extend({type:E.literal(`resource_link`)}),mm=E.union([cm,lm,um,pm,fm]),hm=E.object({role:Lp,content:mm}),gm=Uf.extend({description:E.string().optional(),messages:E.array(hm)}),_m=Hf.extend({method:E.literal(`notifications/prompts/list_changed`),params:Vf.optional()}),vm=E.object({title:E.string().optional(),readOnlyHint:E.boolean().optional(),destructiveHint:E.boolean().optional(),idempotentHint:E.boolean().optional(),openWorldHint:E.boolean().optional()}),ym=E.object({taskSupport:E.enum([`required`,`optional`,`forbidden`]).optional()}),bm=E.object({...tp.shape,...ep.shape,description:E.string().optional(),inputSchema:E.object({type:E.literal(`object`),properties:E.record(E.string(),jf).optional(),required:E.array(E.string()).optional()}).catchall(E.unknown()),outputSchema:E.object({type:E.literal(`object`),properties:E.record(E.string(),jf).optional(),required:E.array(E.string()).optional()}).catchall(E.unknown()).optional(),annotations:vm.optional(),execution:ym.optional(),_meta:E.record(E.string(),E.unknown()).optional()}),xm=vp.extend({method:E.literal(`tools/list`)}),Sm=yp.extend({tools:E.array(bm)}),Cm=Uf.extend({content:E.array(mm).default([]),structuredContent:E.record(E.string(),E.unknown()).optional(),isError:E.boolean().optional()}),Cm.or(Uf.extend({toolResult:E.unknown()})),wm=zf.extend({name:E.string(),arguments:E.record(E.string(),E.unknown()).optional()}),Tm=Bf.extend({method:E.literal(`tools/call`),params:wm}),Em=Hf.extend({method:E.literal(`notifications/tools/list_changed`),params:Vf.optional()}),E.object({autoRefresh:E.boolean().default(!0),debounceMs:E.number().int().nonnegative().default(300)}),Dm=E.enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Om=Rf.extend({level:Dm}),km=Bf.extend({method:E.literal(`logging/setLevel`),params:Om}),Am=Vf.extend({level:Dm,logger:E.string().optional(),data:E.unknown()}),jm=Hf.extend({method:E.literal(`notifications/message`),params:Am}),Mm=E.object({name:E.string().optional()}),Nm=E.object({hints:E.array(Mm).optional(),costPriority:E.number().min(0).max(1).optional(),speedPriority:E.number().min(0).max(1).optional(),intelligencePriority:E.number().min(0).max(1).optional()}),Pm=E.object({mode:E.enum([`auto`,`required`,`none`]).optional()}),Fm=E.object({type:E.literal(`tool_result`),toolUseId:E.string().describe(`The unique identifier for the corresponding tool call.`),content:E.array(mm).default([]),structuredContent:E.object({}).loose().optional(),isError:E.boolean().optional(),_meta:E.record(E.string(),E.unknown()).optional()}),Im=E.discriminatedUnion(`type`,[cm,lm,um]),Lm=E.discriminatedUnion(`type`,[cm,lm,um,dm,Fm]),Rm=E.object({role:Lp,content:E.union([Lm,E.array(Lm)]),_meta:E.record(E.string(),E.unknown()).optional()}),zm=zf.extend({messages:E.array(Rm),modelPreferences:Nm.optional(),systemPrompt:E.string().optional(),includeContext:E.enum([`none`,`thisServer`,`allServers`]).optional(),temperature:E.number().optional(),maxTokens:E.number().int(),stopSequences:E.array(E.string()).optional(),metadata:Mf.optional(),tools:E.array(bm).optional(),toolChoice:Pm.optional()}),Bm=Bf.extend({method:E.literal(`sampling/createMessage`),params:zm}),Vm=Uf.extend({model:E.string(),stopReason:E.optional(E.enum([`endTurn`,`stopSequence`,`maxTokens`]).or(E.string())),role:Lp,content:Im}),Hm=Uf.extend({model:E.string(),stopReason:E.optional(E.enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(E.string())),role:Lp,content:E.union([Lm,E.array(Lm)])}),Um=E.object({type:E.literal(`boolean`),title:E.string().optional(),description:E.string().optional(),default:E.boolean().optional()}),Wm=E.object({type:E.literal(`string`),title:E.string().optional(),description:E.string().optional(),minLength:E.number().optional(),maxLength:E.number().optional(),format:E.enum([`email`,`uri`,`date`,`date-time`]).optional(),default:E.string().optional()}),Gm=E.object({type:E.enum([`number`,`integer`]),title:E.string().optional(),description:E.string().optional(),minimum:E.number().optional(),maximum:E.number().optional(),default:E.number().optional()}),Km=E.object({type:E.literal(`string`),title:E.string().optional(),description:E.string().optional(),enum:E.array(E.string()),default:E.string().optional()}),qm=E.object({type:E.literal(`string`),title:E.string().optional(),description:E.string().optional(),oneOf:E.array(E.object({const:E.string(),title:E.string()})),default:E.string().optional()}),Jm=E.object({type:E.literal(`string`),title:E.string().optional(),description:E.string().optional(),enum:E.array(E.string()),enumNames:E.array(E.string()).optional(),default:E.string().optional()}),Ym=E.union([Km,qm]),Xm=E.object({type:E.literal(`array`),title:E.string().optional(),description:E.string().optional(),minItems:E.number().optional(),maxItems:E.number().optional(),items:E.object({type:E.literal(`string`),enum:E.array(E.string())}),default:E.array(E.string()).optional()}),Zm=E.object({type:E.literal(`array`),title:E.string().optional(),description:E.string().optional(),minItems:E.number().optional(),maxItems:E.number().optional(),items:E.object({anyOf:E.array(E.object({const:E.string(),title:E.string()}))}),default:E.array(E.string()).optional()}),Qm=E.union([Xm,Zm]),$m=E.union([Jm,Ym,Qm]),eh=E.union([$m,Um,Wm,Gm]),th=zf.extend({mode:E.literal(`form`).optional(),message:E.string(),requestedSchema:E.object({type:E.literal(`object`),properties:E.record(E.string(),eh),required:E.array(E.string()).optional()})}),nh=zf.extend({mode:E.literal(`url`),message:E.string(),elicitationId:E.string(),url:E.string().url()}),rh=E.union([th,nh]),ih=Bf.extend({method:E.literal(`elicitation/create`),params:rh}),ah=Vf.extend({elicitationId:E.string()}),oh=Hf.extend({method:E.literal(`notifications/elicitation/complete`),params:ah}),sh=Uf.extend({action:E.enum([`accept`,`decline`,`cancel`]),content:E.preprocess(e=>e===null?void 0:e,E.record(E.string(),E.union([E.string(),E.number(),E.boolean(),E.array(E.string())])).optional())}),ch=E.object({type:E.literal(`ref/resource`),uri:E.string()}),lh=E.object({type:E.literal(`ref/prompt`),name:E.string()}),uh=Rf.extend({ref:E.union([lh,ch]),argument:E.object({name:E.string(),value:E.string()}),context:E.object({arguments:E.record(E.string(),E.string()).optional()}).optional()}),dh=Bf.extend({method:E.literal(`completion/complete`),params:uh}),fh=Uf.extend({completion:E.looseObject({values:E.array(E.string()).max(100),total:E.optional(E.number().int()),hasMore:E.optional(E.boolean())})}),ph=E.object({uri:E.string().startsWith(`file://`),name:E.string().optional(),_meta:E.record(E.string(),E.unknown()).optional()}),mh=Bf.extend({method:E.literal(`roots/list`),params:Rf.optional()}),hh=Uf.extend({roots:E.array(ph)}),gh=Hf.extend({method:E.literal(`notifications/roots/list_changed`),params:Vf.optional()}),_h=E.union([pp,lp,dh,km,sm,im,Vp,Up,qp,Zp,$p,Tm,xm,Tp,Dp,kp,jp]),vh=E.union([Qf,gp,fp,gh,wp]),E.union([Xf,Vm,Hm,sh,hh,Ep,Ap,Sp]),yh=E.union([pp,Bm,ih,mh,Tp,Dp,kp,jp]),bh=E.union([Qf,gp,jm,tm,Yp,Em,_m,wp,oh]),E.union([Xf,dp,fh,gm,am,Hp,Wp,Jp,Cm,Sm,Ep,Ap,Sp]),xh={ping:Xf,initialize:dp,"completion/complete":fh,"logging/setLevel":Xf,"prompts/get":gm,"prompts/list":am,"resources/list":Hp,"resources/templates/list":Wp,"resources/read":Jp,"resources/subscribe":Xf,"resources/unsubscribe":Xf,"tools/call":E.union([Cm,Sp]),"tools/list":Sm,"sampling/createMessage":E.union([Hm,Sp]),"elicitation/create":E.union([sh,Sp]),"roots/list":hh,"tasks/get":Ep,"tasks/result":Uf,"tasks/list":Ap,"tasks/cancel":Mp},Sh=Md([..._h.options,...yh.options]),Ch=Md([...vh.options,...bh.options]),wh=e=>Gf.safeParse(e).success,Th=e=>Kf.safeParse(e).success,Eh=e=>qf.safeParse(e).success,Dh=e=>Jf.safeParse(e).success,Oh=e=>zf.safeParse(e).success,kh=e=>lp.safeParse(e).success,Ah=e=>fp.safeParse(e).success,jh=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,Sp,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},zd(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},Ep,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},Ap,t)}async cancelTask(e,t){return this._requireHost.request({method:`tasks/cancel`,params:e},Mp,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(!zd(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,[wf]:{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(zd(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,[wf]: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)?.[wf]?.taskId,r=Oh(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),Eh(e)?n(e):n(new U(e.error.code,e.error.message,e.error.data)),!0):!1}shouldPreserveProgressHandler(e,t){if(Eh(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,[wf]: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(Dh(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=wp.parse({method:`notifications/tasks/status`,params:o});await r?.notification(t),zd(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(zd(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=wp.parse({method:`notifications/tasks/status`,params:s});await r?.notification(t),zd(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,[wf]: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`&&wh(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))}},Mh=class extends jh{constructor(){super({})}processInboundRequest(e,t){let n=Oh(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`}}}},Nh=6e4,Ph=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??Cf,this._taskManager=e?.tasks?new jh(e.tasks):new Mh,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=Nd(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),Eh(e)||Dh(e)?this._onresponse(e):wh(e)?this._onrequest(e,t):Th(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,jd(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),Eh(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=jd(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=Rd(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=Nd(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=Pd(e);this._notificationHandlers.set(e,e=>{let r=n.parse(e);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}},Fh=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 Gd(t)}catch(e){if(e instanceof SyntaxError)continue;throw e}}return null}clear(){this._buffer=void 0}},Ih=/^[A-Za-z0-9._-]{1,128}$/,Lh=1e6,Rh=1e6,zh=1e4,Bh=1e6,Vh=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,Lh,`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>zh)throw Error(`Template contains too many expressions (max ${zh})`);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,Rh,`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,Rh,`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,Rh,`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,Lh,`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,Bh,`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}},Hh=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})),Uh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Hh();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=Hh(),n=Uh();var r=Hh();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=Uh();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=D(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=D(this.rhs,e,n),this}get names(){return E(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=D(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(O(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>te(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(k(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=D(this.condition,e,t),this}get names(){let e=super.names;return E(e,this.condition),this.else&&te(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=D(this.iteration,e,t),this}get names(){return te(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return E(E(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=D(this.iterable,e,t),this}get names(){return te(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&te(e,this.catch.names),this.finally&&te(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var ee=class extends m{render(e){return`finally`+super.render(e)}};ee.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
177
- `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new ee,this.code(n)),this._endBlockNode(T,ee)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function te(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function E(e,n){return n instanceof t._CodeOrName?te(e,n.names):e}function D(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function O(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function k(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ie(e)}`}e.not=k;let ne=re(e.operators.AND);function A(...e){return e.reduce(ne)}e.and=A;let j=re(e.operators.OR);function M(...e){return e.reduce(j)}e.or=M;function re(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ie(n)} ${e} ${ie(r)}`}function ie(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),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=Hh();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})),Wh=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`)}})),Gh=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=Wh();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])}})),Kh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Gh(),n=W(),r=Wh(),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)}})),qh=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})),Jh=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})),Yh=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=qh(),n=Jh(),r=Gh(),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:[tu({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`)})}),tu({name:`doctor`,description:`Validate MCP server startup and tool listing`})]},{name:`skills`,aliases:[`skill`],description:`Sync skill files to agents`,subcommands:[tu({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`)})}),tu({name:`list`,aliases:[`ls`],description:`List skills`})]}]}));function cu(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(...yu(c,r,a)),l.join(`
171
+ `)}function lu(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=uu(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=du(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=pu(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(...yu(f,i,o)),l){let e=fu(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??Yl();n.name in i&&r.push(`set: ${bu(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 uu(e,t){if(!t)return e;let n=[e];for(let[e,r]of Object.entries(t.shape)){let t=mu(r),i=(t.includes(`|`)?t:e)+(t===`array`?`...`:``);n.push(r._zod.optout===`optional`?`[${i}]`:`<${i}>`)}return n.join(` `)}function du(e){let t=[];for(let[n,r]of Object.entries(e.shape))t.push({name:n,description:r.description??``});return t}function fu(e){let t=[];for(let[n,r]of Object.entries(e.shape)){let e=_u(r);t.push({name:n,description:r.description??``,defaultValue:e})}return t}function pu(e,t){let n=[];for(let[r,i]of Object.entries(e.shape)){let e=mu(i),a=t?.[r],o=un(r),s=e===`boolean`?``:` <${e}>`,c=a?`--${o}, -${a}${s}`:`--${o}${s}`,l=_u(i);e===`boolean`&&l===!1&&(l=void 0);let u=vu(i);n.push({flag:c,description:i.description??``,defaultValue:l,deprecated:u})}return n}function mu(e){if(hu(e))return`count`;let t=gu(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 hu(e){let t=e;return typeof t?.meta==`function`&&t.meta()?.count===!0}function gu(e){return e instanceof f.ZodOptional?gu(e.unwrap()):e instanceof f.ZodDefault?gu(e.removeDefault()):e instanceof f.ZodNullable?gu(e.unwrap()):e}function _u(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 _u(e.unwrap())}function vu(e){return e?.meta?.()?.deprecated===!0||void 0}function yu(e=!1,t,n){let r=[];if(e){let e=ou.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=pu(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 bu(e){return e.length<=4?`****`:`****${e.slice(-4)}`}var xu=F((()=>{su(),pn(),Xl()}));function Su(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=>wu(e,t))}}function Cu(e){let t=[e.description];for(let n of e.commands)t.push(` ${n.command}${n.description?` - ${n.description}`:``}`);return t.join(`
173
+ `)}function wu(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 Tu=F((()=>{}));async function Eu(e,t={}){let n=[],r=t.exclude?c.resolve(t.exclude):void 0;async function i(e,t){let a=await w.readdir(e,{withFileTypes:!0});a.sort((e,t)=>e.name.localeCompare(t.name));for(let o of a){if(o.name.startsWith(`.`)||o.name.startsWith(`_`))continue;let a=c.join(e,o.name);if(o.isDirectory()){ku(o.name,a),await i(a,[...t,o.name]);continue}if(!o.isFile()||a===r)continue;let s=Au.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}ku(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 Du(){return globalThis[Symbol.for(Mu)]?.shift()}async function Ou(e){return Promise.all(e.map(async({load:e,...t})=>({...t,command:await e()})))}function ku(e,t){if(!ju.test(e))throw Error(`Invalid filesystem command segment '${e}' from '${t}'. Use lowercase kebab-case names.`)}var Au,ju,Mu,Nu=F((()=>{Au=[`.cts`,`.cjs`,`.mts`,`.mjs`,`.ts`,`.js`],ju=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Mu=`incur.fs.manifests`}));function Pu(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 Fu=F((()=>{}));function Iu(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(!Iu(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(!Iu(e[r],t[r]))return!1;return!0}return e===t}var Lu=F((()=>{}));function Ru(e){return encodeURI(zu(e))}function zu(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var Bu=F((()=>{}));function Vu(e,t=Object.create(null),n=Gu,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:Vu(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(Wu[i])continue;let a=`${r}/${Ru(i)}`,o=e[i];if(Array.isArray(o)){if(Hu[i]){let e=o.length;for(let r=0;r<e;r++)Vu(o[r],t,n,`${a}/${r}`)}}else if(Uu[i])for(let e in o)Vu(o[e],t,n,`${a}/${Ru(e)}`);else Vu(o,t,n,a)}return t}var Hu,Uu,Wu,Gu,Ku=F((()=>{Bu(),Hu={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Uu={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Wu={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},Gu=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 qu(e){return e.test.bind(e)}function Ju(e){return e%4==0&&(e%100!=0||e%400==0)}function Yu(e){let t=e.match(ed);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&Ju(n)?29:td[r])}function Xu(e,t){let n=t.match(nd);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 Zu(e){let t=e.split(gd);return t.length==2&&Yu(t[0])&&Xu(!0,t[1])}function Qu(e){return _d.test(e)&&vd.test(e)}function $u(e){if(yd.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}var ed,td,nd,rd,id,ad,od,sd,cd,ld,ud,dd,fd,pd,md,hd,gd,_d,vd,yd,bd=F((()=>{ed=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,td=[0,31,28,31,30,31,30,31,31,30,31,30,31],nd=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,rd=/^(?=.{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,id=/^(?:[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,ad=/^(?:(?:[^\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,od=/^(?:(?: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,sd=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,cd=/^(?:\/(?:[^~/]|~0|~1)*)*$/,ld=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,ud=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,dd=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))},fd=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,pd=/^((([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,md=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)),hd={date:Yu,time:Xu.bind(void 0,!1),"date-time":Zu,duration:md,uri:Qu,"uri-reference":qu(id),"uri-template":qu(ad),url:qu(od),email:dd,hostname:qu(rd),ipv4:qu(fd),ipv6:qu(pd),regex:$u,uuid:qu(sd),"json-pointer":qu(cd),"json-pointer-uri-fragment":qu(ld),"relative-json-pointer":qu(ud)},gd=/t|\s/i,_d=/\/|:/,vd=/^(?:[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,yd=/[^\\]\\Z/})),xd=F((()=>{}));function Sd(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 Cd=F((()=>{}));function wd(e,t,n=`2019-09`,r=Vu(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:C,else:w,format:T,properties:E,patternProperties:ee,additionalProperties:D,unevaluatedProperties:O,minProperties:k,maxProperties:A,propertyNames:te,dependentRequired:ne,dependentSchemas:j,dependencies:re,prefixItems:M,items:ie,additionalItems:ae,unevaluatedItems:oe,contains:se,minContains:N,maxContains:ce,minItems:le,maxItems:ue,uniqueItems:de,minimum:fe,maximum:pe,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=wd(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=wd(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`?Iu(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=>Iu(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`;wd(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=wd(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=wd(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=wd(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(wd(e,S,n,r,i,a,o,t,c).valid){if(C!==void 0){let l=wd(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=wd(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.`}),A!==void 0&&t.length>A&&P.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${A} properties.`}),te!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${Ru(s)}`,c=wd(s,te,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(ne!==void 0){let t=`${s}/dependantRequired`;for(let n in ne)if(n in e){let r=ne[n];for(let i of r)i in e||P.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(j!==void 0)for(let t in j){let l=`${s}/dependentSchemas`;if(t in e){let s=wd(e,j[t],n,r,i,a,o,`${l}/${Ru(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(re!==void 0){let t=`${s}/dependencies`;for(let s in re)if(s in e){let c=re[s];if(Array.isArray(c))for(let n of c)n in e||P.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=wd(e,c,n,r,i,a,o,`${t}/${Ru(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(E!==void 0){let t=`${s}/properties`;for(let s in E){if(!(s in e))continue;let d=`${o}/${Ru(s)}`,f=wd(e[s],E[s],n,r,i,a,d,`${t}/${Ru(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&&ee!==void 0){let t=`${s}/patternProperties`;for(let s in ee){let d=new RegExp(s,`u`),f=ee[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${Ru(p)}`,h=wd(e[p],f,n,r,i,a,m,`${t}/${Ru(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}/${Ru(s)}`,f=wd(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}/${Ru(s)}`,u=wd(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`){ue!==void 0&&e.length>ue&&P.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${ue}).`}),le!==void 0&&e.length<le&&P.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${le}).`});let t=e.length,l=0,u=!1;if(M!==void 0){let d=`${s}/prefixItems`,f=Math.min(M.length,t);for(;l<f;l++){let t=wd(e[l],M[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(ie!==void 0){let d=`${s}/items`;if(Array.isArray(ie)){let s=Math.min(ie.length,t);for(;l<s;l++){let t=wd(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:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=wd(e[l],ie,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&&ae!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=wd(e[l],ae,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(se!==void 0){if(t===0&&N===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(N!==void 0&&t<N)P.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${N}).`});else{let l=`${s}/contains`,u=P.length,d=0;for(let s=0;s<t;s++){let t=wd(e[s],se,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):P.push(...t.errors)}d>=(N||0)&&(P.length=u),N===void 0&&ce===void 0&&d===0?P.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):N!==void 0&&d<N?P.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${N} items matching schema. Only ${d} items were found.`}):ce!==void 0&&d>ce&&P.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${ce} items matching schema. ${d} items were found.`})}}if(!u&&oe!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=wd(e[l],oe,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(de)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&Iu(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`?(fe!==void 0&&(me===!0&&e<=fe||e<fe)&&P.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${me?`or equal to `:``} ${fe}.`}),pe!==void 0&&(he===!0&&e>=pe||e>pe)&&P.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${he?`or equal to `:``} ${pe}.`})):(fe!==void 0&&e<fe&&P.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${fe}.`}),pe!==void 0&&e>pe&&P.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${pe}.`}),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:Sd(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&&hd[T]&&!hd[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 Td=F((()=>{Lu(),Ku(),bd(),Bu(),Cd()})),Ed,Dd=F((()=>{Ku(),Td(),Ed=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Vu(e)}validate(e){return wd(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Vu(e,this.lookup)}}})),Od=F((()=>{Lu(),Ku(),bd(),Bu(),xd(),Cd(),Td(),Dd()}));function kd(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Ad({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 jd(e){return e.title!==void 0&&e.title!==``?e.title:`annotations`in e&&e.annotations?.title?e.annotations.title:e.name}function Md(e){return Sh[e]}function Nd(e){let t={};for(let n of e){let e=n.shape.method.value;t[e]=n}return t}function Pd(e){return Ch[e]}function Fd(e){return wh[e]}function Id(e){return Xf.parse(e)}function Ld(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Rd(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}function zd(e,t){return O.safeParse(e,t)}function Bd(e){return e===`completed`||e===`failed`||e===`cancelled`}function Vd(e){if(!e)return;let{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}=e;return{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}}function Hd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ud(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]=Hd(a)&&Hd(i)?{...a,...i}:i}return n}async function Wd(e){let t=[];for await(let n of e)t.push(n);return t}async function Gd(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 Kd(e){return Xf.parse(JSON.parse(e))}function qd(e){return JSON.stringify(e)+`
175
+ `}function Jd(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`),!Lh.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 Yd(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 Xd(e){let t=Jd(e);return Yd(e,t.warnings),t.isValid}function Zd(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?{...Zd(t.headers),...Zd(r.headers)}:t.headers}):e}function $d(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 ef(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function tf(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>ef(e)).join(`, `)}:{success:!0,data:n.value}}function nf(e){let t=$d(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 rf(){let e=new i_.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,a_.default)(e),e}function af(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 of,sf,cf,lf,uf,df,z,ff,pf,mf,hf,B,V,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Tf,Ef,Df,Of,kf,Af,H,U,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,Bh,Vh,Hh,Uh,Wh,W,G,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_,i_,a_,o_,s_,c_=F((()=>{Od(),of=Object.create,sf=Object.defineProperty,cf=Object.getOwnPropertyDescriptor,lf=Object.getOwnPropertyNames,uf=Object.getPrototypeOf,df=Object.prototype.hasOwnProperty,z=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ff=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=lf(t),a=0,o=i.length,s;a<o;a++)s=i[a],!df.call(e,s)&&s!==n&&sf(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=cf(t,s))||r.enumerable});return e},pf=(e,t,n)=>(n=e==null?{}:of(uf(e)),ff(t||!e||!e.__esModule?sf(n,`default`,{value:e,enumerable:!0}):n,e)),mf=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}({}),hf=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`}},gf=O.url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:O.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),O.NEVER}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),O.looseObject({resource:O.string().url(),authorization_servers:O.array(gf).optional(),jwks_uri:O.string().url().optional(),scopes_supported:O.array(O.string()).optional(),bearer_methods_supported:O.array(O.string()).optional(),resource_signing_alg_values_supported:O.array(O.string()).optional(),resource_name:O.string().optional(),resource_documentation:O.string().optional(),resource_policy_uri:O.string().url().optional(),resource_tos_uri:O.string().url().optional(),tls_client_certificate_bound_access_tokens:O.boolean().optional(),authorization_details_types_supported:O.array(O.string()).optional(),dpop_signing_alg_values_supported:O.array(O.string()).optional(),dpop_bound_access_tokens_required:O.boolean().optional()}),_f=O.looseObject({issuer:O.string(),authorization_endpoint:gf,token_endpoint:gf,registration_endpoint:gf.optional(),scopes_supported:O.array(O.string()).optional(),response_types_supported:O.array(O.string()),response_modes_supported:O.array(O.string()).optional(),grant_types_supported:O.array(O.string()).optional(),token_endpoint_auth_methods_supported:O.array(O.string()).optional(),token_endpoint_auth_signing_alg_values_supported:O.array(O.string()).optional(),service_documentation:gf.optional(),revocation_endpoint:gf.optional(),revocation_endpoint_auth_methods_supported:O.array(O.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:O.array(O.string()).optional(),introspection_endpoint:O.string().optional(),introspection_endpoint_auth_methods_supported:O.array(O.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:O.array(O.string()).optional(),code_challenge_methods_supported:O.array(O.string()).optional(),client_id_metadata_document_supported:O.boolean().optional()}),vf=O.looseObject({issuer:O.string(),authorization_endpoint:gf,token_endpoint:gf,userinfo_endpoint:gf.optional(),jwks_uri:gf,registration_endpoint:gf.optional(),scopes_supported:O.array(O.string()).optional(),response_types_supported:O.array(O.string()),response_modes_supported:O.array(O.string()).optional(),grant_types_supported:O.array(O.string()).optional(),acr_values_supported:O.array(O.string()).optional(),subject_types_supported:O.array(O.string()),id_token_signing_alg_values_supported:O.array(O.string()),id_token_encryption_alg_values_supported:O.array(O.string()).optional(),id_token_encryption_enc_values_supported:O.array(O.string()).optional(),userinfo_signing_alg_values_supported:O.array(O.string()).optional(),userinfo_encryption_alg_values_supported:O.array(O.string()).optional(),userinfo_encryption_enc_values_supported:O.array(O.string()).optional(),request_object_signing_alg_values_supported:O.array(O.string()).optional(),request_object_encryption_alg_values_supported:O.array(O.string()).optional(),request_object_encryption_enc_values_supported:O.array(O.string()).optional(),token_endpoint_auth_methods_supported:O.array(O.string()).optional(),token_endpoint_auth_signing_alg_values_supported:O.array(O.string()).optional(),display_values_supported:O.array(O.string()).optional(),claim_types_supported:O.array(O.string()).optional(),claims_supported:O.array(O.string()).optional(),service_documentation:O.string().optional(),claims_locales_supported:O.array(O.string()).optional(),ui_locales_supported:O.array(O.string()).optional(),claims_parameter_supported:O.boolean().optional(),request_parameter_supported:O.boolean().optional(),request_uri_parameter_supported:O.boolean().optional(),require_request_uri_registration:O.boolean().optional(),op_policy_uri:gf.optional(),op_tos_uri:gf.optional(),client_id_metadata_document_supported:O.boolean().optional()}),O.object({...vf.shape,..._f.pick({code_challenge_methods_supported:!0}).shape}),O.object({access_token:O.string(),id_token:O.string().optional(),token_type:O.string(),expires_in:O.coerce.number().optional(),scope:O.string().optional(),refresh_token:O.string().optional()}).strip(),O.object({issued_token_type:O.literal(`urn:ietf:params:oauth:token-type:id-jag`),access_token:O.string(),token_type:O.string().optional(),expires_in:O.number().optional(),scope:O.string().optional()}).strip(),O.object({error:O.string(),error_description:O.string().optional(),error_uri:O.string().optional()}),yf=gf.optional().or(O.literal(``).transform(()=>void 0)),bf=O.object({redirect_uris:O.array(gf),token_endpoint_auth_method:O.string().optional(),grant_types:O.array(O.string()).optional(),response_types:O.array(O.string()).optional(),client_name:O.string().optional(),client_uri:gf.optional(),logo_uri:yf,scope:O.string().optional(),contacts:O.array(O.string()).optional(),tos_uri:yf,policy_uri:O.string().optional(),jwks_uri:gf.optional(),jwks:O.any().optional(),software_id:O.string().optional(),software_version:O.string().optional(),software_statement:O.string().optional()}).strip(),xf=O.object({client_id:O.string(),client_secret:O.string().optional(),client_id_issued_at:O.number().optional(),client_secret_expires_at:O.number().optional()}).strip(),bf.merge(xf),O.object({error:O.string(),error_description:O.string().optional()}).strip(),O.object({token:O.string(),token_type_hint:O.string().optional()}).strip(),Sf=`2025-11-25`,Cf=`2025-03-26`,wf=[Sf,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Tf=`io.modelcontextprotocol/related-task`,Ef=-32700,Df=-32600,Of=-32601,kf=-32602,Af=-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 jf(e.elicitations,n)}return new e(t,n,r)}},jf=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??[]}},Mf=O.lazy(()=>O.union([O.string(),O.number(),O.boolean(),O.null(),O.record(O.string(),Mf),O.array(Mf)])),Nf=O.record(O.string(),Mf),O.array(Mf),Pf=O.union([O.string(),O.number().int()]),Ff=O.string(),O.looseObject({ttl:O.number().optional(),pollInterval:O.number().optional()}),If=O.object({ttl:O.number().optional()}),Lf=O.object({taskId:O.string()}),Rf=O.looseObject({progressToken:Pf.optional(),[Tf]:Lf.optional()}),zf=O.object({_meta:Rf.optional()}),Bf=zf.extend({task:If.optional()}),Vf=O.object({method:O.string(),params:zf.loose().optional()}),Hf=O.object({_meta:Rf.optional()}),Uf=O.object({method:O.string(),params:Hf.loose().optional()}),Wf=O.looseObject({_meta:Rf.optional()}),Gf=O.union([O.string(),O.number().int()]),Kf=O.object({jsonrpc:O.literal(`2.0`),id:Gf,...Vf.shape}).strict(),qf=O.object({jsonrpc:O.literal(`2.0`),...Uf.shape}).strict(),Jf=O.object({jsonrpc:O.literal(`2.0`),id:Gf,result:Wf}).strict(),Yf=O.object({jsonrpc:O.literal(`2.0`),id:Gf.optional(),error:O.object({code:O.number().int(),message:O.string(),data:O.unknown().optional()})}).strict(),Xf=O.union([Kf,qf,Jf,Yf]),O.union([Jf,Yf]),Zf=Wf.strict(),Qf=Hf.extend({requestId:Gf.optional(),reason:O.string().optional()}),$f=Uf.extend({method:O.literal(`notifications/cancelled`),params:Qf}),ep=O.object({src:O.string(),mimeType:O.string().optional(),sizes:O.array(O.string()).optional(),theme:O.enum([`light`,`dark`]).optional()}),tp=O.object({icons:O.array(ep).optional()}),np=O.object({name:O.string(),title:O.string().optional()}),rp=np.extend({...np.shape,...tp.shape,version:O.string(),websiteUrl:O.string().optional(),description:O.string().optional()}),ip=O.intersection(O.object({applyDefaults:O.boolean().optional()}),Nf),ap=O.preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,O.intersection(O.object({form:ip.optional(),url:Nf.optional()}),Nf.optional())),op=O.looseObject({list:Nf.optional(),cancel:Nf.optional(),requests:O.looseObject({sampling:O.looseObject({createMessage:Nf.optional()}).optional(),elicitation:O.looseObject({create:Nf.optional()}).optional()}).optional()}),sp=O.looseObject({list:Nf.optional(),cancel:Nf.optional(),requests:O.looseObject({tools:O.looseObject({call:Nf.optional()}).optional()}).optional()}),cp=O.object({experimental:O.record(O.string(),Nf).optional(),sampling:O.object({context:Nf.optional(),tools:Nf.optional()}).optional(),elicitation:ap.optional(),roots:O.object({listChanged:O.boolean().optional()}).optional(),tasks:op.optional(),extensions:O.record(O.string(),Nf).optional()}),lp=zf.extend({protocolVersion:O.string(),capabilities:cp,clientInfo:rp}),up=Vf.extend({method:O.literal(`initialize`),params:lp}),dp=O.object({experimental:O.record(O.string(),Nf).optional(),logging:Nf.optional(),completions:Nf.optional(),prompts:O.object({listChanged:O.boolean().optional()}).optional(),resources:O.object({subscribe:O.boolean().optional(),listChanged:O.boolean().optional()}).optional(),tools:O.object({listChanged:O.boolean().optional()}).optional(),tasks:sp.optional(),extensions:O.record(O.string(),Nf).optional()}),fp=Wf.extend({protocolVersion:O.string(),capabilities:dp,serverInfo:rp,instructions:O.string().optional()}),pp=Uf.extend({method:O.literal(`notifications/initialized`),params:Hf.optional()}),mp=Vf.extend({method:O.literal(`ping`),params:zf.optional()}),hp=O.object({progress:O.number(),total:O.optional(O.number()),message:O.optional(O.string())}),gp=O.object({...Hf.shape,...hp.shape,progressToken:Pf}),_p=Uf.extend({method:O.literal(`notifications/progress`),params:gp}),vp=zf.extend({cursor:Ff.optional()}),yp=Vf.extend({params:vp.optional()}),bp=Wf.extend({nextCursor:Ff.optional()}),xp=O.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Sp=O.object({taskId:O.string(),status:xp,ttl:O.union([O.number(),O.null()]),createdAt:O.string(),lastUpdatedAt:O.string(),pollInterval:O.optional(O.number()),statusMessage:O.optional(O.string())}),Cp=Wf.extend({task:Sp}),wp=Hf.merge(Sp),Tp=Uf.extend({method:O.literal(`notifications/tasks/status`),params:wp}),Ep=Vf.extend({method:O.literal(`tasks/get`),params:zf.extend({taskId:O.string()})}),Dp=Wf.merge(Sp),Op=Vf.extend({method:O.literal(`tasks/result`),params:zf.extend({taskId:O.string()})}),kp=Wf.loose(),Ap=yp.extend({method:O.literal(`tasks/list`)}),jp=bp.extend({tasks:O.array(Sp)}),Mp=Vf.extend({method:O.literal(`tasks/cancel`),params:zf.extend({taskId:O.string()})}),Np=Wf.merge(Sp),Pp=O.object({uri:O.string(),mimeType:O.optional(O.string()),_meta:O.record(O.string(),O.unknown()).optional()}),Fp=Pp.extend({text:O.string()}),Ip=O.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Lp=Pp.extend({blob:Ip}),Rp=O.enum([`user`,`assistant`]),zp=O.object({audience:O.array(Rp).optional(),priority:O.number().min(0).max(1).optional(),lastModified:O.iso.datetime({offset:!0}).optional()}),Bp=O.object({...np.shape,...tp.shape,uri:O.string(),description:O.optional(O.string()),mimeType:O.optional(O.string()),size:O.optional(O.number()),annotations:zp.optional(),_meta:O.optional(O.looseObject({}))}),Vp=O.object({...np.shape,...tp.shape,uriTemplate:O.string(),description:O.optional(O.string()),mimeType:O.optional(O.string()),annotations:zp.optional(),_meta:O.optional(O.looseObject({}))}),Hp=yp.extend({method:O.literal(`resources/list`)}),Up=bp.extend({resources:O.array(Bp)}),Wp=yp.extend({method:O.literal(`resources/templates/list`)}),Gp=bp.extend({resourceTemplates:O.array(Vp)}),Kp=zf.extend({uri:O.string()}),qp=Kp,Jp=Vf.extend({method:O.literal(`resources/read`),params:qp}),Yp=Wf.extend({contents:O.array(O.union([Fp,Lp]))}),Xp=Uf.extend({method:O.literal(`notifications/resources/list_changed`),params:Hf.optional()}),Zp=Kp,Qp=Vf.extend({method:O.literal(`resources/subscribe`),params:Zp}),$p=Kp,em=Vf.extend({method:O.literal(`resources/unsubscribe`),params:$p}),tm=Hf.extend({uri:O.string()}),nm=Uf.extend({method:O.literal(`notifications/resources/updated`),params:tm}),rm=O.object({name:O.string(),description:O.optional(O.string()),required:O.optional(O.boolean())}),im=O.object({...np.shape,...tp.shape,description:O.optional(O.string()),arguments:O.optional(O.array(rm)),_meta:O.optional(O.looseObject({}))}),am=yp.extend({method:O.literal(`prompts/list`)}),om=bp.extend({prompts:O.array(im)}),sm=zf.extend({name:O.string(),arguments:O.record(O.string(),O.string()).optional()}),cm=Vf.extend({method:O.literal(`prompts/get`),params:sm}),lm=O.object({type:O.literal(`text`),text:O.string(),annotations:zp.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),um=O.object({type:O.literal(`image`),data:Ip,mimeType:O.string(),annotations:zp.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),dm=O.object({type:O.literal(`audio`),data:Ip,mimeType:O.string(),annotations:zp.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),fm=O.object({type:O.literal(`tool_use`),name:O.string(),id:O.string(),input:O.record(O.string(),O.unknown()),_meta:O.record(O.string(),O.unknown()).optional()}),pm=O.object({type:O.literal(`resource`),resource:O.union([Fp,Lp]),annotations:zp.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),mm=Bp.extend({type:O.literal(`resource_link`)}),hm=O.union([lm,um,dm,mm,pm]),gm=O.object({role:Rp,content:hm}),_m=Wf.extend({description:O.string().optional(),messages:O.array(gm)}),vm=Uf.extend({method:O.literal(`notifications/prompts/list_changed`),params:Hf.optional()}),ym=O.object({title:O.string().optional(),readOnlyHint:O.boolean().optional(),destructiveHint:O.boolean().optional(),idempotentHint:O.boolean().optional(),openWorldHint:O.boolean().optional()}),bm=O.object({taskSupport:O.enum([`required`,`optional`,`forbidden`]).optional()}),xm=O.object({...np.shape,...tp.shape,description:O.string().optional(),inputSchema:O.object({type:O.literal(`object`),properties:O.record(O.string(),Mf).optional(),required:O.array(O.string()).optional()}).catchall(O.unknown()),outputSchema:O.object({type:O.literal(`object`),properties:O.record(O.string(),Mf).optional(),required:O.array(O.string()).optional()}).catchall(O.unknown()).optional(),annotations:ym.optional(),execution:bm.optional(),_meta:O.record(O.string(),O.unknown()).optional()}),Sm=yp.extend({method:O.literal(`tools/list`)}),Cm=bp.extend({tools:O.array(xm)}),wm=Wf.extend({content:O.array(hm).default([]),structuredContent:O.record(O.string(),O.unknown()).optional(),isError:O.boolean().optional()}),wm.or(Wf.extend({toolResult:O.unknown()})),Tm=Bf.extend({name:O.string(),arguments:O.record(O.string(),O.unknown()).optional()}),Em=Vf.extend({method:O.literal(`tools/call`),params:Tm}),Dm=Uf.extend({method:O.literal(`notifications/tools/list_changed`),params:Hf.optional()}),O.object({autoRefresh:O.boolean().default(!0),debounceMs:O.number().int().nonnegative().default(300)}),Om=O.enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),km=zf.extend({level:Om}),Am=Vf.extend({method:O.literal(`logging/setLevel`),params:km}),jm=Hf.extend({level:Om,logger:O.string().optional(),data:O.unknown()}),Mm=Uf.extend({method:O.literal(`notifications/message`),params:jm}),Nm=O.object({name:O.string().optional()}),Pm=O.object({hints:O.array(Nm).optional(),costPriority:O.number().min(0).max(1).optional(),speedPriority:O.number().min(0).max(1).optional(),intelligencePriority:O.number().min(0).max(1).optional()}),Fm=O.object({mode:O.enum([`auto`,`required`,`none`]).optional()}),Im=O.object({type:O.literal(`tool_result`),toolUseId:O.string().describe(`The unique identifier for the corresponding tool call.`),content:O.array(hm).default([]),structuredContent:O.object({}).loose().optional(),isError:O.boolean().optional(),_meta:O.record(O.string(),O.unknown()).optional()}),Lm=O.discriminatedUnion(`type`,[lm,um,dm]),Rm=O.discriminatedUnion(`type`,[lm,um,dm,fm,Im]),zm=O.object({role:Rp,content:O.union([Rm,O.array(Rm)]),_meta:O.record(O.string(),O.unknown()).optional()}),Bm=Bf.extend({messages:O.array(zm),modelPreferences:Pm.optional(),systemPrompt:O.string().optional(),includeContext:O.enum([`none`,`thisServer`,`allServers`]).optional(),temperature:O.number().optional(),maxTokens:O.number().int(),stopSequences:O.array(O.string()).optional(),metadata:Nf.optional(),tools:O.array(xm).optional(),toolChoice:Fm.optional()}),Vm=Vf.extend({method:O.literal(`sampling/createMessage`),params:Bm}),Hm=Wf.extend({model:O.string(),stopReason:O.optional(O.enum([`endTurn`,`stopSequence`,`maxTokens`]).or(O.string())),role:Rp,content:Lm}),Um=Wf.extend({model:O.string(),stopReason:O.optional(O.enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(O.string())),role:Rp,content:O.union([Rm,O.array(Rm)])}),Wm=O.object({type:O.literal(`boolean`),title:O.string().optional(),description:O.string().optional(),default:O.boolean().optional()}),Gm=O.object({type:O.literal(`string`),title:O.string().optional(),description:O.string().optional(),minLength:O.number().optional(),maxLength:O.number().optional(),format:O.enum([`email`,`uri`,`date`,`date-time`]).optional(),default:O.string().optional()}),Km=O.object({type:O.enum([`number`,`integer`]),title:O.string().optional(),description:O.string().optional(),minimum:O.number().optional(),maximum:O.number().optional(),default:O.number().optional()}),qm=O.object({type:O.literal(`string`),title:O.string().optional(),description:O.string().optional(),enum:O.array(O.string()),default:O.string().optional()}),Jm=O.object({type:O.literal(`string`),title:O.string().optional(),description:O.string().optional(),oneOf:O.array(O.object({const:O.string(),title:O.string()})),default:O.string().optional()}),Ym=O.object({type:O.literal(`string`),title:O.string().optional(),description:O.string().optional(),enum:O.array(O.string()),enumNames:O.array(O.string()).optional(),default:O.string().optional()}),Xm=O.union([qm,Jm]),Zm=O.object({type:O.literal(`array`),title:O.string().optional(),description:O.string().optional(),minItems:O.number().optional(),maxItems:O.number().optional(),items:O.object({type:O.literal(`string`),enum:O.array(O.string())}),default:O.array(O.string()).optional()}),Qm=O.object({type:O.literal(`array`),title:O.string().optional(),description:O.string().optional(),minItems:O.number().optional(),maxItems:O.number().optional(),items:O.object({anyOf:O.array(O.object({const:O.string(),title:O.string()}))}),default:O.array(O.string()).optional()}),$m=O.union([Zm,Qm]),eh=O.union([Ym,Xm,$m]),th=O.union([eh,Wm,Gm,Km]),nh=Bf.extend({mode:O.literal(`form`).optional(),message:O.string(),requestedSchema:O.object({type:O.literal(`object`),properties:O.record(O.string(),th),required:O.array(O.string()).optional()})}),rh=Bf.extend({mode:O.literal(`url`),message:O.string(),elicitationId:O.string(),url:O.string().url()}),ih=O.union([nh,rh]),ah=Vf.extend({method:O.literal(`elicitation/create`),params:ih}),oh=Hf.extend({elicitationId:O.string()}),sh=Uf.extend({method:O.literal(`notifications/elicitation/complete`),params:oh}),ch=Wf.extend({action:O.enum([`accept`,`decline`,`cancel`]),content:O.preprocess(e=>e===null?void 0:e,O.record(O.string(),O.union([O.string(),O.number(),O.boolean(),O.array(O.string())])).optional())}),lh=O.object({type:O.literal(`ref/resource`),uri:O.string()}),uh=O.object({type:O.literal(`ref/prompt`),name:O.string()}),dh=zf.extend({ref:O.union([uh,lh]),argument:O.object({name:O.string(),value:O.string()}),context:O.object({arguments:O.record(O.string(),O.string()).optional()}).optional()}),fh=Vf.extend({method:O.literal(`completion/complete`),params:dh}),ph=Wf.extend({completion:O.looseObject({values:O.array(O.string()).max(100),total:O.optional(O.number().int()),hasMore:O.optional(O.boolean())})}),mh=O.object({uri:O.string().startsWith(`file://`),name:O.string().optional(),_meta:O.record(O.string(),O.unknown()).optional()}),hh=Vf.extend({method:O.literal(`roots/list`),params:zf.optional()}),gh=Wf.extend({roots:O.array(mh)}),_h=Uf.extend({method:O.literal(`notifications/roots/list_changed`),params:Hf.optional()}),vh=O.union([mp,up,fh,Am,cm,am,Hp,Wp,Jp,Qp,em,Em,Sm,Ep,Op,Ap,Mp]),yh=O.union([$f,_p,pp,_h,Tp]),O.union([Zf,Hm,Um,ch,gh,Dp,jp,Cp]),bh=O.union([mp,Vm,ah,hh,Ep,Op,Ap,Mp]),xh=O.union([$f,_p,Mm,nm,Xp,Dm,vm,Tp,sh]),O.union([Zf,fp,ph,_m,om,Up,Gp,Yp,wm,Cm,Dp,jp,Cp]),Sh={ping:Zf,initialize:fp,"completion/complete":ph,"logging/setLevel":Zf,"prompts/get":_m,"prompts/list":om,"resources/list":Up,"resources/templates/list":Gp,"resources/read":Yp,"resources/subscribe":Zf,"resources/unsubscribe":Zf,"tools/call":O.union([wm,Cp]),"tools/list":Cm,"sampling/createMessage":O.union([Um,Cp]),"elicitation/create":O.union([ch,Cp]),"roots/list":gh,"tasks/get":Dp,"tasks/result":Wf,"tasks/list":jp,"tasks/cancel":Np},Ch=Nd([...vh.options,...bh.options]),wh=Nd([...yh.options,...xh.options]),Th=e=>Kf.safeParse(e).success,Eh=e=>qf.safeParse(e).success,Dh=e=>Jf.safeParse(e).success,Oh=e=>Yf.safeParse(e).success,kh=e=>Bf.safeParse(e).success,Ah=e=>up.safeParse(e).success,jh=e=>pp.safeParse(e).success,Mh=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,Cp,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},Bd(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},Dp,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},jp,t)}async cancelTask(e,t){return this._requireHost.request({method:`tasks/cancel`,params:e},Np,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(!Bd(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,[Tf]:{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(Bd(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,[Tf]: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)?.[Tf]?.taskId,r=kh(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),Dh(e)?n(e):n(new U(e.error.code,e.error.message,e.error.data)),!0):!1}shouldPreserveProgressHandler(e,t){if(Dh(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,[Tf]: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(Oh(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=Tp.parse({method:`notifications/tasks/status`,params:o});await r?.notification(t),Bd(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(Bd(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=Tp.parse({method:`notifications/tasks/status`,params:s});await r?.notification(t),Bd(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,[Tf]: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`&&Th(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))}},Nh=class extends Mh{constructor(){super({})}processInboundRequest(e,t){let n=kh(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`}}}},Ph=6e4,Fh=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??wf,this._taskManager=e?.tasks?new Mh(e.tasks):new Nh,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=Pd(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),Dh(e)||Oh(e)?this._onresponse(e):Th(e)?this._onrequest(e,t):Eh(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,Md(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),Dh(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=Md(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=zd(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=Pd(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=Fd(e);this._notificationHandlers.set(e,e=>{let r=n.parse(e);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}},Ih=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 Kd(t)}catch(e){if(e instanceof SyntaxError)continue;throw e}}return null}clear(){this._buffer=void 0}},Lh=/^[A-Za-z0-9._-]{1,128}$/,Rh=1e6,zh=1e6,Bh=1e4,Vh=1e6,Hh=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,Rh,`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>Bh)throw Error(`Template contains too many expressions (max ${Bh})`);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,zh,`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,zh,`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,zh,`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,Rh,`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,Vh,`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}},Uh=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})),Wh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Uh();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=Uh(),n=Wh();var r=Uh();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=Wh();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=O(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=O(this.rhs,e,n),this}get names(){return D(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=O(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(k(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>ee(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(A(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=O(this.condition,e,t),this}get names(){let e=super.names;return D(e,this.condition),this.else&&ee(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=O(this.iteration,e,t),this}get names(){return ee(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return D(D(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=O(this.iterable,e,t),this}get names(){return ee(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&ee(e,this.catch.names),this.finally&&ee(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var E=class extends m{render(e){return`finally`+super.render(e)}};E.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
177
+ `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new E,this.code(n)),this._endBlockNode(T,E)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function ee(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function D(e,n){return n instanceof t._CodeOrName?ee(e,n.names):e}function O(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function k(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function A(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ie(e)}`}e.not=A;let te=M(e.operators.AND);function ne(...e){return e.reduce(te)}e.and=ne;let j=M(e.operators.OR);function re(...e){return e.reduce(j)}e.or=re;function M(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ie(n)} ${e} ${ie(r)}`}function ie(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=Uh();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})),Gh=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`)}})),Kh=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=Gh();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),qh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Kh(),n=W(),r=Gh(),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)}})),Jh=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})),Yh=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})),Xh=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=Jh(),n=Yh(),r=Kh(),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}}})),Xh=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)}`)}})),Zh=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=Wh(),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=Wh(),r=Zh(),i=Gh();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})),$h=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})),eg=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}})),tg=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`)}})),ng=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=eg(),r=tg(),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})),rg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Kh(),n=Yh(),r=Jh(),i=Yh(),a=Xh(),o=Qh(),s=$h(),c=W(),l=Wh(),u=ng(),d=G(),f=Gh();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&O(e),te(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),k(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&O(e),E(e),D(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),ee(e)}function T(e,t){if(e.opts.jtd)return A(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);A(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function ee(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function te(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function E(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function D(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function O({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function k(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&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 A(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(()=>P(e,`$ref`,h.all.$ref.definition));return}p.jtd||M(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),j(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):j(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function j(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&P(e,n.keyword,n.definition,t.type)})}function M(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(re(e,t),e.opts.allowUnionTypes||ie(e,t),ae(e,e.dataTypes))}function re(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{se(e.dataTypes,t)||ce(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),N(e,t)}}function ie(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ce(e,`use allowUnionTypes to allow union type keyword`)}function ae(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>oe(t,e))&&ce(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function oe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function se(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function N(e,t){let n=[];for(let r of e.dataTypes)se(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ce(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var le=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,fe(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=le;function P(e,t,n,r){let i=new le(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let ue=/^\/(?:[^~]|~0|~1)*$/,de=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function fe(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!ue.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=de.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=fe})),ig=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}}})),ag=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ng();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))}}})),og=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=W(),n=ig(),r=Wh(),i=ng(),a=G(),o=rg();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}})),sg=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}})),cg=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}})),lg=z(((e,t)=>{let{isUUID:n}=cg(),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}})),ug=z(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=cg(),{SCHEMES:c,getSchemeHandler:l}=lg();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=_})),dg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ug();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),fg=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=rg();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=ig(),i=ag(),a=qh(),o=og(),s=W(),c=ng(),l=Yh(),u=G(),d=sg(),f=dg(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=te(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(D.call(this,n,t),!t)return(0,u.eachItem)(n,e=>O.call(this,e)),this;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=>O.call(this,e,r):e=>r.type.forEach(t=>O.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=j(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let ee={log(){},warn(){},error(){}};function te(e){if(e===!1)return ee;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let E=/^[a-z_$][a-z0-9_$:-]*$/i;function D(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!E.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function O(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?k.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function k(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function ne(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=j(t)),e.validateSchema=this.compile(t,!0))}let A={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function j(e){return{anyOf:[e,A]}}})),pg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),mg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=ag(),n=Zh(),r=W(),i=Wh(),a=og(),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})),hg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=pg(),n=mg();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),gg=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})`)}}})),_g=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}))`)}}})),vg=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`})),yg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=vg();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}`)}}})),bg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Zh(),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})`)}}}})),xg=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}`)}}})),Sg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Zh(),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)}}}})),Cg=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}`)}}})),wg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=eg();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),Tg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Yh(),n=W(),r=G(),i=wg();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)})))}}}})),Eg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=wg();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}`)}}})),Dg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=wg();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}`}}}})),Og=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=gg(),n=_g(),r=yg(),i=bg(),a=xg(),o=Sg(),s=Cg(),c=Tg(),l=Eg(),u=Dg();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]})),kg=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})),Ag=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=W(),n=G(),r=Zh(),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})),jg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ag();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Mg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=Zh(),i=kg();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)))}}})),Ng=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)))}}}})),Pg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=W(),n=G(),r=Zh();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}}})),Zh=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=Gh(),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})),$h=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=W(),n=Gh(),r=Qh(),i=Kh();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})),eg=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})),tg=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}})),ng=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`)}})),rg=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=tg(),r=ng(),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})),ig=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=qh(),n=Xh(),r=Yh(),i=Xh(),a=Zh(),o=$h(),s=eg(),c=W(),l=Gh(),u=rg(),d=G(),f=Kh();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&k(e),ee(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),A(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&k(e),D(e),O(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),E(e)}function T(e,t){if(e.opts.jtd)return ne(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);ne(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function E(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function ee(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function D(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function O(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function k({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function A(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&te(e),t.return((0,c._)`${l.default.errors} === 0`))}function te({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function ne(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>ue(e,`$ref`,h.all.$ref.definition));return}p.jtd||re(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),j(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):j(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function j(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&ue(e,n.keyword,n.definition,t.type)})}function re(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(M(e,t),e.opts.allowUnionTypes||ie(e,t),ae(e,e.dataTypes))}function M(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{se(e.dataTypes,t)||ce(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),N(e,t)}}function ie(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ce(e,`use allowUnionTypes to allow union type keyword`)}function ae(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>oe(t,e))&&ce(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function oe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function se(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function N(e,t){let n=[];for(let r of e.dataTypes)se(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ce(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var le=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,pe(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=le;function ue(e,t,n,r){let i=new le(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let de=/^\/(?:[^~]|~0|~1)*$/,fe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function pe(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!de.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=fe.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=pe})),ag=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}}})),og=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rg();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))}}})),sg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=W(),n=ag(),r=Gh(),i=rg(),a=G(),o=ig();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}})),cg=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}})),lg=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}})),ug=z(((e,t)=>{let{isUUID:n}=lg(),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}})),dg=z(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=lg(),{SCHEMES:c,getSchemeHandler:l}=ug();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=_})),fg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=dg();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),pg=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=ig();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=ag(),i=og(),a=Jh(),o=sg(),s=W(),c=rg(),l=Xh(),u=G(),d=cg(),f=fg(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=ee(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(O.call(this,n,t),!t)return(0,u.eachItem)(n,e=>k.call(this,e)),this;te.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>k.call(this,e,r):e=>r.type.forEach(t=>k.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=j(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let E={log(){},warn(){},error(){}};function ee(e){if(e===!1)return E;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let D=/^[a-z_$][a-z0-9_$:-]*$/i;function O(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!D.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function k(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?A.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function A(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function te(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=j(t)),e.validateSchema=this.compile(t,!0))}let ne={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function j(e){return{anyOf:[e,ne]}}})),mg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),hg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=og(),n=Qh(),r=W(),i=Gh(),a=sg(),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})),gg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=mg(),n=hg();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),_g=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})`)}}})),vg=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}))`)}}})),yg=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`})),bg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=yg();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}`)}}})),xg=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})`)}}}})),Sg=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}`)}}})),Cg=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)}}}})),wg=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}`)}}})),Tg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=tg();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),Eg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Xh(),n=W(),r=G(),i=Tg();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)})))}}}})),Dg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=Tg();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}`)}}})),Og=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=Tg();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}`}}}})),kg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=_g(),n=vg(),r=bg(),i=xg(),a=Sg(),o=Cg(),s=wg(),c=Eg(),l=Dg(),u=Og();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]})),Ag=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})),jg=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})),Mg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=jg();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Ng=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=Qh(),i=Ag();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)))}}})),Pg=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)))}}}})),Fg=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})),Fg=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)}}})),Ig=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Zh(),n=W(),r=Wh(),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)}}}})),Lg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rg(),n=Zh(),r=G(),i=Ig();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)}}}})),Rg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Zh(),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())})})}}}})),zg=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`}}})),Bg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Zh().validateUnion,error:{message:`must match a schema in anyOf`}}})),Vg=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)})})}}}})),Hg=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)})}}})),Ug=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})),Wg=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`)}}})),Gg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=kg(),n=jg(),r=Ag(),i=Mg(),a=Ng(),o=Pg(),s=Fg(),c=Ig(),l=Lg(),u=Rg(),d=zg(),f=Bg(),p=Vg(),m=Hg(),h=Ug(),g=Wg();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=_})),Kg=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})`}}}}})),qg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Kg().default]})),Jg=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`]})),Yg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=hg(),n=Og(),r=Gg(),i=qg(),a=Jg();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Xg=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={}))})),Zg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=Xg(),r=og(),i=ag(),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}})),$g=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=fg(),r=Yg(),i=Zg(),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=rg();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=ig();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=ag();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),e_=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}}})),t_=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=$g(),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)})),n_=z(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=e_(),r=t_(),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})),r_=$g(),i_=ff(n_(),1),a_=class{_ajv;constructor(e){this._ajv=e??nf()}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)}}},o_=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft??`2020-12`}getValidator(e){let t=new Td(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 c_(){throw Error(`StdioServerTransport is not supported in this environment. Use StreamableHTTPServerTransport instead.`)}var l_,u_=I((()=>{s_(),l_={get stdin(){return c_()},get stdout(){return c_()}}})),d_=tt({AjvJsonSchemaValidator:()=>a_,CfWorkerJsonSchemaValidator:()=>o_,DEFAULT_NEGOTIATED_PROTOCOL_VERSION:()=>Sf,DEFAULT_REQUEST_TIMEOUT_MSEC:()=>Nh,ExperimentalMcpServerTasks:()=>A_,ExperimentalServerTasks:()=>j_,INTERNAL_ERROR:()=>kf,INVALID_PARAMS:()=>Of,INVALID_REQUEST:()=>Ef,InMemoryTaskMessageQueue:()=>k_,InMemoryTaskStore:()=>O_,JSONRPC_VERSION:()=>`2.0`,LATEST_PROTOCOL_VERSION:()=>xf,METHOD_NOT_FOUND:()=>Df,McpServer:()=>N_,OAuthError:()=>mf,OAuthErrorCode:()=>pf,PARSE_ERROR:()=>Tf,ProtocolError:()=>U,ProtocolErrorCode:()=>H,RELATED_TASK_META_KEY:()=>wf,ReadBuffer:()=>Fh,ResourceTemplate:()=>P_,SUPPORTED_PROTOCOL_VERSIONS:()=>Cf,SdkError:()=>V,SdkErrorCode:()=>B,Server:()=>M_,StdioServerTransport:()=>L_,UriTemplate:()=>Vh,UrlElicitationRequiredError:()=>Af,WebStandardStreamableHTTPServerTransport:()=>R_,assertClientRequestTaskCapability:()=>g_,assertCompleteRequestPrompt:()=>Id,assertCompleteRequestResourceTemplate:()=>Ld,assertToolsCallTaskCapability:()=>h_,checkResourceAllowed:()=>kd,completable:()=>f_,createFetchWithInit:()=>Zd,deserializeMessage:()=>Gd,fromJsonSchema:()=>E_,getDisplayName:()=>Ad,hostHeaderValidationResponse:()=>T_,isCompletable:()=>p_,isInitializeRequest:()=>kh,isInitializedNotification:()=>Ah,isJSONRPCErrorResponse:()=>Dh,isJSONRPCNotification:()=>Th,isJSONRPCRequest:()=>wh,isJSONRPCResultResponse:()=>Eh,isTaskAugmentedRequestParams:()=>Oh,isTerminal:()=>zd,localhostAllowedHostnames:()=>w_,parseJSONRPCMessage:()=>Fd,resourceUrlFromServerUrl:()=>Od,serializeMessage:()=>Kd,takeResult:()=>Wd,toArrayAsync:()=>Ud,validateHostHeader:()=>C_});function f_(e,t){return Object.defineProperty(e,D_,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function p_(e){return!!e&&typeof e==`object`&&D_ in e}function m_(e){return e[D_]?.complete}function h_(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 g_(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 __(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 v_(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await ef(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 y_(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}function b_(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function x_(e){return e?.type===`optional`}function S_(e){return x_(e)?e.def?.innerType??e:e}function C_(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 w_(){return[`localhost`,`127.0.0.1`,`[::1]`]}function T_(e,t){let n=C_(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 E_(e,t){return rf(e,t??(z_??=new o_))}var D_,O_,k_,A_,j_,M_,N_,P_,F_,I_,L_,R_,z_,B_=I((()=>{s_(),u_(),D_=Symbol.for(`mcp.completable`),O_=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(zd(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(zd(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(),zd(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}))}},k_=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}},A_=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)}},j_=class{constructor(e){this._server=e}get _module(){return this._server.taskManager}requestStream(e,t){let n=jd(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},Op,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)}},M_=class extends Ph{_clientCapabilities;_clientVersion;_capabilities;_instructions;_jsonSchemaValidator;_experimental;oninitialized;constructor(e,t){if(super({...t,tasks:Bd(t?.capabilities?.tasks)}),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new o_,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=Rd(Dm,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 j_(this)},this._experimental}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Dm.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=Hd(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}setRequestHandler(e,t){return e===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=Rd(Tm,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=Rd(Sp,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=Rd(Cm,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){g_(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){h_(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`},Xf)}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},Hm,t):this._requestWithSchema({method:`sampling/createMessage`,params:e},Vm,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},sh,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},sh,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},hh,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`})}},N_=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_experimental;constructor(e,t){this.server=new M_(e,t)}get experimental(){return this._experimental||={tasks:new A_(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`):F_,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 ef(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 ef(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 Id(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Ld(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 I_;let r=S_(b_(n.argsSchema)?.[e.params.argument.name]);if(!p_(r))return I_;let i=m_(r);return i?y_(await i(e.params.argument.value,e.params.context)):I_}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 I_;throw new U(H.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?y_(await r(e.params.argument.value,e.params.context)):I_}_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?tf(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:v_(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=v_(e,o,s)),t.enabled!==void 0&&(c.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=c,r){let e=b_(r);e&&Object.values(e).some(e=>p_(S_(e)))&&this.setCompletionRequestHandler()}return c}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Yd(e);let l=c,u={title:t,description:n,inputSchema:r,outputSchema:i,annotations:a,execution:o,_meta:s,handler:c,executor:__(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`&&Yd(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=__(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()}},P_=class{_uriTemplate;constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new Vh(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},F_={type:`object`,properties:{}},I_={completion:{values:[],hasMore:!1}},L_=class{_readBuffer=new Fh;_started=!1;_closed=!1;constructor(e=l_.stdin,t=l_.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=Kd(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)})}},R_=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??Cf}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=>Yf.parse(e)):[Yf.parse(a)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let s=o.some(e=>kh(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=>wh(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=>kh(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)wh(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)wh(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;wh(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((Eh(e)||Dh(e))&&(n=e.id),n===void 0){if(Eh(e)||Dh(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(Eh(e)||Dh(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 V_(e,t,n,r={}){let i=U_(),a=await Promise.resolve().then(()=>(B_(),d_)),{fromJsonSchema:o,McpServer:s}=a,c=await H_(a,i),l=new s({name:e,...r.title?{title:r.title}:void 0,version:t},r.instructions?{instructions:r.instructions}:void 0);G_(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 H_(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 U_(){return Promise.resolve().then(()=>(B_(),d_)).then(e=>({module:e})).catch(e=>({error:e}))}async function W_(e,t,n={}){let r=[...n.middlewares??[],...e.middlewares??[],...e.command.middleware??[]],i=await Xl(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:Vr(a)}})}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}return{content:[{type:`text`,text:Vr(e)}]}}if(!i.ok){let t=xu(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${Su(t)}`:r}],...t?{_meta:{cta:t}}:void 0,isError:!0}}let a=i.data??null,o=Hr(a),s=xu(n.name??e.name,i.cta),c=Vr(o);return{content:[{type:`text`,text:s?`${c}\n\n${Su(s)}`:c}],...a!==null&&e.outputSchema?{structuredContent:o}:void 0,...s?{_meta:{cta:s}}:void 0}}function G_(e,t,n){let r=ev(t,[],[],n.tools);if(r.length!==0){if((n.tools?.discovery??`progressive`)===`direct`){for(let t of r)K_(e,t,n);return}q_(e,r,n)}}function K_(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)=>W_(t,i?e[0]:{},J_(n,i?e[1]:e[0])))}function q_(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:lv},async e=>{let n=Y_(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:lv},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}):$_(`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:cv,annotations:uv},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?W_(i,e.arguments,J_(n,t)):$_(`Tool is not read-only: ${e.name}`):$_(`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:cv,annotations:dv},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?$_(`Tool is read-only: ${e.name}`):W_(i,e.arguments,J_(n,t)):$_(`Unknown tool: ${e.name}`)})}function J_(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 Y_(e,t){let n=Z_(t),r=n.split(` `).filter(Boolean);return e.map(e=>({tool:e,score:X_(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 X_(e,t,n){let r=Z_(e.name),i=Z_(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 Z_(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,` `).trim()}function Q_(e){return{content:[{type:`text`,text:Vr(e)}]}}function $_(e){return{...Q_({error:e}),isError:!0}}function ev(e,t,n=[],r){let i=rv(tv(e,t,n),r);return av(i),i.sort((e,t)=>e.name.localeCompare(t.name))}function tv(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(nv(a.root,e,t)),r.push(...tv(a.commands,e,t))}else r.push(nv(a,e,n))}return r}function nv(e,t,n){let r=e.mcp===!1?void 0:e.mcp,i=e.output?ov(e.output):void 0;return{name:r?.name??t.join(`_`),description:r?.description??e.description,inputSchema:sv(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 rv(e,t){if(!t)return e;let n=t.include?.map(iv),r=t.exclude?.map(iv)??[];return e.filter(e=>r.some(t=>t.test(e.name))?!1:!n||n.length===0||n.some(t=>t.test(e.name)))}function iv(e){let t=e.replace(/[|\\{}()[\]^$+?.]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function av(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 ov(e){let t=Nu(e);if(t.type===`object`)return t}function sv(e,t){let n={},r=[];for(let i of[e,t]){if(!i)continue;let e=Nu(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 cv,lv,uv,dv,fv=I((()=>{ou(),wu(),Ur(),Pu(),cv=f.object({name:f.string().min(1).describe(`Exact tool name.`),arguments:f.record(f.string(),f.unknown()).default({}).describe(`Arguments from its schema.`)}),lv={destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},uv={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},dv={destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1}}));function pv(e){return mv(e,e,new Map)}function mv(e,t,n){if(Array.isArray(e))return e.map(e=>mv(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=hv(t,e);if(typeof i!=`object`||!i||Array.isArray(i)){let r=mv(i,t,n);return n.set(e,r),r}let a={};n.set(e,a);let o=mv(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]=mv(r[e],t,n);return i}function hv(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 gv=I((()=>{}));function _v(e,t={}){let n=xx.get(e);if(!n)throw Error(`No commands registered on this CLI instance`);let r={},i=wx.get(e);i&&bv(r,[],i);for(let[e,t]of n)vv(r,yv(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 vv(e,t,n){if(!(`_alias`in n)&&!(`_fetch`in n)){if(`_group`in n){n.root&&bv(e,t,n.root);for(let[r,i]of n.commands)vv(e,[...t,...yv(r)],i);return}bv(e,t,n)}}function yv(e){return e.split(/\s+/).filter(Boolean)}function bv(e,t,n){let r=n.args?Nu(n.args):void 0,i=n.options?Nu(n.options):void 0,a=n.output?Nu(n.output):void 0,o=Ov(r),s=new Set(kv(r)),c=Sv(t),l=xv(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(Ov(i)))s.push({name:e,in:`query`,...kv(i).includes(e)?{required:!0}:void 0,schema:t});let l={operationId:Av(t,c,r.args),...n.description?{summary:n.description}:void 0,...s.length?{parameters:s}:void 0,...wv(c,i),responses:Tv(a)},u=e[r.path]??{};u[c]=l,e[r.path]=u}}function xv(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(jv).join(`/`)}`})}return o.length===0&&o.push({args:[],path:`/${e.map(jv).join(`/`)}`}),o}function Sv(e){let t=e.map(Cv).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 Cv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`)}function wv(e,t){return!t||e===`get`||e===`delete`?{}:{requestBody:{required:kv(t).length>0,content:{"application/json":{schema:t}}}}}function Tv(e){return{200:{description:`Command completed successfully.`,content:{"application/json":{schema:{type:`object`,required:[`ok`,`data`,`meta`],properties:{ok:{const:!0},data:e??{},meta:Dv()}}}}},400:Ev(`Validation error.`),500:Ev(`Command failed.`)}}function Ev(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:Dv()}}}}}}function Dv(){return{type:`object`,required:[`command`,`duration`],properties:{command:{type:`string`},duration:{type:`string`}}}}function Ov(e){return e?.properties??{}}function kv(e){return e?.required??[]}function Av(e,t,n){return`${t}${[...e,...n.length?[n.join(` `)]:[]].join(` `).replace(/(?:^|[\s_-]+)(\w)/g,(e,t)=>t.toUpperCase())}`}function jv(e){return e.startsWith(`{`)&&e.endsWith(`}`)?e:encodeURIComponent(e)}async function Mv(e,t={}){if(typeof e!=`string`&&!(e instanceof URL))return e;let n=await fetch(Nv(e,t.baseUrl));if(!n.ok)throw Error(`Failed to fetch OpenAPI spec from ${e}: ${n.status}`);return await n.json()}function Nv(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 Pv(e,t,n={}){let r=pv(structuredClone(e)),i=new Map,a=Iv(r.paths??{}),o=Wv(a),{config:s}=n;s?.compact&&zv(a);for(let{method:e,operation:c,path:l}of a){let a=Gv({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=Hv([...(c.parameters??[]).filter(e=>e.in===`header`),...s?.security===!1?[]:Lv(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?ty(t.schema):f.string();t.description&&(n=n.describe(t.description)),e[t.name]=ny(n)}v=f.object(e)}let y={},b=new Set;for(let e of p){let t=e.schema?ty(e.schema):f.string();e.required||(t=t.optional()),e.description&&(t=t.describe(e.description)),y[e.name]=ny(t),b.add(e.name)}for(let[e,t]of Object.entries(g)){let n=ty(t);_.has(e)||(n=n.optional()),y[e]=n,b.add(e)}for(let e of m){let t=Uv(e.optionName,b);e.optionName=t;let n=e.schema?ty(e.schema):f.string();e.required||(n=n.optional()),n=n.describe(e.description??`${e.name} header`),y[t]=ny(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:Fv(e),...c.summary&&c.description&&c.summary!==c.description?{description:`${c.summary}\n\n${c.description}`}:void 0},args:v,options:x,run:ey({basePath:n.basePath,fetch:t,forwardHeaders:s?.forwardHeaders,httpMethod:u,path:l,headerParams:m,pathParams:d,queryParams:p,bodyProps:g})})}return i}function Fv(e){let t=[`get`,`head`,`options`,`trace`].includes(e);return{destructiveHint:!t,idempotentHint:t||e===`delete`||e===`put`,openWorldHint:!0,readOnlyHint:t}}function Iv(e){let t=[];for(let[n,r]of Object.entries(e))for(let[e,i]of Object.entries(r))ry.has(e)&&t.push({method:e,operation:i,path:n});return t}function Lv(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=Rv(t,e);r&&i.push(r)}return i}function Rv(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`&&iy.has(t.scheme?.toLowerCase()??``))return{description:t.description??`${e} authorization header`,in:`header`,name:`authorization`,required:!1,schema:{type:`string`}}}}function zv(e){for(let{operation:t}of e){for(let e of t.parameters??[])e.schema&&=Bv(e.schema);let e=t.requestBody?.content?.[`application/json`];e?.schema&&(e.schema=Bv(e.schema))}}function Bv(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>ay&&delete r.pattern,typeof r.format==`string`&&oy.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=>Bv(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];Vv(n)&&(r[e]=Bv(n,t))}for(let e of[`$defs`,`patternProperties`,`properties`]){let n=r[e];if(!Vv(n))continue;let i={};for(let[e,r]of Object.entries(n))i[e]=Vv(r)?Bv(r,t):r;r[e]=i}return r}function Vv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Hv(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 Uv(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 Wv(e){let t=new Map,n=new Set;for(let{path:r}of e){t.set(r,(t.get(r)??0)+1);let e=qv(r);for(let t=1;t<e.length;t++)n.add(`/${e.slice(0,t).join(`/`)}`)}return{parentPaths:n,pathOperations:t}}function Gv(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=Kv(a,i),s=o.length===0||r.parentPaths.has(Jv(a))||(r.pathOperations.get(a)??0)>1,c=Zv(o,i.summary??i.description);return[...c.length>0?c:[{name:`root`}],...s?[{name:t}]:[]]}function Kv(e,t){return e.split(`/`).map(e=>Yv(e,t)).filter(Xv)}function qv(e){return Kv(e).map(e=>e.name)}function Jv(e){return`/${qv(e).join(`/`)}`}function Yv(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 Xv(e){return e!==void 0}function Zv(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($v(e,r).commands,i,n)}}function $v(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 ey(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=Mn(c),u=await Fn(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 ty(e){return f.fromJSONSchema(e)}function ny(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 ry,iy,ay,oy,sy=I((()=>{jx(),Rn(),gv(),Pu(),ry=new Set([`delete`,`get`,`head`,`options`,`patch`,`post`,`put`,`trace`]),iy=new Set([`basic`,`bearer`]),ay=100,oy=new Set([`date`,`date-time`,`duration`,`time`])}));async function cy(e,t={}){let n=py(e);await my(n,`initialize`,{protocolVersion:by,capabilities:{},clientInfo:{name:`incur`,version:t.version??`1.0.0`}}),n.initialized=!0,await my(n,`notifications/initialized`);let r=(await my(n,`tools/list`)).tools??[];return uy(r)?{discovery:`progressive`,tools:await dy(n),session:n}:{tools:r,session:n}}function ly(e){let t=new Map;for(let n of e.tools){let r=n.inputSchema?gy(n.inputSchema):void 0,i=_y(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 my(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:vy(i)}):yy(i)}})}return t}function uy(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 dy(e){let t=[],n=0;for(;n!==void 0;){let r=await fy(e,`search_tools`,{query:``,limit:20,offset:n});for(let n of r.tools??[]){if(!n.name)continue;let r=await fy(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 fy(e,t,n){let r=await my(e,`tools/call`,{name:t,arguments:n});if(r.isError)throw Error(vy(r)||`MCP tool failed: ${t}`);return yy(r)}function py(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 my(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`,by);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`)?hy(l,i):JSON.parse(l);if(u.error)throw Error(u.error.message??`MCP request failed`);return u.result??{}}function hy(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 gy(e){let t=e.properties??{},n=new Set(e.required??[]),r={};for(let[e,i]of Object.entries(t)){let t=ty(i);n.has(e)||(t=t.optional()),typeof i.description==`string`&&(t=t.describe(i.description)),r[e]=ny(t)}return Object.keys(r).length>0?f.object(r):void 0}function _y(e){if(!(!e||e.type!==`object`))try{return f.fromJSONSchema(e)}catch{return}}function vy(e){return(Array.isArray(e.content)?e.content:[]).map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
186
- `)}function yy(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 by,xy=I((()=>{sy(),by=`2025-06-18`}));function Sy(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=Cy(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 Cy(e,t){let n=t.name?`${e} ${t.name}`:e;if(!t.args)return n;let r=t.args.shape,i=Nu(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 wy(e,t,n=new Map){if(!(n.size>0))return t.map(t=>Dy(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})),Ig=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)}}})),Lg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qh(),n=W(),r=Gh(),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)}}}})),Rg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ig(),n=Qh(),r=G(),i=Lg();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)}}}})),zg=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())})})}}}})),Bg=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`}}})),Vg=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`}}})),Hg=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)})})}}}})),Ug=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)})}}})),Wg=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})),Gg=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`)}}})),Kg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ag(),n=Mg(),r=jg(),i=Ng(),a=Pg(),o=Fg(),s=Ig(),c=Lg(),l=Rg(),u=zg(),d=Bg(),f=Vg(),p=Hg(),m=Ug(),h=Wg(),g=Gg();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),qg=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})`}}}}})),Jg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[qg().default]})),Yg=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`]})),Xg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=gg(),n=kg(),r=Kg(),i=Jg(),a=Yg();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Zg=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=Zg(),r=sg(),i=og(),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}}}}})),$g=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}})),e_=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=pg(),r=Xg(),i=Qg(),a=$g(),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=ig();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=ag();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=og();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),t_=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:E,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function E(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),n_=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=e_(),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)})),r_=z(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=t_(),r=n_(),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})),i_=e_(),a_=pf(r_(),1),o_=class{_ajv;constructor(e){this._ajv=e??rf()}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)}}},s_=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft??`2020-12`}getValidator(e){let t=new Ed(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 l_(){throw Error(`StdioServerTransport is not supported in this environment. Use StreamableHTTPServerTransport instead.`)}var u_,d_=F((()=>{c_(),u_={get stdin(){return l_()},get stdout(){return l_()}}})),f_=rt({AjvJsonSchemaValidator:()=>o_,CfWorkerJsonSchemaValidator:()=>s_,DEFAULT_NEGOTIATED_PROTOCOL_VERSION:()=>Cf,DEFAULT_REQUEST_TIMEOUT_MSEC:()=>Ph,ExperimentalMcpServerTasks:()=>j_,ExperimentalServerTasks:()=>M_,INTERNAL_ERROR:()=>Af,INVALID_PARAMS:()=>kf,INVALID_REQUEST:()=>Df,InMemoryTaskMessageQueue:()=>A_,InMemoryTaskStore:()=>k_,JSONRPC_VERSION:()=>`2.0`,LATEST_PROTOCOL_VERSION:()=>Sf,METHOD_NOT_FOUND:()=>Of,McpServer:()=>P_,OAuthError:()=>hf,OAuthErrorCode:()=>mf,PARSE_ERROR:()=>Ef,ProtocolError:()=>U,ProtocolErrorCode:()=>H,RELATED_TASK_META_KEY:()=>Tf,ReadBuffer:()=>Ih,ResourceTemplate:()=>F_,SUPPORTED_PROTOCOL_VERSIONS:()=>wf,SdkError:()=>V,SdkErrorCode:()=>B,Server:()=>N_,StdioServerTransport:()=>R_,UriTemplate:()=>Hh,UrlElicitationRequiredError:()=>jf,WebStandardStreamableHTTPServerTransport:()=>z_,assertClientRequestTaskCapability:()=>__,assertCompleteRequestPrompt:()=>Ld,assertCompleteRequestResourceTemplate:()=>Rd,assertToolsCallTaskCapability:()=>g_,checkResourceAllowed:()=>Ad,completable:()=>p_,createFetchWithInit:()=>Qd,deserializeMessage:()=>Kd,fromJsonSchema:()=>D_,getDisplayName:()=>jd,hostHeaderValidationResponse:()=>E_,isCompletable:()=>m_,isInitializeRequest:()=>Ah,isInitializedNotification:()=>jh,isJSONRPCErrorResponse:()=>Oh,isJSONRPCNotification:()=>Eh,isJSONRPCRequest:()=>Th,isJSONRPCResultResponse:()=>Dh,isTaskAugmentedRequestParams:()=>kh,isTerminal:()=>Bd,localhostAllowedHostnames:()=>T_,parseJSONRPCMessage:()=>Id,resourceUrlFromServerUrl:()=>kd,serializeMessage:()=>qd,takeResult:()=>Gd,toArrayAsync:()=>Wd,validateHostHeader:()=>w_});function p_(e,t){return Object.defineProperty(e,O_,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function m_(e){return!!e&&typeof e==`object`&&O_ in e}function h_(e){return e[O_]?.complete}function g_(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 __(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 v_(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 y_(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await tf(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 b_(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}function x_(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function S_(e){return e?.type===`optional`}function C_(e){return S_(e)?e.def?.innerType??e:e}function w_(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 T_(){return[`localhost`,`127.0.0.1`,`[::1]`]}function E_(e,t){let n=w_(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 D_(e,t){return af(e,t??(B_??=new s_))}var O_,k_,A_,j_,M_,N_,P_,F_,I_,L_,R_,z_,B_,V_=F((()=>{c_(),d_(),O_=Symbol.for(`mcp.completable`),k_=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(Bd(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(Bd(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(),Bd(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}))}},A_=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}},j_=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)}},M_=class{constructor(e){this._server=e}get _module(){return this._server.taskManager}requestStream(e,t){let n=Md(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},kp,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)}},N_=class extends Fh{_clientCapabilities;_clientVersion;_capabilities;_instructions;_jsonSchemaValidator;_experimental;oninitialized;constructor(e,t){if(super({...t,tasks:Vd(t?.capabilities?.tasks)}),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new s_,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=zd(Om,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 M_(this)},this._experimental}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Om.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=Ud(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}setRequestHandler(e,t){return e===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=zd(Em,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=zd(Cp,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=zd(wm,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){__(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){g_(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`},Zf)}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},Um,t):this._requestWithSchema({method:`sampling/createMessage`,params:e},Hm,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},ch,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},ch,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},gh,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`})}},P_=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_experimental;constructor(e,t){this.server=new N_(e,t)}get experimental(){return this._experimental||={tasks:new j_(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?$d(t.inputSchema,`input`):I_,annotations:t.annotations,execution:t.execution,_meta:t._meta};return t.outputSchema&&(n.outputSchema=$d(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 tf(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 tf(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 Ld(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Rd(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 L_;let r=C_(x_(n.argsSchema)?.[e.params.argument.name]);if(!m_(r))return L_;let i=h_(r);return i?b_(await i(e.params.argument.value,e.params.context)):L_}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 L_;throw new U(H.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?b_(await r(e.params.argument.value,e.params.context)):L_}_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?nf(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:y_(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=y_(e,o,s)),t.enabled!==void 0&&(c.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=c,r){let e=x_(r);e&&Object.values(e).some(e=>m_(C_(e)))&&this.setCompletionRequestHandler()}return c}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Xd(e);let l=c,u={title:t,description:n,inputSchema:r,outputSchema:i,annotations:a,execution:o,_meta:s,handler:c,executor:v_(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`&&Xd(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=v_(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()}},F_=class{_uriTemplate;constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new Hh(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},I_={type:`object`,properties:{}},L_={completion:{values:[],hasMore:!1}},R_=class{_readBuffer=new Ih;_started=!1;_closed=!1;constructor(e=u_.stdin,t=u_.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=qd(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)})}},z_=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??wf}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=>Xf.parse(e)):[Xf.parse(a)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let s=o.some(e=>Ah(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=>Th(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=>Ah(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)Th(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)Th(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;Th(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((Dh(e)||Oh(e))&&(n=e.id),n===void 0){if(Dh(e)||Oh(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(Dh(e)||Oh(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 H_(e,t,n,r={}){let i=W_(),a=await Promise.resolve().then(()=>(V_(),f_)),{fromJsonSchema:o,McpServer:s}=a,c=await U_(a,i),l=new s({name:e,...r.title?{title:r.title}:void 0,version:t},r.instructions?{instructions:r.instructions}:void 0);K_(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 U_(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 W_(){return Promise.resolve().then(()=>(V_(),f_)).then(e=>({module:e})).catch(e=>({error:e}))}async function G_(e,t,n={}){let r=[...n.middlewares??[],...e.middlewares??[],...e.command.middleware??[]],i=await Zl(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:Ur(a)}})}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}return{content:[{type:`text`,text:Ur(e)}]}}if(!i.ok){let t=Su(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${Cu(t)}`:r}],...t?{_meta:{cta:t}}:void 0,isError:!0}}let a=i.data??null,o=Wr(a),s=Su(n.name??e.name,i.cta),c=Ur(o);return{content:[{type:`text`,text:s?`${c}\n\n${Cu(s)}`:c}],...a!==null&&e.outputSchema?{structuredContent:o}:void 0,...s?{_meta:{cta:s}}:void 0}}function K_(e,t,n){let r=tv(t,[],[],n.tools);if(r.length!==0){if((n.tools?.discovery??`progressive`)===`direct`){for(let t of r)q_(e,t,n);return}J_(e,r,n)}}function q_(e,t,n){let r={...t.command.args?.shape,...t.command.options?.shape},i=Object.keys(r).length>0;e.registerTool(t.name,{...t.description?{description:t.description}:void 0,...i?{inputSchema:f.object(r)}:void 0,...t.outputSchema?{outputSchema:n.fromJsonSchema(t.outputSchema)}:void 0,...t.annotations?{annotations:t.annotations}:void 0,...t.instructions?{_meta:{instructions:t.instructions}}:void 0},async(...e)=>G_(t,i?e[0]:{},Y_(n,i?e[1]:e[0])))}function J_(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:uv},async e=>{let n=X_(t,e.query),r=n.slice(e.offset,e.offset+e.limit);return $_({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:uv},async e=>{let t=r.get(e.name);return t?$_({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}):ev(`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:lv,annotations:dv},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?G_(i,e.arguments,Y_(n,t)):ev(`Tool is not read-only: ${e.name}`):ev(`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:lv,annotations:fv},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?ev(`Tool is read-only: ${e.name}`):G_(i,e.arguments,Y_(n,t)):ev(`Unknown tool: ${e.name}`)})}function Y_(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 X_(e,t){let n=Q_(t),r=n.split(` `).filter(Boolean);return e.map(e=>({tool:e,score:Z_(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 Z_(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 $_(e){return{content:[{type:`text`,text:Ur(e)}]}}function ev(e){return{...$_({error:e}),isError:!0}}function tv(e,t,n=[],r){let i=iv(nv(e,t,n),r);return ov(i),i.sort((e,t)=>e.name.localeCompare(t.name))}function nv(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(rv(a.root,e,t)),r.push(...nv(a.commands,e,t))}else r.push(rv(a,e,n))}return r}function rv(e,t,n){let r=e.mcp===!1?void 0:e.mcp,i=e.output?sv(e.output):void 0;return{name:r?.name??t.join(`_`),description:r?.description??e.description,inputSchema:cv(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 iv(e,t){if(!t)return e;let n=t.include?.map(av),r=t.exclude?.map(av)??[];return e.filter(e=>r.some(t=>t.test(e.name))?!1:!n||n.length===0||n.some(t=>t.test(e.name)))}function av(e){let t=e.replace(/[|\\{}()[\]^$+?.]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function ov(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 sv(e){let t=Pu(e);if(t.type===`object`)return t}function cv(e,t){let n={},r=[];for(let i of[e,t]){if(!i)continue;let e=Pu(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 lv,uv,dv,fv,pv=F((()=>{su(),Tu(),Gr(),Fu(),lv=f.object({name:f.string().min(1).describe(`Exact tool name.`),arguments:f.record(f.string(),f.unknown()).default({}).describe(`Arguments from its schema.`)}),uv={destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},dv={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},fv={destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1}}));function mv(e){return hv(e,e,new Map)}function hv(e,t,n){if(Array.isArray(e))return e.map(e=>hv(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=gv(t,e);if(typeof i!=`object`||!i||Array.isArray(i)){let r=hv(i,t,n);return n.set(e,r),r}let a={};n.set(e,a);let o=hv(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]=hv(r[e],t,n);return i}function gv(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 _v=F((()=>{}));function vv(e,t={}){let n=Sx.get(e);if(!n)throw Error(`No commands registered on this CLI instance`);let r={},i=Tx.get(e);i&&xv(r,[],i);for(let[e,t]of n)yv(r,bv(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 yv(e,t,n){if(!(`_alias`in n)&&!(`_fetch`in n)){if(`_group`in n){n.root&&xv(e,t,n.root);for(let[r,i]of n.commands)yv(e,[...t,...bv(r)],i);return}xv(e,t,n)}}function bv(e){return e.split(/\s+/).filter(Boolean)}function xv(e,t,n){let r=n.args?Pu(n.args):void 0,i=n.options?Pu(n.options):void 0,a=n.output?Pu(n.output):void 0,o=kv(r),s=new Set(Av(r)),c=Cv(t),l=Sv(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(kv(i)))s.push({name:e,in:`query`,...Av(i).includes(e)?{required:!0}:void 0,schema:t});let l={operationId:jv(t,c,r.args),...n.description?{summary:n.description}:void 0,...s.length?{parameters:s}:void 0,...Tv(c,i),responses:Ev(a)},u=e[r.path]??{};u[c]=l,e[r.path]=u}}function Sv(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(Mv).join(`/`)}`})}return o.length===0&&o.push({args:[],path:`/${e.map(Mv).join(`/`)}`}),o}function Cv(e){let t=e.map(wv).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 wv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`)}function Tv(e,t){return!t||e===`get`||e===`delete`?{}:{requestBody:{required:Av(t).length>0,content:{"application/json":{schema:t}}}}}function Ev(e){return{200:{description:`Command completed successfully.`,content:{"application/json":{schema:{type:`object`,required:[`ok`,`data`,`meta`],properties:{ok:{const:!0},data:e??{},meta:Ov()}}}}},400:Dv(`Validation error.`),500:Dv(`Command failed.`)}}function Dv(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:Ov()}}}}}}function Ov(){return{type:`object`,required:[`command`,`duration`],properties:{command:{type:`string`},duration:{type:`string`}}}}function kv(e){return e?.properties??{}}function Av(e){return e?.required??[]}function jv(e,t,n){return`${t}${[...e,...n.length?[n.join(` `)]:[]].join(` `).replace(/(?:^|[\s_-]+)(\w)/g,(e,t)=>t.toUpperCase())}`}function Mv(e){return e.startsWith(`{`)&&e.endsWith(`}`)?e:encodeURIComponent(e)}async function Nv(e,t={}){if(typeof e!=`string`&&!(e instanceof URL))return e;let n=await fetch(Pv(e,t.baseUrl));if(!n.ok)throw Error(`Failed to fetch OpenAPI spec from ${e}: ${n.status}`);return await n.json()}function Pv(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 Fv(e,t,n={}){let r=mv(structuredClone(e)),i=new Map,a=Lv(r.paths??{}),o=Gv(a),{config:s}=n;s?.compact&&Bv(a);for(let{method:e,operation:c,path:l}of a){let a=Kv({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=Uv([...(c.parameters??[]).filter(e=>e.in===`header`),...s?.security===!1?[]:Rv(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?ny(t.schema):f.string();t.description&&(n=n.describe(t.description)),e[t.name]=ry(n)}v=f.object(e)}let y={},b=new Set;for(let e of p){let t=e.schema?ny(e.schema):f.string();e.required||(t=t.optional()),e.description&&(t=t.describe(e.description)),y[e.name]=ry(t),b.add(e.name)}for(let[e,t]of Object.entries(g)){let n=ny(t);_.has(e)||(n=n.optional()),y[e]=n,b.add(e)}for(let e of m){let t=Wv(e.optionName,b);e.optionName=t;let n=e.schema?ny(e.schema):f.string();e.required||(n=n.optional()),n=n.describe(e.description??`${e.name} header`),y[t]=ry(n),b.add(t)}let x=Object.keys(y).length>0?f.object(y):void 0;$v(i,a,{description:c.summary??c.description,mcp:{annotations:Iv(e),...c.summary&&c.description&&c.summary!==c.description?{description:`${c.summary}\n\n${c.description}`}:void 0},args:v,options:x,run:ty({basePath:n.basePath,fetch:t,forwardHeaders:s?.forwardHeaders,httpMethod:u,path:l,headerParams:m,pathParams:d,queryParams:p,bodyProps:g})})}return i}function Iv(e){let t=[`get`,`head`,`options`,`trace`].includes(e);return{destructiveHint:!t,idempotentHint:t||e===`delete`||e===`put`,openWorldHint:!0,readOnlyHint:t}}function Lv(e){let t=[];for(let[n,r]of Object.entries(e))for(let[e,i]of Object.entries(r))iy.has(e)&&t.push({method:e,operation:i,path:n});return t}function Rv(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=zv(t,e);r&&i.push(r)}return i}function zv(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`&&ay.has(t.scheme?.toLowerCase()??``))return{description:t.description??`${e} authorization header`,in:`header`,name:`authorization`,required:!1,schema:{type:`string`}}}}function Bv(e){for(let{operation:t}of e){for(let e of t.parameters??[])e.schema&&=Vv(e.schema);let e=t.requestBody?.content?.[`application/json`];e?.schema&&(e.schema=Vv(e.schema))}}function Vv(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>oy&&delete r.pattern,typeof r.format==`string`&&sy.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=>Vv(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];Hv(n)&&(r[e]=Vv(n,t))}for(let e of[`$defs`,`patternProperties`,`properties`]){let n=r[e];if(!Hv(n))continue;let i={};for(let[e,r]of Object.entries(n))i[e]=Hv(r)?Vv(r,t):r;r[e]=i}return r}function Hv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Uv(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 Wv(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 Gv(e){let t=new Map,n=new Set;for(let{path:r}of e){t.set(r,(t.get(r)??0)+1);let e=Jv(r);for(let t=1;t<e.length;t++)n.add(`/${e.slice(0,t).join(`/`)}`)}return{parentPaths:n,pathOperations:t}}function Kv(e){let{method:t,mode:n,namespaceInfo:r,operation:i,path:a}=e;if(n===`operation`)return[{name:i.operationId??`${t}_${a.replace(/[/{}]/g,`_`)}`}];let o=qv(a,i),s=o.length===0||r.parentPaths.has(Yv(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 qv(e,t){return e.split(`/`).map(e=>Xv(e,t)).filter(Zv)}function Jv(e){return qv(e).map(e=>e.name)}function Yv(e){return`/${Jv(e).join(`/`)}`}function Xv(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 Zv(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 $v(e,t,n){let[r,...i]=t;if(r){if(i.length===0){e.set(r.name,n);return}$v(ey(e,r).commands,i,n)}}function ey(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 ty(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=Pn(c),u=await Ln(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 ny(e){return f.fromJSONSchema(e)}function ry(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 iy,ay,oy,sy,cy=F((()=>{Mx(),Bn(),_v(),Fu(),iy=new Set([`delete`,`get`,`head`,`options`,`patch`,`post`,`put`,`trace`]),ay=new Set([`basic`,`bearer`]),oy=100,sy=new Set([`date`,`date-time`,`duration`,`time`])}));async function ly(e,t={}){let n=my(e);await hy(n,`initialize`,{protocolVersion:xy,capabilities:{},clientInfo:{name:`incur`,version:t.version??`1.0.0`}}),n.initialized=!0,await hy(n,`notifications/initialized`);let r=(await hy(n,`tools/list`)).tools??[];return dy(r)?{discovery:`progressive`,tools:await fy(n),session:n}:{tools:r,session:n}}function uy(e){let t=new Map;for(let n of e.tools){let r=n.inputSchema?_y(n.inputSchema):void 0,i=vy(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 hy(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:yy(i)}):by(i)}})}return t}function dy(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 fy(e){let t=[],n=0;for(;n!==void 0;){let r=await py(e,`search_tools`,{query:``,limit:20,offset:n});for(let n of r.tools??[]){if(!n.name)continue;let r=await py(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 py(e,t,n){let r=await hy(e,`tools/call`,{name:t,arguments:n});if(r.isError)throw Error(yy(r)||`MCP tool failed: ${t}`);return by(r)}function my(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 hy(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`,xy);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`)?gy(l,i):JSON.parse(l);if(u.error)throw Error(u.error.message??`MCP request failed`);return u.result??{}}function gy(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 _y(e){let t=e.properties??{},n=new Set(e.required??[]),r={};for(let[e,i]of Object.entries(t)){let t=ny(i);n.has(e)||(t=t.optional()),typeof i.description==`string`&&(t=t.describe(i.description)),r[e]=ry(t)}return Object.keys(r).length>0?f.object(r):void 0}function vy(e){if(!(!e||e.type!==`object`))try{return f.fromJSONSchema(e)}catch{return}}function yy(e){return(Array.isArray(e.content)?e.content:[]).map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
186
+ `)}function by(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 xy,Sy=F((()=>{cy(),xy=`2025-06-18`}));function Cy(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=wy(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 wy(e,t){let n=t.name?`${e} ${t.name}`:e;if(!t.args)return n;let r=t.args.shape,i=Pu(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 Ty(e,t,n=new Map){if(!(n.size>0))return t.map(t=>Oy(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(Dy(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(Oy(e,a,t?3:2))}return r.join(`
190
190
 
191
- `)}function Ty(e,t,n,r=new Map){if(n===0)return[{dir:``,content:Ey(e,e,t,r,e)}];let i=new Map;for(let r of t){if(!r.name){let t=Ay(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:Ey(e,o?`${e} ${o}`:e,i,r,o||void 0)}})}function Ey(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${xl().stringify({name:Ay(t),description:c,requires_bin:e,command:t},{lineWidth:0}).trimEnd()}\n---`}\n\n${n.map(t=>Dy(e,t)).join(`
191
+ `)}function Ey(e,t,n,r=new Map){if(n===0)return[{dir:``,content:Dy(e,e,t,r,e)}];let i=new Map;for(let r of t){if(!r.name){let t=jy(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:Dy(e,o?`${e} ${o}`:e,i,r,o||void 0)}})}function Dy(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${Sl().stringify({name:jy(t),description:c,requires_bin:e,command:t},{lineWidth:0}).trimEnd()}\n---`}\n\n${n.map(t=>Oy(e,t)).join(`
192
192
 
193
193
  ---
194
194
 
195
- `)}`}function Dy(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=Nu(t.args),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e];return`| \`${e}\` | \`${jy(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=Nu(t.env),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e],i=jy(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=Nu(t.options).properties,r=Object.entries(e).map(([e,t])=>{let r=n?.[e],i=jy(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=Nu(t.output),n=ky(e);if(n)i.push(`${s} Output\n\n${n}`);else{let t=jy(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 Oy(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=Pu(t.args),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e];return`| \`${e}\` | \`${My(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=Pu(t.env),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e],i=My(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=Pu(t.options).properties,r=Object.entries(e).map(([e,t])=>{let r=n?.[e],i=My(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=Pu(t.output),n=Ay(e);if(n)i.push(`${s} Output\n\n${n}`);else{let t=My(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 Oy(e){let t=e.map(e=>({name:e.name,description:e.description,hint:e.hint,args:e.args?Nu(e.args):void 0,env:e.env?Nu(e.env):void 0,options:e.options?Nu(e.options):void 0,output:e.output?Nu(e.output):void 0}));return g(`sha256`).update(JSON.stringify(t)).digest(`hex`).slice(0,16)}function ky(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=jy(a),s=r.has(e)?`yes`:`no`,c=a.description??``;if(i.push(`| \`${n}\` | \`${o}\` | ${s} | ${c} |`),a.type===`object`&&a.properties){let e=ky(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=ky(e,`${n}[]`);if(t){let e=t.split(`
202
+ `)}function ky(e){let t=e.map(e=>({name:e.name,description:e.description,hint:e.hint,args:e.args?Pu(e.args):void 0,env:e.env?Pu(e.env):void 0,options:e.options?Pu(e.options):void 0,output:e.output?Pu(e.output):void 0}));return _(`sha256`).update(JSON.stringify(t)).digest(`hex`).slice(0,16)}function Ay(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=My(a),s=r.has(e)?`yes`:`no`,c=a.description??``;if(i.push(`| \`${n}\` | \`${o}\` | ${s} | ${c} |`),a.type===`object`&&a.properties){let e=Ay(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=Ay(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 Ay(e){return e.toLowerCase().replace(/[^a-z0-9-]+/g,`-`).replace(/-{2,}/g,`-`).replace(/^-|-$/g,``)}function jy(e){if(!e)return`unknown`;let t=e.type;return t?t===`integer`?`number`:t:`unknown`}var My=I((()=>{Cl(),Pu()}));async function Ny(e,t={}){let n=at(),r=t.command??Fy(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 Vy(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`))&&Py(e,r)&&o.push(`Amp`),{command:r,agents:o}}function Py(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]=By(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 Fy(e,t){return Ly(e)?`${e} --mcp`:`${t} ${zy(e)} --mcp`}function Iy(){let e=(process.argv[1]?.replace(/\\/g,`/`))?.match(/^(.+)\/node_modules\/(.+)$/);return e?{root:e[1],entry:e[2]}:null}function Ly(e){let t=process.argv[1];if(!t)return!1;let n=Iy();if(n)return!n.entry.startsWith(`.bin/`)&&!Ry(n.root,e);let r=t.replace(/\\/g,`/`).split(`/`).pop();return r===e||r===`${e}.cmd`||r===`${e}.ps1`}function Ry(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 zy(e){let t=Iy();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 By(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 Vy(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 Hy=I((()=>{st()}));function Uy(){return $y.filter(e=>e.detect())}function Wy(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??Uy(),l=[],u=[];for(let n of Ky(e)){let e=c.join(o,n.name);Jy(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(Yy(s)!==Yy(e))try{Jy(s),t.mkdirSync(c.dirname(s),{recursive:!0});let n=Yy(c.dirname(s)),r=Yy(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 Gy(e,t={}){let n=t.global!==!1,r=t.cwd||process.cwd(),i=n?K:r;Jy(c.join(i,`.agents`,`skills`,e));for(let t of Uy()){if(t.universal)continue;let i=n?t.globalSkillsDir:c.join(r,t.projectSkillsDir);Jy(c.join(i,e))}}function Ky(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:qy(e?.[1]??a.name),dir:i})}r(i)}}r(e);let i=c.join(e,`SKILL.md`);if(t.existsSync(i)){let r=qy(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 qy(e){return e.trim().replace(/[/\\]/g,`-`).replace(/\.\./g,``).slice(0,255)}function Jy(e){try{t.lstatSync(e).isSymbolicLink()?t.unlinkSync(e):t.rmSync(e,{recursive:!0,force:!0})}catch{}}function Yy(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,Xy,Zy,Qy,$y,eb=I((()=>{K=b.homedir(),Xy=process.env.XDG_CONFIG_HOME||c.join(K,`.config`),Zy=process.env.CLAUDE_CONFIG_DIR?.trim()||c.join(K,`.claude`),Qy=process.env.CODEX_HOME?.trim()||c.join(K,`.codex`),$y=[{name:`Amp`,globalSkillsDir:c.join(Xy,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(Xy,`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(Xy,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.kimi`))},{name:`OpenCode`,globalSkillsDir:c.join(Xy,`opencode`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(Xy,`opencode`))},{name:`Claude Code`,globalSkillsDir:c.join(Zy,`skills`),projectSkillsDir:`.claude/skills`,universal:!1,detect:()=>t.existsSync(Zy)},{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(Xy,`goose`,`skills`),projectSkillsDir:`.goose/skills`,universal:!1,detect:()=>t.existsSync(c.join(Xy,`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(Xy,`crush`,`skills`),projectSkillsDir:`.crush/skills`,universal:!1,detect:()=>t.existsSync(c.join(Xy,`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 tb(e,t,n={}){let{depth:r=1,description:i,global:a=!0}=n,o=n.cwd??(a?ib():process.cwd());await bl();let s=new Map;i&&s.set(e,i);let c=Ty(e,lx(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=mx(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=mx(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}=Wy(u,{global:a,cwd:o}),d=new Set(i.map(e=>l.basename(e))),f=sb(e);if(f?.skills)for(let e of f.skills)d.has(e)||Gy(e,{global:a,cwd:o});return ob(e,Oy(lx(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 nb(e,t,n={}){let{depth:r=1,description:i}=n,a=n.cwd??process.cwd();await bl();let o=new Map;i&&o.set(e,i);let s=Ty(e,lx(t,[],o,n.rootCommand),r,o),c=[],u=cb(e,{cwd:a});for(let t of s){let n=mx(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=mx(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 rb(e,t={}){return cb(e,t).size>0}function ib(){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 ab(e){let t=process.env.XDG_DATA_HOME||l.join(x.homedir(),`.local`,`share`);return l.join(t,`incur`,`${e}.json`)}function ob(e,t,r,i){let a=ab(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 sb(e){try{return JSON.parse(n.readFileSync(ab(e),`utf-8`))}catch{return}}function cb(e,t={}){let n=sb(e);if(!n?.skills?.length)return new Set;if(n.paths?.length){let e=n.paths.filter(e=>lb(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=>lb(l.join(t,e))));return new Set(a)}function lb(e){return n.existsSync(l.join(e,`SKILL.md`))}function ub(e){return sb(e)?.hash}var db=I((()=>{jx(),eb(),Cl(),My()}));function fb(e,t){let n=typeof e==`string`?e:e.name,r=typeof e==`string`?t??{}:e,i=r.version??Ht,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:Gb(o),c=o===void 0?void 0:Kb(o),l=new Map,u=[],d=[],f=mb(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 Pv(await Mv(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(Wb(t))return d.push((async()=>{let n=ly(await cy(t.mcp)),r={_group:!0,description:t.description,commands:n,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0};Zb(e,r,Ox.get(p)),l.set(e,r)})()),p;if(t&&`fetch`in t&&Ub(t.fetch)){let n=Gb(t.fetch);return t.openapi?(d.push((async()=>{let r=await Pv(await Mv(t.openapi,{baseUrl:Kb(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};Zb(e,i,Ox.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(Zb(e,t,Ox.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=wx.get(e),r=e,i=xx.get(r),a=Dx.get(r),o=Cx.get(r),s=Sx.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(()=>{Zb(r.name,c,Ox.get(p))})):Zb(r.name,c,Ox.get(p)),l.set(r.name,c),n){let t=kx.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=Ox.get(p);return _b(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=Eu();return d.push((async()=>{let n=t?await Du(t):await zb(await Rb(e));for(let e of n){if(!Bb(e.command))throw Error(`Expected the default export from '${e.file}' to be created with \`Cli.command()\`.`);Vb(l,e.segments,e.command,e.file,Ox.get(p))}})()),p},async serve(e=process.argv.slice(2),t={}){if(await Ot(e))return;d.length>0&&await Promise.all(d);let o=Ox.get(p);return pb(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&&wx.set(p,a),a&&r.aliases&&kx.set(p,r.aliases),r.options&&Tx.set(p,r.options),r.config!==void 0&&Ex.set(p,!0),r.outputPolicy&&Dx.set(p,r.outputPolicy),r.globals){Ox.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 Cx.set(p,u),xx.set(p,l),Sx.set(p,d),p}async function pb(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=_x(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=Sb(n,{configFlag:l})}catch(e){let t=e instanceof Error?e.message:String(e);d(s?Qb({code:`UNKNOWN`,message:t}):wl({code:`UNKNOWN`,message:t},`toon`)),a(1);return}let{fullOutput:m,format:h,formatExplicit:g,filterOutput:_,tokenLimit:v,tokenOffset:y,tokenCount:b,llms:x,llmsFull:S,mcp:C,help:w,update:T,updateCheck:ee,version:te,schema:E,configPath:D,configDisabled:O,rest:k}=p;s=o&&!g;let ne={...typeof r.update==`object`?r.update:void 0,binary:Vt!==void 0,version:r.version},A={},j=k;function M(e){if(!r.globals)return!0;try{let t=ql(k,r.globals.schema,r.globals.alias,{validate:e});return e&&(A=t.parsed),j=t.rest,!0}catch(e){let t=e instanceof Error?e.message:String(e);return d(s?Qb({code:`UNKNOWN`,message:t}):wl({code:`UNKNOWN`,message:t},`toon`)),a(1),!1}}if(!M(!1))return;if(h===`yaml`&&await bl(),ee){if(r.update!==!1)try{await lt(e,ne)}catch{}return}if(T&&!w){try{let t=await ut(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(wl(t,h))}catch(e){let t={code:`UPDATE_FAILED`,message:e instanceof Error?e.message:String(e)};d(s?Qb(t):wl(t,h)),a(1)}return}if(C){await V_(r.mcp?.name??e,r.version??`0.0.0`,t,{middlewares:r.middlewares,env:r.envSchema,vars:r.vars,version:r.version,...r.mcp?.instructions?{instructions:r.mcp.instructions}:void 0,...r.mcp?.title?{title:r.mcp.title}:void 0,...r.mcp?.tools?{tools:r.mcp.tools}:void 0});return}let re=process.env.COMPLETE;if(re){let a=n.indexOf(`--`),o=a===-1?n:n.slice(a+1);if(o.length===0)i([e,...r.aliases??[]].map(e=>fn(re,e)).join(`
211
- `));else{let e=Number(process.env._COMPLETE_INDEX??o.length-1),n=pn(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 au)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=tu(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=mn(re,n);c&&i(c)}return}let ie;if(!x&&!S&&!E&&!w&&!T&&!ee&&!te){let n=kb(j,e,`skills`)!==-1,i=kb(j,e,`mcp`)!==-1;if(!n&&!i){let n=ub(e);n&&rb(e,{cwd:r.sync?.cwd})&&Oy(lx(t,[],new Map,r.rootCommand))!==n&&(ie={description:`Skills are out of date:`,commands:[{command:process.env.npm_config_user_agent||process.env.npm_execpath?`${at()} ${zy(e)} skills add`:`${u} skills add`,description:`sync outdated skills`}]})}}if(x||S){let n=t,i=[],a=r.description,o=r.rootCommand;for(let e of j){let t=n.get(e);if(!t)break;let r=Xb(n,t);if(qb(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=lx(n,s,t,o);d(wy(i.length>0?`${e} ${i.join(` `)}`:e,r,t));return}d(wl(ox(n,i,r.globals?.schema,o),h));return}if(!g||h===`md`){let t=lx(n,s,new Map,o);d(Sy(i.length>0?`${e} ${i.join(` `)}`:e,t,a));return}d(wl(ix(n,i,r.globals?.schema,o),h));return}let ae=kb(j,e,`completions`);if(ae!==-1){let t=j[ae+1];if(w||!t){let t=tu(`completions`);d(cu(`${e} completions`,{args:t.args,description:t.description,hideGlobalOptions:!0,hint:t.hint?.(e)}));return}if(!iu.includes(t)){d(Qb({code:`INVALID_SHELL`,message:`Unknown shell '${t}'. Supported: ${iu.join(`, `)}`})),a(1);return}d([e,...r.aliases??[]].map(e=>fn(t,e)).join(`
212
- `));return}let oe=kb(j,e,`skills`);if(oe!==-1){let o=tu(`skills`),c=j[oe+1],l=c?nu(o,c):void 0;if(c&&!l){let t=un(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($b(l))):d(wl({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(Ab(e,o));return}if(l?.name===`list`){if(w){d(jb(e,o,`list`));return}try{let n=await nb(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(wl({code:`LIST_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(w){d(jb(e,o,`add`));return}let u=j.slice(oe+2),f=u.indexOf(`--depth`),p=u.find(e=>e.startsWith(`--depth=`)),_=f===-1?p?Number(p.split(`=`)[1]):r.sync?.depth??1:Number(u[f+1]),v=!u.includes(`--no-global`)&&void 0;try{i(`Syncing...`);let n=await tb(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(wl(e,g?h:`toon`))}}catch(e){d(wl({code:`SYNC_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}let se=kb(j,e,`mcp`);if(se!==-1){let o=tu(`mcp`),c=j[se+1],l=c?nu(o,c):void 0;if(c&&!l){let t=un(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($b(l))):d(wl({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(Ab(e,o));return}if(w){d(jb(e,o,l.name));return}if(l.name===`doctor`){let n=await Mb(e,t,r);d(wl(n,g?h:`toon`)),n.ok||a(1);return}let u=j.slice(se+2),f=!u.includes(`--no-global`),p=r.mcp?.command,_=[...r.mcp?.agents??[]];for(let e=0;e<u.length;e++)(u[e]===`--command`||u[e]===`-c`)&&u[e+1]?p=u[++e]:u[e]===`--agent`&&u[e+1]&&_.push(u[++e]);try{let t=r.mcp?.name??e;i(`Registering MCP server...`);let n=await Ny(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(wl({name:t,command:n.command,agents:n.agents},g?h:`toon`))}catch(e){d(wl({code:`MCP_ADD_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(te&&!w&&r.version){d(r.version);return}if(j.length===0){if(r.rootCommand&&s&&r.rootCommand.args&&tx(r.rootCommand.args)){let n=r.rootCommand;await f(),d(cu(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:px(n.examples),usage:n.usage,commands:t.size>0?Ob(t):void 0,root:!0}));return}if(!(r.rootCommand||r.rootFetch)){await f(),d(su(e,{aliases:r.aliases,configFlag:l,description:r.description,globals:r.globals,version:r.version,commands:Ob(t),root:!0}));return}}let N=j.length===0&&r.rootCommand?{command:r.rootCommand,path:e,rest:[]}:j.length===0&&r.rootFetch?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:[]}:xb(t,j);if(w&&`fetchGateway`in N){let n=N.path===e?e:`${e} ${N.path}`;N.path===e&&t.size>0?d(su(e,{aliases:r.aliases,configFlag:l,description:r.description,version:r.version,commands:Ob(t),root:!0})):d(Lb(n,N.fetchGateway.description));return}if(w){if(`help`in N||`error`in N){let n=`help`in N?`${e} ${N.path}`:e,i=`help`in N?N.description:r.description,a=`help`in N?N.commands:t,o=n===e;if(o&&r.rootCommand&&a.size>0){let t=r.rootCommand;d(cu(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:px(t.examples),usage:t.usage,commands:Ob(a),root:!0}))}else d(su(n,{aliases:o?r.aliases:void 0,configFlag:l,description:i,globals:r.globals,version:o?r.version:void 0,commands:Ob(a),root:o}))}else if(`command`in N){let n=N.command,i=N.path===e,a=i?e:`${e} ${N.path}`,o=`commands`in N&&N.commands&&N.commands.size>0?Ob(N.commands):i&&r.rootCommand&&t.size>0?Ob(t):void 0;d(cu(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:px(n.examples),usage:n.usage,commands:o,root:i}))}return}if(E){if(`help`in N){d(su(`${e} ${N.path}`,{configFlag:l,description:N.description,globals:r.globals,commands:Ob(N.commands)}));return}if(`error`in N){let t=N.path?`${e} ${N.path}`:e,n=un(N.error,N.commands.keys()),r=n?` Did you mean '${n}'?`:``;d(`Error: '${N.error}' is not a command for '${t}'.${r}`),a(1);return}if(`fetchGateway`in N){d(`--schema is not supported for fetch commands.`),a(1);return}let t=N.command,n=g?h:`toon`,i={};t.args&&(i.args=Nu(t.args)),t.env&&(i.env=Nu(t.env)),t.options&&(i.options=Nu(t.options)),t.output&&(i.output=Nu(t.output)),r.globals?.schema&&(i.globals=Nu(r.globals.schema)),d(wl(i,n));return}if(`help`in N){d(su(`${e} ${N.path}`,{configFlag:l,description:N.description,globals:r.globals,commands:Ob(N.commands)}));return}let ce;if(s&&r.update!==!1){let t=ct(e,ne);t&&(ce={description:`Update available for ${t.name}:`,commands:[{command:`${u} --update`,description:`upgrade from ${t.current} to ${t.latest}`}]})}let le=ex(ie,ce),P=performance.now(),ue=`command`in N&&N.command.format,de=g?h:ue||r.format||`toon`;de===`yaml`&&await bl();let fe=`error`in N&&!N.path&&(()=>{let e=[...N.commands.keys()];for(let t of au)e.push(t.name);return un(N.error,e)!==void 0})(),pe=`error`in N&&r.rootFetch&&!N.path&&!fe?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:j}:`error`in N&&r.rootCommand&&!N.path&&!fe?{command:r.rootCommand,path:e,rest:j}:N,me=`outputPolicy`in N&&N.outputPolicy||r.outputPolicy,he=!(s&&!g&&me===`agent-only`),ge=_?zn(_):void 0;function _e(e){if(v==null&&y==null)return{text:e,truncated:!1};let t=Xt(e),n=y??0,r=v==null?t:n+v;if(n===0&&r>=t)return{text:e,truncated:!1};let i=Zt(e,n,r),a=Math.min(r,t),o=a<t?a:void 0;return{text:`${i}\n[truncated: showing tokens ${n}–${a} of ${t}]`,truncated:!0,nextOffset:o}}function ve(e){if(ge&&e.ok&&e.data!=null&&(e={...e,data:Bn(e.data,ge)}),le){let t=e.meta.cta;e={...e,meta:{...e.meta,cta:t?{description:t.description,commands:[...t.commands,...le.commands]}:le}}}if(b){let t=e.ok?e.data:e.error,n=t==null?``:wl(t,de);return d(String(Xt(n)))}let t=e.meta.cta;if(s&&!m){e.ok&&e.data!=null&&he?d(_e(wl(e.data,de)).text):e.ok||d(Qb(e.error)),t&&d($b(t));return}if(m){if(v!=null||y!=null){let t=_e(e.ok&&e.data!=null?wl(e.data,de):e.ok?``:wl(e.error,de));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(wl(n,de))}}return d(wl(e,de))}let n=e.ok?e.data:e.error,r=wl(n,de);if(!t){r&&d(_e(r).text);return}d(_e(wl(typeof n==`object`&&n?{...n,cta:t}:{data:n,cta:t},de)).text)}if(`error`in pe){let t=pe.path?`${e} ${pe.path} --help`:`${e} --help`,r=pe.path?`${e} ${pe.path}`:e,i=`commands`in pe?[...pe.commands.keys()]:[];if(!pe.path)for(let e of au)i.push(e.name);let o=un(pe.error,i),c=o?` Did you mean '${o}'?`:``,l=`'${pe.error}' is not a command for '${r}'.${c}`,u=[];if(o){let t=n.map(e=>e===pe.error?o:e);u.push({command:`${e} ${t.join(` `)}`})}u.push({command:t,description:`see all available commands`});let f={description:u.length===1?`Suggested command:`:`Suggested commands:`,commands:u};if(s&&!m){d(Qb({code:`COMMAND_NOT_FOUND`,message:l})),d($b(le?{...f,commands:[...f.commands,...le.commands]}:f)),a(1);return}ve({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:l},meta:{command:pe.error,cta:f,duration:`${Math.round(performance.now()-P)}ms`}}),a(1);return}if(`fetchGateway`in pe){if(!M(!0))return;let{fetchGateway:t,path:n,rest:i}=pe,o=[...r.middlewares??[],...pe.middlewares??[]],c=async()=>{let r=jn(i);t.basePath&&(r.path=t.basePath+r.path);let o=Mn(r),c=await t.fetch(o);if(Nn(c)){await rx(Pn(c),{name:e,path:n,start:P,format:de,formatExplicit:g,human:s,renderOutput:he,fullOutput:m,truncate:_e,write:ve,writeln:d,exit:a});return}let l=await Fn(c);l.ok?ve({ok:!0,data:l.data,meta:{command:n,duration:`${Math.round(performance.now()-P)}ms`}}):(ve({ok:!1,error:{code:`HTTP_${l.status}`,message:typeof l.data==`object`&&l.data!==null&&`message`in l.data?String(l.data.message):typeof l.data==`string`?l.data:`HTTP ${l.status}`},meta:{command:n,duration:`${Math.round(performance.now()-P)}ms`}}),a(1))};try{let t=r.envSchema?Wl(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=>({[Ax]:`error`,...e}),format:de,formatExplicit:g,globals:A,name:e,set(e,t){i[e]=t},var:i,version:r.version},d=e=>{if(!nx(e)||e[Ax]!==`error`)return;let t=e,r=xu(u,t.cta);ve({ok:!1,error:{code:t.code,message:t.message,...t.retryable===void 0?void 0:{retryable:t.retryable}},meta:{command:n,duration:`${Math.round(performance.now()-P)}ms`,...r?{cta:r}:void 0}}),a(t.exitCode??1)};await o.reduceRight((e,t)=>async()=>{d(await t(l,e))},c)()}else await c()}catch(e){ve({ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:n,duration:`${Math.round(performance.now()-P)}ms`}}),a(e instanceof L?e.exitCode??1:1)}return}let{command:ye,path:be,rest:F}=pe;if(!M(!0))return;let xe=[...r.middlewares??[],...`middlewares`in N?N.middlewares??[]:[],...ye.middleware??[]];s&&gx(F,ye.options,ye.alias);let Se;if(c)try{Se=await Cb(e,be,{configDisabled:O,configPath:D,files:r.config?.files,loader:r.config?.loader})}catch(e){ve({ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:be,duration:`${Math.round(performance.now()-P)}ms`}}),a(e instanceof L?e.exitCode??1:1);return}let Ce=await Xl(ye,{agent:!s,argv:F,defaults:Se,displayName:u,env:r.envSchema,envSource:r.env,format:de,formatExplicit:g,globals:A,inputOptions:{},middlewares:xe,name:e,path:be,vars:r.vars,version:r.version}),we=`${Math.round(performance.now()-P)}ms`;if(`stream`in Ce){await rx(Ce.stream,{name:u,path:be,start:P,format:de,formatExplicit:g,human:s,renderOutput:he,fullOutput:m,truncate:_e,write:ve,writeln:d,exit:a});return}if(Ce.ok){let e=xu(u,Ce.cta);ve({ok:!0,data:Ce.data,meta:{command:be,duration:we,...e?{cta:e}:void 0}})}else{let e=xu(u,Ce.cta);if(s&&!g&&Ce.error.fieldErrors){d(yb(u,be,ye,new On({message:Ce.error.message,fieldErrors:Ce.error.fieldErrors}),r.env,l)),a(1);return}ve({ok:!1,error:{code:Ce.error.code,message:Ce.error.message,...Ce.error.retryable===void 0?void 0:{retryable:Ce.error.retryable},...Ce.error.fieldErrors?{fieldErrors:Ce.error.fieldErrors}:void 0},meta:{command:be,duration:we,...e?{cta:e}:void 0}}),a(Ce.exitCode??1)}}function mb(e,t,n={}){let r;async function i(r,i,a){let{fromJsonSchema:o,McpServer:s,WebStandardStreamableHTTPServerTransport:c}=await Promise.resolve().then(()=>(B_(),d_)),l=new s({name:e,...n.title?{title:n.title}:void 0,version:t},n.instructions?{instructions:n.instructions}:void 0);G_(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 hb(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 gb(e,t,n){let r={name:e,description:n.description};return xx.set(r,t),n.rootCommand&&wx.set(r,n.rootCommand),_v(r,{title:e,...n.version?{version:n.version}:void 0,...n.description?{description:n.description}:void 0})}async function _b(e,t,n,r={}){let i=performance.now(),a=new URL(n.url),o=a.pathname.split(`/`).filter(Boolean);if(n.method===`GET`&&hb(o)){let n=gb(e,t,r),i=o[0]===`openapi.yml`||o[0]===`openapi.yaml`;return new Response(i?(await bl()).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 bl();let n=new Map,i=lx(t,[],n,r.rootCommand);if(o[2]===`index.json`&&o.length===3){let t=Ty(e,i,1,n).map(t=>{let n=t.content.match(/^---\n([\s\S]*?)\n---/),r=n?xl().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=Ty(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(Vr(e),{status:t,headers:{"content-type":`application/json`}})}if(o.length===0)return r.rootCommand?vb(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=xb(t,o);if(`error`in l){let t=l.path?`${e} ${l.path}`:e,n=un(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 vb(d,u,f,s,n,i,{...r,groupMiddlewares:p})}async function vb(e,t,n,r,i,a,o){function s(e,t){return new Response(Vr(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 Xl(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(xu(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(nx(s)&&s[Ax]===`error`){a.enqueue(n.encode(Vr(i(s))+`
216
- `)),a.close();return}let t=nx(s)&&s[Ax]===`ok`?xu(o.name??e,s.cta):void 0;a.enqueue(n.encode(Vr({type:`done`,ok:!0,meta:r(t)})+`
217
- `)),a.close();return}if(nx(s)&&s[Ax]===`error`){a.enqueue(n.encode(Vr(i(s))+`
218
- `)),await t.return(void 0),a.close();return}a.enqueue(n.encode(Vr({type:`chunk`,data:s})+`
219
- `))}catch(e){a.enqueue(n.encode(Vr({type:`error`,ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof L?{retryable:e.retryable}:void 0},meta:r()})+`
220
- `)),a.close()}}});return new Response(s,{status:200,headers:{"content-type":`application/x-ndjson`}})}if(!d.ok){let t=xu(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=xu(o.name??e,d.cta);return s({ok:!0,data:d.data,meta:{command:e,duration:f,...p?{cta:p}:void 0}},200)}function yb(e,t,n,r,i,a){let o=[];for(let e of r.fieldErrors){let t=(()=>{let t=bb(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(cu(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:px(n.examples),usage:n.usage})),o.join(`
221
- `)}function bb(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:`--${cn(n)}${e}`}}return e.env?.shape[n]?{kind:`environment variable`,label:`${n}${r.length>0?`.${r.join(`.`)}`:``}`}:{kind:`argument`,label:`<${t}>`}}function xb(e,t){let[n,...r]=t;if(!n||!e.has(n))return{error:n??`(none)`,path:``,commands:e,rest:r};let i=Xb(e,e.get(n)),a=[n],o=r,s,c=[];if(Jb(i)){let e=i.outputPolicy??s;return{fetchGateway:i,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}for(;qb(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&&!un(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=Xb(i.commands,t);if(a.push(e),o=o.slice(1),i=n,Jb(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 Sb(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(!bx.has(e[t+1]))throw new kn({message:`Invalid format: "${e[t+1]}". Expected one of: ${[...bx].join(`, `)}`});d=e[t+1],f=!0,t++}else if(b&&C===b){let n=e[t+1];if(n===void 0)throw new kn({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 kn({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 kn({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 kn({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 Cb(e,t,n={}){if(n.configDisabled)return;let{loader:r}=n,i;i=n.configPath?wb(n.configPath):await Tb(n.files??[`${e}.json`]);let a;if(r){let e=await r(i);if(e===void 0)return;if(!sn(e))throw new kn({message:`Config loader must return a plain object or undefined`});a=e}else{if(!i)return;let e=await Eb(i,!!n.configPath);if(!e)return;a=e}return Db(a,e,t)}function wb(e){return e.startsWith(`~/`)||e===`~`?c.join(b.homedir(),e.slice(1)):c.resolve(process.cwd(),e)}async function Tb(e){for(let t of e){let e=wb(t);try{return await C.access(e,C.constants.R_OK),e}catch{}}}async function Eb(e,t){let n;try{n=await C.readFile(e,`utf8`)}catch(n){if(n.code===`ENOENT`){if(t)throw new kn({message:`Config file not found: ${e}`});return}throw n}let r;try{r=JSON.parse(n)}catch(t){throw new kn({message:`Invalid JSON config file: ${e}`,cause:t instanceof Error?t:void 0})}if(!sn(r))throw new kn({message:`Invalid config file: expected a top-level object in ${e}`});return r}function Db(e,t,n){let r=n===t?[]:n.split(` `),i=e;for(let e of r){if(!sn(i))return;let t=i.commands;if(!sn(t)||(i=t[e],i===void 0))return}if(!sn(i))throw new kn({message:`Invalid config section for '${n}': expected an object`});let a=i.options;if(a!==void 0){if(!sn(a))throw new kn({message:`Invalid config 'options' for '${n}': expected an object`});return Object.keys(a).length>0?a:void 0}}function Ob(e){let t=[];for(let[n,r]of e)Yb(r)||t.push({name:n,description:r.description});return t.sort((e,t)=>e.name.localeCompare(t.name))}function kb(e,t,n){return tu(e[0])?.name===n?0:e[0]===t&&tu(e[1])?.name===n?1:-1}function Ab(e,t){return su(`${e} ${t.name}`,{aliases:t.aliases,description:t.description,commands:t.subcommands?.map(e=>({name:e.name,description:e.description}))})}function jb(e,t,n){let r=nu(t,n);return cu(`${e} ${t.name} ${n}`,{alias:r?.alias,aliases:r?.aliases,description:r?.description,hideGlobalOptions:!0,options:r?.options})}async function Mb(e,t,n){let r=[],i=[],a=new T,o=new T,s=[];o.on(`data`,e=>s.push(e.toString()));let c,l=V_(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(`${Vr({jsonrpc:`2.0`,id:1,method:`initialize`,params:{protocolVersion:`2024-11-05`,capabilities:{},clientInfo:{name:`incur-doctor`,version:`1.0.0`}}})}\n`),a.write(`${Vr({jsonrpc:`2.0`,id:2,method:`tools/list`,params:{}})}\n`),await Nb(s,()=>u),a.end(),await l,c)return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_SERVER_FAILED`,message:Fb(c)}]};let d;try{d=Pb(s)}catch(e){return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_RESPONSE_PARSE_FAILED`,message:Fb(e)}]}}let f=d.find(e=>e.id===1);f?f.error&&i.push({code:`MCP_INITIALIZE_FAILED`,message:Ib(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:Ib(p.error)}):!sn(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(sn).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 Nb(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 Pb(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(!sn(r))throw Error(`Expected JSON-RPC response object.`);t.push(r)}return t}function Fb(e){return e instanceof Error?e.message:String(e)}function Ib(e){return sn(e)&&typeof e.message==`string`?e.message:Vr(e)}function Lb(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 Rb(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 zb(e){let t=await Tu(e.directory,{exclude:e.exclude});return Promise.all(t.map(async e=>({...e,command:(await import(te(e.file).href)).default})))}function Bb(e){return typeof e==`object`&&!!e&&e[yx]===!0}function Vb(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(qb(c)&&!c.root)c.root=n,c.description??=n.description;else throw Hb(t,r);Zb(t.join(` `),n,i);for(let e of n.aliases??[]){if(a.has(e))throw Hb([...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(Yb(c)||Jb(c))throw Hb(t,r);if(qb(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 Hb(e,t){return Error(`Filesystem command '${e.join(` `)}' from '${t}' conflicts with an existing command or alias.`)}function Ub(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 Wb(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 Gb(e){return typeof e==`function`?e:e.fetch}function Kb(e){return typeof e==`function`?void 0:e.url}function qb(e){return`_group`in e}function Jb(e){return`_fetch`in e}function Yb(e){return`_alias`in e}function Xb(e,t){return Yb(t)?e.get(t.target):t}function Zb(e,t,n){if(!(!n||Jb(t)||Yb(t))){if(qb(t)){t.root&&Zb(e,t.root,n);for(let[r,i]of t.commands)Zb(`${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 $b(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 ex(...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 tx(e){return Object.values(e.shape).some(e=>e._zod.optout!==`optional`)}function nx(e){return typeof e==`object`&&!!e&&Ax in e}async function rx(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(nx(i)){let e=i;if(e[Ax]===`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(Vr({type:`chunk`,data:i})):t.renderOutput&&t.writeln(t.truncate(wl(i,t.format)).text)}if(nx(r)&&r[Ax]===`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=nx(r)&&r[Ax]===`ok`?xu(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($b(i))}catch(e){n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof L?{retryable:e.retryable}:void 0}})):t.writeln(Qb({code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)})),t.exit(e instanceof L?e.exitCode??1:1)}else{let n=[];try{let r;for(;;){let{value:i,done:a}=await e.next();if(a){r=i;break}if(nx(i)){let e=i;if(e[Ax]===`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(nx(r)&&r[Ax]===`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=nx(r)&&r[Ax]===`ok`?xu(t.name,r.cta):void 0;t.write({ok:!0,data:n,meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`,...i?{cta:i}:void 0}})}catch(e){t.write({ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof L?{retryable:e.retryable}:void 0},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e instanceof L?e.exitCode??1:1)}}}function ix(e,t=[],n,r){let i=ax(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:Nu(n)}:void 0}}function ax(e,t){let n=[];for(let[r,i]of e){if(Yb(i))continue;let e=[...t,r];if(qb(i)){if(i.root){let t={name:e.join(` `)};i.root.description&&(t.description=i.root.description),n.push(t)}n.push(...ax(i.commands,e))}else{let t={name:e.join(` `)};Jb(i),i.description&&(t.description=i.description),n.push(t)}}return n}function ox(e,t=[],n,r){let i=sx(e,t);return r&&t.length>0&&i.push(cx(t,r)),{version:`incur.v1`,commands:i.sort((e,t)=>e.name.localeCompare(t.name)),...n?{globals:Nu(n)}:void 0}}function sx(e,t){let n=[];for(let[r,i]of e){if(Yb(i))continue;let e=[...t,r];if(Jb(i)){let t={name:e.join(` `)};i.description&&(t.description=i.description),n.push(t)}else qb(i)?(i.root&&n.push(cx(e,i.root)),n.push(...sx(i.commands,e))):n.push(cx(e,i))}return n}function cx(e,t){let n={name:e.join(` `)};t.description&&(n.description=t.description);let r=hx(t.args,t.env,t.options),i=t.output?Nu(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=px(t.examples);if(a){let t=e.join(` `);n.examples=a.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function lx(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),dx(r)&&(e.hint=fx(e.hint)),r.options&&(e.options=r.options),r.output&&(e.output=r.output);let t=px(r.examples);t&&(e.examples=t),i.push(e)}for(let[r,a]of e){if(Yb(a))continue;let e=[...t,r];if(Jb(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 qb(a)?(a.description&&n.set(e.join(` `),a.description),a.root&&i.push(ux(e,a.root)),i.push(...lx(a.commands,e,n))):i.push(ux(e,a))}return i.sort((e,t)=>(e.name??``).localeCompare(t.name??``))}function ux(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),dx(t)&&(n.hint=fx(n.hint)),t.options&&(n.options=t.options),t.output&&(n.output=t.output);let r=px(t.examples);if(r){let t=e.join(` `);n.examples=r.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function dx(e){return e.destructive===!0||e.mcp!==!1&&e.mcp?.annotations?.destructiveHint===!0}function fx(e){return e?e.includes(vx)?e:`${e} ${vx}`:vx}function px(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 mx(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return{};let n=xl().parse(t[1]);return!n||typeof n!=`object`?{}:n}function hx(e,t,n){if(!e&&!t&&!n)return;let r={};return e&&(r.args=Nu(e)),t&&(r.env=Nu(t)),n&&(r.options=Nu(n)),r}function gx(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 _x(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 vx,yx,bx,xx,Sx,Cx,wx,Tx,Ex,Dx,Ox,kx,Ax,jx=I((()=>{on(),Ut(),Tn(),An(),Rn(),Hn(),Ml(),bu(),ou(),wu(),Mu(),dn(),Ur(),st(),Dt(),Cl(),fv(),xy(),sy(),Yl(),Pu(),My(),Hy(),db(),vx=`Confirm with the user before executing this destructive command.`,yx=Symbol.for(`incur.fileCommand`),bx=new Set([`toon`,`json`,`yaml`,`md`,`jsonl`]),xx=new WeakMap,Sx=new WeakMap,Cx=new WeakMap,wx=new WeakMap,Tx=new WeakMap,Ex=new WeakMap,Dx=new WeakMap,Ox=new WeakMap,kx=new WeakMap,Ax=Symbol.for(`incur.sentinel`)})),Mx=I((()=>{Ut(),jx(),Tn(),An(),Ml(),bu(),fv(),Rn(),sy(),Yl(),Pu(),My(),Cl(),Hy(),db()}));function Nx(e,t){if(!(!e||typeof e!=`object`))return e[t]}var q,Px,Fx,Ix,Lx,Rx,zx=I((()=>{q={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Px={payment:`Payment`},Fx={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Ix={charge:`charge`,session:`session`,subscription:`subscription`},Lx={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},Rx={v1:`v1`,v2:`v2`}}));function Bx(e){let t=O.toString(e);return JSON.parse(t)}function Vx(e,t){return e.schema.request.parse(t)}function Hx(e){let t=j.canonicalize(e);return O.fromString(t,{pad:!1,url:!0})}var Ux=I((()=>{})),J=tt({address:()=>Xx,amount:()=>Gx,datetime:()=>Kx,datetimeInput:()=>qx,hash:()=>Zx,period:()=>Qx,signature:()=>$x,toDate:()=>Jx,toDatetimeString:()=>Yx,unwrapOptional:()=>eS});import*as Wx from"zod/mini";rt(J,Wx);function Gx(){return xe.string().check(xe.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function Kx(){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 qx(e=`Invalid ISO 8601 datetime`){return xe.pipe(xe.union([Kx(),xe.custom(e=>e instanceof Date)]),xe.transform(Jx)).check(xe.refine(e=>Number.isFinite(e.getTime()),e))}function Jx(e){return e instanceof Date?e:new Date(e)}function Yx(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function Xx(){return xe.string().check(xe.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function Zx(){return xe.string().check(xe.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function Qx(){return xe.string().check(xe.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function $x(){return xe.string().check(xe.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function eS(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}var tS=I((()=>{}));function nS(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=vS(o)?void 0:o,f=e.expires?Yx(e.expires):void 0,p=e.opaque??(i===void 0?void 0:Hx(i)),m=u?yS({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return xS.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 rS(e){let t=[iS(`id`,e.id),iS(`realm`,e.realm),iS(`method`,e.method),iS(`intent`,e.intent),iS(`request`,Hx(e.request))];e.description!==void 0&&t.push(iS(`description`,e.description)),e.digest!==void 0&&t.push(iS(`digest`,e.digest)),e.expires!==void 0&&t.push(iS(`expires`,e.expires));let n=e.header;return n!==void 0&&!vS(n)&&t.push(iS(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(iS(`opaque`,Hx(e.meta))):t.push(iS(`opaque`,e.opaque)),`${Px.payment} ${t.join(`, `)}`}function iS(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 aS(e,t){let n=oS(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=sS(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>bS)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 nS({...a,request:Bx(r),...i&&{opaque:i}},t)}function oS(e){let t=Px.payment,[n]=fS(e,t);if(n===void 0)return null;let r=n+t.length;for(;r<e.length&&/\s/.test(e[r]??``);)r++;return e.slice(r)}function sS(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]=cS(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function cS(e,t){if(e[t]===`"`)return lS(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function lS(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 uS(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 dS(e){return fS(e,Px.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===Px.payment.toLowerCase())}function fS(e,t){let n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(!uS(e,a,t))continue;let s=a-1;for(;s>=0&&/\s/.test(e[s]??``);)s--;s>=0&&e[s]!==`,`||n.push(a)}return n}function pS(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return mS(e.headers,t)}function mS(e,t){let n=e.get(q.wwwAuthenticate);if(!n)throw Error(`Missing ${q.wwwAuthenticate} header.`);return hS(n,t)}function hS(e,t){let n=fS(e,Px.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 aS(e.slice(r,a).replace(/,\s*$/,``),t)})}function gS(e){let t=[e.realm,e.method,e.intent,Hx(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!vS(n)&&t.push(n),t.push(e.opaque??(e.meta?Hx(e.meta):``)),t.join(`|`)}function _S(e){return e.header??q.authorization}function vS(e){return e?.toLowerCase()===q.authorization.toLowerCase()}function yS(e,t){let n=gS(e),r=k.fromString(t.secretKey),i=k.fromString(n),a=ne.hmac256(r,i,{as:`Bytes`});return O.fromBytes(a,{url:!0,pad:!1})}var bS,xS,SS=I((()=>{zx(),Ux(),tS(),bS=16384,xS=J.object({description:J.optional(J.string()),digest:J.optional(J.string().check(J.regex(/^sha-256=/,`Invalid digest format`))),expires:J.optional(Kx()),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())})})),CS,wS,Y,TS,ES,DS,OS=I((()=>{CS=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}}}},wS=class extends CS{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 CS{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})}},TS=class extends CS{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.`)}},ES=class extends CS{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}},DS=class extends Error{name=`ZoneSettlementPendingError`;challengeId;senderTag;zoneId;constructor(e){let{cause:t,challengeId:n,senderTag:r,zoneId:i}=e;super(`Zone ${i} withdrawal ${r} for challenge "${n}" has not settled on Tempo yet. Retry the challenge to resume waiting instead of paying again.`),this.challengeId=n,this.senderTag=r,this.zoneId=i,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}}}));function kS(e,t){if(!e)throw new wS({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new wS({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new TS({expires:e})}var AS=I((()=>{OS()}));function jS(e){if(e.length>LS)throw new zS;let t=e.match(RegExp(`^${Px.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new RS;try{let e=O.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=MS(r);return{challenge:xS.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Bx(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new zS}}function MS(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!NS(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:Hx(e)}}function NS(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function PS(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function FS(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:Hx(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:Hx(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=O.fromString(s,{pad:!1,url:!0});return`${Px.payment} ${c}`}function IS(e){return e.length>LS?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${Px.payment}\\s+`,`i`).test(e))??null}var LS,RS,zS,BS=I((()=>{SS(),zx(),Ux(),LS=65536,RS=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},zS=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}}}));function VS(){let e=new Uint8Array(64);return crypto.getRandomValues(e),{created:Math.floor(Date.now()/1e3),nonce:O.fromBytes(e,{pad:!1,url:!0})}}var HS=I((()=>{}));function US(e){if(e.length===0)throw TypeError(`Mppx client identity must configure at least one prover.`);for(let t of e)if(t.scope!==`*`&&!Array.isArray(t.scope))throw TypeError(`Identity prover scope must be "*" or an array of origins.`);let t=t=>{let n=new URL(t).origin;return e.filter(e=>e.scope===`*`||e.scope.includes(n))};async function n(e,n,r,i){let a=i?n.clone():n,o=t(n.url);if(o.length===0)return{request:a,response:await e(a)};let s=Object.freeze({...r,...VS()}),c=new Request(a,{redirect:n.redirect===`follow`?`error`:n.redirect});for(let e of o)c=await e.prove(c,s);return{request:c,response:await e(c)}}return{async send(e,r,i={}){let a=!(i.challenge!==void 0||YS.some(e=>r.headers.has(e))||[...r.headers.values()].some(e=>IS(e)!==null))&&t(r.url).some(e=>e.retry),o=await n(e,r,i,a),{response:s}=o;if(!a||s.status<400||s.status===402)return o;let c=[],l=!1;for(let e of t(r.url)){if(!e.retry)continue;let t=s.clone();c.push(t),await e.retry(t)&&(l=!0)}return l?(WS([s,...c]),n(e,r,i,!1)):(WS(c),o)},async challenge(e,n,r){for(let i of t(r)){if(!i.prepare)continue;let t=e.clone();try{await i.prepare(t,n)}finally{WS([t])}}}}}function WS(e){for(let t of e)t.bodyUsed||t.body?.cancel().catch(()=>{})}function GS(e,t,n){return async(r,i)=>{let a=new Request(r,i),o=qS(a.headers)??n?.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[JS]?{[JS]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of KS(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{...n,challenge:e},a.url);return s}}function KS(e){try{return pS(e)}catch{return[]}}function qS(e){for(let[,t]of e){let e=IS(t);if(e)try{return jS(e).challenge}catch{}}}var JS,YS,XS=I((()=>{SS(),BS(),HS(),JS=Symbol.for(`mppx.fetch.skipPayment`),YS=[`payment-signature`,`x-payment`]}));function ZS(e){return Object.defineProperty(e,$S,{value:!0}),e}function QS(e){return!!e?.[$S]}var $S,eC=I((()=>{$S=Symbol.for(`mppx.x402.challenge`)}));function tC(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=sC(n)}return t}function nC(e,t){let n=tC(e),r=mC(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[sC(e)]??1,index:t}));return{definition:r,entries:i,header:iC(i),keys:n}}function rC(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)=>fC(e,t))}function iC(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${vC(n)}`}).join(`, `)}function aC(e,t,n){let r=oC(e,t,n)[0];if(r)return{challenge:r.challenge,method:r.method}}function oC(e,t,n,r){let i=new Map;for(let e of t){let t=sC(e),n=i.get(t);n?n.push(e):i.set(t,[e])}return e.flatMap((e,t)=>{let a=i.get(sC(e));if(!a)return[];let o=cC(e,n);return!o||o.q<=0?[]:a.filter(t=>t.canHandleChallenge?.(r===void 0?{challenge:e}:{challenge:e,context:r})??!0).map(n=>({challenge:e,index:t,match:o,method:n}))}).sort((e,t)=>dC(e.challenge)-dC(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function sC(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function cC(e,t){let n;for(let r of t){if(!lC(e,r))continue;let t={...r,specificity:uC(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 lC(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function uC(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function dC(e){return+!!QS(e)}function fC(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}`);yC(r,`method`),yC(i,`intent`);let a=1;for(let t of pC(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=gC(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function pC(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function mC(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>sC(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]=hC(t,`payment preference "${e}"`)}return a}function hC(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return _C(e,t)}function gC(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 _C(Number(e),t)}function _C(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 vC(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function yC(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}var bC,xC=I((()=>{eC(),bC=Symbol(`mppx.deferredContext`)})),SC,CC,wC=I((()=>{SC=`org.paymentauth/credential`,CC=`org.paymentauth/payment-required`}));function TC(e){let t=``,n=!1,r=!1,i,a=``;function o(t){if(t===``){i!==void 0&&e({data:i,event:a||`message`}),i=void 0,a=``;return}let n=t.indexOf(`:`);if(n===0)return;let r=n===-1?t:t.slice(0,n);if(r!==`data`&&r!==`event`)return;let o=``;n!==-1&&(o=t.slice(t.charCodeAt(n+1)===32?n+2:n+1)),r===`event`?a=o:i=i===void 0?o:i+`
205
+ `)}`}function jy(e){return e.toLowerCase().replace(/[^a-z0-9-]+/g,`-`).replace(/-{2,}/g,`-`).replace(/^-|-$/g,``)}function My(e){if(!e)return`unknown`;let t=e.type;return t?t===`integer`?`number`:t:`unknown`}var Ny=F((()=>{wl(),Fu()}));async function Py(e,t={}){let n=st(),r=t.command??Iy(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 Hy(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`))&&Fy(e,r)&&o.push(`Amp`),{command:r,agents:o}}function Fy(e,t){let n=d(C(),`.config`,`amp`,`settings.json`),s={};if(r(n))try{s=JSON.parse(a(n,`utf-8`))}catch{return!1}let[c,...l]=Vy(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 Iy(e,t){return Ry(e)?`${e} --mcp`:`${t} ${By(e)} --mcp`}function Ly(){let e=(process.argv[1]?.replace(/\\/g,`/`))?.match(/^(.+)\/node_modules\/(.+)$/);return e?{root:e[1],entry:e[2]}:null}function Ry(e){let t=process.argv[1];if(!t)return!1;let n=Ly();if(n)return!n.entry.startsWith(`.bin/`)&&!zy(n.root,e);let r=t.replace(/\\/g,`/`).split(`/`).pop();return r===e||r===`${e}.cmd`||r===`${e}.ps1`}function zy(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 By(e){let t=Ly();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 Vy(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 Hy(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 Uy=F((()=>{lt()}));function Wy(){return eb.filter(e=>e.detect())}function Gy(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??Wy(),l=[],u=[];for(let n of qy(e)){let e=c.join(o,n.name);Yy(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(Xy(s)!==Xy(e))try{Yy(s),t.mkdirSync(c.dirname(s),{recursive:!0});let n=Xy(c.dirname(s)),r=Xy(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 Ky(e,t={}){let n=t.global!==!1,r=t.cwd||process.cwd(),i=n?K:r;Yy(c.join(i,`.agents`,`skills`,e));for(let t of Wy()){if(t.universal)continue;let i=n?t.globalSkillsDir:c.join(r,t.projectSkillsDir);Yy(c.join(i,e))}}function qy(e){let n=[];function r(e){let i;try{i=t.readdirSync(e,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let i=c.join(e,a.name),o=c.join(i,`SKILL.md`);if(t.existsSync(o)){let e=t.readFileSync(o,`utf8`).match(/^name:\s*(.+)$/m);n.push({name:Jy(e?.[1]??a.name),dir:i})}r(i)}}r(e);let i=c.join(e,`SKILL.md`);if(t.existsSync(i)){let r=Jy(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 Jy(e){return e.trim().replace(/[/\\]/g,`-`).replace(/\.\./g,``).slice(0,255)}function Yy(e){try{t.lstatSync(e).isSymbolicLink()?t.unlinkSync(e):t.rmSync(e,{recursive:!0,force:!0})}catch{}}function Xy(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,Zy,Qy,$y,eb,tb=F((()=>{K=x.homedir(),Zy=process.env.XDG_CONFIG_HOME||c.join(K,`.config`),Qy=process.env.CLAUDE_CONFIG_DIR?.trim()||c.join(K,`.claude`),$y=process.env.CODEX_HOME?.trim()||c.join(K,`.codex`),eb=[{name:`Amp`,globalSkillsDir:c.join(Zy,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(Zy,`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($y,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync($y)},{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(Zy,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.kimi`))},{name:`OpenCode`,globalSkillsDir:c.join(Zy,`opencode`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(Zy,`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(Zy,`goose`,`skills`),projectSkillsDir:`.goose/skills`,universal:!1,detect:()=>t.existsSync(c.join(Zy,`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(Zy,`crush`,`skills`),projectSkillsDir:`.crush/skills`,universal:!1,detect:()=>t.existsSync(c.join(Zy,`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 nb(e,t,n={}){let{depth:r=1,description:i,global:a=!0}=n,o=n.cwd??(a?ab():process.cwd());await xl();let s=new Map;i&&s.set(e,i);let c=Ey(e,ux(t,[],s,n.rootCommand),r,s),u=await T.mkdtemp(l.join(S.tmpdir(),`incur-skills-${e}-`));try{let r=[];for(let t of c){let n=t.dir?l.join(u,t.dir,`SKILL.md`):l.join(u,`SKILL.md`);await T.mkdir(l.dirname(n),{recursive:!0}),await T.writeFile(n,`${t.content}\n`);let i=hx(t.content);r.push({name:i.name??(t.dir||e),description:i.description})}if(n.include)for(let t of n.include){let n=t===`_root`?`SKILL.md`:l.join(t,`SKILL.md`);for await(let i of T.glob(n,{cwd:o}))try{let n=await T.readFile(l.resolve(o,i),`utf8`),a=hx(n),s=t===`_root`?a.name??e:l.basename(l.dirname(i)),c=l.join(u,s,`SKILL.md`);await T.mkdir(l.dirname(c),{recursive:!0}),await T.writeFile(c,n),r.some(e=>e.name===s)||r.push({name:s,description:a.description,external:!0})}catch{}}let{paths:i,agents:s}=Gy(u,{global:a,cwd:o}),d=new Set(i.map(e=>l.basename(e))),f=cb(e);if(f?.skills)for(let e of f.skills)d.has(e)||Ky(e,{global:a,cwd:o});return sb(e,ky(ux(t,[],new Map,n.rootCommand)),[...d],[...i,...s.map(e=>e.path)]),{skills:r.sort((e,t)=>e.name.localeCompare(t.name)),paths:i,agents:s}}finally{await T.rm(u,{recursive:!0,force:!0})}}async function rb(e,t,n={}){let{depth:r=1,description:i}=n,a=n.cwd??process.cwd();await xl();let o=new Map;i&&o.set(e,i);let s=Ey(e,ux(t,[],o,n.rootCommand),r,o),c=[],u=lb(e,{cwd:a});for(let t of s){let n=hx(t.content),r=n.name??(t.dir||e);c.push({name:r,description:n.description,installed:u.has(r)})}if(n.include)for(let t of n.include){let n=t===`_root`?`SKILL.md`:l.join(t,`SKILL.md`);for await(let r of T.glob(n,{cwd:a}))try{let n=hx(await T.readFile(l.resolve(a,r),`utf8`)),i=t===`_root`?n.name??e:l.basename(l.dirname(r));c.some(e=>e.name===i)||c.push({name:i,description:n.description,installed:u.has(i)})}catch{}}return c.sort((e,t)=>e.name.localeCompare(t.name))}function ib(e,t={}){return lb(e,t).size>0}function ab(){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 ob(e){let t=process.env.XDG_DATA_HOME||l.join(S.homedir(),`.local`,`share`);return l.join(t,`incur`,`${e}.json`)}function sb(e,t,r,i){let a=ob(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 cb(e){try{return JSON.parse(n.readFileSync(ob(e),`utf-8`))}catch{return}}function lb(e,t={}){let n=cb(e);if(!n?.skills?.length)return new Set;if(n.paths?.length){let e=n.paths.filter(e=>ub(e)).map(e=>l.basename(e));return new Set(e)}let r=t.cwd??process.cwd(),i=[l.join(S.homedir(),`.agents`,`skills`),l.join(r,`.agents`,`skills`)],a=n.skills.filter(e=>i.some(t=>ub(l.join(t,e))));return new Set(a)}function ub(e){return n.existsSync(l.join(e,`SKILL.md`))}function db(e){return cb(e)?.hash}var fb=F((()=>{Mx(),tb(),wl(),Ny()}));function pb(e,t){let n=typeof e==`string`?e:e.name,r=typeof e==`string`?t??{}:e,i=r.version??Wt,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:Kb(o),c=o===void 0?void 0:qb(o),l=new Map,u=[],d=[],f=hb(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 Fv(await Nv(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(Gb(t))return d.push((async()=>{let n=uy(await ly(t.mcp)),r={_group:!0,description:t.description,commands:n,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0};Qb(e,r,kx.get(p)),l.set(e,r)})()),p;if(t&&`fetch`in t&&Wb(t.fetch)){let n=Kb(t.fetch);return t.openapi?(d.push((async()=>{let r=await Fv(await Nv(t.openapi,{baseUrl:qb(t.fetch)}),n,{basePath:t.basePath,config:t.openapiConfig}),i={_group:!0,description:t.description,commands:r,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0,...t.mcp===!1?{mcp:!1}:void 0};Qb(e,i,kx.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,kx.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=Tx.get(e),r=e,i=Sx.get(r),a=Ox.get(r),o=wx.get(r),s=Cx.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,kx.get(p))})):Qb(r.name,c,kx.get(p)),l.set(r.name,c),n){let t=Ax.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=kx.get(p);return vb(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=Du();return d.push((async()=>{let n=t?await Ou(t):await Bb(await zb(e));for(let e of n){if(!Vb(e.command))throw Error(`Expected the default export from '${e.file}' to be created with \`Cli.command()\`.`);Hb(l,e.segments,e.command,e.file,kx.get(p))}})()),p},async serve(e=process.argv.slice(2),t={}){if(await At(e))return;d.length>0&&await Promise.all(d);let o=kx.get(p);return mb(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&&Tx.set(p,a),a&&r.aliases&&Ax.set(p,r.aliases),r.options&&Ex.set(p,r.options),r.config!==void 0&&Dx.set(p,!0),r.outputPolicy&&Ox.set(p,r.outputPolicy),r.globals){kx.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 wx.set(p,u),Sx.set(p,l),Cx.set(p,d),p}async function mb(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=vx(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=Cb(n,{configFlag:l})}catch(e){let t=e instanceof Error?e.message:String(e);d(s?$b({code:`UNKNOWN`,message:t}):Tl({code:`UNKNOWN`,message:t},`toon`)),a(1);return}let{fullOutput:m,format:h,formatExplicit:g,filterOutput:_,tokenLimit:v,tokenOffset:y,tokenCount:b,llms:x,llmsFull:S,mcp:C,help:w,update:T,updateCheck:E,version:ee,schema:D,configPath:O,configDisabled:k,rest:A}=p;s=o&&!g;let te={...typeof r.update==`object`?r.update:void 0,binary:Ut!==void 0,version:r.version},ne={},j=A;function re(e){if(!r.globals)return!0;try{let t=Jl(A,r.globals.schema,r.globals.alias,{validate:e});return e&&(ne=t.parsed),j=t.rest,!0}catch(e){let t=e instanceof Error?e.message:String(e);return d(s?$b({code:`UNKNOWN`,message:t}):Tl({code:`UNKNOWN`,message:t},`toon`)),a(1),!1}}if(!re(!1))return;if(h===`yaml`&&await xl(),E){if(r.update!==!1)try{await dt(e,te)}catch{}return}if(T&&!w){try{let t=await ft(e,te);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(Tl(t,h))}catch(e){let t={code:`UPDATE_FAILED`,message:e instanceof Error?e.message:String(e)};d(s?$b(t):Tl(t,h)),a(1)}return}if(C){await H_(r.mcp?.name??e,r.version??`0.0.0`,t,{middlewares:r.middlewares,env:r.envSchema,vars:r.vars,version:r.version,...r.mcp?.instructions?{instructions:r.mcp.instructions}:void 0,...r.mcp?.title?{title:r.mcp.title}:void 0,...r.mcp?.tools?{tools:r.mcp.tools}:void 0});return}let M=process.env.COMPLETE;if(M){let a=n.indexOf(`--`),o=a===-1?n:n.slice(a+1);if(o.length===0)i([e,...r.aliases??[]].map(e=>mn(M,e)).join(`
211
+ `));else{let e=Number(process.env._COMPLETE_INDEX??o.length-1),n=hn(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 ou)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=nu(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=gn(M,n);c&&i(c)}return}let ie;if(!x&&!S&&!D&&!w&&!T&&!E&&!ee){let n=Ab(j,e,`skills`)!==-1,i=Ab(j,e,`mcp`)!==-1;if(!n&&!i){let n=db(e);n&&ib(e,{cwd:r.sync?.cwd})&&ky(ux(t,[],new Map,r.rootCommand))!==n&&(ie={description:`Skills are out of date:`,commands:[{command:process.env.npm_config_user_agent||process.env.npm_execpath?`${st()} ${By(e)} skills add`:`${u} skills add`,description:`sync outdated skills`}]})}}if(x||S){let n=t,i=[],a=r.description,o=r.rootCommand;for(let e of j){let t=n.get(e);if(!t)break;let r=Zb(n,t);if(Jb(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=ux(n,s,t,o);d(Ty(i.length>0?`${e} ${i.join(` `)}`:e,r,t));return}d(Tl(sx(n,i,r.globals?.schema,o),h));return}if(!g||h===`md`){let t=ux(n,s,new Map,o);d(Cy(i.length>0?`${e} ${i.join(` `)}`:e,t,a));return}d(Tl(ax(n,i,r.globals?.schema,o),h));return}let ae=Ab(j,e,`completions`);if(ae!==-1){let t=j[ae+1];if(w||!t){let t=nu(`completions`);d(lu(`${e} completions`,{args:t.args,description:t.description,hideGlobalOptions:!0,hint:t.hint?.(e)}));return}if(!au.includes(t)){d($b({code:`INVALID_SHELL`,message:`Unknown shell '${t}'. Supported: ${au.join(`, `)}`})),a(1);return}d([e,...r.aliases??[]].map(e=>mn(t,e)).join(`
212
+ `));return}let oe=Ab(j,e,`skills`);if(oe!==-1){let o=nu(`skills`),c=j[oe+1],l=c?ru(o,c):void 0;if(c&&!l){let t=fn(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($b({code:`COMMAND_NOT_FOUND`,message:r})),d(ex(l))):d(Tl({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(jb(e,o));return}if(l?.name===`list`){if(w){d(Mb(e,o,`list`));return}try{let n=await rb(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(Tl({code:`LIST_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(w){d(Mb(e,o,`add`));return}let u=j.slice(oe+2),f=u.indexOf(`--depth`),p=u.find(e=>e.startsWith(`--depth=`)),_=f===-1?p?Number(p.split(`=`)[1]):r.sync?.depth??1:Number(u[f+1]),v=!u.includes(`--no-global`)&&void 0;try{i(`Syncing...`);let n=await nb(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(Tl(e,g?h:`toon`))}}catch(e){d(Tl({code:`SYNC_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}let se=Ab(j,e,`mcp`);if(se!==-1){let o=nu(`mcp`),c=j[se+1],l=c?ru(o,c):void 0;if(c&&!l){let t=fn(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($b({code:`COMMAND_NOT_FOUND`,message:r})),d(ex(l))):d(Tl({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(jb(e,o));return}if(w){d(Mb(e,o,l.name));return}if(l.name===`doctor`){let n=await Nb(e,t,r);d(Tl(n,g?h:`toon`)),n.ok||a(1);return}let u=j.slice(se+2),f=!u.includes(`--no-global`),p=r.mcp?.command,_=[...r.mcp?.agents??[]];for(let e=0;e<u.length;e++)(u[e]===`--command`||u[e]===`-c`)&&u[e+1]?p=u[++e]:u[e]===`--agent`&&u[e+1]&&_.push(u[++e]);try{let t=r.mcp?.name??e;i(`Registering MCP server...`);let n=await Py(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(Tl({name:t,command:n.command,agents:n.agents},g?h:`toon`))}catch(e){d(Tl({code:`MCP_ADD_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(ee&&!w&&r.version){d(r.version);return}if(j.length===0){if(r.rootCommand&&s&&r.rootCommand.args&&nx(r.rootCommand.args)){let n=r.rootCommand;await f(),d(lu(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:mx(n.examples),usage:n.usage,commands:t.size>0?kb(t):void 0,root:!0}));return}if(!(r.rootCommand||r.rootFetch)){await f(),d(cu(e,{aliases:r.aliases,configFlag:l,description:r.description,globals:r.globals,version:r.version,commands:kb(t),root:!0}));return}}let N=j.length===0&&r.rootCommand?{command:r.rootCommand,path:e,rest:[]}:j.length===0&&r.rootFetch?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:[]}:Sb(t,j);if(w&&`fetchGateway`in N){let n=N.path===e?e:`${e} ${N.path}`;N.path===e&&t.size>0?d(cu(e,{aliases:r.aliases,configFlag:l,description:r.description,version:r.version,commands:kb(t),root:!0})):d(Rb(n,N.fetchGateway.description));return}if(w){if(`help`in N||`error`in N){let n=`help`in N?`${e} ${N.path}`:e,i=`help`in N?N.description:r.description,a=`help`in N?N.commands:t,o=n===e;if(o&&r.rootCommand&&a.size>0){let t=r.rootCommand;d(lu(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:mx(t.examples),usage:t.usage,commands:kb(a),root:!0}))}else d(cu(n,{aliases:o?r.aliases:void 0,configFlag:l,description:i,globals:r.globals,version:o?r.version:void 0,commands:kb(a),root:o}))}else if(`command`in N){let n=N.command,i=N.path===e,a=i?e:`${e} ${N.path}`,o=`commands`in N&&N.commands&&N.commands.size>0?kb(N.commands):i&&r.rootCommand&&t.size>0?kb(t):void 0;d(lu(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:mx(n.examples),usage:n.usage,commands:o,root:i}))}return}if(D){if(`help`in N){d(cu(`${e} ${N.path}`,{configFlag:l,description:N.description,globals:r.globals,commands:kb(N.commands)}));return}if(`error`in N){let t=N.path?`${e} ${N.path}`:e,n=fn(N.error,N.commands.keys()),r=n?` Did you mean '${n}'?`:``;d(`Error: '${N.error}' is not a command for '${t}'.${r}`),a(1);return}if(`fetchGateway`in N){d(`--schema is not supported for fetch commands.`),a(1);return}let t=N.command,n=g?h:`toon`,i={};t.args&&(i.args=Pu(t.args)),t.env&&(i.env=Pu(t.env)),t.options&&(i.options=Pu(t.options)),t.output&&(i.output=Pu(t.output)),r.globals?.schema&&(i.globals=Pu(r.globals.schema)),d(Tl(i,n));return}if(`help`in N){d(cu(`${e} ${N.path}`,{configFlag:l,description:N.description,globals:r.globals,commands:kb(N.commands)}));return}let ce;if(s&&r.update!==!1){let t=ut(e,te);t&&(ce={description:`Update available for ${t.name}:`,commands:[{command:`${u} --update`,description:`upgrade from ${t.current} to ${t.latest}`}]})}let le=tx(ie,ce),ue=performance.now(),de=`command`in N&&N.command.format,fe=g?h:de||r.format||`toon`;fe===`yaml`&&await xl();let pe=`error`in N&&!N.path&&(()=>{let e=[...N.commands.keys()];for(let t of ou)e.push(t.name);return fn(N.error,e)!==void 0})(),me=`error`in N&&r.rootFetch&&!N.path&&!pe?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:j}:`error`in N&&r.rootCommand&&!N.path&&!pe?{command:r.rootCommand,path:e,rest:j}:N,he=`outputPolicy`in N&&N.outputPolicy||r.outputPolicy,ge=!(s&&!g&&he===`agent-only`),_e=_?Vn(_):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=$t(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:Hn(e.data,_e)}),le){let t=e.meta.cta;e={...e,meta:{...e.meta,cta:t?{description:t.description,commands:[...t.commands,...le.commands]}:le}}}if(b){let t=e.ok?e.data:e.error,n=t==null?``:Tl(t,fe);return d(String(Qt(n)))}let t=e.meta.cta;if(s&&!m){e.ok&&e.data!=null&&ge?d(ve(Tl(e.data,fe)).text):e.ok||d($b(e.error)),t&&d(ex(t));return}if(m){if(v!=null||y!=null){let t=ve(e.ok&&e.data!=null?Tl(e.data,fe):e.ok?``:Tl(e.error,fe));if(t.truncated){let n=e.ok?{ok:!0,data:t.text}:{ok:!1,error:t.text},r={...e.meta};return t.nextOffset!=null&&(r.nextOffset=t.nextOffset),n.meta=r,d(Tl(n,fe))}}return d(Tl(e,fe))}let n=e.ok?e.data:e.error,r=Tl(n,fe);if(!t){r&&d(ve(r).text);return}d(ve(Tl(typeof n==`object`&&n?{...n,cta:t}:{data:n,cta:t},fe)).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 ou)i.push(e.name);let o=fn(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($b({code:`COMMAND_NOT_FOUND`,message:l})),d(ex(le?{...f,commands:[...f.commands,...le.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()-ue)}ms`}}),a(1);return}if(`fetchGateway`in me){if(!re(!0))return;let{fetchGateway:t,path:n,rest:i}=me,o=[...r.middlewares??[],...me.middlewares??[]],c=async()=>{let r=Nn(i);t.basePath&&(r.path=t.basePath+r.path);let o=Pn(r),c=await t.fetch(o);if(Fn(c)){await ix(In(c),{name:e,path:n,start:ue,format:fe,formatExplicit:g,human:s,renderOutput:ge,fullOutput:m,truncate:ve,write:ye,writeln:d,exit:a});return}let l=await Ln(c);l.ok?ye({ok:!0,data:l.data,meta:{command:n,duration:`${Math.round(performance.now()-ue)}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()-ue)}ms`}}),a(1))};try{let t=r.envSchema?Gl(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=>({[jx]:`error`,...e}),format:fe,formatExplicit:g,globals:ne,name:e,set(e,t){i[e]=t},var:i,version:r.version},d=e=>{if(!rx(e)||e[jx]!==`error`)return;let t=e,r=Su(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()-ue)}ms`,...r?{cta:r}:void 0}}),a(t.exitCode??1)};await o.reduceRight((e,t)=>async()=>{d(await t(l,e))},c)()}else await c()}catch(e){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()-ue)}ms`}}),a(e instanceof I?e.exitCode??1:1)}return}let{command:be,path:xe,rest:P}=me;if(!re(!0))return;let Se=[...r.middlewares??[],...`middlewares`in N?N.middlewares??[]:[],...be.middleware??[]];s&&_x(P,be.options,be.alias);let Ce;if(c)try{Ce=await wb(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()-ue)}ms`}}),a(e instanceof I?e.exitCode??1:1);return}let we=await Zl(be,{agent:!s,argv:P,defaults:Ce,displayName:u,env:r.envSchema,envSource:r.env,format:fe,formatExplicit:g,globals:ne,inputOptions:{},middlewares:Se,name:e,path:xe,vars:r.vars,version:r.version}),Te=`${Math.round(performance.now()-ue)}ms`;if(`stream`in we){await ix(we.stream,{name:u,path:xe,start:ue,format:fe,formatExplicit:g,human:s,renderOutput:ge,fullOutput:m,truncate:ve,write:ye,writeln:d,exit:a});return}if(we.ok){let e=Su(u,we.cta);ye({ok:!0,data:we.data,meta:{command:xe,duration:Te,...e?{cta:e}:void 0}})}else{let e=Su(u,we.cta);if(s&&!g&&we.error.fieldErrors){d(bb(u,xe,be,new An({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 hb(e,t,n={}){let r;async function i(r,i,a){let{fromJsonSchema:o,McpServer:s,WebStandardStreamableHTTPServerTransport:c}=await Promise.resolve().then(()=>(V_(),f_)),l=new s({name:e,...n.title?{title:n.title}:void 0,version:t},n.instructions?{instructions:n.instructions}:void 0);K_(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 gb(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 _b(e,t,n){let r={name:e,description:n.description};return Sx.set(r,t),n.rootCommand&&Tx.set(r,n.rootCommand),vv(r,{title:e,...n.version?{version:n.version}:void 0,...n.description?{description:n.description}:void 0})}async function vb(e,t,n,r={}){let i=performance.now(),a=new URL(n.url),o=a.pathname.split(`/`).filter(Boolean);if(n.method===`GET`&&gb(o)){let n=_b(e,t,r),i=o[0]===`openapi.yml`||o[0]===`openapi.yaml`;return new Response(i?(await xl()).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 xl();let n=new Map,i=ux(t,[],n,r.rootCommand);if(o[2]===`index.json`&&o.length===3){let t=Ey(e,i,1,n).map(t=>{let n=t.content.match(/^---\n([\s\S]*?)\n---/),r=n?Sl().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=Ey(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(Ur(e),{status:t,headers:{"content-type":`application/json`}})}if(o.length===0)return r.rootCommand?yb(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=Sb(t,o);if(`error`in l){let t=l.path?`${e} ${l.path}`:e,n=fn(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 yb(d,u,f,s,n,i,{...r,groupMiddlewares:p})}async function yb(e,t,n,r,i,a,o){function s(e,t){return new Response(Ur(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 Zl(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(Su(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(rx(s)&&s[jx]===`error`){a.enqueue(n.encode(Ur(i(s))+`
216
+ `)),a.close();return}let t=rx(s)&&s[jx]===`ok`?Su(o.name??e,s.cta):void 0;a.enqueue(n.encode(Ur({type:`done`,ok:!0,meta:r(t)})+`
217
+ `)),a.close();return}if(rx(s)&&s[jx]===`error`){a.enqueue(n.encode(Ur(i(s))+`
218
+ `)),await t.return(void 0),a.close();return}a.enqueue(n.encode(Ur({type:`chunk`,data:s})+`
219
+ `))}catch(e){a.enqueue(n.encode(Ur({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=Su(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=Su(o.name??e,d.cta);return s({ok:!0,data:d.data,meta:{command:e,duration:f,...p?{cta:p}:void 0}},200)}function bb(e,t,n,r,i,a){let o=[];for(let e of r.fieldErrors){let t=(()=>{let t=xb(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(lu(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:mx(n.examples),usage:n.usage})),o.join(`
221
+ `)}function xb(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:`--${un(n)}${e}`}}return e.env?.shape[n]?{kind:`environment variable`,label:`${n}${r.length>0?`.${r.join(`.`)}`:``}`}:{kind:`argument`,label:`<${t}>`}}function Sb(e,t){let[n,...r]=t;if(!n||!e.has(n))return{error:n??`(none)`,path:``,commands:e,rest:r};let i=Zb(e,e.get(n)),a=[n],o=r,s,c=[];if(Yb(i)){let e=i.outputPolicy??s;return{fetchGateway:i,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}for(;Jb(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&&!fn(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=Zb(i.commands,t);if(a.push(e),o=o.slice(1),i=n,Yb(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 Cb(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(!xx.has(e[t+1]))throw new jn({message:`Invalid format: "${e[t+1]}". Expected one of: ${[...xx].join(`, `)}`});d=e[t+1],f=!0,t++}else if(b&&C===b){let n=e[t+1];if(n===void 0)throw new jn({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 jn({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 jn({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 jn({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 wb(e,t,n={}){if(n.configDisabled)return;let{loader:r}=n,i;i=n.configPath?Tb(n.configPath):await Eb(n.files??[`${e}.json`]);let a;if(r){let e=await r(i);if(e===void 0)return;if(!ln(e))throw new jn({message:`Config loader must return a plain object or undefined`});a=e}else{if(!i)return;let e=await Db(i,!!n.configPath);if(!e)return;a=e}return Ob(a,e,t)}function Tb(e){return e.startsWith(`~/`)||e===`~`?c.join(x.homedir(),e.slice(1)):c.resolve(process.cwd(),e)}async function Eb(e){for(let t of e){let e=Tb(t);try{return await w.access(e,w.constants.R_OK),e}catch{}}}async function Db(e,t){let n;try{n=await w.readFile(e,`utf8`)}catch(n){if(n.code===`ENOENT`){if(t)throw new jn({message:`Config file not found: ${e}`});return}throw n}let r;try{r=JSON.parse(n)}catch(t){throw new jn({message:`Invalid JSON config file: ${e}`,cause:t instanceof Error?t:void 0})}if(!ln(r))throw new jn({message:`Invalid config file: expected a top-level object in ${e}`});return r}function Ob(e,t,n){let r=n===t?[]:n.split(` `),i=e;for(let e of r){if(!ln(i))return;let t=i.commands;if(!ln(t)||(i=t[e],i===void 0))return}if(!ln(i))throw new jn({message:`Invalid config section for '${n}': expected an object`});let a=i.options;if(a!==void 0){if(!ln(a))throw new jn({message:`Invalid config 'options' for '${n}': expected an object`});return Object.keys(a).length>0?a:void 0}}function kb(e){let t=[];for(let[n,r]of e)Xb(r)||t.push({name:n,description:r.description});return t.sort((e,t)=>e.name.localeCompare(t.name))}function Ab(e,t,n){return nu(e[0])?.name===n?0:e[0]===t&&nu(e[1])?.name===n?1:-1}function jb(e,t){return cu(`${e} ${t.name}`,{aliases:t.aliases,description:t.description,commands:t.subcommands?.map(e=>({name:e.name,description:e.description}))})}function Mb(e,t,n){let r=ru(t,n);return lu(`${e} ${t.name} ${n}`,{alias:r?.alias,aliases:r?.aliases,description:r?.description,hideGlobalOptions:!0,options:r?.options})}async function Nb(e,t,n){let r=[],i=[],a=new E,o=new E,s=[];o.on(`data`,e=>s.push(e.toString()));let c,l=H_(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(`${Ur({jsonrpc:`2.0`,id:1,method:`initialize`,params:{protocolVersion:`2024-11-05`,capabilities:{},clientInfo:{name:`incur-doctor`,version:`1.0.0`}}})}\n`),a.write(`${Ur({jsonrpc:`2.0`,id:2,method:`tools/list`,params:{}})}\n`),await Pb(s,()=>u),a.end(),await l,c)return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_SERVER_FAILED`,message:Ib(c)}]};let d;try{d=Fb(s)}catch(e){return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_RESPONSE_PARSE_FAILED`,message:Ib(e)}]}}let f=d.find(e=>e.id===1);f?f.error&&i.push({code:`MCP_INITIALIZE_FAILED`,message:Lb(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:Lb(p.error)}):!ln(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(ln).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 Pb(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 Fb(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(!ln(r))throw Error(`Expected JSON-RPC response object.`);t.push(r)}return t}function Ib(e){return e instanceof Error?e.message:String(e)}function Lb(e){return ln(e)&&typeof e.message==`string`?e.message:Ur(e)}function Rb(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 zb(e){if(e)return{directory:ee(e)};let t=process.argv[1];if(!t)throw Error("Could not infer the filesystem command directory without an executed entrypoint. Pass a directory URL to `fs()`.");let n=c.resolve(t);try{let e=await w.realpath(n);return{directory:c.dirname(e),exclude:e}}catch(e){if(e.code!==`ENOENT`)throw e;return{directory:c.dirname(n),exclude:n}}}async function Bb(e){let t=await Eu(e.directory,{exclude:e.exclude});return Promise.all(t.map(async e=>({...e,command:(await import(D(e.file).href)).default})))}function Vb(e){return typeof e==`object`&&!!e&&e[bx]===!0}function Hb(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(Jb(c)&&!c.root)c.root=n,c.description??=n.description;else throw Ub(t,r);Qb(t.join(` `),n,i);for(let e of n.aliases??[]){if(a.has(e))throw Ub([...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(Xb(c)||Yb(c))throw Ub(t,r);if(Jb(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 Ub(e,t){return Error(`Filesystem command '${e.join(` `)}' from '${t}' conflicts with an existing command or alias.`)}function Wb(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 Gb(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 Kb(e){return typeof e==`function`?e:e.fetch}function qb(e){return typeof e==`function`?void 0:e.url}function Jb(e){return`_group`in e}function Yb(e){return`_fetch`in e}function Xb(e){return`_alias`in e}function Zb(e,t){return Xb(t)?e.get(t.target):t}function Qb(e,t,n){if(!(!n||Yb(t)||Xb(t))){if(Jb(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 $b(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 ex(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 tx(...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 nx(e){return Object.values(e.shape).some(e=>e._zod.optout!==`optional`)}function rx(e){return typeof e==`object`&&!!e&&jx in e}async function ix(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(rx(i)){let e=i;if(e[jx]===`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($b({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}}n?t.writeln(Ur({type:`chunk`,data:i})):t.renderOutput&&t.writeln(t.truncate(Tl(i,t.format)).text)}if(rx(r)&&r[jx]===`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($b({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}let i=rx(r)&&r[jx]===`ok`?Su(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(ex(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($b({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(rx(i)){let e=i;if(e[jx]===`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(rx(r)&&r[jx]===`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=rx(r)&&r[jx]===`ok`?Su(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 ax(e,t=[],n,r){let i=ox(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:Pu(n)}:void 0}}function ox(e,t){let n=[];for(let[r,i]of e){if(Xb(i))continue;let e=[...t,r];if(Jb(i)){if(i.root){let t={name:e.join(` `)};i.root.description&&(t.description=i.root.description),n.push(t)}n.push(...ox(i.commands,e))}else{let t={name:e.join(` `)};Yb(i),i.description&&(t.description=i.description),n.push(t)}}return n}function sx(e,t=[],n,r){let i=cx(e,t);return r&&t.length>0&&i.push(lx(t,r)),{version:`incur.v1`,commands:i.sort((e,t)=>e.name.localeCompare(t.name)),...n?{globals:Pu(n)}:void 0}}function cx(e,t){let n=[];for(let[r,i]of e){if(Xb(i))continue;let e=[...t,r];if(Yb(i)){let t={name:e.join(` `)};i.description&&(t.description=i.description),n.push(t)}else Jb(i)?(i.root&&n.push(lx(e,i.root)),n.push(...cx(i.commands,e))):n.push(lx(e,i))}return n}function lx(e,t){let n={name:e.join(` `)};t.description&&(n.description=t.description);let r=gx(t.args,t.env,t.options),i=t.output?Pu(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=mx(t.examples);if(a){let t=e.join(` `);n.examples=a.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function ux(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),fx(r)&&(e.hint=px(e.hint)),r.options&&(e.options=r.options),r.output&&(e.output=r.output);let t=mx(r.examples);t&&(e.examples=t),i.push(e)}for(let[r,a]of e){if(Xb(a))continue;let e=[...t,r];if(Yb(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 Jb(a)?(a.description&&n.set(e.join(` `),a.description),a.root&&i.push(dx(e,a.root)),i.push(...ux(a.commands,e,n))):i.push(dx(e,a))}return i.sort((e,t)=>(e.name??``).localeCompare(t.name??``))}function dx(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),fx(t)&&(n.hint=px(n.hint)),t.options&&(n.options=t.options),t.output&&(n.output=t.output);let r=mx(t.examples);if(r){let t=e.join(` `);n.examples=r.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function fx(e){return e.destructive===!0||e.mcp!==!1&&e.mcp?.annotations?.destructiveHint===!0}function px(e){return e?e.includes(yx)?e:`${e} ${yx}`:yx}function mx(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 hx(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return{};let n=Sl().parse(t[1]);return!n||typeof n!=`object`?{}:n}function gx(e,t,n){if(!e&&!t&&!n)return;let r={};return e&&(r.args=Pu(e)),t&&(r.env=Pu(t)),n&&(r.options=Pu(n)),r}function _x(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 vx(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 yx,bx,xx,Sx,Cx,wx,Tx,Ex,Dx,Ox,kx,Ax,jx,Mx=F((()=>{cn(),Gt(),Dn(),Mn(),Bn(),Wn(),Nl(),xu(),su(),Tu(),Nu(),pn(),Gr(),lt(),kt(),wl(),pv(),Sy(),cy(),Xl(),Fu(),Ny(),Uy(),fb(),yx=`Confirm with the user before executing this destructive command.`,bx=Symbol.for(`incur.fileCommand`),xx=new Set([`toon`,`json`,`yaml`,`md`,`jsonl`]),Sx=new WeakMap,Cx=new WeakMap,wx=new WeakMap,Tx=new WeakMap,Ex=new WeakMap,Dx=new WeakMap,Ox=new WeakMap,kx=new WeakMap,Ax=new WeakMap,jx=Symbol.for(`incur.sentinel`)})),Nx=F((()=>{Gt(),Mx(),Dn(),Mn(),Nl(),xu(),pv(),Bn(),cy(),Xl(),Fu(),Ny(),wl(),Uy(),fb()}));function Px(e,t){if(!(!e||typeof e!=`object`))return e[t]}var q,Fx,Ix,Lx,Rx,zx,Bx=F((()=>{q={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Fx={payment:`Payment`},Ix={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Lx={charge:`charge`,session:`session`,subscription:`subscription`},Rx={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},zx={v1:`v1`,v2:`v2`}}));function Vx(e){let t=A.toString(e);return JSON.parse(t)}function Hx(e,t){return e.schema.request.parse(t)}function Ux(e){let t=re.canonicalize(e);return A.fromString(t,{pad:!1,url:!0})}var Wx=F((()=>{})),J=rt({address:()=>Zx,amount:()=>Kx,datetime:()=>qx,datetimeInput:()=>Jx,hash:()=>Qx,period:()=>$x,signature:()=>eS,toDate:()=>Yx,toDatetimeString:()=>Xx,unwrapOptional:()=>tS});import*as Gx from"zod/mini";at(J,Gx);function Kx(){return Ce.string().check(Ce.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function qx(){return Ce.string().check(Ce.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 Jx(e=`Invalid ISO 8601 datetime`){return Ce.pipe(Ce.union([qx(),Ce.custom(e=>e instanceof Date)]),Ce.transform(Yx)).check(Ce.refine(e=>Number.isFinite(e.getTime()),e))}function Yx(e){return e instanceof Date?e:new Date(e)}function Xx(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function Zx(){return Ce.string().check(Ce.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function Qx(){return Ce.string().check(Ce.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function $x(){return Ce.string().check(Ce.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function eS(){return Ce.string().check(Ce.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function tS(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}var nS=F((()=>{}));function rS(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=yS(o)?void 0:o,f=e.expires?Xx(e.expires):void 0,p=e.opaque??(i===void 0?void 0:Ux(i)),m=u?bS({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return SS.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 iS(e){let t=[aS(`id`,e.id),aS(`realm`,e.realm),aS(`method`,e.method),aS(`intent`,e.intent),aS(`request`,Ux(e.request))];e.description!==void 0&&t.push(aS(`description`,e.description)),e.digest!==void 0&&t.push(aS(`digest`,e.digest)),e.expires!==void 0&&t.push(aS(`expires`,e.expires));let n=e.header;return n!==void 0&&!yS(n)&&t.push(aS(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(aS(`opaque`,Ux(e.meta))):t.push(aS(`opaque`,e.opaque)),`${Fx.payment} ${t.join(`, `)}`}function aS(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 oS(e,t){let n=sS(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=cS(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>xS)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 rS({...a,request:Vx(r),...i&&{opaque:i}},t)}function sS(e){let t=Fx.payment,[n]=pS(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 cS(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]=lS(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function lS(e,t){if(e[t]===`"`)return uS(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function uS(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 dS(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 fS(e){return pS(e,Fx.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===Fx.payment.toLowerCase())}function pS(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(!dS(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 mS(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return hS(e.headers,t)}function hS(e,t){let n=e.get(q.wwwAuthenticate);if(!n)throw Error(`Missing ${q.wwwAuthenticate} header.`);return gS(n,t)}function gS(e,t){let n=pS(e,Fx.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 oS(e.slice(r,a).replace(/,\s*$/,``),t)})}function _S(e){let t=[e.realm,e.method,e.intent,Ux(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!yS(n)&&t.push(n),t.push(e.opaque??(e.meta?Ux(e.meta):``)),t.join(`|`)}function vS(e){return e.header??q.authorization}function yS(e){return e?.toLowerCase()===q.authorization.toLowerCase()}function bS(e,t){let n=_S(e),r=te.fromString(t.secretKey),i=te.fromString(n),a=ne.hmac256(r,i,{as:`Bytes`});return A.fromBytes(a,{url:!0,pad:!1})}var xS,SS,CS=F((()=>{Bx(),Wx(),nS(),xS=16384,SS=J.object({description:J.optional(J.string()),digest:J.optional(J.string().check(J.regex(/^sha-256=/,`Invalid digest format`))),expires:J.optional(qx()),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())})})),wS,TS,Y,ES,DS,OS,kS=F((()=>{wS=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}}}},TS=class extends wS{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 wS{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})}},ES=class extends wS{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.`)}},DS=class extends wS{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}},OS=class extends Error{name=`ZoneSettlementPendingError`;challengeId;senderTag;zoneId;constructor(e){let{cause:t,challengeId:n,senderTag:r,zoneId:i}=e;super(`Zone ${i} withdrawal ${r} for challenge "${n}" has not settled on Tempo yet. Retry the challenge to resume waiting instead of paying again.`),this.challengeId=n,this.senderTag=r,this.zoneId=i,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}}}));function AS(e,t){if(!e)throw new TS({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new TS({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new ES({expires:e})}var jS=F((()=>{kS()}));function MS(e){if(e.length>RS)throw new BS;let t=e.match(RegExp(`^${Fx.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new zS;try{let e=A.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=NS(r);return{challenge:SS.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Vx(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new BS}}function NS(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!PS(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:Ux(e)}}function PS(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function FS(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function IS(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:Ux(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:Ux(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=A.fromString(s,{pad:!1,url:!0});return`${Fx.payment} ${c}`}function LS(e){return e.length>RS?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${Fx.payment}\\s+`,`i`).test(e))??null}var RS,zS,BS,VS=F((()=>{CS(),Bx(),Wx(),RS=65536,zS=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},BS=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}}}));function HS(){let e=new Uint8Array(64);return crypto.getRandomValues(e),{created:Math.floor(Date.now()/1e3),nonce:A.fromBytes(e,{pad:!1,url:!0})}}var US=F((()=>{}));function WS(e){if(e.length===0)throw TypeError(`Mppx client identity must configure at least one prover.`);for(let t of e)if(t.scope!==`*`&&!Array.isArray(t.scope))throw TypeError(`Identity prover scope must be "*" or an array of origins.`);let t=t=>{let n=new URL(t).origin;return e.filter(e=>e.scope===`*`||e.scope.includes(n))};async function n(e,n,r,i){let a=i?n.clone():n,o=t(n.url);if(o.length===0)return{request:a,response:await e(a)};let s=Object.freeze({...r,...HS()}),c=new Request(a,{redirect:n.redirect===`follow`?`error`:n.redirect});for(let e of o)c=await e.prove(c,s);return{request:c,response:await e(c)}}return{async send(e,r,i={}){let a=!(i.challenge!==void 0||XS.some(e=>r.headers.has(e))||[...r.headers.values()].some(e=>LS(e)!==null))&&t(r.url).some(e=>e.retry),o=await n(e,r,i,a),{response:s}=o;if(!a||s.status<400||s.status===402)return o;let c=[],l=!1;for(let e of t(r.url)){if(!e.retry)continue;let t=s.clone();c.push(t),await e.retry(t)&&(l=!0)}return l?(GS([s,...c]),n(e,r,i,!1)):(GS(c),o)},async challenge(e,n,r){for(let i of t(r)){if(!i.prepare)continue;let t=e.clone();try{await i.prepare(t,n)}finally{GS([t])}}}}}function GS(e){for(let t of e)t.bodyUsed||t.body?.cancel().catch(()=>{})}function KS(e,t,n){return async(r,i)=>{let a=new Request(r,i),o=JS(a.headers)??n?.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[YS]?{[YS]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of qS(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{...n,challenge:e},a.url);return s}}function qS(e){try{return mS(e)}catch{return[]}}function JS(e){for(let[,t]of e){let e=LS(t);if(e)try{return MS(e).challenge}catch{}}}var YS,XS,ZS=F((()=>{CS(),VS(),US(),YS=Symbol.for(`mppx.fetch.skipPayment`),XS=[`payment-signature`,`x-payment`]}));function QS(e){return Object.defineProperty(e,eC,{value:!0}),e}function $S(e){return!!e?.[eC]}var eC,tC=F((()=>{eC=Symbol.for(`mppx.x402.challenge`)}));function nC(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=cC(n)}return t}function rC(e,t){let n=nC(e),r=hC(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[cC(e)]??1,index:t}));return{definition:r,entries:i,header:aC(i),keys:n}}function iC(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)=>pC(e,t))}function aC(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${yC(n)}`}).join(`, `)}function oC(e,t,n){let r=sC(e,t,n)[0];if(r)return{challenge:r.challenge,method:r.method}}function sC(e,t,n,r){let i=new Map;for(let e of t){let t=cC(e),n=i.get(t);n?n.push(e):i.set(t,[e])}return e.flatMap((e,t)=>{let a=i.get(cC(e));if(!a)return[];let o=lC(e,n);return!o||o.q<=0?[]:a.filter(t=>t.canHandleChallenge?.(r===void 0?{challenge:e}:{challenge:e,context:r})??!0).map(n=>({challenge:e,index:t,match:o,method:n}))}).sort((e,t)=>fC(e.challenge)-fC(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function cC(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function lC(e,t){let n;for(let r of t){if(!uC(e,r))continue;let t={...r,specificity:dC(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 uC(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function dC(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function fC(e){return+!!$S(e)}function pC(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}`);bC(r,`method`),bC(i,`intent`);let a=1;for(let t of mC(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=_C(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function mC(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function hC(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>cC(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]=gC(t,`payment preference "${e}"`)}return a}function gC(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return vC(e,t)}function _C(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 vC(Number(e),t)}function vC(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 yC(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function bC(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}var xC,SC=F((()=>{tC(),xC=Symbol(`mppx.deferredContext`)})),CC,wC,TC=F((()=>{CC=`org.paymentauth/credential`,wC=`org.paymentauth/payment-required`}));function EC(e){let t=``,n=!1,r=!1,i,a=``;function o(t){if(t===``){i!==void 0&&e({data:i,event:a||`message`}),i=void 0,a=``;return}let n=t.indexOf(`:`);if(n===0)return;let r=n===-1?t:t.slice(0,n);if(r!==`data`&&r!==`event`)return;let o=``;n!==-1&&(o=t.slice(t.charCodeAt(n+1)===32?n+2:n+1)),r===`event`?a=o:i=i===void 0?o:i+`
224
224
  `+o}return{feed(e){if(!n&&e&&(n=!0,e.startsWith(``)&&(e=e.slice(1))),r&&e&&(r=!1,e.startsWith(`
225
225
  `)&&(e=e.slice(1))),t+=e,e.indexOf(`
226
226
  `)===-1&&e.indexOf(`\r`)===-1)return;let i=0,a=t.indexOf(`
227
227
  `),s=t.indexOf(`\r`);for(;a!==-1||s!==-1;){let e=a===-1?s:s===-1?a:Math.min(a,s);o(t.slice(i,e)),i=e+1,e===s&&(i===t.length?r=!0:a===i&&i++,s=t.indexOf(`\r`,i)),a!==-1&&a<i&&(a=t.indexOf(`
228
- `,i))}t=t.slice(i)}}}var EC=I((()=>{}));function DC(e){let{extensions:t,resource:n,...r}=e;return VC.parse(r)}var OC,kC,AC,jC,MC,NC,PC,FC,IC,LC,RC,zC,BC,VC,HC,UC,WC,GC,KC,qC,JC,YC,XC=I((()=>{tS(),OC=`charge`,kC=[`exact`],AC=`eip155:`,jC=`x402:`,MC=`PAYMENT-REQUIRED`,NC=`PAYMENT-SIGNATURE`,PC=`PAYMENT-RESPONSE`,FC=J.string().check(J.minLength(1)),IC=J.number().check(J.refine(e=>e>0,`Must be positive`)),LC=J.string().check(J.regex(/^\d+$/,`Invalid atomic amount`)),RC=Xx(),zC=J.string().check(J.regex(RegExp(`^${AC}\\d+$`),`Invalid EVM CAIP-2 network`)),BC=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:LC,asset:FC,extra:J.optional(J.record(J.string(),J.unknown())),maxTimeoutSeconds:IC,network:zC,payTo:FC,scheme:J.enum(kC)}),HC=J.object({info:J.record(J.string(),J.unknown()),schema:J.record(J.string(),J.unknown())}),UC=J.record(J.string(),HC),WC=J.object({accepts:J.array(VC).check(J.minLength(1)),error:J.optional(J.string()),extensions:J.optional(UC),resource:BC,x402Version:J.literal(2)}),GC=J.object({authorization:J.object({from:RC,nonce:Zx(),to:RC,validAfter:LC,validBefore:LC,value:LC}),signature:$x()}),KC=J.object({permit2Authorization:J.object({deadline:LC,from:RC,nonce:LC,permitted:J.object({amount:LC,token:RC}),spender:RC,witness:J.object({to:RC,validAfter:LC})}),signature:$x()}),qC=J.union([GC,KC]),JC=J.object({accepted:VC,extensions:J.optional(UC),payload:qC,resource:J.optional(BC),x402Version:J.literal(2)}),J.object({extensions:J.optional(UC),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())}),YC=J.object({amount:J.optional(LC),errorMessage:J.optional(J.string()),errorReason:J.optional(J.string()),extensions:J.optional(UC),extra:J.optional(J.record(J.string(),J.unknown())),network:FC,payer:J.optional(J.string()),success:J.boolean(),transaction:J.string()})}));function ZC(e,t,n){let r=new Headers(e.headers);for(let e of QC)e===q.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}var QC,$C=I((()=>{zx(),XC(),QC=[q.authorization,MC,PC,NC]}));function ew(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 tw(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t?.method===`tools/call`&&t.params?._meta?.[`mppx/payment-client`]===!0}catch{return!1}}function nw(e){let t=ew(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 rw(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 iw(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=xS.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 aw(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:iw(e.error.data):iw(e.result?._meta?.[CC])}function ow(e,t){return!e||e.id!==t?[]:aw(e)?.challenges??[]}async function sw(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=TC(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=rw(JSON.parse(e.data))}catch{}});try{for(;;){if(i)return a;let{done:e,value:s}=await t.read();if(e)return o.feed(n.decode()),a;if(r+=s.byteLength,r>dw)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function cw(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 rw(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>dw)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function lw(e){let t=fw.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>dw)){if(t.includes(`application/json`))return cw(e);if(t.includes(`text/event-stream`))return sw(e)}})();return fw.set(e,n),n}function uw(){return{getChallenges(e,t){let n=nw(t);return e.status===402||n===void 0?[]:lw(e).then(e=>ow(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=jS(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,[SC]:r}}})}}}}var dw,fw,pw=I((()=>{SS(),BS(),EC(),wC(),$C(),dw=1048576,fw=new WeakMap}));function mw(){return{getChallenges(e){let t=e.headers.get(q.wwwAuthenticate);return e.status!==402||!t||!dS(t)?[]:pS(e)},setCredential(e,t,n){return ZC(e,n?.challenge?_S(n.challenge):q.authorization,t)}}}var hw=I((()=>{SS(),zx(),$C()}));function gw(e){return{encode(t){return O.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(O.toString(t)))}catch{throw new _w}}}}var _w,vw=I((()=>{_w=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}}}));function yw(e){try{let t=JSON.parse(O.toString(e));return Tw(t)}catch{throw new _w}}var bw,xw,Sw,Cw,ww,Tw,Ew=I((()=>{vw(),XC(),bw=gw(WC),xw=gw(JC),Sw=gw(YC),Cw=bw.encode,bw.decode,ww=xw.encode,xw.decode,Sw.encode,Sw.decode,Tw=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new _w;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new _w;let n=BC.parse(t.resource),r=t.extensions===void 0?void 0:UC.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}}}));function Dw(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(MC);if(!t)return[];let n=yw(t);return n.accepts.flatMap((e,t)=>{let r=VC.safeParse(e);if(!r.success)return[];let i=r.data;return ZS(nS({id:`${jC}${t}`,intent:OC,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return ZC(e,NC,t)}}}var Ow=I((()=>{SS(),Ew(),eC(),XC(),$C()}));function kw(e){return e}function Aw(){let e=[mw(),Dw(),uw()],t=new WeakMap,n=(e,n)=>{for(let r of n)t.set(r,e);return n},r=(t,r)=>{let i=(a,o)=>{for(let s=a;s<e.length;s++){let a=e[s],c=a.getChallenges(t,r);if(c instanceof Promise)return c.then(e=>i(s+1,[...o,...n(a,e)]));o.push(...n(a,c))}return o};return i(0,[])};return kw({name:`http`,isPaymentRequired(e,t){if(e.status===402)return!0;let n=r(e,t);return n instanceof Promise?n.then(e=>e.length>0):n.length>0},getChallenges(e,t){return r(e,t)},setCredential(n,r,i){let a=i?.challenge?t.get(i.challenge):void 0,o=e[0];if(!a&&!o)throw Error(`No protocol to attach the credential.`);return(a??o).setCredential(n,r,i)}})}var jw=I((()=>{pw(),hw(),$C(),Ow()}));function Mw(e,t){return Iw.set(e,t),e}function Nw(e){return Iw.has(e)}function Pw(e,t){return Promise.resolve(Iw.get(e)?.(t))}function Fw(e){return Iw.get(e)}var Iw,Lw=I((()=>{Iw=new WeakMap}));function Rw(e,t){return qw.set(e,t),e}function zw(e){qw.delete(e)}function Bw(e,t,n){qw.has(e)&&Jw.set(t,n)}function Vw(e){return Jw.get(e)}function Hw(e,t){return Promise.resolve(qw.get(e)?.(t)??t.response)}function Uw(e,t){return Xw.set(e,t),e}function Ww(e,t){try{return Xw.get(e)?.(t)}catch{return}}function Gw(e,t){Yw.set(e,t)}function Kw(e){return Yw.get(e)??Jw.get(e)?.origin}var qw,Jw,Yw,Xw,Zw=I((()=>{qw=new WeakMap,Jw=new WeakMap,Yw=new WeakMap,Xw=new WeakMap}));function Qw(e,t,n){if(!eT(e)&&(e.method!==`tempo`||e.intent!==`session`))return;t=typeof t==`function`?t():t;let{realm:r}=e;if(r.toLowerCase()===t.hostname.toLowerCase())return;let i=t.origin.toLowerCase();for(let[e,t]of Object.entries(n??{}))if(t===r&&tT(e)===i)return;throw Error(`Refusing to sign Tempo proof for realm ${JSON.stringify(r)} from ${t.origin}. Pin the realm to this origin with \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function $w(e,t){if(!(!eT(e)&&(e.method!==`tempo`||e.intent!==`session`))&&!t?.includes(e.realm))throw Error(`Refusing to sign Tempo proof for untrusted realm ${JSON.stringify(e.realm)}. Add it to \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function eT(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function tT(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}var nT=I((()=>{}));async function rT(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},JT);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>qT){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(YT,`true`);let s=new Response(new Blob(n).slice(0,qT),{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 iT(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 aT(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=KT,methods:a,onChallenge:o,orderChallenges:s,transport:c=Aw(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&kT(e.fetch)),d=e.eventDispatcher??cT(),f=t??nC(a),p=AT(r),m=async(e,t,n)=>u?(await u.send(p,new Request(e,t),n)).response:p(e,t),h=async(e,t,r)=>{let g=OT(e,t?.headers),_=g.has(q.acceptPayment),v=FT(g,f),y=ET(e,t,g),b=TT(e,t,g,v.header,_,n),x=await m(jT(b.input),b.init),S=DT(b.init,await y);if(t?.[GT]||tw(S)||!await c.isPaymentRequired(x,S))return x;let C=t?.context,{context:w,orderChallenges:T,...ee}=S??{},te,E,D,O,k;try{for(let n=0;n<i;n++){E=await c.getChallenges(x,S);let i=(await IT(oC(E,a,v.entries,C),T??s))[0];if(!i){if(await iT(O,{challenges:E,response:x,status:`rejected`}),n>0)return x;throw Error(`No method found for challenges: ${E.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let f=i.challenge;te=f,D=i.method,te.expires&&kS(te.expires,te.id),await u?.challenge(x,{challenge:f},BT(b.input).href);let g=await HT(x,b.input,b.input,ee);Qw(f,()=>BT(g),l);let _=O,y=rS(f),w=_?.method===i.method&&_?.key===y,ne=!1;if(_){let e=await iT(_,{challenges:E,response:x,status:w?`pending`:`rejected`});ne=w&&!e}O=ne?_:void 0;let A=pT(async n=>{if(n===void 0&&ne&&_)return _.promise;ne&&_&&(await iT(_,{status:`rejected`}),O=void 0),MT(e,t)?.throwIfAborted();let r=n??C;if(!Nw(i.method))return PT(f,i.method,r);let a={origin:BT(g).origin,prepare:()=>Pw(i.method,{challenge:f,context:r,fetch:u?GS(p,u,{challenge:f}):p,input:g,signal:MT(e,t)})},o=a.prepare().then(()=>PT(f,i.method,r,a));return O={context:r,attempt:a,key:n===void 0?y:void 0,method:i.method,promise:o},o}),j=await d.emit(`challenge.received`,mT({challenge:f,challenges:E,createCredential:A,init:t,input:e,method:i.method,response:x}))??(o?await o(te,{createCredential:A}):void 0)??await A(),M=O;M&&await M.promise.catch(()=>void 0)!==j&&(await iT(M,{status:`rejected`}),O=void 0);let re=O?O.context:C;NT(j),await d.emit(`credential.created`,hT({challenge:f,credential:j,init:t,input:e,method:i.method,response:x}));let ie=e=>new ES({cause:e,challenge:f,credential:j,transactionHash:Ww(i.method,j)});try{x=await m(g,{...c.setCredential({...ee,headers:b.headers},j,{challenge:f}),redirect:`manual`},{challenge:f})}catch(e){throw k=ie(e),e}let ae=await c.isPaymentRequired(x,S);if(ae||(await iT(M,{response:x,status:x.status>=300&&x.status<400?`pending`:x.ok?`accepted`:`rejected`}),O=void 0),x.ok&&lT(d,`payment.response`)&&await d.emit(`payment.response`,gT({challenge:f,credential:j,init:t,input:e,method:i.method,response:x})),!ae){if(x.status>=500&&lT(d,`payment.failed`)){try{x=await rT(x)}catch(e){throw k=ie(e),x=new Response(null,{headers:x.headers,status:x.status,statusText:x.statusText}),e}await d.emit(`payment.failed`,_T({challenge:f,challenges:E,error:ie(),init:t,input:e,method:i.method,response:x}))}return x.ok?Hw(i.method,{context:re,challenge:f,credential:j,fetch:p,headers:b.headers,input:g,...r?{refetch:()=>h(jT(b.input),t,!1)}:{},response:x,signal:MT(e,t)}):x}}E=void 0;try{E=await c.getChallenges(x,S)}catch{}return await iT(O,{challenges:E,response:x,status:`rejected`}),x}catch(n){throw await iT(O,{challenges:E,response:x,status:`rejected`}),await d.emit(`payment.failed`,_T({challenge:te,challenges:E,error:k??n,init:t,input:e,method:D,response:x})),n}},g=(e,t)=>h(e,t,!0);return g[UT]=p,u&&(g[WT]=u),g}function oT(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);XT||=globalThis.fetch,globalThis.fetch=aT({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??(zT()?`same-origin`:`always`),fetch:AT(globalThis.fetch)})}function sT(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 cT(){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 uT(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await fT(e[`*`],t,n),r}case`credential.created`:await dT(e[`credential.created`],n),await fT(e[`*`],t,n);return;case`payment.failed`:await dT(e[`payment.failed`],n),await fT(e[`*`],t,n);return;case`payment.response`:await dT(e[`payment.response`],n),await fT(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 ZT.set(t,t=>e[t].size>0||e[`*`].size>0),t}function lT(e,t){return ZT.get(e)?.(t)??!0}async function uT(e,t){try{return await e(t)}catch{return}}async function dT(e,t){for(let n of e)try{await n(t)}catch{}}async function fT(e,t,n){await dT(e,Object.freeze({name:t,payload:n}))}function pT(e){let t;return n=>(t??=e(n),t)}function mT(e){return Object.freeze({challenge:ST(e.challenge),challenges:e.challenges.map(e=>ST(e)),createCredential:e.createCredential,init:vT(e.init),input:yT(e.input),method:bT(e.method),response:xT(e.response)})}function hT(e){return Object.freeze({challenge:ST(e.challenge),credential:e.credential,init:vT(e.init),input:yT(e.input),method:bT(e.method),...e.response===void 0?{}:{response:xT(e.response)}})}function gT(e){return Object.freeze({challenge:ST(e.challenge),credential:e.credential,init:vT(e.init),input:yT(e.input),method:bT(e.method),response:xT(e.response)})}function _T(e){return Object.freeze({...e.challenge?{challenge:ST(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>ST(e))}:{},error:e.error,init:vT(e.init),input:yT(e.input),...e.method?{method:bT(e.method)}:{},...e.response===void 0?{}:{response:xT(e.response)}})}function vT(e){if(e)return wT({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function yT(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function bT(e){return wT(Object.assign({},e))}function xT(e){if(e instanceof Response)try{return e.clone()}catch{let t=new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText});for(let n of[`redirected`,`type`,`url`])Object.defineProperty(t,n,{value:e[n]});return t}return ST(e)}function ST(e){try{return CT(structuredClone(e))}catch{return wT(e)}}function CT(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))CT(t);return e}function wT(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function TT(e,t,n,r,i,a){let o=!!r&&!i&&LT(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 ET(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 DT(e,t){return t===void 0?e:{...e,body:t}}function OT(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function kT(e){return e[WT]}function AT(e){let t=e;for(;t[UT];)t=t[UT];return t}function jT(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function MT(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function NT(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
229
- `))throw Error(`Credential header value contains illegal newline characters`)}async function PT(e,t,n,r){let i=t.context&&n!==void 0?t.context.parse(n):void 0,a=i===void 0?{challenge:e}:{challenge:e,context:i};return r?.origin&&Gw(a,r.origin),r&&Bw(t,a,r),t.createCredential(a)}function FT(e,t){let n=e.get(q.acceptPayment);if(!n)return t;try{return{...t,entries:rC(n),header:n}}catch{return t}}async function IT(e,t){return t?t(e):e}function LT(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=BT(e);return t===`same-origin`?!zT()||n.origin===globalThis.location.origin:t.origins.some(e=>RT(n,e))}function RT(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 zT(){return globalThis.location!==void 0}function BT(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,zT()?globalThis.location.href:void 0)}function VT(e,t){let n=e instanceof Request?e:void 0;if((t.mode??n?.mode)===`no-cors`)throw Error(`Cannot automatically pay a no-cors request: it cannot carry a credential.`);if((t.cache??n?.cache)===`only-if-cached`)throw Error(`Cannot automatically pay an only-if-cached request: its retry cannot reach the server.`)}async function HT(e,t,n,r){if(VT(t,r),!e.url)return t;let i=new URL(e.url),a=BT(n);if(i.origin!==a.origin)throw Error(`Refusing to send payment credential across redirect from ${a.origin} to ${i.origin}`);let o=(r.method??(t instanceof Request?t.method:`GET`)).toUpperCase();if(e.redirected&&o!==`GET`&&o!==`HEAD`)throw Error(`Cannot automatically pay a redirected ${o} request. Use prepareRequest() to preserve redirect semantics.`);if(t instanceof Request){let n=r.body==null?t.clone():t,i=new Request(n,t.mode===`navigate`&&r.mode===void 0?{...r,mode:`same-origin`}:r);return i.url.split(`#`)[0]===e.url?i:i.body?new Request(e.url,{body:await i.arrayBuffer(),cache:i.cache,credentials:i.credentials,headers:i.headers,integrity:i.integrity,keepalive:i.keepalive,method:i.method,mode:i.mode,redirect:i.redirect,referrer:i.referrer,referrerPolicy:i.referrerPolicy,signal:i.signal}):new Request(e.url,i)}return e.url}var UT,WT,GT,KT,qT,JT,YT,XT,ZT,QT=I((()=>{SS(),zx(),OS(),AS(),XS(),xC(),jw(),Lw(),Zw(),nT(),pw(),UT=Symbol.for(`mppx.fetch.wrapper`),WT=Symbol.for(`mppx.fetch.identity`),GT=Symbol.for(`mppx.fetch.skipPayment`),KT=3,qT=65536,JT=2e3,YT=`Mppx-Body-Truncated`,ZT=new WeakMap}));Mx(),zx(),AS(),XS(),xC(),QT(),Lw(),Zw(),nT(),jw();const $T=new WeakMap;function eE(e){let{identity:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=Aw(),trustedTempoProofRealms:c}=e;if(`attestation`in e)throw TypeError("Mppx client `attestation` was replaced by `identity: [prover]`.");let l=AT(e.fetch??globalThis.fetch),u=t?US(t):e.fetch&&kT(e.fetch),d=e.methods.flat(),f=nC(d,e.paymentPreferences),p=cT(),m=r,h={acceptPayment:f,acceptPaymentPolicy:o,...e.fetch&&{fetch:l},...u&&{identity:u},eventDispatcher:p,...n!==void 0&&{maxPaymentRetries:n},...m&&{onChallenge:m},...i&&{orderChallenges:i},methods:d,transport:s,...c&&{trustedTempoProofRealms:c}},g=aT(h);a&&oT(h);function _(e){return p.on(`challenge.received`,e)}function v(e){return p.on(`credential.created`,e)}function y(e){return p.on(`payment.failed`,e)}function b(e){return p.on(`payment.response`,e)}async function x(e,t,n){let r=mE(e),a=await s.getChallenges(e,t?.request),o=Object.freeze(a.map(e=>hE(e))),l=vE(f.entries,t?.acceptPayment),u,m;try{let f=oC(a,d,l,n);f.length===0&&n===void 0&&(f=oC(a,d,l,bC));let h=(await yE(f,t?.orderChallenges??i))[0];if(!h)throw Error(`No method found for challenges: ${a.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${d.map(e=>`${e.name}.${e.intent}`).join(`, `)}`);let g=h.challenge;u=o[h.index],m=h.method,u.expires&&kS(u.expires,u.id);let _=xE(e);_?Qw(u,_,c):s.name===`mcp`&&$w(u,c&&Object.values(c));let v=u,y=m,b=lE(async e=>{try{v.expires&&kS(v.expires,v.id);let t=lE(t=>bE(v,y,t??e,_?.origin)),n=await p.emit(`challenge.received`,uE({challenge:v,challenges:a,createCredential:t,method:y,response:r}))??await t();return NT(n),await p.emit(`credential.created`,dE({challenge:v,credential:n,method:y,response:r})),n}catch(e){throw await p.emit(`payment.failed`,fE({challenge:v,challenges:a,error:e,method:y,response:r})),e}}),x=Object.freeze({challenge:v,challenges:o,createCredential:b,method:pE(y),setCredential(e,t){return NT(t),s.setCredential(e,t,{challenge:g})}});return $T.set(x,y),x}catch(e){throw await p.emit(`payment.failed`,fE({challenge:u,challenges:a,error:e,method:m,response:r})),e}}async function S(e,t,n){let{maxRedirects:r=20,requirePayment:i=!1,...a}=n??{},d=await iE({acceptPayment:f.header,acceptPaymentPolicy:o,fetch:l,init:t,input:e,maxRedirects:r,identity:u}),p=aE(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});Qw(m.challenge,new URL(d.replayRequest.url),c);let h=$T.get(m)??m.method,g=lE(async e=>(await u?.challenge(d.response,{challenge:m.challenge},d.replayRequest.url),Nw(h)&&await Pw(h,{challenge:m.challenge,context:e,fetch:u?GS(l,u,{challenge:m.challenge}):l,input:d.replayRequest,signal:d.replayRequest.signal}),m.createCredential(e))),_=Object.freeze({...m,createCredential:g,async pay(e){let t=await g(e),n=m.setCredential(aE(d.replayRequest,d.body),t),r=new Request(d.replayRequest.url,{...n,redirect:`manual`});if(!u)return l(r);let{response:i}=await u.send(l,r,{challenge:m.challenge});return i}});return Object.freeze({payment:_,request:d.request,response:d.response,redirects:d.redirects})}return{fetch:g,rawFetch:l,methods:d,transport:s,on:p.on,onChallengeReceived:_,onCredentialCreated:v,onPaymentFailed:y,onPaymentResponse:b,preparePayment:x,prepareRequest:S,async createCredential(e,t,n){return(await x(e,n,t)).createCredential(t)}}}const tE=new Set([301,302,303,307,308]),nE=[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`,`transfer-encoding`],rE=[`authorization`,`cookie`,`cookie2`,`host`,`payment-authorization`,`payment-signature`,`proxy-authorization`,`x-payment`];async function iE(e){let{acceptPayment:t,acceptPaymentPolicy:n,fetch:r,identity:i,init:a,input:o,maxRedirects:s}=e;if(!Number.isInteger(s)||s<0)throw TypeError(`maxRedirects must be a non-negative integer.`);let c=new Request(o,{...a,redirect:`manual`}),l=c.headers.has(q.acceptPayment),u=await oE(c,a?.body),d=[];for(;;){c=sE(c,t,l,n);let{request:e,response:a}=await(async()=>{if(i)return i.send(r,c.clone());let e=c.clone();return{request:e,response:await r(e)}})();if(a.type===`opaqueredirect`||a.status===0)throw Error(`prepareRequest requires a runtime that exposes manual redirect responses.`);if(!tE.has(a.status))return{body:u,replayRequest:c,request:e,response:a,redirects:Object.freeze(d)};let o=a.headers.get(`location`);if(!o)return{body:u,replayRequest:c,request:e,response:a,redirects:Object.freeze(d)};if(d.length>=s)throw await a.body?.cancel(),Error(`Payment request exceeded ${s} redirects.`);let f=new URL(c.url),p=new URL(o,f);if(f.protocol===`https:`&&p.protocol!==`https:`)throw await a.body?.cancel(),Error(`Payment request refused HTTPS downgrade redirect to ${p.href}`);let m=new Headers(c.headers),h=c.method;if((a.status===301||a.status===302)&&h===`POST`||a.status===303&&h!==`GET`&&h!==`HEAD`){h=`GET`,u=void 0;for(let e of nE)m.delete(e)}if(f.origin!==p.origin)for(let e of[...m.keys()]){let t=m.get(e)??``;(rE.includes(e)||t.startsWith(`Payment `))&&m.delete(e)}d.push(Object.freeze({from:f.href,status:a.status,to:p.href})),await a.body?.cancel(),c=new Request(p,cE(c,m,h,u))}}function aE(e,t){return cE(e,new Headers(e.headers),e.method,t)}async function oE(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 sE(e,t,n,r){if(n)return e;let i=new Headers(e.headers);return i.delete(q.acceptPayment),t&&LT(e,r)&&i.set(q.acceptPayment,t),new Request(e,{headers:i})}function cE(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 lE(e){let t;return n=>(t??=e(n),t)}function uE(e){return Object.freeze({challenge:hE(e.challenge),challenges:e.challenges.map(e=>hE(e)),createCredential:e.createCredential,method:pE(e.method),response:mE(e.response)})}function dE(e){return Object.freeze({challenge:hE(e.challenge),credential:e.credential,method:pE(e.method),response:mE(e.response)})}function fE(e){return Object.freeze({...e.challenge?{challenge:hE(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>hE(e))}:{},error:e.error,...e.method?{method:pE(e.method)}:{},response:mE(e.response)})}function pE(e){return _E(Object.assign({},e))}function mE(e){return e instanceof Response?e.body===null?e.clone():new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText}):hE(e)}function hE(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 gE(t)}catch{return _E(e)}}function gE(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))gE(t);return e}function _E(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function vE(e,t){return t?typeof t==`string`?rC(t):t:e}async function yE(e,t){return t?t(e):e}async function bE(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&&Gw(a,r),t.createCredential(a)}function xE(e){if(typeof Response<`u`&&e instanceof Response&&e.url)return new URL(e.url)}function SE(){return J.string().check(J.regex(CE,`Invalid URI or path`))}var CE,wE,TE,EE,DE,OE,kE,AE,jE,ME=I((()=>{tS(),CE=/^([a-zA-Z][a-zA-Z\d+.-]*:\/\/\S+|\/\S*)$/,wE=new Set([`amount`,`currency`,`description`,`intent`,`method`]),TE=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())}),EE=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(TE).check(J.minLength(1)))}).check(J.refine(e=>e.offers===void 0||Object.keys(e).every(e=>e===`offers`||!wE.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`&&(wE.has(n)||r!==void 0)&&(t[n]=r);return{offers:[t]}})),DE=J.looseObject({apiReference:J.optional(SE()),homepage:J.optional(SE()),llms:J.optional(SE())}),OE=J.looseObject({categories:J.optional(J.array(J.string())),docs:J.optional(DE)}),kE=J.looseObject({"x-payment-info":J.optional(EE),requestBody:J.optional(J.unknown()),responses:J.optional(J.record(J.string(),J.unknown())),summary:J.optional(J.string())}),AE=J.looseObject({delete:J.optional(kE),get:J.optional(kE),head:J.optional(kE),options:J.optional(kE),patch:J.optional(kE),post:J.optional(kE),put:J.optional(kE),trace:J.optional(kE)}),jE=J.looseObject({openapi:J.string(),info:J.looseObject({title:J.string(),version:J.string()}),"x-service-info":J.optional(OE),paths:J.optional(J.record(J.string(),AE))})}));ME();function NE(e){let t=[],n=jE.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=EE.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 PE(e){return e}function FE(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}var IE=I((()=>{}));function LE(e,t){return Ue.resolve(e).toLowerCase()===Ue.resolve(t).toLowerCase()}var RE=I((()=>{}));function zE(e){return Number.isInteger(e)&&e>0&&e<XE}function BE(e,t){return zE(t)?e===!0||(e?.includes(t)??!1):!1}function VE(e){return Ie.zonePortal(e)}function HE(e){if(e>=2**32)return e%2**32;if(e>142431e4&&e<142432e4)return e-142431e4;if(e>4217e5&&e<42171e4)return e-4217e5;throw Error(`Cannot derive a Zone ID from chain ID ${e}. Pass \`zoneId\`.`)}function UE(e){if(e>=2**32)return Math.floor(e/2**32);if(e>142431e4&&e<142432e4)return 42431;if(e>4217e5&&e<42171e4)return 4217}function WE(e){return ne.keccak256(D.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function GE(e,t){let{timeoutMs:n=KE}=t;if(!Number.isFinite(n)||n<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);let r=await Ce(e,{cacheTime:0}),i=r>qE?r-qE:0n,a=Date.now()+n;for(;;){if(i<=r){let n=(await we(e,{address:t.portal,event:YE,args:{senderTag:t.senderTag,...t.to?{to:t.to}:{}},fromBlock:i,toBlock:r}))[0]?.transactionHash;if(n)return n;i=r+1n}if(Date.now()+JE>a)throw Error(`Zone withdrawal ${t.senderTag} did not settle on Tempo within ${n}ms.`);await new Promise(e=>setTimeout(e,JE)),r=await Ce(e,{cacheTime:0})}}var KE,qE,JE,YE,XE,ZE=I((()=>{KE=6e4,qE=7200n,JE=500,YE=N({abi:Ne.zonePortal,name:`WithdrawalProcessed`}),XE=4217e5}));function QE(e){return J.refine(e=>{let{amount:t,decimals:n}=e;return he(t,n)>0n},e)}function $E(e){let{periodCount:t,periodUnit:n}=e;try{let e=rD[n];return e!==void 0&&BigInt(t)*e<=nD}catch{return!1}}var eD,tD,nD,rD,iD,aD,oD,sD,cD,lD,uD,dD,fD,pD=I((()=>{zx(),IE(),tS(),ZE(),eD=[`push`,`pull`],tD=J.object({amount:Gx(),memo:J.optional(Zx()),recipient:J.pipe(J.string(),J.transform(e=>e))}),nD=(1n<<64n)-1n,rD={dev_second:1n,day:86400n,week:604800n},iD=J.pipe(Xx(),J.transform(e=>e.toLowerCase())),aD=J.object({accessKeyAddress:iD,keyType:J.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:J.optional(J.pipe(J.string().check(J.regex(/^0x[0-9a-fA-F]{120}$/)),J.transform(e=>e)))}),oD=J.object({accessKey:J.optional(aD),chainId:J.optional(J.number())}),sD=qx(`subscriptionExpires must be a valid date`).check(J.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),cD=J.enum([`dev_second`,`day`,`week`]),lD=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)<=nD}catch{return!1}},`periodCount exceeds uint64`)),uD=PE({name:`tempo`,intent:`charge`,schema:{credential:{payload:J.discriminatedUnion(`type`,[J.object({hash:Zx(),type:J.literal(`hash`)}),J.object({signature:$x(),type:J.literal(`transaction`)}),J.object({signature:$x(),type:J.literal(`proof`)}),J.object({hash:Zx(),senderTag:Zx(),type:J.literal(`zone`),zoneId:J.number().check(J.refine(zE,`Invalid Zone ID`))})])},request:J.pipe(J.object({machineTokenEnabled:J.optional(J.boolean()),amount:Gx(),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(tD).check(J.minLength(1),J.maxLength(10))),supportedModes:J.optional(J.array(J.enum(eD)).check(J.minLength(1))),zones:J.optional(J.union([J.literal(!0),J.array(J.number().check(J.refine(zE,`Invalid Zone ID`))).check(J.minLength(1))]))}).check(J.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=he(e,t),i=n.reduce((e,n)=>e+he(n.amount,t),0n);return n.every(e=>he(e.amount,t)>0n)&&i<r},`Invalid splits`)),J.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,zones:c,...l})=>({...l,amount:he(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:he(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),dD=PE({name:`tempo`,intent:`session`,schema:{credential:{payload:J.discriminatedUnion(`action`,[J.object({action:J.literal(`open`),authorizedSigner:J.optional(J.string()),channelId:Zx(),cumulativeAmount:Gx(),descriptor:J.optional(J.custom()),signature:$x(),transaction:$x(),type:J.literal(`transaction`)}),J.object({action:J.literal(`topUp`),additionalDeposit:Gx(),channelId:Zx(),descriptor:J.optional(J.custom()),transaction:$x(),type:J.literal(`transaction`)}),J.object({action:J.literal(`voucher`),channelId:Zx(),cumulativeAmount:Gx(),descriptor:J.optional(J.custom()),signature:$x()}),J.object({action:J.literal(`close`),channelId:Zx(),closeSignature:$x(),cumulativeAmount:Gx(),descriptor:J.optional(J.custom()),signature:$x()})])},request:J.pipe(J.object({amount:Gx(),chainId:J.optional(J.number()),channelId:J.optional(Zx()),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(Xx()),minVoucherDelta:J.optional(Gx()),operator:J.optional(Xx()),recipient:J.optional(J.string()),sessionProtocol:J.optional(J.enum([Rx.v2,Rx.v1])),sessionSnapshot:J.optional(J.custom()),suggestedDeposit:J.optional(Gx()),unitType:J.string()}).check(J.refine(({amount:e,decimals:t})=>he(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:he(e,r).toString(),...d?{suggestedDeposit:he(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:he(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&&{[Lx.sessionProtocol]:l},...u!==void 0&&{[Lx.sessionSnapshot]:u}}})))}}),fD=PE({name:`tempo`,intent:`subscription`,schema:{credential:{payload:J.object({signature:$x(),type:J.literal(`keyAuthorization`)})},request:J.pipe(J.object({amount:Gx(),accessKey:J.optional(aD),chainId:J.optional(J.number()),currency:iD,decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:J.optional(oD),periodCount:lD,periodUnit:cD,recipient:iD,subscriptionExpires:sD}).check(QE(`Subscription amount must be greater than 0`),J.refine($E,`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:he(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}})}));function mD(e){return e>=0n&&e<=ND}function hD(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return mD(t)?t:void 0}function gD(e){return _D(e),e}function _D(e){if(!mD(e))throw Error(`Value ${e} is outside uint96 bounds.`)}function vD(e){return typeof e==`object`&&!!e}function yD(e){return typeof e==`string`&&PD.has(e)}function bD(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!yD(t.action))}function xD(e,t=`No session credential context available.`){if(!bD(e))throw Error(t);return e}function SD(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function CD(e){return vD(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function wD(e){return vD(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 TD(e){let t=O.toString(e),n=JSON.parse(t);if(!wD(n))throw Error(`Invalid session receipt.`);return n}function ED(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function DD(e){let t=`message`,n=[];for(let r of e.split(`
228
+ `,i))}t=t.slice(i)}}}var DC=F((()=>{}));function OC(e){let{extensions:t,resource:n,...r}=e;return HC.parse(r)}var kC,AC,jC,MC,NC,PC,FC,IC,LC,RC,zC,BC,VC,HC,UC,WC,GC,KC,qC,JC,YC,XC,ZC=F((()=>{nS(),kC=`charge`,AC=[`exact`],jC=`eip155:`,MC=`x402:`,NC=`PAYMENT-REQUIRED`,PC=`PAYMENT-SIGNATURE`,FC=`PAYMENT-RESPONSE`,IC=J.string().check(J.minLength(1)),LC=J.number().check(J.refine(e=>e>0,`Must be positive`)),RC=J.string().check(J.regex(/^\d+$/,`Invalid atomic amount`)),zC=Zx(),BC=J.string().check(J.regex(RegExp(`^${jC}\\d+$`),`Invalid EVM CAIP-2 network`)),VC=J.object({description:J.optional(J.string()),iconUrl:J.optional(J.string()),mimeType:J.optional(J.string()),serviceName:J.optional(J.string()),tags:J.optional(J.array(J.string())),url:IC}),J.discriminatedUnion(`type`,[J.object({name:IC,type:J.literal(`eip3009`),version:IC}),J.object({name:J.optional(J.string()),type:J.literal(`permit2`),version:J.optional(J.string())})]),HC=J.object({amount:RC,asset:IC,extra:J.optional(J.record(J.string(),J.unknown())),maxTimeoutSeconds:LC,network:BC,payTo:IC,scheme:J.enum(AC)}),UC=J.object({info:J.record(J.string(),J.unknown()),schema:J.record(J.string(),J.unknown())}),WC=J.record(J.string(),UC),GC=J.object({accepts:J.array(HC).check(J.minLength(1)),error:J.optional(J.string()),extensions:J.optional(WC),resource:VC,x402Version:J.literal(2)}),KC=J.object({authorization:J.object({from:zC,nonce:Qx(),to:zC,validAfter:RC,validBefore:RC,value:RC}),signature:eS()}),qC=J.object({permit2Authorization:J.object({deadline:RC,from:zC,nonce:RC,permitted:J.object({amount:RC,token:zC}),spender:zC,witness:J.object({to:zC,validAfter:RC})}),signature:eS()}),JC=J.union([KC,qC]),YC=J.object({accepted:HC,extensions:J.optional(WC),payload:JC,resource:J.optional(VC),x402Version:J.literal(2)}),J.object({extensions:J.optional(WC),extra:J.optional(J.record(J.string(),J.unknown())),invalidMessage:J.optional(J.string()),invalidReason:J.optional(J.string()),isValid:J.boolean(),payer:J.optional(J.string())}),XC=J.object({amount:J.optional(RC),errorMessage:J.optional(J.string()),errorReason:J.optional(J.string()),extensions:J.optional(WC),extra:J.optional(J.record(J.string(),J.unknown())),network:IC,payer:J.optional(J.string()),success:J.boolean(),transaction:J.string()})}));function QC(e,t,n){let r=new Headers(e.headers);for(let e of $C)e===q.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}var $C,ew=F((()=>{Bx(),ZC(),$C=[q.authorization,NC,FC,PC]}));function tw(e){if(typeof e==`string`)try{let t=JSON.parse(e),n=t?.id;return t?.jsonrpc!==`2.0`||typeof t?.method!=`string`?void 0:typeof n==`string`||typeof n==`number`?n:void 0}catch{return}}function nw(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t?.method===`tools/call`&&t.params?._meta?.[`mppx/payment-client`]===!0}catch{return!1}}function rw(e){let t=tw(e?.body);if(t===void 0)return;let n=new Headers(e?.headers);if(n.has(`mcp-method`))return t;let r=n.get(`accept`)?.toLowerCase()??``;return r.includes(`application/json`)&&r.includes(`text/event-stream`)?t:void 0}function iw(e){if(!e||typeof e!=`object`)return;let t=e,n=t.id;if(t.jsonrpc!==`2.0`||n!==void 0&&typeof n!=`string`&&typeof n!=`number`)return;let r=`error`in t;if(r!==`result`in t)return r?Number.isInteger(t.error?.code)&&typeof t.error?.message==`string`?e:void 0:n!==void 0&&typeof t.result==`object`?e:void 0}function aw(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){let t=SS.safeParse(e);if(!t.success)return;n.push(t.data)}let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function ow(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:aw(e.error.data):aw(e.result?._meta?.[wC])}function sw(e,t){return!e||e.id!==t?[]:ow(e)?.challenges??[]}async function cw(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=EC(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=iw(JSON.parse(e.data))}catch{}});try{for(;;){if(i)return a;let{done:e,value:s}=await t.read();if(e)return o.feed(n.decode()),a;if(r+=s.byteLength,r>fw)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function lw(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=``;try{for(;;){let{done:e,value:a}=await t.read();if(e)return iw(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>fw)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function uw(e){let t=pw.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>fw)){if(t.includes(`application/json`))return lw(e);if(t.includes(`text/event-stream`))return cw(e)}})();return pw.set(e,n),n}function dw(){return{getChallenges(e,t){let n=rw(t);return e.status===402||n===void 0?[]:uw(e).then(e=>sw(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=MS(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,[CC]:r}}})}}}}var fw,pw,mw=F((()=>{CS(),VS(),DC(),TC(),ew(),fw=1048576,pw=new WeakMap}));function hw(){return{getChallenges(e){let t=e.headers.get(q.wwwAuthenticate);return e.status!==402||!t||!fS(t)?[]:mS(e)},setCredential(e,t,n){return QC(e,n?.challenge?vS(n.challenge):q.authorization,t)}}}var gw=F((()=>{CS(),Bx(),ew()}));function _w(e){return{encode(t){return A.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(A.toString(t)))}catch{throw new vw}}}}var vw,yw=F((()=>{vw=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}}}));function bw(e){try{let t=JSON.parse(A.toString(e));return Ew(t)}catch{throw new vw}}var xw,Sw,Cw,ww,Tw,Ew,Dw=F((()=>{yw(),ZC(),xw=_w(GC),Sw=_w(YC),Cw=_w(XC),ww=xw.encode,xw.decode,Tw=Sw.encode,Sw.decode,Cw.encode,Cw.decode,Ew=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new vw;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new vw;let n=VC.parse(t.resource),r=t.extensions===void 0?void 0:WC.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}}}));function Ow(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(NC);if(!t)return[];let n=bw(t);return n.accepts.flatMap((e,t)=>{let r=HC.safeParse(e);if(!r.success)return[];let i=r.data;return QS(rS({id:`${MC}${t}`,intent:kC,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return QC(e,PC,t)}}}var kw=F((()=>{CS(),Dw(),tC(),ZC(),ew()}));function Aw(e){return e}function jw(){let e=[hw(),Ow(),dw()],t=new WeakMap,n=(e,n)=>{for(let r of n)t.set(r,e);return n},r=(t,r)=>{let i=(a,o)=>{for(let s=a;s<e.length;s++){let a=e[s],c=a.getChallenges(t,r);if(c instanceof Promise)return c.then(e=>i(s+1,[...o,...n(a,e)]));o.push(...n(a,c))}return o};return i(0,[])};return Aw({name:`http`,isPaymentRequired(e,t){if(e.status===402)return!0;let n=r(e,t);return n instanceof Promise?n.then(e=>e.length>0):n.length>0},getChallenges(e,t){return r(e,t)},setCredential(n,r,i){let a=i?.challenge?t.get(i.challenge):void 0,o=e[0];if(!a&&!o)throw Error(`No protocol to attach the credential.`);return(a??o).setCredential(n,r,i)}})}var Mw=F((()=>{mw(),gw(),ew(),kw()}));function Nw(e,t){return Lw.set(e,t),e}function Pw(e){return Lw.has(e)}function Fw(e,t){return Promise.resolve(Lw.get(e)?.(t))}function Iw(e){return Lw.get(e)}var Lw,Rw=F((()=>{Lw=new WeakMap}));function zw(e,t){return Jw.set(e,t),e}function Bw(e){Jw.delete(e)}function Vw(e,t,n){Jw.has(e)&&Yw.set(t,n)}function Hw(e){return Yw.get(e)}function Uw(e,t){return Promise.resolve(Jw.get(e)?.(t)??t.response)}function Ww(e,t){return Zw.set(e,t),e}function Gw(e,t){try{return Zw.get(e)?.(t)}catch{return}}function Kw(e,t){Xw.set(e,t)}function qw(e){return Xw.get(e)??Yw.get(e)?.origin}var Jw,Yw,Xw,Zw,Qw=F((()=>{Jw=new WeakMap,Yw=new WeakMap,Xw=new WeakMap,Zw=new WeakMap}));function $w(e,t,n){if(!tT(e)&&(e.method!==`tempo`||e.intent!==`session`))return;t=typeof t==`function`?t():t;let{realm:r}=e;if(r.toLowerCase()===t.hostname.toLowerCase())return;let i=t.origin.toLowerCase();for(let[e,t]of Object.entries(n??{}))if(t===r&&nT(e)===i)return;throw Error(`Refusing to sign Tempo proof for realm ${JSON.stringify(r)} from ${t.origin}. Pin the realm to this origin with \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function eT(e,t){if(!(!tT(e)&&(e.method!==`tempo`||e.intent!==`session`))&&!t?.includes(e.realm))throw Error(`Refusing to sign Tempo proof for untrusted realm ${JSON.stringify(e.realm)}. Add it to \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function tT(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function nT(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}var rT=F((()=>{}));async function iT(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},YT);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>JT){i=!0;break}}}finally{clearTimeout(a),t.cancel().catch(()=>{})}if(!i)return e;e.body.cancel().catch(()=>{});let o=new Headers(e.headers);o.delete(`content-length`),o.set(XT,`true`);let s=new Response(new Blob(n).slice(0,JT),{headers:o,status:e.status,statusText:e.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{value:e[t]});return s}async function aT(e,t){let n=e?.attempt.settle;if(!n)return t.status!==`pending`;e.attempt.settle=void 0;let r=await n(t);return r||(e.attempt.settle=n),r}function oT(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=qT,methods:a,onChallenge:o,orderChallenges:s,transport:c=jw(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&AT(e.fetch)),d=e.eventDispatcher??lT(),f=t??rC(a),p=jT(r),m=async(e,t,n)=>u?(await u.send(p,new Request(e,t),n)).response:p(e,t),h=async(e,t,r)=>{let g=kT(e,t?.headers),_=g.has(q.acceptPayment),v=IT(g,f),y=DT(e,t,g),b=ET(e,t,g,v.header,_,n),x=await m(MT(b.input),b.init),S=OT(b.init,await y);if(t?.[KT]||nw(S)||!await c.isPaymentRequired(x,S))return x;let C=t?.context,{context:w,orderChallenges:T,...E}=S??{},ee,D,O,k,A;try{for(let n=0;n<i;n++){D=await c.getChallenges(x,S);let i=(await LT(sC(D,a,v.entries,C),T??s))[0];if(!i){if(await aT(k,{challenges:D,response:x,status:`rejected`}),n>0)return x;throw Error(`No method found for challenges: ${D.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let f=i.challenge;ee=f,O=i.method,ee.expires&&AS(ee.expires,ee.id),await u?.challenge(x,{challenge:f},VT(b.input).href);let g=await UT(x,b.input,b.input,E);$w(f,()=>VT(g),l);let _=k,y=iS(f),w=_?.method===i.method&&_?.key===y,te=!1;if(_){let e=await aT(_,{challenges:D,response:x,status:w?`pending`:`rejected`});te=w&&!e}k=te?_:void 0;let ne=mT(async n=>{if(n===void 0&&te&&_)return _.promise;te&&_&&(await aT(_,{status:`rejected`}),k=void 0),NT(e,t)?.throwIfAborted();let r=n??C;if(!Pw(i.method))return FT(f,i.method,r);let a={origin:VT(g).origin,prepare:()=>Fw(i.method,{challenge:f,context:r,fetch:u?KS(p,u,{challenge:f}):p,input:g,signal:NT(e,t)})},o=a.prepare().then(()=>FT(f,i.method,r,a));return k={context:r,attempt:a,key:n===void 0?y:void 0,method:i.method,promise:o},o}),j=await d.emit(`challenge.received`,hT({challenge:f,challenges:D,createCredential:ne,init:t,input:e,method:i.method,response:x}))??(o?await o(ee,{createCredential:ne}):void 0)??await ne(),re=k;re&&await re.promise.catch(()=>void 0)!==j&&(await aT(re,{status:`rejected`}),k=void 0);let M=k?k.context:C;PT(j),await d.emit(`credential.created`,gT({challenge:f,credential:j,init:t,input:e,method:i.method,response:x}));let ie=e=>new DS({cause:e,challenge:f,credential:j,transactionHash:Gw(i.method,j)});try{x=await m(g,{...c.setCredential({...E,headers:b.headers},j,{challenge:f}),redirect:`manual`},{challenge:f})}catch(e){throw A=ie(e),e}let ae=await c.isPaymentRequired(x,S);if(ae||(await aT(re,{response:x,status:x.status>=300&&x.status<400?`pending`:x.ok?`accepted`:`rejected`}),k=void 0),x.ok&&uT(d,`payment.response`)&&await d.emit(`payment.response`,_T({challenge:f,credential:j,init:t,input:e,method:i.method,response:x})),!ae){if(x.status>=500&&uT(d,`payment.failed`)){try{x=await iT(x)}catch(e){throw A=ie(e),x=new Response(null,{headers:x.headers,status:x.status,statusText:x.statusText}),e}await d.emit(`payment.failed`,vT({challenge:f,challenges:D,error:ie(),init:t,input:e,method:i.method,response:x}))}return x.ok?Uw(i.method,{context:M,challenge:f,credential:j,fetch:p,headers:b.headers,input:g,...r?{refetch:()=>h(MT(b.input),t,!1)}:{},response:x,signal:NT(e,t)}):x}}D=void 0;try{D=await c.getChallenges(x,S)}catch{}return await aT(k,{challenges:D,response:x,status:`rejected`}),x}catch(n){throw await aT(k,{challenges:D,response:x,status:`rejected`}),await d.emit(`payment.failed`,vT({challenge:ee,challenges:D,error:A??n,init:t,input:e,method:O,response:x})),n}},g=(e,t)=>h(e,t,!0);return g[WT]=p,u&&(g[GT]=u),g}function sT(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);ZT||=globalThis.fetch,globalThis.fetch=oT({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??(BT()?`same-origin`:`always`),fetch:jT(globalThis.fetch)})}function cT(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return Array.isArray(e)?Object.fromEntries(e):e}function lT(){let e={"*":new Set,"challenge.received":new Set,"credential.created":new Set,"payment.failed":new Set,"payment.response":new Set},t={async emit(t,n){switch(t){case`challenge.received`:{let r;for(let t of e[`challenge.received`]){let e=await dT(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await pT(e[`*`],t,n),r}case`credential.created`:await fT(e[`credential.created`],n),await pT(e[`*`],t,n);return;case`payment.failed`:await fT(e[`payment.failed`],n),await pT(e[`*`],t,n);return;case`payment.response`:await fT(e[`payment.response`],n),await pT(e[`*`],t,n);return}},on:(t,n)=>{switch(t){case`*`:case`challenge.received`:case`credential.created`:case`payment.failed`:case`payment.response`:return e[t].add(n),()=>e[t].delete(n);default:throw Error(`Unknown client event "${String(t)}".`)}}};return QT.set(t,t=>e[t].size>0||e[`*`].size>0),t}function uT(e,t){return QT.get(e)?.(t)??!0}async function dT(e,t){try{return await e(t)}catch{return}}async function fT(e,t){for(let n of e)try{await n(t)}catch{}}async function pT(e,t,n){await fT(e,Object.freeze({name:t,payload:n}))}function mT(e){let t;return n=>(t??=e(n),t)}function hT(e){return Object.freeze({challenge:CT(e.challenge),challenges:e.challenges.map(e=>CT(e)),createCredential:e.createCredential,init:yT(e.init),input:bT(e.input),method:xT(e.method),response:ST(e.response)})}function gT(e){return Object.freeze({challenge:CT(e.challenge),credential:e.credential,init:yT(e.init),input:bT(e.input),method:xT(e.method),...e.response===void 0?{}:{response:ST(e.response)}})}function _T(e){return Object.freeze({challenge:CT(e.challenge),credential:e.credential,init:yT(e.init),input:bT(e.input),method:xT(e.method),response:ST(e.response)})}function vT(e){return Object.freeze({...e.challenge?{challenge:CT(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>CT(e))}:{},error:e.error,init:yT(e.init),input:bT(e.input),...e.method?{method:xT(e.method)}:{},...e.response===void 0?{}:{response:ST(e.response)}})}function yT(e){if(e)return TT({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function bT(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function xT(e){return TT(Object.assign({},e))}function ST(e){if(e instanceof Response)try{return e.clone()}catch{let t=new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText});for(let n of[`redirected`,`type`,`url`])Object.defineProperty(t,n,{value:e[n]});return t}return CT(e)}function CT(e){try{return wT(structuredClone(e))}catch{return TT(e)}}function wT(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))wT(t);return e}function TT(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function ET(e,t,n,r,i,a){let o=!!r&&!i&&RT(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(q.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function DT(e,t,n){if(!(!(e instanceof Request)||t?.body!==void 0||!e.body||e.bodyUsed)){if(!n.has(`mcp-method`)){let e=n.get(`accept`)?.toLowerCase()??``;if(!e.includes(`application/json`)||!e.includes(`text/event-stream`))return}try{return e.clone().text().catch(()=>void 0)}catch{return}}}function OT(e,t){return t===void 0?e:{...e,body:t}}function kT(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function AT(e){return e[GT]}function jT(e){let t=e;for(;t[WT];)t=t[WT];return t}function MT(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function NT(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function PT(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
229
+ `))throw Error(`Credential header value contains illegal newline characters`)}async function FT(e,t,n,r){let i=t.context&&n!==void 0?t.context.parse(n):void 0,a=i===void 0?{challenge:e}:{challenge:e,context:i};return r?.origin&&Kw(a,r.origin),r&&Vw(t,a,r),t.createCredential(a)}function IT(e,t){let n=e.get(q.acceptPayment);if(!n)return t;try{return{...t,entries:iC(n),header:n}}catch{return t}}async function LT(e,t){return t?t(e):e}function RT(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=VT(e);return t===`same-origin`?!BT()||n.origin===globalThis.location.origin:t.origins.some(e=>zT(n,e))}function zT(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e.hostname.endsWith(n)||e.hostname===t.slice(2)}return e.origin===new URL(t).origin}function BT(){return globalThis.location!==void 0}function VT(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,BT()?globalThis.location.href:void 0)}function HT(e,t){let n=e instanceof Request?e:void 0;if((t.mode??n?.mode)===`no-cors`)throw Error(`Cannot automatically pay a no-cors request: it cannot carry a credential.`);if((t.cache??n?.cache)===`only-if-cached`)throw Error(`Cannot automatically pay an only-if-cached request: its retry cannot reach the server.`)}async function UT(e,t,n,r){if(HT(t,r),!e.url)return t;let i=new URL(e.url),a=VT(n);if(i.origin!==a.origin)throw Error(`Refusing to send payment credential across redirect from ${a.origin} to ${i.origin}`);let o=(r.method??(t instanceof Request?t.method:`GET`)).toUpperCase();if(e.redirected&&o!==`GET`&&o!==`HEAD`)throw Error(`Cannot automatically pay a redirected ${o} request. Use prepareRequest() to preserve redirect semantics.`);if(t instanceof Request){let n=r.body==null?t.clone():t,i=new Request(n,t.mode===`navigate`&&r.mode===void 0?{...r,mode:`same-origin`}:r);return i.url.split(`#`)[0]===e.url?i:i.body?new Request(e.url,{body:await i.arrayBuffer(),cache:i.cache,credentials:i.credentials,headers:i.headers,integrity:i.integrity,keepalive:i.keepalive,method:i.method,mode:i.mode,redirect:i.redirect,referrer:i.referrer,referrerPolicy:i.referrerPolicy,signal:i.signal}):new Request(e.url,i)}return e.url}var WT,GT,KT,qT,JT,YT,XT,ZT,QT,$T=F((()=>{CS(),Bx(),kS(),jS(),ZS(),SC(),Mw(),Rw(),Qw(),rT(),mw(),WT=Symbol.for(`mppx.fetch.wrapper`),GT=Symbol.for(`mppx.fetch.identity`),KT=Symbol.for(`mppx.fetch.skipPayment`),qT=3,JT=65536,YT=2e3,XT=`Mppx-Body-Truncated`,QT=new WeakMap}));Nx(),Bx(),jS(),ZS(),SC(),$T(),Rw(),Qw(),rT(),Mw();const eE=new WeakMap;function tE(e){let{identity:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=jw(),trustedTempoProofRealms:c}=e;if(`attestation`in e)throw TypeError("Mppx client `attestation` was replaced by `identity: [prover]`.");let l=jT(e.fetch??globalThis.fetch),u=t?WS(t):e.fetch&&AT(e.fetch),d=e.methods.flat(),f=rC(d,e.paymentPreferences),p=lT(),m=r,h={acceptPayment:f,acceptPaymentPolicy:o,...e.fetch&&{fetch:l},...u&&{identity:u},eventDispatcher:p,...n!==void 0&&{maxPaymentRetries:n},...m&&{onChallenge:m},...i&&{orderChallenges:i},methods:d,transport:s,...c&&{trustedTempoProofRealms:c}},g=oT(h);a&&sT(h);function _(e){return p.on(`challenge.received`,e)}function v(e){return p.on(`credential.created`,e)}function y(e){return p.on(`payment.failed`,e)}function b(e){return p.on(`payment.response`,e)}async function x(e,t,n){let r=hE(e),a=await s.getChallenges(e,t?.request),o=Object.freeze(a.map(e=>gE(e))),l=yE(f.entries,t?.acceptPayment),u,m;try{let f=sC(a,d,l,n);f.length===0&&n===void 0&&(f=sC(a,d,l,xC));let h=(await bE(f,t?.orderChallenges??i))[0];if(!h)throw Error(`No method found for challenges: ${a.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${d.map(e=>`${e.name}.${e.intent}`).join(`, `)}`);let g=h.challenge;u=o[h.index],m=h.method,u.expires&&AS(u.expires,u.id);let _=SE(e);_?$w(u,_,c):s.name===`mcp`&&eT(u,c&&Object.values(c));let v=u,y=m,b=uE(async e=>{try{v.expires&&AS(v.expires,v.id);let t=uE(t=>xE(v,y,t??e,_?.origin)),n=await p.emit(`challenge.received`,dE({challenge:v,challenges:a,createCredential:t,method:y,response:r}))??await t();return PT(n),await p.emit(`credential.created`,fE({challenge:v,credential:n,method:y,response:r})),n}catch(e){throw await p.emit(`payment.failed`,pE({challenge:v,challenges:a,error:e,method:y,response:r})),e}}),x=Object.freeze({challenge:v,challenges:o,createCredential:b,method:mE(y),setCredential(e,t){return PT(t),s.setCredential(e,t,{challenge:g})}});return eE.set(x,y),x}catch(e){throw await p.emit(`payment.failed`,pE({challenge:u,challenges:a,error:e,method:m,response:r})),e}}async function S(e,t,n){let{maxRedirects:r=20,requirePayment:i=!1,...a}=n??{},d=await aE({acceptPayment:f.header,acceptPaymentPolicy:o,fetch:l,init:t,input:e,maxRedirects:r,identity:u}),p=oE(d.replayRequest,d.body);if(!await s.isPaymentRequired(d.response,p)){if(i)throw Error(`Response does not require payment.`);return Object.freeze({payment:void 0,request:d.request,response:d.response,redirects:d.redirects})}let m=await x(d.response,{...a,request:p});$w(m.challenge,new URL(d.replayRequest.url),c);let h=eE.get(m)??m.method,g=uE(async e=>(await u?.challenge(d.response,{challenge:m.challenge},d.replayRequest.url),Pw(h)&&await Fw(h,{challenge:m.challenge,context:e,fetch:u?KS(l,u,{challenge:m.challenge}):l,input:d.replayRequest,signal:d.replayRequest.signal}),m.createCredential(e))),_=Object.freeze({...m,createCredential:g,async pay(e){let t=await g(e),n=m.setCredential(oE(d.replayRequest,d.body),t),r=new Request(d.replayRequest.url,{...n,redirect:`manual`});if(!u)return l(r);let{response:i}=await u.send(l,r,{challenge:m.challenge});return i}});return Object.freeze({payment:_,request:d.request,response:d.response,redirects:d.redirects})}return{fetch:g,rawFetch:l,methods:d,transport:s,on:p.on,onChallengeReceived:_,onCredentialCreated:v,onPaymentFailed:y,onPaymentResponse:b,preparePayment:x,prepareRequest:S,async createCredential(e,t,n){return(await x(e,n,t)).createCredential(t)}}}const nE=new Set([301,302,303,307,308]),rE=[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`,`transfer-encoding`],iE=[`authorization`,`cookie`,`cookie2`,`host`,`payment-authorization`,`payment-signature`,`proxy-authorization`,`x-payment`];async function aE(e){let{acceptPayment:t,acceptPaymentPolicy:n,fetch:r,identity:i,init:a,input:o,maxRedirects:s}=e;if(!Number.isInteger(s)||s<0)throw TypeError(`maxRedirects must be a non-negative integer.`);let c=new Request(o,{...a,redirect:`manual`}),l=c.headers.has(q.acceptPayment),u=await sE(c,a?.body),d=[];for(;;){c=cE(c,t,l,n);let{request:e,response:a}=await(async()=>{if(i)return i.send(r,c.clone());let e=c.clone();return{request:e,response:await r(e)}})();if(a.type===`opaqueredirect`||a.status===0)throw Error(`prepareRequest requires a runtime that exposes manual redirect responses.`);if(!nE.has(a.status))return{body:u,replayRequest:c,request:e,response:a,redirects:Object.freeze(d)};let o=a.headers.get(`location`);if(!o)return{body:u,replayRequest:c,request:e,response:a,redirects:Object.freeze(d)};if(d.length>=s)throw await a.body?.cancel(),Error(`Payment request exceeded ${s} redirects.`);let f=new URL(c.url),p=new URL(o,f);if(f.protocol===`https:`&&p.protocol!==`https:`)throw await a.body?.cancel(),Error(`Payment request refused HTTPS downgrade redirect to ${p.href}`);let m=new Headers(c.headers),h=c.method;if((a.status===301||a.status===302)&&h===`POST`||a.status===303&&h!==`GET`&&h!==`HEAD`){h=`GET`,u=void 0;for(let e of rE)m.delete(e)}if(f.origin!==p.origin)for(let e of[...m.keys()]){let t=m.get(e)??``;(iE.includes(e)||t.startsWith(`Payment `))&&m.delete(e)}d.push(Object.freeze({from:f.href,status:a.status,to:p.href})),await a.body?.cancel(),c=new Request(p,lE(c,m,h,u))}}function oE(e,t){return lE(e,new Headers(e.headers),e.method,t)}async function sE(e,t){if(typeof t==`string`)return t;if(!e.body)return;let n=e.headers.get(`accept`)?.toLowerCase()??``;return e.headers.has(`mcp-method`)||n.includes(`application/json`)&&n.includes(`text/event-stream`)?e.clone().text():e.clone().arrayBuffer()}function cE(e,t,n,r){if(n)return e;let i=new Headers(e.headers);return i.delete(q.acceptPayment),t&&RT(e,r)&&i.set(q.acceptPayment,t),new Request(e,{headers:i})}function lE(e,t,n,r){return{...r?{body:r}:{},cache:e.cache,credentials:e.credentials,headers:t,integrity:e.integrity,keepalive:e.keepalive,method:n,mode:e.mode,redirect:`manual`,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal}}function uE(e){let t;return n=>(t??=e(n),t)}function dE(e){return Object.freeze({challenge:gE(e.challenge),challenges:e.challenges.map(e=>gE(e)),createCredential:e.createCredential,method:mE(e.method),response:hE(e.response)})}function fE(e){return Object.freeze({challenge:gE(e.challenge),credential:e.credential,method:mE(e.method),response:hE(e.response)})}function pE(e){return Object.freeze({...e.challenge?{challenge:gE(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>gE(e))}:{},error:e.error,...e.method?{method:mE(e.method)}:{},response:hE(e.response)})}function mE(e){return vE(Object.assign({},e))}function hE(e){return e instanceof Response?e.body===null?e.clone():new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText}):gE(e)}function gE(e){try{let t=structuredClone(e);if(e&&t&&typeof e==`object`&&typeof t==`object`)for(let n of Object.getOwnPropertySymbols(e)){let r=Object.getOwnPropertyDescriptor(e,n);r&&Object.defineProperty(t,n,r)}return _E(t)}catch{return vE(e)}}function _E(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))_E(t);return e}function vE(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function yE(e,t){return t?typeof t==`string`?iC(t):t:e}async function bE(e,t){return t?t(e):e}async function xE(e,t,n,r){let i=t.context&&n!==void 0?t.context.parse(n):void 0,a=i===void 0?{challenge:e}:{challenge:e,context:i};return r&&Kw(a,r),t.createCredential(a)}function SE(e){if(typeof Response<`u`&&e instanceof Response&&e.url)return new URL(e.url)}function CE(){return J.string().check(J.regex(wE,`Invalid URI or path`))}var wE,TE,EE,DE,OE,kE,AE,jE,ME,NE=F((()=>{nS(),wE=/^([a-zA-Z][a-zA-Z\d+.-]*:\/\/\S+|\/\S*)$/,TE=new Set([`amount`,`currency`,`description`,`intent`,`method`]),EE=J.looseObject({amount:J.optional(J.union([J.null(),J.string().check(J.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:J.optional(J.string()),description:J.optional(J.string()),intent:J.optional(J.string()),method:J.optional(J.string())}),DE=J.pipe(J.looseObject({amount:J.optional(J.union([J.null(),J.string().check(J.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:J.optional(J.string()),description:J.optional(J.string()),intent:J.optional(J.string()),method:J.optional(J.string()),offers:J.optional(J.array(EE).check(J.minLength(1)))}).check(J.refine(e=>e.offers===void 0||Object.keys(e).every(e=>e===`offers`||!TE.has(e)),`Cannot mix offers with flat payment info fields`)),J.transform(e=>{if(e.offers)return{offers:e.offers};let t={};for(let[n,r]of Object.entries(e))n!==`offers`&&(TE.has(n)||r!==void 0)&&(t[n]=r);return{offers:[t]}})),OE=J.looseObject({apiReference:J.optional(CE()),homepage:J.optional(CE()),llms:J.optional(CE())}),kE=J.looseObject({categories:J.optional(J.array(J.string())),docs:J.optional(OE)}),AE=J.looseObject({"x-payment-info":J.optional(DE),requestBody:J.optional(J.unknown()),responses:J.optional(J.record(J.string(),J.unknown())),summary:J.optional(J.string())}),jE=J.looseObject({delete:J.optional(AE),get:J.optional(AE),head:J.optional(AE),options:J.optional(AE),patch:J.optional(AE),post:J.optional(AE),put:J.optional(AE),trace:J.optional(AE)}),ME=J.looseObject({openapi:J.string(),info:J.looseObject({title:J.string(),version:J.string()}),"x-service-info":J.optional(kE),paths:J.optional(J.record(J.string(),jE))})}));NE();function PE(e){let t=[],n=ME.safeParse(e);if(!n.success){for(let e of n.error.issues)t.push({message:e.message,path:e.path.map(String).join(`.`)||`(root)`,severity:`error`});return t}let r=n.data.paths;if(!r)return t;for(let[e,n]of Object.entries(r))for(let[r,i]of Object.entries(n)){if(!i||typeof i!=`object`||Array.isArray(i))continue;let n=i,a=`paths.${e}.${r}`,o=n[`x-payment-info`];if(!o)continue;let s=DE.safeParse(o);if(!s.success){for(let e of s.error.issues){let n=e.path.length>0?`.${e.path.map(String).join(`.`)}`:``;t.push({message:e.message,path:`${a}.x-payment-info${n}`,severity:`error`})}continue}let c=n.responses;(!c||!(`402`in c))&&t.push({message:`Operation with x-payment-info MUST have a 402 response`,path:`${a}.responses`,severity:`error`});let l=r.toUpperCase();!n.requestBody&&(l===`POST`||l===`PUT`||l===`PATCH`)&&t.push({message:`Operation with x-payment-info has no requestBody`,path:a,severity:`warning`})}return t}const FE=`2026-07-29.preview`;function IE(e){return e}function LE(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}var RE=F((()=>{}));function zE(e,t){return Ge.resolve(e).toLowerCase()===Ge.resolve(t).toLowerCase()}var BE=F((()=>{}));function VE(e){return Number.isInteger(e)&&e>0&&e<QE}function HE(e,t){return VE(t)?e===!0||(e?.includes(t)??!1):!1}function UE(e){return Re.zonePortal(e)}function WE(e){if(e>=2**32)return e%2**32;if(e>142431e4&&e<142432e4)return e-142431e4;if(e>4217e5&&e<42171e4)return e-4217e5;throw Error(`Cannot derive a Zone ID from chain ID ${e}. Pass \`zoneId\`.`)}function GE(e){if(e>=2**32)return Math.floor(e/2**32);if(e>142431e4&&e<142432e4)return 42431;if(e>4217e5&&e<42171e4)return 4217}function KE(e){return ne.keccak256(k.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function qE(e,t){let{timeoutMs:n=JE}=t;if(!Number.isFinite(n)||n<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);let r=await Te(e,{cacheTime:0}),i=r>YE?r-YE:0n,a=Date.now()+n;for(;;){if(i<=r){let n=(await Ee(e,{address:t.portal,event:ZE,args:{senderTag:t.senderTag,...t.to?{to:t.to}:{}},fromBlock:i,toBlock:r}))[0]?.transactionHash;if(n)return n;i=r+1n}if(Date.now()+XE>a)throw Error(`Zone withdrawal ${t.senderTag} did not settle on Tempo within ${n}ms.`);await new Promise(e=>setTimeout(e,XE)),r=await Te(e,{cacheTime:0})}}var JE,YE,XE,ZE,QE,$E=F((()=>{JE=6e4,YE=7200n,XE=500,ZE=ce({abi:Fe.zonePortal,name:`WithdrawalProcessed`}),QE=4217e5}));function eD(e){return J.refine(e=>{let{amount:t,decimals:n}=e;return _e(t,n)>0n},e)}function tD(e){let{periodCount:t,periodUnit:n}=e;try{let e=aD[n];return e!==void 0&&BigInt(t)*e<=iD}catch{return!1}}var nD,rD,iD,aD,oD,sD,cD,lD,uD,dD,fD,pD,mD,hD=F((()=>{Bx(),RE(),nS(),$E(),nD=[`push`,`pull`],rD=J.object({amount:Kx(),memo:J.optional(Qx()),recipient:J.pipe(J.string(),J.transform(e=>e))}),iD=(1n<<64n)-1n,aD={dev_second:1n,day:86400n,week:604800n},oD=J.pipe(Zx(),J.transform(e=>e.toLowerCase())),sD=J.object({accessKeyAddress:oD,keyType:J.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:J.optional(J.pipe(J.string().check(J.regex(/^0x[0-9a-fA-F]{120}$/)),J.transform(e=>e)))}),cD=J.object({accessKey:J.optional(sD),chainId:J.optional(J.number())}),lD=Jx(`subscriptionExpires must be a valid date`).check(J.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),uD=J.enum([`dev_second`,`day`,`week`]),dD=J.pipe(J.union([J.string(),J.bigint(),J.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),J.transform(e=>e.toString())).check(J.regex(/^[1-9]\d*$/,`Invalid periodCount`),J.refine(e=>{try{return BigInt(e)<=iD}catch{return!1}},`periodCount exceeds uint64`)),fD=IE({name:`tempo`,intent:`charge`,schema:{credential:{payload:J.discriminatedUnion(`type`,[J.object({hash:Qx(),type:J.literal(`hash`)}),J.object({signature:eS(),type:J.literal(`transaction`)}),J.object({signature:eS(),type:J.literal(`proof`)}),J.object({hash:Qx(),senderTag:Qx(),type:J.literal(`zone`),zoneId:J.number().check(J.refine(VE,`Invalid Zone ID`))})])},request:J.pipe(J.object({machineTokenEnabled:J.optional(J.boolean()),amount:Kx(),chainId:J.optional(J.number()),currency:J.string(),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),feePayer:J.optional(J.pipe(J.union([J.boolean(),J.custom()]),J.transform(e=>typeof e==`object`||e))),memo:J.optional(J.never()),recipient:J.optional(J.string()),splits:J.optional(J.array(rD).check(J.minLength(1),J.maxLength(10))),supportedModes:J.optional(J.array(J.enum(nD)).check(J.minLength(1))),zones:J.optional(J.union([J.literal(!0),J.array(J.number().check(J.refine(VE,`Invalid Zone ID`))).check(J.minLength(1))]))}).check(J.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=_e(e,t),i=n.reduce((e,n)=>e+_e(n.amount,t),0n);return n.every(e=>_e(e.amount,t)>0n)&&i<r},`Invalid splits`)),J.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,zones:c,...l})=>({...l,amount:_e(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:_e(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),pD=IE({name:`tempo`,intent:`session`,schema:{credential:{payload:J.discriminatedUnion(`action`,[J.object({action:J.literal(`open`),authorizedSigner:J.optional(J.string()),channelId:Qx(),cumulativeAmount:Kx(),descriptor:J.optional(J.custom()),signature:eS(),transaction:eS(),type:J.literal(`transaction`)}),J.object({action:J.literal(`topUp`),additionalDeposit:Kx(),channelId:Qx(),descriptor:J.optional(J.custom()),transaction:eS(),type:J.literal(`transaction`)}),J.object({action:J.literal(`voucher`),channelId:Qx(),cumulativeAmount:Kx(),descriptor:J.optional(J.custom()),signature:eS()}),J.object({action:J.literal(`close`),channelId:Qx(),closeSignature:eS(),cumulativeAmount:Kx(),descriptor:J.optional(J.custom()),signature:eS()})])},request:J.pipe(J.object({amount:Kx(),chainId:J.optional(J.number()),channelId:J.optional(Qx()),currency:J.string(),decimals:J.number(),escrowContract:J.optional(J.string()),feePayer:J.optional(J.pipe(J.union([J.boolean(),J.custom()]),J.transform(e=>typeof e==`object`||e))),feeToken:J.optional(Zx()),minVoucherDelta:J.optional(Kx()),operator:J.optional(Zx()),recipient:J.optional(J.string()),sessionProtocol:J.optional(J.enum([zx.v2,zx.v1])),sessionSnapshot:J.optional(J.custom()),suggestedDeposit:J.optional(Kx()),unitType:J.string()}).check(J.refine(({amount:e,decimals:t})=>_e(e,t)>0n,`Session amount must be greater than 0`)),J.transform(({amount:e,chainId:t,channelId:n,decimals:r,escrowContract:i,feePayer:a,feeToken:o,minVoucherDelta:s,operator:c,sessionProtocol:l,sessionSnapshot:u,suggestedDeposit:d,...f})=>({...f,amount:_e(e,r).toString(),...d?{suggestedDeposit:_e(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:_e(s,r).toString()},...t!==void 0&&{chainId:t},...a!==void 0&&{feePayer:a},...o!==void 0&&{feeToken:o},...c!==void 0&&{operator:c},...l!==void 0&&{[Rx.sessionProtocol]:l},...u!==void 0&&{[Rx.sessionSnapshot]:u}}})))}}),mD=IE({name:`tempo`,intent:`subscription`,schema:{credential:{payload:J.object({signature:eS(),type:J.literal(`keyAuthorization`)})},request:J.pipe(J.object({amount:Kx(),accessKey:J.optional(sD),chainId:J.optional(J.number()),currency:oD,decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:J.optional(cD),periodCount:dD,periodUnit:uD,recipient:oD,subscriptionExpires:lD}).check(eD(`Subscription amount must be greater than 0`),J.refine(tD,`Subscription period exceeds uint64`)),J.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:_e(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}})}));function gD(e){return e>=0n&&e<=FD}function _D(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return gD(t)?t:void 0}function vD(e){return yD(e),e}function yD(e){if(!gD(e))throw Error(`Value ${e} is outside uint96 bounds.`)}function bD(e){return typeof e==`object`&&!!e}function xD(e){return typeof e==`string`&&ID.has(e)}function SD(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!xD(t.action))}function CD(e,t=`No session credential context available.`){if(!SD(e))throw Error(t);return e}function wD(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function TD(e){return bD(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function ED(e){return bD(e)?e.method===`tempo`&&e.intent===`session`&&e.status===`success`&&typeof e.timestamp==`string`&&typeof e.reference==`string`&&typeof e.challengeId==`string`&&typeof e.channelId==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.spent==`string`&&(e.units===void 0||typeof e.units==`number`)&&(e.txHash===void 0||typeof e.txHash==`string`):!1}function DD(e){let t=A.toString(e),n=JSON.parse(t);if(!ED(n))throw Error(`Invalid session receipt.`);return n}function OD(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function kD(e){let t=`message`,n=[];for(let r of e.split(`
230
230
  `))r.startsWith(`event: `)?t=r.slice(7).trim():r.startsWith(`data: `)?n.push(r.slice(6)):r===`data:`&&n.push(``);if(n.length===0)return null;let r=n.join(`
231
- `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=OD(r);return CD(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=OD(r);return wD(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function OD(e){try{return JSON.parse(e)}catch{return null}}function kD(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function AD(){return JSON.stringify({mpp:`payment-close-request`})}function jD(e){let t=MD(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`&&wD(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`&&CD(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&wD(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function MD(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}var ND,PD,FD,ID=I((()=>{ND=(1n<<96n)-1n,PD=new Set([`open`,`topUp`,`voucher`,`close`]),FD=`0x4d50500000000000000000000000000000000000`}));function LD(e){return WD.encode(e)}function RD(e){return WD.decode(e)}var zD,BD,VD,HD,UD,WD,GD=I((()=>{vw(),tS(),zD=J.custom(e=>typeof e==`string`&&ue(e,{strict:!1})),BD=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),VD=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),HD=J.object({authorizedSigner:zD,expiringNonceHash:BD,operator:zD,payee:zD,payer:zD,salt:BD,token:zD}),UD=J.object({acceptedCumulative:J.string(),chainId:J.number(),channelId:BD,closeRequestedAt:J.optional(J.string()),deposit:J.string(),descriptor:HD,escrow:zD,highestVoucher:J.optional(J.object({channelId:BD,cumulativeAmount:J.string(),signature:VD})),requiredCumulative:J.string(),settled:J.string(),spent:J.string(),units:J.optional(J.number())}),WD=gw(UD)}));function KD(e){return{status:`active`,...e}}function qD(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?QD(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?QD(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:XD(e.challengeId,t.snapshot),effects:[]}:QD(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?QD(e,t):{state:uO({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:ZD(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:QD(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?QD(e,t):{state:pO(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?YD({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):QD(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:QD(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?QD(e,t):{state:ZD(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}]}:QD(e,t);case`settled`:return e.status===`settling`?{state:ZD(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:QD(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:QD(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:QD(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?QD(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`?QD(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function JD(e,t){let n=qD(e.state,t);return e.state=n.state,n}function YD(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 XD(e,t){return KD({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function ZD(e,t,n,r){return KD({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function QD(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function $D(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function eO(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`);$D({cumulativeAmount:i,maxVoucherCumulative:n}),$D({cumulativeAmount:a,maxVoucherCumulative:n})}function tO(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;eO({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function nO(e,t){return typeof e==`bigint`?e:he(e,t)}function rO(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(aO(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 iO(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;$D({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 aO(e,t){$D({cumulativeAmount:e,maxVoucherCumulative:t??null})}function oO(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 sO(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function cO(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!mD(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>sO({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function lO(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=hD(r),s=hD(a.spent);return o===void 0||s===void 0||!mD(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function uO(e){return KD({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 dO(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:yO}}function fO(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=tO({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&JD(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function pO(e,t){return KD({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function mO(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=hD(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 hO(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 qD(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function gO(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 _O(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 vO(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(AD()),e.waitForCloseReady()))(),a=BigInt(i.spent);cO({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=>lO({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(kD(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}var yO,bO=I((()=>{ID(),GD(),yO={status:`idle`}}));function xO(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=ok.CLOSED,r=null}if(a.type===`open`&&(i=ok.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 SO(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function CO(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=nO(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 wO(e){let{additionalDeposit:t,channel:n,channelId:r,challengeId:i,currentState:a,knownDeposit:o,receipt:s,spent:c}=e;if(n?.channelId!==r)return;let l=o!==void 0&&o>n.deposit?o:n.deposit,u={...n,deposit:l+t};return s?{channel:u,state:pO(s,u)}:i?{channel:u,state:uO({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function TO(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=SO(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,headers:e.headers,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative,...e.signal?{signal:e.signal}:{}});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:gD(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function EO(e){return e.method===Fx.tempo&&e.intent===Ix.session}function DO(e){return EO(e)&&Nx(e.request.methodDetails,Lx.sessionProtocol)===Rx.v2}function OO(e){return Nx(e.request.methodDetails,Lx.sessionSnapshot)}function kO(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return ZC({...t,redirect:`manual`,headers:{...sT(i),...sT(t?.headers)}},_S(r),n)}function AO(e){return e instanceof Request||typeof e==`object`&&!!e&&!(e instanceof URL)&&typeof e.url==`string`&&typeof e.method==`string`&&typeof e.clone==`function`}function jO(e){try{let t=typeof location>`u`?void 0:location.href,n=AO(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function MO(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function NO(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 PO(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);if(t.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let r=await FO({challenge:e.challenge,context:{action:`topUp`,...e.autoSwap===void 0?{}:{autoSwap:e.autoSwap},channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,headers:e.headers,input:e.input,signal:e.signal}).catch(async n=>{throw n instanceof lk&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(q.paymentReceipt);return i?TD(i):void 0}async function FO(e){let t=async t=>{e.signal?.throwIfAborted();let n=await e.createSessionCredential(t,e.context);e.signal?.throwIfAborted();let r=new AbortController,i=()=>r.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,i,{once:!0});let a=setTimeout(()=>r.abort(new DOMException(`Session management request timed out; payment outcome unknown`,`TimeoutError`)),3e4),o,s=new Promise((e,t)=>{o=()=>t(r.signal.reason),r.signal.addEventListener(`abort`,o,{once:!0})});try{return await Promise.race([e.fetch(jO(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:ak(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new lk(t):t}finally{clearTimeout(a),e.signal?.removeEventListener(`abort`,i),r.signal.removeEventListener(`abort`,o)}},n=await t(e.challenge);if(n.status!==402)return n;let r=pS(n).find(DO);return r?t(r):n}async function IO(e){let t=LO({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,headers:e.init?.headers,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,signal:e.init?.signal??(e.input instanceof Request?e.input.signal:void 0)});let s=e.getChannel();if(!s?.descriptor||s.channelId!==i.channelId)return;let c=s.cumulativeAmount>a?s.cumulativeAmount:a,l=()=>e.restoreCumulative(i.channelId,o),u;try{let t=await e.createSessionCredential(r,{action:`voucher`,channelId:i.channelId,descriptor:s.descriptor,cumulativeAmountRaw:c.toString()});u=await e.fetch(e.input,kO(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(q.paymentReceipt)&&await l(),u}function LO(e){let t=pS(e.response).find(DO);if(!t)return;let n=OO(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function RO(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=AO(e.lastUrl)?e.lastUrl:void 0,i=r?{cache:r.cache,credentials:r.credentials,integrity:r.integrity,keepalive:r.keepalive,mode:r.mode===`navigate`?`same-origin`:r.mode,referrer:r.referrer,referrerPolicy:r.referrerPolicy}:void 0,a=async(a,o=!1)=>{t=a,n=(o?e.resolveSignedCloseAmount?.(a):void 0)??e.signedCloseAmount;let s=await e.createSessionCredential(a,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(r?jO(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:ak(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=pS(o).find(DO);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await NO(o),t=o.headers.get(q.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${q.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(q.paymentReceipt);if(!s)return;let c=TD(s);if(!c.txHash||!A.validate(c.txHash,{strict:!0})||A.size(c.txHash)!==32||!lO({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:0n,receipt:c}))throw Error(`Session close response included a mismatched payment receipt.`);return c}async function zO(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...sT(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!ED(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),BO(e,c,{onReceipt:r,signal:o},n,s.headers)}function BO(e,t,n,r,i){if(!ED(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return VO({onNeedVoucher:t=>KO({challenge:a,driver:r,headers:i,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*VO(e){for await(let t of HO(e))t.data!==void 0&&(yield t.data)}async function*HO(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=UO(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=DD(i.replace(/\r\n|\r/g,`
232
- `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function UO(e,t){for(let n=0;n<e.length;n++){let r=WO(e,n,t);if(!r)continue;let i=WO(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function WO(e,t,n){return e[t]===`
231
+ `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=AD(r);return TD(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=AD(r);return ED(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function AD(e){try{return JSON.parse(e)}catch{return null}}function jD(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function MD(){return JSON.stringify({mpp:`payment-close-request`})}function ND(e){let t=PD(e);return t?t.mpp===`authorization`&&typeof t.authorization==`string`?{mpp:`authorization`,authorization:t.authorization}:t.mpp===`message`&&typeof t.data==`string`?{mpp:`message`,data:t.data}:t.mpp===`payment-close-request`?{mpp:`payment-close-request`}:t.mpp===`payment-close-ready`&&ED(t.data)?{mpp:`payment-close-ready`,data:t.data}:t.mpp===`payment-error`&&typeof t.status==`number`&&typeof t.message==`string`?{mpp:`payment-error`,status:t.status,message:t.message}:t.mpp===`payment-need-voucher`&&TD(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&ED(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function PD(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}var FD,ID,LD,RD=F((()=>{FD=(1n<<96n)-1n,ID=new Set([`open`,`topUp`,`voucher`,`close`]),LD=`0x4d50500000000000000000000000000000000000`}));function zD(e){return KD.encode(e)}function BD(e){return KD.decode(e)}var VD,HD,UD,WD,GD,KD,qD=F((()=>{yw(),nS(),VD=J.custom(e=>typeof e==`string`&&fe(e,{strict:!1})),HD=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),UD=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),WD=J.object({authorizedSigner:VD,expiringNonceHash:HD,operator:VD,payee:VD,payer:VD,salt:HD,token:VD}),GD=J.object({acceptedCumulative:J.string(),chainId:J.number(),channelId:HD,closeRequestedAt:J.optional(J.string()),deposit:J.string(),descriptor:WD,escrow:VD,highestVoucher:J.optional(J.object({channelId:HD,cumulativeAmount:J.string(),signature:UD})),requiredCumulative:J.string(),settled:J.string(),spent:J.string(),units:J.optional(J.number())}),KD=_w(GD)}));function JD(e){return{status:`active`,...e}}function YD(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?eO(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?eO(e,t):t.snapshot?{state:{status:`hydrating`,challengeId:t.challengeId,snapshot:t.snapshot},effects:[{type:`hydrate`,snapshot:t.snapshot}]}:{state:{status:`opening`,challengeId:t.challengeId},effects:[{type:`open`}]};case`hydrated`:return e.status===`hydrating`?{state:QD(e.challengeId,t.snapshot),effects:[]}:eO(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?eO(e,t):{state:fO({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:$D(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:eO(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?eO(e,t):{state:hO(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?ZD({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):eO(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:eO(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?eO(e,t):{state:$D(e.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]};case`settleStarted`:return e.status===`active`?{state:{status:`settling`,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[{type:`settle`,channelId:e.channelId}]}:eO(e,t);case`settled`:return e.status===`settling`?{state:$D(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:eO(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:eO(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:eO(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?eO(e,t):{state:{status:`closing`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`close`,channelId:e.channelId}]};case`closed`:return e.status!==`closing`&&e.status!==`withdrawable`?eO(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function XD(e,t){let n=YD(e.state,t);return e.state=n.state,n}function ZD(e){let{challengeId:t,descriptor:n,event:r}=e,i=BigInt(r.requiredCumulative),a=BigInt(r.deposit);return i>a?{state:{status:`toppingUp`,challengeId:t,channelId:r.channelId,descriptor:n,deposit:r.deposit},effects:[{type:`topUp`,channelId:r.channelId,amount:(i-a).toString()}]}:{state:{status:`voucherNeeded`,challengeId:t,channelId:r.channelId,descriptor:n,requiredCumulative:r.requiredCumulative,deposit:r.deposit},effects:[{type:`voucher`}]}}function QD(e,t){return JD({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function $D(e,t,n,r){return JD({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function eO(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function tO(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function nO(e){let{channel:t,maxVoucherCumulative:n,receipt:r}=e;if(!t||r.channelId!==t.channelId)return;let i=BigInt(r.acceptedCumulative),a=BigInt(r.spent);if(a>i)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(i>t.cumulativeAmount)throw Error(`receipt accepted cumulative exceeds local voucher state`);if(a>t.cumulativeAmount)throw Error(`receipt spent exceeds local voucher state`);tO({cumulativeAmount:i,maxVoucherCumulative:n}),tO({cumulativeAmount:a,maxVoucherCumulative:n})}function rO(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;nO({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function iO(e,t){return typeof e==`bigint`?e:_e(e,t)}function aO(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(sO(r,n),t!==void 0){let e=BigInt(t);if(e<r)throw Error(`opening deposit ${e} below request amount ${r}`);return e}let a=i===void 0?void 0:BigInt(i),o=a!==void 0&&a>r?a:r;return n===void 0||o<n?o:n}function oO(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;tO({cumulativeAmount:r,maxVoucherCumulative:n??null});let o=r-t,s=a??i??o,c=s>o?s:o;if(n==null)return c;let l=n-t;return c<l?c:l}function sO(e,t){tO({cumulativeAmount:e,maxVoucherCumulative:t??null})}function cO(e){let{channel:t,currentSocket:n,lastChallenge:r}=e;if(!t?.opened)return;let i=n?.challenge??r,a=n?.channelId??t.channelId;if(!i)throw Error(`Cannot close session: no challenge available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or make a request first to receive a fresh 402 challenge.`);if(!a)throw Error(`Cannot close session: no channel ID available. The session may not have been fully opened.`);return{challenge:i,channel:t,channelId:a}}function lO(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function uO(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!gD(n))throw Error(`close-ready spent is not a uint96 amount`);if(n<r)throw Error(`close-ready spent is below locally confirmed spend`);if(n>lO({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function dO(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=_D(r),s=_D(a.spent);return o===void 0||s===void 0||!gD(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function fO(e){return JD({challengeId:e.challengeId,channelId:e.entry.channelId,descriptor:e.entry.descriptor,acceptedCumulative:e.entry.cumulativeAmount.toString(),deposit:e.entry.deposit.toString(),spent:e.spent,units:e.units})}function pO(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:xO}}function mO(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=rO({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&XD(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function hO(e,t){return JD({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function gO(e){let{challengeId:t,channelId:n,closeReadyReceipt:r,cumulativeAmount:i,deliveredChunks:a=0n,socketChallengeId:o,socketChannelId:s,spent:c,tickCost:l=0n}=e;if(c>i)throw Error(`locally confirmed spend exceeds local voucher state`);if(r&&r.challengeId===t&&r.channelId===n){let e=_D(r.spent);if(e===void 0)throw Error(`close-ready spent is not a uint96 amount`);return e>c?e:c}if(o===t&&s===n&&l>0n){let e=a*l,t=c>e?c:e;return t>i?i:t}return i}function _O(e){let{channel:t,channelId:n,challengeId:r,cumulativeAmount:i,spent:a,state:o}=e;if(!(!t||t.channelId!==n)&&(t.cumulativeAmount=i,r))return YD(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function vO(e){return{channel:e.channel===null?null:{entry:e.channel,cumulativeAmount:e.channel.cumulativeAmount,deposit:e.channel.deposit,opened:e.channel.opened},spent:e.spent,state:e.state}}function yO(e,t){return e.channel?(e.channel.entry.cumulativeAmount=e.channel.cumulativeAmount,e.channel.entry.deposit=e.channel.deposit,e.channel.entry.opened=e.channel.opened,{channel:e.channel.entry,spent:e.spent,state:e.state}):(t&&(t.opened=!1),{channel:null,spent:e.spent,state:e.state})}async function bO(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(MD()),e.waitForCloseReady()))(),a=BigInt(i.spent);uO({cumulativeAmount:r.channel.cumulativeAmount,readySpent:a,spent:e.spent});let o=await e.createSessionCredential(r.challenge,{action:`close`,channelId:r.channelId,descriptor:r.channel.descriptor,cumulativeAmountRaw:a.toString()}),s=a.toString();n.expectedCloseAmount=s;try{let i=e.waitForReceipt(e=>dO({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(jD(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}var xO,SO=F((()=>{RD(),qD(),xO={status:`idle`}}));function CO(e){let t=new Map,n=!1,r=[],i=e.readyState,a=(e,n,i)=>{let a=t.get(e);if(a||(a=new Set,t.set(e,a)),a.add({once:typeof i==`object`&&i.once===!0,value:n}),e===`message`&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},o=(e,n)=>{let r=t.get(e);if(r)for(let e of r)e.value===n&&r.delete(e)};function s(e,a){if(a.type===`close`){if(n)return;n=!0,i=ck.CLOSED,r=null}if(a.type===`open`&&(i=ck.OPEN),a.type===`message`&&r){r.push(a);return}switch(a.type){case`close`:l.onclose?.(a);break;case`error`:l.onerror?.(a);break;case`message`:l.onmessage?.(a);break;case`open`:l.onopen?.(a)}let o=t.get(e);if(o)for(let e of Array.from(o))typeof e.value==`function`?e.value(a):e.value.handleEvent(a),e.once&&o.delete(e)}let c=null,l={addEventListener:a,close(t,n){e.close(t,n)},get bufferedAmount(){return e.bufferedAmount},get extensions(){return e.extensions},on(e,t){a(e,t)},onclose:null,onerror:null,get onmessage(){return c},set onmessage(e){if(c=e,e&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},onopen:null,off(e,t){o(e,t)},get protocol(){return e.protocol},get readyState(){return i},removeEventListener:o,send(t){e.send(t)},get url(){return e.url}};return{emit:s,socket:l}}function wO(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function TO(e){let{amount:t,assertVoucherWithinLocalLimit:n,channel:r,decimals:i,lastChallenge:a,lastUrl:o}=e;if(!r?.opened)throw Error(`Cannot top up session: no open channel.`);if(!a)throw Error(`Cannot top up session: no challenge available. Make a request first.`);if(!o)throw Error(`Cannot top up session: no URL available. Call fetch(), sse(), or ws() first.`);let s=iO(t,i);if(s<=0n)throw Error(`Top-up amount must be greater than zero.`);return n(r.cumulativeAmount+s),{additionalDeposit:s,challenge:a,channelId:r.channelId,input:o}}function EO(e){let{additionalDeposit:t,channel:n,channelId:r,challengeId:i,currentState:a,knownDeposit:o,receipt:s,spent:c}=e;if(n?.channelId!==r)return;let l=o!==void 0&&o>n.deposit?o:n.deposit,u={...n,deposit:l+t};return s?{channel:u,state:hO(s,u)}:i?{channel:u,state:fO({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function DO(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=wO(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,headers:e.headers,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative,...e.signal?{signal:e.signal}:{}});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:vD(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function OO(e){return e.method===Ix.tempo&&e.intent===Lx.session}function kO(e){return OO(e)&&Px(e.request.methodDetails,Rx.sessionProtocol)===zx.v2}function AO(e){return Px(e.request.methodDetails,Rx.sessionSnapshot)}function jO(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return QC({...t,redirect:`manual`,headers:{...cT(i),...cT(t?.headers)}},vS(r),n)}function MO(e){return e instanceof Request||typeof e==`object`&&!!e&&!(e instanceof URL)&&typeof e.url==`string`&&typeof e.method==`string`&&typeof e.clone==`function`}function NO(e){try{let t=typeof location>`u`?void 0:location.href,n=MO(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function PO(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function FO(e){let t=await e.text().catch(()=>``);if(!t)return``;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return t;try{return JSON.parse(t).detail??t}catch{return t}}async function IO(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);if(t.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let r=await LO({challenge:e.challenge,context:{action:`topUp`,...e.autoSwap===void 0?{}:{autoSwap:e.autoSwap},channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,headers:e.headers,input:e.input,signal:e.signal}).catch(async n=>{throw n instanceof dk&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(q.paymentReceipt);return i?DD(i):void 0}async function LO(e){let t=async t=>{e.signal?.throwIfAborted();let n=await e.createSessionCredential(t,e.context);e.signal?.throwIfAborted();let r=new AbortController,i=()=>r.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,i,{once:!0});let a=setTimeout(()=>r.abort(new DOMException(`Session management request timed out; payment outcome unknown`,`TimeoutError`)),3e4),o,s=new Promise((e,t)=>{o=()=>t(r.signal.reason),r.signal.addEventListener(`abort`,o,{once:!0})});try{return await Promise.race([e.fetch(NO(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:sk(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new dk(t):t}finally{clearTimeout(a),e.signal?.removeEventListener(`abort`,i),r.signal.removeEventListener(`abort`,o)}},n=await t(e.challenge);if(n.status!==402)return n;let r=mS(n).find(kO);return r?t(r):n}async function RO(e){let t=zO({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,headers:e.init?.headers,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,signal:e.init?.signal??(e.input instanceof Request?e.input.signal:void 0)});let s=e.getChannel();if(!s?.descriptor||s.channelId!==i.channelId)return;let c=s.cumulativeAmount>a?s.cumulativeAmount:a,l=()=>e.restoreCumulative(i.channelId,o),u;try{let t=await e.createSessionCredential(r,{action:`voucher`,channelId:i.channelId,descriptor:s.descriptor,cumulativeAmountRaw:c.toString()});u=await e.fetch(e.input,jO(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(q.paymentReceipt)&&await l(),u}function zO(e){let t=mS(e.response).find(kO);if(!t)return;let n=AO(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function BO(e){if(!e.lastUrl)throw Error(`Cannot close session: no URL available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or call fetch()/sse() before close().`);let t=e.target.challenge,n=e.signedCloseAmount,r=MO(e.lastUrl)?e.lastUrl:void 0,i=r?{cache:r.cache,credentials:r.credentials,integrity:r.integrity,keepalive:r.keepalive,mode:r.mode===`navigate`?`same-origin`:r.mode,referrer:r.referrer,referrerPolicy:r.referrerPolicy}:void 0,a=async(a,o=!1)=>{t=a,n=(o?e.resolveSignedCloseAmount?.(a):void 0)??e.signedCloseAmount;let s=await e.createSessionCredential(a,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(r?NO(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:sk(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=mS(o).find(kO);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await FO(o),t=o.headers.get(q.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${q.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(q.paymentReceipt);if(!s)return;let c=DD(s);if(!c.txHash||!j.validate(c.txHash,{strict:!0})||j.size(c.txHash)!==32||!dO({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:0n,receipt:c}))throw Error(`Session close response included a mismatched payment receipt.`);return c}async function VO(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...cT(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!OD(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),HO(e,c,{onReceipt:r,signal:o},n,s.headers)}function HO(e,t,n,r,i){if(!OD(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return UO({onNeedVoucher:t=>JO({challenge:a,driver:r,headers:i,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*UO(e){for await(let t of WO(e))t.data!==void 0&&(yield t.data)}async function*WO(e){if(!e.response.body)throw Error(`Response has no body.`);let t=e.response.body.getReader(),n=new TextDecoder,r=``,i=!1,a=()=>{t.cancel(e.signal?.reason).catch(()=>void 0)};e.signal?.addEventListener(`abort`,a,{once:!0}),e.signal?.aborted&&a();try{for(;!e.signal?.aborted;){let{done:a,value:o}=await t.read();for(a?(i=!0,r+=n.decode()):r+=n.decode(o,{stream:!0});;){let t=GO(r,a);if(!t)break;let n=t.index+t.length,i=r.slice(0,t.index),o=r.slice(0,n);if(r=r.slice(n),!i.trim())continue;let s=kD(i.replace(/\r\n|\r/g,`
232
+ `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function GO(e,t){for(let n=0;n<e.length;n++){let r=KO(e,n,t);if(!r)continue;let i=KO(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function KO(e,t,n){return e[t]===`
233
233
  `?1:e[t]===`\r`?e[t+1]===`
234
- `?2:t+1===e.length&&!n?0:1:0}function GO(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=HO({...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 KO(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await TO({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,headers:e.headers,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await FO({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,headers:e.headers,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function qO(e){let t=new URL(e.input.toString()),n=MO(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=pS(r).find(DO);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 JO(e){e.signal?.throwIfAborted();let t=await qO(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function YO(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:jS(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:SD(t)}}function XO(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function ZO(e){if(!XO(e))return`received mismatched payment-close-ready frame`;let t=hD(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 QO(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!XO(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!lO({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function $O(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=YO({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=xO(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===ok.CONNECTING||s.readyState===ok.OPEN)&&s.close(sk,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 tk({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await ek(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(kD(n)),await e.waitForReceipt(),l.socket}function ek(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 tk(e){let t=jD(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`:nk(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 rk(e,t.data);return;case`payment-receipt`:ik(e,t.data);return}}function nk(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=ZO({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 rk(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+ck&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await TO({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(kD(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function ik(e,t){let n=QO({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}function ak(e,t,n,r){let i=_S(e),a=new Headers;if(i.toLowerCase()!==q.authorization.toLowerCase()){let e=new Headers(r).get(q.authorization)??(n instanceof Request?n.headers.get(q.authorization):null);e&&!e.startsWith(`${Px.payment} `)&&a.set(q.authorization,e)}return a.set(i,t),a}var ok,sk,ck,lk,uk=I((()=>{SS(),QT(),$C(),zx(),BS(),ID(),bO(),ok={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},sk=3008,ck=5e3,lk=class extends Error{constructor(e){let t=e instanceof Error||e instanceof DOMException?e.message:String(e);super(`${t}; payment outcome unknown`),this.name=`UncertainFundingError`}}})),dk,fk,pk,mk,hk,gk=I((()=>{dk={mainnet:4217,testnet:42431},fk={ousd:Ke(dk.mainnet).address,usdc:ce(Je(dk.mainnet).address),pathUsd:qe(dk.mainnet).address},pk={[dk.mainnet]:fk.usdc,[dk.testnet]:fk.pathUsd},mk=Object.freeze({[dk.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[dk.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})}),dk.mainnet,dk.testnet,hk={[dk.mainnet]:`https://rpc.tempo.xyz`,[dk.testnet]:`https://rpc.moderato.tempo.xyz`}})),_k=tt({chainName:()=>Pk,confirm:()=>kk,decodeMemo:()=>xk,fetchBalanceLines:()=>Rk,fetchTokenInfo:()=>Lk,fmtBalance:()=>Ak,fmtChallengeValue:()=>Sk,fmtProblemValue:()=>Ck,fmtRequestValue:()=>bk,isAgentEnvironment:()=>Ek,isTempoAccount:()=>Dk,isTestnet:()=>Ik,link:()=>wk,mainnetTokens:()=>Uk,networkRpcUrls:()=>Bk,parseMethodOpts:()=>Tk,pathUsd:()=>Vk,pc:()=>X,printRequestHeaders:()=>vk,printResponseHeaders:()=>yk,prompt:()=>Ok,resolveChain:()=>Nk,resolveFundingNetwork:()=>Mk,resolveRpcUrl:()=>jk,testnetTokens:()=>Wk,usdc:()=>Hk});function vk(e,t,n){let{pathname:r,host:i}=new URL(e);n(`> ${(t.method??`GET`).toUpperCase()} ${r} HTTP/1.1\n`),n(`> Host: ${i}\n`);for(let[e,r]of Object.entries(t.headers??{}))n(`> ${e}: ${r}\n`);n(`>
235
- `)}function yk(e,t){if(!t.include&&t.verbose<2||t.silent)return;let n=`HTTP/1.1 ${e.status} ${e.statusText}`,r=t.verbose>=2?process.stderr:process.stdout,i=t.verbose>=2?`< `:``;r.write(`${i}${n}\n`);for(let[t,n]of e.headers)r.write(`${i}${t}: ${n}\n`);r.write(t.verbose>=2?`<
234
+ `?2:t+1===e.length&&!n?0:1:0}function qO(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=WO({...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 JO(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await DO({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,headers:e.headers,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await LO({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,headers:e.headers,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function YO(e){let t=new URL(e.input.toString()),n=PO(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=mS(r).find(kO);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 XO(e){e.signal?.throwIfAborted();let t=await YO(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function ZO(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:MS(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:wD(t)}}function QO(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function $O(e){if(!QO(e))return`received mismatched payment-close-ready frame`;let t=_D(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 ek(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!QO(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!dO({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function tk(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=ZO({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=CO(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===ck.CONNECTING||s.readyState===ck.OPEN)&&s.close(lk,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 rk({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await nk(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(jD(n)),await e.waitForReceipt(),l.socket}function nk(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 rk(e){let t=ND(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`:ik(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 ak(e,t.data);return;case`payment-receipt`:ok(e,t.data);return}}function ik(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=$O({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 ak(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+uk&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await DO({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(jD(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function ok(e,t){let n=ek({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}function sk(e,t,n,r){let i=vS(e),a=new Headers;if(i.toLowerCase()!==q.authorization.toLowerCase()){let e=new Headers(r).get(q.authorization)??(n instanceof Request?n.headers.get(q.authorization):null);e&&!e.startsWith(`${Fx.payment} `)&&a.set(q.authorization,e)}return a.set(i,t),a}var ck,lk,uk,dk,fk=F((()=>{CS(),$T(),ew(),Bx(),VS(),RD(),SO(),ck={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},lk=3008,uk=5e3,dk=class extends Error{constructor(e){let t=e instanceof Error||e instanceof DOMException?e.message:String(e);super(`${t}; payment outcome unknown`),this.name=`UncertainFundingError`}}})),pk,mk,hk,gk,_k,vk=F((()=>{pk={mainnet:4217,testnet:42431},mk={ousd:Je(pk.mainnet).address,usdc:le(Xe(pk.mainnet).address),pathUsd:Ye(pk.mainnet).address},hk={[pk.mainnet]:mk.usdc,[pk.testnet]:mk.pathUsd},gk=Object.freeze({[pk.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[pk.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})}),pk.mainnet,pk.testnet,_k={[pk.mainnet]:`https://rpc.tempo.xyz`,[pk.testnet]:`https://rpc.moderato.tempo.xyz`}})),yk=rt({chainName:()=>Ik,confirm:()=>jk,decodeMemo:()=>Ck,fetchBalanceLines:()=>Bk,fetchTokenInfo:()=>zk,fmtBalance:()=>Mk,fmtChallengeValue:()=>wk,fmtProblemValue:()=>Tk,fmtRequestValue:()=>Sk,isAgentEnvironment:()=>Ok,isTempoAccount:()=>kk,isTestnet:()=>Rk,link:()=>Ek,mainnetTokens:()=>Gk,networkRpcUrls:()=>Hk,parseMethodOpts:()=>Dk,pathUsd:()=>Uk,pc:()=>X,printRequestHeaders:()=>bk,printResponseHeaders:()=>xk,prompt:()=>Ak,resolveChain:()=>Fk,resolveFundingNetwork:()=>Pk,resolveRpcUrl:()=>Nk,testnetTokens:()=>Kk,usdc:()=>Wk});function bk(e,t,n){let{pathname:r,host:i}=new URL(e);n(`> ${(t.method??`GET`).toUpperCase()} ${r} HTTP/1.1\n`),n(`> Host: ${i}\n`);for(let[e,r]of Object.entries(t.headers??{}))n(`> ${e}: ${r}\n`);n(`>
235
+ `)}function xk(e,t){if(!t.include&&t.verbose<2||t.silent)return;let n=`HTTP/1.1 ${e.status} ${e.statusText}`,r=t.verbose>=2?process.stderr:process.stdout,i=t.verbose>=2?`< `:``;r.write(`${i}${n}\n`);for(let[t,n]of e.headers)r.write(`${i}${t}: ${n}\n`);r.write(t.verbose>=2?`<
236
236
  `:`
237
- `)}function bk(e,t,n){if(zk.has(e)&&typeof t==`string`)return`${t} ${X.dim(`(${Ak(BigInt(t),n.tokenSymbol,n.tokenDecimals)})`)}`;if(e===`chainId`&&typeof t==`number`){let e=Pk({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?wk(`${n.explorerUrl}/address/${t}`,t):t:typeof t==`string`&&/^https?:\/\//.test(t)?X.link(t,t):String(t)}function xk(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 Sk(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 Ck(e){return typeof e==`object`&&e?JSON.stringify(e):String(e)}function wk(e,t){return X.link(e,t)}function Tk(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 Ek(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 Dk(e){return e.startsWith(`tempo:`)}function Ok(e){let t=Ge.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 kk(e,t=!1){let n=Ge.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 Ak(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 jk(e,t={}){return e??(t.network?Bk[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}function Mk(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 Nk(e={}){let t=jk(e.rpcUrl,{network:e.network});if(!t)return be;let{getChainId:n}=await import(`viem/actions`),r=await n(M({transport:P(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 Pk(e){return{[be.id]:`mainnet`,[F.id]:`testnet`}[e.id]??e.name}function Fk(e){return typeof e==`bigint`?e:e.amount}function Ik(e){return e.id!==be.id}async function Lk(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(Fk).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 Rk(e,t){if(t?.chain){let n=M({chain:t.chain,transport:P(t.rpcUrl)}),r=t.chain.blockExplorers?.default?.url,i=X.dim(`(${Pk(t.chain)})`);return Ik(t.chain)?(await Promise.all(Wk.map(t=>Lk(n,t,e)))).filter(e=>e.balance>0n).map(e=>`${Ak(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`):(await Promise.all(Uk.map(t=>Lk(n,t,e)))).map(e=>`${Ak(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`)}let n=M({chain:be,transport:P(jk())}),r=be.blockExplorers?.default?.url,i=(await Promise.all(Uk.map(t=>Lk(n,t,e)))).map(e=>Ak(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token}));if(t?.includeTestnet!==!1){let t=M({chain:F,transport:P()}),n=F.blockExplorers?.default?.url,r=await Promise.all(Wk.map(n=>Lk(t,n,e)));for(let e of r)e.balance>0n&&i.push(`${Ak(e.balance,e.symbol,e.decimals,{explorerUrl:n,token:e.token})} ${X.dim(`(testnet)`)}`)}return i}var X,zk,Bk,Vk,Hk,Uk,Wk,Gk=I((()=>{gk(),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}}})(),zk=new Set([`amount`,`suggestedDeposit`,`minVoucherDelta`]),Bk={mainnet:hk[dk.mainnet],testnet:hk[dk.testnet]},Vk=`0x20c0000000000000000000000000000000000000`,Hk=`0x20C000000000000000000000b9537d11c60E8b50`,Uk=[Vk,Hk],Wk=[`0x20c0000000000000000000000000000000000000`,`0x20c0000000000000000000000000000000000001`,`0x20c0000000000000000000000000000000000002`,`0x20c0000000000000000000000000000000000003`]}));function Kk(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:iA}function qk(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function Jk(e){return new L({code:`KEYCHAIN_UNAVAILABLE`,message:`Linux keyring requires secret-tool. Install libsecret-tools.`,hint:`On Debian/Ubuntu, run: sudo apt install libsecret-tools gnome-keyring dbus-x11`,exitCode:69,cause:e})}function Yk(e){if(e&&qk(e,`secret-tool`))throw Jk(e)}function Xk(e,t){return new Promise(n=>{m.execFile(e,t,{timeout:Kk()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function Zk(){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 Qk(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:Zk().get())}function $k(e=`main`){let t=rA;return{async list(){let e=b.platform();if(e===`darwin`){let{stdout:e,error:n}=await Xk(`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 Xk(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(Yk(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 Xk(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await Xk(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return Yk(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=b.platform();if(r===`darwin`){await Xk(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await Xk(`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(),Kk());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(qk(e,`secret-tool`)?Jk(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=b.platform();if(n===`darwin`){await Xk(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await Xk(`secret-tool`,[`clear`,`service`,t,`account`,e]);Yk(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function eA(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=Qk(e),i=await $k(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function tA(e){let t=Qk(e);if(!process.env.MPPX_PRIVATE_KEY?.trim()&&Dk(t))throw new L({code:`UNSUPPORTED_ACCOUNT`,message:`Persistent sessions require an mppx account or MPPX_PRIVATE_KEY.`,exitCode:2});return eA(e).catch(e=>{throw new L({code:`ACCOUNT_NOT_FOUND`,message:e instanceof Error?e.message:`No account found.`,exitCode:69,...e instanceof Error&&{cause:e}})})}async function nA(e){return(await eA(e)).account}var rA,iA,aA=I((()=>{Gk(),rA=`mppx`,iA=1e4}));uk(),aA();const oA=[[`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 sA(e=process.env){return oA.find(([t])=>e[t])?.[1]}function cA(e){let{_mppx_nonce:t,_mppx_identity:n,...r}=e??{};return Object.keys(r).length?r:void 0}const lA=Symbol(`mppx.x402.asset`);function uA(e){return{[lA]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function dA(e,t){let n=e(t.chainId);return uA({address:n.address,decimals:n.decimals,network:xA(t.chainId),transfer:CA(t.transfer,n)})}const fA={USDC:uA({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},pA={USDC:uA({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},mA={USDC:uA({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:uA({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},hA={USDC:uA({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function gA(e){return typeof e!=`object`||!e?!1:e[lA]===!0}function _A(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function vA(e){return typeof e==`string`}function yA(e,t){if(gA(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(_A(e)){let n=e.addresses[SA(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function bA(e,t,n){let r=yA(e,n);return r?ce(r.address)===ce(t):!1}function xA(e){return`eip155:${e}`}function SA(e){return Number(e.slice(7))}function CA(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 wA=tt({base:()=>fA,baseSepolia:()=>pA,celo:()=>mA,celoSepolia:()=>hA,define:()=>uA,fromToken:()=>dA,isAsset:()=>gA,isRawAddress:()=>vA,isToken:()=>_A,matches:()=>bA,resolve:()=>yA,toChainId:()=>SA,toNetwork:()=>xA}),TA=tt({base:()=>EA,baseSepolia:()=>DA,celo:()=>OA,celoSepolia:()=>kA});const EA=8453,DA=84532,OA=42220,kA=11142220;Ux();function AA(e){let t=[Hx(e.accepted),Hx(e.resource),Hx(e.extensions)].join(`|`);return ne.sha256(k.fromString(t),{as:`Hex`})}Ew(),XC();async function jA(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=DC(n);if(FA(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?LA(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} signing is not implemented yet.`);let o=r.extra?.name,s=r.extra?.version;if(typeof o!=`string`||typeof s!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let c=Math.floor(Date.now()/1e3),l={from:ce(t.address),nonce:i?.mppx?AA({accepted:r,extensions:i,resource:n.resource}):zA(),to:ce(r.payTo),validAfter:(c-600).toString(),validBefore:(c+r.maxTimeoutSeconds).toString(),value:r.amount},u=await t.signTypedData({domain:{chainId:PA(r.network),name:o,verifyingContract:ce(r.asset),version:s},message:{...l,value:BigInt(l.value),validAfter:BigInt(l.validAfter),validBefore:BigInt(l.validBefore)},primaryType:`TransferWithAuthorization`,types:NA});return ww({accepted:r,...i?{extensions:i}:{},payload:{authorization:l,signature:u},...n.resource?{resource:n.resource}:{},x402Version:2})}function MA(e){let t=e.challenge.request,n;try{n=DC(t),FA(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 NA={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 PA(e){return Number(e.slice(AC.length))}function FA(e,t){let n=PA(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=>vA(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=ce(t.asset);if(!r.some(n=>bA(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=IA(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>he(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function IA(e,t){let n=e.currencies??e.assets,r=ce(t.asset),i=n?.find(e=>bA(e,r,t.network)),a=i?yA(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function LA(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:RA()}}}:e}function RA(){return BA().slice(2)}function zA(){return BA()}function BA(){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(``)}`}tS();const VA=[`authorization`],HA=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 UA=J.object({chainId:J.number(),credentialTypes:J.optional(J.array(J.enum(VA)).check(J.minLength(1))),decimals:J.optional(J.number()),permit2Address:J.optional(Xx()),splits:J.optional(J.array(J.object({amount:HA,recipient:Xx()})))});J.object({amount:HA,currency:Xx(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:UA,recipient:Xx()});const WA=J.object({amount:Gx(),chainId:J.number(),currency:Xx(),credentialTypes:J.optional(J.array(J.enum(VA)).check(J.minLength(1))),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),permit2Address:J.optional(Xx()),recipient:Xx(),splits:J.optional(J.array(J.object({amount:HA,recipient:Xx()})))}),GA=J.object({from:Xx(),nonce:Zx(),signature:$x(),to:Xx(),type:J.literal(`authorization`),validAfter:HA,validBefore:HA,value:HA}),KA={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 qA(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function JA(e){return ne.keccak256(k.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function YA(e){return`eip155:${e}`}function XA(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}IE(),tS();const ZA=PE({name:`evm`,intent:`charge`,schema:{credential:{payload:GA},request:J.pipe(WA,J.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...c})=>({...c,amount:he(e,i).toString(),currency:ce(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:ce(a)}:{},...s?{splits:s}:{}},recipient:ce(o)})))}});BS(),IE(),eC(),tS();function QA(e){return FE(ZA,{canHandleChallenge({challenge:t}){return!$A(t)||MA({challenge:t,config:e})},context:J.object({account:J.optional(J.custom())}),async createCredential({challenge:t,context:n}){if($A(t))return jA({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(ej(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=tj(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return FS(PS({challenge:t,payload:{from:ce(r.address),nonce:JA(t),signature:await r.signTypedData({domain:qA({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:ce(r.address),nonce:JA(t),to:ce(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:KA}),to:ce(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:XA({address:ce(r.address),chainId:i.methodDetails.chainId})}))}})}function $A(e){return QS(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function ej(e,t){let n=t.methodDetails.chainId,r=YA(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=>vA(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=ce(t.currency);if(!i.some(t=>bA(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=nj(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>he(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function tj(e,t){let n=e.currencies??e.assets,r=ce(t.currency),i=YA(t.methodDetails.chainId),a=n?.find(e=>bA(e,r,i)),o=a?yA(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 nj(e,t){let n=e.currencies??e.assets,r=ce(t.currency),i=YA(t.methodDetails.chainId),a=n?.find(e=>bA(e,r,i)),o=a?yA(a,i):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function rj(e){return[rj.charge(e)]}(function(e){e.charge=QA,e.assets=wA,e.chains=TA})(rj||={});function ij(e){return e}var aj=I((()=>{}));eC(),aj();function oj(){return ij({method:`evm`,supports:e=>e.method===`evm`&&!QS(e),async setup({challenge:e,options:t}){let n=e.request,r=n.methodDetails,i=r?.chainId,a=i?sj(i):void 0,o=n.currency,s=await nA(t.account),c=[...Object.values(fA),...Object.values(pA),...Object.values(mA),...Object.values(hA)],l=o??``;if(a&&o)try{let e=M({chain:a,transport:P()}),t=await Ee(e,{address:o,abi:oe,functionName:`symbol`});t&&(l=t)}catch{}return{tokenSymbol:l,tokenDecimals:r?.decimals??6,explorerUrl:a?.blockExplorers?.default?.url,methods:[...rj({account:s,currencies:c})]}}})}function sj(e){return Object.values(Ye).find(t=>t.id===e)}function cj(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}tS();const lj=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)))}),uj=J.custom(e=>typeof e==`function`),dj=J.union([lj,uj]);IE(),tS();const fj=PE({name:`stripe`,intent:`charge`,schema:{credential:{payload:J.object({externalId:J.optional(J.string()),spt:J.string()})},request:J.pipe(J.object({amount:Gx(),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(dj),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:cj(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});BS(),IE(),tS();function pj(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return FE(fj,{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 FS({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function mj(e){return[pj(e)]}(function(e){e.charge=pj})(mj||={}),Mx(),Gk(),aj();function hj(){return ij({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=_j(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 L({code:`MISSING_ENV`,message:`MPPX_STRIPE_SECRET_KEY environment variable is required for Stripe payments.`,exitCode:2});return{tokenSymbol:r?.toUpperCase()??``,tokenDecimals:n.decimals??2,methods:[mj.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=gj(a),l=process.env.MPPX_STRIPE_SPT_URL?process.env.MPPX_STRIPE_SPT_URL:c?`https://api.stripe.com/v1/test_helpers/shared_payment/granted_tokens`:`https://api.stripe.com/v1/shared_payment/issued_tokens`;if(r){let e=c?`seller_details[network_id]`:`seller_details[network_business_profile]`;s.set(e,r)}if(o)for(let[e,t]of Object.entries(o))s.set(`metadata[${e}]`,t);let u={Authorization:`Basic ${btoa(`${a}:`)}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":`2026-07-29.preview`},d=await globalThis.fetch(l,{method:`POST`,headers:u,body:s});if(!d.ok){let a=await d.json();if(c&&(o||r)&&a.error.message.includes(`Received unknown parameter`)){let r=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()});if(d=await globalThis.fetch(l,{method:`POST`,headers:u,body:r}),!d.ok){let e=await d.json();throw new L({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${e.error.message}`,exitCode:77})}}else throw new L({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${a.error.message}`,exitCode:77})}let{id:f}=await d.json();return f}})]}},formatReceiptField(e,t){if(e===`reference`&&typeof t==`string`&&t.startsWith(`pi_`)){let e=process.env.MPPX_STRIPE_SECRET_KEY,n=`https://dashboard.stripe.com${e!==void 0&&gj(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function gj(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function _j(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 vj(e={}){let{account:t}=e;return(e,{account:n}={})=>{let r=n??t;if(!r){if(!e.account)throw Error("No `account` provided. Pass `account` to parameters or context.");return e.account}return ve(r)}}var yj=I((()=>{}));function bj(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}var xj=I((()=>{}));function Sj(e,t={}){return P(e.url,{fetchFn:e.fetch,fetchOptions:{headers:bj(e)},...t})}function Cj(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(ie({request:t=>e(t)},{retryCount:0}),Sj(r,{retryCount:i.transport.retryCount}))({account:i.account,chain:i.chain,pollingInterval:i.pollingInterval,retryCount:0}),n=re({...t.config,retryCount:0},t.value);a=Object.assign({},i,{request:n.request,transport:{...n.config,...n.value}})}return!t?.serializers||a.chain?.serializers?.transaction?a:Object.assign({},a,{chain:{...t,...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(P(a),Sj(r)):P(a);return M({chain:Ej[n]??{...t,id:n},transport:o})}}function wj(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 Tj(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}var Ej,Dj=I((()=>{xj(),Ej={[be.id]:be,[F.id]:F}}));function Oj(e){let t=ne.keccak256(k.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,10))}function kj(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(A.toBytes(jj),0),i[4]=Mj,i.set(Oj(t),5),n&&i.set(Oj(n),15),i.set(Aj(r),25),A.fromBytes(i)}function Aj(e){let t=ne.keccak256(k.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,7))}var jj,Mj,Nj=I((()=>{jj=A.slice(ne.keccak256(k.fromString(`mpp`),{as:`Hex`}),0,4),Mj=1}));async function Pj(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t;if(!Number.isFinite(o)||o<0||o>50)throw Error(`Auto-swap slippage must be between 0 and 50 percent.`);if(t.maxAmountIn!==void 0&&t.maxAmountIn<=0n)throw Error(`Auto-swap maxAmountIn must be positive.`);let s=a.filter(e=>!LE(e,i)),c=await Promise.allSettled([Ee(e,{...Fe.token.getBalance.call(e,{account:n,token:i}),account:null}),...s.map(t=>Ee(e,{...Fe.token.getBalance.call(e,{account:n,token:t}),account:null}))]),l=c[0];if(l.status!==`fulfilled`)throw l.reason;let u=l.value;if(u>=r)return;let d=r-u,f=BigInt(Math.round(o*100)),p=t.maxAmountIn??d+d*f/Ij;for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=s[t];try{let t=await Fe.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:d});if(t<=0n||t>p)continue;let n=t+t*f/Ij,o=n<p?n:p;if(r>=o)return[Fe.token.approve.call(e,{amount:o,spender:Ie.stablecoinDex,token:a}),Fe.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:d,maxAmountIn:o})]}catch{}}throw new Rj({currency:i})}function Fj(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...e.fallback===!1?[]:t.filter(t=>!e.tokenIn.some(e=>LE(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var Ij,Lj,Rj,zj=I((()=>{RE(),gk(),Ij=10000n,Lj=[fk.pathUsd,fk.usdc,fk.ousd],Rj=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}}}));function Bj(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:BigInt(e.amount).toString(),memo:e.memo,recipient:e.recipient}))]}var Vj=I((()=>{}));function Hj(e,t,n){t&&(n&&!n.some(e=>LE(e,t))||e.some(e=>LE(e,t))||e.push(t))}async function Uj(e,t,n){try{return(await Fe.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function Wj(e){let t=e.chain?.feeToken;if(t)return Le.toAddress(t);let n=e.chain?.id;return n?pk[n]:void 0}function Gj(e){let t=[];return Hj(t,fk.pathUsd),Hj(t,pk[e]),t}async function Kj(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])Hj(o,e,n);if(Hj(o,await Fe.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),Hj(o,Wj(i),n),!a)for(let e of r??[])Hj(o,e,n);for(let e of o)if(await Uj(i,t,e))return e;return o[0]}var qj=I((()=>{RE(),gk()}));function Jj(e){if(e!==void 0)return mk[e]}function Yj(e){let t=Jj(e.chainId);return!!t&&ue(e.currency,{strict:!1})&&de(e.currency,t.token)}function Xj(e){let t=Jj(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let r=BigInt(n.amount),i=n.memo;return{calls:[{data:ae({abi:Ne.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:ae({abi:Qj,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 Zj(e,t){let n=Xj(t);if(n)try{return await Ee(e,Fe.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await Se(e,{account:t.account,calls:n.calls}),n)}catch{return}}var Qj,$j=I((()=>{gk(),Qj=pe([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`])}));function eM(e){return{name:`MPP`,version:`3`,chainId:e}}function tM(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function nM(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:eM(n),types:aM,primaryType:iM,message:tM({account:t,challengeId:r,realm:i})}}function rM(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}var iM,aM,oM=I((()=>{iM=`Proof`,aM={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]}}));function sM(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:hM(e.maxAmount,e.decimals),maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=Cj({chain:be,getClient:e.getClient,rpcUrl:hk}),i=vj({account:e.account});uM(e.zone);let a=new Map,o=FE(uD,{canHandleChallenge({challenge:t}){try{return gM(e,n,t.request),!0}catch{return!1}},context:_M,async createCredential({challenge:o,context:s}){gM(e,n,o.request);let c=o.request.methodDetails?.chainId??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),l=await r({chainId:c});wj(l,c);let u=c??l.chain?.id;if(Tj(e.allowedChainIds,u),u===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:d}=o,{amount:f,methodDetails:p}=d,m=p?.supportedModes??[`pull`,`push`],h=e.zone?.client.chain,g=e.zone?e.zone.zoneId??HE(h?.id??0):void 0,_=h?.sourceId??(h?UE(h.id):void 0),v=s?.mode??e.mode;if(BigInt(f)>0n&&e.zone&&g!==void 0&&_===u&&m.includes(`push`)&&(v===void 0||v===`push`)&&BE(p?.zones,g)&&!p?.splits&&(a.has(pM(o))||dM(o.expires,e.zone.settlementTimeoutMs)))return lM({challenge:o,clientId:t,client:l,pending:a,zone:e.zone,zoneId:g});let y=i(l,s),b=async t=>await e.resolveAccount?.({account:y,chainId:u,operation:t})??y;if(BigInt(f)===0n){let e=await b({kind:`signPaymentProof`});return FS({challenge:o,payload:{signature:await je(l,{account:e,...nM({account:e.address,chainId:u,challengeId:o.id,realm:o.realm})}),type:`proof`},source:rM({address:e.address,chainId:u})})}let x=d.currency,S=Yj({chainId:u,currency:x}),C=kj({challengeId:o.id,clientId:t,serverId:o.realm}),w=Bj({amount:f,methodDetails:{...p,memo:C},recipient:d.recipient}),T=w.map(e=>Fe.token.transfer.call(l,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:x})),ee=Fj(s?.autoSwap??e.autoSwap,Lj),te=p?.machineTokenEnabled===!0?Xj({chainId:u,currency:x,transfers:w}):void 0,E=y,D;if(te){let e=await(async()=>{try{return await b({calls:te.calls,kind:`executeCalls`})}catch{return}})();e&&(D=await Zj(l,{account:e.address,chainId:u,currency:x,transfers:w}),D&&(E=e))}let O;D||(E=await b({kind:`executeCalls`,...ee?{}:{calls:T}}),O=ee?await Pj(l,{account:E.address,amountOut:BigInt(f),tokenOut:x,tokenIn:ee.tokenIn,slippage:ee.slippage,maxAmountIn:ee.maxAmountIn}):void 0);let k=D?.calls??[...O??[],...T],ne=Gj(u),A=(s?.feeToken??e.feeToken)||(D||S?await Kj({account:E.address,allowedTokens:ne,candidateTokens:ne,client:l,prioritizeCandidates:!0}):void 0),j=(()=>{let t=s?.mode??e.mode;if(t){if(!m.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=E.type===`json-rpc`?`push`:`pull`;return m.includes(n)?n:m[0]})(),M=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!o.expires)return e;let t=Math.floor(new Date(o.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(j===`push`){let{receipts:e}=E.type===`local`?{receipts:[await ke(l,{account:E,calls:k,...A?{feeToken:A}:{},nonceKey:`expiring`,validBefore:M})]}:await De(l,{account:E,...A?{capabilities:{feeToken:A}}:{},calls:k,experimental_fallback:k.length===1,forceAtomic:k.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return FS({challenge:o,payload:{hash:t,type:`hash`},source:rM({address:E.address,chainId:u})})}let re=()=>{if(p?.feePayer!==!0)return;let e=15e3,t=o.expires?new Date(o.expires).getTime():1/0,n=Date.now();if(!(t-n>=e))throw Error(`Sponsored challenge expires in less than 15 seconds; the fee payer would reject the transaction. Request a new challenge.`);if(!(M*1e3-n>=e))throw Error(`Sponsored transaction preparation took too long: less than 15 seconds of its validity window remain, so the fee payer would reject it.`)};re();let ie=await Te(l,{account:E,calls:k,...A?{feeToken:A}:{},nonceKey:`expiring`,validBefore:M});if(ie.gas=(ie.gas??0n)+5000n,p?.feePayer){let e=ie;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return re(),FS({challenge:o,payload:{signature:await Ae(l,ie),type:`transaction`},source:rM({address:E.address,chainId:u})})}}),s=new Map,c=async t=>{gM(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=s.get(i);return a||(a=o.createCredential(t).finally(()=>s.delete(i)),s.set(i,a)),a};return Uw({...o,createCredential:c},cM)}function cM(e){let t=uD.schema.credential.payload.safeParse(jS(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`||n.type===`zone`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(We.serializedType))return;let i=We.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&We.serialize(i)===r)return fe(r)}async function lM(e){let{challenge:t,client:n,pending:r,zone:i,zoneId:a}=e,o=t.request.recipient,s=pM(t),c=r.get(s);if(!c){let t={sent:!1};c=mM(e,t),r.set(s,c),c.catch(()=>{t.sent||r.delete(s)})}let l=await c,u;try{u=await GE(n,{portal:VE(a),senderTag:l,timeoutMs:fM(t.expires,i.settlementTimeoutMs),to:o})}catch(e){throw new DS({cause:e,challengeId:t.id,senderTag:l,zoneId:a})}return r.delete(s),FS({challenge:t,payload:{hash:u,senderTag:l,type:`zone`,zoneId:a}})}function uM(e){let t=e?.settlementTimeoutMs;if(t!==void 0&&(!Number.isFinite(t)||t<0))throw Error("`zone.settlementTimeoutMs` must be a finite, non-negative number.");let n=e?.client.chain?.id;if(e?.zoneId===void 0||n===void 0||UE(n)===void 0)return;let r=HE(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function dM(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+vM}function fM(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function pM(e){return JSON.stringify(e)}async function mM(e,t){let{challenge:n,clientId:r,zone:i}=e,a=n.request,o=i.client.account;if(!o)throw Error("`zone.client` requires an account.");let s=BigInt(a.amount),c=a.currency,l=a.recipient,u=kj({challengeId:n.id,clientId:r,serverId:n.realm}),d=await Fe.zone.getWithdrawalFee(i.client),[,f]=Fe.zone.requestWithdrawal.calls({amount:s,fallbackRecipient:o.address,memo:u,to:l,token:c}),p=await Te(i.client,{account:o,calls:[Fe.token.approve.call({amount:s+d,spender:Ie.zoneOutbox,token:c}),f]}),m=await Ae(i.client,p);t.sent=!0;let h=fe(m),g=await Oe(i.client,{serializedTransaction:m}).catch(e=>Me(i.client,{hash:h,timeout:yM}).catch(()=>{let t=Error(`Zone withdrawal outcome is unknown: transaction ${h} may have been sent. Retrying this challenge does not withdraw again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),t}));if(g.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${g.transactionHash} reverted.`);let[_]=me({abi:Ne.zoneOutbox,eventName:`WithdrawalRequested`,logs:g.logs});if(!_)throw Error("Zone withdrawal request did not emit `WithdrawalRequested`.");return WE({fallbackNonce:_.args.fallbackNonce,sender:_.args.sender,transactionHash:g.transactionHash})}function hM(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo charge maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo charge maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return he(e,t)}}function gM(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)&&Tj(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 _M,vM,yM,bM=I((()=>{Zw(),BS(),OS(),IE(),yj(),Dj(),tS(),Nj(),zj(),Vj(),gk(),qj(),$j(),oM(),ZE(),pD(),_M=J.object({account:J.optional(J.custom()),autoSwap:J.optional(J.custom()),feeToken:J.optional(J.custom()),mode:J.optional(J.enum(eD))}),vM=15e3,yM=15e3}));function xM(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function SM(e){let t=D.encode(D.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return ne.keccak256(t)}function CM(e){return We.encodeForSigning(e)}function wM(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function TM(e,t){return ne.keccak256(A.concat(CM(e),t.sender))}var EM=I((()=>{ID()})),DM,OM,kM,AM,jM=I((()=>{DM=[{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`}],OM=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],kM={name:`descriptor`,type:`tuple`,components:DM},AM=[{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:[kM,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[kM,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[kM,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[kM],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[kM],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[kM],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:DM},{name:`state`,type:`tuple`,components:OM}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:OM}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:OM}]},{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 MM(e,t){return{name:HM,version:UM,chainId:t,verifyingContract:e}}function NM(e,t,n){return le({domain:MM(e,t),types:GM,primaryType:`CloseAuthorization`,message:n})}function PM(e,t){return Be.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function FM(e,t,n){return e.toLowerCase()===Be.address.toLowerCase()?PM(t,n):le({domain:MM(e,t),types:WM,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function IM(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function LM(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function RM(e,t){return Pe.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function zM(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===Be.address.toLowerCase())try{return await RM(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return je(e,{account:t,domain:MM(r,i),types:WM,primaryType:`Voucher`,message:n})})(),o=He.from(a);if(!IM(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return He.serialize(o)}async function BM(e,t,n,r,i){let a=LM(t)?await t.sign({hash:NM(r,i,n),raw:!0}):await je(e,{account:t,domain:MM(r,i),types:GM,primaryType:`CloseAuthorization`,message:n}),o=He.from(a);if(!IM(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return He.serialize(o)}function VM(e,t,n,r){try{let i=He.from(n.signature);if(!IM(i.type)||He.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=FM(e,t,n),o=He.extractAddress({payload:a,signature:i});return He.verify(i,{address:o,payload:a})&&LE(o,r)}catch{return!1}}var HM,UM,WM,GM,KM=I((()=>{RE(),HM=`TIP20 Channel Reserve`,UM=`1`,WM={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},GM={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]}}));function qM(e){return typeof e==`object`&&!!e}function JM(e){return typeof e==`string`&&ue(e,{strict:!1})?e:void 0}function YM(e){return JM(e.accessKeyAddress)}function XM(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(A.random(8))%e)}function ZM(e){return YM(e)??e.address}async function QM(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return Te(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function $M(e,t){return await Ae(e,t)}function eN(e,t,n=!1){let r=e.request.methodDetails,i=qM(r)?JM(r.escrowContract)??JM(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!nN(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!nN(i,a)?i:a}function tN(e,t,n,r){return FS({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function nN(e,t){return e.toLowerCase()===t.toLowerCase()}async function rN(e,t,n,r,i,a=FD){let o=SM({...n,chainId:i,escrow:a}),s=gD(r),c=await zM(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function iN(e,t,n,r,i,a=FD){let o=await rN(e,t,n,r,i,a),s=await BM(e,t,{channelId:o.channelId,cumulativeAmount:gD(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function aN(e,t,n){let r=ZM(t),i=n.escrow??`0x4d50500000000000000000000000000000000000`,a=n.operator??`0x0000000000000000000000000000000000000000`,o=A.random(32),s=gD(n.deposit),c=gD(n.initialAmount),l=ae({abi:AM,functionName:`open`,args:[n.payee,a,n.token,s,o,r]}),u=await $M(e,await QM(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:TM(wM({...n.feePayer?{feePayer:!0}:{},transaction:d}),{sender:t.address}),operator:a,payee:n.payee,payer:t.address,salt:o,token:n.token},p=SM({...f,chainId:n.chainId,escrow:i});return{action:`open`,type:`transaction`,channelId:p,transaction:u,signature:await zM(e,t,{channelId:p,cumulativeAmount:c},i,n.chainId),descriptor:f,cumulativeAmount:c.toString(),authorizedSigner:f.authorizedSigner}}async function oN(e,t,n,r,i,a,o=FD,s=[],c=n.token){let l=SM({...n,chainId:i,escrow:o}),u=gD(r);return{action:`topUp`,type:`transaction`,channelId:l,transaction:await $M(e,await QM(e,{account:t,calls:[...s,{to:o,data:ae({abi:AM,functionName:`topUp`,args:[n,u]})}],feePayer:a,feeToken:c,validAfter:XM()})),descriptor:n,additionalDeposit:u.toString()}}var sN=I((()=>{BS(),EM(),jM(),ID(),KM()}));function cN(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function lN(e){return cN({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function uN(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(lN(t),t)},delete(t){e.delete(t)}}}function dN(e){return{...e,cumulativeAmount:e.cumulativeAmount.toString(),deposit:e.deposit.toString()}}function fN(e){return{...e,cumulativeAmount:BigInt(e.cumulativeAmount),deposit:BigInt(e.deposit)}}function pN(e,t){yN.set(e,yN.get(t)??t)}async function mN(e,t,n){let r=vN.get(e);r||(r=new Map,vN.set(e,r));let i=(r.get(t)??Promise.resolve()).catch(()=>{}).then(n);r.set(t,i);try{return await i}finally{r.get(t)===i&&r.delete(t)}}function hN(e,t,n){return mN(yN.get(e)??e,`funding:${t}`,n)}async function gN(e,t){await mN(e,`write:${lN(t)}`,async()=>{let n=await e.get(lN(t));if(n?.origin!==void 0){if(t.origin!==void 0&&t.origin!==n.origin)throw Error(`SessionManager: stored channel origin mismatch`);t.origin=n.origin}if(n?.uncertainTopUp){if(n.channelId!==t.channelId)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);t.uncertainTopUp=!0}await e.set(t)})}async function _N(e,t){await mN(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}var vN,yN,bN=I((()=>{vN=new WeakMap,yN=new WeakMap}));function xN(e){if(e<0n||e>wN)throw new Y({reason:`amount exceeds uint96 range`})}async function SN(e,t,n=FD,r){return CN(await Ee(e,{address:n,abi:AM,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function CN(e){return xN(e.settled),xN(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}var wN,TN=I((()=>{OS(),jM(),ID(),wN=2n**96n-1n}));function EN(e){return`cumulativeAmount`in e}function DN(e){if(EN(e))return BigInt(e.cumulativeAmount)}async function ON(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await gN(e.store,t):await _N(e.store,lN(t)),e.notifyUpdate(t)}async function kN(e,t,n){let r=DN(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 ON(e,i))}function AN(e){return e?.action!==void 0}function jN(e){return AN(e)&&e.descriptor!==void 0}function MN(e,t,n){let r=n===`additionalDeposit`?e.additionalDepositRaw:e.cumulativeAmountRaw,i=n===`additionalDeposit`?e.additionalDeposit:e.cumulativeAmount;if(r)return BigInt(r);if(i)return he(i,t)}function NN(e,t,n,r){let i=MN(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function PN(e){return typeof e==`object`&&!!e}function FN(e){return typeof e==`string`&&ue(e,{strict:!1})?e:void 0}function IN(e){let t=e.request.methodDetails;return PN(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:FN(t.escrowContract),escrow:FN(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:FN(t.feeToken),operator:FN(t.operator),sessionSnapshot:Nx(t,Lx.sessionSnapshot)}:{}}function LN(e,t){if(typeof e==`string`&&ue(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function RN(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function zN(e){return typeof e==`string`?e:void 0}async function BN(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=IN(n);(o.chainId!==void 0||i?.length===0)&&Tj(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});wj(c,s);let l=s??c.chain?.id;if(Tj(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=eN(n,r,t),d=LN(n.request.recipient,`recipient`),f=LN(n.request.currency,`currency`);return{amount:RN(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:cN({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:zN(n.request.suggestedDeposit),token:f}}async function VN(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=SN}=e,o=SM({...r,chainId:i.chainId,escrow:i.escrow});HN({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 HN(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(!nN(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!nN(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!nN(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!nN(xM(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function UN(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function WN(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=MN(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function GN(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(!VM(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},xM(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await VN({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:ZM(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 KN(e,t){return nN(e.address,t.payer)?nN(ZM(e),xM(t)):!1}function qN(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(AN(r)){if(!jN(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=UN({context:r,snapshot:o.snapshot});return!n&&s&&KN(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&KN(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 JN(e,t,n=!1){switch(e.type){case`open`:return XN(e,t,n);case`recover`:return ZN(e,t);case`voucher`:return QN(e,t);case`manual`:return $N(e,t,n)}}async function YN(e,t){if(e)return await Pj(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function XN(e,t,n){let{account:r,resolved:i}=e,a=rO({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await aN(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 YN(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await ON(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function ZN(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await VN({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:ZM(n),token:o.token}}),l=WN({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`);aO(l,a);let u=await rN(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await ON(t,{...d?.channelId===c.channelId&&d.uncertainTopUp?{uncertainTopUp:!0}:{},channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function QN(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;aO(a,e.maxDeposit);let o=await rN(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await ON(t,r),o}async function $N(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=SM({...s,chainId:o.chainId,escrow:o.escrow});HN({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:ZM(r),token:o.token});let l=await eP({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await kN(t,o.key,l),l}async function eP(e,t){switch(e.context.action){case`open`:return tP(e);case`topUp`:return nP(e,t);case`voucher`:return rP(e);case`close`:return iP(e)}}async function tP(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=NN(r,i,`cumulativeAmount`,`open`),c=await rN(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 nP(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=NN(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:oN(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await YN(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function rP(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return rN(a.client,t,i,NN(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function iP(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return iN(a.client,t,i,NN(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}var aP,oP,sP,cP=I((()=>{zx(),Dj(),tS(),zj(),TN(),EM(),KM(),sN(),bN(),bO(),aP=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),oP=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),sP=J.object({account:J.optional(J.custom()),autoSwap:J.optional(J.custom()),action:J.optional(J.enum([`open`,`topUp`,`voucher`,`close`])),channelId:J.optional(oP),cumulativeAmount:J.optional(Gx()),cumulativeAmountRaw:J.optional(J.string()),transaction:J.optional(aP),descriptor:J.optional(J.custom()),additionalDeposit:J.optional(Gx()),additionalDepositRaw:J.optional(J.string()),depositRaw:J.optional(J.string())})}));async function lP(e,t){let n=yP.get(e)??new Map;yP.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 uP(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function dP(e,t,n){try{let r=e.response?.headers.get(q.paymentReceipt);if(r){let e=TD(r);if(e.challengeId===t.id&&uP(n,e))return!0}}catch{}return e.challenges?.some(e=>DO(e)?uP(n,OO(e)):!1)??!1}function fP(e){let{currencies:t,decimals:n,expectedRecipients:r,maxAmount:i,maxAtomicAmount:a}=e;if((i!==void 0||a!==void 0)&&t===void 0)throw Error(`Tempo session maxAmount and maxAtomicAmount require currencies.`);return{currencies:t?.map(e=>e.toLowerCase()),expectedRecipients:r?new Set(r.map(e=>e.toLowerCase())):void 0,maxAmount:pP(i,n),maxAtomicAmount:a===void 0?void 0:BigInt(a)}}function pP(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo session maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo session maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return he(e,t)}}function mP(e,t){if(e.currencies&&!e.currencies.includes(t.currency.toLowerCase()))throw Error(`Tempo session currency is not allowed: ${t.currency}.`);if(e.expectedRecipients&&(!t.recipient||!e.expectedRecipients.has(t.recipient.toLowerCase())))throw Error(`Unexpected session recipient: ${t.recipient}`);let n=BigInt(t.amount);if(e.maxAtomicAmount!==void 0&&n>e.maxAtomicAmount)throw Error(`Tempo session amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0&&n>e.maxAmount)throw Error(`Tempo session amount exceeds maxAmount.`)}function hP(e,t){try{return mP(e,t),!0}catch{return!1}}function gP(e){return typeof e==`object`&&!!e&&e.action===`close`}function _P(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=fP(e),m=Cj({chain:Xe,getClient:c,rpcUrl:hk}),h=vj({account:t}),g=l===void 0?void 0:he(l,a),_=u===void 0?void 0:he(u,a),v=e.origin===void 0?void 0:new URL(e.origin);if(v&&![`http:`,`https:`].includes(v.protocol))throw Error(`Session origins require HTTP or HTTPS`);let y=i??uN(),b={store:y,notifyUpdate:e=>d?.(e)},x=async(e,t,n)=>{let r=h(e.client,t),i=t?.action?t.descriptor:n?.descriptor??UN({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:xM(i)}:{}}})??r},S=async(e,t,n)=>qN({account:await x(e,t,n),entry:n,context:t,decimals:a,maxDeposit:g,resolved:e}),C=FE(dD,{canHandleChallenge:({challenge:e,context:t})=>DO(e)&&(gP(t)||t===bC||hP(p,e.request)),context:sP,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&mP(p,t.request);let a=await BN({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m}),c=Vw(e),l=Kw(e)??v?.origin;if(l!==void 0&&(l===`null`||![`http:`,`https:`].includes(new URL(l).protocol)))throw Error(`Session payments require an HTTP or HTTPS origin`);if(v&&l!==v.origin)throw Error(`Session channel origin mismatch`);let u={...b,origin:l},d=()=>{};try{let e=!AN(i)&&i?.descriptor===void 0;e&&(d=await lP(y,a.key),c&&(await y.get(a.key))?.opened&&await c.prepare());let n=await y.get(a.key);if(n&&n.origin!==l)throw Error(`Session channel origin mismatch`);if(l&&!n&&a.snapshot&&!i?.descriptor&&!v)throw Error(`Session snapshot recovery requires an explicitly configured origin or descriptor`);let o=await S(a,i,n);if(!e&&c&&o.type===`open`){d=await lP(y,a.key);let e=await y.get(a.key);if(e&&e.origin!==l)throw Error(`Session channel origin mismatch`);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await y.get(a.key)),o=await S(a,i,n))}let s,f=c&&o.type===`open`?{store:{get:e=>y.get(e),async set(e){s=l?{...e,origin:l}:e},delete:e=>y.delete(e)},notifyUpdate(){}}:u,p=await tN(t,await JN(o,f,Fj(i?.autoSwap??r,Lj)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||dP(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await y.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await gN(y,e),b.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function w(e,t,n){let r={challenge:e,context:t};return Gw(r,vP(n)),C.createCredential(r)}let T=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>hN(y,lN(n),async()=>{s?.throwIfAborted();let c=await y.get(lN(n));if(c?.channelId===n.channelId&&(n=c),n.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let l=n.deposit>r?n.deposit:r,u=iO({deposit:l,maxDeposit:g,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:_});u>0n&&await PO({autoSwap:e,additionalDeposit:u,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>w(e,t,a),onUncertainFunding:async e=>{let t=await y.get(lN(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await gN(y,n),b.notifyUpdate(n)},fetch:i,input:a,signal:s});let d=l+u;if(d===n.deposit)return;let f=await y.get(lN(n)),p=f?.channelId.toLowerCase()===n.channelId.toLowerCase()?f:n,m={...p,deposit:p.deposit>d?p.deposit:d};await gN(y,m),b.notifyUpdate(m)});return Mw(C,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!DO(e))return;let c=t===void 0?void 0:sP.parse(t);if(AN(c))return;mP(p,e.request);let l=await BN({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await y.get(l.key);if(!u?.opened)return;let d=vP(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,h=u.cumulativeAmount+SD(e),g=f?BigInt(f.requiredCumulative):h,_=g>h?g:h,v=f?BigInt(f.deposit):u.deposit,b=v>u.deposit?v:u.deposit;_<=b&&b===u.deposit||!KN(await x(l,c,u),u.descriptor)||await T({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:b,fetch:r,input:i,requiredCumulative:_,signal:a})}),Rw(C,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!DO(e))return u;if(!ED(u))return xD(jS(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await BN({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await y.get(f),h={assertVoucherWithinLocalLimit:e=>aO(e,g),createSessionCredential:(e,t)=>w(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await T({autoSwap:t===void 0?void 0:sP.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return GO({onNeedVoucher:(t,n)=>KO({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function vP(e){let t=new URL(e instanceof Request?e.url:e,globalThis.location===void 0?void 0:globalThis.location.href);if(![`http:`,`https:`].includes(t.protocol))throw Error(`Session payments require an HTTP or HTTPS origin`);return t.origin}var yP,bP=I((()=>{Lw(),Zw(),zx(),BS(),xC(),IE(),yj(),Dj(),zj(),gk(),pD(),EM(),ID(),sN(),bN(),cP(),bO(),yP=new WeakMap}));function xP(e,t){CP.set(e,t)}function SP(e){let t=CP.get(e);if(!t)throw Error(`Session manager internals are unavailable.`);return t}var CP,wP=I((()=>{CP=new WeakMap}));function TP(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 EP(e){let t=TP(`close-ready`),n=TP(`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 DP=I((()=>{}));function OP(e){return e.method===Fx.tempo&&e.intent===Ix.charge}function kP(e){if(!OP(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function AP(e,t,n){if(!n)return t;let r={...sT(AO(e)?e.headers:void 0),...sT(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===q.paymentSession.toLowerCase())?t:{...t,headers:{...r,[q.paymentSession]:n}}}function jP(e,t){return e===void 0?t:{...sP.parse(e),...t}}function MP(e){let t=e.decimals??6,n=e.webSocket??globalThis.WebSocket;return{decimals:t,fetch:e.fetch??globalThis.fetch.bind(globalThis),maxVoucherCumulative:e.maxDeposit===void 0?null:he(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:he(e.topUpAmount,t),WebSocket:n}}function NP(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&Tj(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=MP(e),i;function a(e){let t=new URL(AO(e)?e.url:String(e),typeof location>`u`?void 0:location.href);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`SessionManager: session payments require an HTTP origin`);let n=t.origin;if(i!==void 0&&i!==n)throw Error(`SessionManager: session payment origin mismatch`);return i=n,n}let o=kT(r.fetch),s=AT(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(AO(e)?e.redirect:void 0))===`manual`?`manual`:`error`});if(r.url&&new URL(r.url).origin!==n)throw Error(`SessionManager: session response origin mismatch`);return r};let c=r.fetch;o&&(r.fetch=GS(c,o));let l=Cj({chain:Xe,getClient:e.client?()=>e.client:e.getClient,rpcUrl:hk}),u=vj({account:e.account}),d=dO(),f=e.credentialContext===void 0?void 0:jP(e.credentialContext,{}),p=EP({getSocketSession:()=>d.socketSession}),m=e.channelStore??uN(),h=new Set,g;async function _(e){let t=await m.get(e);if(t?.opened&&!h.has(t.channelId)){if(t.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return t}}let v=e=>{if(e.origin!==void 0&&e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return e.origin=i,gN(m,e)},y={async get(e){let t=await _(e);return t&&g&&(g.seenExisting.add(e),!g.committed&&!g.created.has(e)&&(g.resumed??=t)),t},async set(e){let t=lN(e);e.opened&&h.delete(e.channelId),g?.trackCreates&&!g.seenExisting.has(t)&&g.created.set(t,e),await v(e)},delete:e=>_N(m,e)};pN(y,m);async function b(e){let t=lN(e),n=await m.get(t);if(e.uncertainTopUp||n?.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);h.add(e.channelId),g?.seenExisting.delete(t),g?.resumed===e&&(g.resumed=void 0),await Promise.resolve(_N(m,t)).catch(()=>void 0)}async function x(){let e=g;if(e?.created.size){for(let[t,n]of e.created){let e=await m.get(t);if(n.uncertainTopUp||e?.channelId===n.channelId&&e.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before discarding the channel.`);h.add(n.channelId),await Promise.resolve(_N(m,t)).catch(()=>void 0)}e.created.clear(),await de(e.committed??e.previous)}}function S(e){let t=Nx(e.request.methodDetails,Lx.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=g;if(!n?.created.size||!d.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&d.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=gO({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return JD(d,e)}function w(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function T(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=gO({channel:d.channel,spent:d.spent,state:d.state}))}let ee=_P({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}}),te=Fw(ee);te&&Mw(ee,e=>ce(()=>Promise.resolve(te(e)),e.signal)),zw(ee);let E=sM({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),D=aT({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[ee],onChallenge:async(e,t)=>{if(!EO(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&rS(e)===rS(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await de(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function O(e,t){let n={challenge:e,context:jP(f,t)};return i&&Gw(n,i),ee.createCredential(n)}function k(e){fO({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function ne(e=d.state.status===`active`?d.state.units:0){!d.channel||!d.lastChallenge||d.state.status!==`active`&&d.state.status!==`withdrawable`&&d.state.status!==`closeRequested`&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function A(t){let n=t.headers.get(q.paymentSessionSnapshot);if(!n)return;let r=RD(n);Tj(e.allowedChainIds,r.chainId);let i=await l({chainId:r.chainId});wj(i,r.chainId);let a=u(i),{entry:o,spent:s}=await GN({account:await e.resolveAccount?.({account:a,chainId:r.chainId,operation:{authority:xM(r.descriptor),kind:`authorizePaymentChannel`}})??a,client:i,snapshot:r});return oe(o.cumulativeAmount),await Promise.resolve(y.set(o)).catch(()=>void 0),d.channel=o,d.spent=s,o}async function j(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=AO(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=AO(t)?t.url:t,l={...s,method:`HEAD`,headers:{...sT(i),...sT(n?.headers),[q.acceptPayment]:`${Fx.tempo}/${Ix.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await A(t);let n=pS(t).find(OP);if(!n||!kP(n))return;let i=new URL(String(c),typeof location<`u`?location.href:void 0);if(t.url&&new URL(t.url).origin!==i.origin)return;Qw(n,i,e.trustedTempoProofRealms);let a=await E.createCredential({challenge:n,context:{}}),o=await r.fetch(c,ZC({...l,redirect:`manual`},_S(n),a));return o.ok?await A(o):void 0}catch{return}}function M(e,t){let n=d.socketSession;return mO({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:d.channel?.channelId===t?d.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:d.spent,tickCost:n?.tickCost})}function re(e,t){let n=OO(t);if(!n)return;if(SM({...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 ie(e,t){let n=re(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(d.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>d.spent&&(d.spent=i),n}function ae(e,t=e.challenge,n=!1){let r=(n?ie(e,t):re(e.channel,t))?.acceptedCumulative??M(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return oe(r),r.toString()}function oe(e){$D({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let se,N;async function ce(e,t){if(N)throw N;for(;;){let e=se;if(!e)break;if(!t)await e;else{t.throwIfAborted();let n;try{await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0})})])}finally{t.removeEventListener(`abort`,n)}}}if(t?.throwIfAborted(),N)throw N;let n=e();se=n;try{return await n}catch(e){throw e instanceof lk&&(N=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{se===n&&(se=void 0)}}async function le(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return hN(m,lN(d.channel),async()=>{let{knownDeposit:t,...n}=e,i=d.channel?await y.get(lN(d.channel)):void 0;if(i?.channelId===e.channelId&&i.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let a=await PO({...n,channel:d.channel,createSessionCredential:O,fetch:r.fetch,onUncertainFunding:async e=>{let t=await y.get(lN(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};d.channel?.channelId===e.channelId&&(d.channel=n),await y.set(n),T(n)}});k(a);let o=d.channel,s=wO({additionalDeposit:e.additionalDeposit,channel:d.channel,channelId:e.channelId,challengeId:d.lastChallenge?.id,currentState:d.state,knownDeposit:t,receipt:a,spent:d.spent});if(s?.channel&&d.lastChallenge){let e=s.channel;for(;;){await y.set(e);let t=d.channel;if(t===o)break;if(!t)return a;let n=s.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,o=t}if(e.channelId!==s.channel.channelId)return a;d.channel=e,C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}return a})}async function P(e){return ce(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=iO({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 le({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function ue(e,t){let n=hO({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(C({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function de(e){let t=_O(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function fe(e){let t=e.headers.get(q.paymentReceipt),n=t?TD(t):null;return k(n),Object.assign(e,{receipt:n,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function pe(e,t){if(g)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a(e),d.lastUrl=e,d.lastHeaders=t?.headers;let n=gO({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await j(e,t),i.trackCreates=!0;let a=AP(e,t,d.channel?.opened?d.channel.channelId:void 0);f&&(a={...a,context:f});let o=!n.channel?.opened;async function s(){let n=i.resumed;return!o||!n?!1:(o=!1,await b(n),a=AP(e,t,void 0),!0)}for(;;){let t;try{t=await D(e,a)}catch(e){if(i.created.size?await x():await de(i.committed??n),await s())continue;throw e}let o=fe(t),c=!1;if(o.status===402){let t=await IO({input:e,init:a,response:o,createSessionCredential:O,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:ue,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:P});t&&(c=!0,o=fe(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await de(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function me(e){let t=await RO({createSessionCredential:O,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>ae(e,t,!0),signedCloseAmount:ae(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(ne(),C({type:`closeStarted`}),C({type:`closed`,receipt:t})),t}let he={createSessionCredential:O,doFetch:pe,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:oe,acceptReceipt(e){k(e)},topUpIfNeeded:P},ge={get channelId(){return d.channel?.channelId},get cumulative(){return d.channel?.cumulativeAmount??0n},get opened(){return d.channel?.opened??!1},get state(){return d.state},fetch:pe,async topUp(e){let t=CO({amount:e,assertVoucherWithinLocalLimit:oe,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return ce(async()=>{if(d.channel?.channelId!==t.channelId||d.lastChallenge!==t.challenge||d.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=CO({amount:e,assertVoucherWithinLocalLimit:oe,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return le({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){return zO(e,t,he)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=MO(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await j(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await JO({async createSessionCredential(e,i){return d.lastChallenge=e,await Pw(ee,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),O(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:AP(n,i,o),signal:t?.signal});return d.lastChallenge=s,$O({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:O,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await qO({fetch:r.fetch,input:l,probeInit:AP(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:oe,acceptReceipt:k,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:P,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=oO({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===ok.OPEN){let r=await vO({activeSocket:n,createSessionCredential:O,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return ne(),C({type:`closeStarted`}),C({type:`closed`,receipt:r}),r}return me(t)}};return xP(ge,{consumeSseResponse(e,t,n){let r=a(e);if(t.url&&new URL(t.url).origin!==r)throw Error(`SessionManager: session response origin mismatch`);return BO(e,t,n,he)},rehydrate({channel:e,challenge:t,input:n,spent:r}){let i=a(n);if(e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!EO(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.`);oe(e.cumulativeAmount);let o=re(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,C({type:`challengeReceived`,challengeId:t.id}),C({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),ge}var PP=I((()=>{SS(),QT(),Lw(),Zw(),nT(),$C(),zx(),XS(),yj(),Dj(),bM(),gk(),bN(),cP(),bP(),EM(),ID(),GD(),wP(),DP(),bO(),uk(),(function(e){e.serializeSnapshot=LD,e.deserializeSnapshot=RD})(NP||={})}));function FP(e){return e instanceof Date?e:new Date(e)}function IP(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 LP(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=nF[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>tF)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 RP(e){let{challengeExpires:t,request:n}=e;LP(n);let r=IP(FP(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 zP(e){let t=QP(e.currency,`currency`),n=QP(e.recipient,`recipient`);return[{address:t,selector:eF,recipients:[n]}]}function BP(e){try{let t=A.fromBytes(O.toBytes(e));if(A.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function VP(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=UP({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:Ve.getSignPayload(o)}),c=He.from(s);if(c.type===`keychain`||c.type===`multisig`)throw new Y({reason:`keyAuthorization must use a primitive signature`});return Ve.from(o,{signature:s})}function HP(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=WP(i.signature),s=GP(o);if(KP({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==BP(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return qP(o,a),YP(JP(o),a),XP(o.scopes,a),{authorization:o,source:{address:ZP(o,s),chainId:r}}}function UP(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return Ve.from({address:QP(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:IP(FP(i.subscriptionExpires)),limits:[{token:QP(i.currency,`currency`),limit:BigInt(i.amount),period:LP(i)}],scopes:zP(i),type:t.keyType,witness:BP(n)})}function WP(e){try{return Ve.deserialize(e)}catch(e){throw e instanceof Ve.InvalidSignatureTypeError?new Y({reason:`keyAuthorization must use a primitive signature`}):new Y({reason:`invalid keyAuthorization payload`})}}function GP(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function KP(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new Y({reason:`keyAuthorization chainId mismatch`});if(t){if(!de(n.address,QP(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 qP(e,t){if(RP({request:t}),e.expiry!==IP(FP(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function JP(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 YP(e,t){if(!de(e.token,QP(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!==LP(t))throw new Y({reason:`keyAuthorization period mismatch`})}function XP(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=QP(t.currency,`currency`),r=QP(t.recipient,`recipient`),i=new Set;for(let t of e){if(!de(t.address,n))throw new Y({reason:`keyAuthorization call target mismatch`});let e=$P(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||!de(t.recipients[0],r))throw new Y({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new Y({reason:`keyAuthorization must allow transferWithMemo`})}function ZP(e,t){let n=Ve.getSignPayload(e);try{let e=He.extractAddress({payload:n,signature:t});if(!He.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 QP(e,t){if(!ue(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function $P(e){return typeof e==`string`?e.toLowerCase():``}var eF,tF,nF,rF=I((()=>{OS(),eF=`0x95777d59`,tF=(1n<<64n)-1n,nF={dev_second:1n,day:86400n,week:604800n}}));function iF(e={}){let t=Cj({chain:be,getClient:e.getClient,rpcUrl:hk}),n=vj({account:e.account});return FE(fD,{context:sF,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??dk.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.");oF(r.request),await e.validateRequest?.(r.request);let l=await aF(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=HP({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:Ve.serialize(l),type:`keyAuthorization`},request:r.request});if(!de(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return FS({challenge:r,payload:{signature:Ve.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function aF(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await VP({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:IP(FP(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:A.fromNumber(BigInt(o.amount)),period:LP(o)}],scopes:zP(o),witness:BP(i)}]});return Ve.fromRpc(c.keyAuthorization)}function oF(e){LP(e),IP(FP(e.subscriptionExpires))}var sF,cF=I((()=>{BS(),IE(),yj(),Dj(),tS(),gk(),pD(),rF(),sF=J.object({accessKey:J.optional(J.custom()),account:J.optional(J.custom())})}));function lF(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[sM(e),uF(n)]}var uF,dF=I((()=>{bP(),PP(),bM(),cF(),uF=Object.assign(_P,{manager:NP}),(function(e){e.charge=sM,e.common=lF,e.session=uF,e.subscription=iF})(lF||={})})),fF=I((()=>{bM(),dF(),cF(),bP(),PP()})),pF=tt({orderTempoChargeChallengesByBalance:()=>hF,readTempoKeystore:()=>FF,resolveTempoAccount:()=>IF,tempo:()=>gF});async function mF(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}async function hF(e,t){let n=[],r=[];for(let[t,i]of e.entries())CF(i)&&(n.push(t),r.push(i));if(r.length<2)return[...e];let i=await wF(t).catch(()=>void 0);if(!i)return[...e];let a=await Promise.all(r.map(async(e,t)=>({challenge:e,index:t,score:await TF(e,i)})));a.sort((e,t)=>WF.indexOf(e.score)-WF.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 gF(){let e;return ij({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:t,options:n,methodOpts:r}){let i=Qk(n.account),a=t.request,o=a.currency,s=SF(r),c=kF({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()||(Dk(i)?void 0:await $k(i).get());if(!h&&Dk(i)&&LF()){m=!0;let e=IF(i);if(e){let r=jk(n.rpcUrl,{network:n.network});p=M({chain:await Nk({network:n.network,rpcUrl:r}),transport:P(r)}),DF({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let i=o?await Lk(p,o,e.wallet_address).catch(()=>void 0):void 0;l=i?.symbol??o??``,u=i?.decimals??a.decimals??6}}else if(h)f=ye(h);else{let e=zF();if(e){let t=await $k(e).get();t&&(f=ye(t))}if(!f)throw n.account?new L({code:`ACCOUNT_NOT_FOUND`,message:`Account "${i}" not found.`,exitCode:69}):new L({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!m&&f){let e=jk(n.rpcUrl,{network:n.network});p=M({chain:await Nk({network:n.network,rpcUrl:e}),transport:P(e)}),DF({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let r=o?await Lk(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 RF(t)}};if(!f||!p)throw new L({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let g=lF({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??(Ik(p.chain)?`10`:void 0);if(!n)throw new L({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return n})()}),_=(()=>{if(!s.channel)return;let e=s.channel,t=jF(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 zM(p,f,c,i,a);return FS({challenge:t,payload:{action:o,channelId:n,...o===`close`?{closeSignature:await BM(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=jS(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(e.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${X.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
237
+ `)}function Sk(e,t,n){if(Vk.has(e)&&typeof t==`string`)return`${t} ${X.dim(`(${Mk(BigInt(t),n.tokenSymbol,n.tokenDecimals)})`)}`;if(e===`chainId`&&typeof t==`number`){let e=Ik({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?Ek(`${n.explorerUrl}/address/${t}`,t):t:typeof t==`string`&&/^https?:\/\//.test(t)?X.link(t,t):String(t)}function Ck(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 wk(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 Tk(e){return typeof e==`object`&&e?JSON.stringify(e):String(e)}function Ek(e,t){return X.link(e,t)}function Dk(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 Ok(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 kk(e){return e.startsWith(`tempo:`)}function Ak(e){let t=qe.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 jk(e,t=!1){let n=qe.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 Mk(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 Nk(e,t={}){return e??(t.network?Hk[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}function Pk(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 Fk(e={}){let t=Nk(e.rpcUrl,{network:e.network});if(!t)return P;let{getChainId:n}=await import(`viem/actions`),r=await n(M({transport:de(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 Ik(e){return{[P.id]:`mainnet`,[Se.id]:`testnet`}[e.id]??e.name}function Lk(e){return typeof e==`bigint`?e:e.amount}function Rk(e){return e.id!==P.id}async function zk(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(Lk).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 Bk(e,t){if(t?.chain){let n=M({chain:t.chain,transport:de(t.rpcUrl)}),r=t.chain.blockExplorers?.default?.url,i=X.dim(`(${Ik(t.chain)})`);return Rk(t.chain)?(await Promise.all(Kk.map(t=>zk(n,t,e)))).filter(e=>e.balance>0n).map(e=>`${Mk(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`):(await Promise.all(Gk.map(t=>zk(n,t,e)))).map(e=>`${Mk(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`)}let n=M({chain:P,transport:de(Nk())}),r=P.blockExplorers?.default?.url,i=(await Promise.all(Gk.map(t=>zk(n,t,e)))).map(e=>Mk(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token}));if(t?.includeTestnet!==!1){let t=M({chain:Se,transport:de()}),n=Se.blockExplorers?.default?.url,r=await Promise.all(Kk.map(n=>zk(t,n,e)));for(let e of r)e.balance>0n&&i.push(`${Mk(e.balance,e.symbol,e.decimals,{explorerUrl:n,token:e.token})} ${X.dim(`(testnet)`)}`)}return i}var X,Vk,Hk,Uk,Wk,Gk,Kk,qk=F((()=>{vk(),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}}})(),Vk=new Set([`amount`,`suggestedDeposit`,`minVoucherDelta`]),Hk={mainnet:_k[pk.mainnet],testnet:_k[pk.testnet]},Uk=`0x20c0000000000000000000000000000000000000`,Wk=`0x20C000000000000000000000b9537d11c60E8b50`,Gk=[Uk,Wk],Kk=[`0x20c0000000000000000000000000000000000000`,`0x20c0000000000000000000000000000000000001`,`0x20c0000000000000000000000000000000000002`,`0x20c0000000000000000000000000000000000003`]}));function Jk(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:oA}function Yk(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function Xk(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 Zk(e){if(e&&Yk(e,`secret-tool`))throw Xk(e)}function Qk(e,t){return new Promise(n=>{m.execFile(e,t,{timeout:Jk()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function $k(){let e=c.join(process.env.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`mppx`,`default`);return{get(){try{return t.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,n,`utf-8`)},clear(){try{t.unlinkSync(e)}catch{}}}}function eA(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:$k().get())}function tA(e=`main`){let t=aA;return{async list(){let e=x.platform();if(e===`darwin`){let{stdout:e,error:n}=await Qk(`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 Qk(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(Zk(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=x.platform();if(n===`darwin`){let{stdout:n,error:r}=await Qk(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await Qk(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return Zk(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=x.platform();if(r===`darwin`){await Qk(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await Qk(`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(),Jk());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(Yk(e,`secret-tool`)?Xk(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=x.platform();if(n===`darwin`){await Qk(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await Qk(`secret-tool`,[`clear`,`service`,t,`account`,e]);Zk(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function nA(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=eA(e),i=await tA(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function rA(e){let t=eA(e);if(!process.env.MPPX_PRIVATE_KEY?.trim()&&kk(t))throw new I({code:`UNSUPPORTED_ACCOUNT`,message:`Persistent sessions require an mppx account or MPPX_PRIVATE_KEY.`,exitCode:2});return nA(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 iA(e){return(await nA(e)).account}var aA,oA,sA=F((()=>{qk(),aA=`mppx`,oA=1e4}));fk(),sA();const cA=[[`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 lA(e=process.env){return cA.find(([t])=>e[t])?.[1]}function uA(e){let{_mppx_nonce:t,_mppx_identity:n,...r}=e??{};return Object.keys(r).length?r:void 0}const dA=Symbol(`mppx.x402.asset`);function fA(e){return{[dA]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function pA(e,t){let n=e(t.chainId);return fA({address:n.address,decimals:n.decimals,network:CA(t.chainId),transfer:TA(t.transfer,n)})}const mA={USDC:fA({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},hA={USDC:fA({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},gA={USDC:fA({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:fA({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},_A={USDC:fA({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function vA(e){return typeof e!=`object`||!e?!1:e[dA]===!0}function yA(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function bA(e){return typeof e==`string`}function xA(e,t){if(vA(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(yA(e)){let n=e.addresses[wA(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function SA(e,t,n){let r=xA(e,n);return r?le(r.address)===le(t):!1}function CA(e){return`eip155:${e}`}function wA(e){return Number(e.slice(7))}function TA(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 EA=rt({base:()=>mA,baseSepolia:()=>hA,celo:()=>gA,celoSepolia:()=>_A,define:()=>fA,fromToken:()=>pA,isAsset:()=>vA,isRawAddress:()=>bA,isToken:()=>yA,matches:()=>SA,resolve:()=>xA,toChainId:()=>wA,toNetwork:()=>CA}),DA=rt({base:()=>OA,baseSepolia:()=>kA,celo:()=>AA,celoSepolia:()=>jA});const OA=8453,kA=84532,AA=42220,jA=11142220;Wx();function MA(e){let t=[Ux(e.accepted),Ux(e.resource),Ux(e.extensions)].join(`|`);return ne.sha256(te.fromString(t),{as:`Hex`})}Dw(),ZC();async function NA(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(LA(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?zA(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:le(t.address),nonce:i?.mppx?MA({accepted:r,extensions:i,resource:n.resource}):VA(),to:le(r.payTo),validAfter:(c-600).toString(),validBefore:(c+r.maxTimeoutSeconds).toString(),value:r.amount},u=await t.signTypedData({domain:{chainId:IA(r.network),name:o,verifyingContract:le(r.asset),version:s},message:{...l,value:BigInt(l.value),validAfter:BigInt(l.validAfter),validBefore:BigInt(l.validBefore)},primaryType:`TransferWithAuthorization`,types:FA});return Tw({accepted:r,...i?{extensions:i}:{},payload:{authorization:l,signature:u},...n.resource?{resource:n.resource}:{},x402Version:2})}function PA(e){let t=e.challenge.request,n;try{n=OC(t),LA(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 FA={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 IA(e){return Number(e.slice(jC.length))}function LA(e,t){let n=IA(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=>bA(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=le(t.asset);if(!r.some(n=>SA(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=RA(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>_e(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function RA(e,t){let n=e.currencies??e.assets,r=le(t.asset),i=n?.find(e=>SA(e,r,t.network)),a=i?xA(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function zA(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:BA()}}}:e}function BA(){return HA().slice(2)}function VA(){return HA()}function HA(){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(``)}`}nS();const UA=[`authorization`],WA=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 GA=J.object({chainId:J.number(),credentialTypes:J.optional(J.array(J.enum(UA)).check(J.minLength(1))),decimals:J.optional(J.number()),permit2Address:J.optional(Zx()),splits:J.optional(J.array(J.object({amount:WA,recipient:Zx()})))});J.object({amount:WA,currency:Zx(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:GA,recipient:Zx()});const KA=J.object({amount:Kx(),chainId:J.number(),currency:Zx(),credentialTypes:J.optional(J.array(J.enum(UA)).check(J.minLength(1))),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),permit2Address:J.optional(Zx()),recipient:Zx(),splits:J.optional(J.array(J.object({amount:WA,recipient:Zx()})))}),qA=J.object({from:Zx(),nonce:Qx(),signature:eS(),to:Zx(),type:J.literal(`authorization`),validAfter:WA,validBefore:WA,value:WA}),JA={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 YA(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function XA(e){return ne.keccak256(te.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function ZA(e){return`eip155:${e}`}function QA(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}RE(),nS();const $A=IE({name:`evm`,intent:`charge`,schema:{credential:{payload:qA},request:J.pipe(KA,J.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...c})=>({...c,amount:_e(e,i).toString(),currency:le(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:le(a)}:{},...s?{splits:s}:{}},recipient:le(o)})))}});VS(),RE(),tC(),nS();function ej(e){return LE($A,{canHandleChallenge({challenge:t}){return!tj(t)||PA({challenge:t,config:e})},context:J.object({account:J.optional(J.custom())}),async createCredential({challenge:t,context:n}){if(tj(t))return NA({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(nj(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=rj(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return IS(FS({challenge:t,payload:{from:le(r.address),nonce:XA(t),signature:await r.signTypedData({domain:YA({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:le(r.address),nonce:XA(t),to:le(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:JA}),to:le(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:QA({address:le(r.address),chainId:i.methodDetails.chainId})}))}})}function tj(e){return $S(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function nj(e,t){let n=t.methodDetails.chainId,r=ZA(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=>bA(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=le(t.currency);if(!i.some(t=>SA(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=ij(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>_e(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function rj(e,t){let n=e.currencies??e.assets,r=le(t.currency),i=ZA(t.methodDetails.chainId),a=n?.find(e=>SA(e,r,i)),o=a?xA(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 ij(e,t){let n=e.currencies??e.assets,r=le(t.currency),i=ZA(t.methodDetails.chainId),a=n?.find(e=>SA(e,r,i)),o=a?xA(a,i):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function aj(e){return[aj.charge(e)]}(function(e){e.charge=ej,e.assets=EA,e.chains=DA})(aj||={});function oj(e){return e}var sj=F((()=>{}));tC(),sj();function cj(){return oj({method:`evm`,supports:e=>e.method===`evm`&&!$S(e),async setup({challenge:e,options:t}){let n=e.request,r=n.methodDetails,i=r?.chainId,a=i?lj(i):void 0,o=n.currency,s=await iA(t.account),c=[...Object.values(mA),...Object.values(hA),...Object.values(gA),...Object.values(_A)],l=o??``;if(a&&o)try{let e=M({chain:a,transport:de()}),t=await Oe(e,{address:o,abi:se,functionName:`symbol`});t&&(l=t)}catch{}return{tokenSymbol:l,tokenDecimals:r?.decimals??6,explorerUrl:a?.blockExplorers?.default?.url,methods:[...aj({account:s,currencies:c})]}}})}function lj(e){return Object.values(Ze).find(t=>t.id===e)}function uj(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}nS();const dj=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)))}),fj=J.custom(e=>typeof e==`function`),pj=J.union([dj,fj]);RE(),nS();const mj=IE({name:`stripe`,intent:`charge`,schema:{credential:{payload:J.object({externalId:J.optional(J.string()),spt:J.string()})},request:J.pipe(J.object({amount:Kx(),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(pj),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:uj(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});VS(),RE(),nS();function hj(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return LE(mj,{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 IS({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function gj(e){return[hj(e)]}(function(e){e.charge=hj})(gj||={}),Nx(),qk(),sj();function _j(){return oj({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=yj(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:[gj.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=vj(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":FE},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&&vj(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function vj(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function yj(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 bj(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 be(r)}}var xj=F((()=>{}));function Sj(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}var Cj=F((()=>{}));function wj(e,t={}){return de(e.url,{fetchFn:e.fetch,fetchOptions:{headers:Sj(e)},...t})}function Tj(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=Ve(ae({request:t=>e(t)},{retryCount:0}),wj(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?Ve(de(a),wj(r)):de(a);return M({chain:Oj[n]??{...t,id:n},transport:o})}}function Ej(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 Dj(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}var Oj,kj=F((()=>{Cj(),Oj={[P.id]:P,[Se.id]:Se}}));function Aj(e){let t=ne.keccak256(te.fromString(e),{as:`Hex`});return j.toBytes(j.slice(t,0,10))}function jj(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(j.toBytes(Nj),0),i[4]=Pj,i.set(Aj(t),5),n&&i.set(Aj(n),15),i.set(Mj(r),25),j.fromBytes(i)}function Mj(e){let t=ne.keccak256(te.fromString(e),{as:`Hex`});return j.toBytes(j.slice(t,0,7))}var Nj,Pj,Fj=F((()=>{Nj=j.slice(ne.keccak256(te.fromString(`mpp`),{as:`Hex`}),0,4),Pj=1}));async function Ij(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t;if(!Number.isFinite(o)||o<0||o>50)throw Error(`Auto-swap slippage must be between 0 and 50 percent.`);if(t.maxAmountIn!==void 0&&t.maxAmountIn<=0n)throw Error(`Auto-swap maxAmountIn must be positive.`);let s=a.filter(e=>!zE(e,i)),c=await Promise.allSettled([Oe(e,{...Le.token.getBalance.call(e,{account:n,token:i}),account:null}),...s.map(t=>Oe(e,{...Le.token.getBalance.call(e,{account:n,token:t}),account:null}))]),l=c[0];if(l.status!==`fulfilled`)throw l.reason;let u=l.value;if(u>=r)return;let d=r-u,f=BigInt(Math.round(o*100)),p=t.maxAmountIn??d+d*f/Rj;for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=s[t];try{let t=await Le.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:d});if(t<=0n||t>p)continue;let n=t+t*f/Rj,o=n<p?n:p;if(r>=o)return[Le.token.approve.call(e,{amount:o,spender:Re.stablecoinDex,token:a}),Le.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:d,maxAmountIn:o})]}catch{}}throw new Bj({currency:i})}function Lj(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...e.fallback===!1?[]:t.filter(t=>!e.tokenIn.some(e=>zE(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var Rj,zj,Bj,Vj=F((()=>{BE(),vk(),Rj=10000n,zj=[mk.pathUsd,mk.usdc,mk.ousd],Bj=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}}}));function Hj(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:BigInt(e.amount).toString(),memo:e.memo,recipient:e.recipient}))]}var Uj=F((()=>{}));function Wj(e,t,n){t&&(n&&!n.some(e=>zE(e,t))||e.some(e=>zE(e,t))||e.push(t))}async function Gj(e,t,n){try{return(await Le.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function Kj(e){let t=e.chain?.feeToken;if(t)return ze.toAddress(t);let n=e.chain?.id;return n?hk[n]:void 0}function qj(e){let t=[];return Wj(t,mk.pathUsd),Wj(t,hk[e]),t}async function Jj(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])Wj(o,e,n);if(Wj(o,await Le.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),Wj(o,Kj(i),n),!a)for(let e of r??[])Wj(o,e,n);for(let e of o)if(await Gj(i,t,e))return e;return o[0]}var Yj=F((()=>{BE(),vk()}));function Xj(e){if(e!==void 0)return gk[e]}function Zj(e){let t=Xj(e.chainId);return!!t&&fe(e.currency,{strict:!1})&&pe(e.currency,t.token)}function Qj(e){let t=Xj(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:Fe.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:oe({abi:eM,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 $j(e,t){let n=Qj(t);if(n)try{return await Oe(e,Le.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await we(e,{account:t.account,calls:n.calls}),n)}catch{return}}var eM,tM=F((()=>{vk(),eM=he([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`])}));function nM(e){return{name:`MPP`,version:`3`,chainId:e}}function rM(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function iM(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:nM(n),types:sM,primaryType:oM,message:rM({account:t,challengeId:r,realm:i})}}function aM(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}var oM,sM,cM=F((()=>{oM=`Proof`,sM={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]}}));function lM(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:_M(e.maxAmount,e.decimals),maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=Tj({chain:P,getClient:e.getClient,rpcUrl:_k}),i=bj({account:e.account});fM(e.zone);let a=new Map,o=LE(fD,{canHandleChallenge({challenge:t}){try{return vM(e,n,t.request),!0}catch{return!1}},context:yM,async createCredential({challenge:o,context:s}){vM(e,n,o.request);let c=o.request.methodDetails?.chainId??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),l=await r({chainId:c});Ej(l,c);let u=c??l.chain?.id;if(Dj(e.allowedChainIds,u),u===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:d}=o,{amount:f,methodDetails:p}=d,m=p?.supportedModes??[`pull`,`push`],h=e.zone?.client.chain,g=e.zone?e.zone.zoneId??WE(h?.id??0):void 0,_=h?.sourceId??(h?GE(h.id):void 0),v=s?.mode??e.mode;if(BigInt(f)>0n&&e.zone&&g!==void 0&&_===u&&m.includes(`push`)&&(v===void 0||v===`push`)&&HE(p?.zones,g)&&!p?.splits&&(a.has(hM(o))||pM(o.expires,e.zone.settlementTimeoutMs)))return dM({challenge:o,clientId:t,client:l,pending:a,zone:e.zone,zoneId:g});let y=i(l,s),b=async t=>await e.resolveAccount?.({account:y,chainId:u,operation:t})??y;if(BigInt(f)===0n){let e=await b({kind:`signPaymentProof`});return IS({challenge:o,payload:{signature:await Ne(l,{account:e,...iM({account:e.address,chainId:u,challengeId:o.id,realm:o.realm})}),type:`proof`},source:aM({address:e.address,chainId:u})})}let x=d.currency,S=Zj({chainId:u,currency:x}),C=jj({challengeId:o.id,clientId:t,serverId:o.realm}),w=Hj({amount:f,methodDetails:{...p,memo:C},recipient:d.recipient}),T=w.map(e=>Le.token.transfer.call(l,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:x})),E=Lj(s?.autoSwap??e.autoSwap,zj),ee=p?.machineTokenEnabled===!0?Qj({chainId:u,currency:x,transfers:w}):void 0,D=y,O;if(ee){let e=await(async()=>{try{return await b({calls:ee.calls,kind:`executeCalls`})}catch{return}})();e&&(O=await $j(l,{account:e.address,chainId:u,currency:x,transfers:w}),O&&(D=e))}let k;O||(D=await b({kind:`executeCalls`,...E?{}:{calls:T}}),k=E?await Ij(l,{account:D.address,amountOut:BigInt(f),tokenOut:x,tokenIn:E.tokenIn,slippage:E.slippage,maxAmountIn:E.maxAmountIn}):void 0);let A=O?.calls??[...k??[],...T],te=qj(u),ne=(s?.feeToken??e.feeToken)||(O||S?await Jj({account:D.address,allowedTokens:te,candidateTokens:te,client:l,prioritizeCandidates:!0}):void 0),j=(()=>{let t=s?.mode??e.mode;if(t){if(!m.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=D.type===`json-rpc`?`push`:`pull`;return m.includes(n)?n:m[0]})(),re=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!o.expires)return e;let t=Math.floor(new Date(o.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(j===`push`){let{receipts:e}=D.type===`local`?{receipts:[await je(l,{account:D,calls:A,...ne?{feeToken:ne}:{},nonceKey:`expiring`,validBefore:re})]}:await ke(l,{account:D,...ne?{capabilities:{feeToken:ne}}:{},calls:A,experimental_fallback:A.length===1,forceAtomic:A.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return IS({challenge:o,payload:{hash:t,type:`hash`},source:aM({address:D.address,chainId:u})})}let M=()=>{if(p?.feePayer!==!0)return;let e=15e3,t=o.expires?new Date(o.expires).getTime():1/0,n=Date.now();if(!(t-n>=e))throw Error(`Sponsored challenge expires in less than 15 seconds; the fee payer would reject the transaction. Request a new challenge.`);if(!(re*1e3-n>=e))throw Error(`Sponsored transaction preparation took too long: less than 15 seconds of its validity window remain, so the fee payer would reject it.`)};M();let ie=await De(l,{account:D,calls:A,...ne?{feeToken:ne}:{},nonceKey:`expiring`,validBefore:re});if(ie.gas=(ie.gas??0n)+5000n,p?.feePayer){let e=ie;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return M(),IS({challenge:o,payload:{signature:await Me(l,ie),type:`transaction`},source:aM({address:D.address,chainId:u})})}}),s=new Map,c=async t=>{vM(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=s.get(i);return a||(a=o.createCredential(t).finally(()=>s.delete(i)),s.set(i,a)),a};return Ww({...o,createCredential:c},uM)}function uM(e){let t=fD.schema.credential.payload.safeParse(MS(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`||n.type===`zone`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(Ke.serializedType))return;let i=Ke.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&Ke.serialize(i)===r)return me(r)}async function dM(e){let{challenge:t,client:n,pending:r,zone:i,zoneId:a}=e,o=t.request.recipient,s=hM(t),c=r.get(s);if(!c){let t={sent:!1};c=gM(e,t),r.set(s,c),c.catch(()=>{t.sent||r.delete(s)})}let l=await c,u;try{u=await qE(n,{portal:UE(a),senderTag:l,timeoutMs:mM(t.expires,i.settlementTimeoutMs),to:o})}catch(e){throw new OS({cause:e,challengeId:t.id,senderTag:l,zoneId:a})}return r.delete(s),IS({challenge:t,payload:{hash:u,senderTag:l,type:`zone`,zoneId:a}})}function fM(e){let t=e?.settlementTimeoutMs;if(t!==void 0&&(!Number.isFinite(t)||t<0))throw Error("`zone.settlementTimeoutMs` must be a finite, non-negative number.");let n=e?.client.chain?.id;if(e?.zoneId===void 0||n===void 0||GE(n)===void 0)return;let r=WE(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function pM(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+bM}function mM(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function hM(e){return JSON.stringify(e)}async function gM(e,t){let{challenge:n,clientId:r,zone:i}=e,a=n.request,o=i.client.account;if(!o)throw Error("`zone.client` requires an account.");let s=BigInt(a.amount),c=a.currency,l=a.recipient,u=jj({challengeId:n.id,clientId:r,serverId:n.realm}),d=await Le.zone.getWithdrawalFee(i.client),[,f]=Le.zone.requestWithdrawal.calls({amount:s,fallbackRecipient:o.address,memo:u,to:l,token:c}),p=await De(i.client,{account:o,calls:[Le.token.approve.call({amount:s+d,spender:Re.zoneOutbox,token:c}),f]}),m=await Me(i.client,p);t.sent=!0;let h=me(m),g=await Ae(i.client,{serializedTransaction:m}).catch(e=>Pe(i.client,{hash:h,timeout:xM}).catch(()=>{let t=Error(`Zone withdrawal outcome is unknown: transaction ${h} may have been sent. Retrying this challenge does not withdraw again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),t}));if(g.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${g.transactionHash} reverted.`);let[_]=ge({abi:Fe.zoneOutbox,eventName:`WithdrawalRequested`,logs:g.logs});if(!_)throw Error("Zone withdrawal request did not emit `WithdrawalRequested`.");return KE({fallbackNonce:_.args.fallbackNonce,sender:_.args.sender,transactionHash:g.transactionHash})}function _M(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 _e(e,t)}}function vM(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)&&Dj(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 yM,bM,xM,SM=F((()=>{Qw(),VS(),kS(),RE(),xj(),kj(),nS(),Fj(),Vj(),Uj(),vk(),Yj(),tM(),cM(),$E(),hD(),yM=J.object({account:J.optional(J.custom()),autoSwap:J.optional(J.custom()),feeToken:J.optional(J.custom()),mode:J.optional(J.enum(nD))}),bM=15e3,xM=15e3}));function CM(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function wM(e){let t=k.encode(k.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return ne.keccak256(t)}function TM(e){return Ke.encodeForSigning(e)}function EM(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function DM(e,t){return ne.keccak256(j.concat(TM(e),t.sender))}var OM=F((()=>{RD()})),kM,AM,jM,MM,NM=F((()=>{kM=[{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`}],AM=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],jM={name:`descriptor`,type:`tuple`,components:kM},MM=[{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:[jM,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[jM,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[jM,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[jM],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[jM],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[jM],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:kM},{name:`state`,type:`tuple`,components:AM}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:AM}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:AM}]},{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 PM(e,t){return{name:WM,version:GM,chainId:t,verifyingContract:e}}function FM(e,t,n){return ue({domain:PM(e,t),types:qM,primaryType:`CloseAuthorization`,message:n})}function IM(e,t){return He.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function LM(e,t,n){return e.toLowerCase()===He.address.toLowerCase()?IM(t,n):ue({domain:PM(e,t),types:KM,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function RM(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function zM(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function BM(e,t){return Ie.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function VM(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===He.address.toLowerCase())try{return await BM(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return Ne(e,{account:t,domain:PM(r,i),types:KM,primaryType:`Voucher`,message:n})})(),o=We.from(a);if(!RM(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return We.serialize(o)}async function HM(e,t,n,r,i){let a=zM(t)?await t.sign({hash:FM(r,i,n),raw:!0}):await Ne(e,{account:t,domain:PM(r,i),types:qM,primaryType:`CloseAuthorization`,message:n}),o=We.from(a);if(!RM(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return We.serialize(o)}function UM(e,t,n,r){try{let i=We.from(n.signature);if(!RM(i.type)||We.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=LM(e,t,n),o=We.extractAddress({payload:a,signature:i});return We.verify(i,{address:o,payload:a})&&zE(o,r)}catch{return!1}}var WM,GM,KM,qM,JM=F((()=>{BE(),WM=`TIP20 Channel Reserve`,GM=`1`,KM={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},qM={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]}}));function YM(e){return typeof e==`object`&&!!e}function XM(e){return typeof e==`string`&&fe(e,{strict:!1})?e:void 0}function ZM(e){return XM(e.accessKeyAddress)}function QM(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(j.random(8))%e)}function $M(e){return ZM(e)??e.address}async function eN(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 tN(e,t){return await Me(e,t)}function nN(e,t,n=!1){let r=e.request.methodDetails,i=YM(r)?XM(r.escrowContract)??XM(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!iN(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!iN(i,a)?i:a}function rN(e,t,n,r){return IS({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function iN(e,t){return e.toLowerCase()===t.toLowerCase()}async function aN(e,t,n,r,i,a=LD){let o=wM({...n,chainId:i,escrow:a}),s=vD(r),c=await VM(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function oN(e,t,n,r,i,a=LD){let o=await aN(e,t,n,r,i,a),s=await HM(e,t,{channelId:o.channelId,cumulativeAmount:vD(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function sN(e,t,n){let r=$M(t),i=n.escrow??`0x4d50500000000000000000000000000000000000`,a=n.operator??`0x0000000000000000000000000000000000000000`,o=j.random(32),s=vD(n.deposit),c=vD(n.initialAmount),l=oe({abi:MM,functionName:`open`,args:[n.payee,a,n.token,s,o,r]}),u=await tN(e,await eN(e,{account:t,calls:[...n.prefixCalls??[],{to:i,data:l}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),d=Be.deserialize(u),f={authorizedSigner:r,expiringNonceHash:DM(EM({...n.feePayer?{feePayer:!0}:{},transaction:d}),{sender:t.address}),operator:a,payee:n.payee,payer:t.address,salt:o,token:n.token},p=wM({...f,chainId:n.chainId,escrow:i});return{action:`open`,type:`transaction`,channelId:p,transaction:u,signature:await VM(e,t,{channelId:p,cumulativeAmount:c},i,n.chainId),descriptor:f,cumulativeAmount:c.toString(),authorizedSigner:f.authorizedSigner}}async function cN(e,t,n,r,i,a,o=LD,s=[],c=n.token){let l=wM({...n,chainId:i,escrow:o}),u=vD(r);return{action:`topUp`,type:`transaction`,channelId:l,transaction:await tN(e,await eN(e,{account:t,calls:[...s,{to:o,data:oe({abi:MM,functionName:`topUp`,args:[n,u]})}],feePayer:a,feeToken:c,validAfter:QM()})),descriptor:n,additionalDeposit:u.toString()}}var lN=F((()=>{VS(),OM(),NM(),RD(),JM()}));function uN(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function dN(e){return uN({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function fN(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(dN(t),t)},delete(t){e.delete(t)}}}function pN(e){return{...e,cumulativeAmount:e.cumulativeAmount.toString(),deposit:e.deposit.toString()}}function mN(e){return{...e,cumulativeAmount:BigInt(e.cumulativeAmount),deposit:BigInt(e.deposit)}}function hN(e,t){xN.set(e,xN.get(t)??t)}async function gN(e,t,n){let r=bN.get(e);r||(r=new Map,bN.set(e,r));let i=(r.get(t)??Promise.resolve()).catch(()=>{}).then(n);r.set(t,i);try{return await i}finally{r.get(t)===i&&r.delete(t)}}function _N(e,t,n){return gN(xN.get(e)??e,`funding:${t}`,n)}async function vN(e,t){await gN(e,`write:${dN(t)}`,async()=>{let n=await e.get(dN(t));if(n?.origin!==void 0){if(t.origin!==void 0&&t.origin!==n.origin)throw Error(`SessionManager: stored channel origin mismatch`);t.origin=n.origin}if(n?.uncertainTopUp){if(n.channelId!==t.channelId)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);t.uncertainTopUp=!0}await e.set(t)})}async function yN(e,t){await gN(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}var bN,xN,SN=F((()=>{bN=new WeakMap,xN=new WeakMap}));function CN(e){if(e<0n||e>EN)throw new Y({reason:`amount exceeds uint96 range`})}async function wN(e,t,n=LD,r){return TN(await Oe(e,{address:n,abi:MM,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function TN(e){return CN(e.settled),CN(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}var EN,DN=F((()=>{kS(),NM(),RD(),EN=2n**96n-1n}));function ON(e){return`cumulativeAmount`in e}function kN(e){if(ON(e))return BigInt(e.cumulativeAmount)}async function AN(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await vN(e.store,t):await yN(e.store,dN(t)),e.notifyUpdate(t)}async function jN(e,t,n){let r=kN(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 AN(e,i))}function MN(e){return e?.action!==void 0}function NN(e){return MN(e)&&e.descriptor!==void 0}function PN(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 _e(i,t)}function FN(e,t,n,r){let i=PN(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function IN(e){return typeof e==`object`&&!!e}function LN(e){return typeof e==`string`&&fe(e,{strict:!1})?e:void 0}function RN(e){let t=e.request.methodDetails;return IN(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:LN(t.escrowContract),escrow:LN(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:LN(t.feeToken),operator:LN(t.operator),sessionSnapshot:Px(t,Rx.sessionSnapshot)}:{}}function zN(e,t){if(typeof e==`string`&&fe(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function BN(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function VN(e){return typeof e==`string`?e:void 0}async function HN(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=RN(n);(o.chainId!==void 0||i?.length===0)&&Dj(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});Ej(c,s);let l=s??c.chain?.id;if(Dj(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=nN(n,r,t),d=zN(n.request.recipient,`recipient`),f=zN(n.request.currency,`currency`);return{amount:BN(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:uN({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:VN(n.request.suggestedDeposit),token:f}}async function UN(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=wN}=e,o=wM({...r,chainId:i.chainId,escrow:i.escrow});WN({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 WN(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(!iN(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!iN(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!iN(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!iN(CM(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function GN(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function KN(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=PN(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function qN(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(!UM(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},CM(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await UN({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:$M(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 JN(e,t){return iN(e.address,t.payer)?iN($M(e),CM(t)):!1}function YN(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(MN(r)){if(!NN(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=GN({context:r,snapshot:o.snapshot});return!n&&s&&JN(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&JN(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 XN(e,t,n=!1){switch(e.type){case`open`:return QN(e,t,n);case`recover`:return $N(e,t);case`voucher`:return eP(e,t);case`manual`:return tP(e,t,n)}}async function ZN(e,t){if(e)return await Ij(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function QN(e,t,n){let{account:r,resolved:i}=e,a=aO({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await sN(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 ZN(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await AN(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function $N(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await UN({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:$M(n),token:o.token}}),l=KN({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`);sO(l,a);let u=await aN(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await AN(t,{...d?.channelId===c.channelId&&d.uncertainTopUp?{uncertainTopUp:!0}:{},channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function eP(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;sO(a,e.maxDeposit);let o=await aN(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await AN(t,r),o}async function tP(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=wM({...s,chainId:o.chainId,escrow:o.escrow});WN({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:$M(r),token:o.token});let l=await nP({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await jN(t,o.key,l),l}async function nP(e,t){switch(e.context.action){case`open`:return rP(e);case`topUp`:return iP(e,t);case`voucher`:return aP(e);case`close`:return oP(e)}}async function rP(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=FN(r,i,`cumulativeAmount`,`open`),c=await aN(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 iP(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=FN(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:cN(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await ZN(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function aP(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return aN(a.client,t,i,FN(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function oP(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return oN(a.client,t,i,FN(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}var sP,cP,lP,uP=F((()=>{Bx(),kj(),nS(),Vj(),DN(),OM(),JM(),lN(),SN(),SO(),sP=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),cP=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),lP=J.object({account:J.optional(J.custom()),autoSwap:J.optional(J.custom()),action:J.optional(J.enum([`open`,`topUp`,`voucher`,`close`])),channelId:J.optional(cP),cumulativeAmount:J.optional(Kx()),cumulativeAmountRaw:J.optional(J.string()),transaction:J.optional(sP),descriptor:J.optional(J.custom()),additionalDeposit:J.optional(Kx()),additionalDepositRaw:J.optional(J.string()),depositRaw:J.optional(J.string())})}));async function dP(e,t){let n=xP.get(e)??new Map;xP.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 fP(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function pP(e,t,n){try{let r=e.response?.headers.get(q.paymentReceipt);if(r){let e=DD(r);if(e.challengeId===t.id&&fP(n,e))return!0}}catch{}return e.challenges?.some(e=>kO(e)?fP(n,AO(e)):!1)??!1}function mP(e){let{currencies:t,decimals:n,expectedRecipients:r,maxAmount:i,maxAtomicAmount:a}=e;if((i!==void 0||a!==void 0)&&t===void 0)throw Error(`Tempo session maxAmount and maxAtomicAmount require currencies.`);return{currencies:t?.map(e=>e.toLowerCase()),expectedRecipients:r?new Set(r.map(e=>e.toLowerCase())):void 0,maxAmount:hP(i,n),maxAtomicAmount:a===void 0?void 0:BigInt(a)}}function hP(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo session maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo session maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return _e(e,t)}}function gP(e,t){if(e.currencies&&!e.currencies.includes(t.currency.toLowerCase()))throw Error(`Tempo session currency is not allowed: ${t.currency}.`);if(e.expectedRecipients&&(!t.recipient||!e.expectedRecipients.has(t.recipient.toLowerCase())))throw Error(`Unexpected session recipient: ${t.recipient}`);let n=BigInt(t.amount);if(e.maxAtomicAmount!==void 0&&n>e.maxAtomicAmount)throw Error(`Tempo session amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0&&n>e.maxAmount)throw Error(`Tempo session amount exceeds maxAmount.`)}function _P(e,t){try{return gP(e,t),!0}catch{return!1}}function vP(e){return typeof e==`object`&&!!e&&e.action===`close`}function yP(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=mP(e),m=Tj({chain:Qe,getClient:c,rpcUrl:_k}),h=bj({account:t}),g=l===void 0?void 0:_e(l,a),_=u===void 0?void 0:_e(u,a),v=e.origin===void 0?void 0:new URL(e.origin);if(v&&![`http:`,`https:`].includes(v.protocol))throw Error(`Session origins require HTTP or HTTPS`);let y=i??fN(),b={store:y,notifyUpdate:e=>d?.(e)},x=async(e,t,n)=>{let r=h(e.client,t),i=t?.action?t.descriptor:n?.descriptor??GN({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:CM(i)}:{}}})??r},S=async(e,t,n)=>YN({account:await x(e,t,n),entry:n,context:t,decimals:a,maxDeposit:g,resolved:e}),C=LE(pD,{canHandleChallenge:({challenge:e,context:t})=>kO(e)&&(vP(t)||t===xC||_P(p,e.request)),context:lP,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&gP(p,t.request);let a=await HN({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m}),c=Hw(e),l=qw(e)??v?.origin;if(l!==void 0&&(l===`null`||![`http:`,`https:`].includes(new URL(l).protocol)))throw Error(`Session payments require an HTTP or HTTPS origin`);if(v&&l!==v.origin)throw Error(`Session channel origin mismatch`);let u={...b,origin:l},d=()=>{};try{let e=!MN(i)&&i?.descriptor===void 0;e&&(d=await dP(y,a.key),c&&(await y.get(a.key))?.opened&&await c.prepare());let n=await y.get(a.key);if(n&&n.origin!==l)throw Error(`Session channel origin mismatch`);if(l&&!n&&a.snapshot&&!i?.descriptor&&!v)throw Error(`Session snapshot recovery requires an explicitly configured origin or descriptor`);let o=await S(a,i,n);if(!e&&c&&o.type===`open`){d=await dP(y,a.key);let e=await y.get(a.key);if(e&&e.origin!==l)throw Error(`Session channel origin mismatch`);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await y.get(a.key)),o=await S(a,i,n))}let s,f=c&&o.type===`open`?{store:{get:e=>y.get(e),async set(e){s=l?{...e,origin:l}:e},delete:e=>y.delete(e)},notifyUpdate(){}}:u,p=await rN(t,await XN(o,f,Lj(i?.autoSwap??r,zj)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||pP(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await y.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await vN(y,e),b.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function w(e,t,n){let r={challenge:e,context:t};return Kw(r,bP(n)),C.createCredential(r)}let T=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>_N(y,dN(n),async()=>{s?.throwIfAborted();let c=await y.get(dN(n));if(c?.channelId===n.channelId&&(n=c),n.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let l=n.deposit>r?n.deposit:r,u=oO({deposit:l,maxDeposit:g,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:_});u>0n&&await IO({autoSwap:e,additionalDeposit:u,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>w(e,t,a),onUncertainFunding:async e=>{let t=await y.get(dN(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await vN(y,n),b.notifyUpdate(n)},fetch:i,input:a,signal:s});let d=l+u;if(d===n.deposit)return;let f=await y.get(dN(n)),p=f?.channelId.toLowerCase()===n.channelId.toLowerCase()?f:n,m={...p,deposit:p.deposit>d?p.deposit:d};await vN(y,m),b.notifyUpdate(m)});return Nw(C,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!kO(e))return;let c=t===void 0?void 0:lP.parse(t);if(MN(c))return;gP(p,e.request);let l=await HN({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await y.get(l.key);if(!u?.opened)return;let d=bP(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,h=u.cumulativeAmount+wD(e),g=f?BigInt(f.requiredCumulative):h,_=g>h?g:h,v=f?BigInt(f.deposit):u.deposit,b=v>u.deposit?v:u.deposit;_<=b&&b===u.deposit||!JN(await x(l,c,u),u.descriptor)||await T({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:b,fetch:r,input:i,requiredCumulative:_,signal:a})}),zw(C,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!kO(e))return u;if(!OD(u))return CD(MS(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await HN({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await y.get(f),h={assertVoucherWithinLocalLimit:e=>sO(e,g),createSessionCredential:(e,t)=>w(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await T({autoSwap:t===void 0?void 0:lP.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return qO({onNeedVoucher:(t,n)=>JO({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function bP(e){let t=new URL(e instanceof Request?e.url:e,globalThis.location===void 0?void 0:globalThis.location.href);if(![`http:`,`https:`].includes(t.protocol))throw Error(`Session payments require an HTTP or HTTPS origin`);return t.origin}var xP,SP=F((()=>{Rw(),Qw(),Bx(),VS(),SC(),RE(),xj(),kj(),Vj(),vk(),hD(),OM(),RD(),lN(),SN(),uP(),SO(),xP=new WeakMap}));function CP(e,t){TP.set(e,t)}function wP(e){let t=TP.get(e);if(!t)throw Error(`Session manager internals are unavailable.`);return t}var TP,EP=F((()=>{TP=new WeakMap}));function DP(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 OP(e){let t=DP(`close-ready`),n=DP(`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 kP=F((()=>{}));function AP(e){return e.method===Ix.tempo&&e.intent===Lx.charge}function jP(e){if(!AP(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function MP(e,t,n){if(!n)return t;let r={...cT(MO(e)?e.headers:void 0),...cT(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===q.paymentSession.toLowerCase())?t:{...t,headers:{...r,[q.paymentSession]:n}}}function NP(e,t){return e===void 0?t:{...lP.parse(e),...t}}function PP(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:_e(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:_e(e.topUpAmount,t),WebSocket:n}}function FP(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&Dj(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=PP(e),i;function a(e){let t=new URL(MO(e)?e.url:String(e),typeof location>`u`?void 0:location.href);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`SessionManager: session payments require an HTTP origin`);let n=t.origin;if(i!==void 0&&i!==n)throw Error(`SessionManager: session payment origin mismatch`);return i=n,n}let o=AT(r.fetch),s=jT(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(MO(e)?e.redirect:void 0))===`manual`?`manual`:`error`});if(r.url&&new URL(r.url).origin!==n)throw Error(`SessionManager: session response origin mismatch`);return r};let c=r.fetch;o&&(r.fetch=KS(c,o));let l=Tj({chain:Qe,getClient:e.client?()=>e.client:e.getClient,rpcUrl:_k}),u=bj({account:e.account}),d=pO(),f=e.credentialContext===void 0?void 0:NP(e.credentialContext,{}),p=OP({getSocketSession:()=>d.socketSession}),m=e.channelStore??fN(),h=new Set,g;async function _(e){let t=await m.get(e);if(t?.opened&&!h.has(t.channelId)){if(t.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return t}}let v=e=>{if(e.origin!==void 0&&e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return e.origin=i,vN(m,e)},y={async get(e){let t=await _(e);return t&&g&&(g.seenExisting.add(e),!g.committed&&!g.created.has(e)&&(g.resumed??=t)),t},async set(e){let t=dN(e);e.opened&&h.delete(e.channelId),g?.trackCreates&&!g.seenExisting.has(t)&&g.created.set(t,e),await v(e)},delete:e=>yN(m,e)};hN(y,m);async function b(e){let t=dN(e),n=await m.get(t);if(e.uncertainTopUp||n?.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);h.add(e.channelId),g?.seenExisting.delete(t),g?.resumed===e&&(g.resumed=void 0),await Promise.resolve(yN(m,t)).catch(()=>void 0)}async function x(){let e=g;if(e?.created.size){for(let[t,n]of e.created){let e=await m.get(t);if(n.uncertainTopUp||e?.channelId===n.channelId&&e.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before discarding the channel.`);h.add(n.channelId),await Promise.resolve(yN(m,t)).catch(()=>void 0)}e.created.clear(),await fe(e.committed??e.previous)}}function S(e){let t=Px(e.request.methodDetails,Rx.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=g;if(!n?.created.size||!d.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&d.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=vO({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return XD(d,e)}function w(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function T(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=vO({channel:d.channel,spent:d.spent,state:d.state}))}let E=yP({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}}),ee=Iw(E);ee&&Nw(E,e=>ce(()=>Promise.resolve(ee(e)),e.signal)),Bw(E);let D=lM({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),O=oT({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[E],onChallenge:async(e,t)=>{if(!OO(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&iS(e)===iS(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await fe(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function k(e,t){let n={challenge:e,context:NP(f,t)};return i&&Kw(n,i),E.createCredential(n)}function A(e){mO({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function te(e=d.state.status===`active`?d.state.units:0){!d.channel||!d.lastChallenge||d.state.status!==`active`&&d.state.status!==`withdrawable`&&d.state.status!==`closeRequested`&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function ne(t){let n=t.headers.get(q.paymentSessionSnapshot);if(!n)return;let r=BD(n);Dj(e.allowedChainIds,r.chainId);let i=await l({chainId:r.chainId});Ej(i,r.chainId);let a=u(i),{entry:o,spent:s}=await qN({account:await e.resolveAccount?.({account:a,chainId:r.chainId,operation:{authority:CM(r.descriptor),kind:`authorizePaymentChannel`}})??a,client:i,snapshot:r});return oe(o.cumulativeAmount),await Promise.resolve(y.set(o)).catch(()=>void 0),d.channel=o,d.spent=s,o}async function j(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=MO(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=MO(t)?t.url:t,l={...s,method:`HEAD`,headers:{...cT(i),...cT(n?.headers),[q.acceptPayment]:`${Ix.tempo}/${Lx.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await ne(t);let n=mS(t).find(AP);if(!n||!jP(n))return;let i=new URL(String(c),typeof location<`u`?location.href:void 0);if(t.url&&new URL(t.url).origin!==i.origin)return;$w(n,i,e.trustedTempoProofRealms);let a=await D.createCredential({challenge:n,context:{}}),o=await r.fetch(c,QC({...l,redirect:`manual`},vS(n),a));return o.ok?await ne(o):void 0}catch{return}}function re(e,t){let n=d.socketSession;return gO({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:d.channel?.channelId===t?d.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:d.spent,tickCost:n?.tickCost})}function M(e,t){let n=AO(t);if(!n)return;if(wM({...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 ie(e,t){let n=M(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(d.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>d.spent&&(d.spent=i),n}function ae(e,t=e.challenge,n=!1){let r=(n?ie(e,t):M(e.channel,t))?.acceptedCumulative??re(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return oe(r),r.toString()}function oe(e){tO({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let se,N;async function ce(e,t){if(N)throw N;for(;;){let e=se;if(!e)break;if(!t)await e;else{t.throwIfAborted();let n;try{await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0})})])}finally{t.removeEventListener(`abort`,n)}}}if(t?.throwIfAborted(),N)throw N;let n=e();se=n;try{return await n}catch(e){throw e instanceof dk&&(N=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{se===n&&(se=void 0)}}async function le(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return _N(m,dN(d.channel),async()=>{let{knownDeposit:t,...n}=e,i=d.channel?await y.get(dN(d.channel)):void 0;if(i?.channelId===e.channelId&&i.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let a=await IO({...n,channel:d.channel,createSessionCredential:k,fetch:r.fetch,onUncertainFunding:async e=>{let t=await y.get(dN(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};d.channel?.channelId===e.channelId&&(d.channel=n),await y.set(n),T(n)}});A(a);let o=d.channel,s=EO({additionalDeposit:e.additionalDeposit,channel:d.channel,channelId:e.channelId,challengeId:d.lastChallenge?.id,currentState:d.state,knownDeposit:t,receipt:a,spent:d.spent});if(s?.channel&&d.lastChallenge){let e=s.channel;for(;;){await y.set(e);let t=d.channel;if(t===o)break;if(!t)return a;let n=s.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,o=t}if(e.channelId!==s.channel.channelId)return a;d.channel=e,C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}return a})}async function ue(e){return ce(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=oO({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 le({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function de(e,t){let n=_O({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(C({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function fe(e){let t=yO(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function pe(e){let t=e.headers.get(q.paymentReceipt),n=t?DD(t):null;return A(n),Object.assign(e,{receipt:n,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function me(e,t){if(g)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a(e),d.lastUrl=e,d.lastHeaders=t?.headers;let n=vO({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await j(e,t),i.trackCreates=!0;let a=MP(e,t,d.channel?.opened?d.channel.channelId:void 0);f&&(a={...a,context:f});let o=!n.channel?.opened;async function s(){let n=i.resumed;return!o||!n?!1:(o=!1,await b(n),a=MP(e,t,void 0),!0)}for(;;){let t;try{t=await O(e,a)}catch(e){if(i.created.size?await x():await fe(i.committed??n),await s())continue;throw e}let o=pe(t),c=!1;if(o.status===402){let t=await RO({input:e,init:a,response:o,createSessionCredential:k,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:de,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:ue});t&&(c=!0,o=pe(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await fe(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function he(e){let t=await BO({createSessionCredential:k,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>ae(e,t,!0),signedCloseAmount:ae(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(te(),C({type:`closeStarted`}),C({type:`closed`,receipt:t})),t}let ge={createSessionCredential:k,doFetch:me,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:oe,acceptReceipt(e){A(e)},topUpIfNeeded:ue},_e={get channelId(){return d.channel?.channelId},get cumulative(){return d.channel?.cumulativeAmount??0n},get opened(){return d.channel?.opened??!1},get state(){return d.state},fetch:me,async topUp(e){let t=TO({amount:e,assertVoucherWithinLocalLimit:oe,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return ce(async()=>{if(d.channel?.channelId!==t.channelId||d.lastChallenge!==t.challenge||d.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=TO({amount:e,assertVoucherWithinLocalLimit:oe,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return le({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){return VO(e,t,ge)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=PO(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await j(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await XO({async createSessionCredential(e,i){return d.lastChallenge=e,await Fw(E,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),k(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:MP(n,i,o),signal:t?.signal});return d.lastChallenge=s,tk({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:k,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await YO({fetch:r.fetch,input:l,probeInit:MP(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:oe,acceptReceipt:A,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:ue,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=cO({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===ck.OPEN){let r=await bO({activeSocket:n,createSessionCredential:k,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return te(),C({type:`closeStarted`}),C({type:`closed`,receipt:r}),r}return he(t)}};return CP(_e,{consumeSseResponse(e,t,n){let r=a(e);if(t.url&&new URL(t.url).origin!==r)throw Error(`SessionManager: session response origin mismatch`);return HO(e,t,n,ge)},rehydrate({channel:e,challenge:t,input:n,spent:r}){let i=a(n);if(e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!OO(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.`);oe(e.cumulativeAmount);let o=M(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,C({type:`challengeReceived`,challengeId:t.id}),C({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),_e}var IP=F((()=>{CS(),$T(),Rw(),Qw(),rT(),ew(),Bx(),ZS(),xj(),kj(),SM(),vk(),SN(),uP(),SP(),OM(),RD(),qD(),EP(),kP(),SO(),fk(),(function(e){e.serializeSnapshot=zD,e.deserializeSnapshot=BD})(FP||={})}));function LP(e){return e instanceof Date?e:new Date(e)}function RP(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 zP(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=iF[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>rF)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 BP(e){let{challengeExpires:t,request:n}=e;zP(n);let r=RP(LP(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 VP(e){let t=eF(e.currency,`currency`),n=eF(e.recipient,`recipient`);return[{address:t,selector:nF,recipients:[n]}]}function HP(e){try{let t=j.fromBytes(A.toBytes(e));if(j.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function UP(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=GP({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 WP(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=KP(i.signature),s=qP(o);if(JP({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==HP(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return YP(o,a),ZP(XP(o),a),QP(o.scopes,a),{authorization:o,source:{address:$P(o,s),chainId:r}}}function GP(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return Ue.from({address:eF(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:RP(LP(i.subscriptionExpires)),limits:[{token:eF(i.currency,`currency`),limit:BigInt(i.amount),period:zP(i)}],scopes:VP(i),type:t.keyType,witness:HP(n)})}function KP(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 qP(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function JP(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new Y({reason:`keyAuthorization chainId mismatch`});if(t){if(!pe(n.address,eF(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 YP(e,t){if(BP({request:t}),e.expiry!==RP(LP(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function XP(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 ZP(e,t){if(!pe(e.token,eF(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!==zP(t))throw new Y({reason:`keyAuthorization period mismatch`})}function QP(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=eF(t.currency,`currency`),r=eF(t.recipient,`recipient`),i=new Set;for(let t of e){if(!pe(t.address,n))throw new Y({reason:`keyAuthorization call target mismatch`});let e=tF(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||!pe(t.recipients[0],r))throw new Y({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new Y({reason:`keyAuthorization must allow transferWithMemo`})}function $P(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 eF(e,t){if(!fe(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function tF(e){return typeof e==`string`?e.toLowerCase():``}var nF,rF,iF,aF=F((()=>{kS(),nF=`0x95777d59`,rF=(1n<<64n)-1n,iF={dev_second:1n,day:86400n,week:604800n}}));function oF(e={}){let t=Tj({chain:P,getClient:e.getClient,rpcUrl:_k}),n=bj({account:e.account});return LE(mD,{context:lF,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??pk.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.");cF(r.request),await e.validateRequest?.(r.request);let l=await sF(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=WP({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:Ue.serialize(l),type:`keyAuthorization`},request:r.request});if(!pe(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return IS({challenge:r,payload:{signature:Ue.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function sF(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await UP({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:RP(LP(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:j.fromNumber(BigInt(o.amount)),period:zP(o)}],scopes:VP(o),witness:HP(i)}]});return Ue.fromRpc(c.keyAuthorization)}function cF(e){zP(e),RP(LP(e.subscriptionExpires))}var lF,uF=F((()=>{VS(),RE(),xj(),kj(),nS(),vk(),hD(),aF(),lF=J.object({accessKey:J.optional(J.custom()),account:J.optional(J.custom())})}));function dF(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[lM(e),fF(n)]}var fF,pF=F((()=>{SP(),IP(),SM(),uF(),fF=Object.assign(yP,{manager:FP}),(function(e){e.charge=lM,e.common=dF,e.session=fF,e.subscription=oF})(dF||={})})),mF=F((()=>{SM(),pF(),uF(),SP(),IP()})),hF=rt({orderTempoChargeChallengesByBalance:()=>_F,readTempoKeystore:()=>LF,resolveTempoAccount:()=>RF,tempo:()=>vF});async function gF(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}async function _F(e,t){let n=[],r=[];for(let[t,i]of e.entries())TF(i)&&(n.push(t),r.push(i));if(r.length<2)return[...e];let i=await EF(t).catch(()=>void 0);if(!i)return[...e];let a=await Promise.all(r.map(async(e,t)=>({challenge:e,index:t,score:await DF(e,i)})));a.sort((e,t)=>KF.indexOf(e.score)-KF.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 vF(){let e;return oj({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:t,options:n,methodOpts:r}){let i=eA(n.account),a=t.request,o=a.currency,s=wF(r),c=jF({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()||(kk(i)?void 0:await tA(i).get());if(!h&&kk(i)&&zF()){m=!0;let e=RF(i);if(e){let r=Nk(n.rpcUrl,{network:n.network});p=M({chain:await Fk({network:n.network,rpcUrl:r}),transport:de(r)}),kF({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let i=o?await zk(p,o,e.wallet_address).catch(()=>void 0):void 0;l=i?.symbol??o??``,u=i?.decimals??a.decimals??6}}else if(h)f=xe(h);else{let e=VF();if(e){let t=await tA(e).get();t&&(f=xe(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=Nk(n.rpcUrl,{network:n.network});p=M({chain:await Fk({network:n.network,rpcUrl:e}),transport:de(e)}),kF({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let r=o?await zk(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 BF(t)}};if(!f||!p)throw new I({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let g=dF({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??(Rk(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=NF(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 VM(p,f,c,i,a);return IS({challenge:t,payload:{action:o,channelId:n,...o===`close`?{closeSignature:await HM(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=MS(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(e.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${X.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
238
238
  `}${X.dim(`Channel opened ${h.payload.channelId}`)}${t}\n`)}else m(`${l?``:`
239
- `}${X.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(q.paymentReceipt);if(w)try{let e=JSON.parse(O.toString(w));vF(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&MF(v,S),s>=1&&_F(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
240
- `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await yF(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 mF(C),v&&y&&b&&(l&&m(`
241
- `),l&&!await t.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await bF({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 _F(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(`(${Ak(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,wk(`${t.explorerUrl}/tx/${o}`,o)]):n.push([a,String(o)]):n.push([a,e])}n.sort(([e],[t])=>e.localeCompare(t));let a=Math.max(...n.map(([e])=>e.length));for(let[e,r]of n)t.info(` ${X.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
242
- `)}function vF(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 yF(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 xF():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{_F(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
239
+ `}${X.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(q.paymentReceipt);if(w)try{let e=JSON.parse(A.toString(w));bF(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&PF(v,S),s>=1&&yF(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
240
+ `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await xF(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 gF(C),v&&y&&b&&(l&&m(`
241
+ `),l&&!await t.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await SF({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 yF(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(`(${Mk(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,Ek(`${t.explorerUrl}/tx/${o}`,o)]):n.push([a,String(o)]):n.push([a,e])}n.sort(([e],[t])=>e.localeCompare(t));let a=Math.max(...n.map(([e])=>e.length));for(let[e,r]of n)t.info(` ${X.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
242
+ `)}function bF(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 xF(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 CF():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{yF(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
243
243
 
244
244
  `})}catch{}o=``;continue}if(e.length===0)u(`
245
245
  `);else try{let t=JSON.parse(e);u(t.token??t.choices?.[0]?.delta?.content??e)}catch{u(e)}o=``}}};for(;;){let{done:e,value:t}=await r.read();if(e)break;a+=i.decode(t,{stream:!0});let n=a.split(`
246
- `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await bF({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 bF(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:{...sT(e.fetchInit.headers),Authorization:t}});if(n.ok){if(NF(e.channelId),e.verbose>=1){let t=n.headers.get(q.paymentReceipt),r;if(t)try{let e=JSON.parse(O.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${X.dim(wk(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${Ak(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 xF(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 SF(e){return EF(HF,e,UF)}function CF(e){return e.method===`tempo`&&e.intent===`charge`}async function wF(e){let t=Qk(e.options.account),n=process.env.MPPX_PRIVATE_KEY?.trim()||(Dk(t)?void 0:await $k(t).get()),r;if(n)r=ye(n).address;else if(Dk(t)&&LF())r=IF(t)?.wallet_address;else{let e=zF();if(e){let t=await $k(e).get();t&&(r=ye(t).address)}}if(!r)return;let i=jk(e.options.rpcUrl,{network:e.options.network}),a=M({chain:await Nk({network:e.options.network,rpcUrl:i}),transport:P(i)});return{account:r,client:a}}async function TF(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 EF(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 DF(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new L({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function OF(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function kF(e){let t=OF(e.tokenIn)??OF(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 AF(){return c.join(process.env.XDG_CONFIG_HOME||c.join(b.homedir(),`.config`),`mppx`,`channels`)}function jF(e){try{let n=t.readFileSync(c.join(AF(),e),`utf-8`).trim();return n?BigInt(n):void 0}catch{return}}function MF(e,n){let r=AF();t.mkdirSync(r,{recursive:!0}),t.writeFileSync(c.join(r,e),n.toString(),`utf-8`)}function NF(e){try{t.unlinkSync(c.join(AF(),e))}catch{}}function PF(){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 FF(){try{let e=t.readFileSync(PF(),`utf-8`),n=[],r;for(let t of e.split(`
247
- `)){let e=t.trim();if(e===`[[keys]]`){r?.wallet_address&&n.push(r),r={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!r)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?r.wallet_type=o:a===`wallet_address`?r.wallet_address=o:a===`chain_id`&&(r.chain_id=Number.parseInt(o,10))}return r?.wallet_address&&n.push(r),n}catch{return[]}}function IF(e){let t=FF();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 LF(){if(GF!==void 0)return GF;try{m.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),GF=!0}catch{GF=!1}return GF}async function RF(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 zF(){let e=Zk();if(Dk(e.get())&&!LF()&&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]===BF&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}var BF,VF,HF,UF,WF,GF,KF=I((()=>{Mx(),QT(),zx(),BS(),fF(),ID(),KM(),aA(),Gk(),aj(),BF=`mppx`,VF=p.union([p.boolean(),p.literal(`true`).transform(()=>!0),p.literal(`false`).transform(()=>!1)]),HF=p.object({allowCustomEscrow:p.optional(VF),autoSwap:p.optional(VF),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())}),UF=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`],WF=[`payable`,`unknownBalance`,`insufficientBalance`,`unsupported`]}));eC(),aA(),aj();const qF=[...Object.entries(fA),...Object.entries(pA),...Object.entries(mA),...Object.entries(hA)];function JF(){return ij({method:`evm`,supports:YF,async setup({challenge:e,options:t}){let n=e.request,r=n.network?XF(SA(n.network)):void 0,i=n.network&&n.asset?qF.find(([,e])=>bA(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`?uA({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await nA(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...rj({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function YF(e){if(!QS(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 XF(e){return Object.values(Ye).find(t=>t.id===e)}SS(),xC(),Ux(),KF();const ZF=[gF(),hj(),oj(),JF()];async function QF(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 $F(e,t){let n=t?.plugins?.find(t=>rI(t,e));if(n)return{plugin:n};let r=nI(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=ZF.find(t=>rI(t,e));return a?{plugin:a}:{}}function eI(e,t){let n=nI(t);if(n?.length){let r=aC(e,n,nC(n,t?.paymentPreferences).entries);if(r){let e=t?.plugins?.find(e=>rI(e,r.challenge));return{challenge:r.challenge,...e?{plugin:e}:{method:r.method}}}return}for(let n of e){let e=$F(n,t);if(e.plugin||e.method)return{challenge:n,...e}}}function tI(e){let t=nI(e);if(t?.length)return nC(t,e?.paymentPreferences).header}function nI(e){return Array.isArray(e?.methods)?e.methods.flat():void 0}function rI(e,t){return e.supports?e.supports(t):e.method===t.method}async function iI(e){let t=aI(e);if(!t)return;let n=await import(t);return{config:n.default??n,path:t}}function aI(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 oI(e,t){function n(t){let n={...t.request};if(t.method===`tempo`&&t.intent===`session`){let e={...n.methodDetails};delete e.sessionSnapshot,Object.keys(e).length?n.methodDetails=e:delete n.methodDetails}let{meta:r,opaque:i,...a}=t;return JSON.stringify([rS({...a,request:n,id:e.id,expires:e.expires}),sI(t)])}if(n(t)!==n(e))throw Error(`Payment request changed on retry. Run the command again to approve the new payment.`)}function sI(e){let t=e.opaque??(e.meta?Hx(e.meta):void 0);if(t===void 0)return;let n;try{n=Bx(t)}catch{return t}if(typeof n!=`object`||!n||Array.isArray(n))return t;let r=cA(n);return r?Hx(r):void 0}KF(),SS(),nT(),sN(),wP(),PP(),uk();function cI(e){return e??globalThis.fetch.bind(globalThis)}function lI(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(eN(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Error(`Close challenge changed the session escrow.`);let r=OO(e);if(r&&r.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Close challenge changed the session channel.`)}async function uI(e){lI(e.challenge,e.channel);let t=e.channel;if(t.origin===void 0){let n=new URL(e.input instanceof Request?e.input.url:e.input);if(![`http:`,`https:`].includes(n.protocol))throw Error(`Legacy session close requires an HTTP origin`);Qw(e.challenge,n,e.manager.trustedTempoProofRealms),t={...t,origin:n.origin}}let n=cI(e.fetch),r,i=async(t,i)=>{r&&=(await e.onChallenge?.(r),void 0);let a=await n(t,i);if(a.status!==402)return a;let o=pS(a).find(EO);if(!o)throw Error(`Refreshed close response did not include tempo/session.`);return lI(o,e.channel),r=o,a},a=NP({...e.manager,bootstrap:!1,escrow:e.channel.escrow,fetch:i});SP(a).rehydrate({...e,channel:t}),t!==e.channel&&await e.manager.channelStore?.set(t);let o=await a.close();if(!o)throw Error(`Session close response did not include a payment receipt.`);return{manager:a,receipt:o}}SS(),sN(),bN(),uk(),EM(),tS();var dI=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}},fI=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 pI=J.object({origin:J.optional(J.string()),channelId:Zx(),cumulativeAmount:J.string(),deposit:J.string(),descriptor:J.object({payer:Xx(),payee:Xx(),operator:Xx(),token:Xx(),salt:Zx(),authorizedSigner:Xx(),expiringNonceHash:Zx()}),escrow:Xx(),chainId:J.number(),opened:J.boolean()}),mI=J.object({name:J.optional(J.string()),address:Xx()}),hI=J.object({method:J.literal(`tempo`),intent:J.literal(`session`),status:J.literal(`success`),timestamp:J.string(),reference:J.string(),challengeId:J.string(),channelId:Zx(),acceptedCumulative:J.string(),spent:J.string(),units:J.optional(J.number()),txHash:J.optional(Zx())}),gI=J.object({version:J.literal(1),method:J.literal(`tempo`),intent:J.literal(`session`),status:J.enum([`opening`,`open`,`closing`,`stale`]),channel:pI,account:mI,endpoint:J.string(),challenge:xS,receipt:J.optional(hI),spent:J.string(),units:J.number(),createdAt:J.string(),updatedAt:J.string()}),_I=J.object({version:J.literal(1),channelId:Zx()}),vI=J.object({version:J.literal(1),scope:J.string(),hostname:J.string(),pid:J.number(),token:J.string(),createdAt:J.string()});function yI(e,t,n,r){let i=e.safeParse(t);if(!i.success)throw Z(n,r,i.error);return i.data}function bI(e){let t=AI(e);return[t.payer,t.payee,t.token,t.escrow,t.chainId].join(`:`)}function xI(e){return{payer:e.descriptor.payer,payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId}}function SI(e={}){let t=e.stateRoot??wI(),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??nL;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=OI(e),r=TI(n,t),i=await qI(r);if(i===void 0)return;let a=RI(i,r);if(a.channel.channelId.toLowerCase()!==t)throw Z(r,`Session filename does not match its channel ID.`);return zI(a)}async function u(){let e;try{e=await C.readdir(n.channels,{withFileTypes:!0})}catch(e){if(iL(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);OI(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=PI(e.channel),r=OI(t.channelId),i=TI(n,r),o=await qI(i),c=o===void 0?void 0:RI(o,i);c&&BI(c,e,i);let l=c?.channel.origin??t.origin;if(c?.channel.origin&&t.origin&&c.channel.origin!==t.origin)throw Z(i,`Session payment origin mismatch.`);if(l!==void 0&&new URL(l).origin!==l)throw Z(i,`Session payment origin must be a normalized origin.`);let u=II(e.challenge,i);HI(u,t,i);let d=e.receipt?LI(e.receipt,t.channelId,i):void 0,f=c?fN(c.channel):void 0,p=KI(t.cumulativeAmount,f?.cumulativeAmount??0n),m=KI(e.spent??0n,d?BigInt(d.spent):0n,c?BigInt(c.spent):0n);if(m>p)throw Z(i,`Session spend exceeds the locally authorized cumulative amount.`);let h=FI(dN({...t,cumulativeAmount:p,...l!==void 0&&{origin:l}}),i),g=GI(c?.updatedAt,a(),i),_=WI(c?.receipt,d),v=NI(e.account,i),y=RI({version:1,method:`tempo`,intent:`session`,status:e.status,channel:h,account:{...v.name===void 0?c?.account.name===void 0?{}:{name:c.account.name}:{name:v.name},address:v.address},endpoint:MI(e.endpoint,i),challenge:u,..._!==void 0&&{receipt:_},spent:m.toString(),units:Math.max(c?.units??0,e.units??0,d?.units??0),createdAt:c?.createdAt??g,updatedAt:g},i);return await JI(i,y),zI(y)}async function f(e){let t=DI(n,e),r=await qI(t);if(r===void 0)return;let{channelId:i}=yI(_I,r,t,`Preferred session is invalid.`),a=await l(i);if(!a)throw Z(t,`Preferred session ${i} does not exist.`);return UI(a.channel,e,t),i}async function p(e,t){let r=OI(t),i=await l(r),a=DI(n,e);if(!i)throw Z(a,`Session ${r} does not exist.`);UI(i.channel,e,a),await JI(a,{version:1,channelId:r})}async function m(e,t){let r=DI(n,e),i=t===void 0?void 0:OI(t),a=await qI(r);if(a===void 0)return;let o=yI(_I,a,r,`Preferred session is invalid.`).channelId;i&&o.toLowerCase()!==i||await eL(r,`Unable to clear preferred session.`)}async function h(e){let t=OI(e),r=await l(t);r&&(await m(xI(r.channel),t),await eL(TI(n,t),`Unable to remove session.`))}async function g(e){await s();let t=EI(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 YI(t,n),await QI(ZI(t))){await $I(t,n);continue}return{async release(){await $I(t,n)}}}catch(e){if(!iL(e,`EEXIST`))throw e}let s=await qI(t);if(s===void 0)continue;let c=yI(vI,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 fI(e,c);await XI(t,c)}let c=await qI(t);throw c===void 0?Z(t,`Unable to acquire session lock.`):new fI(e,yI(vI,c,t,`Session lock is invalid.`))}async function v(e){return g(bI(e))}return{root:t,get:l,list:u,upsert:d,remove:h,getPreferred:f,setPreferred:p,clearPreferred:m,acquire:v}}function CI(e,t){let n=jI(t.scope),r=t.selection===`auto`||t.selection===`new`?void 0:OI(t.selection);function i(e){if(e.toLowerCase()!==n)throw new dI(`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 dI(`Session ${i} does not exist.`);if(UI(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(lN(n)),UI(n,t.scope),r&&r.toLowerCase()!==n.channelId.toLowerCase())throw new dI(`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 wI(){let e=process.env.XDG_STATE_HOME||c.join(b.homedir(),`.local`,`state`);return c.join(e,`mppx`,`sessions`,`v1`)}function TI(e,t){return c.join(e.channels,`${t}.json`)}function EI(e,t){let n=g(`sha256`).update(t).digest(`hex`);return c.join(e.locks,`${n}.lock`)}function DI(e,t){let n=g(`sha256`).update(bI(t)).digest(`hex`);return c.join(e.preferred,`${n}.json`)}function OI(e){return yI(Zx(),e,void 0,`Invalid session channel ID: ${e}.`).toLowerCase()}function kI(e,t,n){return yI(Xx(),e,n,`Invalid ${t}.`).toLowerCase()}function AI(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<0)throw new dI(`Invalid session chain ID.`);return{payer:kI(e.payer,`session payer`),payee:kI(e.payee,`session payee`),token:kI(e.token,`session token`),escrow:kI(e.escrow,`session escrow`),chainId:e.chainId}}function jI(e){let t=AI(e);return[t.payee,t.token,t.escrow,t.chainId].join(`:`)}function MI(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 NI(e,t){return yI(mI,e,t,`Session account is invalid.`)}function PI(e){return fN(FI(dN(e)))}function FI(e,t){return yI(pI,e,t,`Stored session channel is invalid.`)}function II(e,t){let n=xS.safeParse(e);if(!n.success||!EO(n.data))throw Z(t,`Stored session challenge is invalid.`);return n.data}function LI(e,t,n){let r=yI(hI,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 RI(e,t){let n=yI(gI,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?LI(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=MI(n.endpoint,t);if(u!==n.endpoint)throw Z(t,`Stored session endpoint contains a fragment.`);let d=II(n.challenge,t);return HI(d,fN(a),t),{...i,account:o,channel:a,endpoint:u,challenge:d,...s&&{receipt:s}}}function zI(e){return{version:1,status:e.status,channel:fN(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 BI(e,t,n){let r=PI(t.channel),i=NI(t.account,n),a=fN(e.channel);if(JSON.stringify(VI(r))!==JSON.stringify(VI(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 VI(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 HI(e,t,n){if(SM({...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=kI(e.request.recipient,`challenge recipient`,n),i=kI(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(eN(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Z(n,`Session challenge escrow does not match the channel.`);if(rL(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 UI(e,t,n){let r=AI(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 WI(e,t){return e?t&&Date.parse(t.timestamp)>=Date.parse(e.timestamp)?t:e:t}function GI(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 KI(...e){return e.reduce((e,t)=>t>e?t:e,0n)}async function qI(e){let t;try{t=await C.readFile(e,`utf8`)}catch(t){if(iL(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 JI(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 tL(c.dirname(e))}catch(t){throw await r?.close().catch(()=>void 0),await C.unlink(n).catch(()=>void 0),t instanceof dI?t:Z(e,`Unable to write session state.`,t)}}async function YI(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 tL(c.dirname(e))}catch(t){throw await n?.close().catch(()=>void 0),n&&await C.unlink(e).catch(()=>void 0),t}}async function XI(e,t){let n=ZI(e);try{await C.link(e,n)}catch(t){if(iL(t,`EEXIST`)||iL(t,`ENOENT`))return;throw Z(e,`Unable to claim dead lock.`,t)}try{let r=await qI(n);if(r===void 0||yI(vI,r,n,`Session lock is invalid.`).token!==t.token)return;await eL(e,`Unable to reclaim dead lock.`)}finally{await eL(n,`Unable to release dead lock claim.`)}}function ZI(e){return`${e}.reclaim`}async function QI(e){try{return await C.access(e),!0}catch(t){if(iL(t,`ENOENT`))return!1;throw Z(e,`Unable to inspect session lock.`,t)}}async function $I(e,t){let n=await qI(e);n!==void 0&&yI(vI,n,e,`Session lock is invalid.`).token===t.token&&await eL(e,`Unable to release session lock.`)}async function eL(e,t){try{await C.unlink(e),await tL(c.dirname(e))}catch(n){if(!iL(n,`ENOENT`))throw Z(e,t,n)}}async function tL(e){let t=await C.open(e,`r`);try{await t.sync()}finally{await t.close()}}function nL(e){try{return process.kill(e,0),!0}catch(e){if(iL(e,`ESRCH`))return!1;if(iL(e,`EPERM`))return!0;throw e}}function rL(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function iL(e,t){return e instanceof Error&&`code`in e&&e.code===t}function Z(e,t,n){return new dI(t,{...n!==void 0&&{cause:n},file:e})}Mx(),QT(),cP(),TN(),EM(),aA(),Gk();const aL=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()}),oL=p.object({channelId:p.string(),status:p.enum([`closed`,`already-closed`]),spent:p.string(),txHash:p.string().optional()}),sL=p.object({closed:p.array(oL),failed:p.array(p.object({channelId:p.string(),message:p.string()}))});function cL(e){return e===`mainnet`?be.id:F.id}function lL(e){if(e===be.id)return`mainnet`;if(e===F.id)return`testnet`}function uL(e){let t={};for(let n of e??[]){let e=n.indexOf(`:`);if(e===-1)throw new L({code:`INVALID_HEADER`,message:`Invalid header format: ${n}`,exitCode:2});t[n.slice(0,e).trim()]=n.slice(e+1).trim()}return t}function dL(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 fL(e,t){throw e instanceof L?e:e instanceof fI?new L({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e instanceof dI?new L({code:e.code,message:e.message,exitCode:65,cause:e}):new L({code:t,message:e instanceof Error?e.message:String(e),exitCode:75,...e instanceof Error&&{cause:e}})}async function pL(e,t){let n=await tA(t??e.account.name);if(!KN(n.account,e.channel.descriptor))throw new L({code:`SESSION_ACCOUNT_MISMATCH`,message:`Account ${n.account.address} cannot sign for session ${e.channel.channelId}.`,exitCode:2});return n}async function mL(e,t){if(t.network&&cL(t.network)!==e)throw new L({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, not ${t.network}.`,exitCode:2});let n=t.network??lL(e),r=jk(t.rpcUrl,{network:n}),i=await Nk({network:n,rpcUrl:r});if(i.id!==e)throw new L({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, but RPC is chainId ${i.id}.`,exitCode:2});return M({chain:i,transport:P(r)})}const hL=fb(`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(aL)}),alias:{account:`a`},async run(e){try{let t=(await SI().list()).filter(t=>!(e.options.account&&t.account.name!==e.options.account||e.options.network&&t.channel.chainId!==cL(e.options.network))).map(dL),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(``),gL(n);return}catch(e){return fL(e,`SESSION_LIST_FAILED`)}}}).command(`view`,{description:`View a persistent payment session`,args:p.object({channelId:p.string().describe(`Full session channel ID`)}),output:aL,async run(e){try{let t=await SI().get(e.args.channelId);if(!t)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${e.args.channelId} was not found.`,exitCode:2});let n=dL(t);if(e.format===`json`&&e.formatExplicit)return e.ok(n);gL(n);return}catch(e){return fL(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([oL,sL]),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=SI();async function n(e,n={}){let r=await t.get(e);if(!r)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let i=xI(r.channel),a=await t.acquire(i);try{let r=await t.get(e);if(!r)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let a=await pL(r,n.account),o=await mL(r.channel.chainId,n);if(SM({...r.channel.descriptor,escrow:r.channel.escrow,chainId:r.channel.chainId}).toLowerCase()!==r.channel.channelId.toLowerCase())throw new L({code:`SESSION_STATE_INVALID`,message:`Stored descriptor does not derive the session channel ID.`,exitCode:65});if((await SN(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=MI(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=uL(n.headers),f=u.challenge,p=await uI({channel:u.channel,challenge:u.challenge,fetch:async(e,t)=>globalThis.fetch(e,{...t,headers:{...d,...sT(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:CI(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===cL(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 fL(e,`SESSION_CLOSE_FAILED`)}}});function gL(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}`)}Mx(),cP(),wP(),PP(),ID(),aA(),Gk();function _L(e,t){if(t&&e!==`auto`&&t.toLowerCase()!==e.toLowerCase())throw new L({code:`SESSION_SELECTION_CONFLICT`,message:`--session and -M channel= select different sessions.`,exitCode:2});let n=t??e;if(n===`auto`||n===`new`)return n;if(/^0x[0-9a-fA-F]{64}$/.test(n))return n.toLowerCase();throw new L({code:`INVALID_SESSION`,message:`Session must be auto, new, or a 32-byte channel ID.`,exitCode:2})}function vL(e){let t=e.allowCustomEscrow;if(t!==void 0){if(t===`true`)return!0;if(t===`false`)return!1;throw new L({code:`INVALID_ALLOW_CUSTOM_ESCROW`,message:`allowCustomEscrow must be true or false.`,exitCode:2})}}function yL(e,t,n,r){if(t.deposit!==void 0)return t.deposit;let i=e.request.suggestedDeposit;return typeof i==`string`?se(BigInt(i),r):n?`10`:void 0}function bL(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 xL(e,t){return e.channel.channelId.toLowerCase()===t.toLowerCase()}function SL(e){if(e.trim()!==`[DONE]`){if(e.length===0){process.stdout.write(`
248
- `);return}try{let t=JSON.parse(e);process.stdout.write(t.token??t.choices?.[0]?.delta?.content??e)}catch{process.stdout.write(e)}}}async function CL(e){let{options:t}=e,n=await tA(t.account),r=jk(t.rpcUrl,{network:t.network}),i=await Nk({network:t.network,rpcUrl:r}),a=M({chain:i,transport:P(r)}),o=vL(e.methodOptions),s=await BN({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new L({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let{decimals:c}=await Lk(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=_L(t.session,e.methodOptions.channel),d=e.registry??SI(),f=await d.acquire(l).catch(e=>{throw e instanceof fI?new L({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 L({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&u!==`auto`&&(s.status!==`open`||!s.channel.opened||bI(xI(s.channel))!==bI(l)||!KN(n.account,s.channel.descriptor)))throw new L({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let 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=MI(e.endpoint),y={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},b=CI(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=NP({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:b,credentialContext:e.credentialContext,decimals:c,maxDeposit:yL(e.challenge,e.methodOptions,Ik(i),c),fetch:async(t,n)=>w?(w=!1,e.challengeResponse):e.fetch(t,n)});f&&SP(T).rehydrate({channel:f.channel,challenge:e.challenge,input:e.fetchInput,spent:f.spent});let{onReceipt:ee,...te}=C,E=await T.fetch(e.fetchInput,te);if(t.fail&&E.status>=400)throw new L({code:`HTTP_ERROR`,message:`HTTP error ${E.status}`,exitCode:22});if(E.status===402)throw new L({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});yk(E,{include:!1,verbose:t.include?Math.max(t.verbose,2):t.verbose,silent:t.silent}),m=E.challenge??e.challenge;let D=T.channelId;if(!D)throw Error(`Session manager did not select a channel.`);if(h=bL(E.receipt,{challenge:m,channelId:D,cumulative:T.cumulative})??h,ED(E)){let t=SP(T).consumeSseResponse(e.fetchInput,E,{onReceipt:ee,signal:e.init.signal??void 0});for await(let e of t)SL(e)}else process.stdout.write(Buffer.from(await E.arrayBuffer()));let O=await d.get(D);if(!O||!xL(O,D))throw Error(`Session ${D} was not persisted.`);if(h){let e=bL(h,{challenge:m,channelId:D,cumulative:T.cumulative});if(!e)throw Error(`Session receipt validation failed.`);h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0),p=`open`}await d.upsert({status:p,channel:O.channel,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),t.silent||(e.info(`Session retained ${D}\n`),e.info(`Close with: mppx sessions close ${D}\n`))}finally{await f.release()}}QT(),Gk();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 wL(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function TL(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}const EL={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function DL(e){let t=EL[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 OL(e){console.log(`\n${X.bold(e)}`)}function kL(e,t){for(let n of e)DL(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 AL(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{let n=globalThis.fetch,i=AT(n),a=kT(n),o={[GT]:!0,...t,redirect:`error`,signal:r.signal};return a?(await a.send((e,t)=>i(e,{...t,[GT]:!0}),new Request(e,o))).response:await i(e,o)}finally{clearTimeout(i)}}function jL(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const ML=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function NL(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function PL(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function FL(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!ML.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 IL(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 LL(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 RL(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await AL(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 zL(e){let t=new URL(`/llms.txt`,e).href,n=`llms.txt found and nonempty`;try{let e=await AL(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 BL(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=UL(i.parameters);for(let[a,o]of Object.entries(i)){if(!ML.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=WL(r,UL(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 VL(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=KL(o,e,s),!o||o.type!==`object`)return;let c=qL(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function HL(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=GL(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 UL(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 WL(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 GL(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 KL(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 qL(e,t,n){let r=KL(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]=qL(i,t,n))}return a}default:return null}}SS(),zx(),Ew(),Gk();const JL=Object.values(Ye);function YL(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&JL.find(e=>e.id===t.chainId)?.testnet===!0}async function XL(e,t,n,r){let i=[],a;try{a=HL(e,t,r?.query)}catch(e){return i.push($(`Request URL valid`,e.message)),{results:i}}let o=LL(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 AL(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?VL(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 AL(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(TL(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(TL(`Returns 402 without credentials`,`Got ${c.status} (endpoint requires auth before payment gate)`)):i.push($(`Returns 402 without credentials`,`Got ${c.status} instead`,c.status===400||c.status===422?`Server requires a valid request body before returning 402. Add a requestBody schema with examples to your OpenAPI doc, or use --body.`:`Endpoints that require payment must return HTTP 402 with a WWW-Authenticate: Payment header when no valid credential is provided.`)),{results:i};i.push(Q(`Returns 402 without credentials`));let l=c.headers.get(q.wwwAuthenticate),u=sR(c);if(!l)return u.length>0?(i.push(TL(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(TL(`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(`${Px.payment} `))return i.push(TL(`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=pS(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(wL(`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;ZL(d,i),QL(d,i),$L(d,i),eR(d,p,i);let m=d.length>1;for(let e of d){let t=e.request;tR(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 ZL(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 QL(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 $L(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(wL(`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 eR(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 tR(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===Fx.tempo?nR(t,i,n,e):e.method===Fx.stripe?rR(t,i,n):e.method===Fx.evm&&iR(e,t,i,n)}function nR(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if(NL(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.`)),NL(e.currency)){let e=YL(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.`));aR(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function rR(e,t,n){aR(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 iR(e,t,n,r){if(NL(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.`)),NL(t.currency)){let t=YL(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.`));aR(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 aR(e,t,n,r){PL(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 oR(e,t,n){let r=[],i=HL(e,t,n?.query),a=LL(n?.extraHeaders),o=n?.challenge?_S(n.challenge):q.authorization;a[o.toLowerCase()]=`${Px.payment} dGhpcyBpcyBnYXJiYWdl`;let s;n?.body&&(s=n.body,a[`content-type`]||=`application/json`);try{let e=await AL(i,{method:t.method,headers:a,body:s??null});e.status===402?(r.push(Q(`Malformed credential returns 402`,`not 500`)),e.headers.get(q.wwwAuthenticate)?.startsWith(`${Px.payment} `)?r.push(Q(`Error response includes fresh challenge`)):r.push(wL(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the ${o} header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(wL(`Malformed credential returns 402`,`Got ${e.status}`,`When the ${o} header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function sR(e){let t=[],n=e.headers.get(`payment-required`)??e.headers.get(`x-payment-required`);if(!n)return t;let r=e.headers.get(`payment-required`)?`PAYMENT-REQUIRED`:`X-Payment-Required`;try{let e=yw(n);t.push(Q(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(wL(`x402 payment challenge`,`${r} header present but failed schema validation`,`Ensure the PAYMENT-REQUIRED header contains a valid base64-encoded JSON payload matching the x402 schema.`))}return t}const cR=[`No discovery document found, endpoints could not be automatically found.`,`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,`The MPP SDKs can automatically expose this endpoint. See https://mpp.dev/sdk.`,``,`To test a specific endpoint: mppx validate <url> --endpoint POST:/your/path`].join(`
249
- `);tS();const lR={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:Kx()};J.object(lR);const uR=J.looseObject(lR);function dR(e){let t=O.toString(e);return fR(JSON.parse(t))}function fR(e){return uR.parse(e)}SS(),nT(),zx(),fF(),gk(),uk(),ID(),aA(),Gk();async function pR(e,t,n){try{n||console.log(X.dim(` Provisioning testnet wallet and funding via faucet...`));let t=_e(),r=ye(t),i=M({chain:F,transport:P()});if(EO(e)){let{chainId:t,operator:n}=e.request.methodDetails??{};if(t===F.id&&typeof n==`string`&&ue(n)&&n!==ge){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:[...lF({account:r})]}}catch(e){t&&console.log(X.dim(` Provisioning failed: ${e.message}`));return}}async function mR(){let e=Qk(),{isTempoAccount:t}=await Promise.resolve().then(()=>(Gk(),_k)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(KF(),pF));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await nA()).address}catch{return}}function hR(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 gR(e,t,n){let r=M({chain:e,transport:P()}),[i,a,o]=await Promise.all([n?Ee(r,{address:t,abi:oe,functionName:`balanceOf`,args:[n]}):0n,Ee(r,{address:t,abi:oe,functionName:`decimals`}),Ee(r,{address:t,abi:oe,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,decimals:a,symbol:o??void 0}}function _R(e){return Object.values(Ye).find(t=>t.id===e)}function vR(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function yR(e){switch(e.method){case Fx.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 bR(e,t,n,r){let i=[],a=HL(e,t,r.query),o=LL(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await AL(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(TL(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=pS(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=[];eR(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 iI().catch(()=>void 0),p=l.find(e=>{if(e.method!==Fx.tempo||nI(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!==dk.mainnet});if(p){let e=await pR(p,n,r.silent);if(e)try{let r=DR((e,t)=>AL(e,t??{},3e4));await TR(i,await eE({methods:e.methods,polyfill:!1,async onChallenge(e,{createCredential:t}){oI(p,e);let n=await t(await QF(e,f?.config.extensions));return i.push(Q(`Payment: submitted`,`ephemeral testnet wallet`)),n},fetch:r.fetch}).fetch(a,{method:t.method,headers:o,body:s??null}),n,F,EO(p),r.receipt)}catch(e){i.push($(`Payment: create credential`,e.message))}else i.push($(`Payment: auto-provision wallet`,`Failed to create and fund testnet wallet`));r.onResults?.(i)}let m=r.interactive,h=process.env.MPPX_STRIPE_SECRET_KEY??hR(n),g=h?.startsWith(`sk_test_`)||h?.startsWith(`rk_test_`),_=new Set([Fx.tempo,Fx.evm,Fx.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 Fx.tempo:case Fx.evm:await xR(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,options:r});break;case Fx.stripe:await SR(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 xR(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=PL(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,{plugin:g,method:_}=$F(e,l?.config);if(!g&&!_){r.push(TL(t,yR(e)));return}let v;if(!_){try{v=await mR()}catch{}if(!v){r.push(TL(t,`no wallet configured. Run "mppx account create" to create one.`));return}}let y;if(e.method===Fx.tempo){let e=f?.chainId??(_?void 0:be.id);e!==void 0&&(y=e===F.id?F:_R(e))}else if(e.method===Fx.evm){let e=f?.chainId;e&&(y=_R(e))}if(p&&h&&!y){r.push(TL(t,`unable to resolve payment chain and verify token decimals`));return}let b;if(p&&h&&y)try{let n;if(e.method===Fx.tempo){let e=await Lk(M({chain:y,transport:P()}),h,v??ge,{requireDecimals:!0});n=e.balance,m=e.decimals,b=e.symbol}else{let e=await gR(y,h,v);n=e.balance,m=e.decimals,b=e.symbol}if(v&&n<p){let e=vR(p,m),i=vR(n,m),a=b??`tokens`;r.push(TL(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(TL(t,`unable to verify token balance and decimals from the payment chain`));return}let x=p?vR(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(TL(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 kk(` ${X.yellow(`Pay`)} ${w}. Continue?`,!1)){r.push(TL(t,`declined`));return}let T,ee,te;if(g)try{let t=await g.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});T=t.methods,ee=t.createCredential,te=t.credentialContext}catch(e){r.push(TL(t,e.message));return}else T=[_];if(_&&EO(e)){let n=!0,u=DR((e,t)=>AL(e,t??{},3e4)),d=eE({methods:[_],polyfill:!1,async onChallenge(n,{createCredential:i}){let a=await QF(n,l?.config.extensions);oI(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]:rS(e)}})):u.fetch(t,r)});try{await TR(r,await d.fetch(i,{method:a.method,headers:o,body:s??null}),c,y,!0,u.receipt)}catch(e){r.push($(t,e.message))}return}let E=await CR(e,T,ee,t,r,l?.config.extensions,te,i);E&&(g?.prepareCredentialRequest?.({challenge:e,credential:E,headers:o}),await wR(r,i,a,E,o,s,c,y,_S(e),EO(e)))}async function SR(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}=$F(e,l?.config);if(!f&&!p){r.push(TL(t,`no Stripe payment method available`));return}let m=!!(f&&!l?.config.plugins?.includes(f)&&n.isStripeTestKey),h=e.request,g=PL(h.amount)?BigInt(h.amount):void 0,_=h.decimals??2,v=h.currency,y=g?vR(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(TL(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 kk(` ${X.yellow(`Pay`)} ${x}. Continue?`,!1)){r.push(TL(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(TL(t,e.message));return}else S=[p];let T=await CR(e,S,C,t,r,l?.config.extensions,w,i);if(T){if(f?.prepareCredentialRequest?.({challenge:e,credential:T,headers:o}),m){let n=await AL(i,{method:a.method,headers:{...o,[_S(e)]:T},body:s??null},3e4);n.status>=200&&n.status<300?r.push(Q(`${t}: successful`,`HTTP ${n.status}`)):r.push(TL(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await wR(r,i,a,T,o,s,c,void 0,_S(e))}}async function CR(e,t,n,r,i,a,o,s){let c=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:rS(e)}});try{Qw(e,new URL(s),void 0);let l=await QF(e,a,o),u;return u=n?await n(c,l):await eE({methods:t,polyfill:!1}).createCredential(c,l),i.push(Q(`${r}: submitted`)),u}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(TL(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function wR(e,t,n,r,i,a,o,s,c=q.authorization,l=!1){let u;try{u=await AL(t,{method:n.method,headers:{...i,[c]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}return TR(e,u,o,s,l)}async function TR(e,t,n,r,i=!1,a){if(t.status===402){let n=await t.text().catch(()=>``),r=`Payment rejected`;try{let e=JSON.parse(n);r=e.detail??e.title??r}catch{}return e.push($(`Payment: accepted`,r,`The server rejected a valid credential. Check that your payment verification logic accepts the credential format and that the payment was processed on-chain.`)),e}if(t.status>=400&&t.status<500)e.push(wL(`Payment: post-payment response`,`Got ${t.status}`,`Payment succeeded but the endpoint returned a client error. The endpoint likely requires request body parameters. Use --body to provide them.`));else if(t.status>=500)return e.push($(`Payment: server response`,`Got ${t.status}`,`Payment was accepted but the server errored while generating the response. Check server logs for the underlying error.`)),e;else e.push(Q(`Payment: successful`,`HTTP ${t.status}`));let o=t.headers.get(`content-type`)??``,s=t.headers.get(q.paymentReceipt),c=!s&&i&&ED(t),l=await t.text().catch(()=>``);if(c){let t=a?.(),n=t===void 0?ER(l):t??void 0;n?e.push(Q(`Payment receipt in event stream`,n.reference)):e.push($(`Payment receipt in event stream`,void 0,`SSE session responses without a Payment-Receipt header must end with an "event: payment-receipt" carrying the session receipt.`))}else if(!s)e.push($(`Payment-Receipt header present`,void 0,`After accepting payment, include a Payment-Receipt header with a base64url-encoded JSON object containing: method, reference, status ("success"), and timestamp (ISO 8601).`));else{e.push(Q(`Payment-Receipt header present`));try{let t=dR(s);if(e.push(Q(`Receipt parseable`)),t.status===`success`?e.push(Q(`Receipt status is "success"`)):e.push($(`Receipt status is "success"`,`Got: ${t.status}`)),t.reference){let n=/^0x[0-9a-fA-F]{64}$/.test(t.reference),r=t.reference.startsWith(`pi_`);n||r?e.push(Q(`Receipt reference valid`,t.reference.slice(0,20)+`...`)):e.push(wL(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(wL(`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(wL(`Receipt timestamp recent`,`${Math.round(r/6e4)}m ago`))}n&&console.log(X.dim(` Receipt: ${JSON.stringify(t,null,2)}`))}catch(t){e.push($(`Receipt parseable`,t.message))}}if(l.length>0)e.push(Q(`Response body non-empty`,`${o.split(`;`)[0]}, ${jL(l.length)}`));else{let n=[...t.headers.entries()].filter(([e])=>!e.startsWith(`x-`)&&![`content-type`,`content-length`,`date`,`server`,`connection`,`keep-alive`,`cache-control`,`vary`,`access-control-allow-origin`,`payment-receipt`,`payment-session`,`payment-session-snapshot`].includes(e.toLowerCase()));n.length>0?e.push(wL(`Response body empty -- data may be in headers only`,n.map(([e])=>e).join(`, `))):e.push(wL(`Response body empty`))}if(o?e.push(Q(`Content-Type header set`,o.split(`;`)[0])):e.push(wL(`Content-Type header set`)),s)try{let t=dR(s);if(t.reference&&/^0x[0-9a-fA-F]{64}$/.test(t.reference)){let n=r?.blockExplorers?.default?.url;if(n){let r=n.includes(`tempo`)?`receipt`:`tx`;e.push(Q(`On-chain transaction`,`${n}/${r}/${t.reference}`))}}}catch{}return e}function ER(e){for(let t of e.replace(/\r\n|\r/g,`
246
+ `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await SF({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId,fetchUrl:t.fetchUrl,fetchInit:t.fetchInit,session:t.session,info:t.info,verbose:t.verbose,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,confirmEnabled:!1})}async function SF(e){let t=await e.session.signVoucher({channelId:e.channelId,cumulativeAmount:e.cumulativeAmount,escrowContract:e.escrowContract,chainId:e.chainId,action:`close`}),n=await globalThis.fetch(e.fetchUrl,{...e.fetchInit,headers:{...cT(e.fetchInit.headers),Authorization:t}});if(n.ok){if(FF(e.channelId),e.verbose>=1){let t=n.headers.get(q.paymentReceipt),r;if(t)try{let e=JSON.parse(A.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${X.dim(Ek(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${Mk(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${X.dim(X.yellow(`Channel close failed`))} ${X.dim(`(${n.status})`)}\n`),e.info(`${X.dim(` channelId: ${e.channelId}`)}\n${X.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${X.dim(` escrowContract: ${e.escrowContract}`)}\n${X.dim(` chainId: ${e.chainId}`)}\n${X.dim(` response: ${t||`(empty)`}`)}\n`)}}function CF(e=100){return!process.stdin.isTTY||!process.stdout.isTTY?Promise.resolve(void 0):new Promise(t=>{let n=process.stdin.isRaw,r=``,i=()=>{clearTimeout(a),process.stdin.removeListener(`data`,o),process.stdin.isTTY&&process.stdin.setRawMode(n??!1),process.stdin.pause()},a=setTimeout(()=>{i(),t(void 0)},e),o=e=>{r+=e.toString();let n=r.match(/\x1b\]11;rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!n)return;i();let a=e=>Number.parseInt(e.slice(0,2),16);t({r:a(n[1]),g:a(n[2]),b:a(n[3])})};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,o),process.stdout.write(`\x1B]11;?\x07`)})}function wF(e){return OF(WF,e,GF)}function TF(e){return e.method===`tempo`&&e.intent===`charge`}async function EF(e){let t=eA(e.options.account),n=process.env.MPPX_PRIVATE_KEY?.trim()||(kk(t)?void 0:await tA(t).get()),r;if(n)r=xe(n).address;else if(kk(t)&&zF())r=RF(t)?.wallet_address;else{let e=VF();if(e){let t=await tA(e).get();t&&(r=xe(t).address)}}if(!r)return;let i=Nk(e.options.rpcUrl,{network:e.options.network}),a=M({chain:await Fk({network:e.options.network,rpcUrl:i}),transport:de(i)});return{account:r,client:a}}async function DF(e,t){let n=e.request,r=n.currency,i=n.amount;if(typeof r!=`string`||typeof i!=`string`)return`unsupported`;let a=n.methodDetails?.chainId;if(a&&t.client.chain?.id&&a!==t.client.chain.id)return`unsupported`;let o=BigInt(i);if(o===0n)return`payable`;let s=await Le.token.getBalance(t.client,{account:t.account,token:r}).then(e=>e.amount).catch(()=>void 0);return s===void 0?`unknownBalance`:s>=o?`payable`:`insufficientBalance`}function OF(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function kF(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new I({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function AF(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function jF(e){let t=AF(e.tokenIn)??AF(e.payWith);if(!(!e.autoSwap&&!t&&e.slippage===void 0)){if(e.autoSwap===!1&&!t&&e.slippage===void 0)return!1;if(e.slippage!==void 0&&(!Number.isFinite(e.slippage)||e.slippage<0))throw Error(`Invalid CLI options (slippage: expected a non-negative number)`);return{...t?{tokenIn:t}:{},...e.slippage===void 0?{}:{slippage:e.slippage}}}}function MF(){return c.join(process.env.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`mppx`,`channels`)}function NF(e){try{let n=t.readFileSync(c.join(MF(),e),`utf-8`).trim();return n?BigInt(n):void 0}catch{return}}function PF(e,n){let r=MF();t.mkdirSync(r,{recursive:!0}),t.writeFileSync(c.join(r,e),n.toString(),`utf-8`)}function FF(e){try{t.unlinkSync(c.join(MF(),e))}catch{}}function IF(){return x.platform()===`darwin`?c.join(x.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):c.join(process.env.XDG_DATA_HOME||c.join(x.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function LF(){try{let e=t.readFileSync(IF(),`utf-8`),n=[],r;for(let t of e.split(`
247
+ `)){let e=t.trim();if(e===`[[keys]]`){r?.wallet_address&&n.push(r),r={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!r)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?r.wallet_type=o:a===`wallet_address`?r.wallet_address=o:a===`chain_id`&&(r.chain_id=Number.parseInt(o,10))}return r?.wallet_address&&n.push(r),n}catch{return[]}}function RF(e){let t=LF();if(t.length===0)return;let n=e.slice(6);if(n==="default"||n===``)return t[0];let r=Number.parseInt(n,10);if(!Number.isNaN(r)&&r>=0&&r<t.length)return t[r]}function zF(){if(qF!==void 0)return qF;try{m.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),qF=!0}catch{qF=!1}return qF}async function BF(e){return new Promise((t,n)=>{m.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function VF(){let e=$k();if(kk(e.get())&&!zF()&&x.platform()===`darwin`)try{let t=m.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===HF&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}var HF,UF,WF,GF,KF,qF,JF=F((()=>{Nx(),$T(),Bx(),VS(),mF(),RD(),JM(),sA(),qk(),sj(),HF=`mppx`,UF=p.union([p.boolean(),p.literal(`true`).transform(()=>!0),p.literal(`false`).transform(()=>!1)]),WF=p.object({allowCustomEscrow:p.optional(UF),autoSwap:p.optional(UF),channel:p.optional(p.coerce.string()),deposit:p.optional(p.union([p.string(),p.number()])),payWith:p.optional(p.string()),slippage:p.optional(p.coerce.number()),tokenIn:p.optional(p.string())}),GF=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`],KF=[`payable`,`unknownBalance`,`insufficientBalance`,`unsupported`]}));tC(),sA(),sj();const YF=[...Object.entries(mA),...Object.entries(hA),...Object.entries(gA),...Object.entries(_A)];function XF(){return oj({method:`evm`,supports:ZF,async setup({challenge:e,options:t}){let n=e.request,r=n.network?QF(wA(n.network)):void 0,i=n.network&&n.asset?YF.find(([,e])=>SA(e,n.asset,n.network)):void 0,a=n.extra?.name,o=n.extra?.version,s=n.asset&&n.network&&typeof a==`string`&&typeof o==`string`?fA({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await iA(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...aj({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function ZF(e){if(!$S(e))return!1;let t=e.request,n=t.extra,r=n?.assetTransferMethod;return t.scheme===`exact`&&typeof t.asset==`string`&&typeof t.network==`string`&&typeof n?.name==`string`&&typeof n?.version==`string`&&(r===void 0||r===`eip3009`)}function QF(e){return Object.values(Ze).find(t=>t.id===e)}CS(),SC(),Wx(),JF();const $F=[vF(),_j(),cj(),XF()];async function eI(e,t,n){let r=n;for(let n of t??[]){let t=await n.preparePayment?.({challenge:e,...r===void 0?{}:{credentialContext:r}});t&&`credentialContext`in t&&(r=t.credentialContext)}return r}function tI(e,t){let n=t?.plugins?.find(t=>aI(t,e));if(n)return{plugin:n};let r=iI(t)?.filter(t=>t.name===e.method&&t.intent===e.intent),i=r?.find(t=>t.canHandleChallenge?.({challenge:e})??!0);if(i)return{method:i};if(r?.length)return{};let a=$F.find(t=>aI(t,e));return a?{plugin:a}:{}}function nI(e,t){let n=iI(t);if(n?.length){let r=oC(e,n,rC(n,t?.paymentPreferences).entries);if(r){let e=t?.plugins?.find(e=>aI(e,r.challenge));return{challenge:r.challenge,...e?{plugin:e}:{method:r.method}}}return}for(let n of e){let e=tI(n,t);if(e.plugin||e.method)return{challenge:n,...e}}}function rI(e){let t=iI(e);if(t?.length)return rC(t,e?.paymentPreferences).header}function iI(e){return Array.isArray(e?.methods)?e.methods.flat():void 0}function aI(e,t){return e.supports?e.supports(t):e.method===t.method}async function oI(e){let t=sI(e);if(!t)return;let n=await import(t);return{config:n.default??n,path:t}}function sI(e){if(e){let n=c.resolve(e);return t.existsSync(n)?n:void 0}let n=process.env.MPPX_CONFIG?.trim();if(n){let e=c.resolve(n);return t.existsSync(e)?e:void 0}}function cI(e,t){function n(t){let n={...t.request};if(t.method===`tempo`&&t.intent===`session`){let e={...n.methodDetails};delete e.sessionSnapshot,Object.keys(e).length?n.methodDetails=e:delete n.methodDetails}let{meta:r,opaque:i,...a}=t;return JSON.stringify([iS({...a,request:n,id:e.id,expires:e.expires}),lI(t)])}if(n(t)!==n(e))throw Error(`Payment request changed on retry. Run the command again to approve the new payment.`)}function lI(e){let t=e.opaque??(e.meta?Ux(e.meta):void 0);if(t===void 0)return;let n;try{n=Vx(t)}catch{return t}if(typeof n!=`object`||!n||Array.isArray(n))return t;let r=uA(n);return r?Ux(r):void 0}JF(),CS(),rT(),lN(),EP(),IP(),fk();function uI(e){return e??globalThis.fetch.bind(globalThis)}function dI(e,t){let n=e.request.methodDetails?.chainId;if(n!==void 0&&n!==t.chainId)throw Error(`Close challenge changed the session chain.`);if(typeof e.request.recipient!=`string`||e.request.recipient.toLowerCase()!==t.descriptor.payee.toLowerCase())throw Error(`Close challenge changed the session payee.`);if(typeof e.request.currency!=`string`||e.request.currency.toLowerCase()!==t.descriptor.token.toLowerCase())throw Error(`Close challenge changed the session token.`);if(nN(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Error(`Close challenge changed the session escrow.`);let r=AO(e);if(r&&r.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Close challenge changed the session channel.`)}async function fI(e){dI(e.challenge,e.channel);let t=e.channel;if(t.origin===void 0){let n=new URL(e.input instanceof Request?e.input.url:e.input);if(![`http:`,`https:`].includes(n.protocol))throw Error(`Legacy session close requires an HTTP origin`);$w(e.challenge,n,e.manager.trustedTempoProofRealms),t={...t,origin:n.origin}}let n=uI(e.fetch),r,i=async(t,i)=>{r&&=(await e.onChallenge?.(r),void 0);let a=await n(t,i);if(a.status!==402)return a;let o=mS(a).find(OO);if(!o)throw Error(`Refreshed close response did not include tempo/session.`);return dI(o,e.channel),r=o,a},a=FP({...e.manager,bootstrap:!1,escrow:e.channel.escrow,fetch:i});wP(a).rehydrate({...e,channel:t}),t!==e.channel&&await e.manager.channelStore?.set(t);let o=await a.close();if(!o)throw Error(`Session close response did not include a payment receipt.`);return{manager:a,receipt:o}}CS(),lN(),SN(),fk(),OM(),nS();var pI=class extends Error{name=`SessionStateError`;code=`SESSION_STATE_INVALID`;file;constructor(e,t={}){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.file=t.file}},mI=class extends Error{name=`SessionBusyError`;code=`SESSION_BUSY`;exitCode=75;scope;owner;constructor(e,t){super(`Session scope is busy in process ${t.pid} on ${t.hostname}.`),this.scope=e,this.owner=t}};const hI=J.object({origin:J.optional(J.string()),channelId:Qx(),cumulativeAmount:J.string(),deposit:J.string(),descriptor:J.object({payer:Zx(),payee:Zx(),operator:Zx(),token:Zx(),salt:Qx(),authorizedSigner:Zx(),expiringNonceHash:Qx()}),escrow:Zx(),chainId:J.number(),opened:J.boolean()}),gI=J.object({name:J.optional(J.string()),address:Zx()}),_I=J.object({method:J.literal(`tempo`),intent:J.literal(`session`),status:J.literal(`success`),timestamp:J.string(),reference:J.string(),challengeId:J.string(),channelId:Qx(),acceptedCumulative:J.string(),spent:J.string(),units:J.optional(J.number()),txHash:J.optional(Qx())}),vI=J.object({version:J.literal(1),method:J.literal(`tempo`),intent:J.literal(`session`),status:J.enum([`opening`,`open`,`closing`,`stale`]),channel:hI,account:gI,endpoint:J.string(),challenge:SS,receipt:J.optional(_I),spent:J.string(),units:J.number(),createdAt:J.string(),updatedAt:J.string()}),yI=J.object({version:J.literal(1),channelId:Qx()}),bI=J.object({version:J.literal(1),scope:J.string(),hostname:J.string(),pid:J.number(),token:J.string(),createdAt:J.string()});function xI(e,t,n,r){let i=e.safeParse(t);if(!i.success)throw Z(n,r,i.error);return i.data}function SI(e){let t=MI(e);return[t.payer,t.payee,t.token,t.escrow,t.chainId].join(`:`)}function CI(e){return{payer:e.descriptor.payer,payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId}}function wI(e={}){let t=e.stateRoot??EI(),n={root:t,channels:c.join(t,`channels`),locks:c.join(t,`locks`),preferred:c.join(t,`preferred`)},r=e.hostname??x.hostname(),i=e.pid??process.pid,a=e.now??(()=>new Date),o=e.isProcessAlive??iL;async function s(){for(let e of[n.root,n.channels,n.locks,n.preferred])await w.mkdir(e,{recursive:!0,mode:448}),await w.chmod(e,448)}async function l(e){let t=AI(e),r=DI(n,t),i=await YI(r);if(i===void 0)return;let a=BI(i,r);if(a.channel.channelId.toLowerCase()!==t)throw Z(r,`Session filename does not match its channel ID.`);return VI(a)}async function u(){let e;try{e=await w.readdir(n.channels,{withFileTypes:!0})}catch(e){if(oL(e,`ENOENT`))return[];throw Z(n.channels,`Unable to list managed sessions.`,e)}let t=[];for(let n of e){if(!n.isFile()||n.name.includes(`.tmp-`)||!n.name.endsWith(`.json`))continue;let e=n.name.slice(0,-5);AI(e);let r=await l(e);r&&t.push(r)}return t.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}async function d(e){await s();let t=II(e.channel),r=AI(t.channelId),i=DI(n,r),o=await YI(i),c=o===void 0?void 0:BI(o,i);c&&HI(c,e,i);let l=c?.channel.origin??t.origin;if(c?.channel.origin&&t.origin&&c.channel.origin!==t.origin)throw Z(i,`Session payment origin mismatch.`);if(l!==void 0&&new URL(l).origin!==l)throw Z(i,`Session payment origin must be a normalized origin.`);let u=RI(e.challenge,i);WI(u,t,i);let d=e.receipt?zI(e.receipt,t.channelId,i):void 0,f=c?mN(c.channel):void 0,p=JI(t.cumulativeAmount,f?.cumulativeAmount??0n),m=JI(e.spent??0n,d?BigInt(d.spent):0n,c?BigInt(c.spent):0n);if(m>p)throw Z(i,`Session spend exceeds the locally authorized cumulative amount.`);let h=LI(pN({...t,cumulativeAmount:p,...l!==void 0&&{origin:l}}),i),g=qI(c?.updatedAt,a(),i),_=KI(c?.receipt,d),v=FI(e.account,i),y=BI({version:1,method:`tempo`,intent:`session`,status:e.status,channel:h,account:{...v.name===void 0?c?.account.name===void 0?{}:{name:c.account.name}:{name:v.name},address:v.address},endpoint:PI(e.endpoint,i),challenge:u,..._!==void 0&&{receipt:_},spent:m.toString(),units:Math.max(c?.units??0,e.units??0,d?.units??0),createdAt:c?.createdAt??g,updatedAt:g},i);return await XI(i,y),VI(y)}async function f(e){let t=kI(n,e),r=await YI(t);if(r===void 0)return;let{channelId:i}=xI(yI,r,t,`Preferred session is invalid.`),a=await l(i);if(!a)throw Z(t,`Preferred session ${i} does not exist.`);return GI(a.channel,e,t),i}async function p(e,t){let r=AI(t),i=await l(r),a=kI(n,e);if(!i)throw Z(a,`Session ${r} does not exist.`);GI(i.channel,e,a),await XI(a,{version:1,channelId:r})}async function m(e,t){let r=kI(n,e),i=t===void 0?void 0:AI(t),a=await YI(r);if(a===void 0)return;let o=xI(yI,a,r,`Preferred session is invalid.`).channelId;i&&o.toLowerCase()!==i||await nL(r,`Unable to clear preferred session.`)}async function h(e){let t=AI(e),r=await l(t);r&&(await m(CI(r.channel),t),await nL(DI(n,t),`Unable to remove session.`))}async function g(e){await s();let t=OI(n,e);for(let n=0;n<3;n++){let n={version:1,scope:e,hostname:r,pid:i,token:v(),createdAt:a().toISOString()};try{if(await ZI(t,n),await eL($I(t))){await tL(t,n);continue}return{async release(){await tL(t,n)}}}catch(e){if(!oL(e,`EEXIST`))throw e}let s=await YI(t);if(s===void 0)continue;let c=xI(bI,s,t,`Session lock is invalid.`);if(c.scope!==e)throw Z(t,`Session lock scope is invalid.`);if(c.hostname!==r||o(c.pid))throw new mI(e,c);await QI(t,c)}let c=await YI(t);throw c===void 0?Z(t,`Unable to acquire session lock.`):new mI(e,xI(bI,c,t,`Session lock is invalid.`))}async function _(e){return g(SI(e))}return{root:t,get:l,list:u,upsert:d,remove:h,getPreferred:f,setPreferred:p,clearPreferred:m,acquire:_}}function TI(e,t){let n=NI(t.scope),r=t.selection===`auto`||t.selection===`new`?void 0:AI(t.selection);function i(e){if(e.toLowerCase()!==n)throw new pI(`Session manager requested an unexpected payment scope.`)}async function a(n=!0){if(t.selection===`new`&&!r)return;let i=r??await e.getPreferred(t.scope);if(!i)return;let a=await e.get(i);if(!a)throw new pI(`Session ${i} does not exist.`);if(GI(a.channel,t.scope),!(n&&(a.status!==`open`||!a.channel.opened)))return r=i,a}return{async get(e){return i(e),(await a())?.channel},async set(n){if(i(dN(n)),GI(n,t.scope),r&&r.toLowerCase()!==n.channelId.toLowerCase())throw new pI(`Session manager selected ${r}, but attempted to store ${n.channelId}.`);r||t.onNewChannel?.(n);let a=await e.upsert({...t.context(),channel:n});r=a.channel.channelId,await e.setPreferred(t.scope,a.channel.channelId)},async delete(n){i(n);let o=await a(!1);if(!o)return;let s=t.context();await e.upsert({...o,...s,status:s.status===`closing`?`closing`:`stale`,channel:o.channel,spent:s.spent??o.spent,units:s.units??o.units}),s.status!==`closing`&&await e.clearPreferred(t.scope,o.channel.channelId),r=void 0}}}function EI(){let e=process.env.XDG_STATE_HOME||c.join(x.homedir(),`.local`,`state`);return c.join(e,`mppx`,`sessions`,`v1`)}function DI(e,t){return c.join(e.channels,`${t}.json`)}function OI(e,t){let n=_(`sha256`).update(t).digest(`hex`);return c.join(e.locks,`${n}.lock`)}function kI(e,t){let n=_(`sha256`).update(SI(t)).digest(`hex`);return c.join(e.preferred,`${n}.json`)}function AI(e){return xI(Qx(),e,void 0,`Invalid session channel ID: ${e}.`).toLowerCase()}function jI(e,t,n){return xI(Zx(),e,n,`Invalid ${t}.`).toLowerCase()}function MI(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<0)throw new pI(`Invalid session chain ID.`);return{payer:jI(e.payer,`session payer`),payee:jI(e.payee,`session payee`),token:jI(e.token,`session token`),escrow:jI(e.escrow,`session escrow`),chainId:e.chainId}}function NI(e){let t=MI(e);return[t.payee,t.token,t.escrow,t.chainId].join(`:`)}function PI(e,t){if(typeof e!=`string`)throw Z(t,`Session endpoint is invalid.`);let n;try{n=new URL(e)}catch(e){throw Z(t,`Session endpoint is invalid.`,e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Z(t,`Session endpoint must use HTTP or HTTPS.`);if(n.username||n.password)throw Z(t,`Session endpoint must not contain credentials.`);let r=e.indexOf(`#`);return r===-1?e:e.slice(0,r)}function FI(e,t){return xI(gI,e,t,`Session account is invalid.`)}function II(e){return mN(LI(pN(e)))}function LI(e,t){return xI(hI,e,t,`Stored session channel is invalid.`)}function RI(e,t){let n=SS.safeParse(e);if(!n.success||!OO(n.data))throw Z(t,`Stored session challenge is invalid.`);return n.data}function zI(e,t,n){let r=xI(_I,e,n,`Stored session receipt is invalid.`);if(r.channelId!==t.toLowerCase())throw Z(n,`Stored session receipt has a different channel ID.`);if(r.reference.toLowerCase()!==t.toLowerCase())throw Z(n,`Stored session receipt has a different reference.`);if(BigInt(r.spent)>BigInt(r.acceptedCumulative))throw Z(n,`Stored session receipt spend exceeds its accepted amount.`);return r}function BI(e,t){let n=xI(vI,e,t,`Stored session is invalid.`),{receipt:r,...i}=n,a=n.channel,o=n.account;if(o.address.toLowerCase()!==a.descriptor.payer.toLowerCase())throw Z(t,`Stored session account does not match the channel payer.`);let s=r?zI(r,a.channelId,t):void 0,c=n.spent,l=BigInt(a.cumulativeAmount);if(BigInt(c)>l)throw Z(t,`Stored session spend exceeds its cumulative authorization.`);if(s&&BigInt(s.acceptedCumulative)>l)throw Z(t,`Stored receipt exceeds the cumulative authorization.`);if(Date.parse(n.updatedAt)<Date.parse(n.createdAt))throw Z(t,`Stored session timestamps are not monotonic.`);let u=PI(n.endpoint,t);if(u!==n.endpoint)throw Z(t,`Stored session endpoint contains a fragment.`);let d=RI(n.challenge,t);return WI(d,mN(a),t),{...i,account:o,channel:a,endpoint:u,challenge:d,...s&&{receipt:s}}}function VI(e){return{version:1,status:e.status,channel:mN(e.channel),account:e.account,endpoint:e.endpoint,challenge:e.challenge,...e.receipt&&{receipt:e.receipt},spent:BigInt(e.spent),units:e.units,createdAt:e.createdAt,updatedAt:e.updatedAt}}function HI(e,t,n){let r=II(t.channel),i=FI(t.account,n),a=mN(e.channel);if(JSON.stringify(UI(r))!==JSON.stringify(UI(a)))throw Z(n,`Session update changed immutable channel identity.`);if(i.address.toLowerCase()!==e.account.address.toLowerCase())throw Z(n,`Session update changed the payer account.`)}function UI(e){return{channelId:e.channelId.toLowerCase(),descriptor:Object.fromEntries(Object.entries(e.descriptor).map(([e,t])=>[e,typeof t==`string`?t.toLowerCase():t])),escrow:e.escrow.toLowerCase(),chainId:e.chainId}}function WI(e,t,n){if(wM({...t.descriptor,chainId:t.chainId,escrow:t.escrow}).toLowerCase()!==t.channelId.toLowerCase())throw Z(n,`Session channel ID does not match its descriptor.`);let r=jI(e.request.recipient,`challenge recipient`,n),i=jI(e.request.currency,`challenge currency`,n);if(r!==t.descriptor.payee.toLowerCase())throw Z(n,`Session challenge payee does not match the channel.`);if(i!==t.descriptor.token.toLowerCase())throw Z(n,`Session challenge token does not match the channel.`);if(nN(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Z(n,`Session challenge escrow does not match the channel.`);if(aL(e.request.methodDetails)){let r=e.request.methodDetails;if(r.chainId!==void 0&&r.chainId!==t.chainId)throw Z(n,`Session challenge chain does not match the channel.`)}}function GI(e,t,n){let r=MI(t);if(e.descriptor.payer.toLowerCase()!==r.payer||e.descriptor.payee.toLowerCase()!==r.payee||e.descriptor.token.toLowerCase()!==r.token||e.escrow.toLowerCase()!==r.escrow||e.chainId!==r.chainId)throw Z(n,`Session channel does not match the selected payment scope.`)}function KI(e,t){return e?t&&Date.parse(t.timestamp)>=Date.parse(e.timestamp)?t:e:t}function qI(e,t,n){if(!Number.isFinite(t.getTime()))throw Z(n,`Session clock is invalid.`);let r=t.toISOString();return!e||Date.parse(r)>=Date.parse(e)?r:e}function JI(...e){return e.reduce((e,t)=>t>e?t:e,0n)}async function YI(e){let t;try{t=await w.readFile(e,`utf8`)}catch(t){if(oL(t,`ENOENT`))return;throw Z(e,`Unable to read session state.`,t)}try{return JSON.parse(t)}catch(t){throw Z(e,`Session state contains invalid JSON.`,t)}}async function XI(e,t){await w.mkdir(c.dirname(e),{recursive:!0,mode:448}),await w.chmod(c.dirname(e),448);let n=`${e}.tmp-${process.pid}-${v()}`,r;try{r=await w.open(n,`wx`,384),await r.writeFile(`${JSON.stringify(t,null,2)}\n`,`utf8`),await r.sync(),await r.close(),r=void 0,await w.rename(n,e),await w.chmod(e,384),await rL(c.dirname(e))}catch(t){throw await r?.close().catch(()=>void 0),await w.unlink(n).catch(()=>void 0),t instanceof pI?t:Z(e,`Unable to write session state.`,t)}}async function ZI(e,t){let n;try{n=await w.open(e,`wx`,384),await n.writeFile(`${JSON.stringify(t)}\n`,`utf8`),await n.sync(),await n.close(),n=void 0,await rL(c.dirname(e))}catch(t){throw await n?.close().catch(()=>void 0),n&&await w.unlink(e).catch(()=>void 0),t}}async function QI(e,t){let n=$I(e);try{await w.link(e,n)}catch(t){if(oL(t,`EEXIST`)||oL(t,`ENOENT`))return;throw Z(e,`Unable to claim dead lock.`,t)}try{let r=await YI(n);if(r===void 0||xI(bI,r,n,`Session lock is invalid.`).token!==t.token)return;await nL(e,`Unable to reclaim dead lock.`)}finally{await nL(n,`Unable to release dead lock claim.`)}}function $I(e){return`${e}.reclaim`}async function eL(e){try{return await w.access(e),!0}catch(t){if(oL(t,`ENOENT`))return!1;throw Z(e,`Unable to inspect session lock.`,t)}}async function tL(e,t){let n=await YI(e);n!==void 0&&xI(bI,n,e,`Session lock is invalid.`).token===t.token&&await nL(e,`Unable to release session lock.`)}async function nL(e,t){try{await w.unlink(e),await rL(c.dirname(e))}catch(n){if(!oL(n,`ENOENT`))throw Z(e,t,n)}}async function rL(e){let t=await w.open(e,`r`);try{await t.sync()}finally{await t.close()}}function iL(e){try{return process.kill(e,0),!0}catch(e){if(oL(e,`ESRCH`))return!1;if(oL(e,`EPERM`))return!0;throw e}}function aL(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function oL(e,t){return e instanceof Error&&`code`in e&&e.code===t}function Z(e,t,n){return new pI(t,{...n!==void 0&&{cause:n},file:e})}Nx(),$T(),uP(),DN(),OM(),sA(),qk();const sL=p.object({status:p.enum([`opening`,`open`,`closing`,`stale`]),channelId:p.string(),account:p.string().optional(),payer:p.string(),payee:p.string(),authorizedSigner:p.string(),token:p.string(),escrow:p.string(),chainId:p.number(),cumulativeAmount:p.string(),confirmedSpend:p.string(),deposit:p.string(),units:p.number(),resourceUrl:p.string(),createdAt:p.string(),updatedAt:p.string()}),cL=p.object({channelId:p.string(),status:p.enum([`closed`,`already-closed`]),spent:p.string(),txHash:p.string().optional()}),lL=p.object({closed:p.array(cL),failed:p.array(p.object({channelId:p.string(),message:p.string()}))});function uL(e){return e===`mainnet`?P.id:Se.id}function dL(e){if(e===P.id)return`mainnet`;if(e===Se.id)return`testnet`}function fL(e){let t={};for(let n of e??[]){let e=n.indexOf(`:`);if(e===-1)throw new I({code:`INVALID_HEADER`,message:`Invalid header format: ${n}`,exitCode:2});t[n.slice(0,e).trim()]=n.slice(e+1).trim()}return t}function pL(e){return{status:e.status,channelId:e.channel.channelId,...e.account.name&&{account:e.account.name},payer:e.channel.descriptor.payer,payee:e.channel.descriptor.payee,authorizedSigner:e.channel.descriptor.authorizedSigner,token:e.channel.descriptor.token,escrow:e.channel.escrow,chainId:e.channel.chainId,cumulativeAmount:e.channel.cumulativeAmount.toString(),confirmedSpend:e.spent.toString(),deposit:e.channel.deposit.toString(),units:e.units,resourceUrl:e.endpoint,createdAt:e.createdAt,updatedAt:e.updatedAt}}function mL(e,t){throw e instanceof I?e:e instanceof mI?new I({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e instanceof pI?new I({code:e.code,message:e.message,exitCode:65,cause:e}):new I({code:t,message:e instanceof Error?e.message:String(e),exitCode:75,...e instanceof Error&&{cause:e}})}async function hL(e,t){let n=await rA(t??e.account.name);if(!JN(n.account,e.channel.descriptor))throw new I({code:`SESSION_ACCOUNT_MISMATCH`,message:`Account ${n.account.address} cannot sign for session ${e.channel.channelId}.`,exitCode:2});return n}async function gL(e,t){if(t.network&&uL(t.network)!==e)throw new I({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, not ${t.network}.`,exitCode:2});let n=t.network??dL(e),r=Nk(t.rpcUrl,{network:n}),i=await Fk({network:n,rpcUrl:r});if(i.id!==e)throw new I({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, but RPC is chainId ${i.id}.`,exitCode:2});return M({chain:i,transport:de(r)})}const _L=pb(`sessions`,{description:`Manage persistent payment sessions (list, view, close)`}).command(`list`,{description:`List persistent payment sessions`,options:p.object({account:p.string().optional().describe(`Filter by account name`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Filter by Tempo network`)}),output:p.object({sessions:p.array(sL)}),alias:{account:`a`},async run(e){try{let t=(await wI().list()).filter(t=>!(e.options.account&&t.account.name!==e.options.account||e.options.network&&t.channel.chainId!==uL(e.options.network))).map(pL),n={sessions:t};if(e.format===`json`&&e.formatExplicit)return e.ok(n);t.length===0&&console.log(`No sessions.`);for(let[e,n]of t.entries())e>0&&console.log(``),vL(n);return}catch(e){return mL(e,`SESSION_LIST_FAILED`)}}}).command(`view`,{description:`View a persistent payment session`,args:p.object({channelId:p.string().describe(`Full session channel ID`)}),output:sL,async run(e){try{let t=await wI().get(e.args.channelId);if(!t)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e.args.channelId} was not found.`,exitCode:2});let n=pL(t);if(e.format===`json`&&e.formatExplicit)return e.ok(n);vL(n);return}catch(e){return mL(e,`SESSION_VIEW_FAILED`)}}}).command(`close`,{description:`Cooperatively close persistent payment sessions`,usage:[{suffix:`<channel-id> [options]`},{suffix:`--all --yes [options]`}],args:p.object({channelId:p.string().optional().describe(`Full session channel ID`)}),options:p.object({account:p.string().optional().describe(`Account name`),all:p.boolean().optional().default(!1).describe(`Close every matching session`),header:p.array(p.string()).optional().describe(`Add close request header (repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`),url:p.string().optional().describe(`Override the stored resource URL`),yes:p.boolean().optional().default(!1).describe(`Confirm closing every session`)}),output:p.union([cL,lL]),alias:{account:`a`,header:`H`,rpcUrl:`r`},async run(e){if(e.options.all&&e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all, not both.`,exitCode:2});if(!e.options.all&&!e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all.`,exitCode:2});if(e.options.all&&!e.options.yes)return e.error({code:`CONFIRMATION_REQUIRED`,message:`Closing all sessions requires --yes.`,exitCode:2});if(e.options.all&&(e.options.header||e.options.rpcUrl||e.options.url))return e.error({code:`INVALID_SESSION_CLOSE`,message:`--header, --rpc-url, and --url only apply to a single session.`,exitCode:2});let t=wI();async function n(e,n={}){let r=await t.get(e);if(!r)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let i=CI(r.channel),a=await t.acquire(i);try{let r=await t.get(e);if(!r)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let a=await hL(r,n.account),o=await gL(r.channel.chainId,n);if(wM({...r.channel.descriptor,escrow:r.channel.escrow,chainId:r.channel.chainId}).toLowerCase()!==r.channel.channelId.toLowerCase())throw new I({code:`SESSION_STATE_INVALID`,message:`Stored descriptor does not derive the session channel ID.`,exitCode:65});if((await wN(o,r.channel.channelId,r.channel.escrow)).deposit===0n)return await t.remove(r.channel.channelId),{channelId:r.channel.channelId,status:`already-closed`,spent:r.spent.toString()};let s=PI(n.resourceUrl??r.endpoint),c={...a.source===`keychain`&&{name:a.accountName},address:a.account.address},l=(e=r.challenge)=>({status:`closing`,account:c,endpoint:s,challenge:e,...r.receipt&&{receipt:r.receipt},spent:r.spent,units:r.units}),u=await t.upsert({...l(),channel:r.channel}),d=fL(n.headers),f=u.challenge,p=await fI({channel:u.channel,challenge:u.challenge,fetch:async(e,t)=>globalThis.fetch(e,{...t,headers:{...d,...cT(t?.headers)}}),input:s,spent:u.spent,async onChallenge(e){f=e,await t.upsert({...l(e),channel:u.channel})},manager:{account:a.account,client:o,channelStore:TI(t,{scope:i,selection:u.channel.channelId,context:()=>l(f)})}});return await t.remove(u.channel.channelId),{channelId:u.channel.channelId,status:`closed`,spent:p.receipt.spent,txHash:p.receipt.txHash}}finally{await a.release()}}try{if(e.options.all){let r=(await t.list()).filter(t=>(!e.options.account||t.account.name===e.options.account)&&(!e.options.network||t.channel.chainId===uL(e.options.network))),i=[],a=[];for(let t of r)try{i.push(await n(t.channel.channelId,{account:e.options.account,network:e.options.network}))}catch(e){a.push({channelId:t.channel.channelId,message:e instanceof Error?e.message:String(e)})}let o={closed:i,failed:a};if(a.length>0){for(let e of a)process.stderr.write(`${e.channelId}: ${e.message}\n`);process.exitCode=1}if(e.format===`json`&&e.formatExplicit)return e.ok(o);for(let e of i)console.log(`${e.channelId} ${e.status} ${e.spent}`);for(let e of a)console.log(`${e.channelId} failed ${e.message}`);return}let r=await n(e.args.channelId,{account:e.options.account,headers:e.options.header,network:e.options.network,resourceUrl:e.options.url,rpcUrl:e.options.rpcUrl});if(e.format===`json`&&e.formatExplicit)return e.ok(r);console.log(`${r.channelId} ${r.status} ${r.spent}`),r.txHash&&console.log(` transaction ${r.txHash}`);return}catch(e){return mL(e,`SESSION_CLOSE_FAILED`)}}});function vL(e){console.log(e.channelId),console.log(` status ${e.status}`),console.log(` cumulative amount ${e.cumulativeAmount}`),console.log(` confirmed spend ${e.confirmedSpend}`),console.log(` deposit ${e.deposit}`),console.log(` chain ${e.chainId}`),console.log(` payer ${e.payer}`),console.log(` payee ${e.payee}`),console.log(` token ${e.token}`),console.log(` resource ${e.resourceUrl}`)}Nx(),uP(),EP(),IP(),RD(),sA(),qk();function yL(e,t){if(t&&e!==`auto`&&t.toLowerCase()!==e.toLowerCase())throw new I({code:`SESSION_SELECTION_CONFLICT`,message:`--session and -M channel= select different sessions.`,exitCode:2});let n=t??e;if(n===`auto`||n===`new`)return n;if(/^0x[0-9a-fA-F]{64}$/.test(n))return n.toLowerCase();throw new I({code:`INVALID_SESSION`,message:`Session must be auto, new, or a 32-byte channel ID.`,exitCode:2})}function bL(e){let t=e.allowCustomEscrow;if(t!==void 0){if(t===`true`)return!0;if(t===`false`)return!1;throw new I({code:`INVALID_ALLOW_CUSTOM_ESCROW`,message:`allowCustomEscrow must be true or false.`,exitCode:2})}}function xL(e,t,n,r){if(t.deposit!==void 0)return t.deposit;let i=e.request.suggestedDeposit;return typeof i==`string`?N(BigInt(i),r):n?`10`:void 0}function SL(e,t){if(!e)return;if(e.challengeId!==t.challenge.id)throw Error(`Session receipt challenge does not match the paid request.`);if(e.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Session receipt channel does not match the selected channel.`);let n=BigInt(e.acceptedCumulative),r=BigInt(e.spent);if(n>t.cumulative)throw Error(`Session receipt exceeds the local cumulative authorization.`);if(r>n)throw Error(`Session receipt spend exceeds its accepted authorization.`);return e}function CL(e,t){return e.channel.channelId.toLowerCase()===t.toLowerCase()}function wL(e){if(e.trim()!==`[DONE]`){if(e.length===0){process.stdout.write(`
248
+ `);return}try{let t=JSON.parse(e);process.stdout.write(t.token??t.choices?.[0]?.delta?.content??e)}catch{process.stdout.write(e)}}}async function TL(e){let{options:t}=e,n=await rA(t.account),r=Nk(t.rpcUrl,{network:t.network}),i=await Fk({network:t.network,rpcUrl:r}),a=M({chain:i,transport:de(r)}),o=bL(e.methodOptions),s=await HN({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new I({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let{decimals:c}=await zk(a,s.token,n.account.address,{requireDecimals:!0}),l={payer:n.account.address,payee:s.payee,token:s.token,escrow:s.escrow,chainId:s.chainId},u=yL(t.session,e.methodOptions.channel),d=e.registry??wI(),f=await d.acquire(l).catch(e=>{throw e instanceof mI?new I({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=u===`auto`?await d.getPreferred(l):u===`new`?void 0:u,s=r?await d.get(r):void 0;if(r&&!s)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&u!==`auto`&&(s.status!==`open`||!s.channel.opened||SI(CI(s.channel))!==SI(l)||!JN(n.account,s.channel.descriptor)))throw new I({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let f=s?.status===`open`&&s.channel.opened?s:void 0,p=f?`open`:`opening`,m=e.challenge,h=f?.receipt,g=f?.spent??0n,_=f?.units??0,v=PI(e.endpoint),y={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},b=TI(d,{scope:l,selection:u,context:()=>({status:p,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),onNewChannel(){p=`opening`,h=void 0,g=0n,_=0}}),{signal:x,...S}=e.init,C={...S,...x&&{signal:x},onReceipt(e){h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0)}};if(e.challengeResponse.status!==402||e.challengeResponse.bodyUsed)throw Error(`Session manager requires an unconsumed 402 challenge response.`);let w=!0,T=FP({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:b,credentialContext:e.credentialContext,decimals:c,maxDeposit:xL(e.challenge,e.methodOptions,Rk(i),c),fetch:async(t,n)=>w?(w=!1,e.challengeResponse):e.fetch(t,n)});f&&wP(T).rehydrate({channel:f.channel,challenge:e.challenge,input:e.fetchInput,spent:f.spent});let{onReceipt:E,...ee}=C,D=await T.fetch(e.fetchInput,ee);if(t.fail&&D.status>=400)throw new I({code:`HTTP_ERROR`,message:`HTTP error ${D.status}`,exitCode:22});if(D.status===402)throw new I({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});xk(D,{include:!1,verbose:t.include?Math.max(t.verbose,2):t.verbose,silent:t.silent}),m=D.challenge??e.challenge;let O=T.channelId;if(!O)throw Error(`Session manager did not select a channel.`);if(h=SL(D.receipt,{challenge:m,channelId:O,cumulative:T.cumulative})??h,OD(D)){let t=wP(T).consumeSseResponse(e.fetchInput,D,{onReceipt:E,signal:e.init.signal??void 0});for await(let e of t)wL(e)}else process.stdout.write(Buffer.from(await D.arrayBuffer()));let k=await d.get(O);if(!k||!CL(k,O))throw Error(`Session ${O} was not persisted.`);if(h){let e=SL(h,{challenge:m,channelId:O,cumulative:T.cumulative});if(!e)throw Error(`Session receipt validation failed.`);h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0),p=`open`}await d.upsert({status:p,channel:k.channel,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),t.silent||(e.info(`Session retained ${O}\n`),e.info(`Close with: mppx sessions close ${O}\n`))}finally{await f.release()}}const EL=`StripeCLI`;function DL(e){let t=e.env??process.env,n=e.secretKey?.trim();if(n)return{key:n,source:`flag`};let r=t.STRIPE_SECRET_KEY?.trim();if(r)return{key:r,source:`env`};let i=OL(e);if(i)return{key:i,source:`stripe-cli`}}function OL(e){let t=e.env??process.env,n=c.join(t.XDG_CONFIG_HOME||c.join(x.homedir(),`.config`),`stripe`),r=e.projectName||t.STRIPE_PROJECT_NAME||`default`,i=ML(c.join(n,`config.toml`),r);if(!e.live)return i.test_mode_api_key||i.secret_key||i.api_key||void 0;let a=i.live_mode_api_key;if(a&&!a.includes(`*`))return a;let o=`${r}.live_mode_api_key`,s=jL(c.join(n,`credentials.json`))?.[o];return typeof s==`string`&&s?s:kL(o,e)}function kL(e,t){let n=t.platform??process.platform,r=t.exec??AL,i=(()=>{if(n===`darwin`)return[`security`,[`find-generic-password`,`-s`,EL,`-a`,e,`-w`]];if(n===`linux`)return[`secret-tool`,[`lookup`,`service`,EL,`username`,e]]})();if(i)try{let e=r(i[0],i[1]).trim();return e.startsWith(`go-keyring-base64:`)?Buffer.from(e.slice(18),`base64`).toString(`utf8`)||void 0:e||void 0}catch{return}}function AL(e,t){return g(e,t,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:3e3})}function jL(e){try{return JSON.parse(t.readFileSync(e,`utf8`))}catch{return}}function ML(e,n){let r;try{r=t.readFileSync(e,`utf8`)}catch{return{}}let i=new Set([n,`profiles.${n}`]),a={},o;for(let e of r.split(/\r?\n/)){let t=e.trim();if(!t||t.startsWith(`#`))continue;let n=/^\[\s*([^\]]+?)\s*\]$/.exec(t);if(n){o=n[1].replace(/["']/g,``).replace(/\s*\.\s*/g,`.`);continue}if(!o||!i.has(o))continue;let r=/^([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')/.exec(t);r&&(a[r[1]]=r[2]===void 0?r[3]:r[2].replace(/\\(.)/g,`$1`))}return a}function NL(e,n,r){let i=`${n}=${r}`;if(!t.existsSync(e))return t.writeFileSync(e,`${i}\n`,{mode:384});let a=t.readFileSync(e,`utf8`),o=RegExp(`^(?:export\\s+)?${n}\\s*=.*$`,`m`);if(o.test(a))return t.writeFileSync(e,a.replace(o,()=>i));let s=a===``||a.endsWith(`
249
+ `)?``:`
250
+ `;t.writeFileSync(e,`${a}${s}${i}\n`)}function PL(e){let t=e.findIndex((t,n)=>t===`stripe`&&e[n+1]===`address`);if(t===-1)return[...e];let n=e.slice(0,t+2);for(let r=t+2;r<e.length;r++){let t=e[r];if(n.push(t),t===`--`){n.push(...e.slice(r+1));break}let i=e[r+1];t===`--env`&&(i===void 0||i.startsWith(`-`))&&n.push(`.env`)}return n}$T(),qk();function Q(e,t){return t?{label:e,detail:t,severity:`pass`}:{label:e,severity:`pass`}}function $(e,t,n){let r={label:e,severity:`fail`};return t&&(r.detail=t),n&&(r.hint=n),r}function FL(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function IL(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}const LL={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function RL(e){let t=LL[e.severity],n=e.detail?`${e.label} (${e.detail})`:e.label;console.log(` ${t} ${n}`),e.hint&&e.severity!==`pass`&&console.log(X.dim(` → ${e.hint}`))}function zL(e){console.log(`\n${X.bold(e)}`)}function BL(e,t){for(let n of e)RL(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`suggested`?t.suggested++:n.severity===`skip`&&t.skipped++}async function VL(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{let n=globalThis.fetch,i=jT(n),a=AT(n),o={[KT]:!0,...t,redirect:`error`,signal:r.signal};return a?(await a.send((e,t)=>i(e,{...t,[KT]:!0}),new Request(e,o))).response:await i(e,o)}finally{clearTimeout(i)}}function HL(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const UL=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function WL(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function GL(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function KL(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!UL.has(n))return null;let r=e.slice(t+1);if(!r)return null;let i=r.startsWith(`/`)?r:`/`+r;return{method:n.toUpperCase(),path:i}}function qL(e,t){if(e){try{let n=JSON.parse(e);if(n&&typeof n==`object`&&!Array.isArray(n)){let e=Object.keys(n);if(e.length>0&&e.every(e=>e.startsWith(`/`))){let e=n[t];return e===void 0?void 0:typeof e==`string`?e:JSON.stringify(e)}}}catch{}return e}}function JL(e){if(!e)return{};let t={};for(let n of e){let e=n.indexOf(`:`);e>0&&(t[n.slice(0,e).trim().toLowerCase()]=n.slice(e+1).trim())}return t}async function YL(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await VL(t,{});if(!e.ok)return{error:`HTTP ${e.status}`};let n=await e.text();return{doc:JSON.parse(n),raw:n}}catch(e){return e instanceof DOMException&&e.name===`AbortError`?{error:`Request timed out after 15s`}:e instanceof SyntaxError?{error:`Invalid JSON`}:{error:e.message}}}async function XL(e){let t=new URL(`/llms.txt`,e).href,n=`llms.txt found and nonempty`;try{let e=await VL(t,{});if(!e.ok)throw Error(`HTTP ${e.status}`);let r=(await e.text()).trim();if(!r)throw Error(`Empty document`);let i=e.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase();if(i&&!i.startsWith(`text/`)||i===`text/html`||/^<(?:!doctype html|html|head|body)\b/i.test(r))throw Error(`Expected text documentation, received non-text or HTML content`);return Q(n,t)}catch(e){return{label:n,detail:`${t}: ${e.message}`,severity:`suggested`,hint:`Serve nonempty text documentation at /llms.txt.`}}}function ZL(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=eR(i.parameters);for(let[a,o]of Object.entries(i)){if(!UL.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=tR(r,eR(i.parameters)),c=s.length>0?s:void 0;if(i[`x-payment-info`]){let n=i[`x-payment-info`];t.push({method:a.toUpperCase(),path:e,amount:n.amount,parameters:c})}else{let t=i.responses;t&&`402`in t&&n.push({method:a.toUpperCase(),path:e,parameters:c})}}}return t.length>0?t:n}function QL(e,t){let n=e.paths;if(!n)return;let r=n[t.path];if(!r)return;let i=r[t.method.toLowerCase()];if(!i?.requestBody)return;let a=i.requestBody.content?.[`application/json`];if(!a)return;if(a.example)return JSON.stringify(a.example);if(a.examples&&typeof a.examples==`object`){let e=Object.values(a.examples)[0];if(e?.value)return JSON.stringify(e.value)}let o=a.schema,s=new Set;if(o=rR(o,e,s),!o||o.type!==`object`)return;let c=iR(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function $L(e,t,n){if(!t.path.startsWith(`/`)||t.path.startsWith(`//`)||t.path.includes(`\\`))throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let r=t.path;t.parameters&&(r=nR(r,t.parameters));let i=r.startsWith(`/`)?r.slice(1):r,a=new URL(e.replace(/\/?$/,`/`)),o=new URL(i,a);if(o.origin!==a.origin)throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let s=o.href;if(n){let e=new URL(s);for(let t of n){let[n,...r]=t.split(`=`);n&&e.searchParams.set(n,r.join(`=`))}s=e.href}return s}function eR(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;e.in===`path`&&typeof e.name==`string`&&t.push(e.schema&&typeof e.schema==`object`?{name:e.name,in:`path`,schema:e.schema,example:e.example}:{name:e.name,in:`path`,example:e.example})}return t}function tR(e,t){let n=[...e];for(let e of t){let t=n.findIndex(t=>t.name===e.name);t>=0?n[t]=e:n.push(e)}return n}function nR(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{let r=t.find(e=>e.name===n&&e.in===`path`);if(!r)return e;let i=r.example??r.schema?.example??r.schema?.default;return i===void 0?e:encodeURIComponent(String(i))})}function rR(e,t,n){if(!e||typeof e.$ref!=`string`)return e;if(n?.has(e.$ref))return;let r=e.$ref.replace(/^#\//,``).split(`/`),i=t;for(let e of r)if(i&&typeof i==`object`)i=i[e];else return;return i}function iR(e,t,n){let r=rR(e,t,n)??e;if(r.const!==void 0)return r.const;if(r.example!==void 0)return r.example;if(r.default!==void 0)return r.default;switch(r.type){case`string`:return r.enum&&Array.isArray(r.enum)?r.enum[0]:r.format===`email`?`test@example.com`:r.format===`uuid`?`00000000-0000-0000-0000-000000000000`:r.format===`uri`||r.format===`url`?`https://example.com`:r.format===`date`?`2026-01-01`:r.pattern===`^\\d{5}(?:-\\d{4})?$`?`10001`:r.pattern===`^[A-Z]{2}$`?`US`:`test`;case`number`:case`integer`:return r.minimum??1;case`boolean`:return!0;case`array`:return[];case`object`:{let e=r.properties;if(!e)return{};let i=r.required||[],a={};for(let r of i){let i=e[r];i&&(a[r]=iR(i,t,n))}return a}default:return null}}CS(),Bx(),Dw(),qk();const aR=Object.values(Ze);function oR(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&aR.find(e=>e.id===t.chainId)?.testnet===!0}async function sR(e,t,n,r){let i=[],a;try{a=$L(e,t,r?.query)}catch(e){return i.push($(`Request URL valid`,e.message)),{results:i}}let o=JL(r?.extraHeaders),s;r?.body&&!r.bodyIsAutogenerated&&(s=r.body,o[`content-type`]||=`application/json`);let c;try{let e={method:t.method};Object.keys(o).length>0&&(e.headers=o),s&&(e.body=s),c=await VL(a,e)}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}if(!s&&(c.status===400||c.status===422)){let e=r?.body??(r?.discoveryDoc?QL(r.discoveryDoc,t):void 0);if(e){n&&console.log(X.dim(` Retrying with body: ${e}`)),s=e,o[`content-type`]=`application/json`;try{c=await VL(a,{method:t.method,headers:o,body:s})}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}}}if(c.status!==402)return c.status===200?i.push(IL(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(IL(`Returns 402 without credentials`,`Got ${c.status} (endpoint requires auth before payment gate)`)):i.push($(`Returns 402 without credentials`,`Got ${c.status} instead`,c.status===400||c.status===422?`Server requires a valid request body before returning 402. Add a requestBody schema with examples to your OpenAPI doc, or use --body.`:`Endpoints that require payment must return HTTP 402 with a WWW-Authenticate: Payment header when no valid credential is provided.`)),{results:i};i.push(Q(`Returns 402 without credentials`));let l=c.headers.get(q.wwwAuthenticate),u=vR(c);if(!l)return u.length>0?(i.push(IL(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(IL(`Not an MPP endpoint`,`No WWW-Authenticate header (may be x402 or other protocol)`)),{results:i};if(u.length>0&&i.push(...u),!l.startsWith(`${Fx.payment} `))return i.push(IL(`Not an MPP endpoint`,`WWW-Authenticate scheme is not Payment`)),{results:i};i.push(Q(`WWW-Authenticate header present`,`Payment scheme`));let d;try{d=mS(c)}catch(e){let t=e.message;i.push($(`Challenge parseable`,t,`The Payment challenge must include a request="<base64url>" parameter containing JSON-encoded payment details.`));let n=l.slice(l.indexOf(` `)+1);return i.push(FL(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0)return i.push($(`Challenge parseable`,`No Payment challenges found in header`)),{results:i};let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push(Q(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=new URL(e).hostname;cR(d,i),lR(d,i),uR(d,i),dR(d,p,i);let m=d.length>1;for(let e of d){let t=e.request;fR(e,t,i,m)}if(n)for(let e of d)console.log(X.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function cR(e,t){let n=e.filter(e=>!e.id);n.length===0?t.push(Q(`Challenge has id`)):t.push($(`Challenge has id`,`${n.length} missing`,`Every challenge must include a unique id field.`))}function lR(e,t){let n=e.filter(e=>!e.realm);n.length===0?t.push(Q(`Challenge has realm`)):t.push($(`Challenge has realm`,`${n.length} missing`,`Set realm to your server's hostname.`))}function uR(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(FL(`Challenge has expiration`,`missing expires field`,`Add an expires field (ISO 8601) to prevent replay attacks.`));return}if(new Date(r.expires)<=n){t.push($(`Challenge expires in the future`,`Expired at ${r.expires}`,`The expires timestamp must be in the future.`));return}}let r=Math.min(...e.map(e=>new Date(e.expires).getTime()-n.getTime()));t.push(Q(`Challenge expires in the future`,`${Math.round(r/6e4)}m from now`))}function dR(e,t,n){let r=e=>e.toLowerCase().replace(/\.$/,``),i=r(t),a=[...new Set(e.map(e=>e.realm??``))].filter(e=>{let t=r(e);return!t||t!==i&&!i.endsWith(`.${t}`)});a.length>0?n.push($(`Realm matches server hostname`,`realm="${a[0]}" vs host="${t}"`,`Set the realm to your production hostname (or base domain) in the challenge.`)):n.push(Q(`Realm matches server hostname`))}function fR(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===Ix.tempo?pR(t,i,n,e):e.method===Ix.stripe?mR(t,i,n):e.method===Ix.evm&&hR(e,t,i,n)}function pR(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if(WL(e.recipient)?n.push(Q(`${t}Valid recipient address`)):e.recipient===void 0&&a?n.push(Q(`${t}Uses splits (no single recipient)`)):e.recipient===void 0?n.push($(`${t}Valid recipient address`,`Missing recipient (and no splits defined)`,`Set request.recipient to a valid 0x address, or use methodDetails.splits for multiple recipients.`)):n.push($(`${t}Valid recipient address`,`Got: ${String(e.recipient)}`,`Set request.recipient to a valid 0x-prefixed 40-hex-char address.`)),WL(e.currency)){let e=oR(r)?`testnet`:`mainnet`;n.push(Q(`${t}Valid currency address`,e))}else n.push($(`${t}Valid currency address`,`Got: ${String(e.currency)}`,`Set request.currency to a valid token address.`));gR(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function mR(e,t,n){gR(e,t,n,`currency's smallest unit (e.g. "100" = $1.00 for USD)`);let r=e.currency;typeof r==`string`&&/^[a-z]{3}$/i.test(r)?n.push(Q(`${t}Valid currency code`,r.toUpperCase())):n.push($(`${t}Valid currency code`,r?`Got: ${r}`:`missing`,`Must be a three-letter ISO currency code (e.g. "usd").`));let i=e.methodDetails,a=i?.networkId;a?n.push(Q(`${t}Has networkId`,a.slice(0,20))):n.push($(`${t}Has networkId`,`Missing methodDetails.networkId`,`Set methodDetails.networkId to your Stripe Business Network profile ID.`));let o=i?.paymentMethodTypes;Array.isArray(o)&&o.length>0?n.push(Q(`${t}Has paymentMethodTypes`,o.join(`, `))):n.push($(`${t}Has paymentMethodTypes`,`Missing or empty`,`Set methodDetails.paymentMethodTypes to an array (e.g. ["card"]).`))}function hR(e,t,n,r){if(WL(t.recipient)?r.push(Q(`${n}Valid recipient address`)):r.push($(`${n}Valid recipient address`,`Got: ${String(t.recipient)}`,`Set request.recipient to a valid 0x-prefixed Ethereum address.`)),WL(t.currency)){let t=oR(e)?`testnet`:`mainnet`;r.push(Q(`${n}Valid currency address`,t))}else r.push($(`${n}Valid currency address`,`Got: ${String(t.currency)}`,`Set request.currency to a valid ERC-20 token contract address.`));gR(t,n,r,`token's smallest unit`);let i=t.methodDetails?.chainId;typeof i==`number`&&i>0?r.push(Q(`${n}Has chainId`,String(i))):r.push($(`${n}Has chainId`,`Missing methodDetails.chainId`,`Set methodDetails.chainId to the EVM chain ID.`))}function gR(e,t,n,r){GL(e.amount)?n.push(Q(`${t}Amount is valid integer string`)):e.amount===void 0||e.amount===null?n.push($(`${t}Amount is valid integer string`,`Missing amount`,`Set request.amount to a string of digits in the ${r}.`)):n.push($(`${t}Amount is valid integer string`,`Got: ${String(e.amount)}`,`request.amount must be a string of digits (no decimals, no prefix).`))}async function _R(e,t,n){let r=[],i=$L(e,t,n?.query),a=JL(n?.extraHeaders),o=n?.challenge?vS(n.challenge):q.authorization;a[o.toLowerCase()]=`${Fx.payment} dGhpcyBpcyBnYXJiYWdl`;let s;n?.body&&(s=n.body,a[`content-type`]||=`application/json`);try{let e=await VL(i,{method:t.method,headers:a,body:s??null});e.status===402?(r.push(Q(`Malformed credential returns 402`,`not 500`)),e.headers.get(q.wwwAuthenticate)?.startsWith(`${Fx.payment} `)?r.push(Q(`Error response includes fresh challenge`)):r.push(FL(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the ${o} header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(FL(`Malformed credential returns 402`,`Got ${e.status}`,`When the ${o} header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function vR(e){let t=[],n=e.headers.get(`payment-required`)??e.headers.get(`x-payment-required`);if(!n)return t;let r=e.headers.get(`payment-required`)?`PAYMENT-REQUIRED`:`X-Payment-Required`;try{let e=bw(n);t.push(Q(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(FL(`x402 payment challenge`,`${r} header present but failed schema validation`,`Ensure the PAYMENT-REQUIRED header contains a valid base64-encoded JSON payload matching the x402 schema.`))}return t}const yR=[`No discovery document found, endpoints could not be automatically found.`,`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,`The MPP SDKs can automatically expose this endpoint. See https://mpp.dev/sdk.`,``,`To test a specific endpoint: mppx validate <url> --endpoint POST:/your/path`].join(`
251
+ `);nS();const bR={fundingCurrency:J.optional(J.string()),method:J.string(),reference:J.string(),externalId:J.optional(J.string()),subscriptionId:J.optional(J.string()),status:J.literal(`success`),timestamp:qx()};J.object(bR);const xR=J.looseObject(bR);function SR(e){let t=A.toString(e);return CR(JSON.parse(t))}function CR(e){return xR.parse(e)}CS(),rT(),Bx(),mF(),vk(),fk(),RD(),sA(),qk();async function wR(e,t,n){try{n||console.log(X.dim(` Provisioning testnet wallet and funding via faucet...`));let t=ye(),r=xe(t),i=M({chain:Se,transport:de()});if(OO(e)){let{chainId:t,operator:n}=e.request.methodDetails??{};if(t===Se.id&&typeof n==`string`&&fe(n)&&n!==ve){let e=await Le.faucet.fund(i,{account:n});await Promise.all(e.map(e=>Pe(i,{hash:e})))}}let a=await Le.faucet.fund(i,{account:r});await Promise.all(a.map(e=>Pe(i,{hash:e}))),n||console.log(X.dim(` Using wallet: ${r.address}`));let o=e.request.currency;if(typeof o==`string`)for(let e=0;e<10;e++){let e=await Le.token.getBalance(i,{account:r.address,token:o}).catch(()=>void 0);if(e&&e.amount>0n)break;await new Promise(e=>setTimeout(e,500))}return{methods:[...dF({account:r})]}}catch(e){t&&console.log(X.dim(` Provisioning failed: ${e.message}`));return}}async function TR(){let e=eA(),{isTempoAccount:t}=await Promise.resolve().then(()=>(qk(),yk)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(JF(),hF));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await iA()).address}catch{return}}function ER(e){try{let{execSync:t}=m,n=t(`stripe config --list`,{encoding:`utf8`,timeout:5e3}).match(/test_mode_api_key\s*=\s*'([^']+)'/);if(n?.[1])return e&&console.log(X.dim(` Using Stripe test key from stripe CLI`)),n[1]}catch{}}async function DR(e,t,n){let r=M({chain:e,transport:de()}),[i,a,o]=await Promise.all([n?Oe(r,{address:t,abi:se,functionName:`balanceOf`,args:[n]}):0n,Oe(r,{address:t,abi:se,functionName:`decimals`}),Oe(r,{address:t,abi:se,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,decimals:a,symbol:o??void 0}}function OR(e){return Object.values(Ze).find(t=>t.id===e)}function kR(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function AR(e){switch(e.method){case Ix.evm:return`no EVM payment plugin yet`;case`solana`:return`no Solana payment plugin yet`;default:return`no plugin for ${e.method}/${e.intent}`}}async function jR(e,t,n,r){let i=[],a=$L(e,t,r.query),o=JL(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await VL(a,{method:t.method,headers:o,body:s??null})}catch(e){return i.push($(`Payment: fetch challenge`,e.message)),i}if(c.status!==402)return i.push(IL(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=mS(c)}catch(e){return i.push($(`Payment: parse challenge`,e.message)),i}if(l.length===0)return i.push($(`Payment: parse challenge`,`No Payment challenges in response`)),i;let u=[];dR(l,new URL(a).hostname,u);let d=u.filter(e=>e.severity===`fail`);if(d.length>0)return i.push(...d),r.onResults?.(d),i;let f=await oI().catch(()=>void 0),p=l.find(e=>{if(e.method!==Ix.tempo||iI(f?.config)?.some(t=>t.name===e.method&&t.intent===e.intent))return!1;let t=e.request.methodDetails;return typeof t?.chainId==`number`&&t.chainId!==pk.mainnet});if(p){let e=await wR(p,n,r.silent);if(e)try{let r=RR((e,t)=>VL(e,t??{},3e4));await IR(i,await tE({methods:e.methods,polyfill:!1,async onChallenge(e,{createCredential:t}){cI(p,e);let n=await t(await eI(e,f?.config.extensions));return i.push(Q(`Payment: submitted`,`ephemeral testnet wallet`)),n},fetch:r.fetch}).fetch(a,{method:t.method,headers:o,body:s??null}),n,Se,OO(p),r.receipt)}catch(e){i.push($(`Payment: create credential`,e.message))}else i.push($(`Payment: auto-provision wallet`,`Failed to create and fund testnet wallet`));r.onResults?.(i)}let m=r.interactive,h=process.env.MPPX_STRIPE_SECRET_KEY??ER(n),g=h?.startsWith(`sk_test_`)||h?.startsWith(`rk_test_`),_=new Set([Ix.tempo,Ix.evm,Ix.stripe]);for(let e of l){if(e===p||!_.has(e.method))continue;r.silent||console.log(``);let c=i.length,l=()=>{r.onResults&&i.length>c&&r.onResults(i.slice(c))},u=`Payment [${e.method}]`;try{switch(e.method){case Ix.tempo:case Ix.evm:await MR(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,options:r});break;case Ix.stripe:await NR(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,isStripeTestKey:g??!1,stripeKey:h,options:r})}}finally{l()}}return i}async function MR(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u}=n,d=e.request,f=d.methodDetails,p=GL(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,{plugin:g,method:_}=tI(e,l?.config);if(!g&&!_){r.push(IL(t,AR(e)));return}let v;if(!_){try{v=await TR()}catch{}if(!v){r.push(IL(t,`no wallet configured. Run "mppx account create" to create one.`));return}}let y;if(e.method===Ix.tempo){let e=f?.chainId??(_?void 0:P.id);e!==void 0&&(y=e===Se.id?Se:OR(e))}else if(e.method===Ix.evm){let e=f?.chainId;e&&(y=OR(e))}if(p&&h&&!y){r.push(IL(t,`unable to resolve payment chain and verify token decimals`));return}let b;if(p&&h&&y)try{let n;if(e.method===Ix.tempo){let e=await zk(M({chain:y,transport:de()}),h,v??ve,{requireDecimals:!0});n=e.balance,m=e.decimals,b=e.symbol}else{let e=await DR(y,h,v);n=e.balance,m=e.decimals,b=e.symbol}if(v&&n<p){let e=kR(p,m),i=kR(n,m),a=b??`tokens`;r.push(IL(t,`insufficient balance (have ${i}, need ${e} ${a} on ${y.name})`,`Fund wallet ${v} with at least ${e} ${a} on ${y.name}.`));return}}catch(e){c&&console.log(X.dim(` Balance check skipped: ${e.message}`)),r.push(IL(t,`unable to verify token balance and decimals from the payment chain`));return}let x=p?kR(p,m):`unknown amount`,S=b??(h?.length===3?h.toUpperCase():``),C=y?.name,w=`${x}${S?` ${S}`:``}${C?` on ${C}`:``}`;if(u.silent||console.log(X.dim(v?` Attempting payment with wallet ${v}`:` Attempting payment with configured method`)),!_&&y?.testnet)u.silent||console.log(X.dim(` Auto-approved: ${w} (testnet)`));else if(!u.yes&&!n.isInteractive){r.push(IL(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${w}`));else if(!await jk(` ${X.yellow(`Pay`)} ${w}. Continue?`,!1)){r.push(IL(t,`declined`));return}let T,E,ee;if(g)try{let t=await g.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});T=t.methods,E=t.createCredential,ee=t.credentialContext}catch(e){r.push(IL(t,e.message));return}else T=[_];if(_&&OO(e)){let n=!0,u=RR((e,t)=>VL(e,t??{},3e4)),d=tE({methods:[_],polyfill:!1,async onChallenge(n,{createCredential:i}){let a=await eI(n,l?.config.extensions);cI(e,n);let o=await i(a);return r.push(Q(`${t}: submitted`)),o},fetch:async(t,r)=>n?(n=!1,new Response(null,{status:402,headers:{[q.wwwAuthenticate]:iS(e)}})):u.fetch(t,r)});try{await IR(r,await d.fetch(i,{method:a.method,headers:o,body:s??null}),c,y,!0,u.receipt)}catch(e){r.push($(t,e.message))}return}let D=await PR(e,T,E,t,r,l?.config.extensions,ee,i);D&&(g?.prepareCredentialRequest?.({challenge:e,credential:D,headers:o}),await FR(r,i,a,D,o,s,c,y,vS(e),OO(e)))}async function NR(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u,stripeKey:d}=n,{plugin:f,method:p}=tI(e,l?.config);if(!f&&!p){r.push(IL(t,`no Stripe payment method available`));return}let m=!!(f&&!l?.config.plugins?.includes(f)&&n.isStripeTestKey),h=e.request,g=GL(h.amount)?BigInt(h.amount):void 0,_=h.decimals??2,v=h.currency,y=g?kR(g,_):`unknown amount`,b=v?.length===3?v.toUpperCase():``,x=`${y}${b?` ${b}`:``} via Stripe${m?` (testmode)`:``}`;if(m)u.silent||console.log(X.dim(` Attempting: ${x}`));else if(!u.yes&&!n.isInteractive){r.push(IL(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${x}`));else if(!await jk(` ${X.yellow(`Pay`)} ${x}. Continue?`,!1)){r.push(IL(t,`declined`));return}let S,C,w;if(f)try{let t={paymentMethod:`pm_card_visa`};d&&(t.secretKey=d);let n=await f.setup({challenge:e,options:{},methodOpts:t});S=n.methods,C=n.createCredential,w=n.credentialContext}catch(e){r.push(IL(t,e.message));return}else S=[p];let T=await PR(e,S,C,t,r,l?.config.extensions,w,i);if(T){if(f?.prepareCredentialRequest?.({challenge:e,credential:T,headers:o}),m){let n=await VL(i,{method:a.method,headers:{...o,[vS(e)]:T},body:s??null},3e4);n.status>=200&&n.status<300?r.push(Q(`${t}: successful`,`HTTP ${n.status}`)):r.push(IL(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await FR(r,i,a,T,o,s,c,void 0,vS(e))}}async function PR(e,t,n,r,i,a,o,s){let c=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:iS(e)}});try{$w(e,new URL(s),void 0);let l=await eI(e,a,o),u;return u=n?await n(c,l):await tE({methods:t,polyfill:!1}).createCredential(c,l),i.push(Q(`${r}: submitted`)),u}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(IL(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function FR(e,t,n,r,i,a,o,s,c=q.authorization,l=!1){let u;try{u=await VL(t,{method:n.method,headers:{...i,[c]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}return IR(e,u,o,s,l)}async function IR(e,t,n,r,i=!1,a){if(t.status===402){let n=await t.text().catch(()=>``),r=`Payment rejected`;try{let e=JSON.parse(n);r=e.detail??e.title??r}catch{}return e.push($(`Payment: accepted`,r,`The server rejected a valid credential. Check that your payment verification logic accepts the credential format and that the payment was processed on-chain.`)),e}if(t.status>=400&&t.status<500)e.push(FL(`Payment: post-payment response`,`Got ${t.status}`,`Payment succeeded but the endpoint returned a client error. The endpoint likely requires request body parameters. Use --body to provide them.`));else if(t.status>=500)return e.push($(`Payment: server response`,`Got ${t.status}`,`Payment was accepted but the server errored while generating the response. Check server logs for the underlying error.`)),e;else e.push(Q(`Payment: successful`,`HTTP ${t.status}`));let o=t.headers.get(`content-type`)??``,s=t.headers.get(q.paymentReceipt),c=!s&&i&&OD(t),l=await t.text().catch(()=>``);if(c){let t=a?.(),n=t===void 0?LR(l):t??void 0;n?e.push(Q(`Payment receipt in event stream`,n.reference)):e.push($(`Payment receipt in event stream`,void 0,`SSE session responses without a Payment-Receipt header must end with an "event: payment-receipt" carrying the session receipt.`))}else if(!s)e.push($(`Payment-Receipt header present`,void 0,`After accepting payment, include a Payment-Receipt header with a base64url-encoded JSON object containing: method, reference, status ("success"), and timestamp (ISO 8601).`));else{e.push(Q(`Payment-Receipt header present`));try{let t=SR(s);if(e.push(Q(`Receipt parseable`)),t.status===`success`?e.push(Q(`Receipt status is "success"`)):e.push($(`Receipt status is "success"`,`Got: ${t.status}`)),t.reference){let n=/^0x[0-9a-fA-F]{64}$/.test(t.reference),r=t.reference.startsWith(`pi_`);n||r?e.push(Q(`Receipt reference valid`,t.reference.slice(0,20)+`...`)):e.push(FL(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(FL(`Receipt has reference`,`No reference field`));if(t.timestamp){let n=new Date(t.timestamp),r=Date.now()-n.getTime();r<6e4?e.push(Q(`Receipt timestamp recent`,`${Math.round(r/1e3)}s ago`)):e.push(FL(`Receipt timestamp recent`,`${Math.round(r/6e4)}m ago`))}n&&console.log(X.dim(` Receipt: ${JSON.stringify(t,null,2)}`))}catch(t){e.push($(`Receipt parseable`,t.message))}}if(l.length>0)e.push(Q(`Response body non-empty`,`${o.split(`;`)[0]}, ${HL(l.length)}`));else{let n=[...t.headers.entries()].filter(([e])=>!e.startsWith(`x-`)&&![`content-type`,`content-length`,`date`,`server`,`connection`,`keep-alive`,`cache-control`,`vary`,`access-control-allow-origin`,`payment-receipt`,`payment-session`,`payment-session-snapshot`].includes(e.toLowerCase()));n.length>0?e.push(FL(`Response body empty -- data may be in headers only`,n.map(([e])=>e).join(`, `))):e.push(FL(`Response body empty`))}if(o?e.push(Q(`Content-Type header set`,o.split(`;`)[0])):e.push(FL(`Content-Type header set`)),s)try{let t=SR(s);if(t.reference&&/^0x[0-9a-fA-F]{64}$/.test(t.reference)){let n=r?.blockExplorers?.default?.url;if(n){let r=n.includes(`tempo`)?`receipt`:`tx`;e.push(Q(`On-chain transaction`,`${n}/${r}/${t.reference}`))}}}catch{}return e}function LR(e){for(let t of e.replace(/\r\n|\r/g,`
250
252
  `).split(`
251
253
 
252
- `)){let e=DD(t);if(e?.type===`payment-receipt`)return e.data}}function DR(e){let t;return{async fetch(n,r){let i=await e(n,r);if(!i.body||!ED(i)||i.headers.get(q.paymentReceipt))return i;t??=null;let a=new TextDecoder,o=[],s=0,c=!1,l=!1,u=(e,n)=>{let r=c?`\r${e}`:e;c=!n&&r.endsWith(`\r`),c&&(r=r.slice(0,-1));let i=r.replace(/\r\n|\r/g,`
254
+ `)){let e=kD(t);if(e?.type===`payment-receipt`)return e.data}}function RR(e){let t;return{async fetch(n,r){let i=await e(n,r);if(!i.body||!OD(i)||i.headers.get(q.paymentReceipt))return i;t??=null;let a=new TextDecoder,o=[],s=0,c=!1,l=!1,u=(e,n)=>{let r=c?`\r${e}`:e;c=!n&&r.endsWith(`\r`),c&&(r=r.slice(0,-1));let i=r.replace(/\r\n|\r/g,`
253
255
  `),a=[];i.startsWith(`
254
256
  `)&&o.at(-1)?.endsWith(`
255
257
  `)&&(a.push(o.join(``).slice(0,-1)),o=[],s=0,i=i.slice(1));for(let e=i.indexOf(`
@@ -258,18 +260,18 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
258
260
 
259
261
  `))a.push(o.join(``)+i.slice(0,e)),o=[],s=0,i=i.slice(e+2);i&&(o.push(i),s+=i.length),n&&(a.push(o.join(``)),o=[],s=0),l&&a.length>0&&(a.shift(),l=!1),s>1048576&&(o=o.at(-1)?.endsWith(`
260
262
  `)?[`
261
- `]:[],s=o.length,l=!0);for(let e of a){let n=DD(e);n?.type===`payment-receipt`&&!t&&(t=n.data)}},d=i.body.pipeThrough(new TransformStream({transform(e,t){u(a.decode(e,{stream:!0}),!1),t.enqueue(e)},flush(){u(a.decode(),!0)}})),f=new Response(d,{headers:i.headers,status:i.status,statusText:i.statusText});return Object.defineProperty(f,"url",{value:i.url}),f},receipt:()=>t}}async function*OR(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await NR(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=IL(e.body,i.path),!a&&r.doc&&(a=VL(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await XL(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(MR),h=p.some(e=>!MR(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 oR(t,i,{body:u,challenge:l?.[0],extraHeaders:e.headers,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults,a=await bR(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 kR(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of OR(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=AR(r,n,{sawTestnet:a,sawMainnet:o});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function AR(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(cR);let a=n.sawMainnet,o=n.sawTestnet,s=i.some(e=>e.label.includes(`[stripe]`)&&e.label.includes(`livemode`));return a&&!o?r.push(`Validate your testnet server to test without real funds (Tempo wallets are automatically provisioned).`):o&&!a&&r.push(`Validate your mainnet server to confirm real payments work end-to-end.`),s&&r.push(`Validate your testmode Stripe server to test card payments end-to-end (auto-pays with test card).`),r}const jR=Object.values(Ye);function MR(e){return jR.find(t=>t.id===e)?.testnet===!0}async function NR(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await zL(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 RL(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=NE(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=FL(t.endpoint);e&&r.push(e)}else if(i){r=BL(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=PL(t.amount)?BigInt(t.amount):e,i=PL(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}}Mx(),Gk();const PR=fb(`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||Ek()){let t=await kR({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 OR({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=>kL(e,n)}))switch(t.phase){case`discovery`:if(OL(`Discovery (/openapi.json)`),kL(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=cR.split(`
262
- `);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++,OL(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),kL(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`)),kL(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}FR(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function FR(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 IR(e){return RR(e)?e.offers:[e]}function LR(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=zR(t.amount)??zR(i.amount)??null,o=zR(t.currency)??zR(i.currency),s=zR(e.description)??zR(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 RR(e){return`offers`in e&&!(`_canonicalRequest`in e)}function zR(e){return typeof e==`string`?e:void 0}var BR=I((()=>{})),VR=tt({generate:()=>HR,generateProxy:()=>UR});function HR(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=>GR(e,r));return WR({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function UR(e){let t=e.routes.map(t=>({...t,path:KR(e.basePath,t.path)}));return WR({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function WR(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`]=EE.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 GR(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:IR(t).map(LR)},...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:Vx(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:LR(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function KR(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var qR=I((()=>{Ux(),ME(),BR()}));Mx(),SS(),QT(),nT(),hw(),Ow(),jw(),zx(),uk(),Ew(),eC(),XC(),aA(),Gk();const JR=`0.17.4`,YR=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),XR=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),ZR=p.object({message:p.string(),path:p.string(),severity:p.string()}),QR=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),$R=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function ez(e){return e.format===`json`&&e.formatExplicit}function tz(e,t,n){if(ez(e))return e.ok(t);n()}async function nz(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 rz(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function iz(e){return typeof e==`string`?e:void 0}function az(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function oz(e){let t=az(e);return{...iz(e.description)?{description:iz(e.description)}:{},id:iz(e.id)??iz(e.name)??`unknown`,...iz(e.name)?{name:iz(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...iz(e.status)?{status:iz(e.status)}:{},...iz(e.serviceUrl)||iz(e.url)?{url:iz(e.serviceUrl)??iz(e.url)}:{}}}function sz(e){return{...iz(e.description)?{description:iz(e.description)}:{},method:iz(e.method)??`GET`,path:iz(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function cz(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=iz(t.amount),r=iz(t.currency),i=iz(t.method),a=iz(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function lz(e){return e.request.currency??e.request.asset}function uz(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=lz(e);return typeof t==`string`&&t.toLowerCase()===n})}async function dz(e,t,n={}){let r=()=>mw().getChallenges(e),i=()=>Dw().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 fz(e){return kw({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function pz(e,t){if(!QS(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:rS(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[MC]:Cw({accepts:[DC(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function mz(e){let{host:t,hostname:n,protocol:r}=new URL(e);return r===`https:`||!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function hz(e,t,n,r){let i=t,a=mz(i),o={...n,redirect:`manual`,headers:sT(n.headers)};a.host&&vz(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=sT(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=mz(i),a.host&&vz(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 gz(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&_z(i),mz(i.href)}function _z(e){throw new L({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function vz(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function yz(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function bz(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new L({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new L({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function xz(e,t){let n=t.toLowerCase();return e.find(e=>{let t=iz(e.id)?.toLowerCase(),r=iz(e.name)?.toLowerCase();return t===n||r===n})}const Sz=fb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:JR,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (disables payment retries)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await iI(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=sA(),i={"User-Agent":e.options.userAgent??`mppx/${JR}${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=tI(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure??!1,u=l?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,d=mz(o),f=d.url;d.host&&(i.Host=d.host);try{let r=Tk(e.options.methodOpt),a=SI(),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&&vk(o,s,t);let p=await hz(u,o,s,e.options.location??!1),m=p.response;if(l&&m.status===402)return e.error({code:`INSECURE_PAYMENT`,message:`Payment requires verified TLS. Install a trusted certificate and omit --insecure.`,exitCode:2});if(m.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&m.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${m.status}`,exitCode:22});yk(m,c),await nz(m);return}let h=m.url?new URL(m.url):void 0,g=d.host!==void 0&&h?.hostname===`127.0.0.1`,_=await dz(m,e.options.protocol,{ignoreX402ResponseUrl:g});if(_.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let v=uz(_,e.options.currency);if(e.options.currency&&v.length===0){let t=_.map(lz).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let y=nI(n?.config)?.length?v:await hF(v,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),b=eI(y,n?.config);if(!b){let t=y.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:x,plugin:S,method:C}=b,w=QS(x),T=w?void 0:gz(o,d,p.logicalUrl);if(!w)try{Qw(x,new URL(p.logicalUrl||o),void 0)}catch(t){return e.error({code:`UNTRUSTED_PROOF_REALM`,message:t.message,exitCode:1})}let ee=pz(x,m),te=x.request.currency??``,E=x.request.decimals??6,D,k;S&&(k=await S.setup({challenge:x,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),te=k.tokenSymbol,E=k.tokenDecimals,D=k.explorerUrl);let ne=!e.options.silent&&e.options.confirm,A=new Set;{yk(m,x.method===`tempo`&&x.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(x))e.has(n)||r===void 0||t.push([n,Sk(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:te,tokenDecimals:E,explorerUrl:D},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(x.request))e.has(n)||i===void 0||t.push([n,bk(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=x.request.methodDetails;if(!e)return[];let t=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if(n===`memo`&&typeof i==`string`){let e=xk(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,bk(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)A.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||ne){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
263
- `);t(` ${X.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${l}${e}\n`)}}}if(ne&&(t(`
264
- `),!await kk(`Proceed with ${x.intent}?`,!0))){t(`Aborted.
265
- `);return}}let j=process.env.MPPX_PRIVATE_KEY?.trim()||!Dk(Qk(e.options.account));if(EO(x)&&j&&!C){try{await CL({challenge:x,challengeResponse:ee,credentialContext:await QF(x,n?.config.extensions,k?.credentialContext),endpoint:p.logicalUrl,fetch:u,fetchInput:T.url,init:{...p.init,redirect:`manual`},info:t,methodOptions:r,options:{account:e.options.account,fail:e.options.fail,include:e.options.include,network:e.options.network,rpcUrl:e.options.rpcUrl,session:e.options.session,silent:e.options.silent,verbose:e.options.verbose},registry:a})}catch(e){return fL(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:C&&EO(x)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let M=C&&EO(x)?void 0:await QF(x,n?.config.extensions,k?.credentialContext),re,ie;if(C&&EO(x)){let e=ee;re=await eE({methods:[C],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await QF(e,n?.config.extensions,k?.credentialContext);return oI(x,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return u(t,n)}}).fetch(T.url,{...p.init,context:M,redirect:`manual`})}else{if(k?.createCredential)ie=await k.createCredential(ee,M);else if(k)ie=await eE({methods:k.methods,polyfill:!1,transport:fz(x)}).createCredential(ee,M);else if(C)ie=await eE({methods:[C],polyfill:!1,transport:fz(x)}).createCredential(ee,M);else throw Error(`unreachable`);let n=w?NC:_S(x),r={...sT(p.init.headers),[n]:ie},i=w?mz((yz(x)??m.url)||o):T;w&&vz(r,i.host),S?.prepareCredentialRequest?.({challenge:x,credential:ie,headers:r});let a={...p.init,redirect:`manual`,headers:r};e.options.verbose>=2&&vk(i.url,a,t),re=await u(i.url,a)}if(e.options.fail&&re.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${re.status}`,exitCode:22});if(re.status===402){let n=await re.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,Ck(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(yk(re,c),!(ie&&await S?.handleResponse?.({challenge:x,credential:ie,response:re,fetchUrl:f,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:ne,confirm:kk,tokenSymbol:te,tokenDecimals:E,explorerUrl:D,shownKeys:A}))){let n=re.headers.get(q.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(O.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||A.has(t)||t===`reference`&&o)continue;let e=S?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${Ak(BigInt(n),te,E)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&D?r.push([t,wk(`${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(`
266
- `)}catch{}await nz(re)}}catch(t){if(t instanceof L)throw t;let n=t instanceof Error?t.cause:void 0,r=n instanceof Error?n:void 0;if(r&&`code`in r){let t=r.code;return t===`ENOTFOUND`?e.error({code:`DNS_ERROR`,message:`Could not resolve host "${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}`})}}}}),Cz=fb(`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=ez(e),n=e.options.account;if(!n){if((await $k().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 Ok(`Account name`);if(!r)return;n=r}}let r=$k(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 Ok(`Enter different name`);if(!i)return;n=i,r=$k(n)}let i=_e(),a=ye(i);await r.set(i),(await $k().list()).length===1&&Zk().set(n);let o=be.blockExplorers?.default?.url,s=o?wk(`${o}/address/${a.address}`,a.address):a.address,c=Mk(e.options),l=jk(e.options.rpcUrl,{network:c});return Nk({network:c,rpcUrl:l}).then(e=>M({chain:e,transport:P(l)})).then(e=>import(`viem/tempo`).then(({Actions:t})=>t.faucet.fund(e,{account:a}).catch(()=>{}))),tz(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 Dk(t)?IF(t)?(Zk().set(t),tz(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 $k(t).get()?(Zk().set(t),tz(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=$k(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=ye(n),i=await Rk(r.address,{includeTestnet:!1});if(!e.options.yes){if(ez(e))return e.error({code:`CONFIRMATION_REQUIRED`,message:`Pass --yes to delete an account in structured mode.`,exitCode:2});let t=be.blockExplorers?.default?.url,n=t?wk(`${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
263
+ `]:[],s=o.length,l=!0);for(let e of a){let n=kD(e);n?.type===`payment-receipt`&&!t&&(t=n.data)}},d=i.body.pipeThrough(new TransformStream({transform(e,t){u(a.decode(e,{stream:!0}),!1),t.enqueue(e)},flush(){u(a.decode(),!0)}})),f=new Response(d,{headers:i.headers,status:i.status,statusText:i.statusText});return Object.defineProperty(f,"url",{value:i.url}),f},receipt:()=>t}}async function*zR(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await WR(t,e);yield{phase:`discovery`,discovery:r,results:r.checks};for(let i of r.endpoints){yield{phase:`endpoint`,endpoint:i};let a,o=!1;e.endpoint?a=e.body:(a=qL(e.body,i.path),!a&&r.doc&&(a=QL(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await sR(t,i,n,{body:a,bodyIsAutogenerated:o,query:e.query,extraHeaders:e.headers,discoveryDoc:r.doc??void 0}),u=c??a,d=s.some(e=>e.severity===`pass`&&e.label===`Challenge parseable`),f=!s.some(e=>e.severity===`fail`),p=(l??[]).filter(e=>e.method!==`stripe`).map(e=>e.request.methodDetails?.chainId).filter(e=>typeof e==`number`),m=p.some(UR),h=p.some(e=>!UR(e)),g=!d&&s.some(e=>e.label===`Not an MPP endpoint`),_=s.some(e=>e.severity===`pass`&&e.label===`WWW-Authenticate header present`),v=s.some(e=>e.severity===`fail`&&e.label===`Challenge parseable`);if(yield{phase:`challenge`,endpoint:i,results:s,isMpp:d,isTestnet:m,isMainnet:h,isNonMppPayment:g,isMalformedChallenge:!d&&_&&v,methods:l?.map(e=>e.method)??[]},d&&(yield{phase:`errorHandling`,endpoint:i,results:await _R(t,i,{body:u,challenge:l?.[0],extraHeaders:e.headers,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults,a=await jR(t,i,n,{body:u,query:e.query,extraHeaders:e.headers,yes:e.yes,silent:!r,interactive:e.interactive,...r&&{onResults:r}});yield{phase:`payment`,endpoint:i,results:a,succeeded:a.some(e=>e.severity===`pass`&&e.label===`Payment: successful`)}}}}async function BR(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of zR(e))switch(t.phase){case`discovery`:n=t.discovery;break;case`endpoint`:i={method:t.endpoint.method,path:t.endpoint.path,challenge:[],errorHandling:[],payment:[]},r.push(i);break;case`challenge`:i&&(i.challenge=t.results),t.isMpp&&(t.isTestnet&&(a=!0),t.isMainnet&&(o=!0));break;case`errorHandling`:i&&(i.errorHandling=t.results);break;case`payment`:i&&(i.payment=t.results)}let s={passed:0,failed:0,warnings:0,suggested:0,skipped:0};if(n)for(let e of n.checks)e.severity===`pass`?s.passed++:e.severity===`fail`?s.failed++:e.severity===`warn`?s.warnings++:e.severity===`suggested`?s.suggested++:e.severity===`skip`&&s.skipped++;for(let e of r)for(let t of[...e.challenge,...e.errorHandling,...e.payment])t.severity===`pass`?s.passed++:t.severity===`fail`?s.failed++:t.severity===`warn`?s.warnings++:t.severity===`suggested`?s.suggested++:t.severity===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=VR(r,n,{sawTestnet:a,sawMainnet:o});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function VR(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(yR);let a=n.sawMainnet,o=n.sawTestnet,s=i.some(e=>e.label.includes(`[stripe]`)&&e.label.includes(`livemode`));return a&&!o?r.push(`Validate your testnet server to test without real funds (Tempo wallets are automatically provisioned).`):o&&!a&&r.push(`Validate your mainnet server to confirm real payments work end-to-end.`),s&&r.push(`Validate your testmode Stripe server to test card payments end-to-end (auto-pays with test card).`),r}const HR=Object.values(Ze);function UR(e){return HR.find(t=>t.id===e)?.testnet===!0}async function WR(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await XL(e));let s=new URL(e).origin,c;t.discoveryPath?c=[new URL(t.discoveryPath,e+`/`).href.replace(/\/openapi\.json$/i,``)]:(c=[e,s,`${s}/api`],c=[...new Set(c)]);let l,u=[];for(let e of c)if(l=await YL(e),`error`in l)u.push(`${e}/openapi.json: ${l.error}`);else break;if(!l||`error`in l)n.push({label:`Document found`,detail:u.join(`; `),hint:`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,severity:`fail`});else{a=!0,n.push({label:`Document found and parseable`,severity:`pass`});let e=PE(l.doc),t=e.filter(e=>e.severity===`error`),r=e.filter(e=>e.severity===`warning`);if(t.length>0){n.push({label:`Valid OpenAPI structure`,detail:`${t.length} error(s)`,severity:`fail`});for(let e of t)n.push({label:e.message,detail:e.path,severity:`fail`})}else o=!0,n.push({label:`Valid OpenAPI structure`,severity:`pass`});for(let e of r)n.push({label:e.message,detail:e.path,severity:`warn`});i=l.doc}if(t.endpoint){let e=KL(t.endpoint);e&&r.push(e)}else if(i){r=ZL(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=GL(t.amount)?BigInt(t.amount):e,i=GL(n.amount)?BigInt(n.amount):e;return r<i?-1:+(r>i)}),r.length>0?n.push({label:`Paid endpoints found`,detail:`${r.length} endpoint(s)`,severity:`pass`}):n.push({label:`Paid endpoints found`,detail:`No endpoints with x-payment-info`,severity:`warn`})}return{found:a,valid:o,endpoints:r,checks:n,doc:i}}Nx(),qk();const GR=pb(`validate`,{description:`Validate an MPP server implementation end-to-end`,args:p.object({url:p.string().describe(`Base URL of the MPP server to validate`)}),options:p.object({endpoint:p.string().optional().describe(`Endpoint to test (METHOD:path). Skips discovery.`),body:p.string().optional().describe(`Request body. With --endpoint, used directly. In discovery mode, JSON with / keys is a per-path mapping.`),query:p.array(p.string()).optional().describe(`Query parameter (key=value, repeatable)`),header:p.array(p.string()).optional().describe(`Request header (key:value, repeatable)`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity level`),yes:p.boolean().default(!1).describe(`Auto-approve mainnet payments`),outputJson:p.boolean().default(!1).describe(`Output results as JSON (auto-enabled in known agent environments)`)}),alias:{endpoint:`e`,header:`H`,verbose:`v`,yes:`y`,outputJson:`j`},async run(e){if(e.options.outputJson||Ok()){let t=await BR({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!1});console.log(JSON.stringify(t,null,2));let n=t.endpoints.length===0&&!e.options.endpoint;(t.summary.failed>0||!t.discovery.found||n)&&process.exit(1);return}let t=e.args.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``);console.log(`\n${X.bold(`mppx validate`)} ${X.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,suggested:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of zR({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!!process.stdin.isTTY,onPaymentResults:e=>BL(e,n)}))switch(t.phase){case`discovery`:if(zL(`Discovery (/openapi.json)`),BL(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=yR.split(`
264
+ `);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,zL(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),BL(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),BL(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}KR(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function KR(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function qR(e){return YR(e)?e.offers:[e]}function JR(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=XR(t.amount)??XR(i.amount)??null,o=XR(t.currency)??XR(i.currency),s=XR(e.description)??XR(t.description),c={amount:a,...o?{currency:o}:{},...s?{description:s}:{},intent:n,method:r},l=new Set([`amount`,`currency`,`description`,`methodDetails`]);for(let[e,n]of Object.entries(t))!l.has(e)&&n!==void 0&&(c[e]=n);return c}function YR(e){return`offers`in e&&!(`_canonicalRequest`in e)}function XR(e){return typeof e==`string`?e:void 0}var ZR=F((()=>{})),QR=rt({generate:()=>$R,generateProxy:()=>ez});function $R(e,t){let n=e.methods,r=new Map,i={};for(let e of n)r.set(`${e.name}/${e.intent}`,e),i[e.intent]=(i[e.intent]??0)+1;for(let e of n)i[e.intent]===1&&r.set(e.intent,e);let a=t.routes.map(e=>nz(e,r));return tz({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function ez(e){let t=e.routes.map(t=>({...t,path:rz(e.basePath,t.path)}));return tz({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function tz(e){let t={};for(let n of e.routes){let e=n.method.toLowerCase(),r={responses:{...n.payment?{402:{description:`Payment Required`}}:{},200:{description:`Successful response`}}};n.payment&&(r[`x-payment-info`]=DE.parse(n.payment)),n.summary&&(r.summary=n.summary),n.requestBody&&(r.requestBody=n.requestBody),t[n.path]||(t[n.path]={}),t[n.path][e]=r}let n={info:e.info,openapi:`3.1.0`,paths:t};return e.serviceInfo&&(n[`x-service-info`]=e.serviceInfo),n}function nz(e,t){if(`handler`in e){let t=e.handler._internal;if(!t)throw Error(`Route ${e.method.toUpperCase()} ${e.path} is missing discovery metadata`);return{method:e.method,path:e.path,payment:{offers:qR(t).map(JR)},...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}let n=t.get(e.intent);if(!n)throw Error(`Unknown intent "${e.intent}" for route ${e.method.toUpperCase()} ${e.path}. Available: ${[...t.keys()].join(`, `)}`);let{description:r,...i}=e.options,a={_canonicalRequest:Hx(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:JR(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function rz(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var iz=F((()=>{Wx(),NE(),ZR()}));Nx(),CS(),$T(),rT(),gw(),kw(),Mw(),Bx(),fk(),Dw(),tC(),ZC(),sA(),qk();const az=`0.17.5`,oz=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),sz=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),cz=p.object({message:p.string(),path:p.string(),severity:p.string()}),lz=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),uz=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function dz(e){return e.format===`json`&&e.formatExplicit}function fz(e,t,n){if(dz(e))return e.ok(t);n()}async function pz(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function mz(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function hz(e){return typeof e==`string`?e:void 0}function gz(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function _z(e){let t=gz(e);return{...hz(e.description)?{description:hz(e.description)}:{},id:hz(e.id)??hz(e.name)??`unknown`,...hz(e.name)?{name:hz(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...hz(e.status)?{status:hz(e.status)}:{},...hz(e.serviceUrl)||hz(e.url)?{url:hz(e.serviceUrl)??hz(e.url)}:{}}}function vz(e){return{...hz(e.description)?{description:hz(e.description)}:{},method:hz(e.method)??`GET`,path:hz(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function yz(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=hz(t.amount),r=hz(t.currency),i=hz(t.method),a=hz(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function bz(e){return e.request.currency??e.request.asset}function xz(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=bz(e);return typeof t==`string`&&t.toLowerCase()===n})}async function Sz(e,t,n={}){let r=()=>hw().getChallenges(e),i=()=>Ow().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}function Cz(e){return Aw({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function wz(e,t){if(!$S(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:iS(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[NC]:ww({accepts:[OC(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function Tz(e){let{host:t,hostname:n,protocol:r}=new URL(e);return r===`https:`||!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function Ez(e,t,n,r){let i=t,a=Tz(i),o={...n,redirect:`manual`,headers:cT(n.headers)};a.host&&kz(o.headers,a.host);for(let t=0;t<=20;t++){let n=await e(a.url,o),s=n.headers.get(`location`);if(!r||!s||![301,302,303,307,308].includes(n.status))return{init:o,logicalUrl:i,response:n,target:a};if(t===20)throw TypeError(`Too many redirects`);await n.body?.cancel().catch(()=>{});let c=new URL(s,i),l=new URL(i),u=cT(o.headers);if(c.origin!==l.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];let d=(o.method??(o.body?`POST`:`GET`)).toUpperCase(),f=n.status===303&&d!==`GET`&&d!==`HEAD`||(n.status===301||n.status===302)&&d===`POST`;if(f)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];i=c.href,a=Tz(i),a.host&&kz(u,a.host);let p={...o};f&&(delete p.body,p.method=`GET`),o={...p,headers:u,redirect:`manual`}}throw TypeError(`Too many redirects`)}function Dz(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&Oz(i),Tz(i.href)}function Oz(e){throw new I({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function kz(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function Az(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function jz(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new I({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new I({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function Mz(e,t){let n=t.toLowerCase();return e.find(e=>{let t=hz(e.id)?.toLowerCase(),r=hz(e.name)?.toLowerCase();return t===n||r===n})}const Nz=pb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:az,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (disables payment retries)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await oI(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=lA(),i={"User-Agent":e.options.userAgent??`mppx/${az}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=rI(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure??!1,u=l?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,d=Tz(o),f=d.url;d.host&&(i.Host=d.host);try{let r=Dk(e.options.methodOpt),a=wI(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&bk(o,s,t);let p=await Ez(u,o,s,e.options.location??!1),m=p.response;if(l&&m.status===402)return e.error({code:`INSECURE_PAYMENT`,message:`Payment requires verified TLS. Install a trusted certificate and omit --insecure.`,exitCode:2});if(m.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&m.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${m.status}`,exitCode:22});xk(m,c),await pz(m);return}let h=m.url?new URL(m.url):void 0,g=d.host!==void 0&&h?.hostname===`127.0.0.1`,_=await Sz(m,e.options.protocol,{ignoreX402ResponseUrl:g});if(_.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let v=xz(_,e.options.currency);if(e.options.currency&&v.length===0){let t=_.map(bz).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let y=iI(n?.config)?.length?v:await _F(v,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),b=nI(y,n?.config);if(!b){let t=y.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:x,plugin:S,method:C}=b,w=$S(x),T=w?void 0:Dz(o,d,p.logicalUrl);if(!w)try{$w(x,new URL(p.logicalUrl||o),void 0)}catch(t){return e.error({code:`UNTRUSTED_PROOF_REALM`,message:t.message,exitCode:1})}let E=wz(x,m),ee=x.request.currency??``,D=x.request.decimals??6,O,k;S&&(k=await S.setup({challenge:x,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),ee=k.tokenSymbol,D=k.tokenDecimals,O=k.explorerUrl);let te=!e.options.silent&&e.options.confirm,ne=new Set;{xk(m,x.method===`tempo`&&x.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(x))e.has(n)||r===void 0||t.push([n,wk(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:ee,tokenDecimals:D,explorerUrl:O},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(x.request))e.has(n)||i===void 0||t.push([n,Sk(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=x.request.methodDetails;if(!e)return[];let t=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if(n===`memo`&&typeof i==`string`){let e=Ck(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,Sk(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)ne.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||te){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
265
+ `);t(` ${X.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${l}${e}\n`)}}}if(te&&(t(`
266
+ `),!await jk(`Proceed with ${x.intent}?`,!0))){t(`Aborted.
267
+ `);return}}let j=process.env.MPPX_PRIVATE_KEY?.trim()||!kk(eA(e.options.account));if(OO(x)&&j&&!C){try{await TL({challenge:x,challengeResponse:E,credentialContext:await eI(x,n?.config.extensions,k?.credentialContext),endpoint:p.logicalUrl,fetch:u,fetchInput:T.url,init:{...p.init,redirect:`manual`},info:t,methodOptions:r,options:{account:e.options.account,fail:e.options.fail,include:e.options.include,network:e.options.network,rpcUrl:e.options.rpcUrl,session:e.options.session,silent:e.options.silent,verbose:e.options.verbose},registry:a})}catch(e){return mL(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:C&&OO(x)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let re=C&&OO(x)?void 0:await eI(x,n?.config.extensions,k?.credentialContext),M,ie;if(C&&OO(x)){let e=E;M=await tE({methods:[C],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await eI(e,n?.config.extensions,k?.credentialContext);return cI(x,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return u(t,n)}}).fetch(T.url,{...p.init,context:re,redirect:`manual`})}else{if(k?.createCredential)ie=await k.createCredential(E,re);else if(k)ie=await tE({methods:k.methods,polyfill:!1,transport:Cz(x)}).createCredential(E,re);else if(C)ie=await tE({methods:[C],polyfill:!1,transport:Cz(x)}).createCredential(E,re);else throw Error(`unreachable`);let n=w?PC:vS(x),r={...cT(p.init.headers),[n]:ie},i=w?Tz((Az(x)??m.url)||o):T;w&&kz(r,i.host),S?.prepareCredentialRequest?.({challenge:x,credential:ie,headers:r});let a={...p.init,redirect:`manual`,headers:r};e.options.verbose>=2&&bk(i.url,a,t),M=await u(i.url,a)}if(e.options.fail&&M.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${M.status}`,exitCode:22});if(M.status===402){let n=await M.text();t(`${X.bold(X.red(`Payment Rejected`))}\n`);try{let e=JSON.parse(n),r=[];for(let[t,n]of Object.entries(e))n!==void 0&&r.push([t,Tk(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(xk(M,c),!(ie&&await S?.handleResponse?.({challenge:x,credential:ie,response:M,fetchUrl:f,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:te,confirm:jk,tokenSymbol:ee,tokenDecimals:D,explorerUrl:O,shownKeys:ne}))){let n=M.headers.get(q.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(A.toString(n));t(`\n${X.bold(X.green(`Payment Receipt`))}\n`);let r=[],i=e.channelId,a=e.reference,o=i&&a&&i===a,s=new Set([`acceptedCumulative`,`spent`]);for(let[t,n]of Object.entries(e)){if(n===void 0||ne.has(t)||t===`reference`&&o)continue;let e=S?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${Mk(BigInt(n),ee,D)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&O?r.push([t,Ek(`${O}/tx/${n}`,n)]):r.push([t,String(n)]):r.push([t,e])}r.sort(([e],[t])=>e.localeCompare(t));let c=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(c))} ${n}\n`);t(`
268
+ `)}catch{}await pz(M)}}catch(t){if(t instanceof I)throw t;let n=t instanceof Error?t.cause:void 0,r=n instanceof Error?n:void 0;if(r&&`code`in r){let t=r.code;return t===`ENOTFOUND`?e.error({code:`DNS_ERROR`,message:`Could not resolve host "${s}". Check the URL and try again.`,exitCode:6}):t===`ECONNREFUSED`?e.error({code:`CONNECTION_REFUSED`,message:`Connection refused by "${s}". Is the server running?`,retryable:!0,exitCode:7}):t===`ECONNRESET`?e.error({code:`CONNECTION_RESET`,message:`Connection to "${s}" was reset.`,retryable:!0,exitCode:56}):t===`ETIMEDOUT`?e.error({code:`CONNECTION_TIMEOUT`,message:`Connection to "${s}" timed out.`,retryable:!0,exitCode:28}):t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?e.error({code:`TLS_ERROR`,message:`TLS certificate error for "${s}". Use --insecure to skip verification.`,exitCode:60}):e.error({code:`REQUEST_FAILED`,message:`Request to "${s}" failed: ${r.message}`})}{let n=t instanceof Error?t.message:String(t);return e.error({code:`REQUEST_FAILED`,message:r?`Request failed: ${n} (Cause: ${r.message})`:`Request failed: ${n}`})}}}}),Pz=pb(`account`,{description:`Manage accounts (create, default, delete, export, fund, list, view)`}).command(`create`,{description:`Create new account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({address:p.string(),name:p.string()}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=dz(e),n=e.options.account;if(!n){if((await tA().list()).length===0)n=`main`;else{if(t)return e.error({code:`ACCOUNT_REQUIRED`,message:`Account name is required in structured mode.`,exitCode:2});let r=await Ak(`Account name`);if(!r)return;n=r}}let r=tA(n);for(;await r.get();){if(t)return e.error({code:`ACCOUNT_EXISTS`,message:`Account "${n}" already exists.`,exitCode:1});process.stderr.write(`${X.dim(`Account "${n}" already exists.`)}\n\n`);let i=await Ak(`Enter different name`);if(!i)return;n=i,r=tA(n)}let i=ye(),a=xe(i);await r.set(i),(await tA().list()).length===1&&$k().set(n);let o=P.blockExplorers?.default?.url,s=o?Ek(`${o}/address/${a.address}`,a.address):a.address,c=Pk(e.options),l=Nk(e.options.rpcUrl,{network:c});return Fk({network:c,rpcUrl:l}).then(e=>M({chain:e,transport:de(l)})).then(e=>import(`viem/tempo`).then(({Actions:t})=>t.faucet.fund(e,{account:a}).catch(()=>{}))),fz(e,{address:a.address,name:n},()=>{console.log(`Account "${n}" saved to keychain.`),console.log(X.dim(`Address ${s}`)),console.log(X.dim(`Fund testnet tokens: mppx account fund --account ${n} --network testnet`))})}}).command(`default`,{description:`Set default account`,options:p.object({account:p.string().describe(`Account name`)}),output:p.object({name:p.string()}),alias:{account:`a`},async run(e){let t=e.options.account;return kk(t)?RF(t)?($k().set(t),fz(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69}):await tA(t).get()?($k().set(t),fz(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69})}}).command(`delete`,{description:`Delete account`,options:p.object({account:p.string().describe(`Account name`),yes:p.boolean().optional().describe(`DANGER!! Skip confirmation prompts`)}),output:p.object({defaultAccount:p.string().optional(),name:p.string()}),alias:{account:`a`},async run(e){let t=tA(e.options.account),n=await t.get();if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${e.options.account}" not found.`,exitCode:69});let r=xe(n),i=await Bk(r.address,{includeTestnet:!1});if(!e.options.yes){if(dz(e))return e.error({code:`CONFIRMATION_REQUIRED`,message:`Pass --yes to delete an account in structured mode.`,exitCode:2});let t=P.blockExplorers?.default?.url,n=t?Ek(`${t}/address/${r.address}`,r.address):r.address;process.stderr.write(X.dim(`Delete account "${e.options.account}"\n`)),process.stderr.write(X.dim(` Address ${n}\n`));for(let e=0;e<i.length;e++)process.stderr.write(X.dim(` ${e===0?`Balance`:` `} ${i[e]}\n`));if(process.stderr.write(X.dim(`This action cannot be undone
267
269
 
268
- `)),!await kk(`Confirm delete?`)){console.log(`Canceled`);return}}await t.delete();let a=Zk().get(),o;if(a===e.options.account){let e=await $k().list();e.length>0?(o=e[0],Zk().set(o)):Zk().clear()}return tz(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=ez(e),n=Qk(e.options.account),r=await $k(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=ye(r),a=Mk(e.options),o=jk(e.options.rpcUrl,{network:a}),s=await Nk({network:a,rpcUrl:o}),c=M({chain:s,transport:P(o)});t||console.log(`Funding "${n}" on ${Pk(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?wk(`${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}))),tz(e,{account:n,chain:Pk(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(YR)}),async run(e){let t=Zk().get(),n=(await $k().list()).sort(),r=[];for(let e of n){let t=await $k(e).get();t&&r.push({name:e,address:ye(t).address})}let i=FF();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 tz(e,{accounts:[]},()=>{console.log(`No accounts found.`)});let a=be.blockExplorers?.default?.url,o=Math.max(...r.map(e=>e.name.length+ +(e.name===t)));return tz(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?wk(`${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=Qk(e.options.account);if(Dk(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 $k(t).get();return n?tz(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:XR,alias:{account:`a`,rpcUrl:`r`},async run(e){let t=Qk(e.options.account);if(Dk(t)){let n=IF(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=jk(e.options.rpcUrl,{network:e.options.network}),a=await Nk({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?wk(`${o}/address/${r}`,r):r,c=await Rk(r,a&&i?{chain:a,rpcUrl:i}:void 0);return tz(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 $k(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=ye(n),i=jk(e.options.rpcUrl,{network:e.options.network}),a=await Nk({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?wk(`${o}/address/${r.address}`,r.address):r.address,c=await Rk(r.address,a&&i?{chain:a,rpcUrl:i}:void 0);return tz(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}`)})}}),wz=fb(`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||(rz()?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=hS(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.
269
- `);return}let r=await iI(e.options.config),i=eI(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=Tk(e.options.methodOpt),l=rS(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 QF(a,r?.config.extensions,d?.credentialContext),p;if(d)p=d.createCredential?await d.createCredential(u,f):await eE({methods:d.methods,polyfill:!1}).createCredential(u,f);else if(s)p=await eE({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 tz(e,{authorization:p},()=>{console.log(p)})}}),Tz=fb(`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'
270
+ `)),!await jk(`Confirm delete?`)){console.log(`Canceled`);return}}await t.delete();let a=$k().get(),o;if(a===e.options.account){let e=await tA().list();e.length>0?(o=e[0],$k().set(o)):$k().clear()}return fz(e,{defaultAccount:o,name:e.options.account},()=>{o&&console.log(`Default account set to "${o}"`),console.log(`Account "${e.options.account}" deleted`)})}}).command(`fund`,{description:`Fund account with testnet tokens`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({account:p.string(),chain:p.string(),transactions:p.array(p.string())}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=dz(e),n=eA(e.options.account),r=await tA(n).get();if(!r)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${n}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let i=xe(r),a=Pk(e.options),o=Nk(e.options.rpcUrl,{network:a}),s=await Fk({network:a,rpcUrl:o}),c=M({chain:s,transport:de(o)});t||console.log(`Funding "${n}" on ${Ik(s)}`);try{let{Actions:r}=await import(`viem/tempo`),a=await r.faucet.fund(c,{account:i}),o=s.blockExplorers?.default?.url;if(!t)for(let e of a){let t=o?Ek(`${o}/tx/${e}`,X.gray(e)):e;console.log(` ${t}`)}let{waitForTransactionReceipt:l}=await import(`viem/actions`);return await Promise.all(a.map(e=>l(c,{hash:e}))),fz(e,{account:n,chain:Ik(s),transactions:[...a]},()=>{console.log(`Funded successfully`)})}catch(n){let r=n instanceof Error?n.message:String(n);return t?e.error({code:`FUNDING_FAILED`,message:r,exitCode:1}):e.error({code:`FUNDING_FAILED`,message:`Funding failed: ${r}`,exitCode:1})}}}).command(`list`,{description:`List all accounts`,output:p.object({accounts:p.array(oz)}),async run(e){let t=$k().get(),n=(await tA().list()).sort(),r=[];for(let e of n){let t=await tA(e).get();t&&r.push({name:e,address:xe(t).address})}let i=LF();for(let e=0;e<i.length;e++){let t=i[e],n=e===0?`tempo:default`:`tempo:${e}`;t.wallet_address&&r.push({name:n,address:t.wallet_address,source:`tempo wallet`})}if(r.length===0)return fz(e,{accounts:[]},()=>{console.log(`No accounts found.`)});let a=P.blockExplorers?.default?.url,o=Math.max(...r.map(e=>e.name.length+ +(e.name===t)));return fz(e,{accounts:r.map(e=>({...e,...e.name===t?{isDefault:!0}:void 0}))},()=>{for(let e of r){let n=e.name===t,r=n?`${e.name}${X.dim(`*`)}`:e.name,i=e.name.length+ +!!n,s=a?Ek(`${a}/address/${e.address}`,e.address):e.address,c=e.source?` ${X.dim(`(${e.source})`)}`:``;console.log(`${r}${` `.repeat(o-i+2)}${X.dim(s)}${c}`)}})}}).command(`export`,{description:`Export the private key for a local account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`)}),output:p.object({privateKey:p.string()}),alias:{account:`a`},async run(e){let t=eA(e.options.account);if(kk(t))return e.error({code:`UNSUPPORTED_ACCOUNT`,message:`Account "${t}" is managed by Tempo wallet and does not expose a private key via mppx.`,exitCode:2});let n=await tA(t).get();return n?fz(e,{privateKey:n},()=>{console.log(n)}):e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}}).command(`view`,{description:`View account address`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:sz,alias:{account:`a`,rpcUrl:`r`},async run(e){let t=eA(e.options.account);if(kk(t)){let n=RF(t);if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69});let r=n.wallet_address,i=Nk(e.options.rpcUrl,{network:e.options.network}),a=await Fk({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?Ek(`${o}/address/${r}`,r):r,c=await Bk(r,a&&i?{chain:a,rpcUrl:i}:void 0);return fz(e,{address:r,balances:c,name:t,type:`${n.wallet_type} (tempo wallet)`},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`),console.log(`${X.dim(`Type`)} ${n.wallet_type} ${X.dim(`(tempo wallet)`)}`)})}let n=await tA(t).get();if(!n)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let r=xe(n),i=Nk(e.options.rpcUrl,{network:e.options.network}),a=await Fk({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?Ek(`${o}/address/${r.address}`,r.address):r.address,c=await Bk(r.address,a&&i?{chain:a,rpcUrl:i}:void 0);return fz(e,{address:r.address,balances:c,name:t},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`)})}}),Fz=pb(`sign`,{description:`Sign a payment challenge and output the Authorization header`,usage:[{suffix:`--challenge <value> [options]`},{prefix:`echo <challenge> |`,suffix:`[options]`}],options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),challenge:p.string().optional().describe(`WWW-Authenticate challenge value`),config:p.string().optional().describe(`Path to config file`),dryRun:p.boolean().optional().describe(`Validate and parse the challenge without signing`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`)}),output:p.object({authorization:p.string()}),alias:{account:`a`,challenge:`C`,config:`c`,methodOpt:`M`,rpcUrl:`r`},async run(e){let t=e.options.challenge||(mz()?await new Promise((e,t)=>{let n=``;process.stdin.setEncoding(`utf-8`),process.stdin.on(`data`,e=>{n+=e}),process.stdin.on(`end`,()=>e(n.trim())),process.stdin.on(`error`,t)}):void 0);if(!t)return e.error({code:`NO_CHALLENGE`,message:`No challenge provided. Use --challenge or pipe via stdin.`,exitCode:2});let n;try{n=gS(t)}catch(t){return e.error({code:`INVALID_CHALLENGE`,message:`Failed to parse challenge: ${t instanceof Error?t.message:t}`,exitCode:2})}if(e.options.dryRun){process.stderr.write(`Challenge is valid.
271
+ `);return}let r=await oI(e.options.config),i=nI(n,r?.config);if(!i){let t=n.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:a,plugin:o,method:s}=i,c=Dk(e.options.methodOpt),l=iS(a),u=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:l}}),d;o&&(d=await o.setup({challenge:a,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:c}));let f=await eI(a,r?.config.extensions,d?.credentialContext),p;if(d)p=d.createCredential?await d.createCredential(u,f):await tE({methods:d.methods,polyfill:!1}).createCredential(u,f);else if(s)p=await tE({methods:[s],polyfill:!1}).createCredential(u,f);else return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method: ${a.method}/${a.intent}. Add it to mppx.config.ts using defineConfig().`,exitCode:2});return fz(e,{authorization:p},()=>{console.log(p)})}}),Iz=pb(`init`,{description:`Create an mppx.config.ts file in the current directory`,options:p.object({force:p.boolean().optional().describe(`Overwrite existing config file`)}),output:p.object({file:p.string()}),alias:{force:`f`},async run(e){let n=process.cwd(),r=`mppx.config${(()=>{if(t.existsSync(c.join(n,`tsconfig.json`)))return`.ts`;try{if(JSON.parse(t.readFileSync(c.join(n,`package.json`),`utf-8`)).type===`module`)return`.mjs`}catch{}return`.js`})()}`,i=c.join(n,r);return t.existsSync(i)&&!e.options.force?e.error({code:`CONFIG_EXISTS`,message:`${r} already exists. Use --force to overwrite.`,exitCode:1}):(t.writeFileSync(i,`import { defineConfig } from 'mppx/cli'
270
272
 
271
273
  export default defineConfig({
272
274
  methods: [],
273
275
  plugins: [],
274
276
  })
275
- `),tz(e,{file:i},()=>{console.log(`Created ${r}`)}))}}),Ez=fb(`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(QR)}),alias:{query:`q`},async run(e){let t=e.options.query?.toLowerCase(),n=await bz(),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(oz).sort((e,t)=>e.id.localeCompare(t.id));return tz(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=xz(await bz(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=oz(t),r=az(t);return tz(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`)} ${wk(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&&iz(e.homepage);i&&console.log(`${X.dim(`Docs`)} ${wk(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($R),service:QR}),async run(e){let t=xz(await bz(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=oz(t),r=az(t).map(sz);return tz(e,{endpoints:r,service:n},()=>{if(r.length===0){console.log(`No endpoints found for ${n.id}.`);return}let e=Math.max(...r.map(e=>e.method.length)),t=Math.max(...r.map(e=>e.path.length));for(let n of r){let r=cz(n.payment),i=n.description?` ${X.dim(n.description)}`:``;console.log(`${n.method.padEnd(e)} ${n.path.padEnd(t)} ${r}${i}`)}})}}),Dz=fb(`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(()=>(qR(),VR)),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`),tz(e,a,()=>{})}return tz(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(ZR),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=NE(i);if(!ez(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}):tz(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.`)})}});Sz.command(Cz),Sz.command(Dz),Sz.command(Tz),Sz.command(Ez),Sz.command(hL),Sz.command(wz),Sz.command(PR);export{Sz as default,gz as resolveMppCredentialTarget};
277
+ `),fz(e,{file:i},()=>{console.log(`Created ${r}`)}))}}),Lz=pb(`services`,{description:`Browse the MPP services registry`}).command(`list`,{description:`List registered MPP services`,options:p.object({query:p.string().optional().describe(`Filter by id, name, category, tag, or description`)}),output:p.object({services:p.array(lz)}),alias:{query:`q`},async run(e){let t=e.options.query?.toLowerCase(),n=await jz(),r=(t?n.filter(e=>[e.id,e.name,e.description,...Array.isArray(e.categories)?e.categories:[],...Array.isArray(e.tags)?e.tags:[]].filter(e=>typeof e==`string`).some(e=>e.toLowerCase().includes(t))):n).map(_z).sort((e,t)=>e.id.localeCompare(t.id));return fz(e,{services:r},()=>{if(r.length===0){console.log(`No services found.`);return}let e=Math.max(...r.map(e=>e.id.length)),t=Math.max(...r.map(e=>String(e.paidEndpoints).length));for(let n of r){let r=n.name&&n.name!==n.id?` ${n.name}`:``,i=n.url?` ${X.dim(n.url)}`:``;console.log(`${n.id.padEnd(e)} ${String(n.paidEndpoints).padStart(t)} paid${r}${i}`)}})}}).command(`show`,{description:`Show one registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({service:p.record(p.string(),p.unknown())}),async run(e){let t=Mz(await jz(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=_z(t),r=gz(t);return fz(e,{service:t},()=>{console.log(`${n.name??n.id} ${X.dim(`(${n.id})`)}`),n.description&&console.log(n.description),n.url&&console.log(`${X.dim(`URL`)} ${Ek(n.url,n.url)}`),n.status&&console.log(`${X.dim(`Status`)} ${n.status}`),console.log(`${X.dim(`Endpoints`)} ${r.length} (${n.paidEndpoints} paid)`);let e=t.docs,i=e&&hz(e.homepage);i&&console.log(`${X.dim(`Docs`)} ${Ek(i,i)}`)})}}).command(`endpoints`,{description:`List endpoints for a registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({endpoints:p.array(uz),service:lz}),async run(e){let t=Mz(await jz(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=_z(t),r=gz(t).map(vz);return fz(e,{endpoints:r,service:n},()=>{if(r.length===0){console.log(`No endpoints found for ${n.id}.`);return}let e=Math.max(...r.map(e=>e.method.length)),t=Math.max(...r.map(e=>e.path.length));for(let n of r){let r=yz(n.payment),i=n.description?` ${X.dim(n.description)}`:``;console.log(`${n.method.padEnd(e)} ${n.path.padEnd(t)} ${r}${i}`)}})}}),Rz=pb(`discover`,{description:`Discovery tooling`}).command(`generate`,{description:`Generate a static OpenAPI discovery document from a module`,args:p.object({module:p.string().describe(`Path to a module that default-exports a discovery config`)}),options:p.object({output:p.string().optional().describe(`Write output to a file instead of stdout`)}),output:p.record(p.string(),p.unknown()),alias:{output:`o`},async run(e){let n=c.resolve(e.args.module);if(!t.existsSync(n))return e.error({code:`MODULE_NOT_FOUND`,message:`Module not found: ${n}`,exitCode:1});let r;try{r=await import(n)}catch(t){return e.error({code:`MODULE_IMPORT_FAILED`,message:`Failed to import module: ${t.message}`,exitCode:1})}let i=r.default??r,a;if(typeof i.openapi==`string`)a=i;else{let{generate:t}=await Promise.resolve().then(()=>(iz(),QR)),n=i.mppx;if(!n)return e.error({code:`INVALID_MODULE`,message:"Module must default-export an OpenAPI document (with `openapi` key) or an object with `mppx` (server instance) and `routes`.",exitCode:1});a=t(n,i)}let o=JSON.stringify(a,null,2);if(e.options.output){let n=c.resolve(e.options.output);return t.writeFileSync(n,`${o}\n`),process.stderr.write(`Wrote ${n}\n`),fz(e,a,()=>{})}return fz(e,a,()=>{console.log(o)})}}).command(`validate`,{description:`Validate an OpenAPI discovery document from a file or URL`,args:p.object({input:p.string().describe(`Path or URL to a discovery document`)}),output:p.object({errorCount:p.number(),issues:p.array(cz),valid:p.boolean(),warningCount:p.number()}),async run(e){let n=e.args.input,r;if(/^https?:\/\//.test(n)){let t=new AbortController,i=setTimeout(()=>t.abort(),3e4),a;try{a=await globalThis.fetch(n,{signal:t.signal})}catch(t){clearTimeout(i);let n=t instanceof DOMException&&t.name===`AbortError`?`Request timed out after 30s`:t.message;return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: ${n}`,exitCode:1})}if(clearTimeout(i),!a.ok)return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: HTTP ${a.status}`,exitCode:1});let o=10485760,s=a.headers.get(`content-length`);if(s&&Number(s)>o||(r=await a.text(),r.length>o))return e.error({code:`DISCOVERY_TOO_LARGE`,message:`Discovery document exceeds 10 MB limit`,exitCode:1})}else{let i=c.resolve(n);if(!t.existsSync(i))return e.error({code:`DISCOVERY_NOT_FOUND`,message:`Discovery document not found: ${i}`,exitCode:1});r=t.readFileSync(i,`utf-8`)}let i;try{i=JSON.parse(r)}catch(t){return e.error({code:`DISCOVERY_INVALID_JSON`,message:`Invalid discovery JSON: ${t.message}`,exitCode:1})}let a=PE(i);if(!dz(e))for(let e of a)console.log(`[${e.severity}] ${e.path}: ${e.message}`);let o=a.filter(e=>e.severity===`error`).length,s=a.filter(e=>e.severity===`warning`).length;return o>0?e.error({code:`DISCOVERY_INVALID`,message:`Discovery document has ${o} error(s) and ${s} warning(s).`,exitCode:1}):fz(e,{errorCount:o,issues:a,valid:!0,warningCount:s},()=>{console.log(s>0?`Discovery document is valid with ${s} warning(s).`:`Discovery document is valid.`)})}}),zz=p.object({address:p.string(),id:p.string(),livemode:p.boolean(),network:p.string(),supportedTokens:p.array(p.object({contractAddress:p.string(),currency:p.string()}))}),Bz=pb(`stripe`,{description:`Stripe machine payments tooling`}).command(`address`,{description:`Create a Stripe crypto deposit address and print its public address`,usage:[{suffix:`[--network tempo|base|solana] [--env [path]] [--secret-key <key>] [options]`}],options:p.object({customer:p.string().optional().describe(`Scope the address to a Stripe customer (cus_...); it then only accepts their funds`),env:p.string().optional().describe(`Write <NETWORK>_DEPOSIT_ADDRESS to this env file instead of printing (default path: .env)`),live:p.boolean().optional().describe(`Use the Stripe CLI's live mode key instead of its test mode key`),network:p.enum([`tempo`,`base`,`solana`]).default(`tempo`).describe(`Network to create the address on`),projectName:p.string().optional().describe(`Stripe CLI project to read the key from (env: STRIPE_PROJECT_NAME, default: default)`),secretKey:p.string().optional().describe(`Stripe secret key (sk_...); else STRIPE_SECRET_KEY, else the Stripe CLI's login`),stripeAccount:p.string().optional().describe(`Connected account to create the address for (acct_...)`)}),output:zz,alias:{network:`n`},async run(e){let{customer:t,env:n,live:r,network:i,projectName:a,secretKey:o,stripeAccount:s}=e.options;if(n&&t)return e.error({code:`INVALID_OPTIONS`,message:`--env can't be combined with --customer: that address only accepts the customer's funds.`,exitCode:2});let c=DL({live:r,projectName:a,secretKey:o});if(!c)return e.error({code:`MISSING_STRIPE_SECRET_KEY`,message:`No Stripe key found. Pass --secret-key <sk_...>, set STRIPE_SECRET_KEY, or run \`stripe login\` so mppx can read the Stripe CLI's ${r?`live`:`test`} mode key.`,exitCode:2});let l=new URLSearchParams({network:i});t&&l.set(`customer`,t);let u=await globalThis.fetch(new URL(`/v1/crypto/deposit_addresses`,process.env.MPPX_STRIPE_API_URL??`https://api.stripe.com`),{method:`POST`,headers:{Authorization:`Bearer ${c.key}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":FE,...s?{"Stripe-Account":s}:{}},body:l}),d=await u.json().catch(()=>({}));if(!u.ok||!d.address){let t=d.error?.code&&/^[a-z_]+$/.test(d.error.code)?`, ${d.error.code}`:``,n=`HTTP ${u.status}${t}`,r=u.status===401||u.status===403,i=c.source===`stripe-cli`?`the Stripe CLI's login`:c.source===`flag`?`--secret-key`:`STRIPE_SECRET_KEY`,a=r&&c.key.startsWith(`rk_`)?`Stripe refused the restricted key (rk_...) from ${i} for crypto deposit addresses (${n}). Pass a secret key with --secret-key <sk_...> or STRIPE_SECRET_KEY.`:r&&c.source===`stripe-cli`?`Stripe refused the key from the Stripe CLI's login (${n}). Run \`stripe login\` again, or pass --secret-key <sk_...>.`:`Stripe could not create a deposit address (${n}).`;return e.error({code:`STRIPE_REQUEST_FAILED`,message:a,exitCode:1})}let f={address:d.address,id:d.id??``,livemode:d.livemode??!1,network:d.network??i,supportedTokens:(d.supported_tokens??[]).map(e=>({contractAddress:e.token_contract_address,currency:e.token_currency}))};if(n){let t=`${i.toUpperCase()}_DEPOSIT_ADDRESS`;return NL(n,t,f.address),console.error(`Wrote ${t} to ${n}`),fz(e,f,()=>{})}return fz(e,f,()=>console.log(f.address))}});Nz.command(Pz),Nz.command(Rz),Nz.command(Iz),Nz.command(Lz),Nz.command(_L),Nz.command(Fz),Nz.command(Bz),Nz.command(GR);const Vz=Nz.serve.bind(Nz);Nz.serve=(e=process.argv.slice(2),t)=>Vz(PL(e),t);export{Nz as default,Dz as resolveMppCredentialTarget};