everyapp 0.2.2 → 0.3.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -77
  3. package/bin/everyapp.js +235 -0
  4. package/dist/access-LGEN3ABJ.js +1 -0
  5. package/dist/activity-RSD4D66F.js +12 -0
  6. package/dist/apps-4RCFXT74.js +13 -0
  7. package/dist/chunk-23HJ5I2A.js +2 -0
  8. package/dist/chunk-2Y5Q6A5K.js +6 -0
  9. package/dist/chunk-4JRIS6S6.js +1 -0
  10. package/dist/chunk-5PTNYZK6.js +4 -0
  11. package/dist/chunk-6OGVO7QK.js +6 -0
  12. package/dist/chunk-6PGUCTJ6.js +11 -0
  13. package/dist/chunk-AGTCKFRB.js +22 -0
  14. package/dist/chunk-BHMRY53V.js +2 -0
  15. package/dist/chunk-CB4U7H2G.js +4 -0
  16. package/dist/chunk-CCWBPAKH.js +4 -0
  17. package/dist/chunk-CZTEDWZ2.js +22 -0
  18. package/dist/chunk-CZXHKPRZ.js +2 -0
  19. package/dist/chunk-E3EPK27P.js +10 -0
  20. package/dist/chunk-EGEWRFVY.js +1 -0
  21. package/dist/chunk-ELK7QZ2M.js +1 -0
  22. package/dist/chunk-FJJSSVET.js +33 -0
  23. package/dist/chunk-GKBPYVP3.js +25 -0
  24. package/dist/chunk-H6QQMY7B.js +18 -0
  25. package/dist/chunk-H7PDL3X5.js +1 -0
  26. package/dist/chunk-HOUHG236.js +20 -0
  27. package/dist/chunk-IFCPALVC.js +46 -0
  28. package/dist/chunk-IUOBIB5M.js +30 -0
  29. package/dist/chunk-J35DDCNU.js +1 -0
  30. package/dist/chunk-J455FAEN.js +7 -0
  31. package/dist/chunk-JYKRUS5C.js +1 -0
  32. package/dist/chunk-LXYMDZER.js +1 -0
  33. package/dist/chunk-LYNBZ7RV.js +57 -0
  34. package/dist/chunk-M2QQ2UD7.js +132 -0
  35. package/dist/chunk-N4E5YE4X.js +5 -0
  36. package/dist/chunk-N5GQLGEC.js +2 -0
  37. package/dist/chunk-NFU4YFXB.js +1 -0
  38. package/dist/chunk-OM2HDWVP.js +1 -0
  39. package/dist/chunk-ONLNJXVQ.js +32 -0
  40. package/dist/chunk-OP4DYXYI.js +2 -0
  41. package/dist/chunk-PNLU5U3P.js +1 -0
  42. package/dist/chunk-PS7S74DG.js +6 -0
  43. package/dist/chunk-RMF4YGD6.js +98 -0
  44. package/dist/chunk-T2GD7RHS.js +10 -0
  45. package/dist/chunk-TLRM3P7V.js +15 -0
  46. package/dist/chunk-W3JCQHHU.js +1 -0
  47. package/dist/chunk-WOVS3GV5.js +10 -0
  48. package/dist/chunk-YHJZMJYZ.js +1 -0
  49. package/dist/chunk-ZECBN24L.js +15 -0
  50. package/dist/chunk-ZEXVHB22.js +2 -0
  51. package/dist/chunk-ZFCUH5PK.js +7 -0
  52. package/dist/configure-F7UZCJUG.js +8 -0
  53. package/dist/create-2E5HVWYK.js +22 -0
  54. package/dist/db-HEQVTDTM.js +9 -0
  55. package/dist/delete-XCSIQIRS.js +3 -0
  56. package/dist/deploy-3QOZEZHC.js +1 -0
  57. package/dist/dev-JL3ZP5BT.js +86 -0
  58. package/dist/email-RLZFUFUN.js +10 -0
  59. package/dist/events-2V5VRBWP.js +15 -0
  60. package/dist/groups-HDG5DVFY.js +8 -0
  61. package/dist/index.js +97 -1
  62. package/dist/install-Z5FYXUYM.js +1 -0
  63. package/dist/login-KHJBC64Z.js +1 -0
  64. package/dist/mcp-EFDUKJ5V.js +1 -0
  65. package/dist/provider-EOI5PTFH.js +13 -0
  66. package/dist/release-74J5ZIL3.js +1 -0
  67. package/dist/restore-FFGYV7NO.js +3 -0
  68. package/dist/secret-7FKKTLHB.js +1 -0
  69. package/dist/setup-PAKRCAFO.js +1 -0
  70. package/dist/signin-AP3D4XM4.js +12 -0
  71. package/dist/status-RMWNHOEK.js +4 -0
  72. package/dist/teardown-E4JNKAZJ.js +22 -0
  73. package/dist/update-DWVZFNPS.js +1 -0
  74. package/dist/workspace-CJC5I66L.js +21 -0
  75. package/package.json +19 -16
  76. package/skills/build-every-app/SKILL.md +199 -0
  77. package/skills/build-every-app/patterns.md +140 -0
  78. package/skills/everyapp/SKILL.md +292 -0
  79. package/skills/everyapp/mcp.md +350 -0
  80. package/skills/everyapp/security-review.md +61 -0
  81. package/skills/everyapp/setup/README.md +274 -0
  82. package/skills/everyapp/setup/access.md +178 -0
  83. package/skills/everyapp/setup/context.md +117 -0
  84. package/skills/everyapp/setup/dataforseo.md +287 -0
  85. package/skills/everyapp/setup/email.md +366 -0
  86. package/skills/everyapp/setup/gateway.md +243 -0
  87. package/skills/everyapp/setup/google.md +360 -0
  88. package/skills/everyapp/setup/microsoft-365.md +281 -0
  89. package/skills/everyapp/setup/openai.md +318 -0
  90. package/skills/everyapp/setup/openrouter.md +309 -0
  91. package/skills/everyapp/setup/providers.md +1253 -0
  92. package/skills/everyapp/setup/remote-mcp.md +199 -0
  93. package/skills/everyapp/setup/signin-apple.md +178 -0
  94. package/skills/everyapp/setup/signin-cloudflare.md +148 -0
  95. package/skills/everyapp/setup/signin-github.md +139 -0
  96. package/skills/everyapp/setup/signin-google.md +178 -0
  97. package/skills/everyapp/setup/signin-microsoft.md +183 -0
  98. package/skills/everyapp/setup/signin-oidc.md +163 -0
  99. package/skills/everyapp/setup/slack.md +344 -0
  100. package/skills/everyapp/setup/workers-ai.md +138 -0
  101. package/bin/__everyapp_bash_complete.js +0 -12
  102. package/dist/bash-complete.js +0 -3
  103. package/dist/chunk-7BOQJFI5.js +0 -8
  104. package/dist/chunk-7YVJFS4A.js +0 -1
  105. package/dist/chunk-BIXKPCDH.js +0 -2
  106. package/dist/chunk-DLGPLHBH.js +0 -47
  107. package/dist/chunk-FD6K2YA7.js +0 -9
  108. package/dist/chunk-GAJEQYJH.js +0 -39
  109. package/dist/chunk-O2KDOP5R.js +0 -13
  110. package/dist/chunk-OI2MBGBG.js +0 -4
  111. package/dist/chunk-POSDLD3G.js +0 -8
  112. package/dist/chunk-RB5D2R45.js +0 -1
  113. package/dist/chunk-U4LIQ5VR.js +0 -1
  114. package/dist/chunk-VEYSNPDH.js +0 -3
  115. package/dist/chunk-VP6SKW44.js +0 -7
  116. package/dist/chunk-WO3NE7ZU.js +0 -7
  117. package/dist/chunk-XTO2VTPY.js +0 -6
  118. package/dist/chunk-YJ2DKIZS.js +0 -1
  119. package/dist/create-DYQ3NBWJ.js +0 -22
  120. package/dist/deploy-PYTCMDGV.js +0 -7
  121. package/dist/deploy-RMAHOA4Z.js +0 -55
  122. package/dist/dev-SAE237FS.js +0 -0
  123. package/dist/generateConfig-46Z3ERF3.js +0 -1
  124. package/dist/login-B6EF3SMX.js +0 -1
  125. package/dist/logout-XMKZBLNV.js +0 -1
  126. package/dist/remoteD1Shell-A67JMO3H.js +0 -6
  127. package/dist/setupLocal-TZJUW5ES.js +0 -6
  128. package/gateway/every-app-gateway-build.tar.gz +0 -0
@@ -0,0 +1,86 @@
1
+ import{b as Zu}from"./chunk-BHMRY53V.js";import{a as Ku,b as Wu}from"./chunk-J35DDCNU.js";import{a as Yu,b as Xu}from"./chunk-LXYMDZER.js";import{a as Fu,c as Gu,e as Ju}from"./chunk-CZXHKPRZ.js";import{a as Wt,b as Yt}from"./chunk-ONLNJXVQ.js";import{c as xi,d as Hi}from"./chunk-NFU4YFXB.js";import{a as Bu}from"./chunk-H7PDL3X5.js";import"./chunk-JYKRUS5C.js";import{A as gu,Aa as Eu,B as yu,Ba as Tu,Bb as De,C as Su,F as Xo,Fb as Tr,G as Oi,Ja as $u,Kb as qu,L as vu,M as _u,Ma as zu,N as bu,Na as Mi,Nb as Li,Oa as Ni,Ob as Di,Pb as ju,Qa as Pu,Qb as Lu,Ra as kn,Tb as Zo,Ua as Cu,Ub as Du,ac as xu,c as Pn,d as Ko,db as ku,eb as Iu,fb as Au,gb as qi,hb as ji,ia as Ru,ib as In,ja as wu,lb as Ou,m as Kt,n as Tt,o as wr,oc as Hu,p as lu,pb as Mu,q as uu,r as Er,s as Wo,t as du,u as pu,uc as Uu,v as mu,vb as Nu,vc as Vu,w as hu,x as Cn,y as Yo,z as fu}from"./chunk-LYNBZ7RV.js";import Lb from"node:http";import jf from"node:http";import vd from"node:net";import{Readable as ts}from"node:stream";import{pipeline as Lf}from"node:stream/promises";function Xt(e){if(!e)return null;let t=e.trim().toLowerCase();if(t.length===0)return null;let r=t.indexOf(".");return r<=0?{appLabel:"",baseHost:t,host:t}:{appLabel:t.slice(0,r),baseHost:t.slice(r+1),host:t}}var Ui="Your browser sent more than one Every App session cookie, which another site on this domain can cause. Clear this site's cookies and sign in again.";function rf(e,t){let r=e.get("cookie");if(!r)return 0;let n=0;for(let o of r.split(/[;,]/)){let a=o.indexOf("=");a!==-1&&t.includes(o.slice(0,a).trim())&&n++}return n}function Vi(e,t){return t.length>0&&rf(e,t)>1}function Qu(e){let t=e?.scopes??[];return t.length>0&&t.every(r=>r.startsWith("mcp:"))}var nf=new Set(["GET","HEAD","OPTIONS"]);function Bi(e,t,r,n){if(nf.has(e.toUpperCase()))return{allowed:!0,reason:"safe method"};if(n!==null)return n==="same-origin"?{allowed:!0,reason:"sec-fetch-site same-origin"}:{allowed:!1,reason:`sec-fetch-site ${n}`};if(r===null)return{allowed:!1,reason:"no origin and no sec-fetch-site"};let o;try{o=new URL(r).host}catch{return{allowed:!1,reason:"malformed origin"}}return o===t?{allowed:!0,reason:"origin matches app host"}:{allowed:!1,reason:`origin ${o} != ${t}`}}function Fi(e){return e.get("upgrade")?.trim().toLowerCase()==="websocket"}function Gi(e,t){if(t===null)return{allowed:!1,reason:"websocket upgrade without origin"};let r;try{r=new URL(t).host}catch{return{allowed:!1,reason:"malformed origin"}}return r===e?{allowed:!0,reason:"websocket origin matches app host"}:{allowed:!1,reason:`websocket origin ${r} != ${e}`}}var of="/_serverFn";function sf(e){try{return decodeURIComponent(e)}catch{return e.replace(/%[0-9a-f]{2}/gi,t=>{try{return decodeURIComponent(t)}catch{return t}})}}function Ji(e,t=of){let r=sf(e),n;try{n=new URL(r.replace(/^[/\\]+/,"/"),"https://x.invalid").pathname}catch{n=r}let o=n.toLowerCase(),a=t.toLowerCase().replace(/\/+$/,"");return o===a||o.startsWith(`${a}/`)}function af(e){let t=e.get("sec-fetch-mode"),r=e.get("sec-fetch-dest");return t==="navigate"||t==="nested-navigate"||r==="document"||r==="iframe"||r==="frame"?!0:!(t!==null||e.get("sec-fetch-site")!==null)&&(e.get("accept")??"").toLowerCase().includes("text/html")}function cf(e){return e.get("x-tsr-serverfn")?.trim().toLowerCase()==="true"||e.get("x-tsr-redirect")?.trim().toLowerCase()==="manual"}function Ki(e){if(af(e))return{allowed:!1,reason:"server function navigation"};let t=e.get("sec-fetch-site");return t!==null&&t!=="same-origin"?{allowed:!1,reason:`sec-fetch-site ${t}`}:cf(e)?{allowed:!0,reason:"same-origin server function call"}:{allowed:!1,reason:"missing server function client header"}}var td="[redacted]",lf=new Set(["cookie","authorization","set-cookie"]),uf=/token|secret|password|code/i,ed=4;function df(e){return lf.has(e.toLowerCase())||uf.test(e)}function Qo(e,t=0){return Array.isArray(e)?t>=ed?"[truncated]":e.map(r=>Qo(r,t+1)):!e||typeof e!="object"?e:t>=ed?"[truncated]":Object.fromEntries(Object.entries(e).map(([r,n])=>[r,df(r)?td:Qo(n,t+1)]))}function $r(e,t={},r="log"){console[r](JSON.stringify({evt:e,...Qo(t)}))}var rd="x-everyapp-",pf="cf-access-",nd="cloudflare-workers-version-overrides";function od(e){let t=new Headers(e);t.delete("cookie"),t.delete("authorization"),t.delete(nd);for(let r of[...t.keys()]){let n=r.toLowerCase();(n.startsWith(rd)||n.startsWith(pf))&&t.delete(r)}return t}function Wi(e){let t=es(e);return t?.startsWith("epat_")?t:null}var mf=/^[A-Za-z0-9_-]{16}$/,hf=/^[A-Za-z0-9_-]{32}$/;function ff(e){let t=e.split(":");return t.length<3?!1:t.slice(0,-2).join(":").length>0&&mf.test(t[t.length-2])&&hf.test(t[t.length-1])}function es(e){let t=e.get("authorization");if(!t)return null;let[r,...n]=t.trim().split(/\s+/);if(r?.toLowerCase()!=="bearer")return null;let o=n.join(" ").trim();return o||null}function sd(e){let t=es(e);return t!==null&&(t.startsWith("epat_")||ff(t))}function Yi(e){return es(e)!==null}function An(e,t,r=!1){let n=od(e);if(t&&!r){let o=e.get("authorization");o&&n.set("authorization",o)}return n}var gf=["frame-ancestors 'none'","base-uri 'self'","object-src 'none'"].join("; "),yf={"frame-ancestors":{floor:"'none'",allowed:["'none'","'self'"]},"base-uri":{floor:"'self'",allowed:["'none'","'self'"]},"object-src":{floor:"'none'",allowed:["'none'"]}};function ad(e){let t=new Map;for(let r of e.split(";")){let n=r.trim();if(!n)continue;let o=n.indexOf(" "),a=(o===-1?n:n.slice(0,o)).toLowerCase(),i=o===-1?"":n.slice(o+1).trim();t.set(a,i)}for(let[r,{floor:n,allowed:o}]of Object.entries(yf)){let a=t.get(r)?.toLowerCase();t.set(r,a&&o.includes(a)?a:n)}return[...t.entries()].map(([r,n])=>n?`${r} ${n}`:r).join("; ")}function Xi(e){let t=e.getSetCookie();if(t.length!==0){e.delete("set-cookie");for(let r of t)e.append("set-cookie",Sf(r))}}function Sf(e){let[t,...r]=e.split(";"),n=r.filter(o=>{let a=o.indexOf("=");return(a===-1?o:o.slice(0,a)).trim().toLowerCase()!=="domain"});return[t,...n].join(";")}var vf="max-age=63072000; includeSubDomains; preload";function $t(e,t={}){let n=(e.headers.get("content-type")??"").includes("text/html"),o=new Headers(e.headers);if(t.stripCookieDomains!==!1&&Xi(o),o.set("Strict-Transport-Security",t.hsts??vf),o.set("X-Content-Type-Options","nosniff"),o.set("X-Frame-Options","DENY"),o.set("X-Robots-Tag","noindex, nofollow"),o.set("Referrer-Policy",t.referrerPolicy??"strict-origin-when-cross-origin"),t.noStore&&o.set("Cache-Control","no-store"),n){let a=o.get("content-security-policy"),i=a?ad(a):gf;o.set("Content-Security-Policy",i),/(^|;\s*)frame-ancestors 'self'(;|$)/.test(i)&&o.set("X-Frame-Options","SAMEORIGIN")}return new Response(e.body,{status:e.status,statusText:e.statusText,headers:o})}var rt=class extends Error{constructor(r,n="no_binding"){super(r);this.reason=n;this.name="AppUnreachableError"}},id="DISPATCHER",ld="everyapp",_f=Object.freeze({cpuMs:5e3,subrequests:200});function bf(e){return`APP__${e}`}function Rf(e){return typeof e=="object"&&e!==null&&typeof e.get=="function"}var wf=/^[a-z0-9]{1,12}$/;function Ef(e){let t="every-",r=`-${e.appId}`;if(!e.workerName.startsWith(t)||!e.workerName.endsWith(r)||e.workerName.length<=t.length+r.length)return!1;let n=e.workerName.slice(t.length,e.workerName.length-r.length);return wf.test(n)&&Nu({appId:e.appId,orgKey:n,workerName:e.workerName})}function cd(e,t){return e instanceof Error&&e.message.startsWith("Worker not found")?new rt(`The dispatch namespace has no Worker "${t}".`,"worker_not_found"):e}function Tf(e,t){let r=e[id];if(!Rf(r))throw new rt(`No dispatch namespace binding "${id}" for worker "${t.workerName}". Only a hosted gateway with a Workers for Platforms namespace reaches dispatch apps.`,"no_dispatcher");if(!Ef(t))throw new rt(`Worker "${t.workerName}" is not app "${t.appId}"'s registry Worker; refusing to dispatch to it.`,"invalid_worker_name");let n=t.limits??_f,o={appId:t.appId,organizationId:t.organizationId,workerName:t.workerName,egress:[...t.egress??[]]},a;try{a=r.get(t.workerName,{},{limits:{cpuMs:n.cpuMs,subRequests:n.subrequests},outbound:{[ld]:o}})}catch(i){throw cd(i,t.workerName)}return{async fetch(i){try{return await a.fetch(i)}catch(l){throw cd(l,t.workerName)}}}}function On(e,t){if(t.tier==="service_binding"){let r=bf(t.workerName),n=e[r];if(!n||typeof n.fetch!="function")throw new rt(`No service binding "${r}" for worker "${t.workerName}". The gateway must be redeployed with bindings reconstructed from the registry.`);return n}if(t.tier==="dispatch")return Tf(e,t);throw new rt(`Tier "${String(t.tier)}" is not a way to reach an app.`)}var $f=24*60*60,zf=10*60,Pf="__host-everyapp_";var c0=new TextEncoder;function ud(e){return e.trimStart().toLowerCase().startsWith(Pf)}function Zi(e){let t=new Headers(e.headers);t.delete("access-control-allow-credentials");let r=t.getSetCookie();if(r.some(ud)){t.delete("set-cookie");for(let n of r)ud(n)||t.append("set-cookie",n)}if(e.status===101){Xi(t);let{webSocket:n}=e;return new Response(null,{status:101,statusText:e.statusText,webSocket:n,headers:t})}return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}var Cf=/^\/assets\/[^/]+-([A-Za-z0-9_-]{8})\.(?:m?js|css|json|wasm|woff2?|ttf|otf|eot|png|jpe?g|gif|webp|avif|svg|ico)(?:\.map)?$/,kf=/^(?:[a-z]{8}|[A-Z]{8})$/,If="public, max-age=0, must-revalidate",pd="private, max-age=31536000, immutable";function md(e){let t=Cf.exec(e);return t!==null&&!kf.test(t[1])}function dd(e){return e.toLowerCase().replace(/\s+/g,"")}function Qi(e,t,r){if(e!=="GET"&&e!=="HEAD"||r.status!==200&&r.status!==304||!md(t)||(r.headers.get("content-type")??"").includes("text/html"))return r;let o=r.headers.get("cache-control");if(o===null||dd(o)!==dd(If))return r;let a=new Headers(r.headers);return a.set("cache-control",pd),new Response(r.body,{status:r.status,statusText:r.statusText,headers:a})}var Af=uu*1e3/2,hd=new Map;function Me(e,t){return $t(new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}}))}function yd(e){return $r("app.unroutable",{app:e.appId,message:e.message},"error"),Me(503,{error:"app_unavailable",app:e.appId})}function Of(e,t){return t?`Bearer realm="every-app", error="invalid_token", error_description="Use a personal access token here, or connect ${`${e.replace(/\/$/,"")}/mcp`.replace(/["\\]/g,"")}"`:'Bearer realm="every-app"'}function fd(e,t,r,n){return $t(new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json","www-authenticate":Of(r,n)}}))}function gd(e){return(e.headers.get("accept")??"").includes("text/html")}function Sd(e,t){return e.audienceFor?e.audienceFor(t):t.workerName}async function Mf(e,t){let r=e.now??Date.now(),n=Sd(e,t),o=`${n}\0${e.issuer}`,a=hd.get(o);if(a&&r-a.mintedAtMs<Af)return a.marker;let i=await Wo(e.privateKeyPem,{audience:n,issuer:e.issuer,keyId:e.keyId,now:r});return hd.set(o,{marker:i,mintedAtMs:r}),i}function ec(e){$r("proxy",{app:e.app.appId,method:e.method,status:e.status,ms:Date.now()-e.startedAtMs,gatewayMs:e.startedAtMs-e.receivedAtMs,mode:e.mode})}function Nf(e,t,r){return`gw;dur=${t-e}, app;dur=${r-t}`}async function qf(e,t){if(!e.activate)return!1;try{return await e.activate(t)}catch(r){return $r("app.activate_failed",{app:t.appId,message:r instanceof Error?r.message:String(r)},"warn"),!1}}async function tc(e,t){let r=Date.now(),n=new URL(e.url),o=Xt(e.headers.get("host")??n.host);if(!o)return Me(400,{error:"missing_host"});let a;try{a=await t.resolveApp(o,t.registry)}catch(T){if(!(T instanceof xi))throw T;return yd(T)}if(!a)return Me(404,{error:"no_app_for_host",host:o.host});if(a.status==="disabled")return Me(503,{error:"app_unavailable",status:a.status});if(a.status==="binding"&&await qf(t,a)&&(a={...a,status:"active"}),a.status!=="active"){let T=Me(503,{error:"app_deploying",status:a.status});return T.headers.set("retry-after","5"),T}let i=In(a.manifest.public,e.method,n.pathname);if(t.needsSetup){let T=await t.needsSetup({app:a,request:e,publicRoute:i.public});if(T)return T}if(qi(n.pathname))return Me(404,{error:"not_found"});if(ji(n.pathname))return Me(404,{error:"not_found"});if(a.manifest.serverFnGuard!==!1&&Ji(n.pathname,a.manifest.serverFnBase)){let T=Ki(e.headers);if(!T.allowed)return Me(403,{error:"server_fn_denied",reason:T.reason})}if(Vi(e.headers,t.authenticator.sessionCookieNames))return $r("session.duplicate_cookie",{app:a.appId},"warn"),Me(401,{error:"unauthenticated",reason:"duplicate_session_cookie",message:Ui});let l=Yi(e.headers),c=sd(e.headers),u=e.headers.has("cookie"),m=Fi(e.headers)&&u&&!l?Gi(o.host,e.headers.get("origin")):Bi(e.method,o.host,e.headers.get("origin"),e.headers.get("sec-fetch-site"));if(!l&&!m.allowed&&!i.public&&u)return Me(403,{error:"csrf_denied",reason:m.reason});let f=i.public?"public":"user",y=null;if(m.allowed||l)try{y=await t.authenticator.authenticate(e)}catch(T){if(!i.public)throw T;console.error(`authentication failed for public app "${a.appId}"; continuing anonymously:`,T instanceof Error?T.stack??T.message:T)}let R=y?await t.authenticator.hasAppAccess(y,a):!1,S=R!==!1;y&&typeof R=="object"&&(y=R);let P=y?.credential?.kind==="pat"||y?.credential?.kind==="oauth",b=An(e.headers,i.public,c||P);if(y&&S){let T=a.manifest.mcp?.by,_=T==="gateway"&&n.pathname==="/mcp"&&!i.public,C=_||T==="app"&&n.pathname==="/mcp";if(Qu(y.credential)&&!C)return Me(403,{error:"forbidden",reason:"token_scope"});if(_){let U=t.interceptMcp?await t.interceptMcp({request:e,app:a,session:y}):null;return U?$t(U):Me(503,{error:"mcp_unavailable",app:a.appId})}let M=await Er(t.privateKeyPem,{subject:{sub:y.sub,email:y.email,orgId:y.orgId,orgRole:y.orgRole},audience:Sd(t,a),issuer:t.issuer,channel:y.credential?.channel??"web",actor:y.credential?.actor?{sub:y.credential.actor}:void 0,scopes:y.credential?.scopes,keyId:t.keyId,now:t.now});b.set(Tt,M)}else{if(c||P||l&&!i.public)return y?Me(403,{error:"forbidden",reason:"no_app_access"}):fd(401,{error:"unauthenticated"},t.issuer,l);if(i.public){let T=await Mf(t,a);b.set(wr,T)}else return y?Me(403,{error:"forbidden",reason:"no_app_access"}):gd(e)&&t.thirdParty?$t(await t.thirdParty.startSession(e)):gd(e)&&t.loginUrl?$t(new Response(null,{status:302,headers:{location:`${t.loginUrl}?return_to=${encodeURIComponent(n.toString())}`}})):fd(401,{error:"unauthenticated"},t.issuer,l)}let h=new Request(e.url,{method:e.method,headers:b,body:e.body,redirect:"manual",cf:e.cf,...e.body?{duplex:"half"}:{}}),$,v=Date.now();try{$=await(t.fetcherFor??On)(t.env,a).fetch(h)}catch(T){return T instanceof rt?(console.error(`app unreachable: ${T.message}`),ec({app:a,method:e.method,status:503,receivedAtMs:r,startedAtMs:v,mode:f}),Me(503,{error:"app_unreachable",app:a.appId})):(console.error(`app "${a.appId}" threw:`,T instanceof Error?T.stack??T.message:T),ec({app:a,method:e.method,status:502,receivedAtMs:r,startedAtMs:v,mode:f}),Me(502,{error:"app_error",app:a.appId}))}let z=Date.now();if(ec({app:a,method:e.method,status:$.status,receivedAtMs:r,startedAtMs:v,mode:f}),$.status===101)return t.thirdParty?Zi($):$;let I=$t(Qi(e.method,n.pathname,t.thirdParty?Zi($):$));return I.headers.append("server-timing",Nf(r,v,z)),I}var rs=new Set(["connection","keep-alive","transfer-encoding","te","trailer","proxy-authenticate","proxy-authorization"]);function rc(e){let r=`http://${e.headers.host??"localhost"}${e.url??"/"}`,n=new Headers;for(let i=0;i<e.rawHeaders.length;i+=2){let l=e.rawHeaders[i];rs.has(l.toLowerCase())||n.append(l,e.rawHeaders[i+1])}let o=e.method??"GET",a=o!=="GET"&&o!=="HEAD";return new Request(r,{method:o,headers:n,...a?{body:ts.toWeb(e),duplex:"half"}:{}})}async function ns(e,t){let r={};t.headers.forEach((o,a)=>{a==="set-cookie"||rs.has(a)||(r[a]=o)});let n=t.headers.getSetCookie();n.length>0&&(r["set-cookie"]=n),e.writeHead(t.status,r),t.body?await Lf(ts.fromWeb(t.body),e):e.end()}function nc(e,t="127.0.0.1"){return{fetch(r){let n=new URL(r.url),o={};return r.headers.forEach((a,i)=>{rs.has(i)||(o[i]=a)}),o.host=n.host,new Promise((a,i)=>{let l=jf.request({host:t,port:e,method:r.method,path:n.pathname+n.search,headers:o},c=>{let u=new Headers;for(let y=0;y<c.rawHeaders.length;y+=2){let R=c.rawHeaders[y];rs.has(R.toLowerCase())||u.append(R,c.rawHeaders[y+1])}let m=c.statusCode??502,f=m!==204&&m!==304&&r.method!=="HEAD";a(new Response(f?ts.toWeb(c):null,{status:m,headers:u}))});l.on("error",i),r.body?ts.fromWeb(r.body).pipe(l):l.end()})}}}function Df(e){let t=e.headers.host??"localhost",r=new Headers;for(let n=0;n<e.rawHeaders.length;n+=2)r.append(e.rawHeaders[n],e.rawHeaders[n+1]);return new Request(`http://${t}${e.url??"/"}`,{method:e.method??"GET",headers:r})}async function _d(e,t,r,n){try{if(n.parseAppLabel(e.headers.host??null)!==n.appId){t.end(`HTTP/1.1 404 Not Found\r
2
+ connection: close\r
3
+ \r
4
+ `);return}let a=Df(e),i=In(n.publicRoutes,a.method,new URL(a.url).pathname),l=await n.mintIdentity(a);if(!l&&!i.public){t.end(`HTTP/1.1 401 Unauthorized\r
5
+ connection: close\r
6
+ \r
7
+ `);return}let c=An(a.headers,i.public);l?c.set(Tt,l):c.set(wr,await n.mintPublicMarker()),oc(e,t,r,n.appPort,{outboundHeaders:c})}catch{t.destroy()}}function oc(e,t,r,n,o={}){let a=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];if(o.outboundHeaders)o.outboundHeaders.forEach((c,u)=>{a.push(`${u}: ${c}`)});else for(let c=0;c<e.rawHeaders.length;c+=2)a.push(`${e.rawHeaders[c]}: ${e.rawHeaders[c+1]}`);let i=vd.connect(n,o.targetHost??"127.0.0.1",()=>{i.write(a.join(`\r
8
+ `)+`\r
9
+ \r
10
+ `),r.length>0&&i.write(r),t.pipe(i),i.pipe(t)}),l=()=>{t.destroy(),i.destroy()};i.on("error",l),t.on("error",l)}function bd(){return new Promise((e,t)=>{let r=vd.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address();if(n&&typeof n=="object"){let o=n.port;r.close(()=>e(o))}else r.close(()=>t(new Error("could not allocate a port")))})})}function Rd(e,t=9e4){return sc(`http://127.0.0.1:${e}/`,t)}async function sc(e,t=9e4){let r=Date.now()+t,n;for(;Date.now()<r;)try{await fetch(e,{method:"HEAD"});return}catch(o){n=o,await new Promise(a=>setTimeout(a,300))}throw new Error(`nothing answered at ${e} within ${t}ms: ${String(n)}`)}import xf from"node:net";function os(e,t,r=process.argv.slice(2)){let n=e.slice(2).replace(/-([a-z])/g,(i,l)=>l.toUpperCase()),o=new Set([e,`--${n}`]),a=[];for(let i=0;i<r.length;i++){let l=r[i];if(o.has(l)){i++;continue}[...o].some(c=>l.startsWith(`${c}=`))||a.push(l)}return Ko([],{argv:[...a,e,t]})}var Mn=(r=>(r.Stub="stub",r.Mirror="mirror",r))(Mn||{}),ic="EVERYAPP_DEV_MODE",Zt="everyapp.localhost";function wd(e,t){let r=e??t??"stub",n=Object.values(Mn).find(o=>o===r.toLowerCase());if(n)return n;throw new De("INVALID_DEV_MODE",[`${e===void 0?ic:"--mode"} must be stub or mirror, not "${r}"`,"stub signs you in as a seeded dev user; mirror uses real login through a local Gateway."].join(`
11
+ `))}function Hf(e){let t=e.split(":")[0]??e;return t.length===0?0:t.split(".").filter(r=>r.length>0).length}function Ed(e){if(!(Hf(e)>=2))throw new De("MIRROR_BASE_HOST",[`Mirror mode needs a two-label base host, like ${Zt}`,`The session cookie must cross from the Gateway to the app's subdomain; "${e}" has one label.`,`Open apps at http://<app>.${Zt}:<port> through portless or an /etc/hosts entry.`].join(`
12
+ `),{rerun:os("--base-host",Zt),data:{baseHost:e,fix:`on the local Gateway, set EVERYAPP_DEV_COOKIE_DOMAIN=${Zt} and GATEWAY_URL=http://${Zt}:<port>`}})}var ac=e=>e.split(":")[0]??e;function cc(e,t){let r=ac(e).toLowerCase(),n=ac(t).toLowerCase();if(r===n)return{kind:"launcher"};if(r.endsWith(`.${n}`)){let o=r.slice(0,-(n.length+1));if(o.length>0&&!o.includes("."))return{kind:"app",appLabel:o}}return{kind:"invalid"}}function lc(e,t){let r;try{r=new URL(`http://${e.trim().toLowerCase()}`).hostname}catch{return!1}if(!r)return!1;if(r==="localhost"||r.endsWith(".localhost")||xf.isIP(r.replace(/^\[|\]$/g,"")))return!0;if(t){let n=ac(t).trim().toLowerCase();if(n&&(r===n||r.endsWith(`.${n}`)))return!0}return!1}function Td(e){return e.origin!==void 0||e.referer!==void 0||e["sec-fetch-mode"]!==void 0||e["sec-fetch-site"]!==void 0}function $d(e){let t=e.fetchImpl??fetch,r=new URL("/api/dev/identity",e.gatewayUrl).toString(),n=new Set;function o(i){switch(i){case"no_session":return`No Gateway session yet: log in at ${e.loginUrl}, then reload`;case"no_active_organization":return"No active organization: create or pick one in the Gateway, then reload";case"expired":return"Your Gateway session expired: log in again, then reload";default:return`The Gateway rejected the session (${i})`}}function a(i){!i||n.has(i)||(n.add(i),e.onHint?.(o(i)))}return{sessionCookieNames:[],async authenticate(i){let l=i.headers.get("cookie"),c=Wi(i.headers);if(!l&&!c)return a("no_session"),null;let u=c?{authorization:`Bearer ${c}`}:{cookie:l},m;try{m=await t(r,{headers:u})}catch(y){return e.onHint?.([`Can't reach the local Gateway at ${e.gatewayUrl}`,`${Tr(y)}. Is pnpm dev running in apps/every-app-gateway?`].join(`
13
+ `)),null}if(!m.ok)return null;let f=await m.json();return f.session?f.session:(a(f.reason),null)},async hasAppAccess(){return!0}}}var Nn="dev.migrations";async function zd({cwd:e,manifest:t,cf:r,out:n,skip:o}){if(await Yu(e,n),o){n.emit({type:"step",step:Nn,status:"skip",data:{reason:"flag"}});return}let a=await Fu(e,t);if(a.status==="skipped"){n.emit({type:"step",step:Nn,status:"skip",data:{reason:a.reason}});return}n.emit({type:"step",step:Nn,status:"start",message:"Applying local migrations..."});let i;try{i=await Gu({cwd:e,manifest:t,cf:r,...a})}catch(l){let c=Tr(l);throw n.emit({type:"step",step:Nn,status:"fail",data:{message:c}}),new De("MIGRATIONS_FAILED",["A local migration failed",c,"Or start with --skip-migrations if the local database is already usable."].join(`
14
+ `),{data:{fix:`correct the migration, then run ${Ko()} again`}})}Xu(n,Nn,i)}async function Pd({cwd:e,manifest:t,cf:r,port:n}){return t.dev?qu({command:t.dev,args:[],cwd:e,env:{...process.env,PORT:String(n),NODE_OPTIONS:Lu(process.env.NODE_OPTIONS)},shell:!0,hold:!0}):r.start({args:["dev"],cwd:e,env:{PORT:String(n),...Ju(e)},holdOutput:!0})}import Kh from"node:net";var zt={sub:"dev-user",email:"dev@everyapp.localhost",orgId:"dev-org",orgRole:"owner"},Uf="x-everyapp-dev-anon",Vf=/(?:^|;\s*)everyapp_dev_anon=1(?:;|$)/;function Bf(){return{sessionCookieNames:[],authenticate:async e=>e.headers.get(Uf)==="1"||Vf.test(e.headers.get("cookie")??"")?null:zt,hasAppAccess:async()=>!0}}function Cd(e){let t=new Hi(e.apps.map(n=>n.manifest.mcp?n:{...n,manifest:{...n.manifest,mcp:{by:"gateway",why:"everyapp dev serves it locally."}}})),r={env:e.env,registry:t,authenticator:e.authenticator??Bf(),privateKeyPem:Yt,issuer:Wt,keyId:Kt,resolveApp:async(n,o)=>n.appLabel?o.findByAppId(n.appLabel):null,fetcherFor:e.fetcherFor??On,audienceFor:n=>n.appId,interceptMcp:e.interceptMcp};return n=>tc(n,r)}async function uc(e,t=zt){return Er(Yt,{subject:t,audience:e,issuer:Wt,channel:"web",keyId:Kt})}async function kd(e){return Wo(Yt,{audience:e,issuer:Wt,keyId:Kt})}function Se(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var qn=class extends Error{constructor(r){super(`timed out after ${r}ms`);this.ms=r;this.name="TimeoutError"}};async function ss(e,t){let r=new AbortController,n,o=new Promise((a,i)=>{n=setTimeout(()=>{r.abort(),i(new qn(e))},e)});try{return await Promise.race([t(r.signal),o])}finally{clearTimeout(n)}}async function as(e,t,r){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>t)return await e.body?.cancel().catch(()=>{}),{ok:!1,bytes:n};if(!e.body)return{ok:!0,text:"",bytes:0};let o=e.body.getReader(),a=()=>void o.cancel().catch(()=>{});r?.aborted&&a(),r?.addEventListener("abort",a,{once:!0});let i=new TextDecoder,l="",c=0;try{for(;;){let{done:u,value:m}=await o.read();if(u)break;if(c+=m.byteLength,c>t)return await o.cancel().catch(()=>{}),{ok:!1,bytes:c};l+=i.decode(m,{stream:!0})}}finally{r?.removeEventListener("abort",a)}return{ok:!0,text:l+i.decode(),bytes:c}}function jn(e){return e.length>128?`${e.slice(0,128)}\u2026`:e}function nt(e,t){return`${e}_${t}`}function is(e){let t=e.indexOf("_");return t<=0||t===e.length-1?null:{appId:e.slice(0,t),localName:e.slice(t+1)}}function Id(e,t,r){return e.surface==="app"?r.name:nt(t.appId,r.name)}function Ad(e,t){let r,n=t;if(e.surface==="gateway"){let i=is(t);if(!i)return null;({appId:r,localName:n}=i)}let o=e.surface==="app"?e.apps[0]:e.apps.find(i=>i.appId===r),a=o?.tools.find(i=>i.name===n);return o&&a?{app:o,tool:a}:null}var Ff=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),Od=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),Gf=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),Jf=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function Md(e){return typeof e=="string"&&Od.has(e.replace(/#$/,""))}function cs(e,t){if(!("$schema"in e)||typeof e.$schema!="string")return"2020-12";let r=e.$schema.replace(/#$/,"");if(Ff.has(r))return"2020-12";if(Od.has(r))return"2019-09";if(Gf.has(r)||Jf.has(r))return"draft-7";throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}function Ln(e,t){let r=typeof e;if(r!==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 o=0;o<n;o++)if(!Ln(e[o],t[o]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(let a of n)if(!Ln(e[a],t[a]))return!1;return!0}return e===t}function We(e){return encodeURI(Kf(e))}function Kf(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Wf={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Yf={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Xf={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},Zf=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 Qt(e,t=Object.create(null),r=Zf,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let a=e.$id||e.id;if(a){let i=new URL(a,r.href);i.hash.length>1?t[i.href]=e:(i.hash="",n===""?r=i:Qt(e,t,r))}}else if(e!==!0&&e!==!1)return t;let o=r.href+(n?"#"+n:"");if(t[o]!==void 0)throw new Error(`Duplicate schema URI "${o}".`);if(t[o]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:o}),e.$ref&&e.__absolute_ref__===void 0){let a=new URL(e.$ref,r.href);a.hash=a.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:a.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let a=new URL(e.$recursiveRef,r.href);a.hash=a.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:a.href})}if(e.$anchor){let a=new URL("#"+e.$anchor,r.href);t[a.href]=e}for(let a in e){if(Xf[a])continue;let i=`${n}/${We(a)}`,l=e[a];if(Array.isArray(l)){if(Wf[a]){let c=l.length;for(let u=0;u<c;u++)Qt(l[u],t,r,`${i}/${u}`)}}else if(Yf[a])for(let c in l)Qt(l[c],t,r,`${i}/${We(c)}`);else Qt(l,t,r,i)}return t}var Qf=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,eg=[0,31,28,31,30,31,30,31,31,30,31,30,31],tg=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,rg=/^(?=.{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,ng=/^(?:[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,og=/^(?:(?:[^\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,sg=/^(?:(?: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,ag=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,ig=/^(?:\/(?:[^~/]|~0|~1)*)*$/,cg=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,lg=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,ug=e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},dg=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,pg=/^((([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,mg=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));function ot(e){return e.test.bind(e)}var Nd={date:qd,time:jd.bind(void 0,!1),"date-time":gg,duration:mg,uri:vg,"uri-reference":ot(ng),"uri-template":ot(og),url:ot(sg),email:ug,hostname:ot(rg),ipv4:ot(dg),ipv6:ot(pg),regex:bg,uuid:ot(ag),"json-pointer":ot(ig),"json-pointer-uri-fragment":ot(cg),"relative-json-pointer":ot(lg)};function hg(e){return e%4===0&&(e%100!==0||e%400===0)}function qd(e){let t=e.match(Qf);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&hg(r)?29:eg[n])}function jd(e,t){let r=t.match(tg);if(!r)return!1;let n=+r[1],o=+r[2],a=+r[3],i=!!r[5];return(n<=23&&o<=59&&a<=59||n==23&&o==59&&a==60)&&(!e||i)}var fg=/t|\s/i;function gg(e){let t=e.split(fg);return t.length==2&&qd(t[0])&&jd(!0,t[1])}var yg=/\/|:/,Sg=/^(?:[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 vg(e){return yg.test(e)&&Sg.test(e)}var _g=/[^\\]\\Z/;function bg(e){if(_g.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}function Rg(e){let t=0,r=e.length,n=0,o;for(;n<r;)t++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<r&&(o=e.charCodeAt(n),(o&64512)==56320&&n++);return t}function Ee(e,t,r="2019-09",n=Qt(t),o=!0,a=null,i="#",l="#",c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};let u=typeof e,m;switch(u){case"boolean":case"number":case"string":m=u;break;case"object":e===null?m="null":Array.isArray(e)?m="array":m="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}let{$ref:f,$recursiveRef:y,$recursiveAnchor:R,type:S,const:P,enum:b,required:h,not:$,anyOf:v,allOf:z,oneOf:I,if:T,then:_,else:C,format:M,properties:U,patternProperties:q,additionalProperties:D,unevaluatedProperties:W,minProperties:F,maxProperties:ie,propertyNames:he,dependentRequired:ge,dependentSchemas:_e,dependencies:ue,prefixItems:O,items:j,additionalItems:E,unevaluatedItems:p,contains:g,minContains:w,maxContains:A,minItems:x,maxItems:J,uniqueItems:K,minimum:ce,maximum:fe,exclusiveMinimum:k,exclusiveMaximum:L,multipleOf:H,minLength:Q,maxLength:re,pattern:ne,__absolute_ref__:me,__absolute_recursive_ref__:Re}=t,B=[];if(R===!0&&a===null&&(a=t),y==="#"){let X=a===null?n[Re]:a,ee=`${l}/$recursiveRef`,oe=Ee(e,a===null?t:a,r,n,o,X,i,ee,c);oe.valid||B.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:ee,error:"A subschema had errors."},...oe.errors)}if(f!==void 0){let X=n[me||f];if(X===void 0){let Z=`Unresolved $ref "${f}".`;throw me&&me!==f&&(Z+=` Absolute URI "${me}".`),Z+=`
15
+ Known schemas:
16
+ - ${Object.keys(n).join(`
17
+ - `)}`,new Error(Z)}let ee=`${l}/$ref`,oe=Ee(e,X,r,n,o,a,i,ee,c);if(oe.valid||B.push({instanceLocation:i,keyword:"$ref",keywordLocation:ee,error:"A subschema had errors."},...oe.errors),r==="4"||r==="7")return{valid:B.length===0,errors:B}}if(Array.isArray(S)){let X=S.length,ee=!1;for(let oe=0;oe<X;oe++)if(m===S[oe]||S[oe]==="integer"&&m==="number"&&e%1===0&&e===e){ee=!0;break}ee||B.push({instanceLocation:i,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${m}" is invalid. Expected "${S.join('", "')}".`})}else S==="integer"?(m!=="number"||e%1||e!==e)&&B.push({instanceLocation:i,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${m}" is invalid. Expected "${S}".`}):S!==void 0&&m!==S&&B.push({instanceLocation:i,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${m}" is invalid. Expected "${S}".`});if(P!==void 0&&(m==="object"||m==="array"?Ln(e,P)||B.push({instanceLocation:i,keyword:"const",keywordLocation:`${l}/const`,error:`Instance does not match ${JSON.stringify(P)}.`}):e!==P&&B.push({instanceLocation:i,keyword:"const",keywordLocation:`${l}/const`,error:`Instance does not match ${JSON.stringify(P)}.`})),b!==void 0&&(m==="object"||m==="array"?b.some(X=>Ln(e,X))||B.push({instanceLocation:i,keyword:"enum",keywordLocation:`${l}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(X=>e===X)||B.push({instanceLocation:i,keyword:"enum",keywordLocation:`${l}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),$!==void 0){let X=`${l}/not`;Ee(e,$,r,n,o,a,i,X).valid&&B.push({instanceLocation:i,keyword:"not",keywordLocation:X,error:'Instance matched "not" schema.'})}let be=[];if(v!==void 0){let X=`${l}/anyOf`,ee=B.length,oe=!1;for(let Z=0;Z<v.length;Z++){let Y=v[Z],se=Object.create(c),ae=Ee(e,Y,r,n,o,R===!0?a:null,i,`${X}/${Z}`,se);B.push(...ae.errors),oe=oe||ae.valid,ae.valid&&be.push(se)}oe?B.length=ee:B.splice(ee,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:X,error:"Instance does not match any subschemas."})}if(z!==void 0){let X=`${l}/allOf`,ee=B.length,oe=!0;for(let Z=0;Z<z.length;Z++){let Y=z[Z],se=Object.create(c),ae=Ee(e,Y,r,n,o,R===!0?a:null,i,`${X}/${Z}`,se);B.push(...ae.errors),oe=oe&&ae.valid,ae.valid&&be.push(se)}oe?B.length=ee:B.splice(ee,0,{instanceLocation:i,keyword:"allOf",keywordLocation:X,error:"Instance does not match every subschema."})}if(I!==void 0){let X=`${l}/oneOf`,ee=B.length,oe=I.filter((Z,Y)=>{let se=Object.create(c),ae=Ee(e,Z,r,n,o,R===!0?a:null,i,`${X}/${Y}`,se);return B.push(...ae.errors),ae.valid&&be.push(se),ae.valid}).length;oe===1?B.length=ee:B.splice(ee,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:X,error:`Instance does not match exactly one subschema (${oe} matches).`})}if((m==="object"||m==="array")&&Object.assign(c,...be),T!==void 0){let X=`${l}/if`;if(Ee(e,T,r,n,o,a,i,X,c).valid){if(_!==void 0){let ee=Ee(e,_,r,n,o,a,i,`${l}/then`,c);ee.valid||B.push({instanceLocation:i,keyword:"if",keywordLocation:X,error:'Instance does not match "then" schema.'},...ee.errors)}}else if(C!==void 0){let ee=Ee(e,C,r,n,o,a,i,`${l}/else`,c);ee.valid||B.push({instanceLocation:i,keyword:"if",keywordLocation:X,error:'Instance does not match "else" schema.'},...ee.errors)}}if(m==="object"){if(h!==void 0)for(let Z of h)Z in e||B.push({instanceLocation:i,keyword:"required",keywordLocation:`${l}/required`,error:`Instance does not have required property "${Z}".`});let X=Object.keys(e);if(F!==void 0&&X.length<F&&B.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${l}/minProperties`,error:`Instance does not have at least ${F} properties.`}),ie!==void 0&&X.length>ie&&B.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${l}/maxProperties`,error:`Instance does not have at least ${ie} properties.`}),he!==void 0){let Z=`${l}/propertyNames`;for(let Y in e){let se=`${i}/${We(Y)}`,ae=Ee(Y,he,r,n,o,a,se,Z);ae.valid||B.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:Z,error:`Property name "${Y}" does not match schema.`},...ae.errors)}}if(ge!==void 0){let Z=`${l}/dependantRequired`;for(let Y in ge)if(Y in e){let se=ge[Y];for(let ae of se)ae in e||B.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:Z,error:`Instance has "${Y}" but does not have "${ae}".`})}}if(_e!==void 0)for(let Z in _e){let Y=`${l}/dependentSchemas`;if(Z in e){let se=Ee(e,_e[Z],r,n,o,a,i,`${Y}/${We(Z)}`,c);se.valid||B.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:Y,error:`Instance has "${Z}" but does not match dependant schema.`},...se.errors)}}if(ue!==void 0){let Z=`${l}/dependencies`;for(let Y in ue)if(Y in e){let se=ue[Y];if(Array.isArray(se))for(let ae of se)ae in e||B.push({instanceLocation:i,keyword:"dependencies",keywordLocation:Z,error:`Instance has "${Y}" but does not have "${ae}".`});else{let ae=Ee(e,se,r,n,o,a,i,`${Z}/${We(Y)}`);ae.valid||B.push({instanceLocation:i,keyword:"dependencies",keywordLocation:Z,error:`Instance has "${Y}" but does not match dependant schema.`},...ae.errors)}}}let ee=Object.create(null),oe=!1;if(U!==void 0){let Z=`${l}/properties`;for(let Y in U){if(!(Y in e))continue;let se=`${i}/${We(Y)}`,ae=Ee(e[Y],U[Y],r,n,o,a,se,`${Z}/${We(Y)}`);if(ae.valid)c[Y]=ee[Y]=!0;else if(oe=o,B.push({instanceLocation:i,keyword:"properties",keywordLocation:Z,error:`Property "${Y}" does not match schema.`},...ae.errors),oe)break}}if(!oe&&q!==void 0){let Z=`${l}/patternProperties`;for(let Y in q){let se=new RegExp(Y,"u"),ae=q[Y];for(let we in e){if(!se.test(we))continue;let dt=`${i}/${We(we)}`,tt=Ee(e[we],ae,r,n,o,a,dt,`${Z}/${We(Y)}`);tt.valid?c[we]=ee[we]=!0:(oe=o,B.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:Z,error:`Property "${we}" matches pattern "${Y}" but does not match associated schema.`},...tt.errors))}}}if(!oe&&D!==void 0){let Z=`${l}/additionalProperties`;for(let Y in e){if(ee[Y])continue;let se=`${i}/${We(Y)}`,ae=Ee(e[Y],D,r,n,o,a,se,Z);ae.valid?c[Y]=!0:(oe=o,B.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:Z,error:`Property "${Y}" does not match additional properties schema.`},...ae.errors))}}else if(!oe&&W!==void 0){let Z=`${l}/unevaluatedProperties`;for(let Y in e)if(!c[Y]){let se=`${i}/${We(Y)}`,ae=Ee(e[Y],W,r,n,o,a,se,Z);ae.valid?c[Y]=!0:B.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:Z,error:`Property "${Y}" does not match unevaluated properties schema.`},...ae.errors)}}}else if(m==="array"){J!==void 0&&e.length>J&&B.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${l}/maxItems`,error:`Array has too many items (${e.length} > ${J}).`}),x!==void 0&&e.length<x&&B.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${l}/minItems`,error:`Array has too few items (${e.length} < ${x}).`});let X=e.length,ee=0,oe=!1;if(O!==void 0){let Z=`${l}/prefixItems`,Y=Math.min(O.length,X);for(;ee<Y;ee++){let se=Ee(e[ee],O[ee],r,n,o,a,`${i}/${ee}`,`${Z}/${ee}`);if(c[ee]=!0,!se.valid&&(oe=o,B.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:Z,error:"Items did not match schema."},...se.errors),oe))break}}if(j!==void 0){let Z=`${l}/items`;if(Array.isArray(j)){let Y=Math.min(j.length,X);for(;ee<Y;ee++){let se=Ee(e[ee],j[ee],r,n,o,a,`${i}/${ee}`,`${Z}/${ee}`);if(c[ee]=!0,!se.valid&&(oe=o,B.push({instanceLocation:i,keyword:"items",keywordLocation:Z,error:"Items did not match schema."},...se.errors),oe))break}}else for(;ee<X;ee++){let Y=Ee(e[ee],j,r,n,o,a,`${i}/${ee}`,Z);if(c[ee]=!0,!Y.valid&&(oe=o,B.push({instanceLocation:i,keyword:"items",keywordLocation:Z,error:"Items did not match schema."},...Y.errors),oe))break}if(!oe&&E!==void 0){let Y=`${l}/additionalItems`;for(;ee<X;ee++){let se=Ee(e[ee],E,r,n,o,a,`${i}/${ee}`,Y);c[ee]=!0,se.valid||(oe=o,B.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:Y,error:"Items did not match additional items schema."},...se.errors))}}}if(g!==void 0)if(X===0&&w===void 0)B.push({instanceLocation:i,keyword:"contains",keywordLocation:`${l}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(w!==void 0&&X<w)B.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${l}/minContains`,error:`Array has less items (${X}) than minContains (${w}).`});else{let Z=`${l}/contains`,Y=B.length,se=0;for(let ae=0;ae<X;ae++){let we=Ee(e[ae],g,r,n,o,a,`${i}/${ae}`,Z);we.valid?(c[ae]=!0,se++):B.push(...we.errors)}se>=(w||0)&&(B.length=Y),w===void 0&&A===void 0&&se===0?B.splice(Y,0,{instanceLocation:i,keyword:"contains",keywordLocation:Z,error:"Array does not contain item matching schema."}):w!==void 0&&se<w?B.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${l}/minContains`,error:`Array must contain at least ${w} items matching schema. Only ${se} items were found.`}):A!==void 0&&se>A&&B.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${l}/maxContains`,error:`Array may contain at most ${A} items matching schema. ${se} items were found.`})}if(!oe&&p!==void 0){let Z=`${l}/unevaluatedItems`;for(;ee<X;ee++){if(c[ee])continue;let Y=Ee(e[ee],p,r,n,o,a,`${i}/${ee}`,Z);c[ee]=!0,Y.valid||B.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:Z,error:"Items did not match unevaluated items schema."},...Y.errors)}}if(K)for(let Z=0;Z<X;Z++){let Y=e[Z],se=typeof Y=="object"&&Y!==null;for(let ae=0;ae<X;ae++){if(Z===ae)continue;let we=e[ae];(Y===we||se&&typeof we=="object"&&we!==null&&Ln(Y,we))&&(B.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${l}/uniqueItems`,error:`Duplicate items at indexes ${Z} and ${ae}.`}),Z=Number.MAX_SAFE_INTEGER,ae=Number.MAX_SAFE_INTEGER)}}}else if(m==="number"){if(r==="4"?(ce!==void 0&&(k===!0&&e<=ce||e<ce)&&B.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${l}/minimum`,error:`${e} is less than ${k?"or equal to ":""} ${ce}.`}),fe!==void 0&&(L===!0&&e>=fe||e>fe)&&B.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${l}/maximum`,error:`${e} is greater than ${L?"or equal to ":""} ${fe}.`})):(ce!==void 0&&e<ce&&B.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${l}/minimum`,error:`${e} is less than ${ce}.`}),fe!==void 0&&e>fe&&B.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${l}/maximum`,error:`${e} is greater than ${fe}.`}),k!==void 0&&e<=k&&B.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${l}/exclusiveMinimum`,error:`${e} is less than ${k}.`}),L!==void 0&&e>=L&&B.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${l}/exclusiveMaximum`,error:`${e} is greater than or equal to ${L}.`})),H!==void 0){let X=e%H;Math.abs(0-X)>=11920929e-14&&Math.abs(H-X)>=11920929e-14&&B.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${l}/multipleOf`,error:`${e} is not a multiple of ${H}.`})}}else if(m==="string"){let X=Q===void 0&&re===void 0?0:Rg(e);Q!==void 0&&X<Q&&B.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${l}/minLength`,error:`String is too short (${X} < ${Q}).`}),re!==void 0&&X>re&&B.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${l}/maxLength`,error:`String is too long (${X} > ${re}).`}),ne!==void 0&&!new RegExp(ne,"u").test(e)&&B.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${l}/pattern`,error:"String does not match pattern."}),M!==void 0&&Nd[M]&&!Nd[M](e)&&B.push({instanceLocation:i,keyword:"format",keywordLocation:`${l}/format`,error:`String does not match format "${M}".`})}return{valid:B.length===0,errors:B}}var wg=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=Qt(e)}validate(e){return Ee(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Qt(e,this.lookup)}},dc=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=cs(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){let t=new wg(e,this.draft??this._draftFor(e),this.shortcircuit);return r=>{let n=t.validate(r);return n.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:n.errors.map(o=>`${o.instanceLocation}: ${o.error}`).join("; ")}}}};var ls=new dc,xd=1e3,Eg=256,zr=new Map;function Hd(e,t){let r=JSON.stringify(t),n=zr.get(e);if(n?.schema===r)return n.check;let o=Ig(t),a=o?ls.getValidator(o):null;if(zr.delete(e),zr.size>=Eg){let i=zr.keys().next().value;i!==void 0&&zr.delete(i)}return zr.set(e,{schema:r,check:a}),a}function Ud(e){let t=Ag(e);if(t)return`$ref "${t}" does not resolve in the schema`;try{return ls.getValidator(e)({}),null}catch(r){return r instanceof Error?r.message:String(r)}}var Ld=new Set(["pattern","patternProperties"]),Tg=new Set(["$ref","$dynamicRef","$recursiveRef"]),$g=new Set(["unevaluatedProperties","unevaluatedItems"]),zg=new Set(["not","if","oneOf","contains"]),Pg=new Set(["additionalItems","additionalProperties","contains","contentSchema","else","if","items","not","propertyNames","then","unevaluatedItems","unevaluatedProperties"]),Cg=new Set(["allOf","anyOf","oneOf","prefixItems"]),kg=new Set(["$defs","definitions","dependencies","dependentSchemas","patternProperties","properties"]);function Dd(e,t,r){return Pg.has(e)?Array.isArray(t)?t.map(r):r(t):Cg.has(e)?Array.isArray(t)?t.map(r):t:kg.has(e)&&Se(t)?Object.fromEntries(Object.entries(t).map(([n,o])=>[n,r(o)])):t}function Ig(e){let t={regex:!1,regexWhereExact:!1,reference:!1},r=!1,n=(a,i)=>{if(!Se(a))return a;for(let[l,c]of Object.entries(a))Tg.has(l)&&(t.reference=!0),$g.has(l)&&(r=!0),Ld.has(l)&&(t.regex=!0,i&&(t.regexWhereExact=!0)),Dd(l,c,u=>n(u,i||zg.has(l)));return a};if(n(e,!1),t.reference||t.regexWhereExact)return null;if(!t.regex)return e;if(r)return null;let o=a=>{if(!Se(a))return a;let i={};for(let[l,c]of Object.entries(a))Ld.has(l)||l==="additionalProperties"&&"patternProperties"in a||(i[l]=Dd(l,c,o));return i};return o(e)}function Ag(e){let t=new Set,r=[],n=o=>{if(Array.isArray(o))return o.forEach(n);if(!o||typeof o!="object")return;let a=o;typeof a.$anchor=="string"&&t.add(a.$anchor),typeof a.$ref=="string"&&r.push(a.$ref),Object.values(a).forEach(n)};return n(e),r.find(o=>{if(!o.startsWith("#"))return!0;let a=o.slice(1);if(a==="")return!1;if(!a.startsWith("/"))return!t.has(a);let i=e;for(let l of a.slice(1).split("/")){let c;try{c=decodeURIComponent(l).replace(/~1/g,"/").replace(/~0/g,"~")}catch{return!0}if(!i||typeof i!="object"||!(c in i))return!0;i=i[c]}return!1})??null}function Vd(e,t){let r=0,n=[[e,0]];for(let o=n.pop();o;o=n.pop()){let[a,i]=o;if(r+=1,!(a===null||typeof a!="object")){if(i+1>t)return{tooDeep:!0};for(let l of Array.isArray(a)?a:Object.values(a))n.push([l,i+1])}}return{tooDeep:!1,values:r}}var Ve={schemaBytes:20*1024,descriptionChars:2048,titleChars:100,instructionsChars:2048,warningChars:500,warningsMax:100,responseBytes:5*1024*1024},Og=15e3,Mg=/^sha256:[0-9a-f]{64}$/,Ng="x-mcp-header";function qg(e,t){if(!Se(t)||t.v!==1)return{status:"error",error:`expected a v${1} tools catalog`};let{hash:r,sdk:n,tools:o}=t;if(typeof r!="string"||!Mg.test(r))return{status:"error",error:"the catalog has no valid hash"};if(typeof n!="string"||n.length>32)return{status:"error",error:"the catalog has no SDK version"};if(!Array.isArray(o))return{status:"error",error:"the catalog has no tools list"};let a=Array.isArray(t.warnings)?t.warnings.filter(u=>typeof u=="string").slice(0,Ve.warningsMax).map(u=>u.slice(0,Ve.warningChars)):[],i;typeof t.instructions=="string"&&t.instructions&&(i=t.instructions,i.length>Ve.instructionsChars&&(i=i.slice(0,Ve.instructionsChars),a.push(`instructions trimmed to ${Ve.instructionsChars} characters`)));let l=[],c=new Set;for(let u of o){let m=jg(e,u);if(typeof m=="string"){a.push(m);continue}if(c.has(m.name)){a.push(`${m.name}: skipped, duplicate name`);continue}c.add(m.name),l.push(m)}return{status:l.length>0?"ok":"empty",hash:r,sdkVersion:n,...i?{instructions:i}:{},tools:l,warnings:a}}function jg(e,t){if(!Se(t)||typeof t.name!="string")return"skipped a tool without a name";let r=t.name,n=y=>`${r}: skipped, ${y}`;if(!fu.test(r))return n("names must be lowercase snake_case, at most 48 characters");let o=nt(e,r);if(o.length>64)return n(`"${o}" is longer than ${64} characters`);let a=t.description;if(typeof a!="string"||!a.trim())return n("no description");if(a.length>Ve.descriptionChars)return n(`description longer than ${Ve.descriptionChars} characters`);let i=t.title;if(i!==void 0&&typeof i!="string")return n("title is not a string");if(typeof i=="string"&&i.length>Ve.titleChars)return n(`title longer than ${Ve.titleChars} characters`);let l=t.risk??"write";if(!gu(l))return n(`unknown risk "${String(l)}"`);let c=Fd(t.inputSchema);if(typeof c=="string")return n(`inputSchema ${c}`);let u;if(t.outputSchema!==void 0){let y=Fd(t.outputSchema);if(typeof y=="string")return n(`outputSchema ${y}`);u=y}let m={},f=t.annotations;if(Se(f))for(let y of["idempotentHint","openWorldHint"])typeof f[y]=="boolean"&&(m[y]=f[y]);return{name:r,...i?{title:i}:{},description:a,risk:l,inputSchema:c,...u?{outputSchema:u}:{},...Object.keys(m).length>0?{annotations:m}:{}}}function Fd(e){if(!Se(e)||e.type!=="object")return'must be a JSON Schema with type "object"';let t=pc(e);if(new TextEncoder().encode(JSON.stringify(t)).byteLength>Ve.schemaBytes)return`is larger than ${Ve.schemaBytes/1024} KB`;let n=Ud(t);return n?`is not a usable JSON Schema (${n})`:t}function pc(e){if(Array.isArray(e))return e.map(pc);if(!Se(e))return e;let t={};for(let[r,n]of Object.entries(e))r!==Ng&&(t[r]=pc(n));return t}async function Gd(e,t){let r=await du(t.signing.privateKeyPem,{audience:e.audience,issuer:t.signing.issuer,purpose:"tools.list",keyId:t.signing.keyId}),{response:n,read:o}=await ss(t.timeoutMs??Og,async l=>{let c=await t.invoke(new Request(new URL(pu,e.baseUrl),{method:"POST",headers:{"content-type":"application/json",[lu]:r},body:JSON.stringify({v:1}),signal:l})),u=await as(c,Ve.responseBytes,l);return{response:c,read:u}});if(!o.ok)return{status:"error",error:`the catalog is larger than ${Ve.responseBytes/1024/1024} MB`};let a;try{a=JSON.parse(o.text)}catch{a=void 0}if(n.ok)return qg(e.appId,a);let i=Se(a)?a.error:void 0;return Se(a)&&a.v===1&&Se(i)?{status:"error",error:`the app refused the catalog request (${String(i.code)}): ${String(i.message)}`}:[401,403,404,405].includes(n.status)?{status:"unsupported",error:`the app answered ${n.status}; it does not serve agent tools (Every App SDK 0.3 or later)`}:{status:"error",error:`the app answered ${n.status}`}}var Lg=Object.create,us=Object.defineProperty,Dg=Object.getOwnPropertyDescriptor,xg=Object.getOwnPropertyNames,Hg=Object.getPrototypeOf,Ug=Object.prototype.hasOwnProperty,V=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Jd=(e,t)=>{let r={};for(var n in e)us(r,n,{get:e[n],enumerable:!0});return t&&us(r,Symbol.toStringTag,{value:"Module"}),r},Vg=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var o=xg(t),a=0,i=o.length,l;a<i;a++)l=o[a],!Ug.call(e,l)&&l!==r&&us(e,l,{get:(c=>t[c]).bind(null,l),enumerable:!(n=Dg(t,l))||n.enumerable});return e},ds=(e,t,r)=>(r=e!=null?Lg(Hg(e)):{},Vg(t||!e||!e.__esModule?us(r,"default",{value:e,enumerable:!0}):r,e));import*as d from"zod/v4";var rr="2025-11-25",ps="2025-03-26",Dn=[rr,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ms="io.modelcontextprotocol/related-task",Fe="io.modelcontextprotocol/protocolVersion",nr="io.modelcontextprotocol/clientInfo",st="io.modelcontextprotocol/serverInfo",at="io.modelcontextprotocol/clientCapabilities",or="io.modelcontextprotocol/subscriptionId",Ct="io.modelcontextprotocol/logLevel";var sr="2.0";var Pt=d.lazy(()=>d.union([d.string(),d.number(),d.boolean(),d.null(),d.record(d.string(),Pt),d.array(Pt)])),$e=d.record(d.string(),Pt),mc=d.array(Pt),xn=d.union([d.string(),d.number().int()]),Hn=d.string(),hs=d.object({ttl:d.number().optional()}),fs=d.object({taskId:d.string()}),Un=d.looseObject({progressToken:xn.optional(),[ms]:fs.optional()}),ke=d.object({_meta:Un.optional()}),ar=ke.extend({task:hs.optional()}),ze=d.object({method:d.string(),params:ke.loose().optional()}),Ne=d.object({_meta:Un.optional()}),qe=d.object({method:d.string(),params:Ne.loose().optional()}),Vn=d.looseObject({get[st](){return Ir.optional().catch(void 0)}}),Pe=d.looseObject({_meta:Vn.optional()}),kt=d.union([d.string(),d.number().int()]),Bn=d.object({jsonrpc:d.literal(sr),id:kt,...ze.shape}).strict(),Fn=d.object({jsonrpc:d.literal(sr),...qe.shape}).strict(),Pr=d.object({jsonrpc:d.literal(sr),id:kt,result:Pe}).strict(),Cr=d.object({jsonrpc:d.literal(sr),id:kt.optional(),error:d.object({code:d.number().int(),message:d.string(),data:d.unknown().optional()})}).strict(),kr=d.union([Bn,Fn,Pr,Cr]),hc=d.union([Pr,Cr]),Gn=Pe.strict(),gs=Ne.extend({requestId:kt.optional(),reason:d.string().optional()}),Jn=qe.extend({method:d.literal("notifications/cancelled"),params:gs}),ys=d.object({src:d.string(),mimeType:d.string().optional(),sizes:d.array(d.string()).optional(),theme:d.enum(["light","dark"]).optional()}),It=d.object({icons:d.array(ys).optional()}),pt=d.object({name:d.string(),title:d.string().optional()}),Ir=pt.extend({...pt.shape,...It.shape,version:d.string(),websiteUrl:d.string().optional(),description:d.string().optional()}),Bg=d.intersection(d.object({applyDefaults:d.boolean().optional()}),$e),Fg=d.preprocess(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,d.intersection(d.object({form:Bg.optional(),url:$e.optional()}),$e.optional())),Ss=d.looseObject({list:$e.optional(),cancel:$e.optional(),requests:d.looseObject({sampling:d.looseObject({createMessage:$e.optional()}).optional(),elicitation:d.looseObject({create:$e.optional()}).optional()}).optional()}),vs=d.looseObject({list:$e.optional(),cancel:$e.optional(),requests:d.looseObject({tools:d.looseObject({call:$e.optional()}).optional()}).optional()}),_s=d.object({experimental:d.record(d.string(),$e).optional(),sampling:d.object({context:$e.optional(),tools:$e.optional()}).optional(),elicitation:Fg.optional(),roots:d.object({listChanged:d.boolean().optional()}).optional(),tasks:Ss.optional(),extensions:d.record(d.string(),$e).optional()}),bs=ke.extend({protocolVersion:d.string(),capabilities:_s,clientInfo:Ir}),Kn=ze.extend({method:d.literal("initialize"),params:bs}),Wn=d.object({experimental:d.record(d.string(),$e).optional(),logging:$e.optional(),completions:$e.optional(),prompts:d.object({listChanged:d.boolean().optional()}).optional(),resources:d.object({subscribe:d.boolean().optional(),listChanged:d.boolean().optional()}).optional(),tools:d.object({listChanged:d.boolean().optional()}).optional(),tasks:vs.optional(),extensions:d.record(d.string(),$e).optional()}),Rs=Pe.extend({protocolVersion:d.string(),capabilities:Wn,serverInfo:Ir,instructions:d.string().optional()}),ws=qe.extend({method:d.literal("notifications/initialized"),params:Ne.optional()}),Es=ze.extend({method:d.literal("server/discover"),params:ke.optional()}),Ts=Pe.extend({supportedVersions:d.array(d.string()),capabilities:Wn,instructions:d.string().optional()}),Yn=ze.extend({method:d.literal("ping"),params:ke.optional()}),$s=d.object({progress:d.number(),total:d.optional(d.number()),message:d.optional(d.string())}),zs=d.object({...Ne.shape,...$s.shape,progressToken:xn}),Xn=qe.extend({method:d.literal("notifications/progress"),params:zs}),Ps=ke.extend({cursor:Hn.optional()}),At=ze.extend({params:Ps.optional()}),Ot=Pe.extend({nextCursor:Hn.optional()}),Zn=d.object({uri:d.string(),mimeType:d.optional(d.string()),_meta:d.record(d.string(),d.unknown()).optional()}),Qn=Zn.extend({text:d.string()}),fc=d.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),eo=Zn.extend({blob:fc}),Mt=d.enum(["user","assistant"]),mt=d.object({audience:d.array(Mt).optional(),priority:d.number().min(0).max(1).optional(),lastModified:d.iso.datetime({offset:!0}).optional()}),to=d.object({...pt.shape,...It.shape,uri:d.string(),description:d.optional(d.string()),mimeType:d.optional(d.string()),size:d.optional(d.number()),annotations:mt.optional(),_meta:d.optional(d.looseObject({}))}),Cs=d.object({...pt.shape,...It.shape,uriTemplate:d.string(),description:d.optional(d.string()),mimeType:d.optional(d.string()),annotations:mt.optional(),_meta:d.optional(d.looseObject({}))}),ks=At.extend({method:d.literal("resources/list")}),Is=Ot.extend({resources:d.array(to)}),As=At.extend({method:d.literal("resources/templates/list")}),Os=Ot.extend({resourceTemplates:d.array(Cs)}),Ar=ke.extend({uri:d.string()}),Ms=Ar,Ns=ze.extend({method:d.literal("resources/read"),params:Ms}),qs=Pe.extend({contents:d.array(d.union([Qn,eo]))}),js=qe.extend({method:d.literal("notifications/resources/list_changed"),params:Ne.optional()}),Ls=Ar,Ds=ze.extend({method:d.literal("resources/subscribe"),params:Ls}),xs=Ar,Hs=ze.extend({method:d.literal("resources/unsubscribe"),params:xs}),ro=d.object({toolsListChanged:d.boolean().optional(),promptsListChanged:d.boolean().optional(),resourcesListChanged:d.boolean().optional(),resourceSubscriptions:d.array(d.string()).optional()}),Us=ke.extend({notifications:ro}),Vs=ze.extend({method:d.literal("subscriptions/listen"),params:Us}),Bs=Ne.extend({notifications:ro}),Fs=qe.extend({method:d.literal("notifications/subscriptions/acknowledged"),params:Bs}),Gs=Vn.extend({[or]:kt}),Js=Pe.extend({_meta:Gs}),Ks=Ne.extend({uri:d.string()}),Ws=qe.extend({method:d.literal("notifications/resources/updated"),params:Ks}),Ys=d.object({name:d.string(),description:d.optional(d.string()),required:d.optional(d.boolean())}),Xs=d.object({...pt.shape,...It.shape,description:d.optional(d.string()),arguments:d.optional(d.array(Ys)),_meta:d.optional(d.looseObject({}))}),Zs=At.extend({method:d.literal("prompts/list")}),Qs=Ot.extend({prompts:d.array(Xs)}),ea=ke.extend({name:d.string(),arguments:d.record(d.string(),d.string()).optional()}),ta=ze.extend({method:d.literal("prompts/get"),params:ea}),Or=d.object({type:d.literal("text"),text:d.string(),annotations:mt.optional(),_meta:d.record(d.string(),d.unknown()).optional()}),Mr=d.object({type:d.literal("image"),data:fc,mimeType:d.string(),annotations:mt.optional(),_meta:d.record(d.string(),d.unknown()).optional()}),Nr=d.object({type:d.literal("audio"),data:fc,mimeType:d.string(),annotations:mt.optional(),_meta:d.record(d.string(),d.unknown()).optional()}),ra=d.object({type:d.literal("tool_use"),name:d.string(),id:d.string(),input:d.record(d.string(),d.unknown()),_meta:d.record(d.string(),d.unknown()).optional()}),na=d.object({type:d.literal("resource"),resource:d.union([Qn,eo]),annotations:mt.optional(),_meta:d.record(d.string(),d.unknown()).optional()}),oa=to.extend({type:d.literal("resource_link")}),qr=d.union([Or,Mr,Nr,oa,na]),sa=d.object({role:Mt,content:qr}),aa=Pe.extend({description:d.string().optional(),messages:d.array(sa)}),ia=qe.extend({method:d.literal("notifications/prompts/list_changed"),params:Ne.optional()}),ca=d.object({title:d.string().optional(),readOnlyHint:d.boolean().optional(),destructiveHint:d.boolean().optional(),idempotentHint:d.boolean().optional(),openWorldHint:d.boolean().optional()}),la=d.object({taskSupport:d.enum(["required","optional","forbidden"]).optional()}),no=d.object({...pt.shape,...It.shape,description:d.string().optional(),inputSchema:d.object({type:d.literal("object"),properties:d.record(d.string(),Pt).optional(),required:d.array(d.string()).optional()}).catchall(d.unknown()),outputSchema:d.looseObject({$schema:d.string().optional()}).optional(),annotations:ca.optional(),execution:la.optional(),_meta:d.record(d.string(),d.unknown()).optional()}),ua=At.extend({method:d.literal("tools/list")}),da=Ot.extend({tools:d.array(no)}),oo=Pe.extend({content:d.array(qr).default([]),structuredContent:d.unknown().optional(),isError:d.boolean().optional()}),gc=oo.or(Pe.extend({toolResult:d.unknown()})),pa=ar.extend({name:d.string(),arguments:d.record(d.string(),d.unknown()).optional()}),ma=ze.extend({method:d.literal("tools/call"),params:pa}),ha=qe.extend({method:d.literal("notifications/tools/list_changed"),params:Ne.optional()}),yc=d.object({autoRefresh:d.boolean().default(!0),debounceMs:d.number().int().nonnegative().default(300)}),Nt=d.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),fa=ke.extend({level:Nt}),ga=ze.extend({method:d.literal("logging/setLevel"),params:fa}),ya=Ne.extend({level:Nt,logger:d.string().optional(),data:d.unknown()}),Sa=qe.extend({method:d.literal("notifications/message"),params:ya}),va=d.object({name:d.string().optional()}),_a=d.object({hints:d.array(va).optional(),costPriority:d.number().min(0).max(1).optional(),speedPriority:d.number().min(0).max(1).optional(),intelligencePriority:d.number().min(0).max(1).optional()}),ba=d.object({mode:d.enum(["auto","required","none"]).optional()}),Ra=d.object({type:d.literal("tool_result"),toolUseId:d.string().describe("The unique identifier for the corresponding tool call."),content:d.array(qr),structuredContent:d.unknown().optional(),isError:d.boolean().optional(),_meta:d.record(d.string(),d.unknown()).optional()}),wa=d.discriminatedUnion("type",[Or,Mr,Nr]),tr=d.discriminatedUnion("type",[Or,Mr,Nr,ra,Ra]),Ea=d.object({role:Mt,content:d.union([tr,d.array(tr)]),_meta:d.record(d.string(),d.unknown()).optional()}),Ta=ar.extend({messages:d.array(Ea),modelPreferences:_a.optional(),systemPrompt:d.string().optional(),includeContext:d.enum(["none","thisServer","allServers"]).optional(),temperature:d.number().optional(),maxTokens:d.number().int(),stopSequences:d.array(d.string()).optional(),metadata:$e.optional(),tools:d.array(no).optional(),toolChoice:ba.optional()}),$a=ze.extend({method:d.literal("sampling/createMessage"),params:Ta}),za=Pe.extend({model:d.string(),stopReason:d.optional(d.enum(["endTurn","stopSequence","maxTokens"]).or(d.string())),role:Mt,content:wa}),Pa=Pe.extend({model:d.string(),stopReason:d.optional(d.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(d.string())),role:Mt,content:d.union([tr,d.array(tr)])}),so=d.object({type:d.literal("boolean"),title:d.string().optional(),description:d.string().optional(),default:d.boolean().optional()}),jr=d.object({type:d.literal("string"),title:d.string().optional(),description:d.string().optional(),minLength:d.number().optional(),maxLength:d.number().optional(),format:d.enum(["email","uri","date","date-time"]).optional(),default:d.string().optional()}),Lr=d.object({type:d.enum(["number","integer"]),title:d.string().optional(),description:d.string().optional(),minimum:d.number().optional(),maximum:d.number().optional(),default:d.number().optional()}),ao=d.object({type:d.literal("string"),title:d.string().optional(),description:d.string().optional(),enum:d.array(d.string()),default:d.string().optional()}),io=d.object({type:d.literal("string"),title:d.string().optional(),description:d.string().optional(),oneOf:d.array(d.object({const:d.string(),title:d.string()})),default:d.string().optional()}),co=d.object({type:d.literal("string"),title:d.string().optional(),description:d.string().optional(),enum:d.array(d.string()),enumNames:d.array(d.string()).optional(),default:d.string().optional()}),Ca=d.union([ao,io]),lo=d.object({type:d.literal("array"),title:d.string().optional(),description:d.string().optional(),minItems:d.number().optional(),maxItems:d.number().optional(),items:d.object({type:d.literal("string"),enum:d.array(d.string())}),default:d.array(d.string()).optional()}),uo=d.object({type:d.literal("array"),title:d.string().optional(),description:d.string().optional(),minItems:d.number().optional(),maxItems:d.number().optional(),items:d.object({anyOf:d.array(d.object({const:d.string(),title:d.string()}))}),default:d.array(d.string()).optional()}),ka=d.union([lo,uo]),Ia=d.union([co,Ca,ka]),po=d.union([Ia,so,jr,Lr]),Dr=ar.extend({mode:d.literal("form").optional(),message:d.string(),requestedSchema:d.object({type:d.literal("object"),properties:d.record(d.string(),po),required:d.array(d.string()).optional()}).catchall(d.unknown())}),Aa=ar.extend({mode:d.literal("url"),message:d.string(),elicitationId:d.string(),url:d.string().url()}),Oa=d.union([Dr,Aa]),Ma=ze.extend({method:d.literal("elicitation/create"),params:Oa}),Na=Ne.extend({elicitationId:d.string()}),qa=qe.extend({method:d.literal("notifications/elicitation/complete"),params:Na}),ja=Pe.extend({action:d.enum(["accept","decline","cancel"]),content:d.preprocess(e=>e===null?void 0:e,d.record(d.string(),d.union([d.string(),d.number(),d.boolean(),d.array(d.string())])).optional())}),La=d.object({type:d.literal("ref/resource"),uri:d.string()}),Da=d.object({type:d.literal("ref/prompt"),name:d.string()}),xa=ke.extend({ref:d.union([Da,La]),argument:d.object({name:d.string(),value:d.string()}),context:d.object({arguments:d.record(d.string(),d.string()).optional()}).optional()}),Ha=ze.extend({method:d.literal("completion/complete"),params:xa}),Ua=Pe.extend({completion:d.looseObject({values:d.array(d.string()).max(100),total:d.optional(d.number().int()),hasMore:d.optional(d.boolean())})}),Va=d.object({uri:d.string().startsWith("file://"),name:d.string().optional(),_meta:d.record(d.string(),d.unknown()).optional()}),Ba=ze.extend({method:d.literal("roots/list"),params:ke.optional()}),Fa=Pe.extend({roots:d.array(Va)}),Ga=qe.extend({method:d.literal("notifications/roots/list_changed"),params:Ne.optional()}),Sc=d.looseObject({ttl:d.number().optional(),pollInterval:d.number().optional()}),Ja=d.enum(["working","input_required","completed","failed","cancelled"]),qt=d.object({taskId:d.string(),status:Ja,ttl:d.union([d.number(),d.null()]),createdAt:d.string(),lastUpdatedAt:d.string(),pollInterval:d.optional(d.number()),statusMessage:d.optional(d.string())}),vc=Pe.extend({task:qt}),Ka=Ne.merge(qt),_c=qe.extend({method:d.literal("notifications/tasks/status"),params:Ka}),bc=ze.extend({method:d.literal("tasks/get"),params:ke.extend({taskId:d.string()})}),Rc=Pe.merge(qt),wc=ze.extend({method:d.literal("tasks/result"),params:ke.extend({taskId:d.string()})}),Ec=Pe.loose(),Tc=At.extend({method:d.literal("tasks/list")}),$c=Ot.extend({tasks:d.array(qt)}),zc=ze.extend({method:d.literal("tasks/cancel"),params:ke.extend({taskId:d.string()})}),Pc=Pe.merge(qt),Cc=d.union([Yn,Kn,Es,Ha,ga,ta,Zs,ks,As,Ns,Ds,Hs,Vs,ma,ua]),kc=d.union([Jn,Xn,ws,Ga]),Ic=d.union([Gn,za,Pa,ja,Fa]),Ac=d.union([Yn,$a,Ma,Ba]),Oc=d.union([Jn,Xn,Sa,Ws,js,ha,ia,Fs,qa]),Mc=d.union([Gn,Rs,Ts,Ua,aa,Qs,Is,Os,qs,oo,da,Js]);import*as N from"zod/v4";var Ie=N.url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:N.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),N.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"}),qc=N.looseObject({resource:N.string().url(),authorization_servers:N.array(Ie).optional(),jwks_uri:N.string().url().optional(),scopes_supported:N.array(N.string()).optional(),bearer_methods_supported:N.array(N.string()).optional(),resource_signing_alg_values_supported:N.array(N.string()).optional(),resource_name:N.string().optional(),resource_documentation:N.string().optional(),resource_policy_uri:N.string().url().optional(),resource_tos_uri:N.string().url().optional(),tls_client_certificate_bound_access_tokens:N.boolean().optional(),authorization_details_types_supported:N.array(N.string()).optional(),dpop_signing_alg_values_supported:N.array(N.string()).optional(),dpop_bound_access_tokens_required:N.boolean().optional()}),Wa=N.looseObject({issuer:N.string(),authorization_endpoint:Ie,token_endpoint:Ie,registration_endpoint:Ie.optional(),scopes_supported:N.array(N.string()).optional(),response_types_supported:N.array(N.string()),response_modes_supported:N.array(N.string()).optional(),grant_types_supported:N.array(N.string()).optional(),token_endpoint_auth_methods_supported:N.array(N.string()).optional(),token_endpoint_auth_signing_alg_values_supported:N.array(N.string()).optional(),service_documentation:Ie.optional(),revocation_endpoint:Ie.optional(),revocation_endpoint_auth_methods_supported:N.array(N.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:N.array(N.string()).optional(),introspection_endpoint:N.string().optional(),introspection_endpoint_auth_methods_supported:N.array(N.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:N.array(N.string()).optional(),code_challenge_methods_supported:N.array(N.string()).optional(),client_id_metadata_document_supported:N.boolean().optional(),authorization_response_iss_parameter_supported:N.boolean().optional().catch(void 0),dpop_signing_alg_values_supported:N.array(N.string()).optional()}),Ya=N.looseObject({issuer:N.string(),authorization_endpoint:Ie,token_endpoint:Ie,userinfo_endpoint:Ie.optional(),jwks_uri:Ie,registration_endpoint:Ie.optional(),scopes_supported:N.array(N.string()).optional(),response_types_supported:N.array(N.string()),response_modes_supported:N.array(N.string()).optional(),grant_types_supported:N.array(N.string()).optional(),acr_values_supported:N.array(N.string()).optional(),subject_types_supported:N.array(N.string()),id_token_signing_alg_values_supported:N.array(N.string()),id_token_encryption_alg_values_supported:N.array(N.string()).optional(),id_token_encryption_enc_values_supported:N.array(N.string()).optional(),userinfo_signing_alg_values_supported:N.array(N.string()).optional(),userinfo_encryption_alg_values_supported:N.array(N.string()).optional(),userinfo_encryption_enc_values_supported:N.array(N.string()).optional(),request_object_signing_alg_values_supported:N.array(N.string()).optional(),request_object_encryption_alg_values_supported:N.array(N.string()).optional(),request_object_encryption_enc_values_supported:N.array(N.string()).optional(),token_endpoint_auth_methods_supported:N.array(N.string()).optional(),token_endpoint_auth_signing_alg_values_supported:N.array(N.string()).optional(),display_values_supported:N.array(N.string()).optional(),claim_types_supported:N.array(N.string()).optional(),claims_supported:N.array(N.string()).optional(),service_documentation:N.string().optional(),claims_locales_supported:N.array(N.string()).optional(),ui_locales_supported:N.array(N.string()).optional(),claims_parameter_supported:N.boolean().optional(),request_parameter_supported:N.boolean().optional(),request_uri_parameter_supported:N.boolean().optional(),require_request_uri_registration:N.boolean().optional(),op_policy_uri:Ie.optional(),op_tos_uri:Ie.optional(),client_id_metadata_document_supported:N.boolean().optional(),authorization_response_iss_parameter_supported:N.boolean().optional().catch(void 0)}),jc=N.object({...Ya.shape,...Wa.pick({code_challenge_methods_supported:!0}).shape}),Lc=N.object({access_token:N.string(),id_token:N.string().optional(),token_type:N.string(),expires_in:N.coerce.number().optional(),scope:N.string().optional(),refresh_token:N.string().optional(),issuer:N.string().optional().catch(void 0)}).strip(),Dc=N.object({issued_token_type:N.literal("urn:ietf:params:oauth:token-type:id-jag"),access_token:N.string(),token_type:N.string().optional(),expires_in:N.number().optional(),scope:N.string().optional()}).strip(),xc=N.object({error:N.string(),error_description:N.string().optional(),error_uri:N.string().optional()}),Nc=Ie.optional().or(N.literal("").transform(()=>{})),Xa=N.object({redirect_uris:N.array(Ie),token_endpoint_auth_method:N.string().optional(),grant_types:N.array(N.string()).optional(),response_types:N.array(N.string()).optional(),application_type:N.string().optional(),client_name:N.string().optional(),client_uri:Ie.optional(),logo_uri:Nc,scope:N.string().optional(),contacts:N.array(N.string()).optional(),tos_uri:Nc,policy_uri:N.string().optional(),jwks_uri:Ie.optional(),jwks:N.any().optional(),software_id:N.string().optional(),software_version:N.string().optional(),software_statement:N.string().optional()}).strip(),Za=N.object({client_id:N.string(),client_secret:N.string().optional(),client_id_issued_at:N.number().optional(),client_secret_expires_at:N.number().optional(),issuer:N.string().optional().catch(void 0)}).strip(),Hc=Xa.merge(Za),Uc=N.object({error:N.string(),error_description:N.string().optional()}).strip(),Vc=N.object({token:N.string(),token_type_hint:N.string().optional()}).strip();import*as s from"zod/v4";var Kc=Symbol.for("mcp.sdk.errorBrands");function Zc(e,t){let r=new Set,n=t;for(;typeof n=="function";){let o=n.mcpBrand;Object.prototype.hasOwnProperty.call(n,"mcpBrand")&&typeof o=="string"&&r.add(o),n=Object.getPrototypeOf(n)}r.size!==0&&Object.defineProperty(e,Kc,{value:r,enumerable:!1,configurable:!0})}function Vr(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,Kc)){let r=t[Kc];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var cr=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.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e}({}),vo=class yp extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Vr(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Vr(this,t)}constructor(t,r,n){super(r),this.code=t,this.errorUri=n,this.name="OAuthError",Zc(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new yp(t.error,t.error_description??t.error,t.error_uri)}},pe=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.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_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}({}),le=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Vr(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Vr(this,e)}constructor(e,t,r,n){super(t,n),this.code=e,this.data=r,this.name="SdkError",Zc(this,new.target)}},Gg=class extends le{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,n){super(e,t,r,n),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};var rp={};function Sp(e){return Object.hasOwn(rp,e)?rp[e]:void 0}function np(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Jg(e,t,r){return e==="elicitation"&&t==="form"&&r.form===void 0&&r.url===void 0}function vp(e){switch(e.method){case"elicitation/create":return e.params?.mode==="url"?{elicitation:{url:{}}}:{elicitation:{form:{}}};case"sampling/createMessage":{let t=e.params;return t!==void 0&&(t.tools!==void 0||t.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case"roots/list":return{roots:{}};default:return}}function _o(e,t){let r={};for(let[n,o]of Object.entries(e)){if(o===void 0)continue;let a=t===void 0?void 0:t[n];if(a===void 0){r[n]=o;continue}if(np(o)&&np(a)){let i={};for(let[l,c]of Object.entries(o))c!==void 0&&a[l]===void 0&&!Jg(n,l,a)&&(i[l]=c);Object.keys(i).length>0&&(r[n]=i)}}return Object.keys(r).length>0?r:void 0}var _p="2026-07-28",lr=[_p];function ft(e){return e>=_p}function bp(e){return e.filter(t=>!ft(t))}function si(e){return e.filter(t=>ft(t))}function Rp(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(r=>r.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}var wp=["task","inputRequests","requestState"];function Qc(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||wp.some(t=>t in e)?e:{...e,content:[]}}function Kg(){let e=s.lazy(()=>s.union([s.string(),s.number(),s.boolean(),s.null(),s.record(s.string(),e),s.array(e)])),t=s.record(s.string(),e),r=s.union([s.string(),s.number().int()]),n=s.string(),o=s.object({ttl:s.number().optional()}),a=s.object({taskId:s.string()}),i=s.looseObject({progressToken:r.optional(),"io.modelcontextprotocol/related-task":a.optional()}),l=s.object({_meta:i.optional()}),c=l.extend({task:o.optional()}),u=s.object({method:s.string(),params:l.loose().optional()}),m=s.object({_meta:i.optional()}),f=s.object({method:s.string(),params:m.loose().optional()}),y=s.looseObject({_meta:i.optional()}),R=s.union([s.string(),s.number().int()]),S=y.strict(),P=m.extend({requestId:R.optional(),reason:s.string().optional()}),b=f.extend({method:s.literal("notifications/cancelled"),params:P}),h=s.object({src:s.string(),mimeType:s.string().optional(),sizes:s.array(s.string()).optional(),theme:s.enum(["light","dark"]).optional()}),$=s.object({icons:s.array(h).optional()}),v=s.object({name:s.string(),title:s.string().optional()}),z=v.extend({...v.shape,...$.shape,version:s.string(),websiteUrl:s.string().optional(),description:s.string().optional()}),I=s.intersection(s.object({applyDefaults:s.boolean().optional()}),t),T=s.preprocess(Oe=>Oe&&typeof Oe=="object"&&!Array.isArray(Oe)&&Object.keys(Oe).length===0?{form:{}}:Oe,s.intersection(s.object({form:I.optional(),url:t.optional()}),t.optional())),_=s.looseObject({list:t.optional(),cancel:t.optional(),requests:s.looseObject({sampling:s.looseObject({createMessage:t.optional()}).optional(),elicitation:s.looseObject({create:t.optional()}).optional()}).optional()}),C=s.looseObject({list:t.optional(),cancel:t.optional(),requests:s.looseObject({tools:s.looseObject({call:t.optional()}).optional()}).optional()}),M=s.object({experimental:s.record(s.string(),t).optional(),sampling:s.object({context:t.optional(),tools:t.optional()}).optional(),elicitation:T.optional(),roots:s.object({listChanged:s.boolean().optional()}).optional(),tasks:_.optional(),extensions:s.record(s.string(),t).optional()}),U=l.extend({protocolVersion:s.string(),capabilities:M,clientInfo:z}),q=u.extend({method:s.literal("initialize"),params:U}),D=s.object({experimental:s.record(s.string(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:s.object({listChanged:s.boolean().optional()}).optional(),resources:s.object({subscribe:s.boolean().optional(),listChanged:s.boolean().optional()}).optional(),tools:s.object({listChanged:s.boolean().optional()}).optional(),tasks:C.optional(),extensions:s.record(s.string(),t).optional()}),W=y.extend({protocolVersion:s.string(),capabilities:D,serverInfo:z,instructions:s.string().optional()}),F=f.extend({method:s.literal("notifications/initialized"),params:m.optional()}),ie=u.extend({method:s.literal("ping"),params:l.optional()}),he=s.object({progress:s.number(),total:s.optional(s.number()),message:s.optional(s.string())}),ge=s.object({...m.shape,...he.shape,progressToken:r}),_e=f.extend({method:s.literal("notifications/progress"),params:ge}),ue=l.extend({cursor:n.optional()}),O=u.extend({params:ue.optional()}),j=y.extend({nextCursor:n.optional()}),E=s.object({uri:s.string(),mimeType:s.optional(s.string()),_meta:s.record(s.string(),s.unknown()).optional()}),p=E.extend({text:s.string()}),g=s.string().refine(Oe=>{try{return atob(Oe),!0}catch{return!1}},{message:"Invalid Base64 string"}),w=E.extend({blob:g}),A=s.enum(["user","assistant"]),x=s.object({audience:s.array(A).optional(),priority:s.number().min(0).max(1).optional(),lastModified:s.iso.datetime({offset:!0}).optional()}),J=s.object({...v.shape,...$.shape,uri:s.string(),description:s.optional(s.string()),mimeType:s.optional(s.string()),size:s.optional(s.number()),annotations:x.optional(),_meta:s.optional(s.looseObject({}))}),K=s.object({...v.shape,...$.shape,uriTemplate:s.string(),description:s.optional(s.string()),mimeType:s.optional(s.string()),annotations:x.optional(),_meta:s.optional(s.looseObject({}))}),ce=O.extend({method:s.literal("resources/list")}),fe=j.extend({resources:s.array(J)}),k=O.extend({method:s.literal("resources/templates/list")}),L=j.extend({resourceTemplates:s.array(K)}),H=l.extend({uri:s.string()}),Q=H,re=u.extend({method:s.literal("resources/read"),params:Q}),ne=y.extend({contents:s.array(s.union([p,w]))}),me=f.extend({method:s.literal("notifications/resources/list_changed"),params:m.optional()}),Re=H,B=u.extend({method:s.literal("resources/subscribe"),params:Re}),be=H,X=u.extend({method:s.literal("resources/unsubscribe"),params:be}),ee=m.extend({uri:s.string()}),oe=f.extend({method:s.literal("notifications/resources/updated"),params:ee}),Z=s.object({name:s.string(),description:s.optional(s.string()),required:s.optional(s.boolean())}),Y=s.object({...v.shape,...$.shape,description:s.optional(s.string()),arguments:s.optional(s.array(Z)),_meta:s.optional(s.looseObject({}))}),se=O.extend({method:s.literal("prompts/list")}),ae=j.extend({prompts:s.array(Y)}),we=l.extend({name:s.string(),arguments:s.record(s.string(),s.string()).optional()}),dt=u.extend({method:s.literal("prompts/get"),params:we}),tt=s.object({type:s.literal("text"),text:s.string(),annotations:x.optional(),_meta:s.record(s.string(),s.unknown()).optional()}),xt=s.object({type:s.literal("image"),data:g,mimeType:s.string(),annotations:x.optional(),_meta:s.record(s.string(),s.unknown()).optional()}),Ht=s.object({type:s.literal("audio"),data:g,mimeType:s.string(),annotations:x.optional(),_meta:s.record(s.string(),s.unknown()).optional()}),Qr=s.object({type:s.literal("tool_use"),name:s.string(),id:s.string(),input:s.record(s.string(),s.unknown()),_meta:s.record(s.string(),s.unknown()).optional()}),Rt=s.object({type:s.literal("resource"),resource:s.union([p,w]),annotations:x.optional(),_meta:s.record(s.string(),s.unknown()).optional()}),en=J.extend({type:s.literal("resource_link")}),Be=s.union([tt,xt,Ht,en,Rt]),pr=s.object({role:A,content:Be}),mr=y.extend({description:s.string().optional(),messages:s.array(pr)}),Ut=f.extend({method:s.literal("notifications/prompts/list_changed"),params:m.optional()}),tn=s.object({title:s.string().optional(),readOnlyHint:s.boolean().optional(),destructiveHint:s.boolean().optional(),idempotentHint:s.boolean().optional(),openWorldHint:s.boolean().optional()}),hr=s.object({taskSupport:s.enum(["required","optional","forbidden"]).optional()}),Vt=s.object({...v.shape,...$.shape,description:s.string().optional(),inputSchema:s.object({type:s.literal("object"),properties:s.record(s.string(),e).optional(),required:s.array(s.string()).optional()}).catchall(s.unknown()),outputSchema:s.object({type:s.literal("object"),properties:s.record(s.string(),e).optional(),required:s.array(s.string()).optional()}).catchall(s.unknown()).optional(),annotations:tn.optional(),execution:hr.optional(),_meta:s.record(s.string(),s.unknown()).optional()}),fr=O.extend({method:s.literal("tools/list")}),gr=j.extend({tools:s.array(Vt)}),yr=y.extend({content:s.array(Be),structuredContent:s.record(s.string(),s.unknown()).optional(),isError:s.boolean().optional()}),Ae=c.extend({name:s.string(),arguments:s.record(s.string(),s.unknown()).optional()}),rn=u.extend({method:s.literal("tools/call"),params:Ae}),Ao=f.extend({method:s.literal("notifications/tools/list_changed"),params:m.optional()}),Sr=s.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),nn=l.extend({level:Sr}),on=u.extend({method:s.literal("logging/setLevel"),params:nn}),sn=m.extend({level:Sr,logger:s.string().optional(),data:s.unknown()}),an=f.extend({method:s.literal("notifications/message"),params:sn}),cn=s.object({name:s.string().optional()}),ln=s.object({hints:s.array(cn).optional(),costPriority:s.number().min(0).max(1).optional(),speedPriority:s.number().min(0).max(1).optional(),intelligencePriority:s.number().min(0).max(1).optional()}),un=s.object({mode:s.enum(["auto","required","none"]).optional()}),Oo=s.object({type:s.literal("tool_result"),toolUseId:s.string().describe("The unique identifier for the corresponding tool call."),content:s.array(Be),structuredContent:s.object({}).loose().optional(),isError:s.boolean().optional(),_meta:s.record(s.string(),s.unknown()).optional()}),dn=s.discriminatedUnion("type",[tt,xt,Ht]),wt=s.discriminatedUnion("type",[tt,xt,Ht,Qr,Oo]),pn=s.object({role:A,content:s.union([wt,s.array(wt)]),_meta:s.record(s.string(),s.unknown()).optional()}),mn=c.extend({messages:s.array(pn),modelPreferences:ln.optional(),systemPrompt:s.string().optional(),includeContext:s.enum(["none","thisServer","allServers"]).optional(),temperature:s.number().optional(),maxTokens:s.number().int(),stopSequences:s.array(s.string()).optional(),metadata:t.optional(),tools:s.array(Vt).optional(),toolChoice:un.optional()}),hn=u.extend({method:s.literal("sampling/createMessage"),params:mn}),fn=y.extend({model:s.string(),stopReason:s.optional(s.enum(["endTurn","stopSequence","maxTokens"]).or(s.string())),role:A,content:dn}),gn=y.extend({model:s.string(),stopReason:s.optional(s.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(s.string())),role:A,content:s.union([wt,s.array(wt)])}),yn=s.object({type:s.literal("boolean"),title:s.string().optional(),description:s.string().optional(),default:s.boolean().optional()}),Sn=s.object({type:s.literal("string"),title:s.string().optional(),description:s.string().optional(),minLength:s.number().optional(),maxLength:s.number().optional(),format:s.enum(["email","uri","date","date-time"]).optional(),default:s.string().optional()}),vn=s.object({type:s.enum(["number","integer"]),title:s.string().optional(),description:s.string().optional(),minimum:s.number().optional(),maximum:s.number().optional(),default:s.number().optional()}),_n=s.object({type:s.literal("string"),title:s.string().optional(),description:s.string().optional(),enum:s.array(s.string()),default:s.string().optional()}),bn=s.object({type:s.literal("string"),title:s.string().optional(),description:s.string().optional(),oneOf:s.array(s.object({const:s.string(),title:s.string()})),default:s.string().optional()}),Rn=s.object({type:s.literal("string"),title:s.string().optional(),description:s.string().optional(),enum:s.array(s.string()),enumNames:s.array(s.string()).optional(),default:s.string().optional()}),wn=s.union([_n,bn]),Bt=s.object({type:s.literal("array"),title:s.string().optional(),description:s.string().optional(),minItems:s.number().optional(),maxItems:s.number().optional(),items:s.object({type:s.literal("string"),enum:s.array(s.string())}),default:s.array(s.string()).optional()}),Ft=s.object({type:s.literal("array"),title:s.string().optional(),description:s.string().optional(),minItems:s.number().optional(),maxItems:s.number().optional(),items:s.object({anyOf:s.array(s.object({const:s.string(),title:s.string()}))}),default:s.array(s.string()).optional()}),Mo=s.union([Bt,Ft]),No=s.union([Rn,wn,Mo]),He=s.union([No,yn,Sn,vn]),Ue=c.extend({mode:s.literal("form").optional(),message:s.string(),requestedSchema:s.object({type:s.literal("object"),properties:s.record(s.string(),He),required:s.array(s.string()).optional()}).catchall(s.unknown())}),En=c.extend({mode:s.literal("url"),message:s.string(),elicitationId:s.string(),url:s.string().url()}),Ke=s.union([Ue,En]),qo=u.extend({method:s.literal("elicitation/create"),params:Ke}),jo=m.extend({elicitationId:s.string()}),Lo=f.extend({method:s.literal("notifications/elicitation/complete"),params:jo}),Do=y.extend({action:s.enum(["accept","decline","cancel"]),content:s.preprocess(Oe=>Oe===null?void 0:Oe,s.record(s.string(),s.union([s.string(),s.number(),s.boolean(),s.array(s.string())])).optional())}),xo=s.object({type:s.literal("ref/resource"),uri:s.string()}),Ho=s.object({type:s.literal("ref/prompt"),name:s.string()}),Uo=l.extend({ref:s.union([Ho,xo]),argument:s.object({name:s.string(),value:s.string()}),context:s.object({arguments:s.record(s.string(),s.string()).optional()}).optional()}),Tn=u.extend({method:s.literal("completion/complete"),params:Uo}),Vo=y.extend({completion:s.looseObject({values:s.array(s.string()).max(100),total:s.optional(s.number().int()),hasMore:s.optional(s.boolean())})}),Bo=s.object({uri:s.string().startsWith("file://"),name:s.string().optional(),_meta:s.record(s.string(),s.unknown()).optional()}),vr=u.extend({method:s.literal("roots/list"),params:l.optional()}),$n=y.extend({roots:s.array(Bo)}),Fo=f.extend({method:s.literal("notifications/roots/list_changed"),params:m.optional()}),Go=s.looseObject({ttl:s.number().optional(),pollInterval:s.number().optional()}),zn=s.enum(["working","input_required","completed","failed","cancelled"]),Et=s.object({taskId:s.string(),status:zn,ttl:s.union([s.number(),s.null()]),createdAt:s.string(),lastUpdatedAt:s.string(),pollInterval:s.optional(s.number()),statusMessage:s.optional(s.string())}),Le=y.extend({task:Et}),Jo=m.merge(Et),Gt=f.extend({method:s.literal("notifications/tasks/status"),params:Jo}),_r=u.extend({method:s.literal("tasks/get"),params:l.extend({taskId:s.string()})}),br=y.merge(Et),Rr=u.extend({method:s.literal("tasks/result"),params:l.extend({taskId:s.string()})}),Ai=y.loose(),je=O.extend({method:s.literal("tasks/list")}),Ce=j.extend({tasks:s.array(Et)}),Jt=u.extend({method:s.literal("tasks/cancel"),params:l.extend({taskId:s.string()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,TaskMetadataSchema:o,RelatedTaskMetadataSchema:a,RequestMetaSchema:i,BaseRequestParamsSchema:l,TaskAugmentedRequestParamsSchema:c,RequestSchema:u,NotificationsParamsSchema:m,NotificationSchema:f,ResultSchema:y,RequestIdSchema:R,EmptyResultSchema:S,CancelledNotificationParamsSchema:P,CancelledNotificationSchema:b,IconSchema:h,IconsSchema:$,BaseMetadataSchema:v,ImplementationSchema:z,ClientTasksCapabilitySchema:_,ServerTasksCapabilitySchema:C,ClientCapabilitiesSchema:M,InitializeRequestParamsSchema:U,InitializeRequestSchema:q,ServerCapabilitiesSchema:D,InitializeResultSchema:W,InitializedNotificationSchema:F,PingRequestSchema:ie,ProgressSchema:he,ProgressNotificationParamsSchema:ge,ProgressNotificationSchema:_e,PaginatedRequestParamsSchema:ue,PaginatedRequestSchema:O,PaginatedResultSchema:j,ResourceContentsSchema:E,TextResourceContentsSchema:p,BlobResourceContentsSchema:w,RoleSchema:A,AnnotationsSchema:x,ResourceSchema:J,ResourceTemplateSchema:K,ListResourcesRequestSchema:ce,ListResourcesResultSchema:fe,ListResourceTemplatesRequestSchema:k,ListResourceTemplatesResultSchema:L,ResourceRequestParamsSchema:H,ReadResourceRequestParamsSchema:Q,ReadResourceRequestSchema:re,ReadResourceResultSchema:ne,ResourceListChangedNotificationSchema:me,SubscribeRequestParamsSchema:Re,SubscribeRequestSchema:B,UnsubscribeRequestParamsSchema:be,UnsubscribeRequestSchema:X,ResourceUpdatedNotificationParamsSchema:ee,ResourceUpdatedNotificationSchema:oe,PromptArgumentSchema:Z,PromptSchema:Y,ListPromptsRequestSchema:se,ListPromptsResultSchema:ae,GetPromptRequestParamsSchema:we,GetPromptRequestSchema:dt,TextContentSchema:tt,ImageContentSchema:xt,AudioContentSchema:Ht,ToolUseContentSchema:Qr,EmbeddedResourceSchema:Rt,ResourceLinkSchema:en,ContentBlockSchema:Be,PromptMessageSchema:pr,GetPromptResultSchema:mr,PromptListChangedNotificationSchema:Ut,ToolAnnotationsSchema:tn,ToolExecutionSchema:hr,ToolSchema:Vt,ListToolsRequestSchema:fr,ListToolsResultSchema:gr,CallToolResultSchema:yr,CallToolRequestParamsSchema:Ae,CallToolRequestSchema:rn,ToolListChangedNotificationSchema:Ao,LoggingLevelSchema:Sr,SetLevelRequestParamsSchema:nn,SetLevelRequestSchema:on,LoggingMessageNotificationParamsSchema:sn,LoggingMessageNotificationSchema:an,ModelHintSchema:cn,ModelPreferencesSchema:ln,ToolChoiceSchema:un,ToolResultContentSchema:Oo,SamplingContentSchema:dn,SamplingMessageContentBlockSchema:wt,SamplingMessageSchema:pn,CreateMessageRequestParamsSchema:mn,CreateMessageRequestSchema:hn,CreateMessageResultSchema:fn,CreateMessageResultWithToolsSchema:gn,BooleanSchemaSchema:yn,StringSchemaSchema:Sn,NumberSchemaSchema:vn,UntitledSingleSelectEnumSchemaSchema:_n,TitledSingleSelectEnumSchemaSchema:bn,LegacyTitledEnumSchemaSchema:Rn,SingleSelectEnumSchemaSchema:wn,UntitledMultiSelectEnumSchemaSchema:Bt,TitledMultiSelectEnumSchemaSchema:Ft,MultiSelectEnumSchemaSchema:Mo,EnumSchemaSchema:No,PrimitiveSchemaDefinitionSchema:He,ElicitRequestFormParamsSchema:Ue,ElicitRequestURLParamsSchema:En,ElicitRequestParamsSchema:Ke,ElicitRequestSchema:qo,ElicitationCompleteNotificationParamsSchema:jo,ElicitationCompleteNotificationSchema:Lo,ElicitResultSchema:Do,ResourceTemplateReferenceSchema:xo,PromptReferenceSchema:Ho,CompleteRequestParamsSchema:Uo,CompleteRequestSchema:Tn,CompleteResultSchema:Vo,RootSchema:Bo,ListRootsRequestSchema:vr,ListRootsResultSchema:$n,RootsListChangedNotificationSchema:Fo,TaskCreationParamsSchema:Go,TaskStatusSchema:zn,TaskSchema:Et,CreateTaskResultSchema:Le,TaskStatusNotificationParamsSchema:Jo,TaskStatusNotificationSchema:Gt,GetTaskRequestSchema:_r,GetTaskResultSchema:br,GetTaskPayloadRequestSchema:Rr,GetTaskPayloadResultSchema:Ai,ListTasksRequestSchema:je,ListTasksResultSchema:Ce,CancelTaskRequestSchema:Jt,CancelTaskResultSchema:y.merge(Et),ClientRequestSchema:s.union([ie,q,Tn,on,dt,se,ce,k,re,B,X,rn,fr,_r,Rr,je,Jt]),ClientNotificationSchema:s.union([b,_e,F,Fo,Gt]),ClientResultSchema:s.union([S,fn,gn,Do,$n,br,Ce,Le]),ServerRequestSchema:s.union([ie,hn,qo,vr,_r,Rr,je,Jt]),ServerNotificationSchema:s.union([b,_e,an,oe,me,Ao,Ut,Gt,Lo]),ServerResultSchema:s.union([S,W,Vo,mr,ae,fe,L,ne,yr,gr,br,Ce,Le]),CallToolResultWireSchema:s.unknown().superRefine((Oe,tf)=>{if(!(typeof Oe!="object"||Oe===null||Array.isArray(Oe)||Oe.content!==void 0)){for(let cu of wp)if(cu in Oe){tf.addIssue({code:"custom",message:`content is required when the body carries '${cu}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(Qc).pipe(yr)}}var Wg;function Ep(){return Wg??=Kg()}function Tp(e){return e.type!=="object"}var Yg=new Set(["const","enum","default","examples"]),Xg=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function op(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}function Zg(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(op(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=Md(e.$schema)&&e.$recursiveAnchor!==!0,n=(o,a)=>{if(Array.isArray(o))return o.map(c=>n(c,!1));if(o===null||typeof o!="object"||!a&&op(o.$id))return o;let i={},l=!1;for(let[c,u]of Object.entries(o))a?i[c]=n(u,!1):(c==="$ref"||c==="$dynamicRef")&&typeof u=="string"?i[c]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u:c==="$recursiveRef"&&u==="#"&&r?l=!0:Yg.has(c)?i[c]=u:Xg.has(c)?i[c]=n(u,!0):i[c]=n(u,!1);return l&&("$ref"in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:"#/properties/result"}]:i.$ref="#/properties/result"),i};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:n(e,!1)},required:["result"]}}var $p={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},zp={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},Qg={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Qa;function el(){if(Qa)return Qa;let e=Ep();return Qa={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Qa}function Pp(e){return Object.prototype.hasOwnProperty.call($p,e)}function Cp(e){return Object.prototype.hasOwnProperty.call(zp,e)}function ey(e){return Object.prototype.hasOwnProperty.call(Qg,e)}function ty(e){return ey(e)?el().resultSchemas[e]:void 0}function ry(e){return Pp(e)?el().requestSchemas[e]:void 0}function ny(e){return Cp(e)?el().notificationSchemas[e]:void 0}var gw=Object.keys($p),yw=Object.keys(zp);function Wc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ei(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var sp={ok:!1,reason:"not-in-era"};function ap(e){return Wc(e)&&Wc(e.outputSchema)&&Tp(e.outputSchema)}var tl={era:"2025-11-25",hasRequestMethod:Pp,hasNotificationMethod:Cp,validateRequest:(e,t)=>ei(ry(e),t),validateResult:(e,t)=>ei(ty(e),t),validateNotification:(e,t)=>ei(ny(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>sp,validateInputResponse:()=>sp,samplingResultVariant:(e,t)=>{let r=Ep();return ei(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)},outboundEnvelope:e=>{},validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let r=Rp(e),n=r.structuredContent;if(n===void 0)return r;let o=typeof n!="object"||n===null||Array.isArray(n),a=t!==void 0&&Tp(t);return!o&&!a?r:{...r,structuredContent:{result:n}}},decodeResult(e,t){if(Wc(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:r}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;return!Array.isArray(r)||!r.some(n=>ap(n))?t:{...t,tools:r.map(n=>ap(n)?{...n,outputSchema:Zg(n.outputSchema)}:n)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>{}};function oy(){let e=s.lazy(()=>s.union([s.string(),s.number(),s.boolean(),s.null(),s.record(s.string(),e),s.array(e)])),t=s.record(s.string(),e),r=s.union([s.string(),s.number().int()]),n=s.string(),o=s.union([s.string(),s.number().int()]),a=s.enum(["user","assistant"]),i=s.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),l=s.string().refine(Ce=>{try{return atob(Ce),!0}catch{return!1}},{message:"Invalid Base64 string"}),c=s.object({ttl:s.number().optional()}),u=s.object({taskId:s.string()}),m=s.looseObject({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),f=s.object({_meta:m.optional()}),y=f.extend({task:c.optional()}),R=s.object({_meta:m.optional()}),S=s.object({method:s.string(),params:R.loose().optional()}),P=s.object({src:s.string(),mimeType:s.string().optional(),sizes:s.array(s.string()).optional(),theme:s.enum(["light","dark"]).optional()}),b=s.object({icons:s.array(P).optional()}),h=s.object({name:s.string(),title:s.string().optional()}),$=h.extend({...h.shape,...b.shape,version:s.string(),websiteUrl:s.string().optional(),description:s.string().optional()}),v=s.intersection(s.object({applyDefaults:s.boolean().optional()}),t),z=s.preprocess(Ce=>Ce&&typeof Ce=="object"&&!Array.isArray(Ce)&&Object.keys(Ce).length===0?{form:{}}:Ce,s.intersection(s.object({form:v.optional(),url:t.optional()}),t.optional())),I=s.looseObject({list:t.optional(),cancel:t.optional(),requests:s.looseObject({sampling:s.looseObject({createMessage:t.optional()}).optional(),elicitation:s.looseObject({create:t.optional()}).optional()}).optional()}),T=s.looseObject({list:t.optional(),cancel:t.optional(),requests:s.looseObject({tools:s.looseObject({call:t.optional()}).optional()}).optional()}),_=s.object({experimental:s.record(s.string(),t).optional(),sampling:s.object({context:t.optional(),tools:t.optional()}).optional(),elicitation:z.optional(),roots:s.object({listChanged:s.boolean().optional()}).optional(),tasks:I.optional(),extensions:s.record(s.string(),t).optional()}),C=s.object({experimental:s.record(s.string(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:s.object({listChanged:s.boolean().optional()}).optional(),resources:s.object({subscribe:s.boolean().optional(),listChanged:s.boolean().optional()}).optional(),tools:s.object({listChanged:s.boolean().optional()}).optional(),tasks:T.optional(),extensions:s.record(s.string(),t).optional()}),M=s.object({progress:s.number(),total:s.optional(s.number()),message:s.optional(s.string())}),U=s.object({...R.shape,...M.shape,progressToken:r}),q=S.extend({method:s.literal("notifications/progress"),params:U}),D=R.extend({level:i,logger:s.string().optional(),data:s.unknown()}),W=S.extend({method:s.literal("notifications/message"),params:D}),F=s.object({uri:s.string(),mimeType:s.optional(s.string()),_meta:s.record(s.string(),s.unknown()).optional()}),ie=F.extend({text:s.string()}),he=F.extend({blob:l}),ge=s.object({audience:s.array(a).optional(),priority:s.number().min(0).max(1).optional(),lastModified:s.iso.datetime({offset:!0}).optional()}),_e=s.object({...h.shape,...b.shape,uri:s.string(),description:s.optional(s.string()),mimeType:s.optional(s.string()),size:s.optional(s.number()),annotations:ge.optional(),_meta:s.optional(s.looseObject({}))}),ue=s.object({...h.shape,...b.shape,uriTemplate:s.string(),description:s.optional(s.string()),mimeType:s.optional(s.string()),annotations:ge.optional(),_meta:s.optional(s.looseObject({}))}),O=S.extend({method:s.literal("notifications/resources/list_changed"),params:R.optional()}),j=R.extend({uri:s.string()}),E=S.extend({method:s.literal("notifications/resources/updated"),params:j}),p=s.object({name:s.string(),description:s.optional(s.string()),required:s.optional(s.boolean())}),g=s.object({...h.shape,...b.shape,description:s.optional(s.string()),arguments:s.optional(s.array(p)),_meta:s.optional(s.looseObject({}))}),w=S.extend({method:s.literal("notifications/prompts/list_changed"),params:R.optional()}),A=s.object({type:s.literal("text"),text:s.string(),annotations:ge.optional(),_meta:s.record(s.string(),s.unknown()).optional()}),x=s.object({type:s.literal("image"),data:l,mimeType:s.string(),annotations:ge.optional(),_meta:s.record(s.string(),s.unknown()).optional()}),J=s.object({type:s.literal("audio"),data:l,mimeType:s.string(),annotations:ge.optional(),_meta:s.record(s.string(),s.unknown()).optional()}),K=s.object({type:s.literal("tool_use"),name:s.string(),id:s.string(),input:s.record(s.string(),s.unknown()),_meta:s.record(s.string(),s.unknown()).optional()}),ce=s.object({type:s.literal("resource"),resource:s.union([ie,he]),annotations:ge.optional(),_meta:s.record(s.string(),s.unknown()).optional()}),fe=_e.extend({type:s.literal("resource_link")}),k=s.union([A,x,J,fe,ce]),L=s.object({role:a,content:k}),H=s.object({title:s.string().optional(),readOnlyHint:s.boolean().optional(),destructiveHint:s.boolean().optional(),idempotentHint:s.boolean().optional(),openWorldHint:s.boolean().optional()}),Q=S.extend({method:s.literal("notifications/tools/list_changed"),params:R.optional()}),re=s.object({name:s.string().optional()}),ne=s.object({hints:s.array(re).optional(),costPriority:s.number().min(0).max(1).optional(),speedPriority:s.number().min(0).max(1).optional(),intelligencePriority:s.number().min(0).max(1).optional()}),me=s.object({mode:s.enum(["auto","required","none"]).optional()}),Re=s.object({type:s.literal("boolean"),title:s.string().optional(),description:s.string().optional(),default:s.boolean().optional()}),B=s.object({type:s.literal("string"),title:s.string().optional(),description:s.string().optional(),minLength:s.number().optional(),maxLength:s.number().optional(),format:s.enum(["email","uri","date","date-time"]).optional(),default:s.string().optional()}),be=s.object({type:s.enum(["number","integer"]),title:s.string().optional(),description:s.string().optional(),minimum:s.number().optional(),maximum:s.number().optional(),default:s.number().optional()}),X=s.object({type:s.literal("string"),title:s.string().optional(),description:s.string().optional(),enum:s.array(s.string()),default:s.string().optional()}),ee=s.object({type:s.literal("string"),title:s.string().optional(),description:s.string().optional(),oneOf:s.array(s.object({const:s.string(),title:s.string()})),default:s.string().optional()}),oe=s.object({type:s.literal("string"),title:s.string().optional(),description:s.string().optional(),enum:s.array(s.string()),enumNames:s.array(s.string()).optional(),default:s.string().optional()}),Z=s.union([X,ee]),Y=s.object({type:s.literal("array"),title:s.string().optional(),description:s.string().optional(),minItems:s.number().optional(),maxItems:s.number().optional(),items:s.object({type:s.literal("string"),enum:s.array(s.string())}),default:s.array(s.string()).optional()}),se=s.object({type:s.literal("array"),title:s.string().optional(),description:s.string().optional(),minItems:s.number().optional(),maxItems:s.number().optional(),items:s.object({anyOf:s.array(s.object({const:s.string(),title:s.string()}))}),default:s.array(s.string()).optional()}),ae=s.union([Y,se]),we=s.union([oe,Z,ae]),dt=s.union([we,Re,B,be]),tt=y.extend({mode:s.literal("form").optional(),message:s.string(),requestedSchema:s.object({type:s.literal("object"),properties:s.record(s.string(),dt),required:s.array(s.string()).optional()}).catchall(s.unknown())}),xt=s.object({type:s.literal("ref/resource"),uri:s.string()}),Ht=s.object({type:s.literal("ref/prompt"),name:s.string()}),Qr=s.object({uri:s.string().startsWith("file://"),name:s.string().optional(),_meta:s.record(s.string(),s.unknown()).optional()}),Rt=_.shape,en=s.object({experimental:Rt.experimental,sampling:Rt.sampling,elicitation:Rt.elicitation,roots:Rt.roots,extensions:Rt.extensions}),Be=C.shape,pr=s.object({experimental:Be.experimental,logging:Be.logging,completions:Be.completions,prompts:Be.prompts,resources:Be.resources,tools:Be.tools,extensions:Be.extensions}),mr=s.looseObject({progressToken:r.optional(),[Fe]:s.string(),[nr]:$.optional(),[at]:en,[Ct]:i.optional()}),Ut=s.object({...h.shape,...b.shape,description:s.string().optional(),inputSchema:s.looseObject({$schema:s.string().optional(),type:s.literal("object")}),outputSchema:s.looseObject({$schema:s.string().optional()}).optional(),annotations:H.optional(),_meta:s.record(s.string(),s.unknown()).optional()}),tn=s.object({type:s.literal("tool_result"),toolUseId:s.string(),content:s.array(k),structuredContent:s.unknown().optional(),isError:s.boolean().optional(),_meta:s.record(s.string(),s.unknown()).optional()}),hr=s.union([A,x,J,K,tn]),Vt=s.object({role:a,content:s.union([hr,s.array(hr)]),_meta:s.record(s.string(),s.unknown()).optional()}),fr=s.string(),gr=s.looseObject({[st]:$.optional().catch(void 0)}),yr=gr.optional();function Ae(Ce){return s.looseObject({_meta:yr,resultType:fr.default("complete"),...Ce})}let rn=Ae({}),Ao=Ae({nextCursor:n.optional()}),Sr=Ae({content:s.array(k),structuredContent:s.unknown().optional(),isError:s.boolean().optional()}),nn=Ae({ttlMs:s.number().int().min(0),cacheScope:s.enum(["public","private"]),tools:s.array(Ut),nextCursor:n.optional()}),on=Ae({ttlMs:s.number().int().min(0),cacheScope:s.enum(["public","private"]),prompts:s.array(g),nextCursor:n.optional()}),sn=Ae({description:s.string().optional(),messages:s.array(L)}),an=Ae({ttlMs:s.number().int().min(0),cacheScope:s.enum(["public","private"]),resources:s.array(_e),nextCursor:n.optional()}),cn=Ae({ttlMs:s.number().int().min(0),cacheScope:s.enum(["public","private"]),resourceTemplates:s.array(ue),nextCursor:n.optional()}),ln=Ae({ttlMs:s.number().int().min(0),cacheScope:s.enum(["public","private"]),contents:s.array(s.union([ie,he]))}),un=Ae({completion:s.object({values:s.array(s.string()).max(100),total:s.number().int().optional(),hasMore:s.boolean().optional()}).loose()}),Oo=Ae({ttlMs:s.number().int().min(0),cacheScope:s.enum(["public","private"])}),dn=Ae({ttlMs:s.number().int().min(0).catch(0),cacheScope:s.enum(["public","private"]).catch("private"),supportedVersions:s.array(s.string()),capabilities:pr,instructions:s.string().optional()}),wt=s.object({messages:s.array(Vt),modelPreferences:ne.optional(),systemPrompt:s.string().optional(),includeContext:s.enum(["none","thisServer","allServers"]).optional(),temperature:s.number().optional(),maxTokens:s.number().int(),stopSequences:s.array(s.string()).optional(),metadata:t.optional(),tools:s.array(Ut).optional(),toolChoice:me.optional()}),pn=s.object({method:s.literal("sampling/createMessage"),params:wt}),mn=s.object({method:s.literal("roots/list"),params:s.object({_meta:s.record(s.string(),s.unknown()).optional()}).optional()}),hn=s.object({...Vt.shape,model:s.string(),stopReason:s.string().optional()}),fn=s.object({roots:s.array(Qr)}),gn=s.object({action:s.enum(["accept","decline","cancel"]),content:s.record(s.string(),s.union([s.string(),s.number(),s.boolean(),s.array(s.string())])).optional()}),yn=s.object({mode:s.literal("url"),message:s.string(),url:s.string().url()}),Sn=s.union([tt,yn]),vn=s.object({method:s.literal("elicitation/create"),params:Sn}),_n=s.union([pn,mn,vn]),bn=s.union([hn,fn,gn]),Rn=s.record(s.string(),_n),wn=s.record(s.string(),bn),Bt=Ae({inputRequests:Rn.optional(),requestState:s.string().optional()}),Ft={inputResponses:wn.optional(),requestState:s.string().optional()},Mo=s.object({_meta:mr,...Ft}),No=s.looseObject({progressToken:r.optional()});function He(Ce,Jt){return s.object({method:s.literal(Ce),params:s.object({_meta:mr,...Jt})})}function Ue(Ce,Jt){return s.object({method:s.literal(Ce),params:s.object({_meta:No.optional(),...Jt}).optional()})}let En={name:s.string(),arguments:s.record(s.string(),s.unknown()).optional(),...Ft},Ke={cursor:n.optional()},qo=He("tools/call",En),jo=He("tools/list",Ke),Lo=He("prompts/list",Ke),Do=He("prompts/get",{name:s.string(),arguments:s.record(s.string(),s.string()).optional(),...Ft}),xo=He("resources/list",Ke),Ho=He("resources/templates/list",Ke),Uo=He("resources/read",{uri:s.string(),...Ft}),Tn={ref:s.union([Ht,xt]),argument:s.object({name:s.string(),value:s.string()}),context:s.object({arguments:s.record(s.string(),s.string()).optional()}).optional()},Vo=He("completion/complete",Tn),Bo=He("server/discover",{}),vr=s.object({toolsListChanged:s.boolean().optional(),promptsListChanged:s.boolean().optional(),resourcesListChanged:s.boolean().optional(),resourceSubscriptions:s.array(s.string()).optional()}),$n={notifications:vr},Fo=He("subscriptions/listen",$n),Go=gr.extend({"io.modelcontextprotocol/subscriptionId":o}),zn=s.looseObject({_meta:Go,resultType:fr.default("complete")}),Et={"tools/call":Ue("tools/call",En),"tools/list":Ue("tools/list",Ke),"prompts/get":Ue("prompts/get",{name:s.string(),arguments:s.record(s.string(),s.string()).optional()}),"prompts/list":Ue("prompts/list",Ke),"resources/list":Ue("resources/list",Ke),"resources/templates/list":Ue("resources/templates/list",Ke),"resources/read":Ue("resources/read",{uri:s.string()}),"completion/complete":Ue("completion/complete",Tn),"server/discover":Ue("server/discover",{}),"subscriptions/listen":Ue("subscriptions/listen",$n)};function Le(Ce){return s.looseObject({_meta:yr,...Ce})}let Jo={"tools/call":Le({content:s.array(k),structuredContent:s.unknown().optional(),isError:s.boolean().optional()}),"tools/list":Le({ttlMs:s.number().int().min(0),cacheScope:s.enum(["public","private"]),tools:s.array(Ut),nextCursor:n.optional()}),"prompts/get":Le({description:s.string().optional(),messages:s.array(L)}),"prompts/list":Le({ttlMs:s.number().int().min(0),cacheScope:s.enum(["public","private"]),prompts:s.array(g),nextCursor:n.optional()}),"resources/list":Le({ttlMs:s.number().int().min(0),cacheScope:s.enum(["public","private"]),resources:s.array(_e),nextCursor:n.optional()}),"resources/templates/list":Le({ttlMs:s.number().int().min(0),cacheScope:s.enum(["public","private"]),resourceTemplates:s.array(ue),nextCursor:n.optional()}),"resources/read":Le({ttlMs:s.number().int().min(0),cacheScope:s.enum(["public","private"]),contents:s.array(s.union([ie,he]))}),"completion/complete":Le({completion:s.object({values:s.array(s.string()).max(100),total:s.number().int().optional(),hasMore:s.boolean().optional()}).loose()}),"server/discover":Le({ttlMs:s.number().int().min(0).catch(0),cacheScope:s.enum(["public","private"]).catch("private"),supportedVersions:s.array(s.string()),capabilities:pr,instructions:s.string().optional()}),"subscriptions/listen":Le({})},Gt=s.looseObject({"io.modelcontextprotocol/subscriptionId":o.optional()}),_r=s.object({method:s.literal("notifications/subscriptions/acknowledged"),params:s.object({_meta:Gt.optional(),notifications:vr})}),br=s.object({_meta:Gt.optional(),requestId:o,reason:s.string().optional()}),Rr=s.object({method:s.literal("notifications/cancelled"),params:br}),Ai={"notifications/cancelled":Rr,"notifications/progress":q,"notifications/message":W,"notifications/resources/updated":E,"notifications/resources/list_changed":O,"notifications/tools/list_changed":Q,"notifications/prompts/list_changed":w,"notifications/subscriptions/acknowledged":_r},je=Ce=>s.object({jsonrpc:s.literal("2.0"),id:s.union([s.string(),s.number().int()]),result:Ce}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,RequestIdSchema:o,RoleSchema:a,LoggingLevelSchema:i,TaskMetadataSchema:c,RelatedTaskMetadataSchema:u,RequestMetaSchema:m,BaseRequestParamsSchema:f,TaskAugmentedRequestParamsSchema:y,NotificationsParamsSchema:R,NotificationSchema:S,IconSchema:P,IconsSchema:b,BaseMetadataSchema:h,ImplementationSchema:$,ClientTasksCapabilitySchema:I,ServerTasksCapabilitySchema:T,ClientCapabilitiesSchema:_,ServerCapabilitiesSchema:C,ProgressSchema:M,ProgressNotificationParamsSchema:U,ProgressNotificationSchema:q,LoggingMessageNotificationParamsSchema:D,LoggingMessageNotificationSchema:W,ResourceContentsSchema:F,TextResourceContentsSchema:ie,BlobResourceContentsSchema:he,AnnotationsSchema:ge,ResourceSchema:_e,ResourceTemplateSchema:ue,ResourceListChangedNotificationSchema:O,ResourceUpdatedNotificationParamsSchema:j,ResourceUpdatedNotificationSchema:E,PromptArgumentSchema:p,PromptSchema:g,PromptListChangedNotificationSchema:w,TextContentSchema:A,ImageContentSchema:x,AudioContentSchema:J,ToolUseContentSchema:K,EmbeddedResourceSchema:ce,ResourceLinkSchema:fe,ContentBlockSchema:k,PromptMessageSchema:L,ToolAnnotationsSchema:H,ToolListChangedNotificationSchema:Q,ModelHintSchema:re,ModelPreferencesSchema:ne,ToolChoiceSchema:me,BooleanSchemaSchema:Re,StringSchemaSchema:B,NumberSchemaSchema:be,UntitledSingleSelectEnumSchemaSchema:X,TitledSingleSelectEnumSchemaSchema:ee,LegacyTitledEnumSchemaSchema:oe,SingleSelectEnumSchemaSchema:Z,UntitledMultiSelectEnumSchemaSchema:Y,TitledMultiSelectEnumSchemaSchema:se,MultiSelectEnumSchemaSchema:ae,EnumSchemaSchema:we,PrimitiveSchemaDefinitionSchema:dt,ElicitRequestFormParamsSchema:tt,ResourceTemplateReferenceSchema:xt,PromptReferenceSchema:Ht,RootSchema:Qr,ClientCapabilities2026Schema:en,ServerCapabilities2026Schema:pr,RequestMetaEnvelopeSchema:mr,ToolSchema:Ut,ToolResultContentSchema:tn,SamplingMessageContentBlockSchema:hr,SamplingMessageSchema:Vt,ResultTypeSchema:fr,ResultMetaSchema:gr,ResultSchema:rn,PaginatedResultSchema:Ao,CallToolResultSchema:Sr,ListToolsResultSchema:nn,ListPromptsResultSchema:on,GetPromptResultSchema:sn,ListResourcesResultSchema:an,ListResourceTemplatesResultSchema:cn,ReadResourceResultSchema:ln,CompleteResultSchema:un,CacheableResultSchema:Oo,DiscoverResultSchema:dn,CreateMessageRequestParamsSchema:wt,CreateMessageRequestSchema:pn,ListRootsRequestSchema:mn,CreateMessageResultSchema:hn,ListRootsResultSchema:fn,ElicitResultSchema:gn,ElicitRequestURLParamsSchema:yn,ElicitRequestParamsSchema:Sn,ElicitRequestSchema:vn,InputRequestSchema:_n,InputResponseSchema:bn,InputRequestsSchema:Rn,InputResponsesSchema:wn,InputRequiredResultSchema:Bt,InputResponseRequestParamsSchema:Mo,CallToolRequestSchema:qo,ListToolsRequestSchema:jo,ListPromptsRequestSchema:Lo,GetPromptRequestSchema:Do,ListResourcesRequestSchema:xo,ListResourceTemplatesRequestSchema:Ho,ReadResourceRequestSchema:Uo,CompleteRequestSchema:Vo,DiscoverRequestSchema:Bo,SubscriptionFilterSchema:vr,SubscriptionsListenRequestSchema:Fo,SubscriptionsListenResultMetaSchema:Go,SubscriptionsListenResultSchema:zn,dispatchRequestSchemas:Et,dispatchResultSchemas:Jo,NotificationMetaSchema:Gt,SubscriptionsAcknowledgedNotificationSchema:_r,CancelledNotificationParamsSchema:br,CancelledNotificationSchema:Rr,notificationSchemas2026:Ai,JSONRPCResultResponseSchema:je(rn),CallToolResultResponseSchema:je(s.union([Sr,Bt])),ListToolsResultResponseSchema:je(nn),ListPromptsResultResponseSchema:je(on),GetPromptResultResponseSchema:je(s.union([sn,Bt])),ListResourcesResultResponseSchema:je(an),ListResourceTemplatesResultResponseSchema:je(cn),ReadResourceResultResponseSchema:je(s.union([ln,Bt])),CompleteResultResponseSchema:je(un),DiscoverResultResponseSchema:je(dn),SubscriptionsListenResultResponseSchema:je(zn)}}var sy;function jt(){return sy??=oy()}var ay=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function iy(e){return ay.includes(e)}var Hr=Symbol("modelcontextprotocol.resultCacheHintFallback");function ai(e,t){if(t===void 0)return e;let r=e[Hr];if(r===void 0)return{...e,[Hr]:t};let n={},o=r.ttlMs??t.ttlMs;o!==void 0&&(n.ttlMs=o);let a=r.cacheScope??t.cacheScope;return a!==void 0&&(n.cacheScope=a),{...e,[Hr]:n}}function cy(e){return e[Hr]}function rl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function nl(e){return e==="public"||e==="private"}function ol(e,t){if(e.ttlMs!==void 0&&!rl(e.ttlMs))throw new RangeError(`Invalid cache hint for ${t}: ttlMs must be a non-negative safe integer (got ${String(e.ttlMs)})`);if(e.cacheScope!==void 0&&!nl(e.cacheScope))throw new RangeError(`Invalid cache hint for ${t}: cacheScope must be 'public' or 'private' (got ${String(e.cacheScope)})`)}var G=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.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e}({}),te=class kp extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Vr(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Vr(this,t)}constructor(t,r,n){super(r),this.code=t,this.data=n,this.name="ProtocolError",Zc(this,new.target)}static fromError(t,r,n){if(t===G.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ip(o.elicitations,r)}if(t===G.UnsupportedProtocolVersion&&n){let o=n;if(Array.isArray(o.supported)&&typeof o.requested=="string")return new ci({supported:o.supported,requested:o.requested},r)}if(t===G.InvalidParams||t===G.ResourceNotFound){let o=n;if(typeof o?.uri=="string"&&(t===G.ResourceNotFound||Object.keys(o).length===1))return new ii(o.uri,r)}if(t===G.MissingRequiredClientCapability&&n){let o=n;if(o.requiredCapabilities!==null&&typeof o.requiredCapabilities=="object"&&!Array.isArray(o.requiredCapabilities))return new bo({requiredCapabilities:o.requiredCapabilities},r)}return new kp(t,r,n)}},ii=class extends te{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(G.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Ip=class extends te{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(G.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},ci=class extends te{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(G.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},bo=class extends te{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(G.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},ly=0,uy="private",dy=["tools/call","prompts/get","resources/read"];function py(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||dy.includes(e))return t;throw new te(G.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function my(e,t){let r=cy(t);if(t.resultType!=="complete"||!iy(e))return r===void 0?t:Sy(t);let n=t,o=rl(n.ttlMs)?n.ttlMs:gy(r),a=nl(n.cacheScope)?n.cacheScope:yy(r),i={...n,ttlMs:o,cacheScope:a};return delete i[Hr],i}function hy(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fy(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[st]:t}}:!hy(r)||r[st]!==void 0?e:{...e,_meta:{...r,[st]:t}}}function gy(e){return e!==void 0&&rl(e.ttlMs)?e.ttlMs:ly}function yy(e){return e!==void 0&&nl(e.cacheScope)?e.cacheScope:uy}function Sy(e){let t={...e};return delete t[Hr],t}var vy=["elicitation/create","sampling/createMessage","roots/list"],ti;function Ap(){if(ti)return ti;let e=jt();return ti={request:{"elicitation/create":s.object({method:s.literal("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":s.object({method:s.literal("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":s.object({method:s.literal("roots/list"),params:s.looseObject({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},ti}function Op(e){return vy.includes(e)}function Bc(e){return Op(e)?Ap().request[e]:void 0}function _y(e){return Op(e)?Ap().response[e]:void 0}var sl={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Mp={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function Np(e){return Object.prototype.hasOwnProperty.call(sl,e)}function qp(e){return Object.prototype.hasOwnProperty.call(Mp,e)}function by(e){return Object.prototype.hasOwnProperty.call(sl,e)}function Ry(e){return Np(e)?jt().dispatchRequestSchemas[e]:void 0}function wy(e){return by(e)?jt().dispatchResultSchemas[e]:void 0}function Ey(e){return qp(e)?jt().notificationSchemas2026[e]:void 0}var Sw=Object.keys(sl),vw=Object.keys(Mp);function fo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function mo(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var Ty={ok:!1,reason:"not-in-era"},$y=[Fe,at];function zy(e,t){let r=t,n=!1,o=()=>(n||(r={...r},n=!0),r),a=t.tools;e==="tools/list"&&Array.isArray(a)&&a.some(l=>fo(l)&&"execution"in l)&&(o().tools=a.map(l=>{if(!fo(l)||!("execution"in l))return l;let c={...l};return delete c.execution,c}));let i=t.capabilities;if(fo(i)&&"tasks"in i){let l={...i};delete l.tasks,o().capabilities=l}return r}var al={era:"2026-07-28",hasRequestMethod:Np,hasNotificationMethod:qp,hasInputRequestMethod:e=>Bc(e)!==void 0,validateRequest:(e,t)=>mo(Ry(e),t),validateResult:(e,t)=>mo(wy(e),t),validateNotification:(e,t)=>mo(Ey(e),t),validateInputRequest:(e,t)=>mo(Bc(e),t),validateInputResponse:(e,t)=>mo(_y(e),t),samplingResultVariant:()=>Ty,outboundEnvelope(e){return{[Fe]:e.protocolVersion,[nr]:e.clientInfo,[at]:e.clientCapabilities,...e.logLevel!==void 0&&{[Ct]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of $y)n in e||t.push({key:n,problem:"missing"});let r=jt().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let n of r.error.issues){let o=n.path.map(String),a=o.length>0?o.join("."):"_meta";o.length===1&&t.some(i=>i.key===a&&i.problem==="missing")||t.push({key:a,problem:n.message})}return t},projectCallToolResult:e=>Rp(e),inputRequestSchema:Bc,decodeResult(e,t){if(!fo(t))return{kind:"invalid",error:new le(pe.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new le(pe.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!="string")return{kind:"invalid",error:new le(pe.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let i=t.inputRequests,l=fo(i)?i:{},c=t.requestState,u=t._meta===void 0?void 0:jt().ResultMetaSchema.safeParse(t._meta),m=u?.success?u.data:void 0;return Object.keys(l).length===0&&typeof c!="string"?{kind:"invalid",error:new le(pe.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:l,...typeof c=="string"&&{requestState:c},...m!==void 0&&{_meta:m}}}if(r!=="complete")return{kind:"invalid",error:new le(pe.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let n=Py(),o=Object.hasOwn(n,e)?n[e]:void 0;if(o!==void 0){let i=o.safeParse(t);if(!i.success)return{kind:"invalid",error:new le(pe.InvalidResult,`Invalid result for ${e}: ${i.error}`,{method:e})}}let a={...t};return delete a.resultType,{kind:"complete",result:a}},encodeResult(e,t,r){return fy(my(e,py(e,zy(e,t))),r)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=jt().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},ri;function Py(){if(ri)return ri;let e=jt();return ri={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},ri}var Ro="2026-07-28";function ht(e){return e!==void 0&&ft(e)?al:tl}function ip(e){return e.revision!==void 0?ht(e.revision).era:e.era==="modern"?al.era:tl.era}function Fc(e){return jp.some(t=>t.hasRequestMethod(e))}function Gc(e){return jp.some(t=>t.hasNotificationMethod(e))}function cp(e){return e==="tasks/get"||e==="tasks/cancel"}var jp=[tl,al];function lp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Lt(e){if(!lp(e))return;let t=e._meta;return lp(t)?t:void 0}function li(e){let t=Lt(e);return t!==void 0&&Fe in t}function il(e){let t=Lt(e)?.[Fe];return typeof t=="string"?t:void 0}function oi(e){return ht(Ro).validateEnvelopeMeta(e)}var Cy=Jd({AnnotationsSchema:()=>mt,AudioContentSchema:()=>Nr,BaseMetadataSchema:()=>pt,BaseRequestParamsSchema:()=>ke,BlobResourceContentsSchema:()=>eo,BooleanSchemaSchema:()=>so,CallToolRequestParamsSchema:()=>pa,CallToolRequestSchema:()=>ma,CallToolResultSchema:()=>oo,CancelTaskRequestSchema:()=>zc,CancelTaskResultSchema:()=>Pc,CancelledNotificationParamsSchema:()=>gs,CancelledNotificationSchema:()=>Jn,ClientCapabilitiesSchema:()=>_s,ClientNotificationSchema:()=>kc,ClientRequestSchema:()=>Cc,ClientResultSchema:()=>Ic,ClientTasksCapabilitySchema:()=>Ss,CompatibilityCallToolResultSchema:()=>gc,CompleteRequestParamsSchema:()=>xa,CompleteRequestSchema:()=>Ha,CompleteResultSchema:()=>Ua,ContentBlockSchema:()=>qr,CreateMessageRequestParamsSchema:()=>Ta,CreateMessageRequestSchema:()=>$a,CreateMessageResultSchema:()=>za,CreateMessageResultWithToolsSchema:()=>Pa,CreateTaskResultSchema:()=>vc,CursorSchema:()=>Hn,DiscoverRequestSchema:()=>Es,DiscoverResultSchema:()=>Ts,ElicitRequestFormParamsSchema:()=>Dr,ElicitRequestParamsSchema:()=>Oa,ElicitRequestSchema:()=>Ma,ElicitRequestURLParamsSchema:()=>Aa,ElicitResultSchema:()=>ja,ElicitationCompleteNotificationParamsSchema:()=>Na,ElicitationCompleteNotificationSchema:()=>qa,EmbeddedResourceSchema:()=>na,EmptyResultSchema:()=>Gn,EnumSchemaSchema:()=>Ia,GetPromptRequestParamsSchema:()=>ea,GetPromptRequestSchema:()=>ta,GetPromptResultSchema:()=>aa,GetTaskPayloadRequestSchema:()=>wc,GetTaskPayloadResultSchema:()=>Ec,GetTaskRequestSchema:()=>bc,GetTaskResultSchema:()=>Rc,IconSchema:()=>ys,IconsSchema:()=>It,ImageContentSchema:()=>Mr,ImplementationSchema:()=>Ir,InitializeRequestParamsSchema:()=>bs,InitializeRequestSchema:()=>Kn,InitializeResultSchema:()=>Rs,InitializedNotificationSchema:()=>ws,JSONArraySchema:()=>mc,JSONObjectSchema:()=>$e,JSONRPCErrorResponseSchema:()=>Cr,JSONRPCMessageSchema:()=>kr,JSONRPCNotificationSchema:()=>Fn,JSONRPCRequestSchema:()=>Bn,JSONRPCResponseSchema:()=>hc,JSONRPCResultResponseSchema:()=>Pr,JSONValueSchema:()=>Pt,LegacyTitledEnumSchemaSchema:()=>co,ListChangedOptionsBaseSchema:()=>yc,ListPromptsRequestSchema:()=>Zs,ListPromptsResultSchema:()=>Qs,ListResourceTemplatesRequestSchema:()=>As,ListResourceTemplatesResultSchema:()=>Os,ListResourcesRequestSchema:()=>ks,ListResourcesResultSchema:()=>Is,ListRootsRequestSchema:()=>Ba,ListRootsResultSchema:()=>Fa,ListTasksRequestSchema:()=>Tc,ListTasksResultSchema:()=>$c,ListToolsRequestSchema:()=>ua,ListToolsResultSchema:()=>da,LoggingLevelSchema:()=>Nt,LoggingMessageNotificationParamsSchema:()=>ya,LoggingMessageNotificationSchema:()=>Sa,ModelHintSchema:()=>va,ModelPreferencesSchema:()=>_a,MultiSelectEnumSchemaSchema:()=>ka,NotificationSchema:()=>qe,NotificationsParamsSchema:()=>Ne,NumberSchemaSchema:()=>Lr,PaginatedRequestParamsSchema:()=>Ps,PaginatedRequestSchema:()=>At,PaginatedResultSchema:()=>Ot,PingRequestSchema:()=>Yn,PrimitiveSchemaDefinitionSchema:()=>po,ProgressNotificationParamsSchema:()=>zs,ProgressNotificationSchema:()=>Xn,ProgressSchema:()=>$s,ProgressTokenSchema:()=>xn,PromptArgumentSchema:()=>Ys,PromptListChangedNotificationSchema:()=>ia,PromptMessageSchema:()=>sa,PromptReferenceSchema:()=>Da,PromptSchema:()=>Xs,ReadResourceRequestParamsSchema:()=>Ms,ReadResourceRequestSchema:()=>Ns,ReadResourceResultSchema:()=>qs,RelatedTaskMetadataSchema:()=>fs,RequestIdSchema:()=>kt,RequestMetaSchema:()=>Un,RequestSchema:()=>ze,ResourceContentsSchema:()=>Zn,ResourceLinkSchema:()=>oa,ResourceListChangedNotificationSchema:()=>js,ResourceRequestParamsSchema:()=>Ar,ResourceSchema:()=>to,ResourceTemplateReferenceSchema:()=>La,ResourceTemplateSchema:()=>Cs,ResourceUpdatedNotificationParamsSchema:()=>Ks,ResourceUpdatedNotificationSchema:()=>Ws,ResultMetaObjectSchema:()=>Vn,ResultSchema:()=>Pe,RoleSchema:()=>Mt,RootSchema:()=>Va,RootsListChangedNotificationSchema:()=>Ga,SamplingContentSchema:()=>wa,SamplingMessageContentBlockSchema:()=>tr,SamplingMessageSchema:()=>Ea,ServerCapabilitiesSchema:()=>Wn,ServerNotificationSchema:()=>Oc,ServerRequestSchema:()=>Ac,ServerResultSchema:()=>Mc,ServerTasksCapabilitySchema:()=>vs,SetLevelRequestParamsSchema:()=>fa,SetLevelRequestSchema:()=>ga,SingleSelectEnumSchemaSchema:()=>Ca,StringSchemaSchema:()=>jr,SubscribeRequestParamsSchema:()=>Ls,SubscribeRequestSchema:()=>Ds,SubscriptionFilterSchema:()=>ro,SubscriptionsAcknowledgedNotificationParamsSchema:()=>Bs,SubscriptionsAcknowledgedNotificationSchema:()=>Fs,SubscriptionsListenRequestParamsSchema:()=>Us,SubscriptionsListenRequestSchema:()=>Vs,SubscriptionsListenResultMetaSchema:()=>Gs,SubscriptionsListenResultSchema:()=>Js,TaskAugmentedRequestParamsSchema:()=>ar,TaskCreationParamsSchema:()=>Sc,TaskMetadataSchema:()=>hs,TaskSchema:()=>qt,TaskStatusNotificationParamsSchema:()=>Ka,TaskStatusNotificationSchema:()=>_c,TaskStatusSchema:()=>Ja,TextContentSchema:()=>Or,TextResourceContentsSchema:()=>Qn,TitledMultiSelectEnumSchemaSchema:()=>uo,TitledSingleSelectEnumSchemaSchema:()=>io,ToolAnnotationsSchema:()=>ca,ToolChoiceSchema:()=>ba,ToolExecutionSchema:()=>la,ToolListChangedNotificationSchema:()=>ha,ToolResultContentSchema:()=>Ra,ToolSchema:()=>no,ToolUseContentSchema:()=>ra,UnsubscribeRequestParamsSchema:()=>xs,UnsubscribeRequestSchema:()=>Hs,UntitledMultiSelectEnumSchemaSchema:()=>lo,UntitledSingleSelectEnumSchemaSchema:()=>ao});var Xe=e=>Bn.safeParse(e).success,ui=e=>Fn.safeParse(e).success,it=e=>Pr.safeParse(e).success,ct=e=>Cr.safeParse(e).success;var gt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var cl=e=>Kn.safeParse(e).success;function ll(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function ul(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var ky="Mcp-Param-",up="x-mcp-header",Iy=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Ay=new Set(["string","integer","boolean"]);function di(e){let t=[],r=new Map,n,o=(i,l,c)=>{if(i===null||typeof i!="object")return;let u=i;if(up in u){if(!c||l.length===0)return`${xr(l)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let f=u[up];if(typeof f!="string"||f.length===0)return`${xr(l)}: x-mcp-header MUST be a non-empty string`;if(!Iy.test(f))return`${xr(l)}: x-mcp-header '${f}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let y=typeof u.type=="string"?u.type:void 0;if(y===void 0||!Ay.has(y)){let P=`${xr(l)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${y??"<none>"}`;if(y!=="number")return P;n??=P}let R=f.toLowerCase(),S=r.get(R);if(S!==void 0)return`x-mcp-header '${f}' is not case-insensitively unique (also declared as '${S}')`;r.set(R,f),t.push({path:l,headerName:f,type:y})}let m=u.properties;if(m!==null&&typeof m=="object")for(let[f,y]of Object.entries(m)){let R=o(y,[...l,f],c);if(R!==void 0)return R}for(let f of Oy){let y=u[f];if(y===void 0)continue;let R=Array.isArray(y)?y:y!==null&&typeof y=="object"&&My.has(f)?Object.values(y):[y];for(let S of R){let P=o(S,[...l,`<${f}>`],!1);if(P!==void 0)return P}}},a=o(e,[],!0);return a!==void 0?{valid:!1,reason:n??a}:n===void 0?{valid:!0,declarations:t}:{valid:!1,reason:n,declarations:t}}var Oy=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],My=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function xr(e){return e.length===0?"<root>":e.join(".")}var Ny="=?base64?",qy="?=",jy=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Ly=/^-?\d+(\.\d+)?$/;function Dy(e){if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function xy(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.codePointAt(n);return new TextDecoder("utf-8",{fatal:!0}).decode(r)}function Lp(e){if(!(e.startsWith(Ny)&&e.endsWith(qy)))return e;let t=e.slice(9,e.length-2);if(jy.test(t))try{return xy(t)}catch{return}}function Hy(e,t){let r=e;for(let n of t){if(r===null||typeof r!="object")return;r=r[n]}return r}function Dp(e,t,r){for(let n of e){let o=`${ky}${n.headerName}`,a=r.get(o),i=Hy(t,n.path);if(i==null)continue;let l=Dy(i);if(l===void 0)continue;if(a===null)return Jc("param-header-missing",o,`the body carries ${xr(n.path)}=${JSON.stringify(i)} but the ${o} header is absent`);let c=Lp(a);if(c===void 0)return Jc("param-header-invalid-encoding",o,`the ${o} header carries an invalid Base64 sentinel value`);if(!((n.type==="integer"||n.type==="number")&&Ly.test(c)&&typeof i=="number"?Number(c)===i:c===l))return Jc("param-header-mismatch",o,`the ${o} header decodes to ${JSON.stringify(c)} but the body carries ${xr(n.path)}=${JSON.stringify(i)}`)}}function Jc(e,t,r){return{kind:"reject",rung:"param-header-validation",cell:e,httpStatus:400,code:Ur,message:`Bad Request: the request headers and body disagree: ${r}`,data:{mismatch:{header:t,body:r}},settled:!0}}var Ur=-32020,_w=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[G.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Ur,G.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[G.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[G.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[G.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Ur],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[G.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Ur],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],dl={[G.ParseError]:400,[G.InvalidRequest]:400,[G.MethodNotFound]:404,[G.UnsupportedProtocolVersion]:400,[G.MissingRequiredClientCapability]:400,[Ur]:400};function xp(e,t){return t==="in-band"?e===G.MissingRequiredClientCapability?400:200:dl[e]??400}function Ge(e,t,r,n,o){return{kind:"reject",rung:e,cell:t,httpStatus:r,code:n.code,message:n.message,...n.data!==void 0&&{data:n.data},settled:o}}function Ye(e,t,r,n="era-classification"){return Ge(n,e,400,new te(Ur,`Bad Request: the request headers and body disagree: ${r}`,{mismatch:{header:t,body:r}}),!0)}var dp={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function Uy(e,t){let r=Object.hasOwn(dp,e)?dp[e]:void 0;if(r===void 0)return;let n=yo(t)?t[r]:void 0;return{field:r,value:typeof n=="string"?n:void 0}}function ni(e){let t=0;for(;t<e.length;){let n=e.codePointAt(t);if(n!==9&&n!==32)break;t+=1}let r=e.length;for(;r>t;){let n=e.codePointAt(r-1);if(n!==9&&n!==32)break;r-=1}return t===0&&r===e.length?e:e.slice(t,r)}function Hp(e,t){if(t.messageKind!=="request")return;let r=t.message.method;if(e.protocolVersionHeader===void 0){let c=t.classification.revision;return Ye("version-header-missing","(missing)",c===void 0?"the body carries a modern per-request envelope but the required MCP-Protocol-Version header is absent":`the body envelope names protocol version ${c} but the required MCP-Protocol-Version header is absent`,"standard-header-validation")}if(e.mcpMethodHeader===void 0)return Ye("method-header-missing","(missing)",`the body names method ${r} but the required Mcp-Method header is absent`,"standard-header-validation");let n=Uy(r,t.message.params);if(n===void 0)return;let{field:o,value:a}=n;if(e.mcpNameHeader===void 0)return a===void 0?void 0:Ye("name-header-missing","(missing)",`the body carries params.${o}="${a}" but the required Mcp-Name header is absent`,"standard-header-validation");let i=ni(e.mcpNameHeader),l=Lp(i);if(l===void 0)return Ye("name-header-invalid-encoding",i,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation");if(a!==void 0&&l!==a)return Ye("name-header-mismatch",i,`the body carries params.${o}="${a}" but the Mcp-Name header names "${l}"`,"standard-header-validation")}function yo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Up(e){return e===void 0?{era:"modern"}:{era:ft(e)?"modern":"legacy",revision:e}}function Vy(e){if(!li(e))return!1;let t=il(e);if(t===void 0||!ft(t))return!1;let r=Lt(e);return r!==void 0&&oi(r).length===0}function By(e){if(e.length===0)return Ge("jsonrpc-shape","empty-batch",400,new te(G.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let t of e){if(li(yo(t)?t.params:void 0))return Ge("jsonrpc-shape","batch-with-modern-element",400,new te(G.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(Xe(t)||ui(t)||it(t)||ct(t)))return Ge("jsonrpc-shape","batch-with-invalid-element",400,new te(G.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}function Fy(e,t){let r=t.params,n=t.method,o=e.protocolVersionHeader,a=o!==void 0&&ft(o);if(n==="initialize"&&!Vy(r)){if(a)return Ye("initialize-with-modern-header",o,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let i=yo(r)&&typeof r.protocolVersion=="string"?r.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...i!==void 0&&{requestedVersion:i}}}if(li(r)){let i=Lt(r),l=(i===void 0?[]:oi(i))[0];if(l!==void 0)return Ge("envelope","envelope-invalid",400,new te(G.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${l.key}: ${l.problem}`,{envelope:l}),!0);let c=il(r);return o!==void 0&&c!==void 0&&o!==c?Ye("header-body-version-mismatch",o,`the body envelope names protocol version ${c} but the MCP-Protocol-Version header names ${o}`):e.mcpMethodHeader!==void 0&&e.mcpMethodHeader!==n?Ye("method-header-mismatch",e.mcpMethodHeader,`the body names method ${n} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:t,classification:Up(c)}}if(a){let i=Lt(r),l=oi(i??{}).filter(u=>u.problem==="missing").map(u=>u.key),c=i===void 0?["_meta"]:l.length>0?l:[Fe];return Ge("envelope","modern-header-without-claim",400,new te(G.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${o}, but the request is missing the required per-request envelope key(s): ${c.join(", ")}`,{envelope:{missing:c}}),!0)}return{kind:"legacy",reason:"no-claim",...o!==void 0&&{requestedVersion:o}}}function Gy(e,t){let r=t.params,n=t.method,o=e.protocolVersionHeader,a=o!==void 0&&ft(o);if(li(r)){let i=il(r);if(i===void 0){let c=Lt(r),u=(c===void 0?[]:oi(c)).find(m=>m.key===Fe)??{key:Fe,problem:"expected a protocol version string"};return Ge("envelope","notification-envelope-invalid",400,new te(G.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${u.key}: ${u.problem}`,{envelope:u}),!0)}if(o!==void 0&&o!==i)return Ye("notification-header-body-version-mismatch",o,`the notification envelope names protocol version ${i} but the MCP-Protocol-Version header names ${o}`);let l=Up(i);return l.era==="modern"&&e.mcpMethodHeader!==void 0&&e.mcpMethodHeader!==n?Ye("notification-method-header-mismatch",e.mcpMethodHeader,`the notification body names method ${n} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:t,classification:l}}return a?e.mcpMethodHeader!==void 0&&e.mcpMethodHeader!==n?Ye("notification-method-header-mismatch",e.mcpMethodHeader,`the notification body names method ${n} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:t,classification:{era:"modern",revision:o}}:{kind:"legacy",reason:"notification",...o!==void 0&&{requestedVersion:o}}}function pi(e){if(e={...e,...e.protocolVersionHeader!==void 0&&{protocolVersionHeader:ni(e.protocolVersionHeader)},...e.mcpMethodHeader!==void 0&&{mcpMethodHeader:ni(e.mcpMethodHeader)},...e.mcpNameHeader!==void 0&&{mcpNameHeader:ni(e.mcpNameHeader)}},e.httpMethod.toUpperCase()!=="POST")return{kind:"legacy",reason:"http-method"};let t=e.body;return Array.isArray(t)?By(t):it(t)||ct(t)?{kind:"legacy",reason:"response"}:yo(t)&&Xe(t)?Fy(e,t):yo(t)&&ui(t)?Gy(e,t):Ge("jsonrpc-shape","invalid-json-rpc-body",400,new te(G.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}function Vp(e,t){switch(e.reason){case"http-method":return Ge("http-method","modern-only-method-not-allowed",405,new te(-32e3,"Method not allowed."),!0);case"batch":return Ge("jsonrpc-shape","modern-only-batch-not-supported",400,new te(G.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return Ge("jsonrpc-shape","modern-only-response-post",400,new te(G.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let r=e.requestedVersion;return Ge("era-classification","modern-only-missing-envelope",400,r===void 0?new te(G.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...t]}):new ci({supported:[...t],requested:r}),!0)}}}function mi(e,t){return s.safeParse(e,t)}function ho(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function Br(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}var pp=!1,Yc="draft-2020-12";function ur(e,t="input"){let r=e["~standard"],n;if(r.jsonSchema)n=r.jsonSchema[t]({target:Yc});else if(r.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");pp||(pp=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),n=s.toJSONSchema(e,{target:Yc,io:t})}else throw new Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return n.type!==void 0?n:Bp(n)?{type:"object",...n}:n;if(n.type!==void 0&&n.type!=="object")throw new 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}}var Jy=/^#\/(\$defs|definitions)\/([^/~%]+)$/;function Bp(e,t=e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;let r=typeof e.$ref=="string"&&Jy.exec(e.$ref);if(r&&t[r[1]]?.[r[2]]?.type==="object")return!0;for(let n of["oneOf","anyOf","allOf"]){let o=e[n];if(Array.isArray(o)&&o.length>0)return o.every(a=>a!==null&&typeof a=="object"&&(a.type==="object"||Bp(a,"$id"in a?{}:t)))}return!1}function Ky(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}async function ir(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(n=>Ky(n)).join(", ")}:{success:!0,data:r.value}}function Wy(e){let t=s.toJSONSchema(e,{target:Yc,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}var Yy=/\\\.\\d\{(\d+)\}/;function Xy(e){let t=Yy.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(n=>[!1,!0].flatMap(o=>r.map(a=>s.iso.datetime({local:n,offset:o,precision:a}))))}function Zy(e,t){let r;switch(e){case"email":r=[s.email()];break;case"uri":r=[s.url()];break;case"date":r=[s.iso.date()];break;case"date-time":r=Xy(t);break}return new Set(r.map(n=>Wy(n)).filter(n=>n!==void 0))}function Qy(e,t,r){return r!=="zod"?!0:Zy(e,t).has(t)}function Fp(e){let t=ur(e,"input"),r=t.properties||{},n=t.required||[];return Object.entries(r).map(([o,a])=>({name:o,description:a?.description,required:n.includes(o)}))}function So(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eS(e){try{return ur(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new te(G.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}var tS=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function pl(e){return tS.has(e)||e.startsWith("x-")}var rS=new Set(["$schema",...Object.keys(Dr.shape.requestedSchema.shape)]),mp={string:ho([jr,ao,io,co]),number:ho([Lr]),integer:ho([Lr]),boolean:ho([so]),array:ho([lo,uo])},nS=new Set(jr.shape.format.unwrap().options);function oS(e,t,r,n){if(!So(e))return e;let o=typeof e.type=="string"&&Object.hasOwn(mp,e.type)?mp[e.type]:void 0;if(o===void 0)return e;let a={};for(let[i,l]of Object.entries(e))o.has(i)||pl(i)?a[i]=l:i==="pattern"&&e.type==="string"&&typeof e.format=="string"?nS.has(e.format)?(typeof l!="string"||!Qy(e.format,l,r))&&n.push(`${t}.${i}`):a[i]=l:n.push(`${t}.${i}`);return a}function sS(e,t){let r={},n=[];for(let[o,a]of Object.entries(e))o==="properties"&&So(a)?r[o]=Object.fromEntries(Object.entries(a).map(([i,l])=>[i,oS(l,`properties.${i}`,t,n)])):rS.has(o)?r[o]=a:pl(o)||n.push(o);if(n.length>0)throw new te(G.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return r}function aS(e,t){if(!So(e.properties))return t;let r=Object.entries(e.properties).filter(([,n])=>!mi(po,n).success).map(([n])=>`properties.${n}`);return r.length>0?r.join(", "):t}function Xc(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((n,o)=>Xc(n,t[o],`${r}[${o}]`)):!So(e)||!So(t)?[]:Object.entries(e).flatMap(([n,o])=>{let a=r?`${r}.${n}`:n;return Object.prototype.hasOwnProperty.call(t,n)?Xc(o,t[n],a):pl(n)?[]:[a]})}function iS(e){if(!Br(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=sS(eS(e.requestedSchema),t),n=mi(Dr.shape.requestedSchema,r);if(!n.success)throw new te(G.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${aS(r,n.error.message)}`);let o=Xc(r,n.data);if(o.length>0)throw new te(G.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);let a=(n.data.required??[]).filter(i=>!Object.prototype.hasOwnProperty.call(n.data.properties,i));if(a.length>0)throw new te(G.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${a.join(", ")}`);return{...e,mode:"form",requestedSchema:n.data}}function cS(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState=="string";if(!t&&!r)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}var lS=Object.assign(cS,{elicit(e){try{return{method:"elicitation/create",params:iS(e)}}catch(t){throw t instanceof te?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var Gp=250;function Jp(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Kp(e,t){return new Promise((r,n)=>{if(t?.aborted){n(t.reason instanceof le?t.reason:new le(pe.RequestTimeout,String(t.reason)));return}let o=setTimeout(()=>{t?.removeEventListener("abort",a),r()},e),a=()=>{clearTimeout(o),n(t?.reason instanceof le?t.reason:new le(pe.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",a,{once:!0})})}function Wp(e){let t=new AbortController,r=()=>t.abort(e?.reason);return e?.addEventListener("abort",r,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:n=>t.abort(n),dispose:()=>e?.removeEventListener("abort",r)}}var uS=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],dS={IdJagTokenExchangeResponseSchema:Dc,OAuthClientInformationFullSchema:Hc,OAuthClientInformationSchema:Za,OAuthClientMetadataSchema:Xa,OAuthClientRegistrationErrorSchema:Uc,OAuthErrorResponseSchema:xc,OAuthMetadataSchema:Wa,OAuthProtectedResourceMetadataSchema:qc,OAuthTokenRevocationRequestSchema:Vc,OAuthTokensSchema:Lc,OpenIdProviderDiscoveryMetadataSchema:jc,OpenIdProviderMetadataSchema:Ya},Yp={},Xp={};function Zp(e,t){let r=e.slice(0,-6);Yp[r]=t,Xp[r]=n=>t.safeParse(n).success}for(let e of uS)Zp(e,Cy[e]);for(let[e,t]of Object.entries(dS))Zp(e,t);var pS=Object.freeze(Yp),mS=Object.freeze(Xp);function hS(e){switch(e){case"initialize":case"notifications/initialized":return ht(void 0);case"server/discover":return ht(Ro);default:return}}var Qp=6e4,fS=[Fe,nr,at,Ct],gS=["inputResponses","requestState"];function hp(e,t){let r=e.params;if(!go(r))return{message:e,lifted:{}};let n=r._meta,o=go(n)?fS.filter(c=>c in n):[],a=t==="request"?gS.filter(c=>c in r):[];if(o.length===0&&a.length===0)return{message:e,lifted:{}};let i={},l={...r};if(o.length>0&&go(n)){let c={},u={...n};for(let m of o)c[m]=n[m],delete u[m];i.envelope=c,Object.keys(u).length>0?l._meta=u:delete l._meta}for(let c of a)c==="inputResponses"&&(i.inputResponses=l[c]),c==="requestState"&&(i.requestState=l[c]),delete l[c];return{message:{...e,params:l},lifted:i}}function fp(e,t){let r=e.validateResult(t,void 0);if(!(!r.ok&&r.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(n){let o=e.validateResult(t,n);return o.ok?{value:o.value}:{issues:[{message:o.reason==="invalid"?o.message:`not-in-era: ${t}`}]}}}}}function wo(e){return()=>e}var yS=wo(void 0);function ml(e,t){return{...e,mcpReq:{...e.mcpReq,requestState:wo(t)}}}var em;function tm(e,t){em(e,t)}var hl=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{em=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Dn,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new le(pe.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new le(pe.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});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 r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{n?.(o,a),it(o)||ct(o)?this._onresponse(o):Xe(o)?this._onrequest(o,a):ui(o)?this._onnotification(o,a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new le(pe.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let n of e.values())n(r);for(let n of t.values())n.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=hp(e,"notification"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let i=ip(t.classification);if(i!==n.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${i} but this instance serves ${n.era}`));return}}if(Gc(r.method)&&!n.hasNotificationMethod(r.method))return;let o=this._notificationHandlers.get(r.method),a=this.fallbackNotificationHandler;o===void 0&&a===void 0||Promise.resolve().then(()=>o===void 0?a(r):o(r,n)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,t){let{message:r,lifted:n}=hp(e,"request"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let a=this._transport,i=(P,b,h)=>{let $={jsonrpc:"2.0",id:r.id,error:{code:P,message:b,...h!==void 0&&{data:h}}};a?.send($).catch(v=>this._onerror(new Error(`Failed to send an error response: ${v}`)))};if(t?.classification!==void 0){let P=ip(t.classification);if(P!==o.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${P} but this instance serves ${o.era}`));let b=t.classification.revision??P;i(G.UnsupportedProtocolVersion,`Unsupported protocol version: ${b}`,{supported:this._supportedProtocolVersions,requested:b});return}}if(Fc(r.method)&&!o.hasRequestMethod(r.method)&&!(cp(r.method)&&this._customSchemaRequestMethods.has(r.method))){i(G.MethodNotFound,"Method not found");return}let l=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(l===void 0){i(G.MethodNotFound,"Method not found");return}let c=o.checkInboundEnvelope(n);if(c!==void 0){i(G.InvalidParams,c);return}let u=(P,b)=>this._notificationViaCodec(this._resolveOutboundCodec(P.method),P,{...b,relatedRequestId:r.id}),m=(P,b,h)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(P.method),P,b,{...h,relatedRequestId:r.id}),f=new AbortController;this._requestHandlerAbortControllers.set(r.id,f);let y=n.inputResponses===void 0?void 0:SS(n.inputResponses),R={sessionId:a?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...n.envelope!==void 0&&{envelope:n.envelope},...y!==void 0&&{inputResponses:y.accepted},...y!==void 0&&y.droppedKeys.length>0&&{droppedInputResponseKeys:y.droppedKeys},requestState:n.requestState===void 0?yS:wo(n.requestState),signal:f.signal,send:(P,b,h)=>{let $=this._resolveOutboundCodec(P.method);if(this._assertOutboundRequestInEra($,P.method),Br(b))return m(P,b,h);let v=fp($,P.method);if(v===void 0)throw new TypeError(`'${P.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return m(P,v,b)},notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},S=this.buildContext(R,t);Promise.resolve().then(()=>l(r,S)).then(async P=>{if(f.signal.aborted)return;let b;try{b=o.encodeResult(r.method,P,this._outboundServerInfo())}catch($){this._onerror(new Error(`Failed to encode result for ${r.method}: ${$}`)),i(G.InternalError,"Internal error");return}let h={result:b,jsonrpc:"2.0",id:r.id};await a?.send(h)},async P=>{if(f.signal.aborted)return;let b=Number.isSafeInteger(P.code)?P.code:G.InternalError,h={jsonrpc:"2.0",id:r.id,error:{code:o.encodeErrorCode(b),message:P.message??"Internal error",...P.data!==void 0&&{data:P.data}}};await a?.send(h)}).catch(P=>this._onerror(new Error(`Failed to send response: ${P}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===f&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(l){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),a(l);return}o(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),it(e)?r(e):r(te.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let n=this._resolveOutboundCodec(e.method);if(Br(t))return cp(e.method)||this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r);this._assertOutboundRequestInEra(n,e.method);let o=fp(n,e.method);if(o===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(n,e,o,t)}_negotiatedWireCodec(){return ht(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=hS(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Fc(t)&&!e.hasRequestMethod(t))throw new le(pe.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let n=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r)}_requestWithSchemaViaCodec(e,t,r,n){let{relatedRequestId:o,resumptionToken:a,onresumptiontoken:i,headers:l}=n??{},c=Date.now(),u,m;return new Promise((f,y)=>{let R=T=>{y(T)};if(!this._transport){R(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(T){R(T);return}if(n?.signal?.aborted){let T=n.signal.reason;throw T instanceof le?T:new le(pe.RequestTimeout,String(T))}let S=e.era===Ro&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,P=this._requestMessageId++;m=P;let b={...t,jsonrpc:"2.0",id:P};n?.onprogress&&(this._progressHandlers.set(P,n.onprogress),b.params={...t.params,_meta:{...t.params?._meta,progressToken:P}});let h=this._envelopeOutbound(b),$=!1,v=T=>{$||(this._progressHandlers.delete(P),S===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:P,reason:String(T)}}),{relatedRequestId:o,resumptionToken:a,onresumptiontoken:i}).catch(_=>this._onerror(new Error(`Failed to send cancellation: ${_}`))):S.abort(),y(T instanceof le?T:new le(pe.RequestTimeout,String(T))))};this._responseHandlers.set(P,T=>{if(n?.signal?.aborted)return;if($=!0,T instanceof Error)return y(T);let _;try{_=e.decodeResult(t.method,T.result)}catch(M){return y(M instanceof Error?M:new Error(String(M)))}if(_.kind==="invalid")return y(_.error);if(_.kind==="input_required"){if(n?.allowInputRequired===!0)return f(vS(_));let M={codec:e,request:t,resultSchema:r,options:n,flowStartedAt:c,retry:(U,q)=>this._requestWithSchemaViaCodec(e,U===void 0?{method:t.method}:{method:t.method,params:U},r,q)};return f(this._resolveNonCompleteResult(_,M))}let C=_.result;ir(r,C).then(M=>{M.success?f(M.data):y(new le(pe.InvalidResult,`Invalid result for ${t.method}: ${M.error}`))},y)}),u=()=>v(n?.signal?.reason),n?.signal?.addEventListener("abort",u,{once:!0});let z=n?.timeout??Qp,I=()=>v(new le(pe.RequestTimeout,"Request timed out",{timeout:z}));this._setupTimeout(P,z,n?.maxTotalTimeout,I,n?.resetTimeoutOnProgress??!1),this._transport.send(h,{relatedRequestId:o,resumptionToken:a,onresumptiontoken:i,headers:l,requestSignal:S?.signal}).catch(T=>{this._progressHandlers.delete(P),y(T)})}).finally(()=>{u&&n?.signal?.removeEventListener("abort",u),m!==void 0&&(this._responseHandlers.delete(m),this._cleanupTimeout(m))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new le(pe.NotConnected,"Not connected");if(Gc(t.method)&&!e.hasNotificationMethod(t.method))throw new le(pe.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let n=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(n,r).catch(o=>this._onerror(o))});return}await this._transport.send(n,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let n;if(typeof t=="function"){if(!Fc(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);n=(o,a)=>{let i=this._negotiatedWireCodec(),l=i.validateRequest(e,o);if(!l.ok&&l.reason==="not-in-era"&&(l=i.validateInputRequest(e,o)),!l.ok)throw l.reason==="not-in-era"?new te(G.InternalError,`No wire schema for ${e} in the resolved era`):new Error(l.message);return Promise.resolve(t(l.value,a))}}else if(r)n=async(o,a)=>{let i=await ir(t.params,{...o.params});if(!i.success)throw new te(G.InvalidParams,`Invalid params for ${e}: ${i.error}`);return r(i.data,a)};else throw new TypeError("setRequestHandler: handler is required");typeof t=="function"?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,n))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t=="function"){if(!Gc(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,o)=>{let a=o.validateNotification(e,n);if(!a.ok)throw a.reason==="not-in-era"?new te(G.InternalError,`No wire schema for ${e} in the resolved era`):new Error(a.message);return Promise.resolve(t(a.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async n=>{let o=await ir(t.params,{...n.params});if(!o.success)throw new te(G.InvalidParams,`Invalid params for notification ${e}: ${o.error}`);await r(o.data,n)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function go(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fl(e,t){let r={...e};for(let n in t){let o=n,a=t[o];if(a===void 0)continue;let i=r[o];r[o]=go(i)&&go(a)?{...i,...a}:a}return r}function gp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function SS(e){let t={},r=[];if(!gp(e))return{accepted:t,droppedKeys:r};for(let[n,o]of Object.entries(e)){if(!gp(o)||"method"in o||"result"in o){r.push(n);continue}t[n]=o}return{accepted:t,droppedKeys:r}}function vS(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}var _S=V(e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=o;function o(l){if(!l)throw new TypeError("argument string is required");var c=typeof l=="object"?a(l):l;if(typeof c!="string")throw new TypeError("argument string is required to be a string");var u=c.indexOf(";"),m=u!==-1?c.slice(0,u).trim():c.trim();if(!n.test(m))throw new TypeError("invalid media type");var f=new i(m.toLowerCase());if(u!==-1){var y,R,S;for(t.lastIndex=u;R=t.exec(c);){if(R.index!==u)throw new TypeError("invalid parameter format");u+=R[0].length,y=R[1].toLowerCase(),S=R[2],S.charCodeAt(0)===34&&(S=S.slice(1,-1),S.indexOf("\\")!==-1&&(S=S.replace(r,"$1"))),f.parameters[y]=S}if(u!==c.length)throw new TypeError("invalid parameter format")}return f}function a(l){var c;if(typeof l.getHeader=="function"?c=l.getHeader("content-type"):typeof l.headers=="object"&&(c=l.headers&&l.headers["content-type"]),typeof c!="string")throw new TypeError("content-type header is missing from object");return c}function i(l){this.parameters=Object.create(null),this.type=l}}),bS=ds(_S(),1);function gl(e){if(e)try{return bS.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}function Eo(e){return e==="application/json"?!0:gl(e)==="application/json"}var RS=10*1024*1024;var wS=/^[A-Za-z0-9._-]{1,128}$/;function ES(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"),!wS.test(e)){let r=[...e].filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,a)=>a.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function TS(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);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 yl(e){let t=ES(e);return TS(e,t.warnings),t.isValid}function $S(e){return typeof e=="object"&&e!==null&&"_zod"in e}function zS(e){return typeof e=="object"&&e!==null&&!("_zod"in e)&&"_def"in e&&typeof e._def?.typeName=="string"}function PS(e){if(typeof e!="object"||e===null||Br(e))return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.values(e).every(r=>$S(r))}function hi(e){if(e!==void 0){if(PS(e))return s.object(e);if(typeof e=="object"&&e!==null&&!Br(e)&&Object.values(e).some(t=>zS(t)))throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!Br(e))throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return e}}var gi=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var r=class extends t{constructor(h){if(super(),!e.IDENTIFIER.test(h))throw new Error("CodeGen: name must be a valid identifier");this.str=h}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=r;var n=class extends t{constructor(h){super(),this._items=typeof h=="string"?[h]:h}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let h=this._items[0];return h===""||h==='""'}get str(){var h;return(h=this._str)!==null&&h!==void 0?h:this._str=this._items.reduce(($,v)=>`${$}${v}`,"")}get names(){var h;return(h=this._names)!==null&&h!==void 0?h:this._names=this._items.reduce(($,v)=>(v instanceof r&&($[v.str]=($[v.str]||0)+1),$),{})}};e._Code=n,e.nil=new n("");function o(h,...$){let v=[h[0]],z=0;for(;z<$.length;)l(v,$[z]),v.push(h[++z]);return new n(v)}e._=o;let a=new n("+");function i(h,...$){let v=[R(h[0])],z=0;for(;z<$.length;)v.push(a),l(v,$[z]),v.push(a,R(h[++z]));return c(v),new n(v)}e.str=i;function l(h,$){$ instanceof n?h.push(...$._items):$ instanceof r?h.push($):h.push(f($))}e.addCodeArg=l;function c(h){let $=1;for(;$<h.length-1;){if(h[$]===a){let v=u(h[$-1],h[$+1]);if(v!==void 0){h.splice($-1,3,v);continue}h[$++]="+"}$++}}function u(h,$){if($==='""')return h;if(h==='""')return $;if(typeof h=="string")return $ instanceof r||h[h.length-1]!=='"'?void 0:typeof $!="string"?`${h.slice(0,-1)}${$}"`:$[0]==='"'?h.slice(0,-1)+$.slice(1):void 0;if(typeof $=="string"&&$[0]==='"'&&!(h instanceof r))return`"${h}${$.slice(1)}`}function m(h,$){return $.emptyStr()?h:h.emptyStr()?$:i`${h}${$}`}e.strConcat=m;function f(h){return typeof h=="number"||typeof h=="boolean"||h===null?h:R(Array.isArray(h)?h.join(","):h)}function y(h){return new n(R(h))}e.stringify=y;function R(h){return JSON.stringify(h).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=R;function S(h){return typeof h=="string"&&e.IDENTIFIER.test(h)?new n(`.${h}`):o`[${h}]`}e.getProperty=S;function P(h){if(typeof h=="string"&&e.IDENTIFIER.test(h))return new n(`${h}`);throw new Error(`CodeGen: invalid export name: ${h}, use explicit $id name mapping`)}e.getEsmExportName=P;function b(h){return new n(h.toString())}e.regexpCode=b}),rm=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=gi();var r=class extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}},n;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};var o=class{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){let u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,m;if(!((m=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||m===void 0)&&m.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}};e.Scope=o;var a=class extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:m}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${m}]`}};e.ValueScopeName=a;let i=(0,t._)`\n`;var l=class extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?i:t.nil}}get(){return this._scope}name(c){return new a(c,this._newName(c))}value(c,u){var m;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let f=this.toName(c),{prefix:y}=f,R=(m=u.key)!==null&&m!==void 0?m:u.ref,S=this._values[y];if(S){let h=S.get(R);if(h)return h}else S=this._values[y]=new Map;S.set(R,f);let P=this._scope[y]||(this._scope[y]=[]),b=P.length;return P[b]=u.ref,f.setValue(u,{property:y,itemIndex:b}),f}getValue(c,u){let m=this._values[c];if(m)return m.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,m=>{if(m.scopePath===void 0)throw new Error(`CodeGen: name "${m}" has no value`);return(0,t._)`${c}${m.scopePath}`})}scopeCode(c=this._values,u,m){return this._reduceValues(c,f=>{if(f.value===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return f.value.code},u,m)}_reduceValues(c,u,m={},f){let y=t.nil;for(let R in c){let S=c[R];if(!S)continue;let P=m[R]=m[R]||new Map;S.forEach(b=>{if(P.has(b))return;P.set(b,n.Started);let h=u(b);if(h){let $=this.opts.es5?e.varKinds.var:e.varKinds.const;y=(0,t._)`${y}${$} ${b} = ${h};${this.opts._n}`}else if(h=f?.(b))y=(0,t._)`${y}${h}${this.opts._n}`;else throw new r(b);P.set(b,n.Completed)})}return y}};e.ValueScope=l}),de=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=gi(),r=rm();var n=gi();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=rm();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.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(p,g){return this}},i=class extends a{constructor(p,g,w){super(),this.varKind=p,this.name=g,this.rhs=w}render({es5:p,_n:g}){let w=p?r.varKinds.var:this.varKind,A=this.rhs===void 0?"":` = ${this.rhs}`;return`${w} ${this.name}${A};`+g}optimizeNames(p,g){if(p[this.name.str])return this.rhs&&(this.rhs=F(this.rhs,p,g)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},l=class extends a{constructor(p,g,w){super(),this.lhs=p,this.rhs=g,this.sideEffects=w}render({_n:p}){return`${this.lhs} = ${this.rhs};`+p}optimizeNames(p,g){if(!(this.lhs instanceof t.Name&&!p[this.lhs.str]&&!this.sideEffects))return this.rhs=F(this.rhs,p,g),this}get names(){return W(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends l{constructor(p,g,w,A){super(p,w,A),this.op=g}render({_n:p}){return`${this.lhs} ${this.op}= ${this.rhs};`+p}},u=class extends a{constructor(p){super(),this.label=p,this.names={}}render({_n:p}){return`${this.label}:`+p}},m=class extends a{constructor(p){super(),this.label=p,this.names={}}render({_n:p}){return`break${this.label?` ${this.label}`:""};`+p}},f=class extends a{constructor(p){super(),this.error=p}render({_n:p}){return`throw ${this.error};`+p}get names(){return this.error.names}},y=class extends a{constructor(p){super(),this.code=p}render({_n:p}){return`${this.code};`+p}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(p,g){return this.code=F(this.code,p,g),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},R=class extends a{constructor(p=[]){super(),this.nodes=p}render(p){return this.nodes.reduce((g,w)=>g+w.render(p),"")}optimizeNodes(){let{nodes:p}=this,g=p.length;for(;g--;){let w=p[g].optimizeNodes();Array.isArray(w)?p.splice(g,1,...w):w?p[g]=w:p.splice(g,1)}return p.length>0?this:void 0}optimizeNames(p,g){let{nodes:w}=this,A=w.length;for(;A--;){let x=w[A];x.optimizeNames(p,g)||(ie(p,x.names),w.splice(A,1))}return w.length>0?this:void 0}get names(){return this.nodes.reduce((p,g)=>D(p,g.names),{})}},S=class extends R{render(p){return"{"+p._n+super.render(p)+"}"+p._n}},P=class extends R{},b=class extends S{};b.kind="else";var h=class fi extends S{constructor(g,w){super(w),this.condition=g}render(g){let w=`if(${this.condition})`+super.render(g);return this.else&&(w+="else "+this.else.render(g)),w}optimizeNodes(){super.optimizeNodes();let g=this.condition;if(g===!0)return this.nodes;let w=this.else;if(w){let A=w.optimizeNodes();w=this.else=Array.isArray(A)?new b(A):A}if(w)return g===!1?w instanceof fi?w:w.nodes:this.nodes.length?this:new fi(he(g),w instanceof fi?[w]:w.nodes);if(!(g===!1||!this.nodes.length))return this}optimizeNames(g,w){var A;if(this.else=(A=this.else)===null||A===void 0?void 0:A.optimizeNames(g,w),!!(super.optimizeNames(g,w)||this.else))return this.condition=F(this.condition,g,w),this}get names(){let g=super.names;return W(g,this.condition),this.else&&D(g,this.else.names),g}};h.kind="if";var $=class extends S{};$.kind="for";var v=class extends ${constructor(p){super(),this.iteration=p}render(p){return`for(${this.iteration})`+super.render(p)}optimizeNames(p,g){if(super.optimizeNames(p,g))return this.iteration=F(this.iteration,p,g),this}get names(){return D(super.names,this.iteration.names)}},z=class extends ${constructor(p,g,w,A){super(),this.varKind=p,this.name=g,this.from=w,this.to=A}render(p){let g=p.es5?r.varKinds.var:this.varKind,{name:w,from:A,to:x}=this;return`for(${g} ${w}=${A}; ${w}<${x}; ${w}++)`+super.render(p)}get names(){return W(W(super.names,this.from),this.to)}},I=class extends ${constructor(p,g,w,A){super(),this.loop=p,this.varKind=g,this.name=w,this.iterable=A}render(p){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(p)}optimizeNames(p,g){if(super.optimizeNames(p,g))return this.iterable=F(this.iterable,p,g),this}get names(){return D(super.names,this.iterable.names)}},T=class extends S{constructor(p,g,w){super(),this.name=p,this.args=g,this.async=w}render(p){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(p)}};T.kind="func";var _=class extends R{render(p){return"return "+super.render(p)}};_.kind="return";var C=class extends S{render(p){let g="try"+super.render(p);return this.catch&&(g+=this.catch.render(p)),this.finally&&(g+=this.finally.render(p)),g}optimizeNodes(){var p,g;return super.optimizeNodes(),(p=this.catch)===null||p===void 0||p.optimizeNodes(),(g=this.finally)===null||g===void 0||g.optimizeNodes(),this}optimizeNames(p,g){var w,A;return super.optimizeNames(p,g),(w=this.catch)===null||w===void 0||w.optimizeNames(p,g),(A=this.finally)===null||A===void 0||A.optimizeNames(p,g),this}get names(){let p=super.names;return this.catch&&D(p,this.catch.names),this.finally&&D(p,this.finally.names),p}},M=class extends S{constructor(p){super(),this.error=p}render(p){return`catch(${this.error})`+super.render(p)}};M.kind="catch";var U=class extends S{render(p){return"finally"+super.render(p)}};U.kind="finally";var q=class{constructor(p,g={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...g,_n:g.lines?`
18
+ `:""},this._extScope=p,this._scope=new r.Scope({parent:p}),this._nodes=[new P]}toString(){return this._root.render(this.opts)}name(p){return this._scope.name(p)}scopeName(p){return this._extScope.name(p)}scopeValue(p,g){let w=this._extScope.value(p,g);return(this._values[w.prefix]||(this._values[w.prefix]=new Set)).add(w),w}getScopeValue(p,g){return this._extScope.getValue(p,g)}scopeRefs(p){return this._extScope.scopeRefs(p,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(p,g,w,A){let x=this._scope.toName(g);return w!==void 0&&A&&(this._constants[x.str]=w),this._leafNode(new i(p,x,w)),x}const(p,g,w){return this._def(r.varKinds.const,p,g,w)}let(p,g,w){return this._def(r.varKinds.let,p,g,w)}var(p,g,w){return this._def(r.varKinds.var,p,g,w)}assign(p,g,w){return this._leafNode(new l(p,g,w))}add(p,g){return this._leafNode(new c(p,e.operators.ADD,g))}code(p){return typeof p=="function"?p():p!==t.nil&&this._leafNode(new y(p)),this}object(...p){let g=["{"];for(let[w,A]of p)g.length>1&&g.push(","),g.push(w),(w!==A||this.opts.es5)&&(g.push(":"),(0,t.addCodeArg)(g,A));return g.push("}"),new t._Code(g)}if(p,g,w){if(this._blockNode(new h(p)),g&&w)this.code(g).else().code(w).endIf();else if(g)this.code(g).endIf();else if(w)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(p){return this._elseNode(new h(p))}else(){return this._elseNode(new b)}endIf(){return this._endBlockNode(h,b)}_for(p,g){return this._blockNode(p),g&&this.code(g).endFor(),this}for(p,g){return this._for(new v(p),g)}forRange(p,g,w,A,x=this.opts.es5?r.varKinds.var:r.varKinds.let){let J=this._scope.toName(p);return this._for(new z(x,J,g,w),()=>A(J))}forOf(p,g,w,A=r.varKinds.const){let x=this._scope.toName(p);if(this.opts.es5){let J=g instanceof t.Name?g:this.var("_arr",g);return this.forRange("_i",0,(0,t._)`${J}.length`,K=>{this.var(x,(0,t._)`${J}[${K}]`),w(x)})}return this._for(new I("of",A,x,g),()=>w(x))}forIn(p,g,w,A=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(p,(0,t._)`Object.keys(${g})`,w);let x=this._scope.toName(p);return this._for(new I("in",A,x,g),()=>w(x))}endFor(){return this._endBlockNode($)}label(p){return this._leafNode(new u(p))}break(p){return this._leafNode(new m(p))}return(p){let g=new _;if(this._blockNode(g),this.code(p),g.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(_)}try(p,g,w){if(!g&&!w)throw new Error('CodeGen: "try" without "catch" and "finally"');let A=new C;if(this._blockNode(A),this.code(p),g){let x=this.name("e");this._currNode=A.catch=new M(x),g(x)}return w&&(this._currNode=A.finally=new U,this.code(w)),this._endBlockNode(M,U)}throw(p){return this._leafNode(new f(p))}block(p,g){return this._blockStarts.push(this._nodes.length),p&&this.code(p).endBlock(g),this}endBlock(p){let g=this._blockStarts.pop();if(g===void 0)throw new Error("CodeGen: not in self-balancing block");let w=this._nodes.length-g;if(w<0||p!==void 0&&w!==p)throw new Error(`CodeGen: wrong number of nodes: ${w} vs ${p} expected`);return this._nodes.length=g,this}func(p,g=t.nil,w,A){return this._blockNode(new T(p,g,w)),A&&this.code(A).endFunc(),this}endFunc(){return this._endBlockNode(T)}optimize(p=1){for(;p-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(p){return this._currNode.nodes.push(p),this}_blockNode(p){this._currNode.nodes.push(p),this._nodes.push(p)}_endBlockNode(p,g){let w=this._currNode;if(w instanceof p||g&&w instanceof g)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${g?`${p.kind}/${g.kind}`:p.kind}"`)}_elseNode(p){let g=this._currNode;if(!(g instanceof h))throw new Error('CodeGen: "else" without "if"');return this._currNode=g.else=p,this}get _root(){return this._nodes[0]}get _currNode(){let p=this._nodes;return p[p.length-1]}set _currNode(p){let g=this._nodes;g[g.length-1]=p}};e.CodeGen=q;function D(p,g){for(let w in g)p[w]=(p[w]||0)+(g[w]||0);return p}function W(p,g){return g instanceof t._CodeOrName?D(p,g.names):p}function F(p,g,w){if(p instanceof t.Name)return A(p);if(!x(p))return p;return new t._Code(p._items.reduce((J,K)=>(K instanceof t.Name&&(K=A(K)),K instanceof t._Code?J.push(...K._items):J.push(K),J),[]));function A(J){let K=w[J.str];return K===void 0||g[J.str]!==1?J:(delete g[J.str],K)}function x(J){return J instanceof t._Code&&J._items.some(K=>K instanceof t.Name&&g[K.str]===1&&w[K.str]!==void 0)}}function ie(p,g){for(let w in g)p[w]=(p[w]||0)-(g[w]||0)}function he(p){return typeof p=="boolean"||typeof p=="number"||p===null?!p:(0,t._)`!${E(p)}`}e.not=he;let ge=j(e.operators.AND);function _e(...p){return p.reduce(ge)}e.and=_e;let ue=j(e.operators.OR);function O(...p){return p.reduce(ue)}e.or=O;function j(p){return(g,w)=>g===t.nil?w:w===t.nil?g:(0,t._)`${E(g)} ${p} ${E(w)}`}function E(p){return p instanceof t.Name?p:(0,t._)`(${p})`}}),ye=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=de(),r=gi();function n(T){let _={};for(let C of T)_[C]=!0;return _}e.toHash=n;function o(T,_){return typeof _=="boolean"?_:Object.keys(_).length===0?!0:(a(T,_),!i(_,T.self.RULES.all))}e.alwaysValidSchema=o;function a(T,_=T.schema){let{opts:C,self:M}=T;if(!C.strictSchema||typeof _=="boolean")return;let U=M.RULES.keywords;for(let q in _)U[q]||I(T,`unknown keyword: "${q}"`)}e.checkUnknownRules=a;function i(T,_){if(typeof T=="boolean")return!T;for(let C in T)if(_[C])return!0;return!1}e.schemaHasRules=i;function l(T,_){if(typeof T=="boolean")return!T;for(let C in T)if(C!=="$ref"&&_.all[C])return!0;return!1}e.schemaHasRulesButRef=l;function c({topSchemaRef:T,schemaPath:_},C,M,U){if(!U){if(typeof C=="number"||typeof C=="boolean")return C;if(typeof C=="string")return(0,t._)`${C}`}return(0,t._)`${T}${_}${(0,t.getProperty)(M)}`}e.schemaRefOrVal=c;function u(T){return y(decodeURIComponent(T))}e.unescapeFragment=u;function m(T){return encodeURIComponent(f(T))}e.escapeFragment=m;function f(T){return typeof T=="number"?`${T}`:T.replace(/~/g,"~0").replace(/\//g,"~1")}e.escapeJsonPointer=f;function y(T){return T.replace(/~1/g,"/").replace(/~0/g,"~")}e.unescapeJsonPointer=y;function R(T,_){if(Array.isArray(T))for(let C of T)_(C);else _(T)}e.eachItem=R;function S({mergeNames:T,mergeToName:_,mergeValues:C,resultToName:M}){return(U,q,D,W)=>{let F=D===void 0?q:D instanceof t.Name?(q instanceof t.Name?T(U,q,D):_(U,q,D),D):q instanceof t.Name?(_(U,D,q),q):C(q,D);return W===t.Name&&!(F instanceof t.Name)?M(U,F):F}}e.mergeEvaluated={props:S({mergeNames:(T,_,C)=>T.if((0,t._)`${C} !== true && ${_} !== undefined`,()=>{T.if((0,t._)`${_} === true`,()=>T.assign(C,!0),()=>T.assign(C,(0,t._)`${C} || {}`).code((0,t._)`Object.assign(${C}, ${_})`))}),mergeToName:(T,_,C)=>T.if((0,t._)`${C} !== true`,()=>{_===!0?T.assign(C,!0):(T.assign(C,(0,t._)`${C} || {}`),b(T,C,_))}),mergeValues:(T,_)=>T===!0?!0:{...T,..._},resultToName:P}),items:S({mergeNames:(T,_,C)=>T.if((0,t._)`${C} !== true && ${_} !== undefined`,()=>T.assign(C,(0,t._)`${_} === true ? true : ${C} > ${_} ? ${C} : ${_}`)),mergeToName:(T,_,C)=>T.if((0,t._)`${C} !== true`,()=>T.assign(C,_===!0?!0:(0,t._)`${C} > ${_} ? ${C} : ${_}`)),mergeValues:(T,_)=>T===!0?!0:Math.max(T,_),resultToName:(T,_)=>T.var("items",_)})};function P(T,_){if(_===!0)return T.var("props",!0);let C=T.var("props",(0,t._)`{}`);return _!==void 0&&b(T,C,_),C}e.evaluatedPropsToName=P;function b(T,_,C){Object.keys(C).forEach(M=>T.assign((0,t._)`${_}${(0,t.getProperty)(M)}`,!0))}e.setEvaluated=b;let h={};function $(T,_){return T.scopeValue("func",{ref:_,code:h[_.code]||(h[_.code]=new r._Code(_.code))})}e.useFunc=$;var v;(function(T){T[T.Num=0]="Num",T[T.Str=1]="Str"})(v||(e.Type=v={}));function z(T,_,C){if(T instanceof t.Name){let M=_===v.Num;return C?M?(0,t._)`"[" + ${T} + "]"`:(0,t._)`"['" + ${T} + "']"`:M?(0,t._)`"/" + ${T}`:(0,t._)`"/" + ${T}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return C?(0,t.getProperty)(T).toString():"/"+f(T)}e.getErrorPath=z;function I(T,_,C=T.opts.strictSchema){if(C){if(_=`strict mode: ${_}`,C===!0)throw new Error(_);T.self.logger.warn(_)}}e.checkStrictMode=I}),Ze=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r={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")};e.default=r}),Si=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=de(),r=ye(),n=Ze();e.keywordError={message:({keyword:b})=>(0,t.str)`must pass "${b}" keyword validation`},e.keyword$DataError={message:({keyword:b,schemaType:h})=>h?(0,t.str)`"${b}" keyword must be ${h} ($data)`:(0,t.str)`"${b}" keyword is invalid ($data)`};function o(b,h=e.keywordError,$,v){let{it:z}=b,{gen:I,compositeRule:T,allErrors:_}=z,C=f(b,h,$);v??(T||_)?c(I,C):u(z,(0,t._)`[${C}]`)}e.reportError=o;function a(b,h=e.keywordError,$){let{it:v}=b,{gen:z,compositeRule:I,allErrors:T}=v;c(z,f(b,h,$)),I||T||u(v,n.default.vErrors)}e.reportExtraError=a;function i(b,h){b.assign(n.default.errors,h),b.if((0,t._)`${n.default.vErrors} !== null`,()=>b.if(h,()=>b.assign((0,t._)`${n.default.vErrors}.length`,h),()=>b.assign(n.default.vErrors,null)))}e.resetErrorsCount=i;function l({gen:b,keyword:h,schemaValue:$,data:v,errsCount:z,it:I}){if(z===void 0)throw new Error("ajv implementation error");let T=b.name("err");b.forRange("i",z,n.default.errors,_=>{b.const(T,(0,t._)`${n.default.vErrors}[${_}]`),b.if((0,t._)`${T}.instancePath === undefined`,()=>b.assign((0,t._)`${T}.instancePath`,(0,t.strConcat)(n.default.instancePath,I.errorPath))),b.assign((0,t._)`${T}.schemaPath`,(0,t.str)`${I.errSchemaPath}/${h}`),I.opts.verbose&&(b.assign((0,t._)`${T}.schema`,$),b.assign((0,t._)`${T}.data`,v))})}e.extendErrors=l;function c(b,h){let $=b.const("err",h);b.if((0,t._)`${n.default.vErrors} === null`,()=>b.assign(n.default.vErrors,(0,t._)`[${$}]`),(0,t._)`${n.default.vErrors}.push(${$})`),b.code((0,t._)`${n.default.errors}++`)}function u(b,h){let{gen:$,validateName:v,schemaEnv:z}=b;z.$async?$.throw((0,t._)`new ${b.ValidationError}(${h})`):($.assign((0,t._)`${v}.errors`,h),$.return(!1))}let m={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 f(b,h,$){let{createErrors:v}=b.it;return v===!1?(0,t._)`{}`:y(b,h,$)}function y(b,h,$={}){let{gen:v,it:z}=b,I=[R(z,$),S(b,$)];return P(b,h,I),v.object(...I)}function R({errorPath:b},{instancePath:h}){let $=h?(0,t.str)`${b}${(0,r.getErrorPath)(h,r.Type.Str)}`:b;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,$)]}function S({keyword:b,it:{errSchemaPath:h}},{schemaPath:$,parentSchema:v}){let z=v?h:(0,t.str)`${h}/${b}`;return $&&(z=(0,t.str)`${z}${(0,r.getErrorPath)($,r.Type.Str)}`),[m.schemaPath,z]}function P(b,{params:h,message:$},v){let{keyword:z,data:I,schemaValue:T,it:_}=b,{opts:C,propertyName:M,topSchemaRef:U,schemaPath:q}=_;v.push([m.keyword,z],[m.params,typeof h=="function"?h(b):h||(0,t._)`{}`]),C.messages&&v.push([m.message,typeof $=="function"?$(b):$]),C.verbose&&v.push([m.schema,T],[m.parentSchema,(0,t._)`${U}${q}`],[n.default.data,I]),M&&v.push([m.propertyName,M])}}),CS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Si(),r=de(),n=Ze(),o={message:"boolean schema is false"};function a(c){let{gen:u,schema:m,validateName:f}=c;m===!1?l(c,!1):typeof m=="object"&&m.$async===!0?u.return(n.default.data):(u.assign((0,r._)`${f}.errors`,null),u.return(!0))}e.topBoolOrEmptySchema=a;function i(c,u){let{gen:m,schema:f}=c;f===!1?(m.var(u,!1),l(c)):m.var(u,!0)}e.boolOrEmptySchema=i;function l(c,u){let{gen:m,data:f}=c,y={gen:m,keyword:"false schema",data:f,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:c};(0,t.reportError)(y,o,void 0,u)}}),nm=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set(["string","number","integer","boolean","null","object","array"]);function r(o){return typeof o=="string"&&t.has(o)}e.isJSONType=r;function n(){let o={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...o,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},o.number,o.string,o.array,o.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=n}),om=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:o,self:a},i){let l=a.RULES.types[i];return l&&l!==!0&&r(o,l)}e.schemaHasRulesForType=t;function r(o,a){return a.rules.some(i=>n(o,i))}e.shouldUseGroup=r;function n(o,a){var i;return o[a.keyword]!==void 0||((i=a.definition.implements)===null||i===void 0?void 0:i.some(l=>o[l]!==void 0))}e.shouldUseRule=n}),yi=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=nm(),r=om(),n=Si(),o=de(),a=ye();var i;(function(v){v[v.Correct=0]="Correct",v[v.Wrong=1]="Wrong"})(i||(e.DataType=i={}));function l(v){let z=c(v.type);if(z.includes("null")){if(v.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!z.length&&v.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');v.nullable===!0&&z.push("null")}return z}e.getSchemaTypes=l;function c(v){let z=Array.isArray(v)?v:v?[v]:[];if(z.every(t.isJSONType))return z;throw new Error("type must be JSONType or JSONType[]: "+z.join(","))}e.getJSONTypes=c;function u(v,z){let{gen:I,data:T,opts:_}=v,C=f(z,_.coerceTypes),M=z.length>0&&!(C.length===0&&z.length===1&&(0,r.schemaHasRulesForType)(v,z[0]));if(M){let U=P(z,T,_.strictNumbers,i.Wrong);I.if(U,()=>{C.length?y(v,z,C):h(v)})}return M}e.coerceAndCheckDataType=u;let m=new Set(["string","number","integer","boolean","null"]);function f(v,z){return z?v.filter(I=>m.has(I)||z==="array"&&I==="array"):[]}function y(v,z,I){let{gen:T,data:_,opts:C}=v,M=T.let("dataType",(0,o._)`typeof ${_}`),U=T.let("coerced",(0,o._)`undefined`);C.coerceTypes==="array"&&T.if((0,o._)`${M} == 'object' && Array.isArray(${_}) && ${_}.length == 1`,()=>T.assign(_,(0,o._)`${_}[0]`).assign(M,(0,o._)`typeof ${_}`).if(P(z,_,C.strictNumbers),()=>T.assign(U,_))),T.if((0,o._)`${U} !== undefined`);for(let D of I)(m.has(D)||D==="array"&&C.coerceTypes==="array")&&q(D);T.else(),h(v),T.endIf(),T.if((0,o._)`${U} !== undefined`,()=>{T.assign(_,U),R(v,U)});function q(D){switch(D){case"string":T.elseIf((0,o._)`${M} == "number" || ${M} == "boolean"`).assign(U,(0,o._)`"" + ${_}`).elseIf((0,o._)`${_} === null`).assign(U,(0,o._)`""`);return;case"number":T.elseIf((0,o._)`${M} == "boolean" || ${_} === null
19
+ || (${M} == "string" && ${_} && ${_} == +${_})`).assign(U,(0,o._)`+${_}`);return;case"integer":T.elseIf((0,o._)`${M} === "boolean" || ${_} === null
20
+ || (${M} === "string" && ${_} && ${_} == +${_} && !(${_} % 1))`).assign(U,(0,o._)`+${_}`);return;case"boolean":T.elseIf((0,o._)`${_} === "false" || ${_} === 0 || ${_} === null`).assign(U,!1).elseIf((0,o._)`${_} === "true" || ${_} === 1`).assign(U,!0);return;case"null":T.elseIf((0,o._)`${_} === "" || ${_} === 0 || ${_} === false`),T.assign(U,null);return;case"array":T.elseIf((0,o._)`${M} === "string" || ${M} === "number"
21
+ || ${M} === "boolean" || ${_} === null`).assign(U,(0,o._)`[${_}]`)}}}function R({gen:v,parentData:z,parentDataProperty:I},T){v.if((0,o._)`${z} !== undefined`,()=>v.assign((0,o._)`${z}[${I}]`,T))}function S(v,z,I,T=i.Correct){let _=T===i.Correct?o.operators.EQ:o.operators.NEQ,C;switch(v){case"null":return(0,o._)`${z} ${_} null`;case"array":C=(0,o._)`Array.isArray(${z})`;break;case"object":C=(0,o._)`${z} && typeof ${z} == "object" && !Array.isArray(${z})`;break;case"integer":C=M((0,o._)`!(${z} % 1) && !isNaN(${z})`);break;case"number":C=M();break;default:return(0,o._)`typeof ${z} ${_} ${v}`}return T===i.Correct?C:(0,o.not)(C);function M(U=o.nil){return(0,o.and)((0,o._)`typeof ${z} == "number"`,U,I?(0,o._)`isFinite(${z})`:o.nil)}}e.checkDataType=S;function P(v,z,I,T){if(v.length===1)return S(v[0],z,I,T);let _,C=(0,a.toHash)(v);if(C.array&&C.object){let M=(0,o._)`typeof ${z} != "object"`;_=C.null?M:(0,o._)`!${z} || ${M}`,delete C.null,delete C.array,delete C.object}else _=o.nil;C.number&&delete C.integer;for(let M in C)_=(0,o.and)(_,S(M,z,I,T));return _}e.checkDataTypes=P;let b={message:({schema:v})=>`must be ${v}`,params:({schema:v,schemaValue:z})=>typeof v=="string"?(0,o._)`{type: ${v}}`:(0,o._)`{type: ${z}}`};function h(v){let z=$(v);(0,n.reportError)(z,b)}e.reportTypeError=h;function $(v){let{gen:z,data:I,schema:T}=v,_=(0,a.schemaRefOrVal)(v,T,"type");return{gen:z,keyword:"type",data:I,schema:T.type,schemaCode:_,schemaValue:_,parentSchema:T,params:{},it:v}}}),kS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=de(),r=ye();function n(a,i){let{properties:l,items:c}=a.schema;if(i==="object"&&l)for(let u in l)o(a,u,l[u].default);else i==="array"&&Array.isArray(c)&&c.forEach((u,m)=>o(a,m,u.default))}e.assignDefaults=n;function o(a,i,l){let{gen:c,compositeRule:u,data:m,opts:f}=a;if(l===void 0)return;let y=(0,t._)`${m}${(0,t.getProperty)(i)}`;if(u){(0,r.checkStrictMode)(a,`default is ignored for: ${y}`);return}let R=(0,t._)`${y} === undefined`;f.useDefaults==="empty"&&(R=(0,t._)`${R} || ${y} === null || ${y} === ""`),c.if(R,(0,t._)`${y} = ${(0,t.stringify)(l)}`)}}),Qe=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=de(),r=ye(),n=Ze(),o=ye();function a(v,z){let{gen:I,data:T,it:_}=v;I.if(f(I,T,z,_.opts.ownProperties),()=>{v.setParams({missingProperty:(0,t._)`${z}`},!0),v.error()})}e.checkReportMissingProp=a;function i({gen:v,data:z,it:{opts:I}},T,_){return(0,t.or)(...T.map(C=>(0,t.and)(f(v,z,C,I.ownProperties),(0,t._)`${_} = ${C}`)))}e.checkMissingProp=i;function l(v,z){v.setParams({missingProperty:z},!0),v.error()}e.reportMissingProp=l;function c(v){return v.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function u(v,z,I){return(0,t._)`${c(v)}.call(${z}, ${I})`}e.isOwnProperty=u;function m(v,z,I,T){let _=(0,t._)`${z}${(0,t.getProperty)(I)} !== undefined`;return T?(0,t._)`${_} && ${u(v,z,I)}`:_}e.propertyInData=m;function f(v,z,I,T){let _=(0,t._)`${z}${(0,t.getProperty)(I)} === undefined`;return T?(0,t.or)(_,(0,t.not)(u(v,z,I))):_}e.noPropertyInData=f;function y(v){return v?Object.keys(v).filter(z=>z!=="__proto__"):[]}e.allSchemaProperties=y;function R(v,z){return y(z).filter(I=>!(0,r.alwaysValidSchema)(v,z[I]))}e.schemaProperties=R;function S({schemaCode:v,data:z,it:{gen:I,topSchemaRef:T,schemaPath:_,errorPath:C},it:M},U,q,D){let W=D?(0,t._)`${v}, ${z}, ${T}${_}`:z,F=[[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,C)],[n.default.parentData,M.parentData],[n.default.parentDataProperty,M.parentDataProperty],[n.default.rootData,n.default.rootData]];M.opts.dynamicRef&&F.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);let ie=(0,t._)`${W}, ${I.object(...F)}`;return q!==t.nil?(0,t._)`${U}.call(${q}, ${ie})`:(0,t._)`${U}(${ie})`}e.callValidateCode=S;let P=(0,t._)`new RegExp`;function b({gen:v,it:{opts:z}},I){let T=z.unicodeRegExp?"u":"",{regExp:_}=z.code,C=_(I,T);return v.scopeValue("pattern",{key:C.toString(),ref:C,code:(0,t._)`${_.code==="new RegExp"?P:(0,o.useFunc)(v,_)}(${I}, ${T})`})}e.usePattern=b;function h(v){let{gen:z,data:I,keyword:T,it:_}=v,C=z.name("valid");if(_.allErrors){let U=z.let("valid",!0);return M(()=>z.assign(U,!1)),U}return z.var(C,!0),M(()=>z.break()),C;function M(U){let q=z.const("len",(0,t._)`${I}.length`);z.forRange("i",0,q,D=>{v.subschema({keyword:T,dataProp:D,dataPropType:r.Type.Num},C),z.if((0,t.not)(C),U)})}}e.validateArray=h;function $(v){let{gen:z,schema:I,keyword:T,it:_}=v;if(!Array.isArray(I))throw new Error("ajv implementation error");if(I.some(U=>(0,r.alwaysValidSchema)(_,U))&&!_.opts.unevaluated)return;let C=z.let("valid",!1),M=z.name("_valid");z.block(()=>I.forEach((U,q)=>{let D=v.subschema({keyword:T,schemaProp:q,compositeRule:!0},M);z.assign(C,(0,t._)`${C} || ${M}`),v.mergeValidEvaluated(D,M)||z.if((0,t.not)(C))})),v.result(C,()=>v.reset(),()=>v.error(!0))}e.validateUnion=$}),IS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=de(),r=Ze(),n=Qe(),o=Si();function a(R,S){let{gen:P,keyword:b,schema:h,parentSchema:$,it:v}=R,z=S.macro.call(v.self,h,$,v),I=m(P,b,z);v.opts.validateSchema!==!1&&v.self.validateSchema(z,!0);let T=P.name("valid");R.subschema({schema:z,schemaPath:t.nil,errSchemaPath:`${v.errSchemaPath}/${b}`,topSchemaRef:I,compositeRule:!0},T),R.pass(T,()=>R.error(!0))}e.macroKeywordCode=a;function i(R,S){var P;let{gen:b,keyword:h,schema:$,parentSchema:v,$data:z,it:I}=R;u(I,S);let T=m(b,h,!z&&S.compile?S.compile.call(I.self,$,v,I):S.validate),_=b.let("valid");R.block$data(_,C),R.ok((P=S.valid)!==null&&P!==void 0?P:_);function C(){if(S.errors===!1)q(),S.modifying&&l(R),D(()=>R.error());else{let W=S.async?M():U();S.modifying&&l(R),D(()=>c(R,W))}}function M(){let W=b.let("ruleErrs",null);return b.try(()=>q((0,t._)`await `),F=>b.assign(_,!1).if((0,t._)`${F} instanceof ${I.ValidationError}`,()=>b.assign(W,(0,t._)`${F}.errors`),()=>b.throw(F))),W}function U(){let W=(0,t._)`${T}.errors`;return b.assign(W,null),q(t.nil),W}function q(W=S.async?(0,t._)`await `:t.nil){let F=I.opts.passContext?r.default.this:r.default.self,ie=!("compile"in S&&!z||S.schema===!1);b.assign(_,(0,t._)`${W}${(0,n.callValidateCode)(R,T,F,ie)}`,S.modifying)}function D(W){var F;b.if((0,t.not)((F=S.valid)!==null&&F!==void 0?F:_),W)}}e.funcKeywordCode=i;function l(R){let{gen:S,data:P,it:b}=R;S.if(b.parentData,()=>S.assign(P,(0,t._)`${b.parentData}[${b.parentDataProperty}]`))}function c(R,S){let{gen:P}=R;P.if((0,t._)`Array.isArray(${S})`,()=>{P.assign(r.default.vErrors,(0,t._)`${r.default.vErrors} === null ? ${S} : ${r.default.vErrors}.concat(${S})`).assign(r.default.errors,(0,t._)`${r.default.vErrors}.length`),(0,o.extendErrors)(R)},()=>R.error())}function u({schemaEnv:R},S){if(S.async&&!R.$async)throw new Error("async keyword in sync schema")}function m(R,S,P){if(P===void 0)throw new Error(`keyword "${S}" failed to compile`);return R.scopeValue("keyword",typeof P=="function"?{ref:P}:{ref:P,code:(0,t.stringify)(P)})}function f(R,S,P=!1){return!S.length||S.some(b=>b==="array"?Array.isArray(R):b==="object"?R&&typeof R=="object"&&!Array.isArray(R):typeof R==b||P&&typeof R>"u")}e.validSchemaType=f;function y({schema:R,opts:S,self:P,errSchemaPath:b},h,$){if(Array.isArray(h.keyword)?!h.keyword.includes($):h.keyword!==$)throw new Error("ajv implementation error");let v=h.dependencies;if(v?.some(z=>!Object.prototype.hasOwnProperty.call(R,z)))throw new Error(`parent schema must have dependencies of ${$}: ${v.join(",")}`);if(h.validateSchema&&!h.validateSchema(R[$])){let z=`keyword "${$}" value is invalid at path "${b}": `+P.errorsText(h.validateSchema.errors);if(S.validateSchema==="log")P.logger.error(z);else throw new Error(z)}}e.validateKeywordUsage=y}),AS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=de(),r=ye();function n(i,{keyword:l,schemaProp:c,schema:u,schemaPath:m,errSchemaPath:f,topSchemaRef:y}){if(l!==void 0&&u!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(l!==void 0){let R=i.schema[l];return c===void 0?{schema:R,schemaPath:(0,t._)`${i.schemaPath}${(0,t.getProperty)(l)}`,errSchemaPath:`${i.errSchemaPath}/${l}`}:{schema:R[c],schemaPath:(0,t._)`${i.schemaPath}${(0,t.getProperty)(l)}${(0,t.getProperty)(c)}`,errSchemaPath:`${i.errSchemaPath}/${l}/${(0,r.escapeFragment)(c)}`}}if(u!==void 0){if(m===void 0||f===void 0||y===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:u,schemaPath:m,topSchemaRef:y,errSchemaPath:f}}throw new Error('either "keyword" or "schema" must be passed')}e.getSubschema=n;function o(i,l,{dataProp:c,dataPropType:u,data:m,dataTypes:f,propertyName:y}){if(m!==void 0&&c!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:R}=l;if(c!==void 0){let{errorPath:P,dataPathArr:b,opts:h}=l;S(R.let("data",(0,t._)`${l.data}${(0,t.getProperty)(c)}`,!0)),i.errorPath=(0,t.str)`${P}${(0,r.getErrorPath)(c,u,h.jsPropertySyntax)}`,i.parentDataProperty=(0,t._)`${c}`,i.dataPathArr=[...b,i.parentDataProperty]}m!==void 0&&(S(m instanceof t.Name?m:R.let("data",m,!0)),y!==void 0&&(i.propertyName=y)),f&&(i.dataTypes=f);function S(P){i.data=P,i.dataLevel=l.dataLevel+1,i.dataTypes=[],l.definedProperties=new Set,i.parentData=l.data,i.dataNames=[...l.dataNames,P]}}e.extendSubschemaData=o;function a(i,{jtdDiscriminator:l,jtdMetadata:c,compositeRule:u,createErrors:m,allErrors:f}){u!==void 0&&(i.compositeRule=u),m!==void 0&&(i.createErrors=m),f!==void 0&&(i.allErrors=f),i.jtdDiscriminator=l,i.jtdMetadata=c}e.extendSubschemaMode=a}),sm=V((e,t)=>{t.exports=function r(n,o){if(n===o)return!0;if(n&&o&&typeof n=="object"&&typeof o=="object"){if(n.constructor!==o.constructor)return!1;var a,i,l;if(Array.isArray(n)){if(a=n.length,a!=o.length)return!1;for(i=a;i--!==0;)if(!r(n[i],o[i]))return!1;return!0}if(n.constructor===RegExp)return n.source===o.source&&n.flags===o.flags;if(n.valueOf!==Object.prototype.valueOf)return n.valueOf()===o.valueOf();if(n.toString!==Object.prototype.toString)return n.toString()===o.toString();if(l=Object.keys(n),a=l.length,a!==Object.keys(o).length)return!1;for(i=a;i--!==0;)if(!Object.prototype.hasOwnProperty.call(o,l[i]))return!1;for(i=a;i--!==0;){var c=l[i];if(!r(n[c],o[c]))return!1}return!0}return n!==n&&o!==o}}),OS=V((e,t)=>{var r=t.exports=function(a,i,l){typeof i=="function"&&(l=i,i={}),l=i.cb||l;var c=typeof l=="function"?l:l.pre||function(){},u=l.post||function(){};n(i,c,u,a,"",a)};r.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},r.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},r.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},r.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 n(a,i,l,c,u,m,f,y,R,S){if(c&&typeof c=="object"&&!Array.isArray(c)){i(c,u,m,f,y,R,S);for(var P in c){var b=c[P];if(Array.isArray(b)){if(P in r.arrayKeywords)for(var h=0;h<b.length;h++)n(a,i,l,b[h],u+"/"+P+"/"+h,m,u,P,c,h)}else if(P in r.propsKeywords){if(b&&typeof b=="object")for(var $ in b)n(a,i,l,b[$],u+"/"+P+"/"+o($),m,u,P,c,$)}else(P in r.keywords||a.allKeys&&!(P in r.skipKeywords))&&n(a,i,l,b,u+"/"+P,m,u,P,c)}l(c,u,m,f,y,R,S)}}function o(a){return a.replace(/~/g,"~0").replace(/\//g,"~1")}}),vi=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=ye(),r=sm(),n=OS(),o=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function a(b,h=!0){return typeof b=="boolean"?!0:h===!0?!l(b):h?c(b)<=h:!1}e.inlineRef=a;let i=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function l(b){for(let h in b){if(i.has(h))return!0;let $=b[h];if(Array.isArray($)&&$.some(l)||typeof $=="object"&&l($))return!0}return!1}function c(b){let h=0;for(let $ in b){if($==="$ref")return 1/0;if(h++,!o.has($)&&(typeof b[$]=="object"&&(0,t.eachItem)(b[$],v=>h+=c(v)),h===1/0))return 1/0}return h}function u(b,h="",$){return $!==!1&&(h=y(h)),m(b,b.parse(h))}e.getFullPath=u;function m(b,h){return b.serialize(h).split("#")[0]+"#"}e._getFullPath=m;let f=/#\/?$/;function y(b){return b?b.replace(f,""):""}e.normalizeId=y;function R(b,h,$){return $=y($),b.resolve(h,$)}e.resolveUrl=R;let S=/^[a-z_][-a-z0-9._]*$/i;function P(b,h){if(typeof b=="boolean")return{};let{schemaId:$,uriResolver:v}=this.opts,z=y(b[$]||h),I={"":z},T=u(v,z,!1),_={},C=new Set;return n(b,{allKeys:!0},(q,D,W,F)=>{if(F===void 0)return;let ie=T+D,he=I[F];typeof q[$]=="string"&&(he=ge.call(this,q[$])),_e.call(this,q.$anchor),_e.call(this,q.$dynamicAnchor),I[D]=he;function ge(ue){let O=this.opts.uriResolver.resolve;if(ue=y(he?O(he,ue):ue),C.has(ue))throw U(ue);C.add(ue);let j=this.refs[ue];return typeof j=="string"&&(j=this.refs[j]),typeof j=="object"?M(q,j.schema,ue):ue!==y(ie)&&(ue[0]==="#"?(M(q,_[ue],ue),_[ue]=q):this.refs[ue]=ie),ue}function _e(ue){if(typeof ue=="string"){if(!S.test(ue))throw new Error(`invalid anchor "${ue}"`);ge.call(this,`#${ue}`)}}}),_;function M(q,D,W){if(D!==void 0&&!r(q,D))throw U(W)}function U(q){return new Error(`reference "${q}" resolves to more than one schema`)}}e.getSchemaRefs=P}),Fr=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=CS(),r=yi(),n=om(),o=yi(),a=kS(),i=IS(),l=AS(),c=de(),u=Ze(),m=vi(),f=ye(),y=Si();function R(k){if(T(k)&&(C(k),I(k))){h(k);return}S(k,()=>(0,t.topBoolOrEmptySchema)(k))}e.validateFunctionCode=R;function S({gen:k,validateName:L,schema:H,schemaEnv:Q,opts:re},ne){re.code.es5?k.func(L,(0,c._)`${u.default.data}, ${u.default.valCxt}`,Q.$async,()=>{k.code((0,c._)`"use strict"; ${v(H,re)}`),b(k,re),k.code(ne)}):k.func(L,(0,c._)`${u.default.data}, ${P(re)}`,Q.$async,()=>k.code(v(H,re)).code(ne))}function P(k){return(0,c._)`{${u.default.instancePath}="", ${u.default.parentData}, ${u.default.parentDataProperty}, ${u.default.rootData}=${u.default.data}${k.dynamicRef?(0,c._)`, ${u.default.dynamicAnchors}={}`:c.nil}}={}`}function b(k,L){k.if(u.default.valCxt,()=>{k.var(u.default.instancePath,(0,c._)`${u.default.valCxt}.${u.default.instancePath}`),k.var(u.default.parentData,(0,c._)`${u.default.valCxt}.${u.default.parentData}`),k.var(u.default.parentDataProperty,(0,c._)`${u.default.valCxt}.${u.default.parentDataProperty}`),k.var(u.default.rootData,(0,c._)`${u.default.valCxt}.${u.default.rootData}`),L.dynamicRef&&k.var(u.default.dynamicAnchors,(0,c._)`${u.default.valCxt}.${u.default.dynamicAnchors}`)},()=>{k.var(u.default.instancePath,(0,c._)`""`),k.var(u.default.parentData,(0,c._)`undefined`),k.var(u.default.parentDataProperty,(0,c._)`undefined`),k.var(u.default.rootData,u.default.data),L.dynamicRef&&k.var(u.default.dynamicAnchors,(0,c._)`{}`)})}function h(k){let{schema:L,opts:H,gen:Q}=k;S(k,()=>{H.$comment&&L.$comment&&F(k),q(k),Q.let(u.default.vErrors,null),Q.let(u.default.errors,0),H.unevaluated&&$(k),M(k),ie(k)})}function $(k){let{gen:L,validateName:H}=k;k.evaluated=L.const("evaluated",(0,c._)`${H}.evaluated`),L.if((0,c._)`${k.evaluated}.dynamicProps`,()=>L.assign((0,c._)`${k.evaluated}.props`,(0,c._)`undefined`)),L.if((0,c._)`${k.evaluated}.dynamicItems`,()=>L.assign((0,c._)`${k.evaluated}.items`,(0,c._)`undefined`))}function v(k,L){let H=typeof k=="object"&&k[L.schemaId];return H&&(L.code.source||L.code.process)?(0,c._)`/*# sourceURL=${H} */`:c.nil}function z(k,L){if(T(k)&&(C(k),I(k))){_(k,L);return}(0,t.boolOrEmptySchema)(k,L)}function I({schema:k,self:L}){if(typeof k=="boolean")return!k;for(let H in k)if(L.RULES.all[H])return!0;return!1}function T(k){return typeof k.schema!="boolean"}function _(k,L){let{schema:H,gen:Q,opts:re}=k;re.$comment&&H.$comment&&F(k),D(k),W(k);let ne=Q.const("_errs",u.default.errors);M(k,ne),Q.var(L,(0,c._)`${ne} === ${u.default.errors}`)}function C(k){(0,f.checkUnknownRules)(k),U(k)}function M(k,L){if(k.opts.jtd)return ge(k,[],!1,L);let H=(0,r.getSchemaTypes)(k.schema);ge(k,H,!(0,r.coerceAndCheckDataType)(k,H),L)}function U(k){let{schema:L,errSchemaPath:H,opts:Q,self:re}=k;L.$ref&&Q.ignoreKeywordsWithRef&&(0,f.schemaHasRulesButRef)(L,re.RULES)&&re.logger.warn(`$ref: keywords ignored in schema at path "${H}"`)}function q(k){let{schema:L,opts:H}=k;L.default!==void 0&&H.useDefaults&&H.strictSchema&&(0,f.checkStrictMode)(k,"default is ignored in the schema root")}function D(k){let L=k.schema[k.opts.schemaId];L&&(k.baseId=(0,m.resolveUrl)(k.opts.uriResolver,k.baseId,L))}function W(k){if(k.schema.$async&&!k.schemaEnv.$async)throw new Error("async schema in sync schema")}function F({gen:k,schemaEnv:L,schema:H,errSchemaPath:Q,opts:re}){let ne=H.$comment;if(re.$comment===!0)k.code((0,c._)`${u.default.self}.logger.log(${ne})`);else if(typeof re.$comment=="function"){let me=(0,c.str)`${Q}/$comment`,Re=k.scopeValue("root",{ref:L.root});k.code((0,c._)`${u.default.self}.opts.$comment(${ne}, ${me}, ${Re}.schema)`)}}function ie(k){let{gen:L,schemaEnv:H,validateName:Q,ValidationError:re,opts:ne}=k;H.$async?L.if((0,c._)`${u.default.errors} === 0`,()=>L.return(u.default.data),()=>L.throw((0,c._)`new ${re}(${u.default.vErrors})`)):(L.assign((0,c._)`${Q}.errors`,u.default.vErrors),ne.unevaluated&&he(k),L.return((0,c._)`${u.default.errors} === 0`))}function he({gen:k,evaluated:L,props:H,items:Q}){H instanceof c.Name&&k.assign((0,c._)`${L}.props`,H),Q instanceof c.Name&&k.assign((0,c._)`${L}.items`,Q)}function ge(k,L,H,Q){let{gen:re,schema:ne,data:me,allErrors:Re,opts:B,self:be}=k,{RULES:X}=be;if(ne.$ref&&(B.ignoreKeywordsWithRef||!(0,f.schemaHasRulesButRef)(ne,X))){re.block(()=>J(k,"$ref",X.all.$ref.definition));return}B.jtd||ue(k,L),re.block(()=>{for(let oe of X.rules)ee(oe);ee(X.post)});function ee(oe){(0,n.shouldUseGroup)(ne,oe)&&(oe.type?(re.if((0,o.checkDataType)(oe.type,me,B.strictNumbers)),_e(k,oe),L.length===1&&L[0]===oe.type&&H&&(re.else(),(0,o.reportTypeError)(k)),re.endIf()):_e(k,oe),Re||re.if((0,c._)`${u.default.errors} === ${Q||0}`))}}function _e(k,L){let{gen:H,schema:Q,opts:{useDefaults:re}}=k;re&&(0,a.assignDefaults)(k,L.type),H.block(()=>{for(let ne of L.rules)(0,n.shouldUseRule)(Q,ne)&&J(k,ne.keyword,ne.definition,L.type)})}function ue(k,L){k.schemaEnv.meta||!k.opts.strictTypes||(O(k,L),k.opts.allowUnionTypes||j(k,L),E(k,k.dataTypes))}function O(k,L){if(L.length){if(!k.dataTypes.length){k.dataTypes=L;return}L.forEach(H=>{g(k.dataTypes,H)||A(k,`type "${H}" not allowed by context "${k.dataTypes.join(",")}"`)}),w(k,L)}}function j(k,L){L.length>1&&!(L.length===2&&L.includes("null"))&&A(k,"use allowUnionTypes to allow union type keyword")}function E(k,L){let H=k.self.RULES.all;for(let Q in H){let re=H[Q];if(typeof re=="object"&&(0,n.shouldUseRule)(k.schema,re)){let{type:ne}=re.definition;ne.length&&!ne.some(me=>p(L,me))&&A(k,`missing type "${ne.join(",")}" for keyword "${Q}"`)}}}function p(k,L){return k.includes(L)||L==="number"&&k.includes("integer")}function g(k,L){return k.includes(L)||L==="integer"&&k.includes("number")}function w(k,L){let H=[];for(let Q of k.dataTypes)g(L,Q)?H.push(Q):L.includes("integer")&&Q==="number"&&H.push("integer");k.dataTypes=H}function A(k,L){let H=k.schemaEnv.baseId+k.errSchemaPath;L+=` at "${H}" (strictTypes)`,(0,f.checkStrictMode)(k,L,k.opts.strictTypes)}var x=class{constructor(k,L,H){if((0,i.validateKeywordUsage)(k,L,H),this.gen=k.gen,this.allErrors=k.allErrors,this.keyword=H,this.data=k.data,this.schema=k.schema[H],this.$data=L.$data&&k.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,f.schemaRefOrVal)(k,this.schema,H,this.$data),this.schemaType=L.schemaType,this.parentSchema=k.schema,this.params={},this.it=k,this.def=L,this.$data)this.schemaCode=k.gen.const("vSchema",fe(this.$data,k));else if(this.schemaCode=this.schemaValue,!(0,i.validSchemaType)(this.schema,L.schemaType,L.allowUndefined))throw new Error(`${H} value must be ${JSON.stringify(L.schemaType)}`);("code"in L?L.trackErrors:L.errors!==!1)&&(this.errsCount=k.gen.const("_errs",u.default.errors))}result(k,L,H){this.failResult((0,c.not)(k),L,H)}failResult(k,L,H){this.gen.if(k),H?H():this.error(),L?(this.gen.else(),L(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(k,L){this.failResult((0,c.not)(k),void 0,L)}fail(k){if(k===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(k),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(k){if(!this.$data)return this.fail(k);let{schemaCode:L}=this;this.fail((0,c._)`${L} !== undefined && (${(0,c.or)(this.invalid$data(),k)})`)}error(k,L,H){if(L){this.setParams(L),this._error(k,H),this.setParams({});return}this._error(k,H)}_error(k,L){(k?y.reportExtraError:y.reportError)(this,this.def.error,L)}$dataError(){(0,y.reportError)(this,this.def.$dataError||y.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,y.resetErrorsCount)(this.gen,this.errsCount)}ok(k){this.allErrors||this.gen.if(k)}setParams(k,L){L?Object.assign(this.params,k):this.params=k}block$data(k,L,H=c.nil){this.gen.block(()=>{this.check$data(k,H),L()})}check$data(k=c.nil,L=c.nil){if(!this.$data)return;let{gen:H,schemaCode:Q,schemaType:re,def:ne}=this;H.if((0,c.or)((0,c._)`${Q} === undefined`,L)),k!==c.nil&&H.assign(k,!0),(re.length||ne.validateSchema)&&(H.elseIf(this.invalid$data()),this.$dataError(),k!==c.nil&&H.assign(k,!1)),H.else()}invalid$data(){let{gen:k,schemaCode:L,schemaType:H,def:Q,it:re}=this;return(0,c.or)(ne(),me());function ne(){if(H.length){if(!(L instanceof c.Name))throw new Error("ajv implementation error");let Re=Array.isArray(H)?H:[H];return(0,c._)`${(0,o.checkDataTypes)(Re,L,re.opts.strictNumbers,o.DataType.Wrong)}`}return c.nil}function me(){if(Q.validateSchema){let Re=k.scopeValue("validate$data",{ref:Q.validateSchema});return(0,c._)`!${Re}(${L})`}return c.nil}}subschema(k,L){let H=(0,l.getSubschema)(this.it,k);(0,l.extendSubschemaData)(H,this.it,k),(0,l.extendSubschemaMode)(H,k);let Q={...this.it,...H,items:void 0,props:void 0};return z(Q,L),Q}mergeEvaluated(k,L){let{it:H,gen:Q}=this;H.opts.unevaluated&&(H.props!==!0&&k.props!==void 0&&(H.props=f.mergeEvaluated.props(Q,k.props,H.props,L)),H.items!==!0&&k.items!==void 0&&(H.items=f.mergeEvaluated.items(Q,k.items,H.items,L)))}mergeValidEvaluated(k,L){let{it:H,gen:Q}=this;if(H.opts.unevaluated&&(H.props!==!0||H.items!==!0))return Q.if(L,()=>this.mergeEvaluated(k,c.Name)),!0}};e.KeywordCxt=x;function J(k,L,H,Q){let re=new x(k,H,L);"code"in H?H.code(re,Q):re.$data&&H.validate?(0,i.funcKeywordCode)(re,H):"macro"in H?(0,i.macroKeywordCode)(re,H):(H.compile||H.validate)&&(0,i.funcKeywordCode)(re,H)}let K=/^\/(?:[^~]|~0|~1)*$/,ce=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function fe(k,{dataLevel:L,dataNames:H,dataPathArr:Q}){let re,ne;if(k==="")return u.default.rootData;if(k[0]==="/"){if(!K.test(k))throw new Error(`Invalid JSON-pointer: ${k}`);re=k,ne=u.default.rootData}else{let be=ce.exec(k);if(!be)throw new Error(`Invalid JSON-pointer: ${k}`);let X=+be[1];if(re=be[2],re==="#"){if(X>=L)throw new Error(B("property/index",X));return Q[L-X]}if(X>L)throw new Error(B("data",X));if(ne=H[L-X],!re)return ne}let me=ne,Re=re.split("/");for(let be of Re)be&&(ne=(0,c._)`${ne}${(0,c.getProperty)((0,f.unescapeJsonPointer)(be))}`,me=(0,c._)`${me} && ${ne}`);return me;function B(be,X){return`Cannot access ${be} ${X} levels up, current level is ${L}`}}e.getData=fe}),To=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=class extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}};e.default=t}),Gr=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=vi();var r=class extends Error{constructor(n,o,a,i){super(i||`can't resolve reference ${a} from id ${o}`),this.missingRef=(0,t.resolveUrl)(n,o,a),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(n,this.missingRef))}};e.default=r}),_i=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=de(),r=To(),n=Ze(),o=vi(),a=ye(),i=Fr();var l=class{constructor(h){var $;this.refs={},this.dynamicAnchors={};let v;typeof h.schema=="object"&&(v=h.schema),this.schema=h.schema,this.schemaId=h.schemaId,this.root=h.root||this,this.baseId=($=h.baseId)!==null&&$!==void 0?$:(0,o.normalizeId)(v?.[h.schemaId||"$id"]),this.schemaPath=h.schemaPath,this.localRefs=h.localRefs,this.meta=h.meta,this.$async=v?.$async,this.refs={}}};e.SchemaEnv=l;function c(h){let $=f.call(this,h);if($)return $;let v=(0,o.getFullPath)(this.opts.uriResolver,h.root.baseId),{es5:z,lines:I}=this.opts.code,{ownProperties:T}=this.opts,_=new t.CodeGen(this.scope,{es5:z,lines:I,ownProperties:T}),C;h.$async&&(C=_.scopeValue("Error",{ref:r.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let M=_.scopeName("validate");h.validateName=M;let U={gen:_,allErrors:this.opts.allErrors,data:n.default.data,parentData:n.default.parentData,parentDataProperty:n.default.parentDataProperty,dataNames:[n.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:_.scopeValue("schema",this.opts.code.source===!0?{ref:h.schema,code:(0,t.stringify)(h.schema)}:{ref:h.schema}),validateName:M,ValidationError:C,schema:h.schema,schemaEnv:h,rootId:v,baseId:h.baseId||v,schemaPath:t.nil,errSchemaPath:h.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,t._)`""`,opts:this.opts,self:this},q;try{this._compilations.add(h),(0,i.validateFunctionCode)(U),_.optimize(this.opts.code.optimize);let D=_.toString();q=`${_.scopeRefs(n.default.scope)}return ${D}`,this.opts.code.process&&(q=this.opts.code.process(q,h));let W=new Function(`${n.default.self}`,`${n.default.scope}`,q)(this,this.scope.get());if(this.scope.value(M,{ref:W}),W.errors=null,W.schema=h.schema,W.schemaEnv=h,h.$async&&(W.$async=!0),this.opts.code.source===!0&&(W.source={validateName:M,validateCode:D,scopeValues:_._values}),this.opts.unevaluated){let{props:F,items:ie}=U;W.evaluated={props:F instanceof t.Name?void 0:F,items:ie instanceof t.Name?void 0:ie,dynamicProps:F instanceof t.Name,dynamicItems:ie instanceof t.Name},W.source&&(W.source.evaluated=(0,t.stringify)(W.evaluated))}return h.validate=W,h}catch(D){throw delete h.validate,delete h.validateName,q&&this.logger.error("Error compiling schema, function code:",q),D}finally{this._compilations.delete(h)}}e.compileSchema=c;function u(h,$,v){var z;v=(0,o.resolveUrl)(this.opts.uriResolver,$,v);let I=h.refs[v];if(I)return I;let T=R.call(this,h,v);if(T===void 0){let _=(z=h.localRefs)===null||z===void 0?void 0:z[v],{schemaId:C}=this.opts;_&&(T=new l({schema:_,schemaId:C,root:h,baseId:$}))}if(T!==void 0)return h.refs[v]=m.call(this,T)}e.resolveRef=u;function m(h){return(0,o.inlineRef)(h.schema,this.opts.inlineRefs)?h.schema:h.validate?h:c.call(this,h)}function f(h){for(let $ of this._compilations)if(y($,h))return $}e.getCompilingSchema=f;function y(h,$){return h.schema===$.schema&&h.root===$.root&&h.baseId===$.baseId}function R(h,$){let v;for(;typeof(v=this.refs[$])=="string";)$=v;return v||this.schemas[$]||S.call(this,h,$)}function S(h,$){let v=this.opts.uriResolver.parse($),z=(0,o._getFullPath)(this.opts.uriResolver,v),I=(0,o.getFullPath)(this.opts.uriResolver,h.baseId,void 0);if(Object.keys(h.schema).length>0&&z===I)return b.call(this,v,h);let T=(0,o.normalizeId)(z),_=this.refs[T]||this.schemas[T];if(typeof _=="string"){let C=S.call(this,h,_);return typeof C?.schema!="object"?void 0:b.call(this,v,C)}if(typeof _?.schema=="object"){if(_.validate||c.call(this,_),T===(0,o.normalizeId)($)){let{schema:C}=_,{schemaId:M}=this.opts,U=C[M];return U&&(I=(0,o.resolveUrl)(this.opts.uriResolver,I,U)),new l({schema:C,schemaId:M,root:h,baseId:I})}return b.call(this,v,_)}}e.resolveSchema=S;let P=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function b(h,{baseId:$,schema:v,root:z}){var I;if(((I=h.fragment)===null||I===void 0?void 0:I[0])!=="/")return;for(let C of h.fragment.slice(1).split("/")){if(typeof v=="boolean")return;let M=v[(0,a.unescapeFragment)(C)];if(M===void 0)return;v=M;let U=typeof v=="object"&&v[this.opts.schemaId];!P.has(C)&&U&&($=(0,o.resolveUrl)(this.opts.uriResolver,$,U))}let T;if(typeof v!="boolean"&&v.$ref&&!(0,a.schemaHasRulesButRef)(v,this.RULES)){let C=(0,o.resolveUrl)(this.opts.uriResolver,$,v.$ref);T=S.call(this,z,C)}let{schemaId:_}=this.opts;if(T=T||new l({schema:v,schemaId:_,root:z,baseId:$}),T.schema!==T.root.schema)return T}}),MS=V((e,t)=>{t.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}}),am=V((e,t)=>{let r=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),n=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),o=RegExp.prototype.test.bind(/^\d*$/u),a=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),i=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),l=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),c=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),u=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),m=new Array(256);{let E="0123456789ABCDEF";for(let p=0;p<256;p++)m[p]="%"+E[p>>4]+E[p&15]}function f(E){return E<2048?m[192|E>>6]+m[128|E&63]:E<65536?m[224|E>>12]+m[128|E>>6&63]+m[128|E&63]:m[240|E>>18]+m[128|E>>12&63]+m[128|E>>6&63]+m[128|E&63]}function y(E){let p="",g=0,w=0;for(w=0;w<E.length;w++)if(g=E[w].charCodeAt(0),g!==48){if(!(g>=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))return"";p+=E[w];break}for(w+=1;w<E.length;w++){if(g=E[w].charCodeAt(0),!(g>=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))return"";p+=E[w]}return p}let R=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),S=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),P=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),b=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function h(E){if(E.length===0)return!1;for(let p=0;p<E.length;p++)if(!P(E[p])){if(E[p]==="%"&&p+2<E.length&&a(E.slice(p+1,p+3))){p+=2;continue}return!1}return!0}function $(E){let p=-1,g=0,w=-1,A=0;for(let K=0;K<E.length;K++)E[K]==="0"?(w===-1&&(w=K),A++,A>g&&(g=A,p=w)):(w=-1,A=0);if(g<2)return E.join(":");let x=E.slice(0,p).join(":"),J=E.slice(p+g).join(":");return x+"::"+J}function v(E){let p=E.indexOf("::");if(p!==-1&&E.indexOf("::",p+1)!==-1)return;let g=p===-1?E.split(":"):E.slice(0,p).split(":"),w=p===-1?[]:E.slice(p+2).split(":");p!==-1&&(g.length===1&&g[0]===""&&(g.length=0),w.length===1&&w[0]===""&&(w.length=0));let A=g.concat(w),x=0;for(let K=0;K<A.length;K++){let ce=A[K];if(ce==="")return;if(ce.indexOf(".")!==-1){if(K!==A.length-1||p!==-1&&w.length===0||!n(ce))return;x+=2;continue}if(!R(ce))return;A[K]=parseInt(ce,16).toString(16),x++}if(p===-1)return x!==8?void 0:$(A);if(x>=8)return;let J=A.slice(0,g.length);for(let K=x;K<8;K++)J.push("0");for(let K=g.length;K<A.length;K++)J.push(A[K]);return $(J)}function z(E){let p=E[0]==="["&&E[E.length-1]==="]";if((E[0]==="["||E[E.length-1]==="]")&&!p)return{host:E,isIPV6:!1,error:!0};let g=p?E.slice(1,-1):E;if(p&&S(g))return g=g.toLowerCase(),{host:`[${g}]`,escapedHost:g,isIPV6:!1,isIPVFuture:!0};if(I(g,":")<2)return{host:E,isIPV6:!1,error:p};let w="",A=g.indexOf("%");if(A!==-1){let J=g.slice(A,A+3).toLowerCase()==="%25"?3:1;if(w=g.slice(A+J),!h(w))return{host:E,isIPV6:!1,error:!0};g=g.slice(0,A)}let x=v(g);return x===void 0?{host:E,isIPV6:!1,error:!0}:{host:x+(w?"%"+w:""),escapedHost:x+(w?"%25"+w:""),isIPV6:!0}}function I(E,p){let g=0;for(let w=0;w<E.length;w++)E[w]===p&&g++;return g}function T(E){let p=E,g=[],w=-1,A=0;for(;A=p.length;){if(A===1){if(p===".")break;if(p==="/"){g.push("/");break}else{g.push(p);break}}else if(A===2){if(p[0]==="."){if(p[1]===".")break;if(p[1]==="/"){p=p.slice(2);continue}}else if(p[0]==="/"&&(p[1]==="."||p[1]==="/")){g.push("/");break}}else if(A===3&&p==="/.."){g.length!==0&&g.pop(),g.push("/");break}if(p[0]==="."){if(p[1]==="."){if(p[2]==="/"){p=p.slice(3);continue}}else if(p[1]==="/"){p=p.slice(2);continue}}else if(p[0]==="/"&&p[1]==="."){if(p[2]==="/"){p=p.slice(2);continue}else if(p[2]==="."&&p[3]==="/"){p=p.slice(3),g.length!==0&&g.pop();continue}}if((w=p.indexOf("/",1))===-1){g.push(p);break}else g.push(p.slice(0,w)),p=p.slice(w)}return g.join("")}let _={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},C=/[@/?#:]/g,M=/[@/?#]/g;function U(E,p){let g=p?M:C;return g.lastIndex=0,E.replace(g,w=>_[w])}function q(E,p=!1){if(E.indexOf("%")===-1)return E;let g="";for(let w=0;w<E.length;w++){if(E[w]==="%"&&w+2<E.length){let A=E.slice(w+1,w+3);if(a(A)){let x=A.toUpperCase(),J=String.fromCharCode(parseInt(x,16));p&&i(J)?g+=J:g+="%"+x,w+=2;continue}}g+=E[w]}return g}function D(E){let p="";for(let g=0;g<E.length;g++){let w=E[g];if(w==="%"&&g+2<E.length){let A=E.slice(g+1,g+3);if(a(A)){let x=A.toUpperCase(),J=String.fromCharCode(parseInt(x,16));J!=="."&&i(J)?p+=J:p+="%"+x,g+=2;continue}}if(l(w))p+=w;else{let A=E.charCodeAt(g);if(A<128)p+=_e(A)?w:m[A];else if(A<55296||A>57343)p+=f(A);else if(A<=56319&&g+1<E.length){let x=E.charCodeAt(g+1);x>=56320&&x<=57343?(p+=f(65536+(A-55296<<10)+(x-56320)),g++):p+=f(65533)}else p+=f(65533)}}return p}function W(E,p=!1){let g="",w=p&&E[0]!=="/";for(let A=0;A<E.length;A++){let x=E[A];if(x==="%"&&A+2<E.length){let J=E.slice(A+1,A+3);if(a(J)){g+="%"+J.toUpperCase(),A+=2;continue}}if(x==="/"&&(w=!1),l(x)&&(x!==":"||!w))g+=x;else{let J=E.charCodeAt(A);if(J<128)g+=m[J];else if(J<55296||J>57343)g+=f(J);else if(J<=56319&&A+1<E.length){let K=E.charCodeAt(A+1);K>=56320&&K<=57343?(g+=f(65536+(J-55296<<10)+(K-56320)),A++):g+=f(65533)}else g+=f(65533)}}return g}function F(E,p){let g="";for(let w=0;w<E.length;w++){let A=E[w];if(A==="%"&&w+2<E.length){let x=E.slice(w+1,w+3);if(a(x)){g+="%"+x.toUpperCase(),w+=2;continue}}if(p(A))g+=A;else{let x=E.charCodeAt(w);if(x<128)g+=m[x];else if(x<55296||x>57343)g+=f(x);else if(x<=56319&&w+1<E.length){let J=E.charCodeAt(w+1);J>=56320&&J<=57343?(g+=f(65536+(x-55296<<10)+(J-56320)),w++):g+=f(65533)}else g+=f(65533)}}return g}function ie(E){return F(E,u)}function he(E){return F(E,c)}function ge(E){return F(E,c)}function _e(E){return E>=48&&E<=57||E>=65&&E<=90||E>=97&&E<=122||E===42||E===43||E===45||E===46||E===47||E===64||E===95}function ue(E){let p="";for(let g=0;g<E.length;g++){let w=E[g];if(w==="%"&&g+2<E.length){let A=E.slice(g+1,g+3);if(a(A)){let x=A.toUpperCase(),J=String.fromCharCode(parseInt(x,16));i(J)?p+=J:p+="%"+x,g+=2;continue}}if(c(w))p+=w;else{let A=E.charCodeAt(g);if(A<128)p+=_e(A)?w:m[A];else if(A<55296||A>57343)p+=f(A);else if(A<=56319&&g+1<E.length){let x=E.charCodeAt(g+1);x>=56320&&x<=57343?(p+=f(65536+(A-55296<<10)+(x-56320)),g++):p+=f(65533)}else p+=f(65533)}}return p}function O(E){let p="";for(let g=0;g<E.length;g++){if(E[g]==="%"&&g+2<E.length){let w=E.slice(g+1,g+3);if(a(w)){p+="%"+w.toUpperCase(),g+=2;continue}}p+=escape(E[g])}return p}function j(E){let p=[];if(E.userinfo!==void 0&&(p.push(ie(E.userinfo)),p.push("@")),E.host!==void 0){let g=E.host;if(!n(g)){let w=z(g);w.isIPV6!==!0&&w.isIPVFuture!==!0&&(g=q(g,!0),w=z(g)),w.isIPV6===!0||w.isIPVFuture===!0?g=`[${w.escapedHost}]`:g=U(g,!1)}p.push(g)}if(typeof E.port=="number"||typeof E.port=="string"){let g=String(E.port);if(!o(g))throw new TypeError("URI port is malformed.");p.push(":"),p.push(g)}return p.length?p.join(""):void 0}t.exports={nonSimpleDomain:b,recomposeAuthority:j,reescapeHostDelimiters:U,normalizePercentEncoding:q,normalizePathEncoding:D,serializePathEncoding:W,normalizeQueryFragmentEncoding:ue,encodeUserinfo:ie,encodeQuery:he,encodeFragment:ge,escapePreservingEscapes:O,removeDotSegments:T,isIPv4:n,isUUID:r,normalizeIPv6:z,stringArrayToHexStripped:y}}),NS=V((e,t)=>{let{isUUID:r}=am(),n=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,o=["http","https","ws","wss","urn","urn:uuid"];function a(_){return o.indexOf(_)!==-1}function i(_){return _.secure===!0?!0:_.secure===!1?!1:_.scheme?_.scheme.length===3&&(_.scheme[0]==="w"||_.scheme[0]==="W")&&(_.scheme[1]==="s"||_.scheme[1]==="S")&&(_.scheme[2]==="s"||_.scheme[2]==="S"):!1}function l(_){return _.host||(_.error=_.error||"HTTP URIs must have a host."),_}function c(_){let C=String(_.scheme).toLowerCase()==="https";return(_.port===(C?443:80)||_.port==="")&&(_.port=void 0),_.path||(_.path="/"),_}function u(_){return _.secure=i(_),_.resourceName=(_.path||"/")+(_.query?"?"+_.query:""),_.path=void 0,_.query=void 0,_}function m(_){if((_.port===(i(_)?443:80)||_.port==="")&&(_.port=void 0),typeof _.secure=="boolean"&&(_.scheme=_.secure?"wss":"ws",_.secure=void 0),_.resourceName){let C=_.resourceName.indexOf("?"),M=C===-1?_.resourceName:_.resourceName.slice(0,C);_.path=M&&M!=="/"?M:void 0,_.query=C===-1?void 0:_.resourceName.slice(C+1),_.resourceName=void 0}return _.fragment=void 0,_}function f(_,C){if(!_.path)return _.error="URN can not be parsed",_;let M=_.path.match(n);if(M&&M[0]===_.path){let U=C.scheme||_.scheme||"urn";_.nid=M[1].toLowerCase(),_.nss=M[2];let q=T(`${U}:${C.nid||_.nid}`);_.path=void 0,q&&(_=q.parse(_,C))}else _.error=_.error||"URN can not be parsed.";return _}function y(_,C){if(_.nid===void 0)throw new Error("URN without nid cannot be serialized");let M=C.scheme||_.scheme||"urn",U=_.nid.toLowerCase(),q=T(`${M}:${C.nid||U}`);q&&(_=q.serialize(_,C));let D=_,W=_.nss;return D.path=`${U||C.nid}:${W}`,C.skipEscape=!0,D}function R(_,C){let M=_;return M.uuid=M.nss,M.nss=void 0,!C.tolerant&&(!M.uuid||!r(M.uuid))&&(M.error=M.error||"UUID is not valid."),M}function S(_){let C=_;return C.nss=(_.uuid||"").toLowerCase(),C}let P={scheme:"http",domainHost:!0,parse:l,serialize:c},b={scheme:"https",domainHost:P.domainHost,parse:l,serialize:c},h={scheme:"ws",domainHost:!0,parse:u,serialize:m},$={scheme:"wss",domainHost:h.domainHost,parse:h.parse,serialize:h.serialize},I={http:P,https:b,ws:h,wss:$,urn:{scheme:"urn",parse:f,serialize:y,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:R,serialize:S,skipNormalize:!0}};Object.setPrototypeOf(I,null);function T(_){return _&&(I[_]||I[_.toLowerCase()])||void 0}t.exports={wsIsSecure:i,SCHEMES:I,isValidSchemeName:a,getSchemeHandler:T}}),qS=V((e,t)=>{let{normalizeIPv6:r,removeDotSegments:n,recomposeAuthority:o,normalizePercentEncoding:a,normalizePathEncoding:i,serializePathEncoding:l,normalizeQueryFragmentEncoding:c,encodeQuery:u,encodeFragment:m,reescapeHostDelimiters:f,isIPv4:y,nonSimpleDomain:R}=am(),{SCHEMES:S,getSchemeHandler:P}=NS(),b=/^[A-Za-z][A-Za-z0-9+.-]*$/u,h="URI scheme is malformed.";function $(E){let p=unescape(String(E));if(!b.test(p))throw new TypeError(h);return p}function v(E,p){return typeof E=="string"?E=_e(E,p):typeof E=="object"&&(E=ge(_(E,p),p)),E}function z(E,p,g){let w=g?Object.assign({scheme:"null"},g):{scheme:"null"},{parsed:A,malformedAuthorityOrPort:x,malformedPercentEncoding:J,malformedSchemeSpecific:K,malformedHost:ce,malformedScheme:fe}=he(E,w),{parsed:k,malformedAuthorityOrPort:L,malformedPercentEncoding:H,malformedSchemeSpecific:Q,malformedHost:re,malformedScheme:ne}=he(p,w);if(x||L||J||H||K||Q||ce||re||fe||ne)throw new Error(A.error||k.error||"URI is malformed.");let me=I(A,k,w,!0),Re=P(g&&g.scheme||me.scheme),B=me.host,be=B!==void 0&&B!==""&&(y(B)||r(B).isIPV6);ie(me,g||{},Re,be);let X=B&&B.indexOf("%")!==-1&&!/\P{ASCII}/u.test(B);if(me.error&&!X)throw new Error(me.error);return w.skipEscape=!0,_(me,w)}function I(E,p,g,w){let A={};return w||(E=ge(_(E,g),g),p=ge(_(p,g),g)),g=g||{},!g.tolerant&&p.scheme?(A.scheme=p.scheme,A.userinfo=p.userinfo,A.host=p.host,A.port=p.port,A.path=n(p.path||""),A.query=p.query):(p.userinfo!==void 0||p.host!==void 0||p.port!==void 0?(A.userinfo=p.userinfo,A.host=p.host,A.port=p.port,A.path=n(p.path||""),A.query=p.query):(p.path?(p.path[0]==="/"?A.path=n(p.path):((E.userinfo!==void 0||E.host!==void 0||E.port!==void 0)&&!E.path?A.path="/"+p.path:E.path?A.path=E.path.slice(0,E.path.lastIndexOf("/")+1)+p.path:A.path=p.path,A.path=n(A.path)),A.query=p.query):(A.path=E.path,p.query!==void 0?A.query=p.query:A.query=E.query),A.userinfo=E.userinfo,A.host=E.host,A.port=E.port),A.scheme=E.scheme),A.fragment=p.fragment,A}function T(E,p,g){let w=O(E,g),A=O(p,g);return w!==void 0&&A!==void 0&&w===A}function _(E,p){let g={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:""},w=Object.assign({},p),A=[];g.scheme&&(g.scheme=$(g.scheme));let x=P(w.scheme||g.scheme);x&&x.serialize&&x.serialize(g,w);let J=g.userinfo!==void 0||g.host!==void 0||g.port!==void 0,K=!w.skipEscape&&g.scheme===void 0&&!J;g.path!==void 0&&(w.skipEscape?g.path=a(g.path):g.path=l(g.path,K)),w.reference!=="suffix"&&g.scheme&&(g.scheme=$(g.scheme),A.push(g.scheme,":"));let ce=o(g);if(ce!==void 0&&(w.reference!=="suffix"&&A.push("//"),A.push(ce),g.path&&g.path[0]!=="/"&&A.push("/")),g.path!==void 0){let fe=g.path;!w.absolutePath&&(!x||!x.absolutePath)&&(fe=n(fe)),K&&(fe=l(fe,!0)),ce===void 0&&fe[0]==="/"&&fe[1]==="/"&&(fe="/%2F"+fe.slice(2)),A.push(fe)}return g.query!==void 0&&A.push("?",u(g.query)),g.fragment!==void 0&&A.push("#",m(g.fragment)),A.join("")}let C=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,M=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,U=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function q(E,p){if(p[2]!==void 0&&E.path&&E.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof E.port=="number"&&(E.port<0||E.port>65535))return"URI port is malformed."}function D(E){if(E===void 0)return!1;let p=E.indexOf("%");for(;p!==-1;){if(p+2>=E.length||!/^[\da-f]{2}$/iu.test(E.slice(p+1,p+3)))return!0;p=E.indexOf("%",p+3)}return!1}function W(E){return E[0]==="["&&E[E.length-1]==="]"}function F(E){let p=E[4];return D(E[3])||p!==void 0&&!W(p)&&D(p)||D(E[6])||D(E[7])||D(E[8])}function ie(E,p,g,w){if(!p.unicodeSupport&&(!g||!g.unicodeSupport)&&E.host&&!W(E.host)&&(p.domainHost||g&&g.domainHost)&&w===!1&&R(E.host))try{E.host=new URL("http://"+E.host).hostname}catch(A){return E.error=E.error||"Host's domain name can not be converted to ASCII: "+A,!0}return!1}function he(E,p){let g=Object.assign({},p),w={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},A=!1,x=!1,J=!1,K=!1,ce=!1,fe=!1,k=!1;g.reference==="suffix"&&(g.scheme?E=g.scheme+":"+E:E="//"+E);let L=E.match(M);L!==null&&L[1].indexOf("\\")!==-1&&(w.error="URI authority must not contain a literal backslash.",A=!0);let H=E.match(U);if(H!==null){let re=H[1],ne=re.replace(/[\t\n\r]/g,"");ne.length>=2&&(ne.slice(0,2)!=="//"?(w.error=w.error||"URI authority must not contain a literal backslash.",A=!0):re.length!==ne.length&&(w.error=w.error||"URI authority introducer must not contain whitespace.",A=!0))}let Q=E.match(C);if(Q){if(w.scheme=Q[1],w.userinfo=Q[3],w.host=Q[4],w.port=parseInt(Q[5],10),w.path=Q[6]||"",w.query=Q[7],w.fragment=Q[8],w.scheme!==void 0){let me=unescape(w.scheme);b.test(me)?w.scheme=me.toLowerCase():(w.error=w.error||h,fe=!0)}x=F(Q),x&&(w.error=w.error||"URI contains malformed percent-encoding."),isNaN(w.port)&&(w.port=Q[5]);let re=q(w,Q);if(re!==void 0&&(w.error=w.error||re,A=!0),w.host)if(y(w.host)===!1){let me=W(w.host),Re=w.host.indexOf("[")!==-1||w.host.indexOf("]")!==-1,B=r(w.host);k=B.isIPV6||B.isIPVFuture===!0,ce=Re&&(!me||B.error===!0),w.host=k?B.host:B.host.toLowerCase(),ce&&(w.error=w.error||"URI host is malformed.",A=!0)}else k=!0;w.scheme===void 0&&w.userinfo===void 0&&w.host===void 0&&w.port===void 0&&w.query===void 0&&!w.path?w.reference="same-document":w.scheme===void 0?w.reference="relative":w.fragment===void 0?w.reference="absolute":w.reference="uri",g.reference&&g.reference!=="suffix"&&g.reference!==w.reference&&(w.error=w.error||"URI is not a "+g.reference+" reference.");let ne=P(g.scheme||w.scheme);if(ce||(K=ie(w,g,ne,k)),E.indexOf("%")!==-1&&w.host!==void 0&&!ce){let me=k?w.host:a(w.host,!0);k||(me=a(me.toLowerCase())),w.host=f(me,k)}(!ne||ne&&!ne.skipNormalize)&&(w.path&&(w.path=i(w.path)),w.query&&(w.query=c(w.query)),w.fragment&&(w.fragment=c(w.fragment))),ne&&ne.parse&&(ne.parse(w,g),ne===S.urn&&w.nid===void 0&&(J=!0))}else w.error=w.error||"URI can not be parsed.";return{parsed:w,malformedAuthorityOrPort:A,malformedPercentEncoding:x,malformedSchemeSpecific:J,malformedHost:K,malformedScheme:fe}}function ge(E,p){return he(E,p).parsed}function _e(E,p){return ue(E,p).normalized}function ue(E,p){let{parsed:g,malformedAuthorityOrPort:w,malformedPercentEncoding:A,malformedSchemeSpecific:x,malformedHost:J,malformedScheme:K}=he(E,p);return{normalized:w||A||x||J||K?E:_(g,p),malformedAuthorityOrPort:w,malformedPercentEncoding:A,malformedSchemeSpecific:x,malformedHost:J,malformedScheme:K}}function O(E,p){if(typeof E!="string"&&typeof E!="object")return;let g;try{g=typeof E=="string"?E:_(E,p)}catch{return}let{normalized:w,malformedAuthorityOrPort:A,malformedPercentEncoding:x,malformedSchemeSpecific:J,malformedHost:K,malformedScheme:ce}=ue(g,p);return A||x||J||K||ce?void 0:w}let j={SCHEMES:S,normalize:v,resolve:z,resolveComponent:I,equal:T,serialize:_,parse:ge};t.exports=j,t.exports.default=j,t.exports.fastUri=j}),jS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qS();t.code='require("ajv/dist/runtime/uri").default',e.default=t}),vl=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Fr();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=de();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});let n=To(),o=Gr(),a=nm(),i=_i(),l=de(),c=vi(),u=yi(),m=ye(),f=MS(),y=jS(),R=(O,j)=>new RegExp(O,j);R.code="new RegExp";let S=["removeAdditional","useDefaults","coerceTypes"],P=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),b={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."},h={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},$=200;function v(O){var j,E,p,g,w,A,x,J,K,ce,fe,k,L,H,Q,re,ne,me,Re,B,be,X,ee,oe,Z;let Y=O.strict,se=(j=O.code)===null||j===void 0?void 0:j.optimize,ae=se===!0||se===void 0?1:se||0,we=(p=(E=O.code)===null||E===void 0?void 0:E.regExp)!==null&&p!==void 0?p:R,dt=(g=O.uriResolver)!==null&&g!==void 0?g:y.default;return{strictSchema:(A=(w=O.strictSchema)!==null&&w!==void 0?w:Y)!==null&&A!==void 0?A:!0,strictNumbers:(J=(x=O.strictNumbers)!==null&&x!==void 0?x:Y)!==null&&J!==void 0?J:!0,strictTypes:(ce=(K=O.strictTypes)!==null&&K!==void 0?K:Y)!==null&&ce!==void 0?ce:"log",strictTuples:(k=(fe=O.strictTuples)!==null&&fe!==void 0?fe:Y)!==null&&k!==void 0?k:"log",strictRequired:(H=(L=O.strictRequired)!==null&&L!==void 0?L:Y)!==null&&H!==void 0?H:!1,code:O.code?{...O.code,optimize:ae,regExp:we}:{optimize:ae,regExp:we},loopRequired:(Q=O.loopRequired)!==null&&Q!==void 0?Q:$,loopEnum:(re=O.loopEnum)!==null&&re!==void 0?re:$,meta:(ne=O.meta)!==null&&ne!==void 0?ne:!0,messages:(me=O.messages)!==null&&me!==void 0?me:!0,inlineRefs:(Re=O.inlineRefs)!==null&&Re!==void 0?Re:!0,schemaId:(B=O.schemaId)!==null&&B!==void 0?B:"$id",addUsedSchema:(be=O.addUsedSchema)!==null&&be!==void 0?be:!0,validateSchema:(X=O.validateSchema)!==null&&X!==void 0?X:!0,validateFormats:(ee=O.validateFormats)!==null&&ee!==void 0?ee:!0,unicodeRegExp:(oe=O.unicodeRegExp)!==null&&oe!==void 0?oe:!0,int32range:(Z=O.int32range)!==null&&Z!==void 0?Z:!0,uriResolver:dt}}var z=class{constructor(O={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,O=this.opts={...O,...v(O)};let{es5:j,lines:E}=this.opts.code;this.scope=new l.ValueScope({scope:{},prefixes:P,es5:j,lines:E}),this.logger=D(O.logger);let p=O.validateFormats;O.validateFormats=!1,this.RULES=(0,a.getRules)(),I.call(this,b,O,"NOT SUPPORTED"),I.call(this,h,O,"DEPRECATED","warn"),this._metaOpts=U.call(this),O.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),O.keywords&&M.call(this,O.keywords),typeof O.meta=="object"&&this.addMetaSchema(O.meta),_.call(this),O.validateFormats=p}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:O,meta:j,schemaId:E}=this.opts,p=f;E==="id"&&(p={...f},p.id=p.$id,delete p.$id),j&&O&&this.addMetaSchema(p,p[E],!1)}defaultMeta(){let{meta:O,schemaId:j}=this.opts;return this.opts.defaultMeta=typeof O=="object"?O[j]||O:void 0}validate(O,j){let E;if(typeof O=="string"){if(E=this.getSchema(O),!E)throw new Error(`no schema with key or ref "${O}"`)}else E=this.compile(O);let p=E(j);return"$async"in E||(this.errors=E.errors),p}compile(O,j){let E=this._addSchema(O,j);return E.validate||this._compileSchemaEnv(E)}compileAsync(O,j){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:E}=this.opts;return p.call(this,O,j);async function p(K,ce){await g.call(this,K.$schema);let fe=this._addSchema(K,ce);return fe.validate||w.call(this,fe)}async function g(K){K&&!this.getSchema(K)&&await p.call(this,{$ref:K},!0)}async function w(K){try{return this._compileSchemaEnv(K)}catch(ce){if(!(ce instanceof o.default))throw ce;return A.call(this,ce),await x.call(this,ce.missingSchema),w.call(this,K)}}function A({missingSchema:K,missingRef:ce}){if(this.refs[K])throw new Error(`AnySchema ${K} is loaded but ${ce} cannot be resolved`)}async function x(K){let ce=await J.call(this,K);this.refs[K]||await g.call(this,ce.$schema),this.refs[K]||this.addSchema(ce,K,j)}async function J(K){let ce=this._loading[K];if(ce)return ce;try{return await(this._loading[K]=E(K))}finally{delete this._loading[K]}}}addSchema(O,j,E,p=this.opts.validateSchema){if(Array.isArray(O)){for(let w of O)this.addSchema(w,void 0,E,p);return this}let g;if(typeof O=="object"){let{schemaId:w}=this.opts;if(g=O[w],g!==void 0&&typeof g!="string")throw new Error(`schema ${w} must be string`)}return j=(0,c.normalizeId)(j||g),this._checkUnique(j),this.schemas[j]=this._addSchema(O,E,j,p,!0),this}addMetaSchema(O,j,E=this.opts.validateSchema){return this.addSchema(O,j,!0,E),this}validateSchema(O,j){if(typeof O=="boolean")return!0;let E;if(E=O.$schema,E!==void 0&&typeof E!="string")throw new Error("$schema must be a string");if(E=E||this.opts.defaultMeta||this.defaultMeta(),!E)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let p=this.validate(E,O);if(!p&&j){let g="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(g);else throw new Error(g)}return p}getSchema(O){let j;for(;typeof(j=T.call(this,O))=="string";)O=j;if(j===void 0){let{schemaId:E}=this.opts,p=new i.SchemaEnv({schema:{},schemaId:E});if(j=i.resolveSchema.call(this,p,O),!j)return;this.refs[O]=j}return j.validate||this._compileSchemaEnv(j)}removeSchema(O){if(O instanceof RegExp)return this._removeAllSchemas(this.schemas,O),this._removeAllSchemas(this.refs,O),this;switch(typeof O){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let j=T.call(this,O);return typeof j=="object"&&this._cache.delete(j.schema),delete this.schemas[O],delete this.refs[O],this}case"object":{let j=O;this._cache.delete(j);let E=O[this.opts.schemaId];return E&&(E=(0,c.normalizeId)(E),delete this.schemas[E],delete this.refs[E]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(O){for(let j of O)this.addKeyword(j);return this}addKeyword(O,j){let E;if(typeof O=="string")E=O,typeof j=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),j.keyword=E);else if(typeof O=="object"&&j===void 0){if(j=O,E=j.keyword,Array.isArray(E)&&!E.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(F.call(this,E,j),!j)return(0,m.eachItem)(E,g=>ie.call(this,g)),this;ge.call(this,j);let p={...j,type:(0,u.getJSONTypes)(j.type),schemaType:(0,u.getJSONTypes)(j.schemaType)};return(0,m.eachItem)(E,p.type.length===0?g=>ie.call(this,g,p):g=>p.type.forEach(w=>ie.call(this,g,p,w))),this}getKeyword(O){let j=this.RULES.all[O];return typeof j=="object"?j.definition:!!j}removeKeyword(O){let{RULES:j}=this;delete j.keywords[O],delete j.all[O];for(let E of j.rules){let p=E.rules.findIndex(g=>g.keyword===O);p>=0&&E.rules.splice(p,1)}return this}addFormat(O,j){return typeof j=="string"&&(j=new RegExp(j)),this.formats[O]=j,this}errorsText(O=this.errors,{separator:j=", ",dataVar:E="data"}={}){return!O||O.length===0?"No errors":O.map(p=>`${E}${p.instancePath} ${p.message}`).reduce((p,g)=>p+j+g)}$dataMetaSchema(O,j){let E=this.RULES.all;O=JSON.parse(JSON.stringify(O));for(let p of j){let g=p.split("/").slice(1),w=O;for(let A of g)w=w[A];for(let A in E){let x=E[A];if(typeof x!="object")continue;let{$data:J}=x.definition,K=w[A];J&&K&&(w[A]=ue(K))}}return O}_removeAllSchemas(O,j){for(let E in O){let p=O[E];(!j||j.test(E))&&(typeof p=="string"?delete O[E]:p&&!p.meta&&(this._cache.delete(p.schema),delete O[E]))}}_addSchema(O,j,E,p=this.opts.validateSchema,g=this.opts.addUsedSchema){let w,{schemaId:A}=this.opts;if(typeof O=="object")w=O[A];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof O!="boolean")throw new Error("schema must be object or boolean")}let x=this._cache.get(O);if(x!==void 0)return x;E=(0,c.normalizeId)(w||E);let J=c.getSchemaRefs.call(this,O,E);return x=new i.SchemaEnv({schema:O,schemaId:A,meta:j,baseId:E,localRefs:J}),this._cache.set(x.schema,x),g&&!E.startsWith("#")&&(E&&this._checkUnique(E),this.refs[E]=x),p&&this.validateSchema(O,!0),x}_checkUnique(O){if(this.schemas[O]||this.refs[O])throw new Error(`schema with key or id "${O}" already exists`)}_compileSchemaEnv(O){if(O.meta?this._compileMetaSchema(O):i.compileSchema.call(this,O),!O.validate)throw new Error("ajv implementation error");return O.validate}_compileMetaSchema(O){let j=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,O)}finally{this.opts=j}}};z.ValidationError=n.default,z.MissingRefError=o.default,e.default=z;function I(O,j,E,p="error"){for(let g in O){let w=g;w in j&&this.logger[p](`${E}: option ${g}. ${O[w]}`)}}function T(O){return O=(0,c.normalizeId)(O),this.schemas[O]||this.refs[O]}function _(){let O=this.opts.schemas;if(O)if(Array.isArray(O))this.addSchema(O);else for(let j in O)this.addSchema(O[j],j)}function C(){for(let O in this.opts.formats){let j=this.opts.formats[O];j&&this.addFormat(O,j)}}function M(O){if(Array.isArray(O)){this.addVocabulary(O);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let j in O){let E=O[j];E.keyword||(E.keyword=j),this.addKeyword(E)}}function U(){let O={...this.opts};for(let j of S)delete O[j];return O}let q={log(){},warn(){},error(){}};function D(O){if(O===!1)return q;if(O===void 0)return console;if(O.log&&O.warn&&O.error)return O;throw new Error("logger must implement log, warn and error methods")}let W=/^[a-z_$][a-z0-9_$:-]*$/i;function F(O,j){let{RULES:E}=this;if((0,m.eachItem)(O,p=>{if(E.keywords[p])throw new Error(`Keyword ${p} is already defined`);if(!W.test(p))throw new Error(`Keyword ${p} has invalid name`)}),!!j&&j.$data&&!("code"in j||"validate"in j))throw new Error('$data keyword must have "code" or "validate" function')}function ie(O,j,E){var p;let g=j?.post;if(E&&g)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:w}=this,A=g?w.post:w.rules.find(({type:J})=>J===E);if(A||(A={type:E,rules:[]},w.rules.push(A)),w.keywords[O]=!0,!j)return;let x={keyword:O,definition:{...j,type:(0,u.getJSONTypes)(j.type),schemaType:(0,u.getJSONTypes)(j.schemaType)}};j.before?he.call(this,A,x,j.before):A.rules.push(x),w.all[O]=x,(p=j.implements)===null||p===void 0||p.forEach(J=>this.addKeyword(J))}function he(O,j,E){let p=O.rules.findIndex(g=>g.keyword===E);p>=0?O.rules.splice(p,0,j):(O.rules.push(j),this.logger.warn(`rule ${E} is not defined`))}function ge(O){let{metaSchema:j}=O;j!==void 0&&(O.$data&&this.opts.$data&&(j=ue(j)),O.validateSchema=this.compile(j,!0))}let _e={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ue(O){return{anyOf:[O,_e]}}}),LS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};e.default=t}),_l=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=Gr(),r=Qe(),n=de(),o=Ze(),a=_i(),i=ye(),l={keyword:"$ref",schemaType:"string",code(m){let{gen:f,schema:y,it:R}=m,{baseId:S,schemaEnv:P,validateName:b,opts:h,self:$}=R,{root:v}=P;if((y==="#"||y==="#/")&&S===v.baseId)return I();let z=a.resolveRef.call($,v,S,y);if(z===void 0)throw new t.default(R.opts.uriResolver,S,y);if(z instanceof a.SchemaEnv)return T(z);return _(z);function I(){if(P===v)return u(m,b,P,P.$async);let C=f.scopeValue("root",{ref:v});return u(m,(0,n._)`${C}.validate`,v,v.$async)}function T(C){u(m,c(m,C),C,C.$async)}function _(C){let M=f.scopeValue("schema",h.code.source===!0?{ref:C,code:(0,n.stringify)(C)}:{ref:C}),U=f.name("valid"),q=m.subschema({schema:C,dataTypes:[],schemaPath:n.nil,topSchemaRef:M,errSchemaPath:y},U);m.mergeEvaluated(q),m.ok(U)}}};function c(m,f){let{gen:y}=m;return f.validate?y.scopeValue("validate",{ref:f.validate}):(0,n._)`${y.scopeValue("wrapper",{ref:f})}.validate`}e.getValidate=c;function u(m,f,y,R){let{gen:S,it:P}=m,{allErrors:b,schemaEnv:h,opts:$}=P,v=$.passContext?o.default.this:n.nil;R?z():I();function z(){if(!h.$async)throw new Error("async schema referenced by sync schema");let C=S.let("valid");S.try(()=>{S.code((0,n._)`await ${(0,r.callValidateCode)(m,f,v)}`),_(f),b||S.assign(C,!0)},M=>{S.if((0,n._)`!(${M} instanceof ${P.ValidationError})`,()=>S.throw(M)),T(M),b||S.assign(C,!1)}),m.ok(C)}function I(){m.result((0,r.callValidateCode)(m,f,v),()=>_(f),()=>T(f))}function T(C){let M=(0,n._)`${C}.errors`;S.assign(o.default.vErrors,(0,n._)`${o.default.vErrors} === null ? ${M} : ${o.default.vErrors}.concat(${M})`),S.assign(o.default.errors,(0,n._)`${o.default.vErrors}.length`)}function _(C){var M;if(!P.opts.unevaluated)return;let U=(M=y?.validate)===null||M===void 0?void 0:M.evaluated;if(P.props!==!0)if(U&&!U.dynamicProps)U.props!==void 0&&(P.props=i.mergeEvaluated.props(S,U.props,P.props));else{let q=S.var("props",(0,n._)`${C}.evaluated.props`);P.props=i.mergeEvaluated.props(S,q,P.props,n.Name)}if(P.items!==!0)if(U&&!U.dynamicItems)U.items!==void 0&&(P.items=i.mergeEvaluated.items(S,U.items,P.items));else{let q=S.var("items",(0,n._)`${C}.evaluated.items`);P.items=i.mergeEvaluated.items(S,q,P.items,n.Name)}}}e.callRef=u,e.default=l}),im=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=LS(),r=_l(),n=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",t.default,r.default];e.default=n}),DS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=t.operators,n={maximum:{okStr:"<=",ok:r.LTE,fail:r.GT},minimum:{okStr:">=",ok:r.GTE,fail:r.LT},exclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},exclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},o={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:{message:({keyword:a,schemaCode:i})=>(0,t.str)`must be ${n[a].okStr} ${i}`,params:({keyword:a,schemaCode:i})=>(0,t._)`{comparison: ${n[a].okStr}, limit: ${i}}`},code(a){let{keyword:i,data:l,schemaCode:c}=a;a.fail$data((0,t._)`${l} ${n[i].fail} ${c} || isNaN(${l})`)}};e.default=o}),xS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,t._)`{multipleOf: ${n}}`},code(n){let{gen:o,data:a,schemaCode:i,it:l}=n,c=l.opts.multipleOfPrecision,u=o.let("res"),m=c?(0,t._)`Math.abs(Math.round(${u}) - ${u}) > 1e-${c}`:(0,t._)`${u} !== parseInt(${u})`;n.fail$data((0,t._)`(${i} === 0 || (${u} = ${a}/${i}, ${m}))`)}};e.default=r}),HS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(r){let n=r.length,o=0,a=0,i;for(;a<n;)o++,i=r.charCodeAt(a++),i>=55296&&i<=56319&&a<n&&(i=r.charCodeAt(a),(i&64512)===56320&&a++);return o}e.default=t,t.code='require("ajv/dist/runtime/ucs2length").default'}),US=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=ye(),n=HS(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:a,schemaCode:i}){let l=a==="maxLength"?"more":"fewer";return(0,t.str)`must NOT have ${l} than ${i} characters`},params:({schemaCode:a})=>(0,t._)`{limit: ${a}}`},code(a){let{keyword:i,data:l,schemaCode:c,it:u}=a,m=i==="maxLength"?t.operators.GT:t.operators.LT,f=u.opts.unicode===!1?(0,t._)`${l}.length`:(0,t._)`${(0,r.useFunc)(a.gen,n.default)}(${l})`;a.fail$data((0,t._)`${f} ${m} ${c}`)}};e.default=o}),VS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qe(),r=ye(),n=de(),o={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:a})=>(0,n.str)`must match pattern "${a}"`,params:({schemaCode:a})=>(0,n._)`{pattern: ${a}}`},code(a){let{gen:i,data:l,$data:c,schema:u,schemaCode:m,it:f}=a,y=f.opts.unicodeRegExp?"u":"";if(c){let{regExp:R}=f.opts.code,S=R.code==="new RegExp"?(0,n._)`new RegExp`:(0,r.useFunc)(i,R),P=i.let("valid");i.try(()=>i.assign(P,(0,n._)`${S}(${m}, ${y}).test(${l})`),()=>i.assign(P,!1)),a.fail$data((0,n._)`!${P}`)}else{let R=(0,t.usePattern)(a,u);a.fail$data((0,n._)`!${R}.test(${l})`)}}};e.default=o}),BS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){let a=n==="maxProperties"?"more":"fewer";return(0,t.str)`must NOT have ${a} than ${o} properties`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){let{keyword:o,data:a,schemaCode:i}=n,l=o==="maxProperties"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`Object.keys(${a}).length ${l} ${i}`)}};e.default=r}),FS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qe(),r=de(),n=ye(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:a}})=>(0,r.str)`must have required property '${a}'`,params:({params:{missingProperty:a}})=>(0,r._)`{missingProperty: ${a}}`},code(a){let{gen:i,schema:l,schemaCode:c,data:u,$data:m,it:f}=a,{opts:y}=f;if(!m&&l.length===0)return;let R=l.length>=y.loopRequired;if(f.allErrors?S():P(),y.strictRequired){let $=a.parentSchema.properties,{definedProperties:v}=a.it;for(let z of l)if($?.[z]===void 0&&!v.has(z)){let I=`required property "${z}" is not defined at "${f.schemaEnv.baseId+f.errSchemaPath}" (strictRequired)`;(0,n.checkStrictMode)(f,I,f.opts.strictRequired)}}function S(){if(R||m)a.block$data(r.nil,b);else for(let $ of l)(0,t.checkReportMissingProp)(a,$)}function P(){let $=i.let("missing");if(R||m){let v=i.let("valid",!0);a.block$data(v,()=>h($,v)),a.ok(v)}else i.if((0,t.checkMissingProp)(a,l,$)),(0,t.reportMissingProp)(a,$),i.else()}function b(){i.forOf("prop",c,$=>{a.setParams({missingProperty:$}),i.if((0,t.noPropertyInData)(i,u,$,y.ownProperties),()=>a.error())})}function h($,v){a.setParams({missingProperty:$}),i.forOf($,c,()=>{i.assign(v,(0,t.propertyInData)(i,u,$,y.ownProperties)),i.if((0,r.not)(v),()=>{a.error(),i.break()})},r.nil)}}};e.default=o}),GS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){let a=n==="maxItems"?"more":"fewer";return(0,t.str)`must NOT have ${a} than ${o} items`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){let{keyword:o,data:a,schemaCode:i}=n,l=o==="maxItems"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`${a}.length ${l} ${i}`)}};e.default=r}),bl=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=sm();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),JS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=yi(),r=de(),n=ye(),o=bl(),a={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i,j:l}})=>(0,r.str)`must NOT have duplicate items (items ## ${l} and ${i} are identical)`,params:({params:{i,j:l}})=>(0,r._)`{i: ${i}, j: ${l}}`},code(i){let{gen:l,data:c,$data:u,schema:m,parentSchema:f,schemaCode:y,it:R}=i;if(!u&&!m)return;let S=l.let("valid"),P=f.items?(0,t.getSchemaTypes)(f.items):[];i.block$data(S,b,(0,r._)`${y} === false`),i.ok(S);function b(){let z=l.let("i",(0,r._)`${c}.length`),I=l.let("j");i.setParams({i:z,j:I}),l.assign(S,!0),l.if((0,r._)`${z} > 1`,()=>(h()?$:v)(z,I))}function h(){return P.length>0&&!P.some(z=>z==="object"||z==="array")}function $(z,I){let T=l.name("item"),_=(0,t.checkDataTypes)(P,T,R.opts.strictNumbers,t.DataType.Wrong),C=l.const("indices",(0,r._)`{}`);l.for((0,r._)`;${z}--;`,()=>{l.let(T,(0,r._)`${c}[${z}]`),l.if(_,(0,r._)`continue`),P.length>1&&l.if((0,r._)`typeof ${T} == "string"`,(0,r._)`${T} += "_"`),l.if((0,r._)`typeof ${C}[${T}] == "number"`,()=>{l.assign(I,(0,r._)`${C}[${T}]`),i.error(),l.assign(S,!1).break()}).code((0,r._)`${C}[${T}] = ${z}`)})}function v(z,I){let T=(0,n.useFunc)(l,o.default),_=l.name("outer");l.label(_).for((0,r._)`;${z}--;`,()=>l.for((0,r._)`${I} = ${z}; ${I}--;`,()=>l.if((0,r._)`${T}(${c}[${z}], ${c}[${I}])`,()=>{i.error(),l.assign(S,!1).break(_)})))}}};e.default=a}),KS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=ye(),n=bl(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:a})=>(0,t._)`{allowedValue: ${a}}`},code(a){let{gen:i,data:l,$data:c,schemaCode:u,schema:m}=a;c||m&&typeof m=="object"?a.fail$data((0,t._)`!${(0,r.useFunc)(i,n.default)}(${l}, ${u})`):a.fail((0,t._)`${m} !== ${l}`)}};e.default=o}),WS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=ye(),n=bl(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:a})=>(0,t._)`{allowedValues: ${a}}`},code(a){let{gen:i,data:l,$data:c,schema:u,schemaCode:m,it:f}=a;if(!c&&u.length===0)throw new Error("enum must have non-empty array");let y=u.length>=f.opts.loopEnum,R,S=()=>R??(R=(0,r.useFunc)(i,n.default)),P;if(y||c)P=i.let("valid"),a.block$data(P,b);else{if(!Array.isArray(u))throw new Error("ajv implementation error");let $=i.const("vSchema",m);P=(0,t.or)(...u.map((v,z)=>h($,z)))}a.pass(P);function b(){i.assign(P,!1),i.forOf("v",m,$=>i.if((0,t._)`${S()}(${l}, ${$})`,()=>i.assign(P,!0).break()))}function h($,v){let z=u[v];return typeof z=="object"&&z!==null?(0,t._)`${S()}(${l}, ${$}[${v}])`:(0,t._)`${l} === ${z}`}}};e.default=o}),cm=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=DS(),r=xS(),n=US(),o=VS(),a=BS(),i=FS(),l=GS(),c=JS(),u=KS(),m=WS(),f=[t.default,r.default,n.default,o.default,a.default,i.default,l.default,c.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},u.default,m.default];e.default=f}),lm=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=de(),r=ye(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,t.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,t._)`{limit: ${a}}`},code(a){let{parentSchema:i,it:l}=a,{items:c}=i;if(!Array.isArray(c)){(0,r.checkStrictMode)(l,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(a,c)}};function o(a,i){let{gen:l,schema:c,data:u,keyword:m,it:f}=a;f.items=!0;let y=l.const("len",(0,t._)`${u}.length`);if(c===!1)a.setParams({len:i.length}),a.pass((0,t._)`${y} <= ${i.length}`);else if(typeof c=="object"&&!(0,r.alwaysValidSchema)(f,c)){let S=l.var("valid",(0,t._)`${y} <= ${i.length}`);l.if((0,t.not)(S),()=>R(S)),a.ok(S)}function R(S){l.forRange("i",i.length,y,P=>{a.subschema({keyword:m,dataProp:P,dataPropType:r.Type.Num},S),f.allErrors||l.if((0,t.not)(S),()=>l.break())})}}e.validateAdditionalItems=o,e.default=n}),um=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=de(),r=ye(),n=Qe(),o={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(i){let{schema:l,it:c}=i;if(Array.isArray(l))return a(i,"additionalItems",l);c.items=!0,!(0,r.alwaysValidSchema)(c,l)&&i.ok((0,n.validateArray)(i))}};function a(i,l,c=i.schema){let{gen:u,parentSchema:m,data:f,keyword:y,it:R}=i;b(m),R.opts.unevaluated&&c.length&&R.items!==!0&&(R.items=r.mergeEvaluated.items(u,c.length,R.items));let S=u.name("valid"),P=u.const("len",(0,t._)`${f}.length`);c.forEach((h,$)=>{(0,r.alwaysValidSchema)(R,h)||(u.if((0,t._)`${P} > ${$}`,()=>i.subschema({keyword:y,schemaProp:$,dataProp:$},S)),i.ok(S))});function b(h){let{opts:$,errSchemaPath:v}=R,z=c.length,I=z===h.minItems&&(z===h.maxItems||h[l]===!1);if($.strictTuples&&!I){let T=`"${y}" is ${z}-tuple, but minItems or maxItems/${l} are not specified or different at path "${v}"`;(0,r.checkStrictMode)(R,T,$.strictTuples)}}}e.validateTuple=a,e.default=o}),YS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=um(),r={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0,t.validateTuple)(n,"items")};e.default=r}),XS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=ye(),n=Qe(),o=lm(),a={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:i}})=>(0,t.str)`must NOT have more than ${i} items`,params:({params:{len:i}})=>(0,t._)`{limit: ${i}}`},code(i){let{schema:l,parentSchema:c,it:u}=i,{prefixItems:m}=c;u.items=!0,!(0,r.alwaysValidSchema)(u,l)&&(m?(0,o.validateAdditionalItems)(i,m):i.ok((0,n.validateArray)(i)))}};e.default=a}),ZS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=ye(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:a}})=>a===void 0?(0,t.str)`must contain at least ${o} valid item(s)`:(0,t.str)`must contain at least ${o} and no more than ${a} valid item(s)`,params:({params:{min:o,max:a}})=>a===void 0?(0,t._)`{minContains: ${o}}`:(0,t._)`{minContains: ${o}, maxContains: ${a}}`},code(o){let{gen:a,schema:i,parentSchema:l,data:c,it:u}=o,m,f,{minContains:y,maxContains:R}=l;u.opts.next?(m=y===void 0?1:y,f=R):m=1;let S=a.const("len",(0,t._)`${c}.length`);if(o.setParams({min:m,max:f}),f===void 0&&m===0){(0,r.checkStrictMode)(u,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(f!==void 0&&m>f){(0,r.checkStrictMode)(u,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,r.alwaysValidSchema)(u,i)){let v=(0,t._)`${S} >= ${m}`;f!==void 0&&(v=(0,t._)`${v} && ${S} <= ${f}`),o.pass(v);return}u.items=!0;let P=a.name("valid");f===void 0&&m===1?h(P,()=>a.if(P,()=>a.break())):m===0?(a.let(P,!0),f!==void 0&&a.if((0,t._)`${c}.length > 0`,b)):(a.let(P,!1),b()),o.result(P,()=>o.reset());function b(){let v=a.name("_valid"),z=a.let("count",0);h(v,()=>a.if(v,()=>$(z)))}function h(v,z){a.forRange("i",0,S,I=>{o.subschema({keyword:"contains",dataProp:I,dataPropType:r.Type.Num,compositeRule:!0},v),z()})}function $(v){a.code((0,t._)`${v}++`),f===void 0?a.if((0,t._)`${v} >= ${m}`,()=>a.assign(P,!0).break()):(a.if((0,t._)`${v} > ${f}`,()=>a.assign(P,!1).break()),m===1?a.assign(P,!0):a.if((0,t._)`${v} >= ${m}`,()=>a.assign(P,!0)))}}};e.default=n}),Rl=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=de(),r=ye(),n=Qe();e.error={message:({params:{property:c,depsCount:u,deps:m}})=>{let f=u===1?"property":"properties";return(0,t.str)`must have ${f} ${m} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:m,missingProperty:f}})=>(0,t._)`{property: ${c},
22
+ missingProperty: ${f},
23
+ depsCount: ${u},
24
+ deps: ${m}}`};let o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(c){let[u,m]=a(c);i(c,u),l(c,m)}};function a({schema:c}){let u={},m={};for(let f in c){if(f==="__proto__")continue;let y=Array.isArray(c[f])?u:m;y[f]=c[f]}return[u,m]}function i(c,u=c.schema){let{gen:m,data:f,it:y}=c;if(Object.keys(u).length===0)return;let R=m.let("missing");for(let S in u){let P=u[S];if(P.length===0)continue;let b=(0,n.propertyInData)(m,f,S,y.opts.ownProperties);c.setParams({property:S,depsCount:P.length,deps:P.join(", ")}),y.allErrors?m.if(b,()=>{for(let h of P)(0,n.checkReportMissingProp)(c,h)}):(m.if((0,t._)`${b} && (${(0,n.checkMissingProp)(c,P,R)})`),(0,n.reportMissingProp)(c,R),m.else())}}e.validatePropertyDeps=i;function l(c,u=c.schema){let{gen:m,data:f,keyword:y,it:R}=c,S=m.name("valid");for(let P in u)(0,r.alwaysValidSchema)(R,u[P])||(m.if((0,n.propertyInData)(m,f,P,R.opts.ownProperties),()=>{let b=c.subschema({keyword:y,schemaProp:P},S);c.mergeValidEvaluated(b,S)},()=>m.var(S,!0)),c.ok(S))}e.validateSchemaDeps=l,e.default=o}),QS=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=ye(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:o})=>(0,t._)`{propertyName: ${o.propertyName}}`},code(o){let{gen:a,schema:i,data:l,it:c}=o;if((0,r.alwaysValidSchema)(c,i))return;let u=a.name("valid");a.forIn("key",l,m=>{o.setParams({propertyName:m}),o.subschema({keyword:"propertyNames",data:m,dataTypes:["string"],propertyName:m,compositeRule:!0},u),a.if((0,t.not)(u),()=>{o.error(!0),c.allErrors||a.break()})}),o.ok(u)}};e.default=n}),dm=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qe(),r=de(),n=Ze(),o=ye(),a={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:i})=>(0,r._)`{additionalProperty: ${i.additionalProperty}}`},code(i){let{gen:l,schema:c,parentSchema:u,data:m,errsCount:f,it:y}=i;if(!f)throw new Error("ajv implementation error");let{allErrors:R,opts:S}=y;if(y.props=!0,S.removeAdditional!=="all"&&(0,o.alwaysValidSchema)(y,c))return;let P=(0,t.allSchemaProperties)(u.properties),b=(0,t.allSchemaProperties)(u.patternProperties);h(),i.ok((0,r._)`${f} === ${n.default.errors}`);function h(){l.forIn("key",m,T=>{!P.length&&!b.length?z(T):l.if($(T),()=>z(T))})}function $(T){let _;if(P.length>8){let C=(0,o.schemaRefOrVal)(y,u.properties,"properties");_=(0,t.isOwnProperty)(l,C,T)}else P.length?_=(0,r.or)(...P.map(C=>(0,r._)`${T} === ${C}`)):_=r.nil;return b.length&&(_=(0,r.or)(_,...b.map(C=>(0,r._)`${(0,t.usePattern)(i,C)}.test(${T})`))),(0,r.not)(_)}function v(T){l.code((0,r._)`delete ${m}[${T}]`)}function z(T){if(S.removeAdditional==="all"||S.removeAdditional&&c===!1){v(T);return}if(c===!1){i.setParams({additionalProperty:T}),i.error(),R||l.break();return}if(typeof c=="object"&&!(0,o.alwaysValidSchema)(y,c)){let _=l.name("valid");S.removeAdditional==="failing"?(I(T,_,!1),l.if((0,r.not)(_),()=>{i.reset(),v(T)})):(I(T,_),R||l.if((0,r.not)(_),()=>l.break()))}}function I(T,_,C){let M={keyword:"additionalProperties",dataProp:T,dataPropType:o.Type.Str};C===!1&&Object.assign(M,{compositeRule:!0,createErrors:!1,allErrors:!1}),i.subschema(M,_)}}};e.default=a}),ev=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Fr(),r=Qe(),n=ye(),o=dm(),a={keyword:"properties",type:"object",schemaType:"object",code(i){let{gen:l,schema:c,parentSchema:u,data:m,it:f}=i;f.opts.removeAdditional==="all"&&u.additionalProperties===void 0&&o.default.code(new t.KeywordCxt(f,o.default,"additionalProperties"));let y=(0,r.allSchemaProperties)(c);for(let h of y)f.definedProperties.add(h);f.opts.unevaluated&&y.length&&f.props!==!0&&(f.props=n.mergeEvaluated.props(l,(0,n.toHash)(y),f.props));let R=y.filter(h=>!(0,n.alwaysValidSchema)(f,c[h]));if(R.length===0)return;let S=l.name("valid");for(let h of R)P(h)?b(h):(l.if((0,r.propertyInData)(l,m,h,f.opts.ownProperties)),b(h),f.allErrors||l.else().var(S,!0),l.endIf()),i.it.definedProperties.add(h),i.ok(S);function P(h){return f.opts.useDefaults&&!f.compositeRule&&c[h].default!==void 0}function b(h){i.subschema({keyword:"properties",schemaProp:h,dataProp:h},S)}}};e.default=a}),tv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qe(),r=de(),n=ye(),o=ye(),a={keyword:"patternProperties",type:"object",schemaType:"object",code(i){let{gen:l,schema:c,data:u,parentSchema:m,it:f}=i,{opts:y}=f,R=(0,t.allSchemaProperties)(c),S=R.filter(I=>(0,n.alwaysValidSchema)(f,c[I]));if(R.length===0||S.length===R.length&&(!f.opts.unevaluated||f.props===!0))return;let P=y.strictSchema&&!y.allowMatchingProperties&&m.properties,b=l.name("valid");f.props!==!0&&!(f.props instanceof r.Name)&&(f.props=(0,o.evaluatedPropsToName)(l,f.props));let{props:h}=f;$();function $(){for(let I of R)P&&v(I),f.allErrors?z(I):(l.var(b,!0),z(I),l.if(b))}function v(I){for(let T in P)new RegExp(I).test(T)&&(0,n.checkStrictMode)(f,`property ${T} matches pattern ${I} (use allowMatchingProperties)`)}function z(I){l.forIn("key",u,T=>{l.if((0,r._)`${(0,t.usePattern)(i,I)}.test(${T})`,()=>{let _=S.includes(I);_||i.subschema({keyword:"patternProperties",schemaProp:I,dataProp:T,dataPropType:o.Type.Str},b),f.opts.unevaluated&&h!==!0?l.assign((0,r._)`${h}[${T}]`,!0):!_&&!f.allErrors&&l.if((0,r.not)(b),()=>l.break())})})}}};e.default=a}),rv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ye(),r={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(n){let{gen:o,schema:a,it:i}=n;if((0,t.alwaysValidSchema)(i,a)){n.fail();return}let l=o.name("valid");n.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},l),n.failResult(l,()=>n.reset(),()=>n.error())},error:{message:"must NOT be valid"}};e.default=r}),nv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Qe().validateUnion,error:{message:"must match a schema in anyOf"}};e.default=t}),ov=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=ye(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,t._)`{passingSchemas: ${o.passing}}`},code(o){let{gen:a,schema:i,parentSchema:l,it:c}=o;if(!Array.isArray(i))throw new Error("ajv implementation error");if(c.opts.discriminator&&l.discriminator)return;let u=i,m=a.let("valid",!1),f=a.let("passing",null),y=a.name("_valid");o.setParams({passing:f}),a.block(R),o.result(m,()=>o.reset(),()=>o.error(!0));function R(){u.forEach((S,P)=>{let b;(0,r.alwaysValidSchema)(c,S)?a.var(y,!0):b=o.subschema({keyword:"oneOf",schemaProp:P,compositeRule:!0},y),P>0&&a.if((0,t._)`${y} && ${m}`).assign(m,!1).assign(f,(0,t._)`[${f}, ${P}]`).else(),a.if(y,()=>{a.assign(m,!0),a.assign(f,P),b&&o.mergeEvaluated(b,t.Name)})})}}};e.default=n}),sv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ye(),r={keyword:"allOf",schemaType:"array",code(n){let{gen:o,schema:a,it:i}=n;if(!Array.isArray(a))throw new Error("ajv implementation error");let l=o.name("valid");a.forEach((c,u)=>{if((0,t.alwaysValidSchema)(i,c))return;let m=n.subschema({keyword:"allOf",schemaProp:u},l);n.ok(l),n.mergeEvaluated(m)})}};e.default=r}),av=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=ye(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:a})=>(0,t.str)`must match "${a.ifClause}" schema`,params:({params:a})=>(0,t._)`{failingKeyword: ${a.ifClause}}`},code(a){let{gen:i,parentSchema:l,it:c}=a;l.then===void 0&&l.else===void 0&&(0,r.checkStrictMode)(c,'"if" without "then" and "else" is ignored');let u=o(c,"then"),m=o(c,"else");if(!u&&!m)return;let f=i.let("valid",!0),y=i.name("_valid");if(R(),a.reset(),u&&m){let P=i.let("ifClause");a.setParams({ifClause:P}),i.if(y,S("then",P),S("else",P))}else u?i.if(y,S("then")):i.if((0,t.not)(y),S("else"));a.pass(f,()=>a.error(!0));function R(){let P=a.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},y);a.mergeEvaluated(P)}function S(P,b){return()=>{let h=a.subschema({keyword:P},y);i.assign(f,y),a.mergeValidEvaluated(h,f),b?i.assign(b,(0,t._)`${P}`):a.setParams({ifClause:P})}}}};function o(a,i){let l=a.schema[i];return l!==void 0&&!(0,r.alwaysValidSchema)(a,l)}e.default=n}),iv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ye(),r={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:o,it:a}){o.if===void 0&&(0,t.checkStrictMode)(a,`"${n}" without "if" is ignored`)}};e.default=r}),pm=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=lm(),r=YS(),n=um(),o=XS(),a=ZS(),i=Rl(),l=QS(),c=dm(),u=ev(),m=tv(),f=rv(),y=nv(),R=ov(),S=sv(),P=av(),b=iv();function h($=!1){let v=[f.default,y.default,R.default,S.default,P.default,b.default,l.default,c.default,i.default,u.default,m.default];return $?v.push(r.default,o.default):v.push(t.default,n.default),v.push(a.default),v}e.default=h}),cv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,t._)`{format: ${n}}`},code(n,o){let{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:m}=n,{opts:f,errSchemaPath:y,schemaEnv:R,self:S}=m;if(!f.validateFormats)return;l?P():b();function P(){let h=a.scopeValue("formats",{ref:S.formats,code:f.code.formats}),$=a.const("fDef",(0,t._)`${h}[${u}]`),v=a.let("fType"),z=a.let("format");a.if((0,t._)`typeof ${$} == "object" && !(${$} instanceof RegExp)`,()=>a.assign(v,(0,t._)`${$}.type || "string"`).assign(z,(0,t._)`${$}.validate`),()=>a.assign(v,(0,t._)`"string"`).assign(z,$)),n.fail$data((0,t.or)(I(),T()));function I(){return f.strictSchema===!1?t.nil:(0,t._)`${u} && !${z}`}function T(){let _=R.$async?(0,t._)`(${$}.async ? await ${z}(${i}) : ${z}(${i}))`:(0,t._)`${z}(${i})`,C=(0,t._)`(typeof ${z} == "function" ? ${_} : ${z}.test(${i}))`;return(0,t._)`${z} && ${z} !== true && ${v} === ${o} && !${C}`}}function b(){let h=S.formats[c];if(!h){I();return}if(h===!0)return;let[$,v,z]=T(h);$===o&&n.pass(_());function I(){if(f.strictSchema===!1){S.logger.warn(C());return}throw new Error(C());function C(){return`unknown format "${c}" ignored in schema at path "${y}"`}}function T(C){let M=C instanceof RegExp?(0,t.regexpCode)(C):f.code.formats?(0,t._)`${f.code.formats}${(0,t.getProperty)(c)}`:void 0,U=a.scopeValue("formats",{key:c,ref:C,code:M});return typeof C=="object"&&!(C instanceof RegExp)?[C.type||"string",C.validate,(0,t._)`${U}.validate`]:["string",C,U]}function _(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!R.$async)throw new Error("async format in sync schema");return(0,t._)`await ${z}(${i})`}return typeof v=="function"?(0,t._)`${z}(${i})`:(0,t._)`${z}.test(${i})`}}}};e.default=r}),mm=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=[cv().default];e.default=t}),hm=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],e.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}),fm=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=im(),r=cm(),n=pm(),o=mm(),a=hm(),i=[t.default,r.default,(0,n.default)(),o.default,a.metadataVocabulary,a.contentVocabulary];e.default=i}),lv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(r){r.Tag="tag",r.Mapping="mapping"})(t||(e.DiscrError=t={}))}),wl=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=lv(),n=_i(),o=Gr(),a=ye(),i={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:l,tagName:c}})=>l===r.DiscrError.Tag?`tag "${c}" must be string`:`value of tag "${c}" must be in oneOf`,params:({params:{discrError:l,tag:c,tagName:u}})=>(0,t._)`{error: ${l}, tag: ${u}, tagValue: ${c}}`},code(l){let{gen:c,data:u,schema:m,parentSchema:f,it:y}=l,{oneOf:R}=f;if(!y.opts.discriminator)throw new Error("discriminator: requires discriminator option");let S=m.propertyName;if(typeof S!="string")throw new Error("discriminator: requires propertyName");if(m.mapping)throw new Error("discriminator: mapping is not supported");if(!R)throw new Error("discriminator: requires oneOf keyword");let P=c.let("valid",!1),b=c.const("tag",(0,t._)`${u}${(0,t.getProperty)(S)}`);c.if((0,t._)`typeof ${b} == "string"`,()=>h(),()=>l.error(!1,{discrError:r.DiscrError.Tag,tag:b,tagName:S})),l.ok(P);function h(){let z=v();c.if(!1);for(let I in z)c.elseIf((0,t._)`${b} === ${I}`),c.assign(P,$(z[I]));c.else(),l.error(!1,{discrError:r.DiscrError.Mapping,tag:b,tagName:S}),c.endIf()}function $(z){let I=c.name("valid"),T=l.subschema({keyword:"oneOf",schemaProp:z},I);return l.mergeEvaluated(T,t.Name),I}function v(){var z;let I={},T=C(f),_=!0;for(let q=0;q<R.length;q++){let D=R[q];if(D?.$ref&&!(0,a.schemaHasRulesButRef)(D,y.self.RULES)){let F=D.$ref;if(D=n.resolveRef.call(y.self,y.schemaEnv.root,y.baseId,F),D instanceof n.SchemaEnv&&(D=D.schema),D===void 0)throw new o.default(y.opts.uriResolver,y.baseId,F)}let W=(z=D?.properties)===null||z===void 0?void 0:z[S];if(typeof W!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${S}"`);_=_&&(T||C(D)),M(W,q)}if(!_)throw new Error(`discriminator: "${S}" must be required`);return I;function C({required:q}){return Array.isArray(q)&&q.includes(S)}function M(q,D){if(q.const)U(q.const,D);else if(q.enum)for(let W of q.enum)U(W,D);else throw new Error(`discriminator: "properties/${S}" must have "const" or "enum"`)}function U(q,D){if(typeof q!="string"||q in I)throw new Error(`discriminator: "${S}" values must be unique strings`);I[q]=D}}}};e.default=i}),uv=V((e,t)=>{t.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}}),gm=V((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let r=vl(),n=fm(),o=wl(),a=uv(),i=["/properties"],l="http://json-schema.org/draft-07/schema";var c=class extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(R=>this.addVocabulary(R)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let R=this.opts.$data?this.$dataMetaSchema(a,i):a;this.addMetaSchema(R,l,!1),this.refs["http://json-schema.org/schema"]=l}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(l)?l:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var u=Fr();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var m=de();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return m._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return m.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return m.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return m.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return m.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return m.CodeGen}});var f=To();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return f.default}});var y=Gr();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return y.default}})}),ym=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicAnchor=void 0;let t=de(),r=Ze(),n=_i(),o=_l(),a={keyword:"$dynamicAnchor",schemaType:"string",code:c=>i(c,c.schema)};function i(c,u){let{gen:m,it:f}=c;f.schemaEnv.root.dynamicAnchors[u]=!0;let y=(0,t._)`${r.default.dynamicAnchors}${(0,t.getProperty)(u)}`,R=f.errSchemaPath==="#"?f.validateName:l(c);m.if((0,t._)`!${y}`,()=>m.assign(y,R))}e.dynamicAnchor=i;function l(c){let{schemaEnv:u,schema:m,self:f}=c.it,{root:y,baseId:R,localRefs:S,meta:P}=u.root,{schemaId:b}=f.opts,h=new n.SchemaEnv({schema:m,schemaId:b,root:y,baseId:R,localRefs:S,meta:P});return n.compileSchema.call(f,h),(0,o.getValidate)(c,h)}e.default=a}),Sm=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicRef=void 0;let t=de(),r=Ze(),n=_l(),o={keyword:"$dynamicRef",schemaType:"string",code:i=>a(i,i.schema)};function a(i,l){let{gen:c,keyword:u,it:m}=i;if(l[0]!=="#")throw new Error(`"${u}" only supports hash fragment reference`);let f=l.slice(1);if(m.allErrors)y();else{let S=c.let("valid",!1);y(S),i.ok(S)}function y(S){if(m.schemaEnv.root.dynamicAnchors[f]){let P=c.let("_v",(0,t._)`${r.default.dynamicAnchors}${(0,t.getProperty)(f)}`);c.if(P,R(P,S),R(m.validateName,S))}else R(m.validateName,S)()}function R(S,P){return P?()=>c.block(()=>{(0,n.callRef)(i,S),c.let(P,!0)}):()=>(0,n.callRef)(i,S)}}e.dynamicRef=a,e.default=o}),dv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ym(),r=ye(),n={keyword:"$recursiveAnchor",schemaType:"boolean",code(o){o.schema?(0,t.dynamicAnchor)(o,""):(0,r.checkStrictMode)(o.it,"$recursiveAnchor: false is ignored")}};e.default=n}),pv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Sm(),r={keyword:"$recursiveRef",schemaType:"string",code:n=>(0,t.dynamicRef)(n,n.schema)};e.default=r}),vm=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ym(),r=Sm(),n=dv(),o=pv(),a=[t.default,r.default,n.default,o.default];e.default=a}),mv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Rl(),r={keyword:"dependentRequired",type:"object",schemaType:"object",error:t.error,code:n=>(0,t.validatePropertyDeps)(n)};e.default=r}),hv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Rl(),r={keyword:"dependentSchemas",type:"object",schemaType:"object",code:n=>(0,t.validateSchemaDeps)(n)};e.default=r}),fv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ye(),r={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:n,parentSchema:o,it:a}){o.contains===void 0&&(0,t.checkStrictMode)(a,`"${n}" without "contains" is ignored`)}};e.default=r}),_m=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=mv(),r=hv(),n=fv(),o=[t.default,r.default,n.default];e.default=o}),gv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=ye(),n=Ze(),o={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params:a})=>(0,t._)`{unevaluatedProperty: ${a.unevaluatedProperty}}`},code(a){let{gen:i,schema:l,data:c,errsCount:u,it:m}=a;if(!u)throw new Error("ajv implementation error");let{allErrors:f,props:y}=m;y instanceof t.Name?i.if((0,t._)`${y} !== true`,()=>i.forIn("key",c,b=>i.if(S(y,b),()=>R(b)))):y!==!0&&i.forIn("key",c,b=>y===void 0?R(b):i.if(P(y,b),()=>R(b))),m.props=!0,a.ok((0,t._)`${u} === ${n.default.errors}`);function R(b){if(l===!1){a.setParams({unevaluatedProperty:b}),a.error(),f||i.break();return}if(!(0,r.alwaysValidSchema)(m,l)){let h=i.name("valid");a.subschema({keyword:"unevaluatedProperties",dataProp:b,dataPropType:r.Type.Str},h),f||i.if((0,t.not)(h),()=>i.break())}}function S(b,h){return(0,t._)`!${b} || !${b}[${h}]`}function P(b,h){let $=[];for(let v in b)b[v]===!0&&$.push((0,t._)`${h} !== ${v}`);return(0,t.and)(...$)}}};e.default=o}),yv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=de(),r=ye(),n={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len:o}})=>(0,t.str)`must NOT have more than ${o} items`,params:({params:{len:o}})=>(0,t._)`{limit: ${o}}`},code(o){let{gen:a,schema:i,data:l,it:c}=o,u=c.items||0;if(u===!0)return;let m=a.const("len",(0,t._)`${l}.length`);if(i===!1)o.setParams({len:u}),o.fail((0,t._)`${m} > ${u}`);else if(typeof i=="object"&&!(0,r.alwaysValidSchema)(c,i)){let y=a.var("valid",(0,t._)`${m} <= ${u}`);a.if((0,t.not)(y),()=>f(y,u)),o.ok(y)}c.items=!0;function f(y,R){a.forRange("i",R,m,S=>{o.subschema({keyword:"unevaluatedItems",dataProp:S,dataPropType:r.Type.Num},y),c.allErrors||a.if((0,t.not)(y),()=>a.break())})}}};e.default=n}),bm=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=gv(),r=yv(),n=[t.default,r.default];e.default=n}),Sv=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/schema",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0,"https://json-schema.org/draft/2019-09/vocab/applicator":!0,"https://json-schema.org/draft/2019-09/vocab/validation":!0,"https://json-schema.org/draft/2019-09/vocab/meta-data":!0,"https://json-schema.org/draft/2019-09/vocab/format":!1,"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format"},{$ref:"meta/content"}],type:["object","boolean"],properties:{definitions:{$comment:"While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},dependencies:{$comment:'"dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"',type:"object",additionalProperties:{anyOf:[{$recursiveRef:"#"},{$ref:"meta/validation#/$defs/stringArray"}]}}}}}),vv=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/applicator":!0},$recursiveAnchor:!0,title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{additionalItems:{$recursiveRef:"#"},unevaluatedItems:{$recursiveRef:"#"},items:{anyOf:[{$recursiveRef:"#"},{$ref:"#/$defs/schemaArray"}]},contains:{$recursiveRef:"#"},additionalProperties:{$recursiveRef:"#"},unevaluatedProperties:{$recursiveRef:"#"},properties:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$recursiveRef:"#"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$recursiveRef:"#"}},propertyNames:{$recursiveRef:"#"},if:{$recursiveRef:"#"},then:{$recursiveRef:"#"},else:{$recursiveRef:"#"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$recursiveRef:"#"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$recursiveRef:"#"}}}}}),_v=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/content",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentMediaType:{type:"string"},contentEncoding:{type:"string"},contentSchema:{$recursiveRef:"#"}}}}),bv=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/core",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0},$recursiveAnchor:!0,title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{type:"string",format:"uri"},$anchor:{type:"string",pattern:"^[A-Za-z][-A-Za-z0-9.:_]*$"},$ref:{type:"string",format:"uri-reference"},$recursiveRef:{type:"string",format:"uri-reference"},$recursiveAnchor:{type:"boolean",default:!1},$vocabulary:{type:"object",propertyNames:{type:"string",format:"uri"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}}}}}),Rv=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/format",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/format":!0},$recursiveAnchor:!0,title:"Format vocabulary meta-schema",type:["object","boolean"],properties:{format:{type:"string"}}}}),wv=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/meta-data":!0},$recursiveAnchor:!0,title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}}),Ev=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/validation",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/validation":!0},$recursiveAnchor:!0,title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}},const:!0,enum:{type:"array",items:!0},type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}}),Tv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Sv(),r=vv(),n=_v(),o=bv(),a=Rv(),i=wv(),l=Ev(),c=["/properties"];function u(m){return[t,r,n,o,f(this,a),i,f(this,l)].forEach(y=>this.addMetaSchema(y,void 0,!1)),this;function f(y,R){return m?y.$dataMetaSchema(R,c):R}}e.default=u}),$v=V((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv2019=void 0;let r=vl(),n=fm(),o=vm(),a=_m(),i=bm(),l=wl(),c=Tv(),u="https://json-schema.org/draft/2019-09/schema";var m=class extends r.default{constructor(P={}){super({...P,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),this.addVocabulary(o.default),n.default.forEach(P=>this.addVocabulary(P)),this.addVocabulary(a.default),this.addVocabulary(i.default),this.opts.discriminator&&this.addKeyword(l.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:P,meta:b}=this.opts;b&&(c.default.call(this,P),this.refs["http://json-schema.org/schema"]=u)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(u)?u:void 0)}};e.Ajv2019=m,t.exports=e=m,t.exports.Ajv2019=m,Object.defineProperty(e,"__esModule",{value:!0}),e.default=m;var f=Fr();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return f.KeywordCxt}});var y=de();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return y._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return y.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return y.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return y.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return y.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return y.CodeGen}});var R=To();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return R.default}});var S=Gr();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return S.default}})}),zv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=im(),r=cm(),n=pm(),o=vm(),a=_m(),i=bm(),l=mm(),c=hm(),u=[o.default,t.default,r.default,(0,n.default)(!0),l.default,c.metadataVocabulary,c.contentVocabulary,a.default,i.default];e.default=u}),Pv=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}}),Cv=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}}),kv=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}}),Iv=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}}),Av=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}}),Ov=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}}),Mv=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}}),Nv=V((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}}),qv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Pv(),r=Cv(),n=kv(),o=Iv(),a=Av(),i=Ov(),l=Mv(),c=Nv(),u=["/properties"];function m(f){return[t,r,n,o,a,y(this,i),l,y(this,c)].forEach(R=>this.addMetaSchema(R,void 0,!1)),this;function y(R,S){return f?R.$dataMetaSchema(S,u):S}}e.default=m}),jv=V((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv2020=void 0;let r=vl(),n=zv(),o=wl(),a=qv(),i="https://json-schema.org/draft/2020-12/schema";var l=class extends r.default{constructor(y={}){super({...y,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),n.default.forEach(y=>this.addVocabulary(y)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:y,meta:R}=this.opts;R&&(a.default.call(this,y),this.refs["http://json-schema.org/schema"]=i)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}};e.Ajv2020=l,t.exports=e=l,t.exports.Ajv2020=l,Object.defineProperty(e,"__esModule",{value:!0}),e.default=l;var c=Fr();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=de();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 m=To();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return m.default}});var f=Gr();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})}),Lv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(q,D){return{validate:q,compare:D}}e.fullFormats={date:t(a,i),time:t(c(!0),u),"date-time":t(y(!0),R),"iso-time":t(c(),m),"iso-date-time":t(y(),S),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:h,"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:U,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:v,int32:{type:"number",validate:T},int64:{type:"number",validate:_},float:{type:"number",validate:C},double:{type:"number",validate:C},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,i),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,u),"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,R),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),"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,S),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 r(q){return q%4===0&&(q%100!==0||q%400===0)}let n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(q){let D=n.exec(q);if(!D)return!1;let W=+D[1],F=+D[2],ie=+D[3];return F>=1&&F<=12&&ie>=1&&ie<=(F===2&&r(W)?29:o[F])}function i(q,D){if(q&&D)return q>D?1:q<D?-1:0}let l=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(q){return function(W){let F=l.exec(W);if(!F)return!1;let ie=+F[1],he=+F[2],ge=+F[3],_e=F[4],ue=F[5]==="-"?-1:1,O=+(F[6]||0),j=+(F[7]||0);if(O>23||j>59||q&&!_e)return!1;if(ie<=23&&he<=59&&ge<60)return!0;let E=he-j*ue,p=ie-O*ue-(E<0?1:0);return(p===23||p===-1)&&(E===59||E===-1)&&ge<61}}function u(q,D){if(!(q&&D))return;let W=new Date("2020-01-01T"+q).valueOf(),F=new Date("2020-01-01T"+D).valueOf();if(W&&F)return W-F}function m(q,D){if(!(q&&D))return;let W=l.exec(q),F=l.exec(D);if(W&&F)return q=W[1]+W[2]+W[3],D=F[1]+F[2]+F[3],q>D?1:q<D?-1:0}let f=/t|\s/i;function y(q){let D=c(q);return function(F){let ie=F.split(f);return ie.length===2&&a(ie[0])&&D(ie[1])}}function R(q,D){if(!(q&&D))return;let W=new Date(q).valueOf(),F=new Date(D).valueOf();if(W&&F)return W-F}function S(q,D){if(!(q&&D))return;let[W,F]=q.split(f),[ie,he]=D.split(f),ge=i(W,ie);if(ge!==void 0)return ge||u(F,he)}let P=/\/|:/,b=/^(?:[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 h(q){return P.test(q)&&b.test(q)}let $=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function v(q){return $.lastIndex=0,$.test(q)}let z=-(2**31),I=2**31-1;function T(q){return Number.isInteger(q)&&q<=I&&q>=z}function _(q){return Number.isInteger(q)}function C(){return!0}let M=/[^\\]\\Z/;function U(q){if(M.test(q))return!1;try{return new RegExp(q),!0}catch{return!1}}}),Dv=V(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=gm(),r=de(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},a={message:({keyword:l,schemaCode:c})=>(0,r.str)`should be ${o[l].okStr} ${c}`,params:({keyword:l,schemaCode:c})=>(0,r._)`{comparison: ${o[l].okStr}, limit: ${c}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:a,code(l){let{gen:c,data:u,schemaCode:m,keyword:f,it:y}=l,{opts:R,self:S}=y;if(!R.validateFormats)return;let P=new t.KeywordCxt(y,S.RULES.all.format.definition,"format");P.$data?b():h();function b(){let v=c.scopeValue("formats",{ref:S.formats,code:R.code.formats}),z=c.const("fmt",(0,r._)`${v}[${P.schemaCode}]`);l.fail$data((0,r.or)((0,r._)`typeof ${z} != "object"`,(0,r._)`${z} instanceof RegExp`,(0,r._)`typeof ${z}.compare != "function"`,$(z)))}function h(){let v=P.schema,z=S.formats[v];if(!z||z===!0)return;if(typeof z!="object"||z instanceof RegExp||typeof z.compare!="function")throw new Error(`"${f}": format "${v}" does not define "compare" function`);let I=c.scopeValue("formats",{key:v,ref:z,code:R.code.formats?(0,r._)`${R.code.formats}${(0,r.getProperty)(v)}`:void 0});l.fail$data($(I))}function $(v){return(0,r._)`${v}.compare(${u}, ${m}) ${o[f].fail} 0`}},dependencies:["format"]};let i=l=>(l.addKeyword(e.formatLimitDefinition),l);e.default=i}),xv=V((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let r=Lv(),n=Dv(),o=de(),a=new o.Name("fullFormats"),i=new o.Name("fastFormats"),l=(u,m={keywords:!0})=>{if(Array.isArray(m))return c(u,m,r.fullFormats,a),u;let[f,y]=m.mode==="fast"?[r.fastFormats,i]:[r.fullFormats,a];return c(u,m.formats||r.formatNames,f,y),m.keywords&&(0,n.default)(u),u};l.get=(u,m="full")=>{let f=(m==="fast"?r.fastFormats:r.fullFormats)[u];if(!f)throw new Error(`Unknown format "${u}"`);return f};function c(u,m,f,y){var R,S;(R=(S=u.opts.code).formats)!==null&&R!==void 0||(S.formats=(0,o._)`require("ajv-formats/dist/formats").${y}`);for(let P of m)u.addFormat(P,f[P])}t.exports=e=l,Object.defineProperty(e,"__esModule",{value:!0}),e.default=l}),Rm=gm(),Hv=$v(),Uv=jv(),Vv=ds(xv(),1),Bv=Vv.default;function Sl(e){let t=new e({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Bv(t),t}var bi=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor(e){this._userAjv=e!==void 0,this._ajv=e}get ajv(){return this._ajv??=Sl(Uv.Ajv2020)}_engineFor(e){if(this._userAjv)return this.ajv;let t=cs(e,"pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.");return t==="2020-12"?this.ajv:t==="2019-09"?this._ajv2019??=Sl(Hv.Ajv2019):this._ajvDraft7??=Sl(Rm.Ajv)}getValidator(e){let t=this._engineFor(e),r="$id"in e&&typeof e.$id=="string"?t.getSchema(e.$id)??t.compile(e):t.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:t.errorsText(r.errors)}}},Iw=Rm.Ajv;var Im=Symbol.for("mcp.completable");function Tl(e){return!!e&&typeof e=="object"&&Im in e}function Gv(e){return e[Im]?.complete}var Jr=15e3,Jv=2**31-1;function zo(e,t){if(!Number.isFinite(e)||e<1)return;let r=setInterval(t,Math.min(e,Jv));return r.unref?.(),r}var Am,$l=class{static{Am=e=>e._classification}onclose;onerror;onmessage;_classification;_responseMode;_started=!1;_used=!1;_closed=!1;_terminalDelivered=!1;_dispatchWindowOpen=!1;_requestId;_deferredResponse;_sse;_abortCleanup;_keepAliveMs;constructor(e){this._classification=e.classification,this._responseMode=e.responseMode??"auto",this._keepAliveMs=e.keepAliveMs??Jr}async start(){if(this._started)throw new Error("PerRequestHTTPServerTransport is already started");this._started=!0}async handleMessage(e,t){if(this._used)throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request");if(!this._started||this.onmessage===void 0)throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message");if(this._closed)throw new Error("PerRequestHTTPServerTransport is closed");this._used=!0;let r=t?.request?.signal;if(r?.aborted)throw await this.close(),new le(pe.ConnectionClosed,"The request was aborted before it could be handled");let n={classification:this._classification,...t?.request!==void 0&&{request:t.request},...t?.authInfo!==void 0&&{authInfo:t.authInfo}};if(Xe(e)){this._requestId=e.id;let o,a,i=new Promise((l,c)=>{o=l,a=c});if(this._deferredResponse={promise:i,resolve:o,reject:a,settled:!1},r!==void 0){let l=()=>void this.close();r.addEventListener("abort",l,{once:!0}),this._abortCleanup=()=>r.removeEventListener("abort",l)}this._dispatchWindowOpen=!0;try{this.onmessage(e,n)}finally{this._dispatchWindowOpen=!1}return this._responseMode==="sse"&&!this._closed&&!this._deferredResponse.settled&&this.upgradeToSse(),i}return this.onmessage(e,n),new Response(null,{status:202})}async send(e,t){if(this._closed)return;let r=it(e)||ct(e),n=r?e.id:t?.relatedRequestId;if(this._requestId===void 0||n===void 0||n!==this._requestId){r&&this.onerror?.(new Error(`Received a response for an unknown request id: ${String(e.id)}`));return}if(r){if(this._terminalDelivered)return;this._terminalDelivered=!0;let o=ct(e)?e.error.code:void 0,a=o!==void 0&&(this._dispatchWindowOpen||o===G.MissingRequiredClientCapability)?dl[o]:void 0;if(a!==void 0&&this._sse===void 0){this.settleResponse(Response.json(e,{status:a,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>void this.close());return}if(this._sse!==void 0||this._responseMode==="sse"){this._sse===void 0&&this.upgradeToSse(),this.writeMessageFrame(e),this.finalizeStream();return}this.settleResponse(Response.json(e,{status:200,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>void this.close());return}this._responseMode!=="json"&&(this._sse===void 0&&this.upgradeToSse(),this.writeMessageFrame(e))}writeCommentFrame(e){if(this._closed||this._sse===void 0||this._sse.closed)return;let t=e.split(`
25
+ `).map(r=>`: ${r}`).join(`
26
+ `);this.writeFrame(`${t}
27
+
28
+ `)}async close(){if(!this._closed){if(this._closed=!0,this._abortCleanup?.(),this._abortCleanup=void 0,this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),this._sse!==void 0&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}this._deferredResponse!==void 0&&!this._deferredResponse.settled&&(this._deferredResponse.settled=!0,this._deferredResponse.reject(new le(pe.ConnectionClosed,"Connection closed before a response was produced"))),this.onclose?.()}}settleResponse(e){this._deferredResponse===void 0||this._deferredResponse.settled||(this._deferredResponse.settled=!0,this._deferredResponse.resolve(e))}upgradeToSse(){let e,t=new ReadableStream({start:r=>{e=r},cancel:()=>{this.close()}});this._sse={controller:e,encoder:new TextEncoder,closed:!1},this._sse.keepAliveTimer=zo(this._keepAliveMs,()=>this.writeCommentFrame("keepalive")),this.settleResponse(new Response(t,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}))}finalizeStream(){if(this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),this._sse!==void 0&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}queueMicrotask(()=>void this.close())}writeMessageFrame(e){this.writeFrame(`event: message
29
+ data: ${JSON.stringify(e)}
30
+
31
+ `)}writeFrame(e){if(!(this._sse===void 0||this._sse.closed))try{this._sse.controller.enqueue(this._sse.encoder.encode(e))}catch(t){this.onerror?.(new Error(`Failed to write to the response stream: ${t}`))}}};function Kv(e){return e instanceof $l?Am(e):void 0}function Ri(e){return e.replaceAll(/[\\"]/g,String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g," ")}function wm(e,t,r,n){let o=`Bearer error="${Ri(e)}", error_description="${Ri(t)}"`;return r.length>0&&(o+=`, scope="${Ri(r.join(" "))}"`),n&&(o+=`, resource_metadata="${Ri(n)}"`),o}function Om(e,t){let{requiredScopes:r=[],resourceMetadataUrl:n}=t??{};if(!(e instanceof vo)){let o=new vo(cr.ServerError,"Internal Server Error");return Response.json(o.toResponseObject(),{status:500})}switch(e.code){case cr.InvalidToken:{let o=wm(e.code,e.message,r,n);return Response.json(e.toResponseObject(),{status:401,headers:{"WWW-Authenticate":o}})}case cr.InsufficientScope:{let o=wm(e.code,e.message,r,n);return Response.json(e.toResponseObject(),{status:403,headers:{"WWW-Authenticate":o}})}case cr.ServerError:return Response.json(e.toResponseObject(),{status:500});default:return Response.json(e.toResponseObject(),{status:400})}}function Mm(e){let t=new URL(e);return t.pathname=Wv(e),t.hash="",t.href}function Wv(e){let t=Yv(e.pathname);return`/.well-known/oauth-protected-resource${t==="/"?"":t}`}function Yv(e){return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function Xv(e){return typeof e=="object"&&e!==null&&"setScopeChallengeResolver"in e&&typeof e.setScopeChallengeResolver=="function"}function Zv(e,t){if(typeof e!="string"||!/^[\u0021\u0023-\u005B\u005D-\u007E]+$/.test(e))throw new TypeError(`${t} must satisfy the OAuth scope-token grammar`)}function Qv(e){if(e===null||typeof e!="object"||!Array.isArray(e.scopes)||e.scopes.length===0)throw new TypeError("scope challenge must contain at least one scope");for(let[t,r]of e.scopes.entries())Zv(r,`scope challenge scopes[${t}]`);if(e.errorDescription!==void 0&&typeof e.errorDescription!="string")throw new TypeError("scope challenge errorDescription must be a string");if(e.errorDescription!==void 0&&!/^[\u0020-\u0021\u0023-\u005B\u005D-\u007E]+$/.test(e.errorDescription))throw new TypeError("scope challenge errorDescription must satisfy the RFC 6750 error-description grammar");return e}async function zl(e,t,r){for(let n of e){let o=await r({request:n,...t!==void 0&&{authInfo:t}});if(o!==void 0)return Qv(o)}}function Pl(e){if(e?.resourceMetadataUrl!==void 0)return e.resourceMetadataUrl;if(e?.resource?.protocol==="https:"||e?.resource?.protocol==="http:")return Mm(e.resource)}function Cl(e,t){return Om(new vo(cr.InsufficientScope,e.errorDescription??"Insufficient scope"),{requiredScopes:[...e.scopes],resourceMetadataUrl:t})}var e_=8,t_=6e5;function r_(e){if(e?.maxRounds!==void 0&&(!Number.isInteger(e.maxRounds)||e.maxRounds<1))throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${e.maxRounds})`);if(e?.roundTimeoutMs!==void 0&&(!Number.isFinite(e.roundTimeoutMs)||e.roundTimeoutMs<=0))throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${e.roundTimeoutMs})`);return{maxRounds:e?.maxRounds??e_,roundTimeoutMs:e?.roundTimeoutMs??t_,legacyShim:e?.legacyShim??!0}}function Nm(e,t,r){if(r===null||typeof r!="object"||typeof r.method!="string")throw new te(G.InternalError,`Handler for ${e} returned an invalid input request '${t}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let n=r,o=vp(n);if(o===void 0)throw new te(G.InternalError,`Handler for ${e} returned an input request '${t}' of kind '${n.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:n,required:o}}function n_(){let e=globalThis.crypto;if(e?.randomUUID!==void 0)return e.randomUUID();let t=new Uint8Array(16);e.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let r=[...t].map(n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function El(e,t){if(e==="tools/call")return{content:[{type:"text",text:t}],isError:!0};throw new te(G.InternalError,t)}var o_=class{constructor(e){this._host=e}async fulfill(e,t,r,n,o){let{maxRounds:a,roundTimeoutMs:i}=this._host,l=n.mcpReq.signal,c=o,u=0;for(;;){if(u+=1,u>a)return El(e,Jp(e,a));let m=c.inputRequests,f=m!=null&&Object.keys(m).length>0,y=typeof c.requestState=="string"?c.requestState:void 0;if(!f&&y===void 0)throw new te(G.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let R;if(f){let b=this._host.resolvedClientCapabilities(n),h=[];for(let[v,z]of Object.entries(m)){let{embedded:I,required:T}=Nm(e,v,z);if(I.method!=="roots/list"&&I.params===void 0)throw new te(G.InternalError,`Handler for ${e} returned an input request '${v}' of kind '${I.method}' without params`);if(_o(T,b)!==void 0)return El(e,`Cannot request input '${v}' (${I.method}): the client on this 2025-era connection did not declare the required capability${b===void 0?" (no client capabilities are available on this connection \u2014 per-request legacy serving cannot receive server-to-client requests)":""}`);h.push([v,I])}let $=Wp(l);try{let v={relatedRequestId:n.mcpReq.id,timeout:i,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:$.signal},z=await Promise.all(h.map(async([I,T])=>{try{return[I,await this._dispatchLeg(T,v)]}catch(_){throw $.abort(_),_}}));R=Object.fromEntries(z)}catch(v){if(l.aborted)throw v;return El(e,`Fulfilling input required by '${e}' failed: ${v instanceof Error?v.message:String(v)}`)}finally{$.dispose()}}else await Kp(Gp,l);let S={...n,mcpReq:{...n.mcpReq,inputResponses:R,droppedInputResponseKeys:void 0,requestState:wo(y)}};if(y!==void 0){let b=await this._host.verifyRequestState(y,S,e);b!==void 0&&(S=ml(S,b))}let P=await t(r,S);if(!gt(P))return P;c=P}}async _dispatchLeg(e,t){switch(e.method){case"elicitation/create":{let r=e.params;return r.mode==="url"&&r.elicitationId===void 0&&(r={...r,elicitationId:n_()}),await this._host.sendElicitation(r,t)}case"sampling/createMessage":return await this._host.sendSampling(e.params,t);case"roots/list":return await this._host.listRoots(e.params,t)}}},s_=new Set(["tools/call","prompts/get","resources/read"]),qm,jm,Lm;function Dm(e,t){qm(e,t)}function xm(e,t){jm(e,t)}function Hm(e){return Lm(e)}var wi=class extends hl{_clientCapabilities;_clientVersion;static{qm=(e,t)=>{t.clientCapabilities!==void 0&&(e._clientCapabilities=t.clientCapabilities),t.clientInfo!==void 0&&(e._clientVersion=t.clientInfo)},jm=(e,t)=>{let r=t.filter(n=>!e._supportedProtocolVersions.includes(n));r.length>0&&(e._supportedProtocolVersions=[...e._supportedProtocolVersions,...r]),e.setRequestHandler("server/discover",()=>e._ondiscover())},Lm=e=>e._serverInfo}_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_boundFromTransport=!1;_legacyInputRequiredShim(){return this._legacyShim??=new o_({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:e=>this._inputRequestCapabilityView(e),verifyRequestState:(e,t,r)=>this._verifyRequestState(e,t,r),sendElicitation:(e,t)=>this._sendElicitationLeg(e,t,{validateAcceptedContent:!1}),sendSampling:(e,t)=>this.createMessage(e,t),listRoots:(e,t)=>this.listRoots(e,t)})}oninitialized;constructor(e,t){if(super(t),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new bi,this._requestStateVerify=t?.requestState?.verify,this._inputRequiredServing=r_(t?.inputRequired),t?.cacheHints!==void 0){for(let[r,n]of Object.entries(t.cacheHints))n!==void 0&&ol(n,`cacheHints['${r}']`);this._cacheHints=t.cacheHints}this.setRequestHandler("initialize",r=>this._oninitialize(r)),this.setNotificationHandler("notifications/initialized",()=>this.oninitialized?.()),si(this._supportedProtocolVersions).length>0&&this.setRequestHandler("server/discover",()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}async connect(e){if(this.transport!==void 0)throw new le(pe.AlreadyConnected,"Use a separate Server instance per connection: this instance is already connected to a transport. To connect it to a new transport, call close() first.");this._boundFromTransport&&(this._boundFromTransport=!1,this._negotiatedProtocolVersion=void 0);let t=Kv(e)?.revision;t!==void 0&&!this._servedModernEra()&&lr.includes(t)&&si(this._supportedProtocolVersions).includes(t)&&(this._negotiatedProtocolVersion=t,this._boundFromTransport=!0),await super.connect(e)}_registerLoggingHandler(){this.setRequestHandler("logging/setLevel",async(e,t)=>{let r=t.sessionId||t.http?.req?.headers.get("mcp-session-id")||void 0,{level:n}=e.params,o=mi(Nt,n);return o.success&&this._loggingLevels.set(r,o.data),{}})}buildContext(e,t){let r=e.http||t?.request||t?.closeSSEStream||t?.closeStandaloneSSEStream;return{...e,mcpReq:{...e.mcpReq,log:(n,o,a)=>{if(!this._capabilities.logging)return Promise.resolve();let i;if(this._servedModernEra()){if(i=e.mcpReq.envelope?.[Ct],i===void 0)return Promise.resolve()}else i=this._loggingLevels.get(e.sessionId)??this._loggingLevels.get(void 0);return i!==void 0&&this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i)?Promise.resolve():e.mcpReq.notify({method:"notifications/message",params:{level:n,data:o,logger:a}})},elicitInput:(n,o)=>this.elicitInput(n,o),requestSampling:(n,o)=>this.createMessage(n,o)},http:r?{...e.http,req:t?.request,closeSSE:t?.closeSSEStream,closeStandaloneSSE:t?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Nt.options.map((e,t)=>[e,t]));isMessageIgnored=(e,t)=>{let r=this._loggingLevels.get(t);return r?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r):!1};registerCapabilities(e){if(this.transport)throw new le(pe.AlreadyConnected,"Cannot register capabilities after connecting to transport");let t=!!this._capabilities.logging;this._capabilities=fl(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(e,t){if(e!=="tools/call"){let r=this._cacheHints?.[e],n=s_.has(e);return r===void 0&&!n?async(o,a)=>{let i=await t(o,a);if(gt(i))throw new te(G.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return i}:async(o,a)=>{let i=n?await this._invokeInputRequiredCapableHandler(e,t,o,a):await t(o,a);if(gt(i)){if(!n)throw new te(G.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return i}return r===void 0?i:ai(i,r)}}return async(r,n)=>{let o=ht(this._negotiatedProtocolVersion),a=o.validateRequest("tools/call",r);if(!a.ok)throw new te(a.reason==="not-in-era"?G.InternalError:G.InvalidParams,a.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call request: ${a.message}`);let i=await this._invokeInputRequiredCapableHandler("tools/call",t,r,n);if(gt(i))return i;let l=Qc(i),c=o.validateResult("tools/call",l);if(!c.ok)throw new te(c.reason==="not-in-era"?G.InternalError:G.InvalidParams,c.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call result: ${c.message}`);return c.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&ft(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(e,t,r,n){let o=this._servedModernEra(),a=n.mcpReq.requestState();if(a!==void 0&&typeof a!="string")throw new te(G.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"});let i=n;if(typeof a=="string"){let f=await this._verifyRequestState(a,n,e);f!==void 0&&(i=ml(n,f))}let l;try{l=await t(r,i)}catch(f){throw f instanceof te&&f.code===G.UrlElicitationRequired&&o?new te(G.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { \u2026: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):f}if(!gt(l))return l;if(!o){if(!this._inputRequiredServing.legacyShim)throw new te(G.InternalError,`Handler for ${e} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??rr}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(e,t,r,i,l)}let c=l.inputRequests,u=c!=null&&Object.keys(c).length>0,m=typeof l.requestState=="string";if(!u&&!m)throw new te(G.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(u){let f=this._inputRequestCapabilityView(n);for(let[y,R]of Object.entries(c)){let{embedded:S,required:P}=Nm(e,y,R),b=_o(P,f);if(b!==void 0)throw new bo({requiredCapabilities:b},`Cannot request input '${y}' (${S.method}): the request's client capabilities do not declare the required capability`)}}return l}async _verifyRequestState(e,t,r){if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(e,t)}catch(n){throw this.onerror?.(new Error(`requestState verification rejected ${r}: ${n instanceof Error?n.message:String(n)}`)),new te(G.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"})}}_inputRequestCapabilityView(e){return this._servedModernEra()?e.mcpReq.envelope?.[at]:this._clientCapabilities}_assertPushApiInServedEra(e){if(this._servedModernEra())throw new le(pe.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${e}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead \u2014 the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:e,era:"2026-07-28"})}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new le(pe.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new le(pe.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new le(pe.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new le(pe.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 le(pe.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new le(pe.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 le(pe.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 le(pe.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"completion/complete":if(!this._capabilities.completions)throw new le(pe.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new le(pe.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new le(pe.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 le(pe.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new le(pe.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo;let r=bp(this._supportedProtocolVersions),n=r.includes(t)?t:r[0]??rr;return this._negotiatedProtocolVersion=n,this.transport?.setProtocolVersion?.(n),{protocolVersion:n,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:si(this._supportedProtocolVersions),capabilities:a_(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(e,t){return this._wireCodec().projectCallToolResult(e,t)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra("ping"),this.request({method:"ping"})}async createMessage(e,t){if(this._assertPushApiInServedEra("sampling/createMessage"),(e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new le(pe.CapabilityNotSupported,"Client does not support sampling tools capability.");if(e.messages.length>0){let a=e.messages.at(-1),i=Array.isArray(a.content)?a.content:[a.content],l=i.some(f=>f.type==="tool_result"),c=e.messages.length>1?e.messages.at(-2):void 0,u=c?Array.isArray(c.content)?c.content:[c.content]:[],m=u.some(f=>f.type==="tool_use");if(l){if(i.some(f=>f.type!=="tool_result"))throw new te(G.InvalidParams,"The last message must contain only tool_result content if any is present");if(!m)throw new te(G.InvalidParams,"tool_result blocks are not matching any tool_use from the previous message")}if(m){let f=new Set(u.filter(R=>R.type==="tool_use").map(R=>R.id)),y=new Set(i.filter(R=>R.type==="tool_result").map(R=>R.toolUseId));if(f.size!==y.size||![...f].every(R=>y.has(R)))throw new te(G.InvalidParams,"ids of tool_result blocks and tool_use blocks from previous message do not match")}}let r=!!(e.tools||e.toolChoice),n=await this.request({method:"sampling/createMessage",params:e},t),o=this._wireCodec().samplingResultVariant(r,n);if(!o.ok)throw new le(pe.InvalidResult,`Invalid sampling/createMessage result: ${o.reason==="invalid"?o.message:o.reason}`);return o.value}async elicitInput(e,t){switch(this._assertPushApiInServedEra("elicitation/create"),e.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw new le(pe.CapabilityNotSupported,"Client does not support url elicitation.");break;case"form":if(!this._clientCapabilities?.elicitation?.form)throw new le(pe.CapabilityNotSupported,"Client does not support form elicitation.");break}return this._sendElicitationLeg(e,t)}async _sendElicitationLeg(e,t,r){let n=e.mode??"form",o=r?.validateAcceptedContent??!0;switch(n){case"url":{let a=e;return this.request({method:"elicitation/create",params:a},t)}case"form":{let a=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:a},t);if(o&&i.action==="accept"&&i.content&&a.requestedSchema)try{let l=this._jsonSchemaValidator.getValidator(a.requestedSchema)(i.content);if(!l.valid)throw new te(G.InvalidParams,`Elicitation response content does not match requested schema: ${l.errorMessage}`)}catch(l){throw l instanceof te?l:new te(G.InternalError,`Error validating elicitation response: ${l instanceof Error?l.message:String(l)}`)}return i}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new le(pe.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._assertPushApiInServedEra("roots/list"),this.request({method:"roots/list",params:e},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"})}};function a_(e){return{...e}}function i_(e,t){let r=0,n=[e];for(;n.length>0;){let o=n.pop();if(!(o===null||typeof o!="object"))if(Array.isArray(o))for(let a of o){if(++r>t)return r;a!==null&&typeof a=="object"&&n.push(a)}else for(let a in o){if(!Object.prototype.hasOwnProperty.call(o,a))continue;if(++r>t)return r;let i=o[a];i!==null&&typeof i=="object"&&n.push(i)}}return r}function c_(e){if(!(e===void 0||e===1/0)){if(typeof e!="number"||Number.isNaN(e)||e<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}var Ei=class{server;_maxToolInputElements;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(e){let t=this._registeredTools[e];if(!(t===void 0||!t.enabled)){if(Object.hasOwn(this._toolInputSchemaJson,e))return this._toolInputSchemaJson[e];if(t.inputSchema===void 0)return Tm;try{let r=ur(t.inputSchema,"input");return this._toolInputSchemaJson[e]=r,r}catch{return}}}constructor(e,t){this.server=new wi(e,t),this._maxToolInputElements=c_(t?.maxToolInputElements),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(e){return Xv(e)&&e.setScopeChallengeResolver(t=>this.resolveScopeChallenge(t)),await this.server.connect(e)}async close(){await this.server.close()}resolveScopeChallenge=e=>{switch(e.request.method){case"tools/call":{let t=e.request.params?.name;if(typeof t!="string")return;let r=this._registeredTools[t];return r===void 0||!r.enabled?void 0:r.scopeChallenge?.(e)}case"resources/read":{let t=e.request.params?.uri;if(typeof t!="string")return;let r;try{r=new URL(t)}catch{return}let n=this._registeredResources[r.toString()];if(n!==void 0)return n.enabled?n.scopeChallenge?.(e):void 0;for(let o of Object.values(this._registeredResourceTemplates))if(o.resourceTemplate.uriTemplate.match(r.toString()))return o.enabled?o.scopeChallenge?.(e):void 0;return}case"prompts/get":{let t=e.request.params?.name;if(typeof t!="string")return;let r=this._registeredPrompts[t];return r===void 0||!r.enabled?void 0:r.scopeChallenge?.(e)}default:return}};_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 r={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?l_(e,t.inputSchema):Tm,annotations:t.annotations,icons:t.icons,execution:t.execution,_meta:t._meta};return t.outputSchema&&(r.outputSchema=ur(t.outputSchema,"output")),r})})),this.server.setRequestHandler("tools/call",async(e,t)=>{let r=this._registeredTools[e.params.name];if(!r)throw new te(G.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new te(G.InvalidParams,`Tool ${e.params.name} disabled`);try{let n=await this.validateToolInput(r,e.params.arguments,e.params.name),o=await this.executeToolHandler(r,n,t);return await this.validateToolOutput(r,o,e.params.name),gt(o)?o:this.server.projectCallToolResult(o,r.outputSchemaJson)}catch(n){if(n instanceof te&&n.code===G.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(this._maxToolInputElements!==void 0&&i_(t,this._maxToolInputElements)>this._maxToolInputElements)throw new te(G.InvalidParams,`Invalid arguments for tool ${r}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let n=await ir(e.inputSchema,t??{});if(!n.success)throw new te(G.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${n.error}`);return n.data}async validateToolOutput(e,t,r){if(!e.outputSchema||gt(t)||t.isError)return;if(t.structuredContent===void 0)throw new te(G.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=await ir(e.outputSchema,t.structuredContent);if(!n.success)throw new te(G.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${n.error}`)}async executeToolHandler(e,t,r){return e.executor(t,r)}_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 ll(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return ul(e),this.handleResourceCompletion(e,e.params.ref);default:throw new te(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new te(G.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new te(G.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return $o;let n=km(Cm(r.argsSchema)?.[e.params.argument.name]);if(!Tl(n))return $o;let o=Gv(n);return o?Pm(await o(e.params.argument.value,e.params.context)):$o}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(o=>o.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return $o;throw new te(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);return n?Pm(await n(e.params.argument.value,e.params.context)):$o}_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 r=Object.entries(this._registeredResources).filter(([o,a])=>a.enabled).map(([o,a])=>({uri:o,name:a.name,...a.metadata})),n=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let a=await o.resourceTemplate.listCallback(t);for(let i of a.resources)n.push({...o.metadata,...i})}return{resources:[...r,...n]}}),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 r;try{r=new URL(e.params.uri)}catch{throw new te(G.InvalidParams,`Resource URI ${e.params.uri} is invalid`,{uri:e.params.uri,reason:"invalid_uri"})}let n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new te(G.InvalidParams,`Resource ${r} disabled`);return ai(await n.readCallback(r,t),n.cacheHint)}for(let o of Object.values(this._registeredResourceTemplates)){let a=o.resourceTemplate.uriTemplate.match(r.toString());if(a){if(!o.enabled)throw new te(G.InvalidParams,`Resource template ${o.resourceTemplate.uriTemplate} disabled`);return ai(await o.readCallback(r,a,t),o.cacheHint)}}throw new ii(e.params.uri)}),this._resourceHandlersInitialized=!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?Fp(t.argsSchema):void 0,icons:t.icons,_meta:t._meta}))})),this.server.setRequestHandler("prompts/get",async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new te(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new te(G.InvalidParams,`Prompt ${e.params.name} disabled`);return r.handler(e.params.arguments,t)}),this._promptHandlersInitialized=!0)}registerResource(e,t,r,n){let{cacheHint:o,scopeChallenge:a,...i}=r,l=i;if(o!==void 0&&ol(o,`resource ${e}`),typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let c=this._createRegisteredResource(e,r.title,t,l,a,n);return o!==void 0&&(c.cacheHint=o),this.setResourceRequestHandlers(),this.sendResourceListChanged(),c}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let c=this._createRegisteredResourceTemplate(e,r.title,t,l,a,n);return o!==void 0&&(c.cacheHint=o),this.setResourceRequestHandlers(),this.sendResourceListChanged(),c}}_createRegisteredResource(e,t,r,n,o,a){let i={name:e,title:t,metadata:n,readCallback:a,scopeChallenge:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:l=>{l.uri!==void 0&&l.uri!==r&&(delete this._registeredResources[r],l.uri&&(this._registeredResources[l.uri]=i)),l.name!==void 0&&(i.name=l.name),l.metadata!==void 0&&(i.metadata=l.metadata),l.title!==void 0&&(i.title=l.title,i.metadata={...i.metadata,title:l.title}),l.callback!==void 0&&(i.readCallback=l.callback),l.scopeChallenge!==void 0&&(i.scopeChallenge=l.scopeChallenge===null?void 0:l.scopeChallenge),l.enabled!==void 0&&(i.enabled=l.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,t,r,n,o,a){let i={resourceTemplate:r,title:t,metadata:n,readCallback:a,scopeChallenge:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:c=>{c.name!==void 0&&c.name!==e&&(delete this._registeredResourceTemplates[e],c.name&&(this._registeredResourceTemplates[c.name]=i)),c.template!==void 0&&(i.resourceTemplate=c.template),c.metadata!==void 0&&(i.metadata=c.metadata),c.title!==void 0&&(i.title=c.title,i.metadata={...i.metadata,title:c.title}),c.callback!==void 0&&(i.readCallback=c.callback),c.scopeChallenge!==void 0&&(i.scopeChallenge=c.scopeChallenge===null?void 0:c.scopeChallenge),c.enabled!==void 0&&(i.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let l=r.uriTemplate.variableNames;return Array.isArray(l)&&l.some(c=>!!r.completeCallback(c))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,t,r,n,o,a,i,l){let c=n,u=o,m={title:t,description:r,argsSchema:n,icons:a,scopeChallenge:i,_meta:l,handler:zm(e,n,o),enabled:!0,disable:()=>m.update({enabled:!1}),enable:()=>m.update({enabled:!0}),remove:()=>m.update({name:null}),update:f=>{f.name!==void 0&&f.name!==e&&(delete this._registeredPrompts[e],f.name&&(this._registeredPrompts[f.name]=m)),f.title!==void 0&&(m.title=f.title),f.description!==void 0&&(m.description=f.description),f.icons!==void 0&&(m.icons=f.icons),f.scopeChallenge!==void 0&&(m.scopeChallenge=f.scopeChallenge===null?void 0:f.scopeChallenge),f._meta!==void 0&&(m._meta=f._meta);let y=!1;f.argsSchema!==void 0&&(m.argsSchema=f.argsSchema,c=f.argsSchema,y=!0),f.callback!==void 0&&(u=f.callback,y=!0),y&&(m.handler=zm(e,c,u)),f.enabled!==void 0&&(m.enabled=f.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=m,n){let f=Cm(n);f&&Object.values(f).some(y=>Tl(km(y)))&&this.setCompletionRequestHandler()}return m}_createRegisteredTool(e,t,r,n,o,a,i,l,c,u,m){yl(e);let f=m,y,R={title:t,description:r,inputSchema:n,outputSchema:o,get outputSchemaJson(){return y??=$m(R.outputSchema)},set outputSchemaJson(S){y=S},annotations:a,icons:i,execution:l,scopeChallenge:c,_meta:u,handler:m,executor:Em(n,m),enabled:!0,disable:()=>R.update({enabled:!1}),enable:()=>R.update({enabled:!0}),remove:()=>R.update({name:null}),update:S=>{S.name!==void 0&&S.name!==e&&(typeof S.name=="string"&&yl(S.name),delete this._registeredTools[e],delete this._toolInputSchemaJson[e],S.name&&(delete this._toolInputSchemaJson[S.name],this._registeredTools[S.name]=R,e=S.name)),S.title!==void 0&&(R.title=S.title),S.description!==void 0&&(R.description=S.description);let P=!1;S.paramsSchema!==void 0&&(R.inputSchema=S.paramsSchema,delete this._toolInputSchemaJson[e],P=!0),S.callback!==void 0&&(R.handler=S.callback,f=S.callback,P=!0),P&&(R.executor=Em(R.inputSchema,f)),S.outputSchema!==void 0&&(R.outputSchema=S.outputSchema,R.outputSchemaJson=$m(S.outputSchema)),S.annotations!==void 0&&(R.annotations=S.annotations),S.icons!==void 0&&(R.icons=S.icons),S.scopeChallenge!==void 0&&(R.scopeChallenge=S.scopeChallenge===null?void 0:S.scopeChallenge),S._meta!==void 0&&(R._meta=S._meta),S.enabled!==void 0&&(R.enabled=S.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=R,this.setToolRequestHandlers(),this.sendToolListChanged(),R}registerTool(e,t,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:n,description:o,inputSchema:a,outputSchema:i,annotations:l,icons:c,scopeChallenge:u,_meta:m}=t;return this._createRegisteredTool(e,n,o,hi(a),hi(i),l,c,void 0,u,m,r)}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:n,description:o,argsSchema:a,icons:i,scopeChallenge:l,_meta:c}=t,u=this._createRegisteredPrompt(e,n,o,hi(a),r,i,l,c);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),u}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()}};function Em(e,t){if(e){let n=t;return async(o,a)=>n(o,a)}let r=t;return async(n,o)=>r(o)}var Tm={type:"object",properties:{}};function l_(e,t){let r=ur(t,"input"),n=di(r);return n.valid||console.warn(`[mcp-sdk] tool '${e}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${n.reason}`),r}function $m(e){if(e!==void 0)try{return ur(e,"output")}catch{return}}function zm(e,t,r){if(t){let n=r;return async(o,a)=>{let i=await ir(t,o??{});if(!i.success)throw new te(G.InvalidParams,`Invalid arguments for prompt ${e}: ${i.error}`);return n(i.data,a)}}else{let n=r;return async(o,a)=>n(a)}}function Pm(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}var $o={completion:{values:[],hasMore:!1}};function Cm(e){let t=e;if(t.shape&&typeof t.shape=="object")return t.shape}function u_(e){return e?.type==="optional"}function km(e){return u_(e)?e.def?.innerType??e:e}var Bm=class{_listeners=new Set;constructor(e){this.onerror=e}publish(e){for(let t of this._listeners)try{t(e)}catch(r){this.onerror?.(r instanceof Error?r:new Error(String(r)))}}subscribe(e){this._listeners.add(e);let t=!0;return()=>{t&&(t=!1,this._listeners.delete(e))}}get listenerCount(){return this._listeners.size}};function Fm(e){return{toolsChanged:()=>e.publish({kind:"tools_list_changed"}),promptsChanged:()=>e.publish({kind:"prompts_list_changed"}),resourcesChanged:()=>e.publish({kind:"resources_list_changed"}),resourceUpdated:t=>e.publish({kind:"resource_updated",uri:t})}}function d_(e,t){switch(t.kind){case"tools_list_changed":return e.toolsListChanged===!0;case"prompts_list_changed":return e.promptsListChanged===!0;case"resources_list_changed":return e.resourcesListChanged===!0;case"resource_updated":return e.resourceSubscriptions!==void 0&&e.resourceSubscriptions.includes(t.uri)}}function p_(e,t){let r={},n=o=>t===void 0||o===!0;return e.toolsListChanged===!0&&n(t?.tools?.listChanged)&&(r.toolsListChanged=!0),e.promptsListChanged===!0&&n(t?.prompts?.listChanged)&&(r.promptsListChanged=!0),e.resourcesListChanged===!0&&n(t?.resources?.listChanged)&&(r.resourcesListChanged=!0),e.resourceSubscriptions!==void 0&&e.resourceSubscriptions.length>0&&n(t?.resources?.subscribe)&&(r.resourceSubscriptions=[...e.resourceSubscriptions]),r}function m_(e){switch(e.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed",...e.params!==void 0&&{params:e.params}};case"prompts_list_changed":return{method:"notifications/prompts/list_changed",...e.params!==void 0&&{params:e.params}};case"resources_list_changed":return{method:"notifications/resources/list_changed",...e.params!==void 0&&{params:e.params}};case"resource_updated":return{method:"notifications/resources/updated",params:{...e.params,uri:e.uri}}}}var kl=1024;function Um(e,t,r){return Response.json({jsonrpc:"2.0",error:{code:t,message:r},id:e},{status:200})}function Vm(e,t){return{method:e.method,params:{...e.params,_meta:{...e.params?._meta,[or]:t}}}}function h_(e){let t=ht(Ro).validateRequest("subscriptions/listen",e);return t.ok?t.value.params?.notifications:void 0}function Gm(e){let{bus:t,onerror:r}=e,n=e.maxSubscriptions??kl,o=e.keepAliveMs??Jr,a=new Set;function i(l,c,u,m){if(a.size>=n)return r?.(new Error(`subscriptions/listen refused: subscription limit reached (${n})`)),Um(l.id,-32603,"Subscription limit reached");let f=h_(l);if(f===void 0)return Um(l.id,-32602,"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter");let y=p_(f,u),R=l.id,S=new TextEncoder,P,b=!1,h,$,v,z=C=>{if(!b)try{P.enqueue(S.encode(C))}catch(M){r?.(M instanceof Error?M:new Error(String(M)))}},I=(C,M)=>{z(`event: message
32
+ data: ${JSON.stringify({jsonrpc:"2.0",method:C,params:M})}
33
+
34
+ `)},T=C=>{if(!b){C&&z(`event: message
35
+ data: ${JSON.stringify({jsonrpc:"2.0",id:R,result:{resultType:"complete",_meta:{[or]:R,[st]:m}}})}
36
+
37
+ `),b=!0;try{h?.()}catch(M){r?.(M instanceof Error?M:new Error(String(M)))}$!==void 0&&clearInterval($),v?.(),a.delete(T);try{P.close()}catch{}}},_=new ReadableStream({start(C){P=C;let M=Vm({method:"notifications/subscriptions/acknowledged",params:{notifications:y}},R);if(I(M.method,M.params),Object.keys(y).length===0){T(!0);return}h=t.subscribe(U=>{if(b||!d_(y,U))return;let q=Vm(m_(U),R);I(q.method,q.params)}),$=zo(o,()=>z(`: keepalive
38
+
39
+ `)),a.add(T)},cancel(){T(!1)}});if(c!==void 0)if(c.aborted)T(!1);else{let C=()=>T(!1);c.addEventListener("abort",C,{once:!0}),v=()=>c.removeEventListener("abort",C)}return new Response(_,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}return{serve:i,closeAll(){for(let l of a)l(!0)},get openCount(){return a.size}}}async function f_(e,t,r){let n=new $l({classification:r.classification,...r.responseMode!==void 0&&{responseMode:r.responseMode},...r.keepAliveMs!==void 0&&{keepAliveMs:r.keepAliveMs}});return await e.connect(n),n.handleMessage(t,{...r.request!==void 0&&{request:r.request},...r.authInfo!==void 0&&{authInfo:r.authInfo}})}var Al=4*1024*1024,Il=100;function Km(e){return`Payload Too Large: Request body must not exceed ${e} bytes`}function Ol(e){if(e===void 0)return Al;if(typeof e!="number"||!Number.isFinite(e)||e<=0)throw new RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(e)}`);return e}async function $i(e,t=Al){if(Number(e.headers.get("content-length"))>t)return{tooLarge:!0};if(e.body===null)return{tooLarge:!1,text:""};let r=e.body.getReader(),n=new TextDecoder,o=0,a="";try{for(;;){let{done:i,value:l}=await r.read();if(i)break;if(o+=l.byteLength,o>t)return{tooLarge:!0};a+=n.decode(l,{stream:!0})}}finally{r.releaseLock()}return{tooLarge:!1,text:a+n.decode()}}var Ml=class{sessionIdGenerator;_started=!1;_hasHandledRequest=!1;_closed=!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;_keepAliveMs;_maxRequestBodySize;_scopeChallengeResolver;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??Dn,this._keepAliveMs=e.keepAliveMs??Jr,this._maxRequestBodySize=Ol(e.maxRequestBodySize)}startKeepAlive(e,t){if(this._closed)return;let r=zo(this._keepAliveMs,()=>{try{e.enqueue(t.encode(`: keepalive
40
+
41
+ `))}catch{r!==void 0&&clearInterval(r)}});return r}setScopeChallengeResolver(e){this._scopeChallengeResolver=e}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}setSupportedProtocolVersions(e){this._supportedProtocolVersions=e}createJsonErrorResponse(e,t,r,n){let o={code:t,message:r};return n?.data!==void 0&&(o.data=n.data),Response.json({jsonrpc:"2.0",error:o,id:null},{status:e,headers:{"Content-Type":"application/json",...n?.headers}})}async _checkScopeChallenge(e,t){if(!this._scopeChallengeResolver)return;let r=await zl(e.filter(n=>Xe(n)),t,this._scopeChallengeResolver);return r===void 0?void 0:Cl(r,Pl(t))}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 r=`Invalid Host header: ${t}`;return this.onerror?.(new Error(r)),this.createJsonErrorResponse(403,-32e3,r)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get("origin");if(t&&!this._allowedOrigins.includes(t)){let r=`Invalid Origin header: ${t}`;return this.onerror?.(new Error(r)),this.createJsonErrorResponse(403,-32e3,r)}}}}async handleRequest(e,t){if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!this.sessionIdGenerator&&this._hasHandledRequest)throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let r=this.validateRequestHeaders(e);if(r)return r;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()}}supportsEmptySSEData(e){return this._supportedProtocolVersions.includes(e)&&e>="2025-11-25"}async writePrimingEvent(e,t,r,n){if(!this._eventStore||!this.supportsEmptySSEData(n))return;let o=await this._eventStore.storeEvent(r,{}),a=`id: ${o}
42
+ data:
43
+
44
+ `;this._retryInterval!==void 0&&(a=`id: ${o}
45
+ retry: ${this._retryInterval}
46
+ data:
47
+
48
+ `),e.enqueue(t.encode(a))}async handleGetRequest(e){if(!e.headers.get("accept")?.includes("text/event-stream"))return this.onerror?.(new 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 r=this.validateProtocolVersion(e);if(r)return r;if(this._eventStore){let c=e.headers.get("last-event-id");if(c)return this.replayEvents(c)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(new Error("Conflict: Only one SSE stream is allowed per session")),this.createJsonErrorResponse(409,-32e3,"Conflict: Only one SSE stream is allowed per session");let n=new TextEncoder,o,a,i=new ReadableStream({start:c=>{o=c},cancel:()=>{a!==void 0&&clearInterval(a),this._streamMapping.get(this._standaloneSseStreamId)?.controller===o&&this._streamMapping.delete(this._standaloneSseStreamId)}}),l={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};return this.sessionId!==void 0&&(l["mcp-session-id"]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:o,encoder:n,cleanup:()=>{a!==void 0&&clearInterval(a),this._streamMapping.delete(this._standaloneSseStreamId);try{o.close()}catch{}}}),a=this.startKeepAlive(o,n),new Response(i,{headers:l})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(new 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?.(new Error("Invalid event ID format")),this.createJsonErrorResponse(400,-32e3,"Invalid event ID format");if(this._streamMapping.get(t)!==void 0)return this.onerror?.(new Error("Conflict: Stream already has an active connection")),this.createJsonErrorResponse(409,-32e3,"Conflict: Stream already has an active connection")}let r={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(r["mcp-session-id"]=this.sessionId);let n=new TextEncoder,o,a,i=!1,l,c=new ReadableStream({start:m=>{o=m},cancel:()=>{i=!0,a!==void 0&&clearInterval(a),l!==void 0&&this._streamMapping.get(l)?.controller===o&&this._streamMapping.delete(l)}}),u=new Set;if(l=await this._eventStore.replayEventsAfter(e,{send:async(m,f)=>{if(u.add(m),!this.writeSSEEvent(o,n,f,m))try{o.close()}catch{}}}),this._closed||i){try{o.close()}catch{}return this.createJsonErrorResponse(404,-32001,"Session not found")}if(this._streamMapping.get(l)?.cleanup(),this._streamMapping.set(l,{controller:o,encoder:n,replayedEventIds:u,cleanup:()=>{a!==void 0&&clearInterval(a),this._streamMapping.delete(l);try{o.close()}catch{}}}),l!==this._standaloneSseStreamId&&![...this._requestToStreamMapping.values()].includes(l)){this._streamMapping.delete(l);try{o.close()}catch{}}return this._streamMapping.get(l)?.controller===o&&(a=this.startKeepAlive(o,n)),new Response(c,{headers:r})}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(500,-32e3,"Error replaying events")}}writeSSEEvent(e,t,r,n){try{let o=`event: message
49
+ `;return n&&(o+=`id: ${n}
50
+ `),o+=`data: ${JSON.stringify(r)}
51
+
52
+ `,e.enqueue(t.encode(o)),!0}catch(o){return this.onerror?.(o),!1}}handleUnsupportedRequest(){return this.onerror?.(new 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 r=e.headers.get("accept");if(!r?.includes("application/json")||!r.includes("text/event-stream"))return this.onerror?.(new 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");if(!Eo(e.headers.get("content-type")))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let n=e,o;if(t?.parsedBody===void 0)try{let b=await $i(e,this._maxRequestBodySize);if(b.tooLarge){let h=Km(this._maxRequestBodySize);return this.onerror?.(new Error(h)),this.createJsonErrorResponse(413,-32e3,h)}o=JSON.parse(b.text)}catch(b){return this.onerror?.(b),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else o=t.parsedBody;if(Array.isArray(o)&&o.length>Il)return this.onerror?.(new Error(`Invalid Request: Batch must not exceed ${Il} messages`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Batch must not exceed ${Il} messages`);let a;try{a=Array.isArray(o)?o.map(b=>kr.parse(b)):[kr.parse(o)]}catch(b){return this.onerror?.(b),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let i=a.some(b=>cl(b));if(i){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(a.length>1)return this.onerror?.(new 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(!i){let b=this.validateSession(e);if(b)return b;let h=this.validateProtocolVersion(e);if(h)return h}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let l;try{l=await this._checkScopeChallenge(a,t?.authInfo)}catch(b){return this.onerror?.(b),this.createJsonErrorResponse(500,-32603,"Internal server error")}if(l)return l;if(!a.some(b=>Xe(b))){for(let b of a)this.onmessage?.(b,{authInfo:t?.authInfo,request:n});return new Response(null,{status:202})}let c=crypto.randomUUID(),u=a.find(b=>cl(b)),m=u?u.params.protocolVersion:e.headers.get("mcp-protocol-version")??ps;if(this._enableJsonResponse)return new Promise(b=>{this._streamMapping.set(c,{resolveJson:b,cleanup:()=>{this._streamMapping.delete(c)}});for(let h of a)Xe(h)&&this._requestToStreamMapping.set(h.id,c);for(let h of a)this.onmessage?.(h,{authInfo:t?.authInfo,request:n})});let f=new TextEncoder,y,R,S=new ReadableStream({start:b=>{y=b},cancel:()=>{R!==void 0&&clearInterval(R),this._streamMapping.get(c)?.controller===y&&this._streamMapping.delete(c)}}),P={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(P["mcp-session-id"]=this.sessionId);for(let b of a)Xe(b)&&(this._streamMapping.set(c,{controller:y,encoder:f,cleanup:()=>{R!==void 0&&clearInterval(R),this._streamMapping.delete(c);try{y.close()}catch{}}}),this._requestToStreamMapping.set(b.id,c));await this.writePrimingEvent(y,f,c,m);for(let b of a){let h,$;Xe(b)&&this._eventStore&&this.supportsEmptySSEData(m)&&(h=()=>{this.closeSSEStream(b.id)},$=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(b,{authInfo:t?.authInfo,request:n,closeSSEStream:h,closeStandaloneSSEStream:$})}return this._streamMapping.get(c)?.controller===y&&(R=this.startKeepAlive(y,f)),new Response(S,{status:200,headers:P})}catch(r){return this.onerror?.(r),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(r)})}}async handleDeleteRequest(e){let t=this.validateSession(e);if(t)return t;let r=this.validateProtocolVersion(e);if(r)return r;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new 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?.(new 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?.(new 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 r=`Bad Request: Unsupported protocol version: ${t} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(new Error(r)),this.createJsonErrorResponse(400,-32e3,r)}}async close(){if(!this._closed){this._closed=!0;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 r=this._streamMapping.get(t);r&&r.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let r=t?.relatedRequestId;if((it(e)||ct(e))&&(r=e.id),r===void 0){if(it(e)||ct(e))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let a;this._eventStore&&(a=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let i=this._streamMapping.get(this._standaloneSseStreamId);if(i===void 0)return;i.controller&&i.encoder&&(a===void 0||!i.replayedEventIds?.has(a))&&this.writeSSEEvent(i.controller,i.encoder,e,a);return}let n=this._requestToStreamMapping.get(r);if(!n)throw new Error(`No connection established for request ID: ${String(r)}`);let o=this._streamMapping.get(n);if(!this._enableJsonResponse){let a;this._eventStore&&(a=await this._eventStore.storeEvent(n,e),o=this._streamMapping.get(n)),o?.controller&&o?.encoder&&(a===void 0||!o.replayedEventIds?.has(a))&&this.writeSSEEvent(o.controller,o.encoder,e,a)}if(it(e)||ct(e)){this._requestResponseMap.set(r,e);let a=[...this._requestToStreamMapping.entries()].filter(([i,l])=>l===n).map(([i])=>i);if(a.every(i=>this._requestResponseMap.has(i))){if(!o){if(this._enableJsonResponse)throw new Error(`No connection established for request ID: ${String(r)}`);if(!this._eventStore){this.onerror?.(new Error(`Response for request ID ${String(r)} is undeliverable: per-request stream is disconnected and no eventStore is configured`));for(let i of a)this._requestResponseMap.delete(i),this._requestToStreamMapping.delete(i);return}for(let i of a)this._requestResponseMap.delete(i),this._requestToStreamMapping.delete(i);return}if(this._enableJsonResponse&&o.resolveJson){let i={"Content-Type":"application/json"};this.sessionId!==void 0&&(i["mcp-session-id"]=this.sessionId);let l=a.map(c=>this._requestResponseMap.get(c));l.length===1?o.resolveJson(Response.json(l[0],{status:200,headers:i})):o.resolveJson(Response.json(l,{status:200,headers:i})),o.cleanup()}else o.cleanup();for(let i of a)this._requestResponseMap.delete(i),this._requestToStreamMapping.delete(i)}}}};function Dt(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let{method:t,id:r}=e;return typeof t!="string"?null:typeof r=="string"||typeof r=="number"?r:null}function yt(e,t,r,n,o=null){return Response.json({jsonrpc:"2.0",error:{code:t,message:r,...n!==void 0&&{data:n}},id:o},{status:e,...e===405&&{headers:{Allow:"POST"}}})}function Ti(e,t=null){return yt(e.httpStatus,e.code,e.message,e.data,t)}function Po(e){return e instanceof Error?e:new Error(String(e))}function Co(e=null){return yt(500,-32603,"Internal server error",void 0,e)}function Jm(e){if(e.transport!==void 0)throw new Error("The factory returned an instance that is still serving another request. Return a new instance for each request.")}function g_(e,t,r,n){return async(o,a)=>{if(o.method.toUpperCase()!=="POST")return yt(405,-32e3,"Method not allowed.");try{let i=await e({era:"legacy",...a?.authInfo!==void 0&&{authInfo:a.authInfo},requestInfo:o}),l=new Ml({sessionIdGenerator:void 0,...r!==void 0&&{keepAliveMs:r},...n!==void 0&&{maxRequestBodySize:n}});await i.connect(l);let c=()=>{l.close().catch(()=>{}),i.close().catch(()=>{})};o.signal?.addEventListener("abort",c,{once:!0});let u=await l.handleRequest(o,{...a?.authInfo!==void 0&&{authInfo:a.authInfo},...a?.parsedBody!==void 0&&{parsedBody:a.parsedBody}});if(u.body===null||gl(u.headers.get("content-type"))!=="text/event-stream")return c(),u;let m=u.body.getReader(),f=!1,y=()=>{f||(f=!0,c())},R=new ReadableStream({pull:async S=>{try{let{done:P,value:b}=await m.read();if(P){y(),S.close();return}b!==void 0&&S.enqueue(b)}catch(P){y(),S.error(P)}},cancel:S=>(y(),m.cancel(S).catch(()=>{}))});return new Response(R,{status:u.status,statusText:u.statusText,headers:u.headers})}catch(i){try{t?.(Po(i))}catch{}return Co(Dt(a?.parsedBody))}}}function Wm(e){return{protocolVersionHeader:e.headers.get("mcp-protocol-version")??void 0,mcpMethodHeader:e.headers.get("mcp-method")??void 0,mcpNameHeader:e.headers.get("mcp-name")??void 0}}async function Ym(e,t,r=!0,n=Al){let o=e.method.toUpperCase(),a,i=t,l=e,c=!1;if(o==="POST"){if(i===void 0){r&&(l=e.clone());let u;try{let m=await $i(e,n);if(m.tooLarge)return{step:"body-too-large"};u=m.text}catch{return{step:"unreadable-body"}}try{a=u.length===0?void 0:JSON.parse(u)}catch{c=!0}!c&&a!==void 0&&(i=a)}else a=i;if(c||a===void 0)return{step:"no-json-body",forwardRequest:l}}return{step:"classified",outcome:pi({httpMethod:o,...Wm(e),...a!==void 0&&{body:a}}),body:a,parsedBody:i,forwardRequest:l}}async function Xm(e,t,r){let n=Ol(r?.maxRequestBodySize),o=await Ym(t===void 0&&e.method.toUpperCase()==="POST"?e.clone():e,t,!1,n);return o.step==="no-json-body"||o.step==="classified"&&o.outcome.kind==="legacy"}function Zm(e,t={}){let{legacy:r,onerror:n,responseMode:o}=t,a=Ol(t.maxRequestBodySize);if(typeof r=="function")throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.");let i=new Set,l=!1,c=h=>{try{n?.(h)}catch{}},u=t.bus??new Bm(c),m=Fm(u),f=Gm({bus:u,maxSubscriptions:t.maxSubscriptions??kl,keepAliveMs:t.keepAliveMs??Jr,onerror:c});o==="json"&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let y=r==="reject"?void 0:g_(e,c,t.keepAliveMs,a);async function R(h,$,v){let z=h.classification.revision;if(z===void 0||!lr.includes(z)){let D=new ci({supported:[...lr],requested:z??"unknown"});return c(D),yt(400,D.code,D.message,D.data,Dt(h.message))}let I=Hp({httpMethod:$.method,...Wm($)},h);if(I!==void 0)return c(new Error(`Rejected inbound request (${I.cell}): ${I.message}`)),Ti(I,Dt(h.message));let T=h.messageKind==="request"?Lt(h.message.params):void 0,_=T?.[at];if(h.messageKind==="request"){let D=Sp(h.message.method);if(D!==void 0){let W=_o(D,_);if(W!==void 0){let F=new bo({requiredCapabilities:W});return c(F),yt(xp(F.code,"ladder"),F.code,F.message,F.data,h.message.id)}}}let C=await e({era:"modern",...v!==void 0&&{authInfo:v},requestInfo:$}),M=C instanceof Ei?C.server:C;if(Jm(M),h.messageKind==="request"&&h.message.method==="subscriptions/listen"){let D=M.getCapabilities(),W=Hm(M);return C.close().catch(c),f.serve(h.message,$.signal,D,W)}if(h.messageKind==="request"&&h.message.method==="tools/call"&&C instanceof Ei){let D=h.message.params,W=typeof D?.name=="string"?D.name:void 0,F=W===void 0?void 0:C.toolInputSchemaJson(W);if(F!==void 0){let ie=di(F);if(ie.declarations!==void 0&&ie.declarations.length>0){let he=Dp(ie.declarations,D?.arguments,$.headers);if(he!==void 0)return C.close().catch(c),c(new Error(`Rejected inbound request (${he.cell}): ${he.message}`)),Ti(he,h.message.id)}}}if(h.messageKind==="request"&&C instanceof Ei)try{let D=await zl([h.message],v,W=>C.resolveScopeChallenge(W));if(D!==void 0)return C.close().catch(c),Cl(D,Pl(v))}catch(D){return C.close().catch(c),c(Po(D)),Co(h.message.id)}Jm(M),tm(M,z),xm(M,lr),T!==void 0&&Dm(M,{clientInfo:T[nr],clientCapabilities:_});let U=M.onclose;i.add(M);let q=()=>{i.delete(M),M.onclose===q&&(M.onclose=U),U?.()};M.onclose=q;try{let D=await f_(C,h.message,{classification:h.classification,request:$,...v!==void 0&&{authInfo:v},...o!==void 0&&{responseMode:o},...t.keepAliveMs!==void 0&&{keepAliveMs:t.keepAliveMs}});return h.messageKind==="notification"&&queueMicrotask(()=>void M.close().catch(()=>{})),D}catch(D){return D instanceof le&&D.code===pe.ConnectionClosed?new Response(null,{status:499}):(await M.close().catch(()=>{}),i.delete(M),c(Po(D)),Co(Dt(h.message)))}}async function S(h,$,v,z){if(y!==void 0)return y($,{...v!==void 0&&{authInfo:v},...z!==void 0&&{parsedBody:z}});let I=Vp(h,lr);return I===void 0?new Response(null,{status:202}):(c(new Error(`Rejected 2025-era request on a modern-only endpoint (${I.cell}): ${I.message}`)),Ti(I,Dt(z)))}async function P(h,$){let v=$?.authInfo;if(h.method.toUpperCase()==="POST"&&!Eo(h.headers.get("content-type")))return c(new Error("Unsupported Media Type: Content-Type must be application/json")),yt(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let z=await Ym(h,$?.parsedBody,!0,a);if(z.step==="unreadable-body")return yt(400,-32700,"Parse error: the request body could not be read");if(z.step==="body-too-large")return yt(413,-32e3,Km(a));if(z.step==="no-json-body")return y!==void 0?y(z.forwardRequest,{...v!==void 0&&{authInfo:v}}):yt(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:I,body:T,parsedBody:_,forwardRequest:C}=z;try{switch(I.kind){case"reject":return c(new Error(`Rejected inbound request (${I.cell}): ${I.message}`)),Ti(I,Dt(T));case"modern":return await R(I,h,v);case"legacy":return await S(I,C,v,_)}}catch(M){return c(Po(M)),Co(Dt(T))}}return{fetch:async(h,$)=>{if(l)throw new Error("This MCP handler has been closed");try{return await P(h,$)}catch(v){return c(Po(v)),Co(Dt($?.parsedBody))}},notify:m,bus:u,close:async()=>{l=!0,f.closeAll();let h=[...i].map($=>$.close().catch(()=>{}));i.clear(),await Promise.all(h)}}}var Nl={member:0,admin:1,owner:2};function y_(e){return e!==void 0&&e in Nl?Nl[e]:-1}function S_(e,t){return y_(e)>=Nl[t]}function Je(e,t,r){let n=e.risk??"write";return r?.blocked?{action:"hide",reason:"org_blocked"}:e.minRole&&!S_(t.orgRole,e.minRole)?{action:"hide",reason:"role_required"}:e.minRole&&t.appScope==="selected"?{action:"hide",reason:"app_scoped_credential"}:n==="destructive"?{action:"hide",reason:"destructive_requires_approval"}:n==="write"&&t.access==="read"?{action:"hide",reason:"read_only_connection"}:{action:"allow"}}var Qm=[{risk:"read",minRole:"member",name:"provider_list",title:"List the API providers",description:"List the API providers this Gateway brokers: the built-in catalog and the ones registered on this Gateway, each with its id (what an app lists under `capabilities`), name, kind (api_key, ai, oauth_client), where the key goes, hosts, docs link, hint, and the Gateway settings it reads. For owners and admins, whether each setting is set. Never a value. Any member.",inputSchema:{type:"object",properties:{},additionalProperties:!1}},{risk:"write",minRole:"admin",needs:"providers",name:"provider_add",title:"Register an API provider",description:"Register an API provider on this Gateway from its spec: `{ id, name, docs, hosts, auth: { kind: bearer | header | query | basic, secret: SETTING_NAME, \u2026 }, hint?, secrets?, access?, writeMethods?, accountWidePaths?, data?, smoke?, cost?, rate? }`, as `everyapp provider add` takes it (the spec names its settings; it never carries a value). The id must not be a built-in provider's, its settings must start with its own id (`STRIPE_` for `stripe`) and be nobody else's, and its hosts must be the provider's own public https hosts. An id that is registered already is refused: this tool never replaces a row (`everyapp provider add --replace` from the terminal does). The answer says which setting to set next, from the terminal: `everyapp secret set NAME`. Owners and admins, on a self-hosted Gateway.",inputSchema:{type:"object",properties:{spec:{type:"object",description:"The provider spec object (never a URL). Its fields are checked by the same parser as `everyapp provider add`; a problem names the field."}},required:["spec"],additionalProperties:!1}},{risk:"write",minRole:"admin",needs:"providers",name:"provider_remove",title:"Remove a registered API provider",description:"Remove an API provider registered on this Gateway, by its id. Refused for a built-in provider, for a row whose key is set (remove it from the terminal: `everyapp provider remove <id>`, then `everyapp secret unset`), and for a row an app's deployed manifest lists under `capabilities` (naming the apps). The Gateway settings the row named stay until `everyapp secret unset`. Owners and admins, on a self-hosted Gateway.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The provider's id, as everyapp_provider_list lists it (a registered one, never a built-in).",minLength:2,maxLength:40}},required:["id"],additionalProperties:!1}}];var eh=[{risk:"read",minRole:"admin",name:"signin_list",title:"List the sign-in providers",description:"List the ways people can sign in to this Gateway beside their password (Manage workspace \u2192 Sign-in): every sign-in provider (google, microsoft, github, apple, cloudflare, oidc) with its status (on; off; incomplete, which means needs setup: some settings are set and the provider stays off until the rest are), the settings it reads with whether each is set (never a value), the redirect URL to register at the provider, and the command that sets it up from a terminal (`pnpm everyapp signin add <id>`); also whether password sign-in is on and whether Cloudflare Access sign-in is on. Nothing here changes a setting: they are Worker secrets, set from the terminal. Owners and admins.",inputSchema:{type:"object",properties:{},additionalProperties:!1}},{risk:"read",minRole:"admin",name:"signin_show",title:"Show one sign-in provider",description:"Show one sign-in provider as `everyapp signin show <id>` does: its status, each setting's name, what to paste there and whether it is set (never a value), the redirect URL to register, where the OAuth app is made and what it is called there, the scopes asked for, which claim becomes the email, the caveats, the setup guide in the everyapp skill, the command that sets it up from a terminal, and for one that needs setup what is wrong. Owners and admins.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The provider's id, as everyapp_signin_list lists it.",enum:[...bu]}},required:["id"],additionalProperties:!1}}];var v_=64,__=2048,b_=32,R_=255,w_=1e3,E_=64,T_=100,$_=32,z_=256,vt=(e,t,r=1)=>({type:"string",description:e,minLength:r,maxLength:t});function St(e,t=[]){return{type:"object",properties:e,...t.length?{required:t}:{},additionalProperties:!1}}var Kr=vt("The MCP app: its id, the prefix of its tools (`treg` for `treg_<tool>`, as everyapp_mcp_list lists it), or its row id.",v_),th={risk:"read",minRole:"admin"},Wr={risk:"write",minRole:"admin"},rh=[{...th,name:"mcp_list",title:"List MCP apps",description:"List the organization's MCP apps: the built-in ones (DataForSEO) that were added and every remote MCP server added by URL. Each with its id, name, kind (builtin or remote), status (on; off; or needs setup: on, but its credential isn't set or is pinned to another server), how many tools the Gateway serves, a remote server's URL and auth kind, and the credential's setting name with whether it is set and bound. Never a credential's value. Owners and admins.",inputSchema:St({})},{...th,name:"mcp_show",title:"Show an MCP app",description:"Show one MCP app: its URL and auth kind, the credential's setting name and whether it is set and bound (never its value), its status, when its tools were last listed and the error if that failed, and every tool: the name AI clients call, the server's own name, its risk and where that comes from (override, app, hint or default), whether it is on, and why it isn't listed. Owners and admins.",inputSchema:St({app:Kr},["app"])},{...Wr,name:"mcp_add",title:"Add an MCP server",description:"Add a remote MCP server by its URL as an MCP app: the Gateway serves its tools on /mcp as `<id>_<tool>` to whoever has access (you, the owners and the admins to start). For a server with no credential the Gateway lists its tools at once and the answer says how many. For one with a credential the answer names the Gateway setting that holds it and the command the operator runs in a terminal to set it; the credential itself is never passed here and never returned. Refused for a URL on this Gateway's own domains or a private address, an id in use, or a credential name another server uses. Owners and admins.",inputSchema:St({url:vt("The server's MCP endpoint, https (`https://treg.to/mcp`).",__),id:vt("The app id and tool prefix: lowercase letters, digits and hyphens, a letter first. Default: from the URL's host (`treg.to` \u2192 `treg`).",b_),name:vt("The name people read. Default: the id.",R_),description:vt("What the server is for. Default: a sentence naming it and its host.",w_),auth:{description:"How the Gateway authenticates to the server; for a credential, the name of the setting that holds it.",...St({kind:{type:"string",description:"How the Gateway authenticates to the server: none; bearer (`Authorization: Bearer <credential>`); header (a header of your naming); basic (the credential is `user:password`); oauth (recorded, not served yet).",enum:[...Ru]},secret:vt("The NAME of the Gateway setting that holds the credential, ending in _MCP_TOKEN. Default: `<ID>_MCP_TOKEN`. Never the credential itself.",E_),header:vt("For kind header: the header's name (`X-Api-Key`).",T_),prefix:vt("For kind header: text sent before the credential (`Token `). Optional.",$_,0)},["kind"])},risk:{type:"string",description:"How each tool's risk is decided: annotations (the server's hints; a tool without one counts as write; the default), or read or write for every tool.",enum:[...wu]}},["url","auth"])},{...Wr,name:"mcp_remove",title:"Remove an MCP app",description:"Remove an MCP app, built-in or remote: it stops being served, and everyone's access, its tokens, its tools snapshot and its place in AI connections go. The credential stays set on the Gateway. To stop serving it and keep all that, use everyapp_mcp_off. Cannot be undone: needs confirm: true. Owners and admins.",inputSchema:St({app:Kr,confirm:{type:"boolean",description:"Must be true. The action cannot be undone; ask the person before calling.",const:!0}},["app","confirm"]),irreversible:!0},{...Wr,name:"mcp_on",title:"Turn an MCP app on",description:"Serve an MCP app's tools again, to the same people as before. A built-in that was never added is added by the operator (`pnpm everyapp mcp on <id>`). Owners and admins.",inputSchema:St({app:Kr},["app"])},{...Wr,name:"mcp_off",title:"Turn an MCP app off",description:"Stop serving an MCP app's tools. Who has access, their tokens and the tools snapshot are kept, so everyapp_mcp_on brings it back at once. Owners and admins.",inputSchema:St({app:Kr},["app"])},{...Wr,name:"mcp_refresh",title:"List an MCP app's tools again",description:"List an MCP app's tools again now: the Gateway drops its last listing, asks the server, and answers how many tools it serves and which names are new or gone. Owners and admins.",inputSchema:St({app:Kr},["app"])},{...Wr,name:"mcp_tool",title:"Change one tool of an MCP server",description:"Change one tool of a remote MCP app: its risk (read, write or destructive; annotations goes back to the server's hint and the app's default) and whether it is on. A destructive tool is never served to AI clients until approvals exist; a write tool is hidden from read-only connections. Give `risk`, `enabled`, or both. Owners and admins.",inputSchema:St({app:Kr,tool:vt("The tool: the name AI clients call (`treg_get_user`) or the server's own (`getUser`), as everyapp_mcp_show lists them.",z_),risk:{type:"string",description:"The tool's risk, or annotations to clear your override.",enum:[...hu,"annotations"]},enabled:{type:"boolean",description:"false leaves the tool out of the catalog; true serves it again."}},["app","tool"])}];var nh=200,oh=50,P_=864e13,sh=100,ah=20,C_=50,k_=80,I_=80,Ll=254,A_=500,O_=64,ih=60,ch=500,M_=255,N_=1e3,lh=1e9,dr={type:"object",properties:{},additionalProperties:!1},lt=e=>({type:"string",description:e,minLength:1,maxLength:Ll}),Yr=lt("The member: their email address, or their user id (from everyapp_workspace_users)."),ko=lt("The app: its manifest id (as everyapp_list_apps lists it, e.g. `crm`), or its row id (from everyapp_workspace_apps)."),Xr=lt("The group: its name, or its id (`grp_\u2026`, from everyapp_workspace_groups)."),ql=lt("The event subscription: its id (`sub_\u2026`, from everyapp_workspace_events), or its name. A name several subscriptions share is refused; use the id."),q_=$u.map(e=>e.type).filter(e=>e!=="ping").join(", "),uh=e=>({type:"array",description:e,items:{type:"string",minLength:1,maxLength:k_},maxItems:C_}),jl={type:"boolean",description:"Must be true. The action cannot be undone; ask the person before calling.",const:!0},Zr=e=>({type:"array",description:e,items:{type:"string",minLength:1,maxLength:Ll},maxItems:A_});function ve(e,t=[]){return{type:"object",properties:e,...t.length?{required:t}:{},additionalProperties:!1}}function dh(e,t){let[r]=Object.keys(e);return ve({...e,users:Zr(`The full list of ${t}, by email or user id. Replaces the current list; give this or add/remove, not both.`),add:Zr("Members to add (email or user id), keeping the rest."),remove:Zr("Members to take out (email or user id), keeping the rest.")},r?[r]:[])}var et={risk:"read",minRole:"admin"},Te={risk:"write",minRole:"admin"},ph=[{...et,name:"workspace_show",title:"Show the workspace",description:"Show this organization: its id, name and slug, your role, whether the Gateway can send email, and how many members, pending invitations, groups and apps it has. Owners and admins.",inputSchema:dr},{...et,name:"workspace_users",title:"List members",description:"List the organization's members (id, name, email, role, whether deactivated, when the account was created and when they joined) and its pending invitations (id, email, role, when they expire; an expired one stays listed until canceled). Owners and admins.",inputSchema:dr},{...Te,name:"workspace_invite",title:"Invite someone",description:"Invite an email address to the organization as a member or an admin. Creates the invitation and mails it when the Gateway can send email; the answer says whether it was mailed and never carries the invitation link (an admin copies it from Admin \u2192 Users). Refused for an address that is a member or already invited, and once the organization holds 100 pending invitations. Owners and admins.",inputSchema:ve({email:{type:"string",description:"The email address to invite.",minLength:3,maxLength:Ll},role:{type:"string",description:"The role they join with. Default member.",enum:["member","admin"],default:"member"}},["email"])},{...Te,name:"workspace_uninvite",title:"Cancel an invitation",description:"Cancel a pending invitation (an expired one too), by its id or the invited email address. Owners and admins.",inputSchema:ve({invitation:lt("The invitation: its id (from everyapp_workspace_users), or the invited email address.")},["invitation"])},{...Te,name:"workspace_role",title:"Change a member's role",description:"Make a member an admin, an admin a member, or make or demote an owner. Only an owner changes an admin or an owner, or makes one; nobody changes their own role; the last owner is never demoted. Owners and admins.",inputSchema:ve({user:Yr,role:{type:"string",description:"The role to give.",enum:["member","admin","owner"]}},["user","role"])},{...Te,name:"workspace_deactivate",title:"Deactivate a member",description:"Lock a member out everywhere: no sign-in, every session ended, their personal access tokens and AI connections revoked. They stay listed and can be reactivated. Only an owner deactivates an admin; never yourself or an owner. Owners and admins.",inputSchema:ve({user:Yr},["user"])},{...Te,name:"workspace_reactivate",title:"Reactivate a member",description:"Let a deactivated member sign in again. Tokens and connections revoked at deactivation stay revoked. Owners and admins.",inputSchema:ve({user:Yr},["user"])},{...Te,name:"workspace_remove",title:"Remove a member",description:"Remove a member from the organization: their membership, app access, group places, tokens and AI connections go, and their account when it belongs to no other organization. Where Cloudflare Access would let them straight back in they are deactivated instead, and the answer says so. Cannot be undone: needs confirm: true. Owners and admins; an owner is removed only by another owner, never the last one.",inputSchema:ve({user:Yr,confirm:jl},["user","confirm"]),irreversible:!0},{...Te,name:"workspace_reset_email",title:"Send a password-reset email",description:"Mail a member a password-reset link. The link goes to their inbox, never to you. Refused where the Gateway sends no email (an admin copies a reset link from Admin \u2192 Users instead) or password sign-in is off; only for active members of this organization alone, never yourself or an owner. Owners and admins.",inputSchema:ve({user:Yr},["user"])},{...et,name:"workspace_groups",title:"List groups",description:"List the organization's groups with their id (`grp_\u2026`), name, description, and how many members and apps each has. Owners and admins.",inputSchema:dr},{...Te,name:"workspace_group_create",title:"Create a group",description:"Create a group. Names are unique in the organization, letter case aside. Owners and admins.",inputSchema:ve({name:{type:"string",description:"The group's name, 1 to 60 characters.",minLength:1,maxLength:ih},description:{type:"string",description:"What the group is for. Optional.",maxLength:ch}},["name"])},{...Te,name:"workspace_group_set",title:"Rename or describe a group",description:"Change a group's name or description. A field left out keeps its value. Owners and admins.",inputSchema:ve({group:Xr,name:{type:"string",description:"The new name, 1 to 60 characters.",minLength:1,maxLength:ih},description:{type:"string",description:"The new description; an empty string clears it.",maxLength:ch}},["group"])},{...Te,name:"workspace_group_delete",title:"Delete a group",description:"Delete a group. The app access it granted its members ends with it. Owners and admins.",inputSchema:ve({group:Xr},["group"])},{...et,name:"workspace_group_members",title:"List a group's members",description:"List every member of the organization with whether they are in the group. Owners and admins.",inputSchema:ve({group:Xr},["group"])},{...Te,name:"workspace_group_members_set",title:"Set a group's members",description:"Set who is in a group: give `users` (the full list) or `add` and/or `remove` (changes to the current list). Only members of the organization. Owners and admins.",inputSchema:dh({group:Xr},"the group's members")},{...et,name:"workspace_group_apps",title:"List a group's apps",description:"List the organization's own apps with whether the group opens each. Owners and admins.",inputSchema:ve({group:Xr},["group"])},{...Te,name:"workspace_group_apps_set",title:"Set a group's apps",description:"Set which apps a group opens: give `apps` (the full list) or `add` and/or `remove` (changes to the current list), each app by manifest id or row id. Only the organization's own apps; a shared app is everyone's already. Owners and admins.",inputSchema:ve({group:Xr,apps:Zr("The full list of apps the group opens, by manifest id or row id. Replaces the current list; give this or add/remove, not both."),add:Zr("Apps to grant (manifest id or row id), keeping the rest."),remove:Zr("Apps to revoke (manifest id or row id), keeping the rest.")},["group"])},{...et,name:"workspace_apps",title:"List apps",description:"List every app of the organization (and the shared apps on a hosted Gateway): row id, manifest id, name, description, status, whether everyone can open it, how many members have direct access, and what it still needs before it opens (setup). Owners and admins.",inputSchema:dr},{...Te,name:"workspace_app_set",title:"Edit an app",description:"Change an app's name, description, or whether it is available to everyone (every current and future member gets access; turning it off keeps existing access). A field left out keeps its value. Owners and admins.",inputSchema:ve({app:ko,name:{type:"string",description:"The new name.",minLength:1,maxLength:M_},description:{type:"string",description:"The new description.",minLength:1,maxLength:N_},everyone:{type:"boolean",description:"Whether the app is available to every member."}},["app"])},{...et,name:"workspace_app_access",title:"Who can open an app",description:"List every member of the organization with whether they hold direct access to the app, and the groups that grant it to them. Owners and admins.",inputSchema:ve({app:ko},["app"])},{...Te,name:"workspace_app_access_set",title:"Set who can open an app",description:"Set which members hold direct access to an app: give `users` (the full list) or `add` and/or `remove` (changes to the current list). Access a group grants is not touched here; your own access is never revoked. Owners and admins.",inputSchema:dh({app:ko},"members with direct access")},{...Te,name:"workspace_app_cap",title:"Cap an app's monthly calls",description:"Set the organization's monthly cap on an app's provider calls (Admin \u2192 Usage), say the app has no cap whatever the workspace default (`cap: null, unlimited: true`), or neither (`cap: null` alone): the app inherits the workspace default, and without one it is uncapped. Answers the app's own cap, `capUnlimited`, and the cap that binds it now with its source (`app`, `default`, or null). Owners and admins.",inputSchema:ve({app:ko,cap:{type:["integer","null"],description:"Calls per month, 1 to 1,000,000,000; null for no cap of its own (the workspace default applies unless `unlimited`).",minimum:1,maximum:lh},unlimited:{type:"boolean",description:"No cap at all, even with a workspace default. Only with cap null: a cap and unlimited together are refused."}},["app","cap"])},{...Te,name:"workspace_cap_default",title:"The workspace default cap",description:"Set or clear the organization's default monthly cap on provider calls (Admin \u2192 Usage \u2192 Default monthly cap): what binds every app without a cap or `unlimited` of its own. A whole number of calls, or null for no default. Owners and admins.",inputSchema:ve({cap:{type:["integer","null"],description:"Calls per month for every app without its own cap, 1 to 1,000,000,000; null for no default.",minimum:1,maximum:lh}},["cap"])},{...Te,name:"workspace_app_delete",title:"Delete an app",description:"Delete an app from the catalog: it stops being served and leaves every list. Its Worker stays until `everyapp delete`. Cannot be undone: needs confirm: true. Owners and admins.",inputSchema:ve({app:ko,confirm:jl},["app","confirm"]),irreversible:!0},{...et,name:"workspace_usage",title:"Usage for a month",description:"What the organization's apps spent in a UTC month: per app, per member and per provider or capability, with the workspace default cap (`defaultMonthlyCallCap`) and for each app its own cap, `capUnlimited`, the cap that binds it (`effectiveMonthlyCallCap`, `capSource`: app or default) and whether it is `paused` this month. Owners and admins.",inputSchema:ve({month:{type:"string",description:"The month as YYYY-MM (UTC). Default: the current month.",minLength:7,maxLength:7}})},{...et,name:"workspace_activity",title:"Agent activity",description:"One page of the organization's MCP tool calls (the audit trail), newest first: who, through which credential and client, which tool, the decision and outcome. Never the arguments or results. Filter by app, member, decision, risk or time; page with `before` from the previous answer's `nextBefore`. Owners and admins.",inputSchema:ve({app:lt("Only calls to this app: its manifest id (a removed app's too, or `everyapp` for the Gateway's own tools) or its row id."),user:Yr,decision:{type:"string",description:"Only calls that were allowed, or only blocked ones.",enum:["allowed","blocked"]},risk:{type:"string",description:"Only calls to tools of this risk.",enum:["read","write","destructive"]},since:{type:"string",description:"Only calls at or after this time, as an ISO 8601 date-time.",minLength:4,maxLength:40},limit:{type:"integer",description:`Rows per page, 1 to ${nh}. Default ${oh}.`,minimum:1,maximum:nh,default:oh},before:{type:"object",description:"The previous page's `nextBefore`: the page continues before this row.",properties:{createdAt:{type:"integer",description:"The row's time in milliseconds since the epoch.",minimum:0,maximum:P_},id:{type:"string",description:"The row's id.",minLength:1,maxLength:128}},required:["createdAt","id"],additionalProperties:!1}})},{...Te,name:"workspace_rename",title:"Rename the workspace",description:"Rename the organization. The slug (its address) stays as it is. Owners and admins.",inputSchema:ve({name:{type:"string",description:"The new name, 1 to 64 characters.",minLength:1,maxLength:O_}},["name"])},{...et,name:"workspace_events",title:"List event subscriptions",description:"List the organization's event subscriptions: id (`sub_\u2026`), name, where it delivers (a webhook URL's host and path, never its query; or email to the owners, or to the owners and admins), the event types and patterns it takes, whether it is on, whether it is built in (Cap alerts), and its last delivery (when, and delivered, failed or dead) with the failures in a row. Never a signing secret. Owners and admins.",inputSchema:dr},{...Te,name:"workspace_events_add",title:"Add an event subscription",description:`Subscribe a webhook URL (Slack's workflow webhook, Zapier, n8n, your own endpoint), or the organization's owners or owners and admins by email, to the Gateway's events. Give \`url\` or \`email\`, not both. A webhook URL is https on a public hostname, never the Gateway's own host or an app's. \`events\` takes types or patterns; none means every event. The types: ${q_}; patterns: a group (\`member.*\`, \`cap.*\`), an app's own events (\`app.crm.*\`, or \`app.crm.invoice.paid\`), or \`*\`. Every webhook delivery is signed with the subscription's secret (HMAC-SHA256 over the timestamp and the body, in the X-EveryApp-Signature header). Give \`secret\` when the receiver already has one; leave it out and the Gateway generates one and returns it once, in this answer, and never again. That secret only signs deliveries to this URL and opens nothing on the Gateway; the person must store it in their receiver now. At most ${zu} subscriptions per organization. Owners and admins.`,inputSchema:ve({url:{type:"string",description:"The webhook URL every matching event is POSTed to, signed. Give this or email, not both.",minLength:1,maxLength:Pu},email:{type:"string",description:"Mail each event to the organization's owners (`owners`) or its owners and admins (`admins`) instead of a webhook. Give this or url, not both.",enum:[...Cu]},events:uh("Event types (`member.joined`) or patterns (`member.*`, `app.crm.*`, `*`) to deliver. Leave it out for every event."),name:{type:"string",description:`What to call it, like "Slack #ops", up to ${kn} characters. Default: the URL's host, or "Email owners and admins".`,minLength:1,maxLength:kn},secret:{type:"string",description:`A webhook's signing secret the receiver already has, ${Mi} to ${Ni} characters with no spaces. Leave it out to have one generated and returned once.`,minLength:Mi,maxLength:Ni}})},{...Te,name:"workspace_events_set",title:"Change an event subscription",description:"Change an event subscription: turn it off or on (`enabled`; a paused one is sent no events, though everyapp_workspace_events_test still reaches it), replace the event types and patterns it takes (`events`; an empty list means every event), or rename it. A field left out keeps its value. Owners and admins.",inputSchema:ve({subscription:ql,enabled:{type:"boolean",description:"false pauses it; true turns it back on."},events:uh("The event types and patterns it takes from now on, replacing the current list."),name:{type:"string",description:`The new name, 1 to ${kn} characters.`,minLength:1,maxLength:kn}},["subscription"])},{...Te,name:"workspace_events_remove",title:"Remove an event subscription",description:"Remove an event subscription: events stop going to it at once, and its signing secret goes with it. A built-in one (Cap alerts) is turned off instead, so the Gateway never recreates it behind the person's back, and the answer says so. Cannot be undone: needs confirm: true. Owners and admins.",inputSchema:ve({subscription:ql,confirm:jl},["subscription","confirm"]),irreversible:!0},{...Te,name:"workspace_events_test",title:"Send a test event",description:"Send a test event (type `ping`) to one subscription, a paused one too, and wait for the first attempt. The answer says where the delivery stands: delivered, with the receiver's HTTP status (for an email subscription, how many owners and admins were mailed); or failed, with the status or the error and when the Gateway retries; or dead. Nothing goes to any other subscription. Owners and admins.",inputSchema:ve({subscription:ql},["subscription"])},{...et,name:"workspace_event_deliveries",title:"List event deliveries",description:"One page of the organization's event deliveries from the last 30 days, newest first: the event (id, type, its one-line summary, when), the subscription, the attempts, where it stands (pending, delivered, failed and retrying, or dead), the last HTTP status or error, and the next attempt. Never the request body. Only one subscription's with `subscription`, only dead ones with `dead: true`; page with `before` from the previous answer's `nextBefore`. Owners and admins.",inputSchema:ve({subscription:lt("Only this subscription's deliveries: its id (`sub_\u2026`) or its name."),dead:{type:"boolean",description:"true for dead deliveries only: out of attempts, or refused for good (everyapp_workspace_event_redeliver sends one again)."},limit:{type:"integer",description:`Deliveries per page, 1 to ${sh}. Default ${ah}.`,minimum:1,maximum:sh,default:ah},before:{type:"string",description:"The previous page's `nextBefore`: the page continues with the deliveries older than that one.",minLength:1,maxLength:I_}})},{...Te,name:"workspace_event_redeliver",title:"Redeliver an event",description:"Send one failed or dead delivery again now, its retry schedule starting over, and answer where it stands after that attempt. A delivered one is left alone and the answer says so. Owners and admins.",inputSchema:ve({delivery:lt("The delivery's id (`dlv_\u2026`, from everyapp_workspace_event_deliveries).")},["delivery"])},{risk:"read",minRole:"member",name:"my_tokens",title:"My personal access tokens",description:"List your own personal access tokens in this organization: id, name, prefix, scopes, the app it is bound to, when it was made, expires, was last used, and whether it is revoked. Never the token value. Any member.",inputSchema:dr},{risk:"write",minRole:"member",name:"revoke_token",title:"Revoke one of my tokens",description:"Revoke one of your own personal access tokens, by its id or its name. Any member.",inputSchema:ve({token:lt("The token: its id or its name (from everyapp_my_tokens). A name several tokens share is refused; use the id.")},["token"])},{risk:"read",minRole:"member",name:"my_connections",title:"My AI connections",description:"List the AI apps you connected to this Gateway over OAuth, in every organization: id, organization, client, which apps, read only or read & write, when made and last used. Any member.",inputSchema:dr},{risk:"write",minRole:"member",name:"revoke_connection",title:"Revoke one of my AI connections",description:"Revoke one of your own AI connections by its id (from everyapp_my_connections). Revoking the connection this call came through ends it on the next request. Any member.",inputSchema:ve({connection:lt("The connection's id.")},["connection"])},...rh];var ut="everyapp";function Sh(e,t){return t.workspace===!0&&(e.needs!=="providers"||t.providers===!0)}var mh=256*1024,xl=200,Hl=64,vh=10,Ul=25,j_=128,L_="anthropic/alwaysLoad",hh={type:"object",properties:{},additionalProperties:!1},fh={type:"object",properties:{name:{type:"string",description:"The tool's name as everyapp_search_tools lists it: `<app>_<tool>`.",minLength:1,maxLength:j_},arguments:{type:"object",description:"The tool's arguments, as its input schema describes them."}},required:["name"],additionalProperties:!1},_h={type:"object",properties:{query:{type:"string",description:"Words to look for in tool names, titles and descriptions. Give a query, an app id, or both.",minLength:1,maxLength:xl},app:{type:"string",description:"An app id (from everyapp_list_apps): only its tools.",minLength:1,maxLength:Hl},limit:{type:"integer",description:"How many tools to return at most.",minimum:1,maximum:Ul,default:vh}},additionalProperties:!1};function D_(e,t){let r=[];for(let n of Bl)n.kind==="host"&&Sh(n,t)&&Je(n,e.principal).action==="allow"&&r.push({appId:ut,tool:n});for(let n of e.apps)for(let o of n.tools)Je(o,e.principal).action==="allow"&&r.push({appId:n.appId,tool:o});return r}function x_(e,t){return t.tools.filter(r=>Je(r,e.principal).action==="allow").length}var gh=(e,t)=>e.appId<t.appId?-1:e.appId>t.appId?1:e.tool.name<t.tool.name?-1:e.tool.name>t.tool.name?1:0;function H_(e,t,r,n){let o=r===e||r===t.name?10:0,a=t.title?.toLowerCase(),i=t.description.toLowerCase();for(let l of n)e.includes(l)&&(o+=5),a?.includes(l)&&(o+=3),i.includes(l)&&(o+=1);return o}var U_=new Set(Object.keys(_h.properties)),yh=(e,t)=>typeof e=="string"&&e.length>=1&&e.length<=t;function V_(e){let t=Object.keys(e).find(a=>!U_.has(a));if(t!==void 0)return{problem:`\`${t}\` is not one of query, app, limit.`};let r=e.query,n=e.app,o=e.limit===void 0?vh:e.limit;return r!==void 0&&!yh(r,xl)?{problem:`query must be a string of 1 to ${xl} characters.`}:n!==void 0&&!yh(n,Hl)?{problem:`app must be a string of 1 to ${Hl} characters.`}:typeof o!="number"||!Number.isInteger(o)||o<1||o>Ul?{problem:`limit must be an integer from 1 to ${Ul}.`}:{...r!==void 0?{query:r.trim().toLowerCase()}:{},...n!==void 0?{app:n}:{},limit:o}}function B_(e,t,r){let n=V_(t);if("problem"in n)return n;let{query:o,app:a,limit:i}=n;if(o===void 0&&a===void 0)return{problem:"give a query, an app id, or both."};let c=D_(e,r).filter(y=>a===void 0||y.appId===a).map(y=>({...y,name:nt(y.appId,y.tool.name)})).sort(gh);if(o!==void 0){let y=[...new Set(o.split(/[^\p{L}\p{N}]+/u).filter(Boolean))];c=c.map(R=>({entry:R,score:H_(R.name,R.tool,o,y)})).filter(R=>R.score>0).sort((R,S)=>S.score-R.score||gh(R.entry,S.entry)).map(R=>R.entry)}let u=c.slice(0,i).map(({name:y,appId:R,tool:S})=>({name:y,app:R,...S.title?{title:S.title}:{},description:S.description,risk:S.risk,inputSchema:S.inputSchema})),m=y=>({tools:u.slice(0,y),total:c.length,...y<u.length?{truncated:!0}:{}}),f=u.length;if(Io(Vl(m(f)))>mh){let y=0,R=u.length-1;for(;y<R;){let S=Math.ceil((y+R)/2);Io(Vl(m(S)))>mh?R=S-1:y=S}f=y}return{data:m(f)}}var Dl={risk:"read",listedIn:["full","compact"],kind:"answer"},Bl=[{...Dl,name:"list_apps",title:"List apps",description:"List the Every App apps this connection can use: what each is for, its URL, and how many tools it offers. Tool names are `<app>_<tool>`. An app that isn't available yet (it needs setup, or an admin hasn't turned it on) says so, with what an admin runs.",inputSchema:hh,run:e=>({data:{apps:[...e.apps.map(t=>({id:t.appId,name:t.name,...t.description?{description:t.description}:{},url:t.baseUrl,tools:x_(e,t)})),...(e.unavailable??[]).map(t=>({id:t.appId,name:t.name,available:!1,reason:t.reason})),...(e.offered??[]).map(t=>({id:t.appId,name:t.name,available:!1,offered:!0,reason:`off and its key is set: an admin runs ${t.command}`}))]}})},{...Dl,name:"whoami",title:"Who am I",description:"Show who this connection acts as: the user, their organization and role, the access it was granted, and the apps it can use.",inputSchema:hh,run:({principal:e,apps:t})=>({data:{user:{email:e.email,role:e.orgRole},organization:{id:e.organizationId,...e.organizationName?{name:e.organizationName}:{}},connection:{kind:e.credential.kind,access:e.access==="write"?"read & write":"read only",...e.credential.clientName?{client:e.credential.clientName}:{}},apps:t.map(r=>r.appId)}})},{...Dl,name:"search_tools",title:"Search tools",description:"Find tools this connection can call, by words, by app id, or both: each result has the tool's name (`<app>_<tool>`), what it does, whether it reads or changes data, and its input schema. Best matches first, 10 by default and 25 at most. Call a tool by that name when it is listed, else through everyapp_call_read, or everyapp_call_write for one that changes data.",inputSchema:_h,run:B_},{name:"call_read",title:"Call a read tool",description:"Run one tool that only reads data, by its name (`<app>_<tool>`, from everyapp_search_tools) with its arguments. A tool that changes data is refused here; call it through everyapp_call_write.",risk:"read",inputSchema:fh,listedIn:["compact"],kind:"wrapper",ceiling:"read"},{name:"call_write",title:"Call a write tool",description:"Run one tool by its name (`<app>_<tool>`, from everyapp_search_tools) with its arguments, including a tool that changes data.",risk:"write",inputSchema:fh,listedIn:["compact"],kind:"wrapper",ceiling:"write"},...[...ph,...Qm,...eh].map(e=>({name:e.name,title:e.title,description:e.description,risk:e.risk,inputSchema:e.inputSchema,listedIn:["full"],kind:"host",minRole:e.minRole,...e.irreversible?{irreversible:!0}:{},...e.needs?{needs:e.needs}:{}}))],Fl=nt(ut,"call_write");function F_(e){return{name:nt(ut,e.name),title:e.title,description:e.description,inputSchema:e.inputSchema,annotations:e.risk==="read"?{readOnlyHint:!0,idempotentHint:!0,openWorldHint:!1}:{readOnlyHint:!1,destructiveHint:e.kind==="host"&&e.irreversible===!0,idempotentHint:!1,openWorldHint:!1},...e.kind==="host"?{}:{_meta:{[L_]:!0}}}}function bh(e,t={}){let r=e?.listing??"full";return Bl.filter(n=>!e||n.listedIn.includes(r)&&(n.kind!=="host"||Sh(n,t))&&Je(n,e.principal).action==="allow").map(F_)}function Gl(e){return Bl.find(t=>t.name===e)??null}function Vl(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}function Io(e){return new TextEncoder().encode(JSON.stringify(e)).length}function Rh(e,t,r,n={}){let o=e.run(t,r,n);return"problem"in o?o:{result:Vl(o.data)}}var G_=3e4,wh=1024*1024,Eh=64;function Jl(e){return e==="write"?[Cn,Yo]:[Cn]}function J_(e){switch(e.credential.kind){case"pat":return`pat:${e.credential.id}`;case"oauth":return`oauth:${e.credential.id}`;case"access":return`access:${e.credential.id}`;default:return e.userId}}function xe(e){return{content:[{type:"text",text:e}],isError:!0}}function Kl(e){let{view:t,deps:r,call:n}=e,{principal:o}=t;return(a,i)=>r.audit?.({surface:t.surface,tool:jn(a),callId:e.callId,userId:o.userId,organizationId:o.organizationId,credentialKind:o.credential.kind,credentialId:o.credential.id,...o.credential.clientName?{clientName:o.credential.clientName}:{},...n.protocolVersion?{protocolVersion:n.protocolVersion}:{},...n.clientInfo?{clientInfo:n.clientInfo}:{},...t.requestId?{requestId:t.requestId}:{},...e.via?{via:e.via.name}:{},...i,durationMs:Date.now()-e.startedAt})}async function $h(e,t,r){let n={view:e,deps:r,call:t,callId:crypto.randomUUID(),startedAt:Date.now()},o=e.surface==="gateway"&&t.name.length<=128?is(t.name):null,a=o?.appId===ut?Gl(o.localName):null;return a?K_(n,a):Ph(n,t.name,t.arguments)}async function Wl(e,t,r,n,o={}){let a=t??{};if(!Se(a))return{ok:!1,problem:"arguments must be a JSON object."};let i=Vd(a,Eh);if(i.tooDeep)return{ok:!1,problem:`arguments are nested more than ${Eh} levels deep.`,reason:"too_deep"};let l,c;try{l=e.digestArguments?await e.digestArguments(a):void 0,c=o.ownSchema||i.values<=xd?W_(r,n,a):null}catch{return{ok:!1,problem:"they could not be checked.",reason:"check_failed",...l?{argsDigest:l}:{}}}return c?{ok:!1,problem:c,...l?{argsDigest:l}:{}}:{ok:!0,args:a,...l?{argsDigest:l}:{}}}function Yl(e){return{outcome:"invalid_arguments",...e.reason?{reason:e.reason}:{},...e.argsDigest?{argsDigest:e.argsDigest}:{}}}async function K_(e,t){let{view:r,deps:n,call:o}=e;if(t.kind==="host")return zh(e,t,o.arguments);let a=Kl(e),i=nt(ut,t.name),l={appId:ut,risk:t.risk},c=Je(t,r.principal);if(c.action!=="allow")return a(i,{...l,decision:"blocked",reason:c.reason,outcome:"not_run"}),{kind:"unknown_tool"};let u=(S,P)=>(a(i,{...l,decision:"allowed",outcome:"invalid_arguments",...P}),{kind:"result",result:xe(`Invalid arguments for ${i}: ${S}`),tool:t}),m=await Wl(n,o.arguments,`builtin\0${t.name}`,t.inputSchema,{ownSchema:!0});if(!m.ok)return u(m.problem,Yl(m));let f=m.argsDigest?{argsDigest:m.argsDigest}:{};if(t.kind==="answer"){let S=Rh(t,r,m.args,{workspace:n.workspace!==void 0,providers:n.workspace?.providers===!0});return"problem"in S?u(S.problem,f):(a(i,{...l,decision:"allowed",outcome:"ok",...f,resultBytes:Io(S.result)}),{kind:"result",result:S.result,tool:t})}let y=m.args.name,R=m.args.arguments;return typeof y!="string"?u("name must be the tool's name, `<app>_<tool>`.",f):R!==void 0&&!Se(R)?u("arguments must be a JSON object.",f):Ph({...e,via:{name:i,tool:t,ceiling:t.ceiling}},y,R??{})}async function zh(e,t,r){let{view:n,deps:o}=e,a=Kl(e),i=nt(ut,t.name),l={appId:ut,risk:t.risk},c=e.via?.tool??t,u=P=>(a(i,{...l,decision:"blocked",reason:P,outcome:"not_run"}),e.via?{kind:"result",result:xe(`Unknown tool: ${i}`),tool:e.via.tool}:{kind:"unknown_tool"}),m=o.workspace;if(!m||t.needs==="providers"&&m.providers!==!0)return u("unknown_tool");let f=Je(t,n.principal);if(f.action!=="allow")return u(f.reason);if(e.via?.ceiling==="read"&&t.risk!=="read")return a(i,{...l,decision:"blocked",reason:"write_via_read_wrapper",outcome:"not_run"}),{kind:"result",result:xe(`\`${i}\` changes data; call it through ${Fl}.`),tool:e.via.tool};let y=await Wl(o,r,`builtin\0${t.name}`,t.inputSchema,{ownSchema:!0});if(!y.ok)return a(i,{...l,decision:"allowed",...Yl(y)}),{kind:"result",result:xe(`Invalid arguments for ${i}: ${y.problem}`),tool:c};let R={...l,decision:"allowed",...y.argsDigest?{argsDigest:y.argsDigest}:{}},S;try{S=await m.run(t.name,y.args,n.principal)}catch{return a(i,{...R,outcome:"app_error",reason:"host_error"}),{kind:"result",result:xe(`${i} failed.`),tool:c}}return a(i,{...R,outcome:S.isError?"tool_error":"ok",resultBytes:Io(S)}),{kind:"result",result:S,tool:c}}async function Ph(e,t,r){let{view:n,deps:o}=e,{principal:a}=n,i=Kl(e),l=I=>(i(t,{decision:"blocked",outcome:"not_run",...I}),e.via?{kind:"result",result:xe(`Unknown tool: ${jn(t)}`),tool:e.via.tool}:{kind:"unknown_tool"});if(t.length>128)return l({reason:"unknown_tool"});if(e.via){let I=is(t);if(I?.appId===ut){let T=Gl(I.localName);return T?.kind==="host"?zh(e,T,r):l({reason:"unknown_tool"})}}let c=Ad(n,t);if(!c)return l({reason:"unknown_tool"});let{app:u,tool:m}=c,f={appId:u.appId,appRowId:u.rowId,risk:m.risk},y=Je(m,a);if(y.action!=="allow")return l({...f,reason:y.reason});if(e.via?.ceiling==="read"&&m.risk!=="read")return i(t,{...f,decision:"blocked",reason:"write_via_read_wrapper",outcome:"not_run"}),{kind:"result",result:xe(`\`${t}\` changes data; call it through ${Fl}.`),tool:e.via.tool};let R=e.via?.tool??m,S=await Wl(o,r,`${u.rowId}\0${u.catalogHash}\0${m.name}`,m.inputSchema);if(!S.ok)return i(t,{...f,decision:"allowed",...Yl(S)}),{kind:"result",result:xe(`Invalid arguments for ${t}: ${S.problem}`),tool:R};let{args:P}=S,b={...f,decision:"allowed",...S.argsDigest?{argsDigest:S.argsDigest}:{}},h=e.via?.ceiling==="read"?"read":a.access,$=await Er(o.signing.privateKeyPem,{subject:{sub:a.userId,email:a.email,orgId:a.organizationId,orgRole:a.orgRole},audience:u.audience,issuer:o.signing.issuer,keyId:o.signing.keyId,channel:"mcp",actor:{sub:J_(a)},scopes:Jl(h),toolCall:{id:e.callId,name:m.name}}),v=o.callTimeoutMs??G_,z;try{z=await ss(v,async I=>{let T=await o.invokeApp(u,new Request(new URL(mu,u.baseUrl),{method:"POST",headers:{"content-type":"application/json",[Tt]:$},body:JSON.stringify({v:1,name:m.name,arguments:P,callId:e.callId}),signal:I}));return Y_(u,m,T,I)})}catch(I){let T=I instanceof qn;return i(t,{...b,outcome:T?"timeout":"unreachable"}),{kind:"result",result:xe(T?`${u.name} did not answer within ${Math.round(v/1e3)} seconds.`:`${u.name} could not be reached.`),tool:R}}return z.drifted&&o.onCatalogDrift?.(u),i(t,{...b,outcome:z.outcome,resultBytes:z.bytes,...z.reason?{reason:z.reason}:{}}),{kind:"result",result:z.result,tool:R}}function W_(e,t,r){let o=Hd(e,t)?.(r);return!o||o.valid?null:o.errorMessage??"invalid arguments."}async function Y_(e,t,r,n){let o;try{o=await as(r,wh,n)}catch{return{result:xe(`${e.name} failed to run ${t.name}.`),outcome:"app_error",bytes:0,drifted:!1,reason:"unreadable_answer"}}if(!o.ok)return{result:xe(`The result from ${e.name} is larger than ${wh/1024/1024} MB.`),outcome:"app_error",bytes:o.bytes,drifted:!1,reason:"result_too_large"};let a;try{a=JSON.parse(o.text)}catch{a=void 0}let i=u=>({result:xe(`${e.name} failed to run ${t.name}.`),outcome:"app_error",bytes:o.bytes,drifted:!1,reason:u});if(!Se(a)||a.v!==1)return i(`http_${r.status}`);if(r.ok){let u=X_(a.result);return u?{result:u,outcome:u.isError?"tool_error":"ok",bytes:o.bytes,drifted:a.catalogHash!==e.catalogHash}:i("malformed_result")}let l=Se(a.error)?a.error:{},c=typeof l.code=="string"?l.code:"unknown";return c==="invalid_arguments"?{result:xe(typeof l.message=="string"?l.message:`Invalid arguments for ${t.name}.`),outcome:"invalid_arguments",bytes:o.bytes,drifted:!1}:c==="unknown_tool"?{result:xe(`${t.name} is no longer available in ${e.name}. Its tool list is being refreshed; list tools again.`),outcome:"app_error",bytes:o.bytes,drifted:!0,reason:"unknown_tool"}:i(c)}function X_(e){if(!Se(e)||!Array.isArray(e.content))return null;let t=e.content;if(!t.every(n=>Se(n)&&typeof n.type=="string"&&(n.type!=="text"||typeof n.text=="string")))return null;let r=e.structuredContent;return r!==void 0&&!Se(r)?null:{content:t,...r?{structuredContent:r}:{},...e.isError===!0?{isError:!0}:{}}}var Xl="0.1.0",Z_=6e4,Q_=100,eb=50,kh=200;function zi(e,t){if(typeof e!="string")return"";let r=e.replace(/[\p{Cc}\p{Cf}]/gu," ").replace(/\s+/g," ").trim();return Array.from(r).slice(0,t).join("").trim()}function Zl(e){if(!Se(e))return;let t=zi(e.name,Q_);if(!t)return;let r=zi(e.version,eb);return r?`${t} ${r}`:t}function Ch(e){return(t,r)=>e(t)<e(r)?-1:e(t)>e(r)?1:0}function tb(e,t,r){return{name:Id(e,t,r),...r.title?{title:r.title}:{},description:r.description,inputSchema:r.inputSchema,...r.outputSchema?{outputSchema:r.outputSchema}:{},annotations:{...r.annotations,readOnlyHint:r.risk==="read",...r.risk==="read"?{}:{destructiveHint:r.risk==="destructive"},openWorldHint:r.annotations?.openWorldHint??!1}}}function Ql(e,t={}){let r=e.surface==="gateway"?bh(e,t):[];if(e.surface==="gateway"&&e.listing==="compact")return r;for(let n of[...e.apps].sort(Ch(o=>o.appId)))for(let o of[...n.tools].sort(Ch(a=>a.name)))Je(o,e.principal).action==="allow"&&r.push(tb(e,n,o));return r}async function Pi(e,t={}){let r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(yu(Ql(e,t)))),n="";for(let o of new Uint8Array(r).subarray(0,8))n+=o.toString(16).padStart(2,"0");return n}function eu(e,t,r,n={}){let o=new wi({name:e.serverInfo.name,...e.serverInfo.title?{title:e.serverInfo.title}:{},version:Xl},{capabilities:{tools:{listChanged:n.listChanged??!1}},...e.instructions?{instructions:e.instructions}:{},jsonSchemaValidator:ls,cacheHints:{"tools/list":{ttlMs:Z_,cacheScope:"private"}}});return o.setRequestHandler("tools/list",async()=>({tools:Ql(e,{workspace:t.workspace!==void 0,providers:t.workspace?.providers===!0})})),o.setRequestHandler("tools/call",async a=>{let i=Zl(o.getClientVersion())??n.clientInfo,l=await $h(e,{name:a.params.name,arguments:a.params.arguments,...r?{protocolVersion:r}:{},...i?{clientInfo:i}:{}},t);if(l.kind==="unknown_tool")throw new te(G.InvalidParams,`Unknown tool: ${jn(a.params.name)}`);return o.projectCallToolResult(l.result,l.tool.outputSchema)}),o}var Ci=class extends Error{name="ViewRefusedError"};var tu=256*1024,rb=3e4,nb=30*6e4,ob=10*6e4,sb=3,ab=8,Oh=128,ib=Oh/4*3,Ih="2026-07-28",Mh="everyapp.toolbus.view",cb="io.modelcontextprotocol/subscriptionId",lb="io.modelcontextprotocol/serverInfo",Nh={jsonrpc:"2.0",method:"notifications/tools/list_changed"},qh={"content-type":"text/event-stream","cache-control":"no-cache, no-transform","x-accel-buffering":"no"},ub=["accept","authorization","content-type","last-event-id","mcp-method","mcp-name","mcp-protocol-version","mcp-session-id","x-everyapp-tools"].join(", ");function jh(e){let t=new Map,r,n=()=>r??=Zm(o=>{let a=pb(o);return eu(a,e,o.requestInfo?.headers.get("mcp-protocol-version")??void 0,{listChanged:a.refresh!==void 0})},{legacy:"reject",responseMode:"json",maxSubscriptions:0,maxRequestBodySize:tu});return async(o,a)=>{let i=$b(o,e,a);if(i)return i;let l=Pb(o);if(o.method==="OPTIONS")return new Response(null,{status:204,headers:{...l,"access-control-allow-methods":"POST, OPTIONS","access-control-allow-headers":ub,"access-control-max-age":"600"}});if(o.method!=="POST")return ki(_t(405,-32e3,"Method not allowed.",{allow:"POST, OPTIONS"}),l);let c;try{c=await $i(o.clone(),tu)}catch{return ki(_t(400,-32700,"Parse error: the request body could not be read."),l)}if(c.tooLarge)return ki(_t(413,-32600,"Request body too large."),l);let u;try{u=JSON.parse(c.text)}catch{u=void 0}let m={token:"toolbus",clientId:a.principal.credential.id,scopes:Jl(a.principal.access),extra:{[Mh]:a}},f=u!==void 0?{parsedBody:u}:{},y=await Xm(o,u,{maxRequestBodySize:tu}),R,S=a.refresh?db(o,u):null;return y?R=await mb(o,a,e,m,u):S?R=await Rb(o,a,e,S,t):R=await n().fetch(o,{authInfo:m,...f}),ki(R,l)}}function db(e,t){if(e.headers.get("mcp-method")!=="subscriptions/listen"||e.headers.get("mcp-protocol-version")!==Ih||!Eo(e.headers.get("content-type")))return null;let r=pi({httpMethod:e.method,protocolVersionHeader:e.headers.get("mcp-protocol-version"),mcpMethodHeader:"subscriptions/listen",mcpNameHeader:e.headers.get("mcp-name")??void 0,body:t});return r.kind==="modern"&&r.messageKind==="request"&&r.message.method==="subscriptions/listen"&&r.classification.revision===Ih?r.message:null}function pb(e){let t=e.authInfo?.extra?.[Mh];if(!t)throw new Error("ToolBus request has no view");return t}function ru(e){return{workspace:e.workspace!==void 0,providers:e.workspace?.providers===!0}}async function mb(e,t,r,n,o){if(Array.isArray(o))return _t(400,-32600,"Bad Request: JSON-RPC batches are not supported by this endpoint.");let a=Tb(e.headers,o);if(a)return _t(400,-32020,`Bad Request: ${a}`,{},o);let i=Se(o)?o.method:void 0,l=Se(o)&&Se(o.params)?o.params:{},c=await Pi(t,ru(r)),u=e.headers.get("mcp-session-id"),m=gb(u),f=m!==void 0&&m!==c,y=i==="initialize"?Zl(l.clientInfo):fb(u);if(f&&i==="tools/list")return _t(404,-32001,"Session not found");let R=eu(t,r,e.headers.get("mcp-protocol-version")??void 0,{listChanged:!0,...y?{clientInfo:y}:{}}),S=new Ml({sessionIdGenerator:i==="initialize"?()=>Lh(c,y):void 0,enableJsonResponse:!0});try{await R.connect(S);let P=await S.handleRequest(e,{authInfo:n,...o!==void 0?{parsedBody:o}:{}});return f&&yb(o)&&i!=="initialize"&&Dh(e)?await Sb(P,c,y):P}finally{await Promise.all([S.close().catch(()=>{}),R.close().catch(()=>{})])}}function Lh(e,t){let r=t?hb(t):"";return r?`${crypto.randomUUID()}.${r}.${e}`:`${crypto.randomUUID()}.${e}`}function hb(e){let t=new TextEncoder,r=e,n=t.encode(r);for(;n.length>ib;)r=Array.from(r).slice(0,-1).join(""),n=t.encode(r);let o="";for(let a of n)o+=String.fromCharCode(a);return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fb(e){let t=e?.split(".")??[],r=t.length===3?t[1]:void 0;if(!(!r||r.length>Oh||!/^[A-Za-z0-9_-]+$/.test(r)))try{let n=r.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-r.length%4)%4),o=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(atob(n),a=>a.charCodeAt(0)));return zi(o,kh)||void 0}catch{return}}function gb(e){let t=e?.slice(e.lastIndexOf(".")+1);return t&&/^[0-9a-f]{16}$/.test(t)?t:void 0}function yb(e){return Se(e)&&typeof e.method=="string"&&"id"in e}function Dh(e){return(e.headers.get("accept")??"").includes("text/event-stream")}function Ii(e){return`event: message
53
+ data: ${JSON.stringify(e)}
54
+
55
+ `}async function Sb(e,t,r){if(e.status!==200||!e.headers.get("content-type")?.includes("application/json"))return e;let n=new Headers(e.headers);for(let[o,a]of Object.entries(qh))n.set(o,a);return n.set("mcp-session-id",Lh(t,r)),new Response(`${Ii(Nh)}event: message
56
+ data: ${await e.text()}
57
+
58
+ `,{status:200,headers:n})}function vb(e){for(let r of["toolsListChanged","promptsListChanged","resourcesListChanged"])if(r in e&&typeof e[r]!="boolean")return!1;let t=e.resourceSubscriptions;return t===void 0||Array.isArray(t)&&t.every(r=>typeof r=="string")}function _b(e){let{credential:t}=e.principal;return t.id==="session"||t.id==="pat"?`${t.kind}:${e.principal.userId}`:t.id}function bb(e,t){return t.listenMaxMs??(e.surface==="gateway"?nb:ob)}async function Rb(e,t,r,n,o){let a=n.id;if(!Dh(e))return _t(406,-32e3,"Not Acceptable: Client must accept text/event-stream");let l=(Se(n.params)?n.params:{}).notifications;if(!Se(l)||!vb(l))return Response.json({jsonrpc:"2.0",id:a,error:{code:-32602,message:Se(l)?"notifications: invalid subscription filter":"notifications is required"}});let c=l.toolsListChanged===!0,u=t.refresh;if(!u)throw new Error("subscriptions/listen needs view.refresh");let m=_b(t);if((o.get(m)??0)>=ab)return Response.json({jsonrpc:"2.0",id:a,error:{code:-32603,message:"Subscription limit reached"}});o.set(m,(o.get(m)??0)+1);let f=()=>{let z=(o.get(m)??1)-1;z>0?o.set(m,z):o.delete(m)},y=r.listenPollMs??rb,R=bb(t,r),S={[cb]:a},P=new TextEncoder,b;try{b=await Pi(t,ru(r))}catch(z){throw f(),z}let h,$=!1,v=new ReadableStream({start(z){let I=q=>z.enqueue(P.encode(q)),T=()=>{$||($=!0,f(),I(Ii({jsonrpc:"2.0",id:a,result:{resultType:"complete",_meta:{...S,[lb]:wb(t)}}})),z.close())};if(I(Ii({jsonrpc:"2.0",method:"notifications/subscriptions/acknowledged",params:{notifications:c?{toolsListChanged:!0}:{},_meta:S}})),!c){T();return}let _=Date.now(),C=Math.min(_+R,t.listenUntil??1/0),M=0,U=async()=>{if($)return;if(Date.now()>=C){T();return}let q;try{q=await Pi(await Eb(u(),y),ru(r)),M=0}catch(D){if(M+=1,D instanceof Ci||M>=sb){T();return}}$||(q===void 0||q===b?I(`: keepalive
59
+
60
+ `):(b=q,I(Ii({...Nh,params:{_meta:S}}))),h=setTimeout(U,y))};h=setTimeout(U,y)},cancel(){$||f(),$=!0,clearTimeout(h)}});return e.signal?.addEventListener("abort",()=>{$||f(),$=!0,clearTimeout(h)}),new Response(v,{status:200,headers:qh})}function wb(e){return{name:e.serverInfo.name,...e.serverInfo.title?{title:e.serverInfo.title}:{},version:Xl}}function Eb(e,t){let r,n=new Promise((o,a)=>{r=setTimeout(()=>a(new Error("refresh timed out")),t)});return Promise.race([e,n]).finally(()=>clearTimeout(r))}function Ah(e){let t=/^=\?base64\?(.*)\?=$/i.exec(e)?.[1];if(t===void 0)return e;try{return new TextDecoder().decode(Uint8Array.from(atob(t),r=>r.charCodeAt(0)))}catch{return e}}function Tb(e,t){if(!Se(t))return null;let r=e.get("mcp-method");if(r!==null&&Ah(r)!==t.method)return`the Mcp-Method header names "${r}" but the body is "${String(t.method)}"`;let n=e.get("mcp-name");if(n!==null){let o=Se(t.params)?t.params:{},a=o.name??o.uri;if(Ah(n)!==a)return`the Mcp-Name header names "${n}" but the body names "${String(a)}"`}return null}function xh(e){let t=e.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="[::1]"}function $b(e,t,r){if(t.localhostOnly){let o=null;try{o=new URL(`http://${e.headers.get("host")??""}`).hostname}catch{o=null}if(!o||!xh(o))return _t(403,-32e3,"Forbidden: invalid Host header.")}let n=e.headers.get("origin");return n===null||zb(n,e,t,r)?null:_t(403,-32e3,"Forbidden: origin not allowed.")}function zb(e,t,r,n){if(e===new URL(t.url).origin||n.allowedOrigins?.includes(e.toLowerCase()))return!0;if(!r.localhostOnly)return!1;try{let o=new URL(e);return(o.protocol==="http:"||o.protocol==="https:")&&xh(o.hostname)}catch{return!1}}function Pb(e){let t=e.headers.get("origin");return t===null||t===new URL(e.url).origin?{}:{"access-control-allow-origin":t,"access-control-expose-headers":"mcp-protocol-version, mcp-session-id",vary:"Origin"}}function ki(e,t){if(Object.keys(t).length===0)return e;let r=new Headers(e.headers);for(let[n,o]of Object.entries(t))r.set(n,o);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}function _t(e,t,r,n={},o){let a=Se(o)&&(typeof o.id=="string"||typeof o.id=="number")?o.id:null;return Response.json({jsonrpc:"2.0",error:{code:t,message:r},id:a},{status:e,headers:n})}function Hh(e,t){let r={userId:e.sub,email:e.email,organizationId:e.orgId,orgRole:e.orgRole},n=e.credential;if(!n)return{ok:!0,principal:{...r,credential:{kind:t.sessionKind,id:"session"},access:"write"}};if(n.kind!=="pat")return{ok:!1,reason:"unsupported_credential"};let o=n.scopes??[],a=o.some(l=>l==="*"||l===Yo)?"write":o.includes(Cn)?"read":null;if(!a)return{ok:!1,reason:"token_scope"};let i=n.actor?.startsWith("pat:")?n.actor.slice(4):"pat";return{ok:!0,principal:{...r,credential:{kind:"pat",id:i},access:a}}}var KT=8*1024;var WT=1024*1024;function Uh(e,t,r){return{surface:"app",principal:t,apps:[e],serverInfo:{name:`every-app-${e.appId}`,title:e.name},...e.instructions?{instructions:e.instructions}:{},...r?{requestId:r}:{}}}var Cb=2e3;function Vh(e){let t=new Map(e.apps.map(u=>[u.appId,u])),r={privateKeyPem:e.privateKeyPem,issuer:e.issuer,keyId:e.keyId??Kt},n=e.catalogTtlMs??Cb,o=new Map,a=new Set,i=(u,m)=>{let f=`${u}\0${m}`;a.has(f)||(a.add(f),e.onCatalogProblem?.(u,m))},l=u=>{let m=o.get(u.appId);if(m&&m.expiresAt>Date.now())return m.snapshot;let f=Gd({...u,audience:u.appId},{signing:r,invoke:y=>u.fetcher.fetch(y)}).catch(y=>({status:"error",error:`could not reach the app (${y instanceof Error?y.message:String(y)})`}));return o.set(u.appId,{expiresAt:Date.now()+n,snapshot:f}),f},c=jh({signing:r,invokeApp:(u,m)=>{let f=t.get(u.appId);if(!f)throw new Error(`no dev app "${u.appId}"`);return f.fetcher.fetch(m)},onCatalogDrift:u=>o.delete(u.appId),audit:e.onToolCall,localhostOnly:!0});return{async serveAppHost(u,m,f){let y=t.get(m);if(!y)return null;let R=await l(y);if("error"in R)return i(m,R.error),null;if(R.status==="empty")return null;for(let b of R.warnings)i(m,b);let S=Hh(f,{sessionKind:"dev"});if(!S.ok)return Response.json({error:"forbidden",reason:S.reason},{status:403});let P={rowId:m,appId:m,audience:m,name:y.name??m,baseUrl:y.baseUrl,catalogHash:R.hash,...R.instructions?{instructions:R.instructions}:{},tools:R.tools};return c(u,Uh(P,S.principal))}}}var Bh=e=>e.replaceAll("_"," ");function Fh(e){let{out:t}=e,r=Vh({apps:[{appId:e.app.appId,name:e.appName,baseUrl:e.appUrl,fetcher:e.appFetcher}],privateKeyPem:Yt,issuer:Wt,onToolCall:n=>t.emit({type:"progress",step:"dev.mcp",message:["MCP",n.tool,n.decision==="blocked"?`blocked${n.reason?`: ${Bh(n.reason)}`:""}`:`${Bh(n.outcome)} ${n.durationMs}ms`].join(" "),data:{tool:n.tool,decision:n.decision,reason:n.reason,outcome:n.outcome,durationMs:n.durationMs}}),onCatalogProblem:(n,o)=>t.emit({type:"warning",code:"TOOLS_CATALOG",step:"dev.mcp",message:`Agent tools: ${o}`,data:{appId:n}})});return Cd({apps:[e.app],env:{[`APP__${e.app.workerName}`]:e.appFetcher},authenticator:e.authenticator,interceptMcp:({request:n,app:o,session:a})=>r.serveAppHost(n,o.appId,a)})}function Gh(e,t,r){return["<!doctype html><html><head><meta charset=utf-8>","<title>every app \u2014 dev launcher</title>","<style>body{font-family:system-ui;max-width:32rem;margin:4rem auto;padding:0 1rem;color:#222}a{color:#0a7;font-size:1.25rem}p{color:#666}</style>","</head><body>","<h1>every app <small style='color:#999;font-weight:400'>dev launcher</small></h1>","<p>Signed in as <code>dev@everyapp.localhost</code> (seeded dev user \u2014 stub mode).</p>",`<p><a href="http://${e}.${r}/">${t??e} \u2192</a></p>`,"</body></html>"].join("")}function Jh(e){return{appId:e.id,hostname:`${e.id}.localhost`,workerName:Mu(e.id),tier:"service_binding",scope:"org",organizationId:zt.orgId,status:"active",manifest:e}}var nu="/__everyapp/cron";async function Wh(e,t){let r=await Xh(e,t);if(r)throw await Zh(r,e,t)}async function Yh(e,t,r){try{await new Promise((n,o)=>{e.once("error",o),e.listen(t,r,n)})}catch(n){throw await Zh(n,t,r)}return e.address()}function Xh(e,t){return new Promise(r=>{let n=Kh.createServer();n.once("error",r),n.listen(e,t,()=>n.close(()=>r(null)))})}async function Zh(e,t,r){if(e.code!=="EADDRINUSE")return new De("DEV_PORT_UNAVAILABLE",`Can't listen on ${r}:${t}
61
+ ${e.message}`,{data:{port:t,host:r,fix:"pass another --port or --host"}});let n=t+1;for(;await Xh(n,r);)n++;return new De("DEV_PORT_IN_USE",`Port ${t} is already in use`,{rerun:os("--port",String(n)),data:{port:t,host:r,free:n,error:e.message}})}function Qh(e,{manifest:t,mode:r,mirrorBaseHost:n,gatewayUrl:o,authenticator:a,appPort:i,appUrl:l,out:c}){let u=Jh(t),m=Ab(c),f=nc(i),y=Fh({app:u,appName:t.name,appUrl:l,appFetcher:{fetch:b=>f.fetch(b).catch(h=>{throw m.failed(b.method,new URL(b.url).pathname,h),h})},authenticator:a,out:c}),R=Number(o?.port||80),S=o?nc(R,o.hostname):null;e.on("request",(b,h)=>{(async()=>{try{let $=b.headers.host??"";if(!lc($,S?n:void 0)){P(h,$,`${t.id}.localhost`);return}if(b.method==="POST"&&b.url===nu){if(Td(b.headers)){h.writeHead(403,{"content-type":"text/plain; charset=utf-8"}),h.end(`The cron trigger takes a terminal's POST (curl -X POST ... -d '<schedule>'), not a web page's.
62
+ `);return}await ns(h,await kb(await Ib(b),i,u.workerName));return}if(S){let I=cc($,n);if(I.kind==="launcher"){let T=await S.fetch(rc(b));await ns(h,T);return}if(I.kind==="invalid"||I.appLabel!==t.id){P(h,$,`${t.id}.${n}`);return}}let v=Xt($||null);if(r==="stub"&&v){if(v.appLabel===""){h.writeHead(200,{"content-type":"text/html; charset=utf-8"}),h.end(Gh(t.id,t.name,v.host));return}if(v.appLabel!==t.id&&!Kh.isIP(v.host.replace(/:\d+$/,""))){P(h,$,`${t.id}.${v.baseHost.replace(/:\d+$/,"")}`);return}}let z=await y(rc(b));await ns(h,z)}catch($){m.failed(b.method??"GET",b.url??"/",$),h.headersSent||h.writeHead(502,{"content-type":"application/json"}),h.end(JSON.stringify({error:"dev_gateway_error",message:String($)}))}})()});function P(b,h,$){m.misdirected(h,$),b.writeHead(421,{"content-type":"text/plain; charset=utf-8"}),b.end(`This dev server serves ${$}, not ${h}.
63
+ `)}e.on("upgrade",(b,h,$)=>{if(!lc(b.headers.host??"",o?n:void 0)){h.write(`HTTP/1.1 421 Misdirected Request\r
64
+ Connection: close\r
65
+ \r
66
+ `),h.destroy();return}if(o&&cc(b.headers.host??"",n).kind==="launcher"){oc(b,h,$,R,{targetHost:o.hostname});return}_d(b,h,$,{appId:t.id,appPort:i,publicRoutes:u.manifest.public,parseAppLabel:v=>Xt(v)?.appLabel??"",mintIdentity:async v=>{if(a){let z=await a.authenticate(v);return z?uc(t.id,z):null}return uc(t.id)},mintPublicMarker:()=>kd(t.id)})})}async function kb(e,t,r){let n=e.trim();return n?fetch(`http://127.0.0.1:${t}/cdn-cgi/local/explorer/api/local/scheduled?worker=${encodeURIComponent(r)}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({cron:n})}):new Response(`Send the cron schedule as the body: -d '*/5 * * * *'
67
+ `,{status:400,headers:{"content-type":"text/plain; charset=utf-8"}})}async function Ib(e){let t=[];for await(let r of e)t.push(r);return Buffer.concat(t).toString("utf8")}function Ab(e){let t=new Set,r=(n,o)=>{t.has(n)||(t.add(n),o())};return{failed(n,o,a){let i=Tr(a);r(`failed
68
+ ${i}`,()=>e.emit({type:"warning",code:"DEV_REQUEST_FAILED",message:`${n} ${o} failed in the local Gateway: ${i}`,data:{method:n,path:o,status:502}}))},misdirected(n,o){r(`misdirected
69
+ ${n}`,()=>e.emit({type:"warning",code:"DEV_WRONG_HOST",message:`Request for ${n} refused: this dev server serves ${o}`,data:{host:n,served:o,status:421}}))}}}import ou from"node:fs";import su from"node:path";import{parseEnv as Ob}from"node:util";import bt from"chalk";function ef({manifest:e,mode:t,appUrl:r,appPort:n,gatewayUrl:o,loginUrl:a,crons:i,cwd:l}){let c=[{label:"App",value:bt.cyan(r)},{label:"MCP",value:`${bt.cyan(`${r}/mcp`)} ${bt.dim(t==="mirror"?"bearer: a personal access token from the local Gateway":"any bearer token acts as the dev user")}`},...t==="mirror"?[{label:"Log in",value:`${bt.cyan(a)} ${bt.dim("the session carries to the app")}`},{label:"Gateway",value:`${o} ${bt.dim("(real login and launcher)")}`}]:[{label:"Dev user",value:`${zt.email} ${bt.dim(`(${zt.orgRole} of ${zt.orgId})`)}`}],...e.resources?.workflows?.length?[{label:"Workflows",value:bt.cyan(`http://127.0.0.1:${n}/cdn-cgi/local/explorer`)}]:[],...Mb(e,n),...i?[{label:"Cron",value:`curl -X POST ${r}${nu} -d '<schedule>'`}]:[],...Nb(e,l)];return["",...Hu(c).map(u=>` ${u}`),""].join(`
70
+ `)}function Mb(e,t){return e.email?.inbound!==!0?[]:[{label:"Email",value:`curl -X POST "http://127.0.0.1:${t}/cdn-cgi/local/email?from=someone@example.net&to=hello@example.com" --data-binary @message.eml`}]}var au=".dev.vars";function Nb(e,t){let r=qb(e,iu(t));if(r.length===0)return[];let n=jb(t),o=Tu(r,(c,u)=>!!n?.[u]);if(o.ready)return[];let a=[];for(let c of o.unmet)if(c.need.kind==="required")for(let u of c.names)!n?.[u]&&!a.includes(u)&&a.push(u);let i=o.groups.filter(c=>!c.met).map(c=>`one of ${c.members.map(u=>u.names.join(" with ")).join(", ")}`),l=[...a.length>0?[a.join(", ")]:[],...i].join(" and ");return[{label:"Dev vars",value:`${n?`${au} is missing ${l}`:`no ${au} yet: add ${l}`} ${bt.dim(`(the app's keys for local runs; see ${Pn} dev --help)`)}`}]}function qb(e,t){return Eu(e,t).flatMap(r=>{switch(r.kind){case"provider":{let n=vu(r.id);return[n?{...r,names:_u(n)}:r]}case"capability":return Xo(r.id)&&Su[r.id].mode==="service"?[]:[r];case"ai-routes":return[];case"remote-mcp":return[];case"secret":return[r]}})}function iu(e){let t=su.join(e,Iu),r;try{r=ou.readdirSync(t).filter(o=>o.endsWith(".json")).sort()}catch{return Oi}let n=r.flatMap(o=>{try{let a=JSON.parse(ou.readFileSync(su.join(t,o),"utf8"));return[{id:a&&typeof a=="object"&&typeof a.id=="string"?a.id:o.replace(/\.json$/,""),spec:a}]}catch{return[]}});return n.length>0?ku(n):Oi}function jb(e){try{return Ob(ou.readFileSync(su.join(e,au),"utf8"))}catch{return null}}var Db="http://localhost:3000",xb="127.0.0.1",Hb=8787,Ub=5e3;async function Vb(e){let t=Uu(!1);await Vu(t,()=>Bb(e,t))}async function Bb(e,t,{cwd:r=process.cwd(),cf:n=xu(),env:o=process.env}={}){let a=wd(e.mode,o[ic]),i=e.gateway??Db,l=e.baseHost??Zt;a==="mirror"&&Ed(l);let c=await Fb(r);Gb(c,r,t);let u=await Zu(r);if(!c.dev&&!u)throw new De("MISSING_CLOUDFLARE_CONFIG",["No cloudflare.config.ts in this directory","Every App apps build their Worker in cloudflare.config.ts with everyAppWorker() from @every-app/sdk/cloudflare."].join(`
71
+ `),{data:{fix:"copy cloudflare.config.ts from starter/"}});let m=e.host??xb,f=e.port??(o.PORT?Number(o.PORT):Hb);await Wh(f,m);let y=await Du(r);y.source==="project"&&y.version!==Zo&&t.emit({type:"warning",code:"CF_VERSION_DIFFERS",message:`Using the app's cf ${y.version}; everyapp is tested with ${Zo}`,data:{version:y.version,tested:Zo}});let R,S=!1,P=ju({sync:()=>R?.stop(),async:async()=>{await R?.exited,t.emit({type:"step",step:"dev.stop",status:"ok",data:{appId:c.id,started:S}})}}),b=Di(c.id),h=v=>{b(),b=Di(v)},$=()=>R?.stop();process.on("exit",$);try{a==="mirror"&&await Jb(i,t),u&&!await Wu(r)&&(t.emit({type:"step",step:"dev.types",status:"start",message:"Generating Worker types..."}),await Ku(n,r),t.emit({type:"step",step:"dev.types",status:"ok",message:"Generated the Worker's types (.cloudflare/types)."})),h("the local migrations"),await zd({cwd:r,manifest:c,cf:n,out:t,skip:e["skip-migrations"]??!1}),h(c.id);let v=await bd();t.emit({type:"step",step:"dev.app",status:"start",message:c.dev?`Starting ${c.id} with its dev command...`:`Starting ${c.id}...`,data:{appPort:v}}),R=await Pd({cwd:r,manifest:c,cf:n,port:v});let z=Lb.createServer();try{await Wb(R,v,c).catch(async C=>{throw Li()||(t.emit({type:"step",step:"dev.app",status:"fail"}),R.stop(),await R.exited,R.releaseOutput(!0)),C});let I=await Yh(z,f,m),T=a==="mirror"?`http://${c.id}.${l}:${I.port}`:`http://${c.id}.localhost:${I.port}`,_=`http://${l}:${I.port}`;Qh(z,{manifest:c,mode:a,mirrorBaseHost:l,gatewayUrl:a==="mirror"?new URL(i):null,authenticator:Kb(a,i,_,t),appPort:v,appUrl:T,out:t}),S=!0,h(""),t.emit({type:"step",step:"dev.app",status:"ok",message:ef({manifest:c,mode:a,appUrl:T,appPort:v,gatewayUrl:i,loginUrl:_,crons:u?.hasCrons??!1,cwd:r}),data:{appId:c.id}}),R.releaseOutput(!1),t.emit({type:"step",step:"dev.ready",status:"ok",data:{mode:a,appUrl:T,mcpUrl:`${T}/mcp`,host:I.address,port:I.port,appPort:v}}),a==="stub"&&!Yb(I.address)&&t.emit({type:"warning",code:"DEV_EXPOSED",message:`Listening on ${I.address}: anyone who can reach port ${I.port} gets in as the dev user`}),t.emit({type:"progress",step:"dev.session",message:"Every request goes through the real perimeter. Ctrl+C to stop."}),await R.exited}finally{z.close()}}catch(v){if(Li())return;throw R?.stop(),v}finally{process.off("exit",$),b(),P()}}async function Fb(e){try{return await Bu(e)}catch(t){throw t instanceof Ou?new De("INVALID_MANIFEST",`everyapp.config.ts isn't valid
72
+ ${t.message}`):t}}function Gb(e,t,r){let n=iu(t);for(let o of Object.keys(e.capabilities??{})){if(Xo(o))continue;let a=Au(o),i=n.get(o)!==void 0;r.emit({type:"warning",code:"CAPABILITY_NOT_IN_CATALOG",message:i?`${o} isn't in the built-in provider catalog
73
+ This run reaches it from ${a} with your key from .dev.vars; the deploy checks it against the Gateway's registered providers.`:`${o} isn't in the built-in provider catalog
74
+ If it's registered on your Gateway, ${Pn} provider show ${o} --save writes ${a}, which this run reaches it from (start dev again after). The deploy checks it against the Gateway's registered providers.`,data:{id:o,file:a,found:i,...i?{}:{fix:`${Pn} provider show ${o} --save`}}})}}async function Jb(e,t){t.emit({type:"step",step:"dev.gateway",status:"start",message:`Looking for the local Gateway at ${e}...`});try{await sc(e,Ub)}catch{throw t.emit({type:"step",step:"dev.gateway",status:"fail"}),new De("MIRROR_GATEWAY_UNREACHABLE",`No local Gateway at ${e}
75
+ See "mirror mode" in docs/TESTING.md.`,{data:{gatewayUrl:e,fix:"run pnpm dev in apps/every-app-gateway, or pass --gateway <url>"}})}t.emit({type:"step",step:"dev.gateway",status:"ok",data:{gatewayUrl:e}})}function Kb(e,t,r,n){if(e==="mirror")return $d({gatewayUrl:t,loginUrl:r,onHint:o=>n.emit({type:"warning",code:"MIRROR_SESSION",message:o})})}async function Wb(e,t,r){let n=await Promise.race([Rd(t).then(()=>"up",()=>"timeout"),e.exited.then(()=>"exited")]);if(n!=="up")throw n==="exited"?new De("DEV_SERVER_FAILED",`${r.id}'s dev server exited before it was ready
76
+ Its output is above.`):new De("DEV_SERVER_TIMEOUT",`${r.id}'s dev server didn't start listening in time
77
+ It must listen on the port everyapp passes in PORT.`,{data:{appPort:t,fix:r.dev?`make its dev command (${r.dev}) listen on the port in PORT`:"in vite.config.ts, set server.port: Number(process.env.PORT)"}})}function Yb(e){return e==="::1"||e.startsWith("127.")}export{Vb as default,Bb as runDev};
78
+ /*! Bundled license information:
79
+
80
+ @modelcontextprotocol/server/dist/src-DdvbAHrR.mjs:
81
+ (*!
82
+ * content-type
83
+ * Copyright(c) 2015 Douglas Christopher Wilson
84
+ * MIT Licensed
85
+ *)
86
+ */