videobook 0.2.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +6 -2
  3. package/dist/archive-b2.js +1 -1
  4. package/dist/cli/args.js +42 -3
  5. package/dist/cli/config-command.js +17 -1
  6. package/dist/cli/doctor-command.js +15 -0
  7. package/dist/cli/har-command.js +86 -0
  8. package/dist/cli/main.js +13 -1
  9. package/dist/command-reference.js +5 -1
  10. package/dist/content-store.js +2 -1
  11. package/dist/diagnostics.js +1 -1
  12. package/dist/env-secrets.js +1 -0
  13. package/dist/generation-har.js +106 -0
  14. package/dist/har-capture.js +142 -0
  15. package/dist/har-export.js +238 -0
  16. package/dist/har-index.js +98 -0
  17. package/dist/har-retention.js +73 -0
  18. package/dist/har-settings.js +27 -0
  19. package/dist/jobs/_alibaba-upload.js +2 -4
  20. package/dist/jobs/_fal-upload.js +2 -4
  21. package/dist/jobs/_image-edit-adapter.js +1 -1
  22. package/dist/jobs/_kie-upload.js +2 -4
  23. package/dist/jobs/complete-provider-task.js +5 -2
  24. package/dist/jobs/generate-media.js +9 -1
  25. package/dist/jobs/image-subjects.js +1 -1
  26. package/dist/jobs/kie-paygate.js +10 -3
  27. package/dist/jobs/run-notebook.js +4 -1
  28. package/dist/jobs/xai-paygate.js +5 -2
  29. package/dist/media/adapters/kie.js +2 -1
  30. package/dist/media/catalog.js +20 -0
  31. package/dist/media/cost.js +1 -1
  32. package/dist/package-version.js +18 -0
  33. package/dist/posts/dropbox-auth.js +1 -1
  34. package/dist/posts/post-metrics.js +2 -1
  35. package/dist/provider-usage.js +1 -18
  36. package/dist/queue.js +12 -1
  37. package/dist/serve.js +2 -0
  38. package/dist/tools/api-status.js +1 -1
  39. package/dist/tools/generate-media.js +3 -0
  40. package/dist/tools/generation-payload.js +17 -2
  41. package/dist/tools/get-generation-har.js +43 -0
  42. package/dist/tools/index.js +4 -0
  43. package/dist/tools/list-cell-generations.js +19 -0
  44. package/dist/tools/reconcile-project-work.js +18 -12
  45. package/dist/tools/set-har-capture.js +30 -0
  46. package/dist/upload.js +2 -1
  47. package/dist/usage-providers.js +48 -10
  48. package/dist/workspace-action-groups.js +2 -2
  49. package/dist/x/account.js +1 -1
  50. package/dist/x/authenticated-handle.js +1 -1
  51. package/dist/x/oauth-flow.js +1 -1
  52. package/dist/x/post-to-x.js +2 -1
  53. package/dist/x/x-tokens.js +2 -1
  54. package/package.json +15 -14
  55. package/ui/assets/{alive-captions-Bp6dxosy.js → alive-captions-Cj8C1tCN.js} +1 -1
  56. package/ui/assets/{confirm-bodies-Ds1HtaGc.js → confirm-bodies-BxWXwDf0.js} +1 -1
  57. package/ui/assets/{fullscreen-BCeVHjvY.js → fullscreen-DyEncSdm.js} +1 -1
  58. package/ui/assets/{goal-ui-DbAGwgMN.js → goal-ui-BdFeoSWh.js} +2 -2
  59. package/ui/assets/{index-D1d-F1y9.js → index-QZ8lbemN.js} +9 -9
  60. package/ui/assets/inspector-BC6xWkJU.js +1 -0
  61. package/ui/assets/{jobs-ui-C1cbw-xG.js → jobs-ui-BudI4w0r.js} +1 -1
  62. package/ui/assets/{music-video-CWtxPlxq.js → music-video-CT4C55ok.js} +1 -1
  63. package/ui/assets/ui-mq0uIS5P.css +1 -0
  64. package/ui/assets/ui-z5r-p0K9.js +2 -0
  65. package/ui/assets/{vendor-BFupLz37.js → vendor-D8XcMav4.js} +2 -2
  66. package/ui/assets/{vendor-flow-CKiuzaeM.js → vendor-flow-nqTFQmTh.js} +1 -1
  67. package/ui/assets/vendor-mcp-D_C3EZPv.js +60 -0
  68. package/ui/assets/videobook-CsW453sb.js +21 -0
  69. package/ui/index.html +12 -12
  70. package/ui/assets/inspector-BJTC0luH.js +0 -1
  71. package/ui/assets/ui-CXDi5Omq.js +0 -2
  72. package/ui/assets/ui-Oirr9VOf.css +0 -1
  73. package/ui/assets/vendor-mcp-DQEeVZH0.js +0 -67
  74. package/ui/assets/videobook-J-j9bSjM.js +0 -20
@@ -1,67 +0,0 @@
1
- import{W as Fl,X as Hl}from"./vendor-BFupLz37.js";const Jl="modulepreload",Bl=function(e){return"/"+e},Qs={},ny=function(t,o,n){let r=Promise.resolve();if(o&&o.length>0){let u=function(l){return Promise.all(l.map(d=>Promise.resolve(d).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),a=s?.nonce||s?.getAttribute("nonce");r=u(o.map(l=>{if(l=Bl(l),l in Qs)return;Qs[l]=!0;const d=l.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${h}`))return;const m=document.createElement("link");if(m.rel=d?"stylesheet":Jl,d||(m.as="script"),m.crossOrigin="",m.href=l,a&&m.setAttribute("nonce",a),document.head.appendChild(m),d)return new Promise((f,v)=>{m.addEventListener("load",f),m.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${l}`)))})}))}function i(s){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=s,window.dispatchEvent(a),!a.defaultPrevented)throw s}return r.then(s=>{for(const a of s||[])a.status==="rejected"&&i(a.reason);return t().catch(i)})};var ei;const Wl=Object.freeze({status:"aborted"});function g(e,t,o){function n(a,u){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:u,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,u);const l=s.prototype,d=Object.keys(l);for(let h=0;h<d.length;h++){const m=d[h];m in a||(a[m]=l[m].bind(a))}}const r=o?.Parent??Object;class i extends r{}Object.defineProperty(i,"name",{value:e});function s(a){var u;const l=o?.Parent?new i:this;n(l,a),(u=l._zod).deferred??(u.deferred=[]);for(const d of l._zod.deferred)d();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>o?.Parent&&a instanceof o.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class Kt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class oa extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(ei=globalThis).__zod_globalConfig??(ei.__zod_globalConfig={});const Gr=globalThis.__zod_globalConfig;function it(e){return Gr}function na(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,r])=>t.indexOf(+n)===-1).map(([n,r])=>r)}function xr(e,t){return typeof t=="bigint"?t.toString():t}function sr(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Kr(e){return e==null}function Yr(e){const t=e.startsWith("^")?1:0,o=e.endsWith("$")?e.length-1:e.length;return e.slice(t,o)}function Gl(e,t){const o=e/t,n=Math.round(o),r=Number.EPSILON*Math.max(Math.abs(o),1);return Math.abs(o-n)<r?0:o-n}const ti=Symbol("evaluating");function B(e,t,o){let n;Object.defineProperty(e,t,{get(){if(n!==ti)return n===void 0&&(n=ti,n=o()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function zt(e,t,o){Object.defineProperty(e,t,{value:o,writable:!0,enumerable:!0,configurable:!0})}function _t(...e){const t={};for(const o of e){const n=Object.getOwnPropertyDescriptors(o);Object.assign(t,n)}return Object.defineProperties({},t)}function oi(e){return JSON.stringify(e)}function Kl(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ra="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function an(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Yl=sr(()=>{if(Gr.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function po(e){if(an(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const o=t.prototype;return!(an(o)===!1||Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)}function sa(e){return po(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Xl=new Set(["string","number","symbol"]);function ho(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gt(e,t,o){const n=new e._zod.constr(t??e._zod.def);return(!t||o?.parent)&&(n._zod.parent=e),n}function N(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Ql(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const ed={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function td(e,t){const o=e._zod.def,n=o.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=_t(e._zod.def,{get shape(){const s={};for(const a in t){if(!(a in o.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=o.shape[a])}return zt(this,"shape",s),s},checks:[]});return gt(e,i)}function od(e,t){const o=e._zod.def,n=o.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=_t(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const a in t){if(!(a in o.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return zt(this,"shape",s),s},checks:[]});return gt(e,i)}function nd(e,t){if(!po(t))throw new Error("Invalid input to extend: expected a plain object");const o=e._zod.def.checks;if(o&&o.length>0){const i=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=_t(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return zt(this,"shape",i),i}});return gt(e,r)}function rd(e,t){if(!po(t))throw new Error("Invalid input to safeExtend: expected a plain object");const o=_t(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return zt(this,"shape",n),n}});return gt(e,o)}function sd(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const o=_t(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return zt(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return gt(e,o)}function id(e,t,o){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=_t(t._zod.def,{get shape(){const a=t._zod.def.shape,u={...a};if(o)for(const l in o){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);o[l]&&(u[l]=e?new e({type:"optional",innerType:a[l]}):a[l])}else for(const l in a)u[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return zt(this,"shape",u),u},checks:[]});return gt(t,s)}function ad(e,t,o){const n=_t(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(o)for(const s in o){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);o[s]&&(i[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)i[s]=new e({type:"nonoptional",innerType:r[s]});return zt(this,"shape",i),i}});return gt(t,n)}function Wt(e,t=0){if(e.aborted===!0)return!0;for(let o=t;o<e.issues.length;o++)if(e.issues[o]?.continue!==!0)return!0;return!1}function cd(e,t=0){if(e.aborted===!0)return!0;for(let o=t;o<e.issues.length;o++)if(e.issues[o]?.continue===!1)return!0;return!1}function pt(e,t){return t.map(o=>{var n;return(n=o).path??(n.path=[]),o.path.unshift(e),o})}function xn(e){return typeof e=="string"?e:e?.message}function at(e,t,o){const n=e.message?e.message:xn(e.inst?._zod.def?.error?.(e))??xn(t?.error?.(e))??xn(o.customError?.(e))??xn(o.localeError?.(e))??"Invalid input",{inst:r,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=n,t?.reportInput&&(a.input=s),a}function Xr(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function cn(...e){const[t,o,n]=e;return typeof t=="string"?{message:t,code:"custom",input:o,inst:n}:{...t}}const ia=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,xr,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},aa=g("$ZodError",ia),ca=g("$ZodError",ia,{Parent:Error});function ud(e,t=o=>o.message){const o={},n=[];for(const r of e.issues)r.path.length>0?(o[r.path[0]]=o[r.path[0]]||[],o[r.path[0]].push(t(r))):n.push(t(r));return{formErrors:n,fieldErrors:o}}function ld(e,t=o=>o.message){const o={_errors:[]},n=(r,i=[])=>{for(const s of r.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{const a=[...i,...s.path];if(a.length===0)o._errors.push(t(s));else{let u=o,l=0;for(;l<a.length;){const d=a[l];l===a.length-1?(u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(s))):u[d]=u[d]||{_errors:[]},u=u[d],l++}}}};return n(e),o}const Qr=e=>(t,o,n,r)=>{const i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:o,issues:[]},i);if(s instanceof Promise)throw new Kt;if(s.issues.length){const a=new(r?.Err??e)(s.issues.map(u=>at(u,i,it())));throw ra(a,r?.callee),a}return s.value},es=e=>async(t,o,n,r)=>{const i=n?{...n,async:!0}:{async:!0};let s=t._zod.run({value:o,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const a=new(r?.Err??e)(s.issues.map(u=>at(u,i,it())));throw ra(a,r?.callee),a}return s.value},ir=e=>(t,o,n)=>{const r=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:o,issues:[]},r);if(i instanceof Promise)throw new Kt;return i.issues.length?{success:!1,error:new(e??aa)(i.issues.map(s=>at(s,r,it())))}:{success:!0,data:i.value}},dd=ir(ca),ar=e=>async(t,o,n)=>{const r=n?{...n,async:!0}:{async:!0};let i=t._zod.run({value:o,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>at(s,r,it())))}:{success:!0,data:i.value}},pd=ar(ca),hd=e=>(t,o,n)=>{const r=n?{...n,direction:"backward"}:{direction:"backward"};return Qr(e)(t,o,r)},md=e=>(t,o,n)=>Qr(e)(t,o,n),fd=e=>async(t,o,n)=>{const r=n?{...n,direction:"backward"}:{direction:"backward"};return es(e)(t,o,r)},Sd=e=>async(t,o,n)=>es(e)(t,o,n),_d=e=>(t,o,n)=>{const r=n?{...n,direction:"backward"}:{direction:"backward"};return ir(e)(t,o,r)},gd=e=>(t,o,n)=>ir(e)(t,o,n),vd=e=>async(t,o,n)=>{const r=n?{...n,direction:"backward"}:{direction:"backward"};return ar(e)(t,o,r)},yd=e=>async(t,o,n)=>ar(e)(t,o,n),bd=/^[cC][0-9a-z]{6,}$/,Rd=/^[0-9a-z]+$/,wd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Td=/^[0-9a-vA-V]{20}$/,$d=/^[A-Za-z0-9]{27}$/,kd=/^[a-zA-Z0-9_-]{21}$/,Pd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ed=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ni=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Cd=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Id="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function qd(){return new RegExp(Id,"u")}const Od=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Nd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Md=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,zd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ua=/^[A-Za-z0-9_-]*$/,Ad=/^https?$/,Ld=/^\+[1-9]\d{6,14}$/,la="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",jd=new RegExp(`^${la}$`);function da(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ud(e){return new RegExp(`^${da(e)}$`)}function Dd(e){const t=da({precision:e.precision}),o=["Z"];e.local&&o.push(""),e.offset&&o.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${o.join("|")})`;return new RegExp(`^${la}T(?:${n})$`)}const Zd=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Vd=/^-?\d+$/,pa=/^-?\d+(?:\.\d+)?$/,Fd=/^(?:true|false)$/i,Hd=/^null$/i,Jd=/^[^A-Z]*$/,Bd=/^[^a-z]*$/,ke=g("$ZodCheck",(e,t)=>{var o;e._zod??(e._zod={}),e._zod.def=t,(o=e._zod).onattach??(o.onattach=[])}),ha={number:"number",bigint:"bigint",object:"date"},ma=g("$ZodCheckLessThan",(e,t)=>{ke.init(e,t);const o=ha[typeof t.value];e._zod.onattach.push(n=>{const r=n._zod.bag,i=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:o,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),fa=g("$ZodCheckGreaterThan",(e,t)=>{ke.init(e,t);const o=ha[typeof t.value];e._zod.onattach.push(n=>{const r=n._zod.bag,i=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:o,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Wd=g("$ZodCheckMultipleOf",(e,t)=>{ke.init(e,t),e._zod.onattach.push(o=>{var n;(n=o._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=o=>{if(typeof o.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof o.value=="bigint"?o.value%t.value===BigInt(0):Gl(o.value,t.value)===0)||o.issues.push({origin:typeof o.value,code:"not_multiple_of",divisor:t.value,input:o.value,inst:e,continue:!t.abort})}}),Gd=g("$ZodCheckNumberFormat",(e,t)=>{ke.init(e,t),t.format=t.format||"float64";const o=t.format?.includes("int"),n=o?"int":"number",[r,i]=ed[t.format];e._zod.onattach.push(s=>{const a=s._zod.bag;a.format=t.format,a.minimum=r,a.maximum=i,o&&(a.pattern=Vd)}),e._zod.check=s=>{const a=s.value;if(o){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<r&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Kd=g("$ZodCheckMaxLength",(e,t)=>{var o;ke.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!Kr(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const s=Xr(r);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Yd=g("$ZodCheckMinLength",(e,t)=>{var o;ke.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!Kr(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const s=Xr(r);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Xd=g("$ZodCheckLengthEquals",(e,t)=>{var o;ke.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!Kr(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=n=>{const r=n.value,i=r.length;if(i===t.length)return;const s=Xr(r),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),cr=g("$ZodCheckStringFormat",(e,t)=>{var o,n;ke.init(e,t),e._zod.onattach.push(r=>{const i=r._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(o=e._zod).check??(o.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Qd=g("$ZodCheckRegex",(e,t)=>{cr.init(e,t),e._zod.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:"regex",input:o.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),ep=g("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Jd),cr.init(e,t)}),tp=g("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Bd),cr.init(e,t)}),op=g("$ZodCheckIncludes",(e,t)=>{ke.init(e,t);const o=ho(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${o}`:o);t.pattern=n,e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),np=g("$ZodCheckStartsWith",(e,t)=>{ke.init(e,t);const o=new RegExp(`^${ho(t.prefix)}.*`);t.pattern??(t.pattern=o),e._zod.onattach.push(n=>{const r=n._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(o)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),rp=g("$ZodCheckEndsWith",(e,t)=>{ke.init(e,t);const o=new RegExp(`.*${ho(t.suffix)}$`);t.pattern??(t.pattern=o),e._zod.onattach.push(n=>{const r=n._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(o)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),sp=g("$ZodCheckOverwrite",(e,t)=>{ke.init(e,t),e._zod.check=o=>{o.value=t.tx(o.value)}});class ip{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const n=t.split(`
2
- `).filter(s=>s),r=Math.min(...n.map(s=>s.length-s.trimStart().length)),i=n.map(s=>s.slice(r)).map(s=>" ".repeat(this.indent*2)+s);for(const s of i)this.content.push(s)}compile(){const t=Function,o=this?.args,r=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...o,r.join(`
3
- `))}}const ap={major:4,minor:4,patch:3},K=g("$ZodType",(e,t)=>{var o;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ap;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const r of n)for(const i of r._zod.onattach)i(e);if(n.length===0)(o=e._zod).deferred??(o.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const r=(s,a,u)=>{let l=Wt(s),d;for(const h of a){if(h._zod.def.when){if(cd(s)||!h._zod.def.when(s))continue}else if(l)continue;const m=s.issues.length,f=h._zod.check(s);if(f instanceof Promise&&u?.async===!1)throw new Kt;if(d||f instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await f,s.issues.length!==m&&(l||(l=Wt(s,m)))});else{if(s.issues.length===m)continue;l||(l=Wt(s,m))}}return d?d.then(()=>s):s},i=(s,a,u)=>{if(Wt(s))return s.aborted=!0,s;const l=r(a,n,u);if(l instanceof Promise){if(u.async===!1)throw new Kt;return l.then(d=>e._zod.parse(d,u))}return e._zod.parse(l,u)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){const l=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return l instanceof Promise?l.then(d=>i(d,s,a)):i(l,s,a)}const u=e._zod.parse(s,a);if(u instanceof Promise){if(a.async===!1)throw new Kt;return u.then(l=>r(l,n,a))}return r(u,n,a)}}B(e,"~standard",()=>({validate:r=>{try{const i=dd(e,r);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return pd(e,r).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),ts=g("$ZodString",(e,t)=>{K.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Zd(e._zod.bag),e._zod.parse=(o,n)=>{if(t.coerce)try{o.value=String(o.value)}catch{}return typeof o.value=="string"||o.issues.push({expected:"string",code:"invalid_type",input:o.value,inst:e}),o}}),ee=g("$ZodStringFormat",(e,t)=>{cr.init(e,t),ts.init(e,t)}),cp=g("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Ed),ee.init(e,t)}),up=g("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ni(n))}else t.pattern??(t.pattern=ni());ee.init(e,t)}),lp=g("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Cd),ee.init(e,t)}),dp=g("$ZodURL",(e,t)=>{ee.init(e,t),e._zod.check=o=>{try{const n=o.value.trim();if(!t.normalize&&t.protocol?.source===Ad.source&&!/^https?:\/\//i.test(n)){o.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:o.value,inst:e,continue:!t.abort});return}const r=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.hostname)||o.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:o.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||o.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:o.value,inst:e,continue:!t.abort})),t.normalize?o.value=r.href:o.value=n;return}catch{o.issues.push({code:"invalid_format",format:"url",input:o.value,inst:e,continue:!t.abort})}}}),pp=g("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=qd()),ee.init(e,t)}),hp=g("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=kd),ee.init(e,t)}),mp=g("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=bd),ee.init(e,t)}),fp=g("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Rd),ee.init(e,t)}),Sp=g("$ZodULID",(e,t)=>{t.pattern??(t.pattern=wd),ee.init(e,t)}),_p=g("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Td),ee.init(e,t)}),gp=g("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=$d),ee.init(e,t)}),vp=g("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Dd(t)),ee.init(e,t)}),yp=g("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=jd),ee.init(e,t)}),bp=g("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Ud(t)),ee.init(e,t)}),Rp=g("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Pd),ee.init(e,t)}),wp=g("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Od),ee.init(e,t),e._zod.bag.format="ipv4"}),Tp=g("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Nd),ee.init(e,t),e._zod.bag.format="ipv6",e._zod.check=o=>{try{new URL(`http://[${o.value}]`)}catch{o.issues.push({code:"invalid_format",format:"ipv6",input:o.value,inst:e,continue:!t.abort})}}}),$p=g("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Md),ee.init(e,t)}),kp=g("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=zd),ee.init(e,t),e._zod.check=o=>{const n=o.value.split("/");try{if(n.length!==2)throw new Error;const[r,i]=n;if(!i)throw new Error;const s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{o.issues.push({code:"invalid_format",format:"cidrv6",input:o.value,inst:e,continue:!t.abort})}}});function Sa(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Pp=g("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=xd),ee.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=o=>{Sa(o.value)||o.issues.push({code:"invalid_format",format:"base64",input:o.value,inst:e,continue:!t.abort})}});function Ep(e){if(!ua.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),o=t.padEnd(Math.ceil(t.length/4)*4,"=");return Sa(o)}const Cp=g("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ua),ee.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=o=>{Ep(o.value)||o.issues.push({code:"invalid_format",format:"base64url",input:o.value,inst:e,continue:!t.abort})}}),Ip=g("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Ld),ee.init(e,t)});function qp(e,t=null){try{const o=e.split(".");if(o.length!==3)return!1;const[n]=o;if(!n)return!1;const r=JSON.parse(atob(n));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const Op=g("$ZodJWT",(e,t)=>{ee.init(e,t),e._zod.check=o=>{qp(o.value,t.alg)||o.issues.push({code:"invalid_format",format:"jwt",input:o.value,inst:e,continue:!t.abort})}}),_a=g("$ZodNumber",(e,t)=>{K.init(e,t),e._zod.pattern=e._zod.bag.pattern??pa,e._zod.parse=(o,n)=>{if(t.coerce)try{o.value=Number(o.value)}catch{}const r=o.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return o;const i=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return o.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...i?{received:i}:{}}),o}}),Np=g("$ZodNumberFormat",(e,t)=>{Gd.init(e,t),_a.init(e,t)}),Mp=g("$ZodBoolean",(e,t)=>{K.init(e,t),e._zod.pattern=Fd,e._zod.parse=(o,n)=>{if(t.coerce)try{o.value=!!o.value}catch{}const r=o.value;return typeof r=="boolean"||o.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),o}}),zp=g("$ZodNull",(e,t)=>{K.init(e,t),e._zod.pattern=Hd,e._zod.values=new Set([null]),e._zod.parse=(o,n)=>{const r=o.value;return r===null||o.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),o}}),xp=g("$ZodAny",(e,t)=>{K.init(e,t),e._zod.parse=o=>o}),Ap=g("$ZodUnknown",(e,t)=>{K.init(e,t),e._zod.parse=o=>o}),Lp=g("$ZodNever",(e,t)=>{K.init(e,t),e._zod.parse=(o,n)=>(o.issues.push({expected:"never",code:"invalid_type",input:o.value,inst:e}),o)});function ri(e,t,o){e.issues.length&&t.issues.push(...pt(o,e.issues)),t.value[o]=e.value}const jp=g("$ZodArray",(e,t)=>{K.init(e,t),e._zod.parse=(o,n)=>{const r=o.value;if(!Array.isArray(r))return o.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),o;o.value=Array(r.length);const i=[];for(let s=0;s<r.length;s++){const a=r[s],u=t.element._zod.run({value:a,issues:[]},n);u instanceof Promise?i.push(u.then(l=>ri(l,o,s))):ri(u,o,s)}return i.length?Promise.all(i).then(()=>o):o}});function Gn(e,t,o,n,r,i){const s=o in n;if(e.issues.length){if(r&&i&&!s)return;t.issues.push(...pt(o,e.issues))}if(!s&&!r){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[o]});return}e.value===void 0?s&&(t.value[o]=void 0):t.value[o]=e.value}function ga(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const o=Ql(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function va(e,t,o,n,r,i){const s=[],a=r.keySet,u=r.catchall._zod,l=u.def.type,d=u.optin==="optional",h=u.optout==="optional";for(const m in t){if(m==="__proto__"||a.has(m))continue;if(l==="never"){s.push(m);continue}const f=u.run({value:t[m],issues:[]},n);f instanceof Promise?e.push(f.then(v=>Gn(v,o,m,t,d,h))):Gn(f,o,m,t,d,h)}return s.length&&o.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>o):o}const Up=g("$ZodObject",(e,t)=>{if(K.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const a=t.shape;Object.defineProperty(t,"shape",{get:()=>{const u={...a};return Object.defineProperty(t,"shape",{value:u}),u}})}const n=sr(()=>ga(t));B(e._zod,"propValues",()=>{const a=t.shape,u={};for(const l in a){const d=a[l]._zod;if(d.values){u[l]??(u[l]=new Set);for(const h of d.values)u[l].add(h)}}return u});const r=an,i=t.catchall;let s;e._zod.parse=(a,u)=>{s??(s=n.value);const l=a.value;if(!r(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),a;a.value={};const d=[],h=s.shape;for(const m of s.keys){const f=h[m],v=f._zod.optin==="optional",R=f._zod.optout==="optional",y=f._zod.run({value:l[m],issues:[]},u);y instanceof Promise?d.push(y.then(Z=>Gn(Z,a,m,l,v,R))):Gn(y,a,m,l,v,R)}return i?va(d,l,a,u,n.value,e):d.length?Promise.all(d).then(()=>a):a}}),Dp=g("$ZodObjectJIT",(e,t)=>{Up.init(e,t);const o=e._zod.parse,n=sr(()=>ga(t)),r=m=>{const f=new ip(["shape","payload","ctx"]),v=n.value,R=I=>{const L=oi(I);return`shape[${L}]._zod.run({ value: input[${L}], issues: [] }, ctx)`};f.write("const input = payload.value;");const y=Object.create(null);let Z=0;for(const I of v.keys)y[I]=`key_${Z++}`;f.write("const newResult = {};");for(const I of v.keys){const L=y[I],W=oi(I),J=m[I],te=J?._zod?.optin==="optional",ae=J?._zod?.optout==="optional";f.write(`const ${L} = ${R(I)};`),te&&ae?f.write(`
4
- if (${L}.issues.length) {
5
- if (${W} in input) {
6
- payload.issues = payload.issues.concat(${L}.issues.map(iss => ({
7
- ...iss,
8
- path: iss.path ? [${W}, ...iss.path] : [${W}]
9
- })));
10
- }
11
- }
12
-
13
- if (${L}.value === undefined) {
14
- if (${W} in input) {
15
- newResult[${W}] = undefined;
16
- }
17
- } else {
18
- newResult[${W}] = ${L}.value;
19
- }
20
-
21
- `):te?f.write(`
22
- if (${L}.issues.length) {
23
- payload.issues = payload.issues.concat(${L}.issues.map(iss => ({
24
- ...iss,
25
- path: iss.path ? [${W}, ...iss.path] : [${W}]
26
- })));
27
- }
28
-
29
- if (${L}.value === undefined) {
30
- if (${W} in input) {
31
- newResult[${W}] = undefined;
32
- }
33
- } else {
34
- newResult[${W}] = ${L}.value;
35
- }
36
-
37
- `):f.write(`
38
- const ${L}_present = ${W} in input;
39
- if (${L}.issues.length) {
40
- payload.issues = payload.issues.concat(${L}.issues.map(iss => ({
41
- ...iss,
42
- path: iss.path ? [${W}, ...iss.path] : [${W}]
43
- })));
44
- }
45
- if (!${L}_present && !${L}.issues.length) {
46
- payload.issues.push({
47
- code: "invalid_type",
48
- expected: "nonoptional",
49
- input: undefined,
50
- path: [${W}]
51
- });
52
- }
53
-
54
- if (${L}_present) {
55
- if (${L}.value === undefined) {
56
- newResult[${W}] = undefined;
57
- } else {
58
- newResult[${W}] = ${L}.value;
59
- }
60
- }
61
-
62
- `)}f.write("payload.value = newResult;"),f.write("return payload;");const V=f.compile();return(I,L)=>V(m,I,L)};let i;const s=an,a=!Gr.jitless,l=a&&Yl.value,d=t.catchall;let h;e._zod.parse=(m,f)=>{h??(h=n.value);const v=m.value;return s(v)?a&&l&&f?.async===!1&&f.jitless!==!0?(i||(i=r(t.shape)),m=i(m,f),d?va([],v,m,f,h,e):m):o(m,f):(m.issues.push({expected:"object",code:"invalid_type",input:v,inst:e}),m)}});function si(e,t,o,n){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const r=e.filter(i=>!Wt(i));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:o,errors:e.map(i=>i.issues.map(s=>at(s,n,it())))}),t)}const ya=g("$ZodUnion",(e,t)=>{K.init(e,t),B(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),B(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),B(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),B(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>Yr(r.source)).join("|")})$`)}});const o=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,r)=>{if(o)return o(n,r);let i=!1;const s=[];for(const a of t.options){const u=a._zod.run({value:n.value,issues:[]},r);if(u instanceof Promise)s.push(u),i=!0;else{if(u.issues.length===0)return u;s.push(u)}}return i?Promise.all(s).then(a=>si(a,n,e,r)):si(s,n,e,r)}}),Zp=g("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,ya.init(e,t);const o=e._zod.parse;B(e._zod,"propValues",()=>{const r={};for(const i of t.options){const s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const[a,u]of Object.entries(s)){r[a]||(r[a]=new Set);for(const l of u)r[a].add(l)}}return r});const n=sr(()=>{const r=t.options,i=new Map;for(const s of r){const a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const u of a){if(i.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);i.set(u,s)}}return i});e._zod.parse=(r,i)=>{const s=r.value;if(!an(s))return r.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),r;const a=n.value.get(s?.[t.discriminator]);return a?a._zod.run(r,i):t.unionFallback||i.direction==="backward"?o(r,i):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()),input:s,path:[t.discriminator],inst:e}),r)}}),Vp=g("$ZodIntersection",(e,t)=>{K.init(e,t),e._zod.parse=(o,n)=>{const r=o.value,i=t.left._zod.run({value:r,issues:[]},n),s=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([u,l])=>ii(o,u,l)):ii(o,i,s)}});function Ar(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(po(e)&&po(t)){const o=Object.keys(t),n=Object.keys(e).filter(i=>o.indexOf(i)!==-1),r={...e,...t};for(const i of n){const s=Ar(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};r[i]=s.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const o=[];for(let n=0;n<e.length;n++){const r=e[n],i=t[n],s=Ar(r,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};o.push(s.data)}return{valid:!0,data:o}}return{valid:!1,mergeErrorPath:[]}}function ii(e,t,o){const n=new Map;let r;for(const a of t.issues)if(a.code==="unrecognized_keys"){r??(r=a);for(const u of a.keys)n.has(u)||n.set(u,{}),n.get(u).l=!0}else e.issues.push(a);for(const a of o.issues)if(a.code==="unrecognized_keys")for(const u of a.keys)n.has(u)||n.set(u,{}),n.get(u).r=!0;else e.issues.push(a);const i=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&r&&e.issues.push({...r,keys:i}),Wt(e))return e;const s=Ar(t.value,o.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const Fp=g("$ZodTuple",(e,t)=>{K.init(e,t);const o=t.items;e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];const s=[],a=ai(o,"optin"),u=ai(o,"optout");if(!t.rest){if(i.length<a)return n.issues.push({code:"too_small",minimum:a,inclusive:!0,input:i,inst:e,origin:"array"}),n;i.length>o.length&&n.issues.push({code:"too_big",maximum:o.length,inclusive:!0,input:i,inst:e,origin:"array"})}const l=new Array(o.length);for(let d=0;d<o.length;d++){const h=o[d]._zod.run({value:i[d],issues:[]},r);h instanceof Promise?s.push(h.then(m=>{l[d]=m})):l[d]=h}if(t.rest){let d=o.length-1;const h=i.slice(o.length);for(const m of h){d++;const f=t.rest._zod.run({value:m,issues:[]},r);f instanceof Promise?s.push(f.then(v=>ci(v,n,d))):ci(f,n,d)}}return s.length?Promise.all(s).then(()=>ui(l,n,o,i,u)):ui(l,n,o,i,u)}});function ai(e,t){for(let o=e.length-1;o>=0;o--)if(e[o]._zod[t]!=="optional")return o+1;return 0}function ci(e,t,o){e.issues.length&&t.issues.push(...pt(o,e.issues)),t.value[o]=e.value}function ui(e,t,o,n,r){for(let i=0;i<o.length;i++){const s=e[i],a=i<n.length;if(s.issues.length){if(!a&&i>=r){t.value.length=i;break}t.issues.push(...pt(i,s.issues))}t.value[i]=s.value}for(let i=t.value.length-1;i>=n.length&&(o[i]._zod.optout==="optional"&&t.value[i]===void 0);i--)t.value.length=i;return t}const Hp=g("$ZodRecord",(e,t)=>{K.init(e,t),e._zod.parse=(o,n)=>{const r=o.value;if(!po(r))return o.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),o;const i=[],s=t.keyType._zod.values;if(s){o.value={};const a=new Set;for(const l of s)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){a.add(typeof l=="number"?l.toString():l);const d=t.keyType._zod.run({value:l,issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){o.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(f=>at(f,n,it())),input:l,path:[l],inst:e});continue}const h=d.value,m=t.valueType._zod.run({value:r[l],issues:[]},n);m instanceof Promise?i.push(m.then(f=>{f.issues.length&&o.issues.push(...pt(l,f.issues)),o.value[h]=f.value})):(m.issues.length&&o.issues.push(...pt(l,m.issues)),o.value[h]=m.value)}let u;for(const l in r)a.has(l)||(u=u??[],u.push(l));u&&u.length>0&&o.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:u})}else{o.value={};for(const a of Reflect.ownKeys(r)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(r,a))continue;let u=t.keyType._zod.run({value:a,issues:[]},n);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&pa.test(a)&&u.issues.length){const h=t.keyType._zod.run({value:Number(a),issues:[]},n);if(h instanceof Promise)throw new Error("Async schemas not supported in object keys currently");h.issues.length===0&&(u=h)}if(u.issues.length){t.mode==="loose"?o.value[a]=r[a]:o.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(h=>at(h,n,it())),input:a,path:[a],inst:e});continue}const d=t.valueType._zod.run({value:r[a],issues:[]},n);d instanceof Promise?i.push(d.then(h=>{h.issues.length&&o.issues.push(...pt(a,h.issues)),o.value[u.value]=h.value})):(d.issues.length&&o.issues.push(...pt(a,d.issues)),o.value[u.value]=d.value)}}return i.length?Promise.all(i).then(()=>o):o}}),Jp=g("$ZodEnum",(e,t)=>{K.init(e,t);const o=na(t.entries),n=new Set(o);e._zod.values=n,e._zod.pattern=new RegExp(`^(${o.filter(r=>Xl.has(typeof r)).map(r=>typeof r=="string"?ho(r):r.toString()).join("|")})$`),e._zod.parse=(r,i)=>{const s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:o,input:s,inst:e}),r}}),Bp=g("$ZodLiteral",(e,t)=>{if(K.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const o=new Set(t.values);e._zod.values=o,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?ho(n):n?ho(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const i=n.value;return o.has(i)||n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}}),Wp=g("$ZodTransform",(e,t)=>{K.init(e,t),e._zod.optin="optional",e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new oa(e.constructor.name);const r=t.transform(o.value,o);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(s=>(o.value=s,o.fallback=!0,o));if(r instanceof Promise)throw new Kt;return o.value=r,o.fallback=!0,o}});function li(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const ba=g("$ZodOptional",(e,t)=>{K.init(e,t),e._zod.optin="optional",e._zod.optout="optional",B(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),B(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${Yr(o.source)})?$`):void 0}),e._zod.parse=(o,n)=>{if(t.innerType._zod.optin==="optional"){const r=o.value,i=t.innerType._zod.run(o,n);return i instanceof Promise?i.then(s=>li(s,r)):li(i,r)}return o.value===void 0?o:t.innerType._zod.run(o,n)}}),Gp=g("$ZodExactOptional",(e,t)=>{ba.init(e,t),B(e._zod,"values",()=>t.innerType._zod.values),B(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(o,n)=>t.innerType._zod.run(o,n)}),Kp=g("$ZodNullable",(e,t)=>{K.init(e,t),B(e._zod,"optin",()=>t.innerType._zod.optin),B(e._zod,"optout",()=>t.innerType._zod.optout),B(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${Yr(o.source)}|null)$`):void 0}),B(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(o,n)=>o.value===null?o:t.innerType._zod.run(o,n)}),Yp=g("$ZodDefault",(e,t)=>{K.init(e,t),e._zod.optin="optional",B(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);if(o.value===void 0)return o.value=t.defaultValue,o;const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(i=>di(i,t)):di(r,t)}});function di(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Xp=g("$ZodPrefault",(e,t)=>{K.init(e,t),e._zod.optin="optional",B(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>(n.direction==="backward"||o.value===void 0&&(o.value=t.defaultValue),t.innerType._zod.run(o,n))}),Qp=g("$ZodNonOptional",(e,t)=>{K.init(e,t),B(e._zod,"values",()=>{const o=t.innerType._zod.values;return o?new Set([...o].filter(n=>n!==void 0)):void 0}),e._zod.parse=(o,n)=>{const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(i=>pi(i,e)):pi(r,e)}});function pi(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const eh=g("$ZodCatch",(e,t)=>{K.init(e,t),e._zod.optin="optional",B(e._zod,"optout",()=>t.innerType._zod.optout),B(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(i=>(o.value=i.value,i.issues.length&&(o.value=t.catchValue({...o,error:{issues:i.issues.map(s=>at(s,n,it()))},input:o.value}),o.issues=[],o.fallback=!0),o)):(o.value=r.value,r.issues.length&&(o.value=t.catchValue({...o,error:{issues:r.issues.map(i=>at(i,n,it()))},input:o.value}),o.issues=[],o.fallback=!0),o)}}),Ra=g("$ZodPipe",(e,t)=>{K.init(e,t),B(e._zod,"values",()=>t.in._zod.values),B(e._zod,"optin",()=>t.in._zod.optin),B(e._zod,"optout",()=>t.out._zod.optout),B(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(o,n)=>{if(n.direction==="backward"){const i=t.out._zod.run(o,n);return i instanceof Promise?i.then(s=>An(s,t.in,n)):An(i,t.in,n)}const r=t.in._zod.run(o,n);return r instanceof Promise?r.then(i=>An(i,t.out,n)):An(r,t.out,n)}});function An(e,t,o){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},o)}const th=g("$ZodPreprocess",(e,t)=>{Ra.init(e,t)}),oh=g("$ZodReadonly",(e,t)=>{K.init(e,t),B(e._zod,"propValues",()=>t.innerType._zod.propValues),B(e._zod,"values",()=>t.innerType._zod.values),B(e._zod,"optin",()=>t.innerType?._zod?.optin),B(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(hi):hi(r)}});function hi(e){return e.value=Object.freeze(e.value),e}const nh=g("$ZodLazy",(e,t)=>{K.init(e,t),B(e._zod,"innerType",()=>{const o=t;return o._cachedInner||(o._cachedInner=t.getter()),o._cachedInner}),B(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),B(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),B(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),B(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(o,n)=>e._zod.innerType._zod.run(o,n)}),rh=g("$ZodCustom",(e,t)=>{ke.init(e,t),K.init(e,t),e._zod.parse=(o,n)=>o,e._zod.check=o=>{const n=o.value,r=t.fn(n);if(r instanceof Promise)return r.then(i=>mi(i,o,n,e));mi(r,o,n,e)}});function mi(e,t,o,n){if(!e){const r={code:"custom",input:o,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(r.params=n._zod.def.params),t.issues.push(cn(r))}}var fi;class sh{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...o){const n=o[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const o=this._map.get(t);return o&&typeof o=="object"&&"id"in o&&this._idmap.delete(o.id),this._map.delete(t),this}get(t){const o=t._zod.parent;if(o){const n={...this.get(o)??{}};delete n.id;const r={...n,...this._map.get(t)};return Object.keys(r).length?r:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function ih(){return new sh}(fi=globalThis).__zod_globalRegistry??(fi.__zod_globalRegistry=ih());const en=globalThis.__zod_globalRegistry;function ah(e,t){return new e({type:"string",...N(t)})}function wa(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...N(t)})}function Si(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...N(t)})}function ch(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...N(t)})}function uh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...N(t)})}function lh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...N(t)})}function dh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...N(t)})}function Ta(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...N(t)})}function ph(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...N(t)})}function hh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...N(t)})}function mh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...N(t)})}function fh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...N(t)})}function Sh(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...N(t)})}function _h(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...N(t)})}function gh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...N(t)})}function vh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...N(t)})}function yh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...N(t)})}function bh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...N(t)})}function Rh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...N(t)})}function wh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...N(t)})}function Th(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...N(t)})}function $h(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...N(t)})}function kh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...N(t)})}function Ph(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...N(t)})}function Eh(e,t){return new e({type:"string",format:"date",check:"string_format",...N(t)})}function Ch(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...N(t)})}function Ih(e,t){return new e({type:"string",format:"duration",check:"string_format",...N(t)})}function qh(e,t){return new e({type:"number",checks:[],...N(t)})}function Oh(e,t){return new e({type:"number",coerce:!0,checks:[],...N(t)})}function Nh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...N(t)})}function Mh(e,t){return new e({type:"boolean",...N(t)})}function zh(e,t){return new e({type:"null",...N(t)})}function xh(e){return new e({type:"any"})}function Ah(e){return new e({type:"unknown"})}function Lh(e,t){return new e({type:"never",...N(t)})}function _i(e,t){return new ma({check:"less_than",...N(t),value:e,inclusive:!1})}function Tr(e,t){return new ma({check:"less_than",...N(t),value:e,inclusive:!0})}function gi(e,t){return new fa({check:"greater_than",...N(t),value:e,inclusive:!1})}function $r(e,t){return new fa({check:"greater_than",...N(t),value:e,inclusive:!0})}function vi(e,t){return new Wd({check:"multiple_of",...N(t),value:e})}function $a(e,t){return new Kd({check:"max_length",...N(t),maximum:e})}function Kn(e,t){return new Yd({check:"min_length",...N(t),minimum:e})}function ka(e,t){return new Xd({check:"length_equals",...N(t),length:e})}function jh(e,t){return new Qd({check:"string_format",format:"regex",...N(t),pattern:e})}function Uh(e){return new ep({check:"string_format",format:"lowercase",...N(e)})}function Dh(e){return new tp({check:"string_format",format:"uppercase",...N(e)})}function Zh(e,t){return new op({check:"string_format",format:"includes",...N(t),includes:e})}function Vh(e,t){return new np({check:"string_format",format:"starts_with",...N(t),prefix:e})}function Fh(e,t){return new rp({check:"string_format",format:"ends_with",...N(t),suffix:e})}function _o(e){return new sp({check:"overwrite",tx:e})}function Hh(e){return _o(t=>t.normalize(e))}function Jh(){return _o(e=>e.trim())}function Bh(){return _o(e=>e.toLowerCase())}function Wh(){return _o(e=>e.toUpperCase())}function Gh(){return _o(e=>Kl(e))}function Kh(e,t,o){return new e({type:"array",element:t,...N(o)})}function Yh(e,t,o){const n=N(o);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Xh(e,t,o){return new e({type:"custom",check:"custom",fn:t,...N(o)})}function Qh(e,t){const o=em(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(cn(r,n.value,o._zod.def));else{const i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=o),i.continue??(i.continue=!o._zod.def.abort),n.issues.push(cn(i))}},e(n.value,n)),t);return o}function em(e,t){const o=new ke({check:"custom",...N(t)});return o._zod.check=e,o}function Yn(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??en,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Q(e,t,o={path:[],schemaPath:[]}){var n;const r=e._zod.def,i=t.seen.get(e);if(i)return i.count++,o.schemaPath.includes(e)&&(i.cycle=o.path),i.schema;const s={schema:{},count:1,cycle:void 0,path:o.path};t.seen.set(e,s);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const d={...o,schemaPath:[...o.schemaPath,e],path:o.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,d);else{const m=s.schema,f=t.processors[r.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);f(e,t,m,d)}const h=e._zod.parent;h&&(s.ref||(s.ref=h),Q(h,t,d),t.seen.get(h).isParent=!0)}const u=t.metadataRegistry.get(e);return u&&Object.assign(s.schema,u),t.io==="input"&&be(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((n=s.schema).default??(n.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function Xn(e,t){const o=e.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const s of e.seen.entries()){const a=e.metadataRegistry.get(s[0])?.id;if(a){const u=n.get(a);if(u&&u!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,s[0])}}const r=s=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const h=e.external.registry.get(s[0])?.id,m=e.external.uri??(v=>v);if(h)return{ref:m(h)};const f=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=f,{defId:f,ref:`${m("__shared")}#/${a}/${f}`}}if(s[1]===o)return{ref:"#"};const l=`#/${a}/`,d=s[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:l+d}},i=s=>{if(s[1].schema.$ref)return;const a=s[1],{ref:u,defId:l}=r(s);a.def={...a.schema},l&&(a.defId=l);const d=a.schema;for(const h in d)delete d[h];d.$ref=u};if(e.cycles==="throw")for(const s of e.seen.entries()){const a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
63
-
64
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const a=s[1];if(t===s[0]){i(s);continue}if(e.external){const l=e.external.registry.get(s[0])?.id;if(t!==s[0]&&l){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1&&e.reused==="ref"){i(s);continue}}}function Qn(e,t){const o=e.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=a=>{const u=e.seen.get(a);if(u.ref===null)return;const l=u.def??u.schema,d={...l},h=u.ref;if(u.ref=null,h){n(h);const f=e.seen.get(h),v=f.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(v)):Object.assign(l,v),Object.assign(l,d),a._zod.parent===h)for(const y in l)y==="$ref"||y==="allOf"||y in d||delete l[y];if(v.$ref&&f.def)for(const y in l)y==="$ref"||y==="allOf"||y in f.def&&JSON.stringify(l[y])===JSON.stringify(f.def[y])&&delete l[y]}const m=a._zod.parent;if(m&&m!==h){n(m);const f=e.seen.get(m);if(f?.schema.$ref&&(l.$ref=f.schema.$ref,f.def))for(const v in l)v==="$ref"||v==="allOf"||v in f.def&&JSON.stringify(l[v])===JSON.stringify(f.def[v])&&delete l[v]}e.override({zodSchema:a,jsonSchema:l,path:u.path??[]})};for(const a of[...e.seen.entries()].reverse())n(a[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(a)}Object.assign(r,o.def??o.schema);const i=e.metadataRegistry.get(t)?.id;i!==void 0&&r.id===i&&delete r.id;const s=e.external?.defs??{};for(const a of e.seen.entries()){const u=a[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,s[u.defId]=u.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?r.$defs=s:r.definitions=s);try{const a=JSON.parse(JSON.stringify(r));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:er(t,"input",e.processors),output:er(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function be(e,t){const o=t??{seen:new Set};if(o.seen.has(e))return!1;o.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return be(n.element,o);if(n.type==="set")return be(n.valueType,o);if(n.type==="lazy")return be(n.getter(),o);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return be(n.innerType,o);if(n.type==="intersection")return be(n.left,o)||be(n.right,o);if(n.type==="record"||n.type==="map")return be(n.keyType,o)||be(n.valueType,o);if(n.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:be(n.in,o)||be(n.out,o);if(n.type==="object"){for(const r in n.shape)if(be(n.shape[r],o))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(be(r,o))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(be(r,o))return!0;return!!(n.rest&&be(n.rest,o))}return!1}const tm=(e,t={})=>o=>{const n=Yn({...o,processors:t});return Q(e,n),Xn(n,e),Qn(n,e)},er=(e,t,o={})=>n=>{const{libraryOptions:r,target:i}=n??{},s=Yn({...r??{},target:i,io:t,processors:o});return Q(e,s),Xn(s,e),Qn(s,e)},om={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Pa=(e,t,o,n)=>{const r=o;r.type="string";const{minimum:i,maximum:s,format:a,patterns:u,contentEncoding:l}=e._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof s=="number"&&(r.maxLength=s),a&&(r.format=om[a]??a,r.format===""&&delete r.format,a==="time"&&delete r.format),l&&(r.contentEncoding=l),u&&u.size>0){const d=[...u];d.length===1?r.pattern=d[0].source:d.length>1&&(r.allOf=[...d.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},Ea=(e,t,o,n)=>{const r=o,{minimum:i,maximum:s,format:a,multipleOf:u,exclusiveMaximum:l,exclusiveMinimum:d}=e._zod.bag;typeof a=="string"&&a.includes("int")?r.type="integer":r.type="number";const h=typeof d=="number"&&d>=(i??Number.NEGATIVE_INFINITY),m=typeof l=="number"&&l<=(s??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";h?f?(r.minimum=d,r.exclusiveMinimum=!0):r.exclusiveMinimum=d:typeof i=="number"&&(r.minimum=i),m?f?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l:typeof s=="number"&&(r.maximum=s),typeof u=="number"&&(r.multipleOf=u)},Ca=(e,t,o,n)=>{o.type="boolean"},nm=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},rm=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Ia=(e,t,o,n)=>{t.target==="openapi-3.0"?(o.type="string",o.nullable=!0,o.enum=[null]):o.type="null"},sm=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},im=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},qa=(e,t,o,n)=>{o.not={}},Oa=(e,t,o,n)=>{},Na=(e,t,o,n)=>{},am=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Ma=(e,t,o,n)=>{const r=e._zod.def,i=na(r.entries);i.every(s=>typeof s=="number")&&(o.type="number"),i.every(s=>typeof s=="string")&&(o.type="string"),o.enum=i},za=(e,t,o,n)=>{const r=e._zod.def,i=[];for(const s of r.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){const s=i[0];o.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?o.enum=[s]:o.const=s}else i.every(s=>typeof s=="number")&&(o.type="number"),i.every(s=>typeof s=="string")&&(o.type="string"),i.every(s=>typeof s=="boolean")&&(o.type="boolean"),i.every(s=>s===null)&&(o.type="null"),o.enum=i},cm=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},um=(e,t,o,n)=>{const r=o,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=i.source},lm=(e,t,o,n)=>{const r=o,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:u}=e._zod.bag;s!==void 0&&(i.minLength=s),a!==void 0&&(i.maxLength=a),u?u.length===1?(i.contentMediaType=u[0],Object.assign(r,i)):(Object.assign(r,i),r.anyOf=u.map(l=>({contentMediaType:l}))):Object.assign(r,i)},dm=(e,t,o,n)=>{o.type="boolean"},xa=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},pm=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Aa=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},hm=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},mm=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},La=(e,t,o,n)=>{const r=o,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;typeof s=="number"&&(r.minItems=s),typeof a=="number"&&(r.maxItems=a),r.type="array",r.items=Q(i.element,t,{...n,path:[...n.path,"items"]})},ja=(e,t,o,n)=>{const r=o,i=e._zod.def;r.type="object",r.properties={};const s=i.shape;for(const l in s)r.properties[l]=Q(s[l],t,{...n,path:[...n.path,"properties",l]});const a=new Set(Object.keys(s)),u=new Set([...a].filter(l=>{const d=i.shape[l]._zod;return t.io==="input"?d.optin===void 0:d.optout===void 0}));u.size>0&&(r.required=Array.from(u)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=Q(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},Ua=(e,t,o,n)=>{const r=e._zod.def,i=r.inclusive===!1,s=r.options.map((a,u)=>Q(a,t,{...n,path:[...n.path,i?"oneOf":"anyOf",u]}));i?o.oneOf=s:o.anyOf=s},Da=(e,t,o,n)=>{const r=e._zod.def,i=Q(r.left,t,{...n,path:[...n.path,"allOf",0]}),s=Q(r.right,t,{...n,path:[...n.path,"allOf",1]}),a=l=>"allOf"in l&&Object.keys(l).length===1,u=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];o.allOf=u},Za=(e,t,o,n)=>{const r=o,i=e._zod.def;r.type="array";const s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=i.items.map((m,f)=>Q(m,t,{...n,path:[...n.path,s,f]})),l=i.rest?Q(i.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;t.target==="draft-2020-12"?(r.prefixItems=u,l&&(r.items=l)):t.target==="openapi-3.0"?(r.items={anyOf:u},l&&r.items.anyOf.push(l),r.minItems=u.length,l||(r.maxItems=u.length)):(r.items=u,l&&(r.additionalItems=l));const{minimum:d,maximum:h}=e._zod.bag;typeof d=="number"&&(r.minItems=d),typeof h=="number"&&(r.maxItems=h)},Va=(e,t,o,n)=>{const r=o,i=e._zod.def;r.type="object";const s=i.keyType,u=s._zod.bag?.patterns;if(i.mode==="loose"&&u&&u.size>0){const d=Q(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});r.patternProperties={};for(const h of u)r.patternProperties[h.source]=d}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=Q(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=Q(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const l=s._zod.values;if(l){const d=[...l].filter(h=>typeof h=="string"||typeof h=="number");d.length>0&&(r.required=d)}},Fa=(e,t,o,n)=>{const r=e._zod.def,i=Q(r.innerType,t,n),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=r.innerType,o.nullable=!0):o.anyOf=[i,{type:"null"}]},Ha=(e,t,o,n)=>{const r=e._zod.def;Q(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Ja=(e,t,o,n)=>{const r=e._zod.def;Q(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,o.default=JSON.parse(JSON.stringify(r.defaultValue))},Ba=(e,t,o,n)=>{const r=e._zod.def;Q(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,t.io==="input"&&(o._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},Wa=(e,t,o,n)=>{const r=e._zod.def;Q(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType;let s;try{s=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}o.default=s},Ga=(e,t,o,n)=>{const r=e._zod.def,i=r.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?r.out:r.in:r.out;Q(s,t,n);const a=t.seen.get(e);a.ref=s},Ka=(e,t,o,n)=>{const r=e._zod.def;Q(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,o.readOnly=!0},fm=(e,t,o,n)=>{const r=e._zod.def;Q(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},os=(e,t,o,n)=>{const r=e._zod.def;Q(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Ya=(e,t,o,n)=>{const r=e._zod.innerType;Q(r,t,n);const i=t.seen.get(e);i.ref=r},yi={string:Pa,number:Ea,boolean:Ca,bigint:nm,symbol:rm,null:Ia,undefined:sm,void:im,never:qa,any:Oa,unknown:Na,date:am,enum:Ma,literal:za,nan:cm,template_literal:um,file:lm,success:dm,custom:xa,function:pm,transform:Aa,map:hm,set:mm,array:La,object:ja,union:Ua,intersection:Da,tuple:Za,record:Va,nullable:Fa,nonoptional:Ha,default:Ja,prefault:Ba,catch:Wa,pipe:Ga,readonly:Ka,promise:fm,optional:os,lazy:Ya};function Xa(e,t){if("_idmap"in e){const n=e,r=Yn({...t,processors:yi}),i={};for(const u of n._idmap.entries()){const[l,d]=u;Q(d,r)}const s={},a={registry:n,uri:t?.uri,defs:i};r.external=a;for(const u of n._idmap.entries()){const[l,d]=u;Xn(r,d),s[l]=Qn(r,d)}if(Object.keys(i).length>0){const u=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:i}}return{schemas:s}}const o=Yn({...t,processors:yi});return Q(e,o),Xn(o,e),Qn(o,e)}const Sm=g("ZodISODateTime",(e,t)=>{vp.init(e,t),re.init(e,t)});function fn(e){return Ph(Sm,e)}const _m=g("ZodISODate",(e,t)=>{yp.init(e,t),re.init(e,t)});function Qa(e){return Eh(_m,e)}const gm=g("ZodISOTime",(e,t)=>{bp.init(e,t),re.init(e,t)});function vm(e){return Ch(gm,e)}const ym=g("ZodISODuration",(e,t)=>{Rp.init(e,t),re.init(e,t)});function bm(e){return Ih(ym,e)}const Rm=(e,t)=>{aa.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:o=>ld(e,o)},flatten:{value:o=>ud(e,o)},addIssue:{value:o=>{e.issues.push(o),e.message=JSON.stringify(e.issues,xr,2)}},addIssues:{value:o=>{e.issues.push(...o),e.message=JSON.stringify(e.issues,xr,2)}},isEmpty:{get(){return e.issues.length===0}}})},De=g("ZodError",Rm,{Parent:Error}),wm=Qr(De),Tm=es(De),ec=ir(De),$m=ar(De),km=hd(De),Pm=md(De),Em=fd(De),Cm=Sd(De),Im=_d(De),qm=gd(De),Om=vd(De),Nm=yd(De),bi=new WeakMap;function Sn(e,t,o){const n=Object.getPrototypeOf(e);let r=bi.get(n);if(r||(r=new Set,bi.set(n,r)),!r.has(t)){r.add(t);for(const i in o){const s=o[i];Object.defineProperty(n,i,{configurable:!0,enumerable:!1,get(){const a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}const X=g("ZodType",(e,t)=>(K.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:er(e,"input"),output:er(e,"output")}}),e.toJSONSchema=tm(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(o,n)=>wm(e,o,n,{callee:e.parse}),e.safeParse=(o,n)=>ec(e,o,n),e.parseAsync=async(o,n)=>Tm(e,o,n,{callee:e.parseAsync}),e.safeParseAsync=async(o,n)=>$m(e,o,n),e.spa=e.safeParseAsync,e.encode=(o,n)=>km(e,o,n),e.decode=(o,n)=>Pm(e,o,n),e.encodeAsync=async(o,n)=>Em(e,o,n),e.decodeAsync=async(o,n)=>Cm(e,o,n),e.safeEncode=(o,n)=>Im(e,o,n),e.safeDecode=(o,n)=>qm(e,o,n),e.safeEncodeAsync=async(o,n)=>Om(e,o,n),e.safeDecodeAsync=async(o,n)=>Nm(e,o,n),Sn(e,"ZodType",{check(...o){const n=this.def;return this.clone(_t(n,{checks:[...n.checks??[],...o.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...o){return this.check(...o)},clone(o,n){return gt(this,o,n)},brand(){return this},register(o,n){return o.add(this,n),this},refine(o,n){return this.check(kf(o,n))},superRefine(o,n){return this.check(Pf(o,n))},overwrite(o){return this.check(_o(o))},optional(){return M(this)},exactOptional(){return hf(this)},nullable(){return $i(this)},nullish(){return M($i(this))},nonoptional(o){return vf(this,o)},array(){return S(this)},or(o){return E([this,o])},and(o){return Nt(this,o)},transform(o){return ki(this,ac(o))},default(o){return Sf(this,o)},prefault(o){return gf(this,o)},catch(o){return bf(this,o)},pipe(o){return ki(this,o)},readonly(){return Tf(this)},describe(o){const n=this.clone();return en.add(n,{description:o}),n},meta(...o){if(o.length===0)return en.get(this);const n=this.clone();return en.add(n,o[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(o){return o(this)}}),Object.defineProperty(e,"description",{get(){return en.get(e)?.description},configurable:!0}),e)),tc=g("_ZodString",(e,t)=>{ts.init(e,t),X.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Pa(e,n,r);const o=e._zod.bag;e.format=o.format??null,e.minLength=o.minimum??null,e.maxLength=o.maximum??null,Sn(e,"_ZodString",{regex(...n){return this.check(jh(...n))},includes(...n){return this.check(Zh(...n))},startsWith(...n){return this.check(Vh(...n))},endsWith(...n){return this.check(Fh(...n))},min(...n){return this.check(Kn(...n))},max(...n){return this.check($a(...n))},length(...n){return this.check(ka(...n))},nonempty(...n){return this.check(Kn(1,...n))},lowercase(n){return this.check(Uh(n))},uppercase(n){return this.check(Dh(n))},trim(){return this.check(Jh())},normalize(...n){return this.check(Hh(...n))},toLowerCase(){return this.check(Bh())},toUpperCase(){return this.check(Wh())},slugify(){return this.check(Gh())}})}),Mm=g("ZodString",(e,t)=>{ts.init(e,t),tc.init(e,t),e.email=o=>e.check(wa(oc,o)),e.url=o=>e.check(Ta(nc,o)),e.jwt=o=>e.check(kh(Km,o)),e.emoji=o=>e.check(ph(xm,o)),e.guid=o=>e.check(Si(Ri,o)),e.uuid=o=>e.check(ch(Ln,o)),e.uuidv4=o=>e.check(uh(Ln,o)),e.uuidv6=o=>e.check(lh(Ln,o)),e.uuidv7=o=>e.check(dh(Ln,o)),e.nanoid=o=>e.check(hh(Am,o)),e.guid=o=>e.check(Si(Ri,o)),e.cuid=o=>e.check(mh(Lm,o)),e.cuid2=o=>e.check(fh(jm,o)),e.ulid=o=>e.check(Sh(Um,o)),e.base64=o=>e.check(wh(Bm,o)),e.base64url=o=>e.check(Th(Wm,o)),e.xid=o=>e.check(_h(Dm,o)),e.ksuid=o=>e.check(gh(Zm,o)),e.ipv4=o=>e.check(vh(Vm,o)),e.ipv6=o=>e.check(yh(Fm,o)),e.cidrv4=o=>e.check(bh(Hm,o)),e.cidrv6=o=>e.check(Rh(Jm,o)),e.e164=o=>e.check($h(Gm,o)),e.datetime=o=>e.check(fn(o)),e.date=o=>e.check(Qa(o)),e.time=o=>e.check(vm(o)),e.duration=o=>e.check(bm(o))});function c(e){return ah(Mm,e)}const re=g("ZodStringFormat",(e,t)=>{ee.init(e,t),tc.init(e,t)}),oc=g("ZodEmail",(e,t)=>{lp.init(e,t),re.init(e,t)});function zm(e){return wa(oc,e)}const Ri=g("ZodGUID",(e,t)=>{cp.init(e,t),re.init(e,t)}),Ln=g("ZodUUID",(e,t)=>{up.init(e,t),re.init(e,t)}),nc=g("ZodURL",(e,t)=>{dp.init(e,t),re.init(e,t)});function rc(e){return Ta(nc,e)}const xm=g("ZodEmoji",(e,t)=>{pp.init(e,t),re.init(e,t)}),Am=g("ZodNanoID",(e,t)=>{hp.init(e,t),re.init(e,t)}),Lm=g("ZodCUID",(e,t)=>{mp.init(e,t),re.init(e,t)}),jm=g("ZodCUID2",(e,t)=>{fp.init(e,t),re.init(e,t)}),Um=g("ZodULID",(e,t)=>{Sp.init(e,t),re.init(e,t)}),Dm=g("ZodXID",(e,t)=>{_p.init(e,t),re.init(e,t)}),Zm=g("ZodKSUID",(e,t)=>{gp.init(e,t),re.init(e,t)}),Vm=g("ZodIPv4",(e,t)=>{wp.init(e,t),re.init(e,t)}),Fm=g("ZodIPv6",(e,t)=>{Tp.init(e,t),re.init(e,t)}),Hm=g("ZodCIDRv4",(e,t)=>{$p.init(e,t),re.init(e,t)}),Jm=g("ZodCIDRv6",(e,t)=>{kp.init(e,t),re.init(e,t)}),Bm=g("ZodBase64",(e,t)=>{Pp.init(e,t),re.init(e,t)}),Wm=g("ZodBase64URL",(e,t)=>{Cp.init(e,t),re.init(e,t)}),Gm=g("ZodE164",(e,t)=>{Ip.init(e,t),re.init(e,t)}),Km=g("ZodJWT",(e,t)=>{Op.init(e,t),re.init(e,t)}),ns=g("ZodNumber",(e,t)=>{_a.init(e,t),X.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ea(e,n,r),Sn(e,"ZodNumber",{gt(n,r){return this.check(gi(n,r))},gte(n,r){return this.check($r(n,r))},min(n,r){return this.check($r(n,r))},lt(n,r){return this.check(_i(n,r))},lte(n,r){return this.check(Tr(n,r))},max(n,r){return this.check(Tr(n,r))},int(n){return this.check(wi(n))},safe(n){return this.check(wi(n))},positive(n){return this.check(gi(0,n))},nonnegative(n){return this.check($r(0,n))},negative(n){return this.check(_i(0,n))},nonpositive(n){return this.check(Tr(0,n))},multipleOf(n,r){return this.check(vi(n,r))},step(n,r){return this.check(vi(n,r))},finite(){return this}});const o=e._zod.bag;e.minValue=Math.max(o.minimum??Number.NEGATIVE_INFINITY,o.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(o.maximum??Number.POSITIVE_INFINITY,o.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(o.format??"").includes("int")||Number.isSafeInteger(o.multipleOf??.5),e.isFinite=!0,e.format=o.format??null});function b(e){return qh(ns,e)}const Ym=g("ZodNumberFormat",(e,t)=>{Np.init(e,t),ns.init(e,t)});function wi(e){return Nh(Ym,e)}const Xm=g("ZodBoolean",(e,t)=>{Mp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ca(e,o,n)});function P(e){return Mh(Xm,e)}const Qm=g("ZodNull",(e,t)=>{zp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ia(e,o,n)});function un(e){return zh(Qm,e)}const ef=g("ZodAny",(e,t)=>{xp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Oa()});function tf(){return xh(ef)}const of=g("ZodUnknown",(e,t)=>{Ap.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Na()});function z(){return Ah(of)}const nf=g("ZodNever",(e,t)=>{Lp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>qa(e,o,n)});function rf(e){return Lh(nf,e)}const sf=g("ZodArray",(e,t)=>{jp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>La(e,o,n,r),e.element=t.element,Sn(e,"ZodArray",{min(o,n){return this.check(Kn(o,n))},nonempty(o){return this.check(Kn(1,o))},max(o,n){return this.check($a(o,n))},length(o,n){return this.check(ka(o,n))},unwrap(){return this.element}})});function S(e,t){return Kh(sf,e,t)}const sc=g("ZodObject",(e,t)=>{Dp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>ja(e,o,n,r),B(e,"shape",()=>t.shape),Sn(e,"ZodObject",{keyof(){return F(Object.keys(this._zod.def.shape))},catchall(o){return this.clone({...this._zod.def,catchall:o})},passthrough(){return this.clone({...this._zod.def,catchall:z()})},loose(){return this.clone({...this._zod.def,catchall:z()})},strict(){return this.clone({...this._zod.def,catchall:rf()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(o){return nd(this,o)},safeExtend(o){return rd(this,o)},merge(o){return sd(this,o)},pick(o){return td(this,o)},omit(o){return od(this,o)},partial(...o){return id(cc,this,o[0])},required(...o){return ad(uc,this,o[0])}})});function p(e,t){const o={type:"object",shape:e??{},...N(t)};return new sc(o)}function A(e,t){return new sc({type:"object",shape:e,catchall:z(),...N(t)})}const ic=g("ZodUnion",(e,t)=>{ya.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ua(e,o,n,r),e.options=t.options});function E(e,t){return new ic({type:"union",options:e,...N(t)})}const af=g("ZodDiscriminatedUnion",(e,t)=>{ic.init(e,t),Zp.init(e,t)});function tr(e,t,o){return new af({type:"union",options:t,discriminator:e,...N(o)})}const cf=g("ZodIntersection",(e,t)=>{Vp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Da(e,o,n,r)});function Nt(e,t){return new cf({type:"intersection",left:e,right:t})}const uf=g("ZodTuple",(e,t)=>{Fp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Za(e,o,n,r),e.rest=o=>e.clone({...e._zod.def,rest:o})});function ry(e,t,o){const n=t instanceof K,r=n?o:t,i=n?t:null;return new uf({type:"tuple",items:e,rest:i,...N(r)})}const Ti=g("ZodRecord",(e,t)=>{Hp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Va(e,o,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function T(e,t,o){return!t||!t._zod?new Ti({type:"record",keyType:c(),valueType:e,...N(t)}):new Ti({type:"record",keyType:e,valueType:t,...N(o)})}const Lr=g("ZodEnum",(e,t)=>{Jp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ma(e,n,r),e.enum=t.entries,e.options=Object.values(t.entries);const o=new Set(Object.keys(t.entries));e.extract=(n,r)=>{const i={};for(const s of n)if(o.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Lr({...t,checks:[],...N(r),entries:i})},e.exclude=(n,r)=>{const i={...t.entries};for(const s of n)if(o.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Lr({...t,checks:[],...N(r),entries:i})}});function F(e,t){const o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Lr({type:"enum",entries:o,...N(t)})}const lf=g("ZodLiteral",(e,t)=>{Bp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>za(e,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function _(e,t){return new lf({type:"literal",values:Array.isArray(e)?e:[e],...N(t)})}const df=g("ZodTransform",(e,t)=>{Wp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Aa(e,o),e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new oa(e.constructor.name);o.addIssue=i=>{if(typeof i=="string")o.issues.push(cn(i,o.value,t));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=o.value),s.inst??(s.inst=e),o.issues.push(cn(s))}};const r=t.transform(o.value,o);return r instanceof Promise?r.then(i=>(o.value=i,o.fallback=!0,o)):(o.value=r,o.fallback=!0,o)}});function ac(e){return new df({type:"transform",transform:e})}const cc=g("ZodOptional",(e,t)=>{ba.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>os(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function M(e){return new cc({type:"optional",innerType:e})}const pf=g("ZodExactOptional",(e,t)=>{Gp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>os(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function hf(e){return new pf({type:"optional",innerType:e})}const mf=g("ZodNullable",(e,t)=>{Kp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Fa(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function $i(e){return new mf({type:"nullable",innerType:e})}const ff=g("ZodDefault",(e,t)=>{Yp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ja(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Sf(e,t){return new ff({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():sa(t)}})}const _f=g("ZodPrefault",(e,t)=>{Xp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ba(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function gf(e,t){return new _f({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():sa(t)}})}const uc=g("ZodNonOptional",(e,t)=>{Qp.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ha(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function vf(e,t){return new uc({type:"nonoptional",innerType:e,...N(t)})}const yf=g("ZodCatch",(e,t)=>{eh.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Wa(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function bf(e,t){return new yf({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const lc=g("ZodPipe",(e,t)=>{Ra.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ga(e,o,n,r),e.in=t.in,e.out=t.out});function ki(e,t){return new lc({type:"pipe",in:e,out:t})}const Rf=g("ZodPreprocess",(e,t)=>{lc.init(e,t),th.init(e,t)}),wf=g("ZodReadonly",(e,t)=>{oh.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ka(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Tf(e){return new wf({type:"readonly",innerType:e})}const $f=g("ZodLazy",(e,t)=>{nh.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ya(e,o,n,r),e.unwrap=()=>e._zod.def.getter()});function rs(e){return new $f({type:"lazy",getter:e})}const ss=g("ZodCustom",(e,t)=>{rh.init(e,t),X.init(e,t),e._zod.processJSONSchema=(o,n,r)=>xa(e,o)});function sy(e,t){return Yh(ss,(()=>!0),t)}function kf(e,t={}){return Xh(ss,e,t)}function Pf(e,t){return Qh(e,t)}function iy(e,t={}){const o=new ss({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...N(t)});return o._zod.bag.Class=e,o._zod.check=n=>{n.value instanceof e||n.issues.push({code:"invalid_type",expected:e.name,input:n.value,inst:o,path:[...o._zod.def.path??[]]})},o}function ln(e,t){return new Rf({type:"pipe",in:ac(e),out:t})}const Ef={custom:"custom"};function Cf(e){return Oh(ns,e)}var If=Object.create,is=Object.defineProperty,qf=Object.getOwnPropertyDescriptor,Of=Object.getOwnPropertyNames,Nf=Object.getPrototypeOf,Mf=Object.prototype.hasOwnProperty,zf=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),xf=(e,t)=>{let o={};for(var n in e)is(o,n,{get:e[n],enumerable:!0});return o},Af=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var r=Of(t),i=0,s=r.length,a;i<s;i++)a=r[i],!Mf.call(e,a)&&a!==o&&is(e,a,{get:(u=>t[u]).bind(null,a),enumerable:!(n=qf(t,a))||n.enumerable});return e},Lf=(e,t,o)=>(o=e!=null?If(Nf(e)):{},Af(is(o,"default",{value:e,enumerable:!0}),e));const jf=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),dc=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),Uf=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),Df=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function Zf(e){return typeof e=="string"&&dc.has(e.replace(/#$/,""))}function Vf(e,t){if(!("$schema"in e)||typeof e.$schema!="string")return"2020-12";const o=e.$schema.replace(/#$/,"");if(jf.has(o))return"2020-12";if(dc.has(o))return"2019-09";if(Uf.has(o)||Df.has(o))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}`)}const as="2025-11-25",Ff=[as,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Hf="io.modelcontextprotocol/related-task",mo="io.modelcontextprotocol/protocolVersion",cs="io.modelcontextprotocol/clientInfo",Yt="io.modelcontextprotocol/serverInfo",ur="io.modelcontextprotocol/clientCapabilities",pc="io.modelcontextprotocol/subscriptionId",us="io.modelcontextprotocol/logLevel",lr="2.0",fo=rs(()=>E([c(),b(),P(),un(),T(c(),fo),S(fo)])),ue=T(c(),fo),Jf=S(fo),ls=E([c(),b().int()]),ds=c(),hc=p({ttl:b().optional()}),mc=p({taskId:c()}),ps=A({progressToken:ls.optional(),[Hf]:mc.optional()}),Se=p({_meta:ps.optional()}),_n=Se.extend({task:hc.optional()}),le=p({method:c(),params:Se.loose().optional()}),Pe=p({_meta:ps.optional()}),Ee=p({method:c(),params:Pe.loose().optional()}),hs=A({get[Yt](){return hr.optional().catch(void 0)}}),de=A({_meta:hs.optional()}),go=E([c(),b().int()]),ms=p({jsonrpc:_(lr),id:go,...le.shape}).strict(),fs=p({jsonrpc:_(lr),...Ee.shape}).strict(),dr=p({jsonrpc:_(lr),id:go,result:de}).strict(),pr=p({jsonrpc:_(lr),id:go.optional(),error:p({code:b().int(),message:c(),data:z().optional()})}).strict(),tn=E([ms,fs,dr,pr]),Bf=E([dr,pr]),Ss=de.strict(),fc=Pe.extend({requestId:go.optional(),reason:c().optional()}),_s=Ee.extend({method:_("notifications/cancelled"),params:fc}),Sc=p({src:c(),mimeType:c().optional(),sizes:S(c()).optional(),theme:F(["light","dark"]).optional()}),vo=p({icons:S(Sc).optional()}),Mt=p({name:c(),title:c().optional()}),hr=Mt.extend({...Mt.shape,...vo.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),Wf=Nt(p({applyDefaults:P().optional()}),ue),Gf=ln(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Nt(p({form:Wf.optional(),url:ue.optional()}),ue.optional())),_c=A({list:ue.optional(),cancel:ue.optional(),requests:A({sampling:A({createMessage:ue.optional()}).optional(),elicitation:A({create:ue.optional()}).optional()}).optional()}),gc=A({list:ue.optional(),cancel:ue.optional(),requests:A({tools:A({call:ue.optional()}).optional()}).optional()}),vc=p({experimental:T(c(),ue).optional(),sampling:p({context:ue.optional(),tools:ue.optional()}).optional(),elicitation:Gf.optional(),roots:p({listChanged:P().optional()}).optional(),tasks:_c.optional(),extensions:T(c(),ue).optional()}),yc=Se.extend({protocolVersion:c(),capabilities:vc,clientInfo:hr}),gs=le.extend({method:_("initialize"),params:yc}),vs=p({experimental:T(c(),ue).optional(),logging:ue.optional(),completions:ue.optional(),prompts:p({listChanged:P().optional()}).optional(),resources:p({subscribe:P().optional(),listChanged:P().optional()}).optional(),tools:p({listChanged:P().optional()}).optional(),tasks:gc.optional(),extensions:T(c(),ue).optional()}),bc=de.extend({protocolVersion:c(),capabilities:vs,serverInfo:hr,instructions:c().optional()}),ys=Ee.extend({method:_("notifications/initialized"),params:Pe.optional()}),Rc=le.extend({method:_("server/discover"),params:Se.optional()}),mr=de.extend({supportedVersions:S(c()),capabilities:vs,instructions:c().optional()}),bs=le.extend({method:_("ping"),params:Se.optional()}),wc=p({progress:b(),total:M(b()),message:M(c())}),Tc=p({...Pe.shape,...wc.shape,progressToken:ls}),Rs=Ee.extend({method:_("notifications/progress"),params:Tc}),$c=Se.extend({cursor:ds.optional()}),yo=le.extend({params:$c.optional()}),bo=de.extend({nextCursor:ds.optional()}),ws=p({uri:c(),mimeType:M(c()),_meta:T(c(),z()).optional()}),Ts=ws.extend({text:c()}),$s=c().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),ks=ws.extend({blob:$s}),Ro=F(["user","assistant"]),xt=p({audience:S(Ro).optional(),priority:b().min(0).max(1).optional(),lastModified:fn({offset:!0}).optional()}),Ps=p({...Mt.shape,...vo.shape,uri:c(),description:M(c()),mimeType:M(c()),size:M(b()),annotations:xt.optional(),_meta:M(A({}))}),kc=p({...Mt.shape,...vo.shape,uriTemplate:c(),description:M(c()),mimeType:M(c()),annotations:xt.optional(),_meta:M(A({}))}),Pc=yo.extend({method:_("resources/list")}),Ec=bo.extend({resources:S(Ps)}),Cc=yo.extend({method:_("resources/templates/list")}),Ic=bo.extend({resourceTemplates:S(kc)}),fr=Se.extend({uri:c()}),qc=fr,Oc=le.extend({method:_("resources/read"),params:qc}),Nc=de.extend({contents:S(E([Ts,ks]))}),Mc=Ee.extend({method:_("notifications/resources/list_changed"),params:Pe.optional()}),zc=fr,xc=le.extend({method:_("resources/subscribe"),params:zc}),Ac=fr,Lc=le.extend({method:_("resources/unsubscribe"),params:Ac}),Es=p({toolsListChanged:P().optional(),promptsListChanged:P().optional(),resourcesListChanged:P().optional(),resourceSubscriptions:S(c()).optional()}),jc=Se.extend({notifications:Es}),Uc=le.extend({method:_("subscriptions/listen"),params:jc}),Dc=Pe.extend({notifications:Es}),Zc=Ee.extend({method:_("notifications/subscriptions/acknowledged"),params:Dc}),Vc=hs.extend({[pc]:go}),Fc=de.extend({_meta:Vc}),Hc=Pe.extend({uri:c()}),Jc=Ee.extend({method:_("notifications/resources/updated"),params:Hc}),Bc=p({name:c(),description:M(c()),required:M(P())}),Wc=p({...Mt.shape,...vo.shape,description:M(c()),arguments:M(S(Bc)),_meta:M(A({}))}),Gc=yo.extend({method:_("prompts/list")}),Kc=bo.extend({prompts:S(Wc)}),Yc=Se.extend({name:c(),arguments:T(c(),c()).optional()}),Xc=le.extend({method:_("prompts/get"),params:Yc}),Sr=p({type:_("text"),text:c(),annotations:xt.optional(),_meta:T(c(),z()).optional()}),_r=p({type:_("image"),data:$s,mimeType:c(),annotations:xt.optional(),_meta:T(c(),z()).optional()}),gr=p({type:_("audio"),data:$s,mimeType:c(),annotations:xt.optional(),_meta:T(c(),z()).optional()}),Qc=p({type:_("tool_use"),name:c(),id:c(),input:T(c(),z()),_meta:T(c(),z()).optional()}),eu=p({type:_("resource"),resource:E([Ts,ks]),annotations:xt.optional(),_meta:T(c(),z()).optional()}),tu=Ps.extend({type:_("resource_link")}),vr=E([Sr,_r,gr,tu,eu]),ou=p({role:Ro,content:vr}),nu=de.extend({description:c().optional(),messages:S(ou)}),ru=Ee.extend({method:_("notifications/prompts/list_changed"),params:Pe.optional()}),su=p({title:c().optional(),readOnlyHint:P().optional(),destructiveHint:P().optional(),idempotentHint:P().optional(),openWorldHint:P().optional()}),iu=p({taskSupport:F(["required","optional","forbidden"]).optional()}),Cs=p({...Mt.shape,...vo.shape,description:c().optional(),inputSchema:p({type:_("object"),properties:T(c(),fo).optional(),required:S(c()).optional()}).catchall(z()),outputSchema:A({$schema:c().optional()}).optional(),annotations:su.optional(),execution:iu.optional(),_meta:T(c(),z()).optional()}),au=yo.extend({method:_("tools/list")}),cu=bo.extend({tools:S(Cs)}),Is=de.extend({content:S(vr).default([]),structuredContent:z().optional(),isError:P().optional()}),Kf=Is.or(de.extend({toolResult:z()})),uu=_n.extend({name:c(),arguments:T(c(),z()).optional()}),lu=le.extend({method:_("tools/call"),params:uu}),du=Ee.extend({method:_("notifications/tools/list_changed"),params:Pe.optional()}),pu=p({autoRefresh:P().default(!0),debounceMs:b().int().nonnegative().default(300)}),qs=F(["debug","info","notice","warning","error","critical","alert","emergency"]),hu=Se.extend({level:qs}),mu=le.extend({method:_("logging/setLevel"),params:hu}),fu=Pe.extend({level:qs,logger:c().optional(),data:z()}),Su=Ee.extend({method:_("notifications/message"),params:fu}),_u=p({name:c().optional()}),gu=p({hints:S(_u).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),vu=p({mode:F(["auto","required","none"]).optional()}),yu=p({type:_("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:S(vr),structuredContent:z().optional(),isError:P().optional(),_meta:T(c(),z()).optional()}),bu=tr("type",[Sr,_r,gr]),dn=tr("type",[Sr,_r,gr,Qc,yu]),Ru=p({role:Ro,content:E([dn,S(dn)]),_meta:T(c(),z()).optional()}),wu=_n.extend({messages:S(Ru),modelPreferences:gu.optional(),systemPrompt:c().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:S(c()).optional(),metadata:ue.optional(),tools:S(Cs).optional(),toolChoice:vu.optional()}),Tu=le.extend({method:_("sampling/createMessage"),params:wu}),$u=de.extend({model:c(),stopReason:M(F(["endTurn","stopSequence","maxTokens"]).or(c())),role:Ro,content:bu}),ku=de.extend({model:c(),stopReason:M(F(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Ro,content:E([dn,S(dn)])}),Os=p({type:_("boolean"),title:c().optional(),description:c().optional(),default:P().optional()}),yr=p({type:_("string"),title:c().optional(),description:c().optional(),minLength:b().optional(),maxLength:b().optional(),format:F(["email","uri","date","date-time"]).optional(),default:c().optional()}),or=p({type:F(["number","integer"]),title:c().optional(),description:c().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),Ns=p({type:_("string"),title:c().optional(),description:c().optional(),enum:S(c()),default:c().optional()}),Ms=p({type:_("string"),title:c().optional(),description:c().optional(),oneOf:S(p({const:c(),title:c()})),default:c().optional()}),zs=p({type:_("string"),title:c().optional(),description:c().optional(),enum:S(c()),enumNames:S(c()).optional(),default:c().optional()}),Pu=E([Ns,Ms]),xs=p({type:_("array"),title:c().optional(),description:c().optional(),minItems:b().optional(),maxItems:b().optional(),items:p({type:_("string"),enum:S(c())}),default:S(c()).optional()}),As=p({type:_("array"),title:c().optional(),description:c().optional(),minItems:b().optional(),maxItems:b().optional(),items:p({anyOf:S(p({const:c(),title:c()}))}),default:S(c()).optional()}),Eu=E([xs,As]),Cu=E([zs,Pu,Eu]),Ls=E([Cu,Os,yr,or]),br=_n.extend({mode:_("form").optional(),message:c(),requestedSchema:p({type:_("object"),properties:T(c(),Ls),required:S(c()).optional()}).catchall(z())}),Iu=_n.extend({mode:_("url"),message:c(),elicitationId:c(),url:c().url()}),qu=E([br,Iu]),Ou=le.extend({method:_("elicitation/create"),params:qu}),Nu=Pe.extend({elicitationId:c()}),Mu=Ee.extend({method:_("notifications/elicitation/complete"),params:Nu}),zu=de.extend({action:F(["accept","decline","cancel"]),content:ln(e=>e===null?void 0:e,T(c(),E([c(),b(),P(),S(c())])).optional())}),xu=p({type:_("ref/resource"),uri:c()}),Au=p({type:_("ref/prompt"),name:c()}),Lu=Se.extend({ref:E([Au,xu]),argument:p({name:c(),value:c()}),context:p({arguments:T(c(),c()).optional()}).optional()}),ju=le.extend({method:_("completion/complete"),params:Lu}),Uu=de.extend({completion:A({values:S(c()).max(100),total:M(b().int()),hasMore:M(P())})}),Du=p({uri:c().startsWith("file://"),name:c().optional(),_meta:T(c(),z()).optional()}),Zu=le.extend({method:_("roots/list"),params:Se.optional()}),Vu=de.extend({roots:S(Du)}),Fu=Ee.extend({method:_("notifications/roots/list_changed"),params:Pe.optional()}),Yf=A({ttl:b().optional(),pollInterval:b().optional()}),Hu=F(["working","input_required","completed","failed","cancelled"]),wo=p({taskId:c(),status:Hu,ttl:E([b(),un()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:M(b()),statusMessage:M(c())}),Xf=de.extend({task:wo}),Ju=Pe.merge(wo),Qf=Ee.extend({method:_("notifications/tasks/status"),params:Ju}),eS=le.extend({method:_("tasks/get"),params:Se.extend({taskId:c()})}),tS=de.merge(wo),oS=le.extend({method:_("tasks/result"),params:Se.extend({taskId:c()})}),nS=de.loose(),rS=yo.extend({method:_("tasks/list")}),sS=bo.extend({tasks:S(wo)}),iS=le.extend({method:_("tasks/cancel"),params:Se.extend({taskId:c()})}),aS=de.merge(wo),cS=E([bs,gs,Rc,ju,mu,Xc,Gc,Pc,Cc,Oc,xc,Lc,Uc,lu,au]),uS=E([_s,Rs,ys,Fu]),lS=E([Ss,$u,ku,zu,Vu]),dS=E([bs,Tu,Ou,Zu]),pS=E([_s,Rs,Su,Jc,Mc,du,ru,Zc,Mu]),hS=E([Ss,bc,mr,Uu,nu,Kc,Ec,Ic,Nc,Is,cu,Fc]),pe=rc().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Ef.custom,message:"URL must be parseable",fatal:!0}),Wl}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Bu=A({resource:c().url(),authorization_servers:S(pe).optional(),jwks_uri:c().url().optional(),scopes_supported:S(c()).optional(),bearer_methods_supported:S(c()).optional(),resource_signing_alg_values_supported:S(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:P().optional(),authorization_details_types_supported:S(c()).optional(),dpop_signing_alg_values_supported:S(c()).optional(),dpop_bound_access_tokens_required:P().optional()}),js=A({issuer:c(),authorization_endpoint:pe,token_endpoint:pe,registration_endpoint:pe.optional(),scopes_supported:S(c()).optional(),response_types_supported:S(c()),response_modes_supported:S(c()).optional(),grant_types_supported:S(c()).optional(),token_endpoint_auth_methods_supported:S(c()).optional(),token_endpoint_auth_signing_alg_values_supported:S(c()).optional(),service_documentation:pe.optional(),revocation_endpoint:pe.optional(),revocation_endpoint_auth_methods_supported:S(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:S(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:S(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:S(c()).optional(),code_challenge_methods_supported:S(c()).optional(),client_id_metadata_document_supported:P().optional(),authorization_response_iss_parameter_supported:P().optional().catch(void 0),dpop_signing_alg_values_supported:S(c()).optional()}),Wu=A({issuer:c(),authorization_endpoint:pe,token_endpoint:pe,userinfo_endpoint:pe.optional(),jwks_uri:pe,registration_endpoint:pe.optional(),scopes_supported:S(c()).optional(),response_types_supported:S(c()),response_modes_supported:S(c()).optional(),grant_types_supported:S(c()).optional(),acr_values_supported:S(c()).optional(),subject_types_supported:S(c()),id_token_signing_alg_values_supported:S(c()),id_token_encryption_alg_values_supported:S(c()).optional(),id_token_encryption_enc_values_supported:S(c()).optional(),userinfo_signing_alg_values_supported:S(c()).optional(),userinfo_encryption_alg_values_supported:S(c()).optional(),userinfo_encryption_enc_values_supported:S(c()).optional(),request_object_signing_alg_values_supported:S(c()).optional(),request_object_encryption_alg_values_supported:S(c()).optional(),request_object_encryption_enc_values_supported:S(c()).optional(),token_endpoint_auth_methods_supported:S(c()).optional(),token_endpoint_auth_signing_alg_values_supported:S(c()).optional(),display_values_supported:S(c()).optional(),claim_types_supported:S(c()).optional(),claims_supported:S(c()).optional(),service_documentation:c().optional(),claims_locales_supported:S(c()).optional(),ui_locales_supported:S(c()).optional(),claims_parameter_supported:P().optional(),request_parameter_supported:P().optional(),request_uri_parameter_supported:P().optional(),require_request_uri_registration:P().optional(),op_policy_uri:pe.optional(),op_tos_uri:pe.optional(),client_id_metadata_document_supported:P().optional(),authorization_response_iss_parameter_supported:P().optional().catch(void 0)}),Gu=p({...Wu.shape,...js.pick({code_challenge_methods_supported:!0}).shape}),Ku=p({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:Cf().optional(),scope:c().optional(),refresh_token:c().optional(),issuer:c().optional().catch(void 0)}).strip(),mS=p({issued_token_type:_("urn:ietf:params:oauth:token-type:id-jag"),access_token:c(),token_type:c().optional(),expires_in:b().optional(),scope:c().optional()}).strip(),Yu=p({error:c(),error_description:c().optional(),error_uri:c().optional()}),Pi=pe.optional().or(_("").transform(()=>{})),Xu=p({redirect_uris:S(pe),token_endpoint_auth_method:c().optional(),grant_types:S(c()).optional(),response_types:S(c()).optional(),application_type:c().optional(),client_name:c().optional(),client_uri:pe.optional(),logo_uri:Pi,scope:c().optional(),contacts:S(c()).optional(),tos_uri:Pi,policy_uri:c().optional(),jwks_uri:pe.optional(),jwks:tf().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Qu=p({client_id:c(),client_secret:c().optional(),client_id_issued_at:b().optional(),client_secret_expires_at:b().optional(),issuer:c().optional().catch(void 0)}).strip(),el=Xu.merge(Qu),fS=p({error:c(),error_description:c().optional()}).strip(),SS=p({token:c(),token_type_hint:c().optional()}).strip(),jr=Symbol.for("mcp.sdk.errorBrands");function gn(e,t){const o=new Set;let n=t;for(;typeof n=="function";){const r=n.mcpBrand;Object.prototype.hasOwnProperty.call(n,"mcpBrand")&&typeof r=="string"&&o.add(r),n=Object.getPrototypeOf(n)}o.size!==0&&Object.defineProperty(e,jr,{value:o,enumerable:!1,configurable:!0})}function ot(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,jr)){const o=t[jr];if(o&&typeof o.has=="function"&&o.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}let ht=(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})({});var qt,So=(qt=class extends Error{static[Symbol.hasInstance](t){return ot(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 ot(this,t)}constructor(t,o,n){super(o),this.code=t,this.errorUri=n,this.name="OAuthError",gn(this,new.target)}toResponseObject(){const t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new qt(t.error,t.error_description??t.error,t.error_uri)}},Object.defineProperty(qt,"mcpBrand",{value:"mcp.OAuthError"}),qt);let C=(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})({});var Xt,q=(Xt=class extends Error{static[Symbol.hasInstance](t){return ot(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 ot(this,t)}constructor(t,o,n,r){super(o,r),this.code=t,this.data=n,this.name="SdkError",gn(this,new.target)}},Object.defineProperty(Xt,"mcpBrand",{value:"mcp.SdkError"}),Xt),Qt,st=(Qt=class extends q{constructor(t,o,n,r){super(t,o,n,r),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}},Object.defineProperty(Qt,"mcpBrand",{value:"mcp.SdkHttpError"}),Qt);function _S(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function tl(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;const t={...e};return delete t.issuer,t}function gS({requestedResource:e,configuredResource:t}){const o=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(o.origin!==n.origin||o.pathname.length<n.pathname.length)return!1;const r=o.pathname.endsWith("/")?o.pathname:o.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return r.startsWith(i)}const ol="2026-07-28",nl=[ol];function mt(e){return e>=ol}function rl(e){return e.filter(t=>!mt(t))}function nr(e){return e.filter(t=>mt(t))}function sl(e){const t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(o=>o.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}const il=["task","inputRequests","requestState"];function vS(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||il.some(t=>t in e)?e:{...e,content:[]}}function yS(){const e=rs(()=>E([c(),b(),P(),un(),T(c(),e),S(e)])),t=T(c(),e),o=E([c(),b().int()]),n=c(),r=p({ttl:b().optional()}),i=p({taskId:c()}),s=A({progressToken:o.optional(),"io.modelcontextprotocol/related-task":i.optional()}),a=p({_meta:s.optional()}),u=a.extend({task:r.optional()}),l=p({method:c(),params:a.loose().optional()}),d=p({_meta:s.optional()}),h=p({method:c(),params:d.loose().optional()}),m=A({_meta:s.optional()}),f=E([c(),b().int()]),v=m.strict(),R=d.extend({requestId:f.optional(),reason:c().optional()}),y=h.extend({method:_("notifications/cancelled"),params:R}),Z=p({src:c(),mimeType:c().optional(),sizes:S(c()).optional(),theme:F(["light","dark"]).optional()}),V=p({icons:S(Z).optional()}),I=p({name:c(),title:c().optional()}),L=I.extend({...I.shape,...V.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),W=Nt(p({applyDefaults:P().optional()}),t),J=ln(fe=>fe&&typeof fe=="object"&&!Array.isArray(fe)&&Object.keys(fe).length===0?{form:{}}:fe,Nt(p({form:W.optional(),url:t.optional()}),t.optional())),te=A({list:t.optional(),cancel:t.optional(),requests:A({sampling:A({createMessage:t.optional()}).optional(),elicitation:A({create:t.optional()}).optional()}).optional()}),ae=A({list:t.optional(),cancel:t.optional(),requests:A({tools:A({call:t.optional()}).optional()}).optional()}),se=p({experimental:T(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:J.optional(),roots:p({listChanged:P().optional()}).optional(),tasks:te.optional(),extensions:T(c(),t).optional()}),Re=a.extend({protocolVersion:c(),capabilities:se,clientInfo:L}),Ce=l.extend({method:_("initialize"),params:Re}),Y=p({experimental:T(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:P().optional()}).optional(),resources:p({subscribe:P().optional(),listChanged:P().optional()}).optional(),tools:p({listChanged:P().optional()}).optional(),tasks:ae.optional(),extensions:T(c(),t).optional()}),oe=m.extend({protocolVersion:c(),capabilities:Y,serverInfo:L,instructions:c().optional()}),He=h.extend({method:_("notifications/initialized"),params:d.optional()}),ze=l.extend({method:_("ping"),params:a.optional()}),Je=p({progress:b(),total:M(b()),message:M(c())}),we=p({...d.shape,...Je.shape,progressToken:o}),xe=h.extend({method:_("notifications/progress"),params:we}),Be=a.extend({cursor:n.optional()}),Ie=l.extend({params:Be.optional()}),_e=m.extend({nextCursor:n.optional()}),nt=p({uri:c(),mimeType:M(c()),_meta:T(c(),z()).optional()}),rt=nt.extend({text:c()}),We=c().refine(fe=>{try{return atob(fe),!0}catch{return!1}},{message:"Invalid Base64 string"}),he=nt.extend({blob:We}),ge=F(["user","assistant"]),ve=p({audience:S(ge).optional(),priority:b().min(0).max(1).optional(),lastModified:fn({offset:!0}).optional()}),Ze=p({...I.shape,...V.shape,uri:c(),description:M(c()),mimeType:M(c()),size:M(b()),annotations:ve.optional(),_meta:M(A({}))}),vt=p({...I.shape,...V.shape,uriTemplate:c(),description:M(c()),mimeType:M(c()),annotations:ve.optional(),_meta:M(A({}))}),qe=Ie.extend({method:_("resources/list")}),Oe=_e.extend({resources:S(Ze)}),Te=Ie.extend({method:_("resources/templates/list")}),Ae=_e.extend({resourceTemplates:S(vt)}),Le=a.extend({uri:c()}),Ge=Le,Ke=l.extend({method:_("resources/read"),params:Ge}),ct=m.extend({contents:S(E([rt,he]))}),Ye=h.extend({method:_("notifications/resources/list_changed"),params:d.optional()}),yt=Le,$=l.extend({method:_("resources/subscribe"),params:yt}),Xe=Le,x=l.extend({method:_("resources/unsubscribe"),params:Xe}),O=d.extend({uri:c()}),H=h.extend({method:_("notifications/resources/updated"),params:O}),k=p({name:c(),description:M(c()),required:M(P())}),w=p({...I.shape,...V.shape,description:M(c()),arguments:M(S(k)),_meta:M(A({}))}),U=Ie.extend({method:_("prompts/list")}),j=_e.extend({prompts:S(w)}),ce=a.extend({name:c(),arguments:T(c(),c()).optional()}),bt=l.extend({method:_("prompts/get"),params:ce}),Qe=p({type:_("text"),text:c(),annotations:ve.optional(),_meta:T(c(),z()).optional()}),Rt=p({type:_("image"),data:We,mimeType:c(),annotations:ve.optional(),_meta:T(c(),z()).optional()}),wt=p({type:_("audio"),data:We,mimeType:c(),annotations:ve.optional(),_meta:T(c(),z()).optional()}),To=p({type:_("tool_use"),name:c(),id:c(),input:T(c(),z()),_meta:T(c(),z()).optional()}),ut=p({type:_("resource"),resource:E([rt,he]),annotations:ve.optional(),_meta:T(c(),z()).optional()}),$o=Ze.extend({type:_("resource_link")}),je=E([Qe,Rt,wt,$o,ut]),At=p({role:ge,content:je}),Lt=m.extend({description:c().optional(),messages:S(At)}),Tt=h.extend({method:_("notifications/prompts/list_changed"),params:d.optional()}),ko=p({title:c().optional(),readOnlyHint:P().optional(),destructiveHint:P().optional(),idempotentHint:P().optional(),openWorldHint:P().optional()}),jt=p({taskSupport:F(["required","optional","forbidden"]).optional()}),$t=p({...I.shape,...V.shape,description:c().optional(),inputSchema:p({type:_("object"),properties:T(c(),e).optional(),required:S(c()).optional()}).catchall(z()),outputSchema:p({type:_("object"),properties:T(c(),e).optional(),required:S(c()).optional()}).catchall(z()).optional(),annotations:ko.optional(),execution:jt.optional(),_meta:T(c(),z()).optional()}),Ut=Ie.extend({method:_("tools/list")}),Dt=_e.extend({tools:S($t)}),Zt=m.extend({content:S(je),structuredContent:T(c(),z()).optional(),isError:P().optional()}),me=u.extend({name:c(),arguments:T(c(),z()).optional()}),Po=l.extend({method:_("tools/call"),params:me}),yn=h.extend({method:_("notifications/tools/list_changed"),params:d.optional()}),Vt=F(["debug","info","notice","warning","error","critical","alert","emergency"]),Eo=a.extend({level:Vt}),Co=l.extend({method:_("logging/setLevel"),params:Eo}),Io=d.extend({level:Vt,logger:c().optional(),data:z()}),qo=h.extend({method:_("notifications/message"),params:Io}),Oo=p({name:c().optional()}),No=p({hints:S(Oo).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),Mo=p({mode:F(["auto","required","none"]).optional()}),bn=p({type:_("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:S(je),structuredContent:p({}).loose().optional(),isError:P().optional(),_meta:T(c(),z()).optional()}),zo=tr("type",[Qe,Rt,wt]),lt=tr("type",[Qe,Rt,wt,To,bn]),xo=p({role:ge,content:E([lt,S(lt)]),_meta:T(c(),z()).optional()}),Ao=u.extend({messages:S(xo),modelPreferences:No.optional(),systemPrompt:c().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:S(c()).optional(),metadata:t.optional(),tools:S($t).optional(),toolChoice:Mo.optional()}),Lo=l.extend({method:_("sampling/createMessage"),params:Ao}),jo=m.extend({model:c(),stopReason:M(F(["endTurn","stopSequence","maxTokens"]).or(c())),role:ge,content:zo}),Uo=m.extend({model:c(),stopReason:M(F(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:ge,content:E([lt,S(lt)])}),Do=p({type:_("boolean"),title:c().optional(),description:c().optional(),default:P().optional()}),Zo=p({type:_("string"),title:c().optional(),description:c().optional(),minLength:b().optional(),maxLength:b().optional(),format:F(["email","uri","date","date-time"]).optional(),default:c().optional()}),Vo=p({type:F(["number","integer"]),title:c().optional(),description:c().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),Fo=p({type:_("string"),title:c().optional(),description:c().optional(),enum:S(c()),default:c().optional()}),Ho=p({type:_("string"),title:c().optional(),description:c().optional(),oneOf:S(p({const:c(),title:c()})),default:c().optional()}),Jo=p({type:_("string"),title:c().optional(),description:c().optional(),enum:S(c()),enumNames:S(c()).optional(),default:c().optional()}),Bo=E([Fo,Ho]),kt=p({type:_("array"),title:c().optional(),description:c().optional(),minItems:b().optional(),maxItems:b().optional(),items:p({type:_("string"),enum:S(c())}),default:S(c()).optional()}),Pt=p({type:_("array"),title:c().optional(),description:c().optional(),minItems:b().optional(),maxItems:b().optional(),items:p({anyOf:S(p({const:c(),title:c()}))}),default:S(c()).optional()}),Rn=E([kt,Pt]),wn=E([Jo,Bo,Rn]),Ne=E([wn,Do,Zo,Vo]),Me=u.extend({mode:_("form").optional(),message:c(),requestedSchema:p({type:_("object"),properties:T(c(),Ne),required:S(c()).optional()}).catchall(z())}),Wo=u.extend({mode:_("url"),message:c(),elicitationId:c(),url:c().url()}),Ve=E([Me,Wo]),Tn=l.extend({method:_("elicitation/create"),params:Ve}),$n=d.extend({elicitationId:c()}),kn=h.extend({method:_("notifications/elicitation/complete"),params:$n}),Pn=m.extend({action:F(["accept","decline","cancel"]),content:ln(fe=>fe===null?void 0:fe,T(c(),E([c(),b(),P(),S(c())])).optional())}),En=p({type:_("ref/resource"),uri:c()}),Cn=p({type:_("ref/prompt"),name:c()}),In=a.extend({ref:E([Cn,En]),argument:p({name:c(),value:c()}),context:p({arguments:T(c(),c()).optional()}).optional()}),Go=l.extend({method:_("completion/complete"),params:In}),qn=m.extend({completion:A({values:S(c()).max(100),total:M(b().int()),hasMore:M(P())})}),On=p({uri:c().startsWith("file://"),name:c().optional(),_meta:T(c(),z()).optional()}),Ft=l.extend({method:_("roots/list"),params:a.optional()}),Ko=m.extend({roots:S(On)}),Nn=h.extend({method:_("notifications/roots/list_changed"),params:d.optional()}),Mn=A({ttl:b().optional(),pollInterval:b().optional()}),Yo=F(["working","input_required","completed","failed","cancelled"]),dt=p({taskId:c(),status:Yo,ttl:E([b(),un()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:M(b()),statusMessage:M(c())}),$e=m.extend({task:dt}),zn=d.merge(dt),Et=h.extend({method:_("notifications/tasks/status"),params:zn}),Ht=l.extend({method:_("tasks/get"),params:a.extend({taskId:c()})}),Jt=m.merge(dt),Bt=l.extend({method:_("tasks/result"),params:a.extend({taskId:c()})}),wr=m.loose(),ye=Ie.extend({method:_("tasks/list")}),ie=_e.extend({tasks:S(dt)}),Ct=l.extend({method:_("tasks/cancel"),params:a.extend({taskId:c()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:o,CursorSchema:n,TaskMetadataSchema:r,RelatedTaskMetadataSchema:i,RequestMetaSchema:s,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:u,RequestSchema:l,NotificationsParamsSchema:d,NotificationSchema:h,ResultSchema:m,RequestIdSchema:f,EmptyResultSchema:v,CancelledNotificationParamsSchema:R,CancelledNotificationSchema:y,IconSchema:Z,IconsSchema:V,BaseMetadataSchema:I,ImplementationSchema:L,ClientTasksCapabilitySchema:te,ServerTasksCapabilitySchema:ae,ClientCapabilitiesSchema:se,InitializeRequestParamsSchema:Re,InitializeRequestSchema:Ce,ServerCapabilitiesSchema:Y,InitializeResultSchema:oe,InitializedNotificationSchema:He,PingRequestSchema:ze,ProgressSchema:Je,ProgressNotificationParamsSchema:we,ProgressNotificationSchema:xe,PaginatedRequestParamsSchema:Be,PaginatedRequestSchema:Ie,PaginatedResultSchema:_e,ResourceContentsSchema:nt,TextResourceContentsSchema:rt,BlobResourceContentsSchema:he,RoleSchema:ge,AnnotationsSchema:ve,ResourceSchema:Ze,ResourceTemplateSchema:vt,ListResourcesRequestSchema:qe,ListResourcesResultSchema:Oe,ListResourceTemplatesRequestSchema:Te,ListResourceTemplatesResultSchema:Ae,ResourceRequestParamsSchema:Le,ReadResourceRequestParamsSchema:Ge,ReadResourceRequestSchema:Ke,ReadResourceResultSchema:ct,ResourceListChangedNotificationSchema:Ye,SubscribeRequestParamsSchema:yt,SubscribeRequestSchema:$,UnsubscribeRequestParamsSchema:Xe,UnsubscribeRequestSchema:x,ResourceUpdatedNotificationParamsSchema:O,ResourceUpdatedNotificationSchema:H,PromptArgumentSchema:k,PromptSchema:w,ListPromptsRequestSchema:U,ListPromptsResultSchema:j,GetPromptRequestParamsSchema:ce,GetPromptRequestSchema:bt,TextContentSchema:Qe,ImageContentSchema:Rt,AudioContentSchema:wt,ToolUseContentSchema:To,EmbeddedResourceSchema:ut,ResourceLinkSchema:$o,ContentBlockSchema:je,PromptMessageSchema:At,GetPromptResultSchema:Lt,PromptListChangedNotificationSchema:Tt,ToolAnnotationsSchema:ko,ToolExecutionSchema:jt,ToolSchema:$t,ListToolsRequestSchema:Ut,ListToolsResultSchema:Dt,CallToolResultSchema:Zt,CallToolRequestParamsSchema:me,CallToolRequestSchema:Po,ToolListChangedNotificationSchema:yn,LoggingLevelSchema:Vt,SetLevelRequestParamsSchema:Eo,SetLevelRequestSchema:Co,LoggingMessageNotificationParamsSchema:Io,LoggingMessageNotificationSchema:qo,ModelHintSchema:Oo,ModelPreferencesSchema:No,ToolChoiceSchema:Mo,ToolResultContentSchema:bn,SamplingContentSchema:zo,SamplingMessageContentBlockSchema:lt,SamplingMessageSchema:xo,CreateMessageRequestParamsSchema:Ao,CreateMessageRequestSchema:Lo,CreateMessageResultSchema:jo,CreateMessageResultWithToolsSchema:Uo,BooleanSchemaSchema:Do,StringSchemaSchema:Zo,NumberSchemaSchema:Vo,UntitledSingleSelectEnumSchemaSchema:Fo,TitledSingleSelectEnumSchemaSchema:Ho,LegacyTitledEnumSchemaSchema:Jo,SingleSelectEnumSchemaSchema:Bo,UntitledMultiSelectEnumSchemaSchema:kt,TitledMultiSelectEnumSchemaSchema:Pt,MultiSelectEnumSchemaSchema:Rn,EnumSchemaSchema:wn,PrimitiveSchemaDefinitionSchema:Ne,ElicitRequestFormParamsSchema:Me,ElicitRequestURLParamsSchema:Wo,ElicitRequestParamsSchema:Ve,ElicitRequestSchema:Tn,ElicitationCompleteNotificationParamsSchema:$n,ElicitationCompleteNotificationSchema:kn,ElicitResultSchema:Pn,ResourceTemplateReferenceSchema:En,PromptReferenceSchema:Cn,CompleteRequestParamsSchema:In,CompleteRequestSchema:Go,CompleteResultSchema:qn,RootSchema:On,ListRootsRequestSchema:Ft,ListRootsResultSchema:Ko,RootsListChangedNotificationSchema:Nn,TaskCreationParamsSchema:Mn,TaskStatusSchema:Yo,TaskSchema:dt,CreateTaskResultSchema:$e,TaskStatusNotificationParamsSchema:zn,TaskStatusNotificationSchema:Et,GetTaskRequestSchema:Ht,GetTaskResultSchema:Jt,GetTaskPayloadRequestSchema:Bt,GetTaskPayloadResultSchema:wr,ListTasksRequestSchema:ye,ListTasksResultSchema:ie,CancelTaskRequestSchema:Ct,CancelTaskResultSchema:m.merge(dt),ClientRequestSchema:E([ze,Ce,Go,Co,bt,U,qe,Te,Ke,$,x,Po,Ut,Ht,Bt,ye,Ct]),ClientNotificationSchema:E([y,xe,He,Nn,Et]),ClientResultSchema:E([v,jo,Uo,Pn,Ko,Jt,ie,$e]),ServerRequestSchema:E([ze,Lo,Tn,Ft,Ht,Bt,ye,Ct]),ServerNotificationSchema:E([y,xe,qo,H,Ye,yn,Tt,Et,kn]),ServerResultSchema:E([v,oe,qn,Lt,j,Oe,Ae,ct,Zt,Dt,Jt,ie,$e]),CallToolResultWireSchema:z().superRefine((fe,Vl)=>{if(!(typeof fe!="object"||fe===null||Array.isArray(fe)||fe.content!==void 0)){for(const Xs of il)if(Xs in fe){Vl.addIssue({code:"custom",message:`content is required when the body carries '${Xs}' — another result family cannot default into an empty tools/call success`});return}}}).transform(vS).pipe(Zt)}}let bS;function al(){return bS??=yS()}function cl(e){return e.type!=="object"}const RS=new Set(["const","enum","default","examples"]),wS=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function Ei(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}function TS(e){const t=typeof e.$schema=="string"?e.$schema:void 0;if(Ei(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};const o=Zf(e.$schema)&&e.$recursiveAnchor!==!0,n=(r,i)=>{if(Array.isArray(r))return r.map(u=>n(u,!1));if(r===null||typeof r!="object"||!i&&Ei(r.$id))return r;const s={};let a=!1;for(const[u,l]of Object.entries(r))i?s[u]=n(l,!1):(u==="$ref"||u==="$dynamicRef")&&typeof l=="string"?s[u]=l==="#"?"#/properties/result":l.startsWith("#/")?`#/properties/result${l.slice(1)}`:l:u==="$recursiveRef"&&l==="#"&&o?a=!0:RS.has(u)?s[u]=l:wS.has(u)?s[u]=n(l,!0):s[u]=n(l,!1);return a&&("$ref"in s?s.allOf=[...Array.isArray(s.allOf)?s.allOf:[],{$ref:"#/properties/result"}]:s.$ref="#/properties/result"),s};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:n(e,!1)},required:["result"]}}const $S={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},kS={"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},PS={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};let jn;function Us(){if(jn)return jn;const e=al();return jn={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}},jn}function ul(e){return Object.prototype.hasOwnProperty.call($S,e)}function ll(e){return Object.prototype.hasOwnProperty.call(kS,e)}function ES(e){return Object.prototype.hasOwnProperty.call(PS,e)}function CS(e){return ES(e)?Us().resultSchemas[e]:void 0}function IS(e){return ul(e)?Us().requestSchemas[e]:void 0}function qS(e){return ll(e)?Us().notificationSchemas[e]:void 0}function Ur(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Un(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};const o=e.safeParse(t);return o.success?{ok:!0,value:o.data}:{ok:!1,reason:"invalid",message:String(o.error)}}const Ci={ok:!1,reason:"not-in-era"};function Ii(e){return Ur(e)&&Ur(e.outputSchema)&&cl(e.outputSchema)}const Ds={era:"2025-11-25",hasRequestMethod:ul,hasNotificationMethod:ll,validateRequest:(e,t)=>Un(IS(e),t),validateResult:(e,t)=>Un(CS(e),t),validateNotification:(e,t)=>Un(qS(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>Ci,validateInputResponse:()=>Ci,samplingResultVariant:((e,t)=>{const o=al();return Un(e?o.CreateMessageResultWithToolsSchema:o.CreateMessageResultSchema,t)}),outboundEnvelope:e=>{},validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){const o=sl(e),n=o.structuredContent;if(n===void 0)return o;const r=typeof n!="object"||n===null||Array.isArray(n),i=t!==void 0&&cl(t);return!r&&!i?o:{...o,structuredContent:{result:n}}},decodeResult(e,t){if(Ur(t)&&"resultType"in t){const o={...t};return delete o.resultType,{kind:"complete",result:o}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;const o=t.tools;return!Array.isArray(o)||!o.some(n=>Ii(n))?t:{...t,tools:o.map(n=>Ii(n)?{...n,outputSchema:TS(n.outputSchema)}:n)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>{}};function OS(){const e=rs(()=>E([c(),b(),P(),un(),T(c(),e),S(e)])),t=T(c(),e),o=E([c(),b().int()]),n=c(),r=E([c(),b().int()]),i=F(["user","assistant"]),s=F(["debug","info","notice","warning","error","critical","alert","emergency"]),a=c().refine(ie=>{try{return atob(ie),!0}catch{return!1}},{message:"Invalid Base64 string"}),u=p({ttl:b().optional()}),l=p({taskId:c()}),d=A({progressToken:o.optional(),"io.modelcontextprotocol/related-task":l.optional()}),h=p({_meta:d.optional()}),m=h.extend({task:u.optional()}),f=p({_meta:d.optional()}),v=p({method:c(),params:f.loose().optional()}),R=p({src:c(),mimeType:c().optional(),sizes:S(c()).optional(),theme:F(["light","dark"]).optional()}),y=p({icons:S(R).optional()}),Z=p({name:c(),title:c().optional()}),V=Z.extend({...Z.shape,...y.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),I=Nt(p({applyDefaults:P().optional()}),t),L=ln(ie=>ie&&typeof ie=="object"&&!Array.isArray(ie)&&Object.keys(ie).length===0?{form:{}}:ie,Nt(p({form:I.optional(),url:t.optional()}),t.optional())),W=A({list:t.optional(),cancel:t.optional(),requests:A({sampling:A({createMessage:t.optional()}).optional(),elicitation:A({create:t.optional()}).optional()}).optional()}),J=A({list:t.optional(),cancel:t.optional(),requests:A({tools:A({call:t.optional()}).optional()}).optional()}),te=p({experimental:T(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:L.optional(),roots:p({listChanged:P().optional()}).optional(),tasks:W.optional(),extensions:T(c(),t).optional()}),ae=p({experimental:T(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:P().optional()}).optional(),resources:p({subscribe:P().optional(),listChanged:P().optional()}).optional(),tools:p({listChanged:P().optional()}).optional(),tasks:J.optional(),extensions:T(c(),t).optional()}),se=p({progress:b(),total:M(b()),message:M(c())}),Re=p({...f.shape,...se.shape,progressToken:o}),Ce=v.extend({method:_("notifications/progress"),params:Re}),Y=f.extend({level:s,logger:c().optional(),data:z()}),oe=v.extend({method:_("notifications/message"),params:Y}),He=p({uri:c(),mimeType:M(c()),_meta:T(c(),z()).optional()}),ze=He.extend({text:c()}),Je=He.extend({blob:a}),we=p({audience:S(i).optional(),priority:b().min(0).max(1).optional(),lastModified:fn({offset:!0}).optional()}),xe=p({...Z.shape,...y.shape,uri:c(),description:M(c()),mimeType:M(c()),size:M(b()),annotations:we.optional(),_meta:M(A({}))}),Be=p({...Z.shape,...y.shape,uriTemplate:c(),description:M(c()),mimeType:M(c()),annotations:we.optional(),_meta:M(A({}))}),Ie=v.extend({method:_("notifications/resources/list_changed"),params:f.optional()}),_e=f.extend({uri:c()}),nt=v.extend({method:_("notifications/resources/updated"),params:_e}),rt=p({name:c(),description:M(c()),required:M(P())}),We=p({...Z.shape,...y.shape,description:M(c()),arguments:M(S(rt)),_meta:M(A({}))}),he=v.extend({method:_("notifications/prompts/list_changed"),params:f.optional()}),ge=p({type:_("text"),text:c(),annotations:we.optional(),_meta:T(c(),z()).optional()}),ve=p({type:_("image"),data:a,mimeType:c(),annotations:we.optional(),_meta:T(c(),z()).optional()}),Ze=p({type:_("audio"),data:a,mimeType:c(),annotations:we.optional(),_meta:T(c(),z()).optional()}),vt=p({type:_("tool_use"),name:c(),id:c(),input:T(c(),z()),_meta:T(c(),z()).optional()}),qe=p({type:_("resource"),resource:E([ze,Je]),annotations:we.optional(),_meta:T(c(),z()).optional()}),Oe=xe.extend({type:_("resource_link")}),Te=E([ge,ve,Ze,Oe,qe]),Ae=p({role:i,content:Te}),Le=p({title:c().optional(),readOnlyHint:P().optional(),destructiveHint:P().optional(),idempotentHint:P().optional(),openWorldHint:P().optional()}),Ge=v.extend({method:_("notifications/tools/list_changed"),params:f.optional()}),Ke=p({name:c().optional()}),ct=p({hints:S(Ke).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),Ye=p({mode:F(["auto","required","none"]).optional()}),yt=p({type:_("boolean"),title:c().optional(),description:c().optional(),default:P().optional()}),$=p({type:_("string"),title:c().optional(),description:c().optional(),minLength:b().optional(),maxLength:b().optional(),format:F(["email","uri","date","date-time"]).optional(),default:c().optional()}),Xe=p({type:F(["number","integer"]),title:c().optional(),description:c().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),x=p({type:_("string"),title:c().optional(),description:c().optional(),enum:S(c()),default:c().optional()}),O=p({type:_("string"),title:c().optional(),description:c().optional(),oneOf:S(p({const:c(),title:c()})),default:c().optional()}),H=p({type:_("string"),title:c().optional(),description:c().optional(),enum:S(c()),enumNames:S(c()).optional(),default:c().optional()}),k=E([x,O]),w=p({type:_("array"),title:c().optional(),description:c().optional(),minItems:b().optional(),maxItems:b().optional(),items:p({type:_("string"),enum:S(c())}),default:S(c()).optional()}),U=p({type:_("array"),title:c().optional(),description:c().optional(),minItems:b().optional(),maxItems:b().optional(),items:p({anyOf:S(p({const:c(),title:c()}))}),default:S(c()).optional()}),j=E([w,U]),ce=E([H,k,j]),bt=E([ce,yt,$,Xe]),Qe=m.extend({mode:_("form").optional(),message:c(),requestedSchema:p({type:_("object"),properties:T(c(),bt),required:S(c()).optional()}).catchall(z())}),Rt=p({type:_("ref/resource"),uri:c()}),wt=p({type:_("ref/prompt"),name:c()}),To=p({uri:c().startsWith("file://"),name:c().optional(),_meta:T(c(),z()).optional()}),ut=te.shape,$o=p({experimental:ut.experimental,sampling:ut.sampling,elicitation:ut.elicitation,roots:ut.roots,extensions:ut.extensions}),je=ae.shape,At=p({experimental:je.experimental,logging:je.logging,completions:je.completions,prompts:je.prompts,resources:je.resources,tools:je.tools,extensions:je.extensions}),Lt=A({progressToken:o.optional(),[mo]:c(),[cs]:V.optional(),[ur]:$o,[us]:s.optional()}),Tt=p({...Z.shape,...y.shape,description:c().optional(),inputSchema:A({$schema:c().optional(),type:_("object")}),outputSchema:A({$schema:c().optional()}).optional(),annotations:Le.optional(),_meta:T(c(),z()).optional()}),ko=p({type:_("tool_result"),toolUseId:c(),content:S(Te),structuredContent:z().optional(),isError:P().optional(),_meta:T(c(),z()).optional()}),jt=E([ge,ve,Ze,vt,ko]),$t=p({role:i,content:E([jt,S(jt)]),_meta:T(c(),z()).optional()}),Ut=c(),Dt=A({[Yt]:V.optional().catch(void 0)}),Zt=Dt.optional();function me(ie){return A({_meta:Zt,resultType:Ut.default("complete"),...ie})}const Po=me({}),yn=me({nextCursor:n.optional()}),Vt=me({content:S(Te),structuredContent:z().optional(),isError:P().optional()}),Eo=me({ttlMs:b().int().min(0),cacheScope:F(["public","private"]),tools:S(Tt),nextCursor:n.optional()}),Co=me({ttlMs:b().int().min(0),cacheScope:F(["public","private"]),prompts:S(We),nextCursor:n.optional()}),Io=me({description:c().optional(),messages:S(Ae)}),qo=me({ttlMs:b().int().min(0),cacheScope:F(["public","private"]),resources:S(xe),nextCursor:n.optional()}),Oo=me({ttlMs:b().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:S(Be),nextCursor:n.optional()}),No=me({ttlMs:b().int().min(0),cacheScope:F(["public","private"]),contents:S(E([ze,Je]))}),Mo=me({completion:p({values:S(c()).max(100),total:b().int().optional(),hasMore:P().optional()}).loose()}),bn=me({ttlMs:b().int().min(0),cacheScope:F(["public","private"])}),zo=me({ttlMs:b().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:S(c()),capabilities:At,instructions:c().optional()}),lt=p({messages:S($t),modelPreferences:ct.optional(),systemPrompt:c().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:S(c()).optional(),metadata:t.optional(),tools:S(Tt).optional(),toolChoice:Ye.optional()}),xo=p({method:_("sampling/createMessage"),params:lt}),Ao=p({method:_("roots/list"),params:p({_meta:T(c(),z()).optional()}).optional()}),Lo=p({...$t.shape,model:c(),stopReason:c().optional()}),jo=p({roots:S(To)}),Uo=p({action:F(["accept","decline","cancel"]),content:T(c(),E([c(),b(),P(),S(c())])).optional()}),Do=p({mode:_("url"),message:c(),url:c().url()}),Zo=E([Qe,Do]),Vo=p({method:_("elicitation/create"),params:Zo}),Fo=E([xo,Ao,Vo]),Ho=E([Lo,jo,Uo]),Jo=T(c(),Fo),Bo=T(c(),Ho),kt=me({inputRequests:Jo.optional(),requestState:c().optional()}),Pt={inputResponses:Bo.optional(),requestState:c().optional()},Rn=p({_meta:Lt,...Pt}),wn=A({progressToken:o.optional()});function Ne(ie,Ct){return p({method:_(ie),params:p({_meta:Lt,...Ct})})}function Me(ie,Ct){return p({method:_(ie),params:p({_meta:wn.optional(),...Ct}).optional()})}const Wo={name:c(),arguments:T(c(),z()).optional(),...Pt},Ve={cursor:n.optional()},Tn=Ne("tools/call",Wo),$n=Ne("tools/list",Ve),kn=Ne("prompts/list",Ve),Pn=Ne("prompts/get",{name:c(),arguments:T(c(),c()).optional(),...Pt}),En=Ne("resources/list",Ve),Cn=Ne("resources/templates/list",Ve),In=Ne("resources/read",{uri:c(),...Pt}),Go={ref:E([wt,Rt]),argument:p({name:c(),value:c()}),context:p({arguments:T(c(),c()).optional()}).optional()},qn=Ne("completion/complete",Go),On=Ne("server/discover",{}),Ft=p({toolsListChanged:P().optional(),promptsListChanged:P().optional(),resourcesListChanged:P().optional(),resourceSubscriptions:S(c()).optional()}),Ko={notifications:Ft},Nn=Ne("subscriptions/listen",Ko),Mn=Dt.extend({"io.modelcontextprotocol/subscriptionId":r}),Yo=A({_meta:Mn,resultType:Ut.default("complete")}),dt={"tools/call":Me("tools/call",Wo),"tools/list":Me("tools/list",Ve),"prompts/get":Me("prompts/get",{name:c(),arguments:T(c(),c()).optional()}),"prompts/list":Me("prompts/list",Ve),"resources/list":Me("resources/list",Ve),"resources/templates/list":Me("resources/templates/list",Ve),"resources/read":Me("resources/read",{uri:c()}),"completion/complete":Me("completion/complete",Go),"server/discover":Me("server/discover",{}),"subscriptions/listen":Me("subscriptions/listen",Ko)};function $e(ie){return A({_meta:Zt,...ie})}const zn={"tools/call":$e({content:S(Te),structuredContent:z().optional(),isError:P().optional()}),"tools/list":$e({ttlMs:b().int().min(0),cacheScope:F(["public","private"]),tools:S(Tt),nextCursor:n.optional()}),"prompts/get":$e({description:c().optional(),messages:S(Ae)}),"prompts/list":$e({ttlMs:b().int().min(0),cacheScope:F(["public","private"]),prompts:S(We),nextCursor:n.optional()}),"resources/list":$e({ttlMs:b().int().min(0),cacheScope:F(["public","private"]),resources:S(xe),nextCursor:n.optional()}),"resources/templates/list":$e({ttlMs:b().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:S(Be),nextCursor:n.optional()}),"resources/read":$e({ttlMs:b().int().min(0),cacheScope:F(["public","private"]),contents:S(E([ze,Je]))}),"completion/complete":$e({completion:p({values:S(c()).max(100),total:b().int().optional(),hasMore:P().optional()}).loose()}),"server/discover":$e({ttlMs:b().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:S(c()),capabilities:At,instructions:c().optional()}),"subscriptions/listen":$e({})},Et=A({"io.modelcontextprotocol/subscriptionId":r.optional()}),Ht=p({method:_("notifications/subscriptions/acknowledged"),params:p({_meta:Et.optional(),notifications:Ft})}),Jt=p({_meta:Et.optional(),requestId:r,reason:c().optional()}),Bt=p({method:_("notifications/cancelled"),params:Jt}),wr={"notifications/cancelled":Bt,"notifications/progress":Ce,"notifications/message":oe,"notifications/resources/updated":nt,"notifications/resources/list_changed":Ie,"notifications/tools/list_changed":Ge,"notifications/prompts/list_changed":he,"notifications/subscriptions/acknowledged":Ht},ye=ie=>p({jsonrpc:_("2.0"),id:E([c(),b().int()]),result:ie}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:o,CursorSchema:n,RequestIdSchema:r,RoleSchema:i,LoggingLevelSchema:s,TaskMetadataSchema:u,RelatedTaskMetadataSchema:l,RequestMetaSchema:d,BaseRequestParamsSchema:h,TaskAugmentedRequestParamsSchema:m,NotificationsParamsSchema:f,NotificationSchema:v,IconSchema:R,IconsSchema:y,BaseMetadataSchema:Z,ImplementationSchema:V,ClientTasksCapabilitySchema:W,ServerTasksCapabilitySchema:J,ClientCapabilitiesSchema:te,ServerCapabilitiesSchema:ae,ProgressSchema:se,ProgressNotificationParamsSchema:Re,ProgressNotificationSchema:Ce,LoggingMessageNotificationParamsSchema:Y,LoggingMessageNotificationSchema:oe,ResourceContentsSchema:He,TextResourceContentsSchema:ze,BlobResourceContentsSchema:Je,AnnotationsSchema:we,ResourceSchema:xe,ResourceTemplateSchema:Be,ResourceListChangedNotificationSchema:Ie,ResourceUpdatedNotificationParamsSchema:_e,ResourceUpdatedNotificationSchema:nt,PromptArgumentSchema:rt,PromptSchema:We,PromptListChangedNotificationSchema:he,TextContentSchema:ge,ImageContentSchema:ve,AudioContentSchema:Ze,ToolUseContentSchema:vt,EmbeddedResourceSchema:qe,ResourceLinkSchema:Oe,ContentBlockSchema:Te,PromptMessageSchema:Ae,ToolAnnotationsSchema:Le,ToolListChangedNotificationSchema:Ge,ModelHintSchema:Ke,ModelPreferencesSchema:ct,ToolChoiceSchema:Ye,BooleanSchemaSchema:yt,StringSchemaSchema:$,NumberSchemaSchema:Xe,UntitledSingleSelectEnumSchemaSchema:x,TitledSingleSelectEnumSchemaSchema:O,LegacyTitledEnumSchemaSchema:H,SingleSelectEnumSchemaSchema:k,UntitledMultiSelectEnumSchemaSchema:w,TitledMultiSelectEnumSchemaSchema:U,MultiSelectEnumSchemaSchema:j,EnumSchemaSchema:ce,PrimitiveSchemaDefinitionSchema:bt,ElicitRequestFormParamsSchema:Qe,ResourceTemplateReferenceSchema:Rt,PromptReferenceSchema:wt,RootSchema:To,ClientCapabilities2026Schema:$o,ServerCapabilities2026Schema:At,RequestMetaEnvelopeSchema:Lt,ToolSchema:Tt,ToolResultContentSchema:ko,SamplingMessageContentBlockSchema:jt,SamplingMessageSchema:$t,ResultTypeSchema:Ut,ResultMetaSchema:Dt,ResultSchema:Po,PaginatedResultSchema:yn,CallToolResultSchema:Vt,ListToolsResultSchema:Eo,ListPromptsResultSchema:Co,GetPromptResultSchema:Io,ListResourcesResultSchema:qo,ListResourceTemplatesResultSchema:Oo,ReadResourceResultSchema:No,CompleteResultSchema:Mo,CacheableResultSchema:bn,DiscoverResultSchema:zo,CreateMessageRequestParamsSchema:lt,CreateMessageRequestSchema:xo,ListRootsRequestSchema:Ao,CreateMessageResultSchema:Lo,ListRootsResultSchema:jo,ElicitResultSchema:Uo,ElicitRequestURLParamsSchema:Do,ElicitRequestParamsSchema:Zo,ElicitRequestSchema:Vo,InputRequestSchema:Fo,InputResponseSchema:Ho,InputRequestsSchema:Jo,InputResponsesSchema:Bo,InputRequiredResultSchema:kt,InputResponseRequestParamsSchema:Rn,CallToolRequestSchema:Tn,ListToolsRequestSchema:$n,ListPromptsRequestSchema:kn,GetPromptRequestSchema:Pn,ListResourcesRequestSchema:En,ListResourceTemplatesRequestSchema:Cn,ReadResourceRequestSchema:In,CompleteRequestSchema:qn,DiscoverRequestSchema:On,SubscriptionFilterSchema:Ft,SubscriptionsListenRequestSchema:Nn,SubscriptionsListenResultMetaSchema:Mn,SubscriptionsListenResultSchema:Yo,dispatchRequestSchemas:dt,dispatchResultSchemas:zn,NotificationMetaSchema:Et,SubscriptionsAcknowledgedNotificationSchema:Ht,CancelledNotificationParamsSchema:Jt,CancelledNotificationSchema:Bt,notificationSchemas2026:wr,JSONRPCResultResponseSchema:ye(Po),CallToolResultResponseSchema:ye(E([Vt,kt])),ListToolsResultResponseSchema:ye(Eo),ListPromptsResultResponseSchema:ye(Co),GetPromptResultResponseSchema:ye(E([Io,kt])),ListResourcesResultResponseSchema:ye(qo),ListResourceTemplatesResultResponseSchema:ye(Oo),ReadResourceResultResponseSchema:ye(E([No,kt])),CompleteResultResponseSchema:ye(Mo),DiscoverResultResponseSchema:ye(zo),SubscriptionsListenResultResponseSchema:ye(Yo)}}let NS;function ft(){return NS??=OS()}const MS=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function zS(e){return MS.includes(e)}const Zs=Symbol("modelcontextprotocol.resultCacheHintFallback");function xS(e){return e[Zs]}function dl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function pl(e){return e==="public"||e==="private"}let D=(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})({});var Ot,G=(Ot=class extends Error{static[Symbol.hasInstance](t){return ot(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 ot(this,t)}constructor(t,o,n){super(o),this.code=t,this.data=n,this.name="ProtocolError",gn(this,new.target)}static fromError(t,o,n){if(t===D.UrlElicitationRequired&&n){const r=n;if(r.elicitations)return new LS(r.elicitations,o)}if(t===D.UnsupportedProtocolVersion&&n){const r=n;if(Array.isArray(r.supported)&&typeof r.requested=="string")return new Vs({supported:r.supported,requested:r.requested},o)}if(t===D.InvalidParams||t===D.ResourceNotFound){const r=n;if(typeof r?.uri=="string"&&(t===D.ResourceNotFound||Object.keys(r).length===1))return new AS(r.uri,o)}if(t===D.MissingRequiredClientCapability&&n){const r=n;if(r.requiredCapabilities!==null&&typeof r.requiredCapabilities=="object"&&!Array.isArray(r.requiredCapabilities))return new jS({requiredCapabilities:r.requiredCapabilities},o)}return new Ot(t,o,n)}},Object.defineProperty(Ot,"mcpBrand",{value:"mcp.ProtocolError"}),Ot),eo,AS=(eo=class extends G{constructor(t,o=`Resource not found: ${t}`){super(D.InvalidParams,o,{uri:t})}get uri(){return this.data.uri}},Object.defineProperty(eo,"mcpBrand",{value:"mcp.ResourceNotFoundError"}),eo),to,LS=(to=class extends G{constructor(t,o=`URL elicitation${t.length>1?"s":""} required`){super(D.UrlElicitationRequired,o,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}},Object.defineProperty(to,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"}),to),oo,Vs=(oo=class extends G{constructor(t,o=`Unsupported protocol version: ${t.requested}`){super(D.UnsupportedProtocolVersion,o,t)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Object.defineProperty(oo,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"}),oo),no,jS=(no=class extends G{constructor(t,o=`Missing required client capabilities: ${Object.keys(t.requiredCapabilities).join(", ")}`){super(D.MissingRequiredClientCapability,o,t)}get requiredCapabilities(){return this.data.requiredCapabilities}},Object.defineProperty(no,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"}),no);const US=0,DS="private",ZS=["tools/call","prompts/get","resources/read"];function VS(e,t){const o=t.resultType;if(o===void 0)return{...t,resultType:"complete"};if(o==="complete"||ZS.includes(e))return t;throw new G(D.InternalError,`Handler for ${e} returned resultType '${String(o)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function FS(e,t){const o=xS(t);if(t.resultType!=="complete"||!zS(e))return o===void 0?t:GS(t);const n=t,r=dl(n.ttlMs)?n.ttlMs:BS(o),i=pl(n.cacheScope)?n.cacheScope:WS(o),s={...n,ttlMs:r,cacheScope:i};return delete s[Zs],s}function HS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function JS(e,t){if(t===void 0)return e;const o=e._meta;return o===void 0?{...e,_meta:{[Yt]:t}}:!HS(o)||o[Yt]!==void 0?e:{...e,_meta:{...o,[Yt]:t}}}function BS(e){return e!==void 0&&dl(e.ttlMs)?e.ttlMs:US}function WS(e){return e!==void 0&&pl(e.cacheScope)?e.cacheScope:DS}function GS(e){const t={...e};return delete t[Zs],t}const KS=["elicitation/create","sampling/createMessage","roots/list"];let Dn;function hl(){if(Dn)return Dn;const e=ft();return Dn={request:{"elicitation/create":p({method:_("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":p({method:_("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":p({method:_("roots/list"),params:A({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Dn}function ml(e){return KS.includes(e)}function kr(e){return ml(e)?hl().request[e]:void 0}function YS(e){return ml(e)?hl().response[e]:void 0}const fl={"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},XS={"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 Sl(e){return Object.prototype.hasOwnProperty.call(fl,e)}function _l(e){return Object.prototype.hasOwnProperty.call(XS,e)}function QS(e){return Object.prototype.hasOwnProperty.call(fl,e)}function e_(e){return Sl(e)?ft().dispatchRequestSchemas[e]:void 0}function t_(e){return QS(e)?ft().dispatchResultSchemas[e]:void 0}function o_(e){return _l(e)?ft().notificationSchemas2026[e]:void 0}function nn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xo(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};const o=e.safeParse(t);return o.success?{ok:!0,value:o.data}:{ok:!1,reason:"invalid",message:String(o.error)}}const n_={ok:!1,reason:"not-in-era"},r_=[mo,ur];function s_(e,t){let o=t,n=!1;const r=()=>(n||(o={...o},n=!0),o),i=t.tools;e==="tools/list"&&Array.isArray(i)&&i.some(a=>nn(a)&&"execution"in a)&&(r().tools=i.map(a=>{if(!nn(a)||!("execution"in a))return a;const u={...a};return delete u.execution,u}));const s=t.capabilities;if(nn(s)&&"tasks"in s){const a={...s};delete a.tasks,r().capabilities=a}return o}const Fs={era:"2026-07-28",hasRequestMethod:Sl,hasNotificationMethod:_l,hasInputRequestMethod:e=>kr(e)!==void 0,validateRequest:(e,t)=>Xo(e_(e),t),validateResult:(e,t)=>Xo(t_(e),t),validateNotification:(e,t)=>Xo(o_(e),t),validateInputRequest:(e,t)=>Xo(kr(e),t),validateInputResponse:(e,t)=>Xo(YS(e),t),samplingResultVariant:()=>n_,outboundEnvelope(e){return{[mo]:e.protocolVersion,[cs]:e.clientInfo,[ur]:e.clientCapabilities,...e.logLevel!==void 0&&{[us]:e.logLevel}}},validateEnvelopeMeta(e){const t=[];for(const n of r_)n in e||t.push({key:n,problem:"missing"});const o=ft().RequestMetaEnvelopeSchema.safeParse(e);if(!o.success)for(const n of o.error.issues){const r=n.path.map(String),i=r.length>0?r.join("."):"_meta";r.length===1&&t.some(s=>s.key===i&&s.problem==="missing")||t.push({key:i,problem:n.message})}return t},projectCallToolResult:e=>sl(e),inputRequestSchema:kr,decodeResult(e,t){if(!nn(t))return{kind:"invalid",error:new q(C.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};const o=t.resultType;if(o===void 0)return{kind:"invalid",error:new q(C.InvalidResult,`Invalid result for ${e}: missing required resultType — 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 o!="string")return{kind:"invalid",error:new q(C.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:o})};if(o==="input_required"){const s=t.inputRequests,a=nn(s)?s:{},u=t.requestState,l=t._meta===void 0?void 0:ft().ResultMetaSchema.safeParse(t._meta),d=l?.success?l.data:void 0;return Object.keys(a).length===0&&typeof u!="string"?{kind:"invalid",error:new q(C.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:a,...typeof u=="string"&&{requestState:u},...d!==void 0&&{_meta:d}}}if(o!=="complete")return{kind:"invalid",error:new q(C.UnsupportedResultType,`Unsupported result type '${o}' for ${e}`,{resultType:o,method:e})};const n=i_(),r=Object.hasOwn(n,e)?n[e]:void 0;if(r!==void 0){const s=r.safeParse(t);if(!s.success)return{kind:"invalid",error:new q(C.InvalidResult,`Invalid result for ${e}: ${s.error}`,{method:e})}}const i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,o){return JS(FS(e,VS(e,s_(e,t))),o)},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)";const t=ft().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(o=>o.message).join("; ")}`}};let Zn;function i_(){if(Zn)return Zn;const e=ft();return Zn={"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},Zn}const Hs="2026-07-28";function St(e){return e!==void 0&&mt(e)?Fs:Ds}function qi(e){return e.revision!==void 0?St(e.revision).era:e.era==="modern"?Fs.era:Ds.era}function Pr(e){return gl.some(t=>t.hasRequestMethod(e))}function Er(e){return gl.some(t=>t.hasNotificationMethod(e))}function Oi(e){return e==="tasks/get"||e==="tasks/cancel"}const gl=[Ds,Fs];var a_=xf({AnnotationsSchema:()=>xt,AudioContentSchema:()=>gr,BaseMetadataSchema:()=>Mt,BaseRequestParamsSchema:()=>Se,BlobResourceContentsSchema:()=>ks,BooleanSchemaSchema:()=>Os,CallToolRequestParamsSchema:()=>uu,CallToolRequestSchema:()=>lu,CallToolResultSchema:()=>Is,CancelTaskRequestSchema:()=>iS,CancelTaskResultSchema:()=>aS,CancelledNotificationParamsSchema:()=>fc,CancelledNotificationSchema:()=>_s,ClientCapabilitiesSchema:()=>vc,ClientNotificationSchema:()=>uS,ClientRequestSchema:()=>cS,ClientResultSchema:()=>lS,ClientTasksCapabilitySchema:()=>_c,CompatibilityCallToolResultSchema:()=>Kf,CompleteRequestParamsSchema:()=>Lu,CompleteRequestSchema:()=>ju,CompleteResultSchema:()=>Uu,ContentBlockSchema:()=>vr,CreateMessageRequestParamsSchema:()=>wu,CreateMessageRequestSchema:()=>Tu,CreateMessageResultSchema:()=>$u,CreateMessageResultWithToolsSchema:()=>ku,CreateTaskResultSchema:()=>Xf,CursorSchema:()=>ds,DiscoverRequestSchema:()=>Rc,DiscoverResultSchema:()=>mr,ElicitRequestFormParamsSchema:()=>br,ElicitRequestParamsSchema:()=>qu,ElicitRequestSchema:()=>Ou,ElicitRequestURLParamsSchema:()=>Iu,ElicitResultSchema:()=>zu,ElicitationCompleteNotificationParamsSchema:()=>Nu,ElicitationCompleteNotificationSchema:()=>Mu,EmbeddedResourceSchema:()=>eu,EmptyResultSchema:()=>Ss,EnumSchemaSchema:()=>Cu,GetPromptRequestParamsSchema:()=>Yc,GetPromptRequestSchema:()=>Xc,GetPromptResultSchema:()=>nu,GetTaskPayloadRequestSchema:()=>oS,GetTaskPayloadResultSchema:()=>nS,GetTaskRequestSchema:()=>eS,GetTaskResultSchema:()=>tS,IconSchema:()=>Sc,IconsSchema:()=>vo,ImageContentSchema:()=>_r,ImplementationSchema:()=>hr,InitializeRequestParamsSchema:()=>yc,InitializeRequestSchema:()=>gs,InitializeResultSchema:()=>bc,InitializedNotificationSchema:()=>ys,JSONArraySchema:()=>Jf,JSONObjectSchema:()=>ue,JSONRPCErrorResponseSchema:()=>pr,JSONRPCMessageSchema:()=>tn,JSONRPCNotificationSchema:()=>fs,JSONRPCRequestSchema:()=>ms,JSONRPCResponseSchema:()=>Bf,JSONRPCResultResponseSchema:()=>dr,JSONValueSchema:()=>fo,LegacyTitledEnumSchemaSchema:()=>zs,ListChangedOptionsBaseSchema:()=>pu,ListPromptsRequestSchema:()=>Gc,ListPromptsResultSchema:()=>Kc,ListResourceTemplatesRequestSchema:()=>Cc,ListResourceTemplatesResultSchema:()=>Ic,ListResourcesRequestSchema:()=>Pc,ListResourcesResultSchema:()=>Ec,ListRootsRequestSchema:()=>Zu,ListRootsResultSchema:()=>Vu,ListTasksRequestSchema:()=>rS,ListTasksResultSchema:()=>sS,ListToolsRequestSchema:()=>au,ListToolsResultSchema:()=>cu,LoggingLevelSchema:()=>qs,LoggingMessageNotificationParamsSchema:()=>fu,LoggingMessageNotificationSchema:()=>Su,ModelHintSchema:()=>_u,ModelPreferencesSchema:()=>gu,MultiSelectEnumSchemaSchema:()=>Eu,NotificationSchema:()=>Ee,NotificationsParamsSchema:()=>Pe,NumberSchemaSchema:()=>or,PaginatedRequestParamsSchema:()=>$c,PaginatedRequestSchema:()=>yo,PaginatedResultSchema:()=>bo,PingRequestSchema:()=>bs,PrimitiveSchemaDefinitionSchema:()=>Ls,ProgressNotificationParamsSchema:()=>Tc,ProgressNotificationSchema:()=>Rs,ProgressSchema:()=>wc,ProgressTokenSchema:()=>ls,PromptArgumentSchema:()=>Bc,PromptListChangedNotificationSchema:()=>ru,PromptMessageSchema:()=>ou,PromptReferenceSchema:()=>Au,PromptSchema:()=>Wc,ReadResourceRequestParamsSchema:()=>qc,ReadResourceRequestSchema:()=>Oc,ReadResourceResultSchema:()=>Nc,RelatedTaskMetadataSchema:()=>mc,RequestIdSchema:()=>go,RequestMetaSchema:()=>ps,RequestSchema:()=>le,ResourceContentsSchema:()=>ws,ResourceLinkSchema:()=>tu,ResourceListChangedNotificationSchema:()=>Mc,ResourceRequestParamsSchema:()=>fr,ResourceSchema:()=>Ps,ResourceTemplateReferenceSchema:()=>xu,ResourceTemplateSchema:()=>kc,ResourceUpdatedNotificationParamsSchema:()=>Hc,ResourceUpdatedNotificationSchema:()=>Jc,ResultMetaObjectSchema:()=>hs,ResultSchema:()=>de,RoleSchema:()=>Ro,RootSchema:()=>Du,RootsListChangedNotificationSchema:()=>Fu,SamplingContentSchema:()=>bu,SamplingMessageContentBlockSchema:()=>dn,SamplingMessageSchema:()=>Ru,ServerCapabilitiesSchema:()=>vs,ServerNotificationSchema:()=>pS,ServerRequestSchema:()=>dS,ServerResultSchema:()=>hS,ServerTasksCapabilitySchema:()=>gc,SetLevelRequestParamsSchema:()=>hu,SetLevelRequestSchema:()=>mu,SingleSelectEnumSchemaSchema:()=>Pu,StringSchemaSchema:()=>yr,SubscribeRequestParamsSchema:()=>zc,SubscribeRequestSchema:()=>xc,SubscriptionFilterSchema:()=>Es,SubscriptionsAcknowledgedNotificationParamsSchema:()=>Dc,SubscriptionsAcknowledgedNotificationSchema:()=>Zc,SubscriptionsListenRequestParamsSchema:()=>jc,SubscriptionsListenRequestSchema:()=>Uc,SubscriptionsListenResultMetaSchema:()=>Vc,SubscriptionsListenResultSchema:()=>Fc,TaskAugmentedRequestParamsSchema:()=>_n,TaskCreationParamsSchema:()=>Yf,TaskMetadataSchema:()=>hc,TaskSchema:()=>wo,TaskStatusNotificationParamsSchema:()=>Ju,TaskStatusNotificationSchema:()=>Qf,TaskStatusSchema:()=>Hu,TextContentSchema:()=>Sr,TextResourceContentsSchema:()=>Ts,TitledMultiSelectEnumSchemaSchema:()=>As,TitledSingleSelectEnumSchemaSchema:()=>Ms,ToolAnnotationsSchema:()=>su,ToolChoiceSchema:()=>vu,ToolExecutionSchema:()=>iu,ToolListChangedNotificationSchema:()=>du,ToolResultContentSchema:()=>yu,ToolSchema:()=>Cs,ToolUseContentSchema:()=>Qc,UnsubscribeRequestParamsSchema:()=>Ac,UnsubscribeRequestSchema:()=>Lc,UntitledMultiSelectEnumSchemaSchema:()=>xs,UntitledSingleSelectEnumSchemaSchema:()=>Ns});const Gt=e=>ms.safeParse(e).success,c_=e=>fs.safeParse(e).success,pn=e=>dr.safeParse(e).success,hn=e=>pr.safeParse(e).success,u_=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required",Ni=e=>gs.safeParse(e).success,l_=e=>ys.safeParse(e).success,d_="Mcp-Param-",Mi="x-mcp-header",p_=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,h_=new Set(["string","integer","boolean","number"]);function zi(e){const t=[],o=new Map,n=(i,s,a)=>{if(i===null||typeof i!="object")return;const u=i;if(Mi in u){if(!a||s.length===0)return`${Vn(s)}: 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)`;const d=u[Mi];if(typeof d!="string"||d.length===0)return`${Vn(s)}: x-mcp-header MUST be a non-empty string`;if(!p_.test(d))return`${Vn(s)}: x-mcp-header '${d}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;const h=typeof u.type=="string"?u.type:void 0;if(h===void 0||!h_.has(h))return`${Vn(s)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${h??"<none>"}`;const m=d.toLowerCase(),f=o.get(m);if(f!==void 0)return`x-mcp-header '${d}' is not case-insensitively unique (also declared as '${f}')`;o.set(m,d),t.push({path:s,headerName:d,type:h})}const l=u.properties;if(l!==null&&typeof l=="object")for(const[d,h]of Object.entries(l)){const m=n(h,[...s,d],a);if(m!==void 0)return m}for(const d of m_){const h=u[d];if(h===void 0)continue;const m=Array.isArray(h)?h:h!==null&&typeof h=="object"&&f_.has(d)?Object.values(h):[h];for(const f of m){const v=n(f,[...s,`<${d}>`],!1);if(v!==void 0)return v}}},r=n(e,[],!0);return r===void 0?{valid:!0,declarations:t}:{valid:!1,reason:r}}const m_=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],f_=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function Vn(e){return e.length===0?"<root>":e.join(".")}const vl="=?base64?",yl="?=";function S_(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 __(e){if(e.length===0||e.startsWith(vl)&&e.endsWith(yl)||e!==e.trim())return!0;for(let t=0;t<e.length;t++){const o=e.codePointAt(t);if(!(o===9||o>=32&&o<=126))return!0}return!1}function g_(e){const t=new TextEncoder().encode(e);let o="";for(const n of t)o+=String.fromCodePoint(n);return btoa(o)}function bl(e){return __(e)?`${vl}${g_(e)}${yl}`:e}function v_(e,t){let o=e;for(const n of t){if(o===null||typeof o!="object")return;o=o[n]}return o}function y_(e,t){const o={};for(const n of e){const r=v_(t,n.path);if(r==null)continue;const i=S_(r);i!==void 0&&(o[`${d_}${n.headerName}`]=bl(i))}return o}const Jn=-32020;D.InvalidRequest,D.UnsupportedProtocolVersion,D.InvalidParams,D.MethodNotFound,D.InvalidParams,D.MissingRequiredClientCapability;D.ParseError+"",D.InvalidRequest+"",D.MethodNotFound+"",D.UnsupportedProtocolVersion+"",D.MissingRequiredClientCapability+"";const xi={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function b_(e,t){const o=Object.hasOwn(xi,e)?xi[e]:void 0;if(o===void 0)return;const n=R_(t)?t[o]:void 0;return{field:o,value:typeof n=="string"?n:void 0}}function R_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Js(e,t){return ec(e,t)}function Qo(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function Dr(e){if(e==null)return!1;const t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}let Ai=!1;const Zr="draft-2020-12";function w_(e,t="input"){const o=e["~standard"];let n;if(o.jsonSchema)n=o.jsonSchema[t]({target:Zr});else if(o.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().");Ai||(Ai=!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=Xa(e,{target:Zr,io:t})}else throw new Error(`Schema library "${o.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:Rl(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}}function Rl(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(const t of["oneOf","anyOf","allOf"]){const o=e[t];if(Array.isArray(o)&&o.length>0)return o.every(n=>n!==null&&typeof n=="object"&&(n.type==="object"||Rl(n)))}return!1}function T_(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}async function Cr(e,t){const o=await e["~standard"].validate(t);return o.issues&&o.issues.length>0?{success:!1,error:o.issues.map(n=>T_(n)).join(", ")}:{success:!0,data:o.value}}function $_(e){const t=Xa(e,{target:Zr,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}const k_=/\\\.\\d\{(\d+)\}/;function P_(e){const t=k_.exec(e),o=[void 0,-1,0];return t&&o.push(Number(t[1])),[!1,!0].flatMap(n=>[!1,!0].flatMap(r=>o.map(i=>fn({local:n,offset:r,precision:i}))))}function E_(e,t){let o;switch(e){case"email":o=[zm()];break;case"uri":o=[rc()];break;case"date":o=[Qa()];break;case"date-time":o=P_(t);break}return new Set(o.map(n=>$_(n)).filter(n=>n!==void 0))}function C_(e,t,o){return o!=="zod"?!0:E_(e,t).has(t)}function mn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function I_(e){try{return w_(e,"input")}catch(t){const o=t instanceof Error?t.message:String(t);throw new G(D.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${o}`)}}const q_=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function Bs(e){return q_.has(e)||e.startsWith("x-")}const O_=new Set(["$schema",...Object.keys(br.shape.requestedSchema.shape)]),Li={string:Qo([yr,Ns,Ms,zs]),number:Qo([or]),integer:Qo([or]),boolean:Qo([Os]),array:Qo([xs,As])},N_=new Set(yr.shape.format.unwrap().options);function M_(e,t,o,n){if(!mn(e))return e;const r=typeof e.type=="string"&&Object.hasOwn(Li,e.type)?Li[e.type]:void 0;if(r===void 0)return e;const i={};for(const[s,a]of Object.entries(e))r.has(s)||Bs(s)?i[s]=a:s==="pattern"&&e.type==="string"&&typeof e.format=="string"?N_.has(e.format)?(typeof a!="string"||!C_(e.format,a,o))&&n.push(`${t}.${s}`):i[s]=a:n.push(`${t}.${s}`);return i}function z_(e,t){const o={},n=[];for(const[r,i]of Object.entries(e))r==="properties"&&mn(i)?o[r]=Object.fromEntries(Object.entries(i).map(([s,a])=>[s,M_(a,`properties.${s}`,t,n)])):O_.has(r)?o[r]=i:Bs(r)||n.push(r);if(n.length>0)throw new G(D.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return o}function x_(e,t){if(!mn(e.properties))return t;const o=Object.entries(e.properties).filter(([,n])=>!Js(Ls,n).success).map(([n])=>`properties.${n}`);return o.length>0?o.join(", "):t}function Vr(e,t,o=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((n,r)=>Vr(n,t[r],`${o}[${r}]`)):!mn(e)||!mn(t)?[]:Object.entries(e).flatMap(([n,r])=>{const i=o?`${o}.${n}`:n;return Object.prototype.hasOwnProperty.call(t,n)?Vr(r,t[n],i):Bs(n)?[]:[i]})}function A_(e){if(!Dr(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};const t=e.requestedSchema["~standard"].vendor,o=z_(I_(e.requestedSchema),t),n=Js(br.shape.requestedSchema,o);if(!n.success)throw new G(D.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${x_(o,n.error.message)}`);const r=Vr(o,n.data);if(r.length>0)throw new G(D.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${r.join(", ")}`);const i=(n.data.required??[]).filter(s=>!Object.prototype.hasOwnProperty.call(n.data.properties,s));if(i.length>0)throw new G(D.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:n.data}}function L_(e){const t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,o=typeof e.requestState=="string";if(!t&&!o)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}}}Object.assign(L_,{elicit(e){try{return{method:"elicitation/create",params:A_(e)}}catch(t){throw t instanceof G?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"}}});const j_=!0,U_=10,D_=250;function Z_(e){return{autoFulfill:e?.autoFulfill??j_,maxRounds:e?.maxRounds??U_}}function V_(e,t,o){const n=t!==void 0&&Object.keys(t).length>0;return!n&&o===void 0?e:{...e,...n&&{inputResponses:t},...o!==void 0&&{requestState:o}}}function F_(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function H_(e,t){return new Promise((o,n)=>{if(t?.aborted){n(t.reason instanceof q?t.reason:new q(C.RequestTimeout,String(t.reason)));return}const r=setTimeout(()=>{t?.removeEventListener("abort",i),o()},e),i=()=>{clearTimeout(r),n(t?.reason instanceof q?t.reason:new q(C.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",i,{once:!0})})}function J_(e){const t=new AbortController,o=()=>t.abort(e?.reason);return e?.addEventListener("abort",o,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:n=>t.abort(n),dispose:()=>e?.removeEventListener("abort",o)}}async function B_(e){const{config:t,method:o,originalParams:n,requestOptions:r,hooks:i,signal:s}=e,a=e.flowStartedAt??Date.now();let u=e.firstPayload,l=0;for(;;){if(l+=1,l>t.maxRounds)throw new q(C.InputRequiredRoundsExceeded,F_(o,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:u.inputRequests,...u.requestState!==void 0&&{requestState:u.requestState}}});r.onprogress?.({progress:l,message:`Fulfilling input required by '${o}' (round ${l})`});const d=Object.entries(u.inputRequests??{});let h;if(d.length>0){const v=J_(s);try{const R=await Promise.all(d.map(async([y,Z])=>{try{return[y,await i.dispatchInputRequest(y,Z,v.signal)]}catch(V){throw v.abort(V),V}}));h=Object.fromEntries(R)}finally{v.dispose()}}else await H_(D_,s);const m={...r.timeout!==void 0&&{timeout:r.timeout}};if(r.maxTotalTimeout!==void 0){const v=Date.now()-a,R=r.maxTotalTimeout-v;if(R<=0)throw new q(C.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:v});m.maxTotalTimeout=R}const f=await i.retry(V_(n,h,u.requestState),m);if(u_(f)){u={inputRequests:f.inputRequests??{},...f.requestState!==void 0&&{requestState:f.requestState}};continue}return f}}const W_=["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"],G_={IdJagTokenExchangeResponseSchema:mS,OAuthClientInformationFullSchema:el,OAuthClientInformationSchema:Qu,OAuthClientMetadataSchema:Xu,OAuthClientRegistrationErrorSchema:fS,OAuthErrorResponseSchema:Yu,OAuthMetadataSchema:js,OAuthProtectedResourceMetadataSchema:Bu,OAuthTokenRevocationRequestSchema:SS,OAuthTokensSchema:Ku,OpenIdProviderDiscoveryMetadataSchema:Gu,OpenIdProviderMetadataSchema:Wu},wl={},Tl={};function $l(e,t){const o=e.slice(0,-6);wl[o]=t,Tl[o]=n=>t.safeParse(n).success}for(const e of W_)$l(e,a_[e]);for(const[e,t]of Object.entries(G_))$l(e,t);Object.freeze(wl);const K_=Object.freeze(Tl);function Y_(e){switch(e){case"initialize":case"notifications/initialized":return St(void 0);case"server/discover":return St(Hs);default:return}}const Fr=6e4,X_=[mo,cs,ur,us],Q_=["inputResponses","requestState"];function ji(e,t){const o=e.params;if(!rn(o))return{message:e,lifted:{}};const n=o._meta,r=rn(n)?X_.filter(u=>u in n):[],i=t==="request"?Q_.filter(u=>u in o):[];if(r.length===0&&i.length===0)return{message:e,lifted:{}};const s={},a={...o};if(r.length>0&&rn(n)){const u={},l={...n};for(const d of r)u[d]=n[d],delete l[d];s.envelope=u,Object.keys(l).length>0?a._meta=l:delete a._meta}for(const u of i)u==="inputResponses"&&(s.inputResponses=a[u]),u==="requestState"&&(s.requestState=a[u]),delete a[u];return{message:{...e,params:a},lifted:s}}function Ui(e,t){const o=e.validateResult(t,void 0);if(!(!o.ok&&o.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(n){const r=e.validateResult(t,n);return r.ok?{value:r.value}:{issues:[{message:r.reason==="invalid"?r.message:`not-in-era: ${t}`}]}}}}}function Ws(e){return()=>e}const eg=Ws(void 0);var tg=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;_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Ff,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){const t=this._outboundMetaEnvelope();if(t===void 0)return e;const o=e.params??{};return{...e,params:{...o,_meta:{...t,...o._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new q(C.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,o,n,r=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:o,resetTimeoutOnProgress:r,onTimeout:n})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const o=Date.now()-t.startTime;if(t.maxTotalTimeout&&o>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new q(C.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:o});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};const o=this.transport?.onerror;this._transport.onerror=r=>{o?.(r),this._onerror(r)};const n=this._transport?.onmessage;this._transport.onmessage=(r,i)=>{n?.(r,i),pn(r)||hn(r)?this._onresponse(r):Gt(r)?this._onrequest(r,i):c_(r)?this._onnotification(r,i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(r)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(const n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();const t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;const o=new q(C.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(const n of e.values())n(o);for(const n of t.values())n.abort(o)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){const{message:o}=ji(e,"notification"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){const s=qi(t.classification);if(s!==n.era){this._onerror(new Error(`Era mismatch on inbound notification '${o.method}': classified as ${s} but this instance serves ${n.era}`));return}}if(Er(o.method)&&!n.hasNotificationMethod(o.method))return;const r=this._notificationHandlers.get(o.method),i=this.fallbackNotificationHandler;r===void 0&&i===void 0||Promise.resolve().then(()=>r===void 0?i(o):r(o,n)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){const{message:o,lifted:n}=ji(e,"request"),r=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}const i=this._transport,s=(R,y,Z)=>{const V={jsonrpc:"2.0",id:o.id,error:{code:R,message:y,...Z!==void 0&&{data:Z}}};i?.send(V).catch(I=>this._onerror(new Error(`Failed to send an error response: ${I}`)))};if(t?.classification!==void 0){const R=qi(t.classification);if(R!==r.era){this._onerror(new Error(`Era mismatch on inbound request '${o.method}': classified as ${R} but this instance serves ${r.era}`));const y=t.classification.revision??R;s(D.UnsupportedProtocolVersion,`Unsupported protocol version: ${y}`,{supported:this._supportedProtocolVersions,requested:y});return}}if(Pr(o.method)&&!r.hasRequestMethod(o.method)&&!(Oi(o.method)&&this._customSchemaRequestMethods.has(o.method))){s(D.MethodNotFound,"Method not found");return}const a=this._requestHandlers.get(o.method)??this.fallbackRequestHandler;if(a===void 0){s(D.MethodNotFound,"Method not found");return}const u=r.checkInboundEnvelope(n);if(u!==void 0){s(D.InvalidParams,u);return}const l=(R,y)=>this._notificationViaCodec(this._resolveOutboundCodec(R.method),R,{...y,relatedRequestId:o.id}),d=(R,y,Z)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(R.method),R,y,{...Z,relatedRequestId:o.id}),h=new AbortController;this._requestHandlerAbortControllers.set(o.id,h);const m=n.inputResponses===void 0?void 0:ng(n.inputResponses),f={sessionId:i?.sessionId,mcpReq:{id:o.id,method:o.method,_meta:o.params?._meta,...n.envelope!==void 0&&{envelope:n.envelope},...m!==void 0&&{inputResponses:m.accepted},...m!==void 0&&m.droppedKeys.length>0&&{droppedInputResponseKeys:m.droppedKeys},requestState:n.requestState===void 0?eg:Ws(n.requestState),signal:h.signal,send:((R,y,Z)=>{const V=this._resolveOutboundCodec(R.method);if(this._assertOutboundRequestInEra(V,R.method),Dr(y))return d(R,y,Z);const I=Ui(V,R.method);if(I===void 0)throw new TypeError(`'${R.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return d(R,I,y)}),notify:l},http:t?.authInfo?{authInfo:t.authInfo}:void 0},v=this.buildContext(f,t);Promise.resolve().then(()=>a(o,v)).then(async R=>{if(h.signal.aborted)return;let y;try{y=r.encodeResult(o.method,R,this._outboundServerInfo())}catch(V){this._onerror(new Error(`Failed to encode result for ${o.method}: ${V}`)),s(D.InternalError,"Internal error");return}const Z={result:y,jsonrpc:"2.0",id:o.id};await i?.send(Z)},async R=>{if(h.signal.aborted)return;const y=Number.isSafeInteger(R.code)?R.code:D.InternalError,Z={jsonrpc:"2.0",id:o.id,error:{code:r.encodeErrorCode(y),message:R.message??"Internal error",...R.data!==void 0&&{data:R.data}}};await i?.send(Z)}).catch(R=>this._onerror(new Error(`Failed to send response: ${R}`))).finally(()=>{this._requestHandlerAbortControllers.get(o.id)===h&&this._requestHandlerAbortControllers.delete(o.id)})}_onprogress(e){const{progressToken:t,...o}=e.params,n=Number(t),r=this._progressHandlers.get(n);if(!r){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const i=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(a);return}r(o)}_onresponse(e){const t=Number(e.id),o=this._responseHandlers.get(t);if(o===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),pn(e)?o(e):o(G.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,o){const n=this._resolveOutboundCodec(e.method);if(Dr(t))return Oi(e.method)||this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,o);this._assertOutboundRequestInEra(n,e.method);const r=Ui(n,e.method);if(r===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,r,t)}_negotiatedWireCodec(){return St(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){const t=Y_(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Pr(t)&&!e.hasRequestMethod(t))throw new q(C.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,o){const n=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,o)}_requestWithSchemaViaCodec(e,t,o,n){const{relatedRequestId:r,resumptionToken:i,onresumptiontoken:s,headers:a}=n??{},u=Date.now();let l,d;return new Promise((h,m)=>{const f=J=>{m(J)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(J){f(J);return}if(n?.signal?.aborted){const J=n.signal.reason;throw J instanceof q?J:new q(C.RequestTimeout,String(J))}const v=e.era===Hs&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,R=this._requestMessageId++;d=R;const y={...t,jsonrpc:"2.0",id:R};n?.onprogress&&(this._progressHandlers.set(R,n.onprogress),y.params={...t.params,_meta:{...t.params?._meta,progressToken:R}});const Z=this._envelopeOutbound(y);let V=!1;const I=J=>{V||(this._progressHandlers.delete(R),v===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:R,reason:String(J)}}),{relatedRequestId:r,resumptionToken:i,onresumptiontoken:s}).catch(te=>this._onerror(new Error(`Failed to send cancellation: ${te}`))):v.abort(),m(J instanceof q?J:new q(C.RequestTimeout,String(J))))};this._responseHandlers.set(R,J=>{if(n?.signal?.aborted)return;if(V=!0,J instanceof Error)return m(J);let te;try{te=e.decodeResult(t.method,J.result)}catch(se){return m(se instanceof Error?se:new Error(String(se)))}if(te.kind==="invalid")return m(te.error);if(te.kind==="input_required"){if(n?.allowInputRequired===!0)return h(cg(te));const se={codec:e,request:t,resultSchema:o,options:n,flowStartedAt:u,retry:(Re,Ce)=>this._requestWithSchemaViaCodec(e,Re===void 0?{method:t.method}:{method:t.method,params:Re},o,Ce)};return h(this._resolveNonCompleteResult(te,se))}const ae=te.result;Cr(o,ae).then(se=>{se.success?h(se.data):m(new q(C.InvalidResult,`Invalid result for ${t.method}: ${se.error}`))},m)}),l=()=>I(n?.signal?.reason),n?.signal?.addEventListener("abort",l,{once:!0});const L=n?.timeout??Fr,W=()=>I(new q(C.RequestTimeout,"Request timed out",{timeout:L}));this._setupTimeout(R,L,n?.maxTotalTimeout,W,n?.resetTimeoutOnProgress??!1),this._transport.send(Z,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:s,headers:a,requestSignal:v?.signal}).catch(J=>{this._progressHandlers.delete(R),m(J)})}).finally(()=>{l&&n?.signal?.removeEventListener("abort",l),d!==void 0&&(this._responseHandlers.delete(d),this._cleanupTimeout(d))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,o){if(!this._transport)throw new q(C.NotConnected,"Not connected");if(Er(t.method)&&!e.hasNotificationMethod(t.method))throw new q(C.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);const n=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&o?.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,o).catch(r=>this._onerror(r))});return}await this._transport.send(n,o)}setRequestHandler(e,t,o){this.assertRequestHandlerCapability(e);let n;if(typeof t=="function"){if(!Pr(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);n=(r,i)=>{const s=this._negotiatedWireCodec();let a=s.validateRequest(e,r);if(!a.ok&&a.reason==="not-in-era"&&(a=s.validateInputRequest(e,r)),!a.ok)throw a.reason==="not-in-era"?new G(D.InternalError,`No wire schema for ${e} in the resolved era`):new Error(a.message);return Promise.resolve(t(a.value,i))}}else if(o)n=async(r,i)=>{const s=await Cr(t.params,{...r.params});if(!s.success)throw new G(D.InvalidParams,`Invalid params for ${e}: ${s.error}`);return o(s.data,i)};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,o){if(typeof t=="function"){if(!Er(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,r)=>{const i=r.validateNotification(e,n);if(!i.ok)throw i.reason==="not-in-era"?new G(D.InternalError,`No wire schema for ${e} in the resolved era`):new Error(i.message);return Promise.resolve(t(i.value))});return}if(!o)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async n=>{const r=await Cr(t.params,{...n.params});if(!r.success)throw new G(D.InvalidParams,`Invalid params for notification ${e}: ${r.error}`);await o(r.data,n)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function rn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function og(e,t){const o={...e};for(const n in t){const r=n,i=t[r];if(i===void 0)continue;const s=o[r];o[r]=rn(s)&&rn(i)?{...s,...i}:i}return o}function rr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ng(e){const t={},o=[];if(!rr(e))return{accepted:t,droppedKeys:o};for(const[n,r]of Object.entries(e)){if(!rr(r)||"method"in r||"result"in r){o.push(n);continue}t[n]=r}return{accepted:t,droppedKeys:o}}function Di(e){throw new q(C.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function rg(e,t,o,n,r){return{sessionId:r,mcpReq:{id:e,method:t,_meta:o?._meta,requestState:Ws(void 0),signal:n,send:(()=>Di("send")),notify:()=>Di("notify")}}}async function sg(e,t,o,n,r){if(!rr(n)||typeof n.method!="string")throw new q(C.InvalidResult,`Invalid input request '${o}': each inputRequests entry must be an embedded request object with a method`,{key:o});const i=n.method;if(!t.hasInputRequestMethod(i))throw new q(C.InvalidResult,`Invalid input request '${o}': '${i}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:o,method:i});const s=e.getRequestHandler(i);if(s===void 0)throw new q(C.CapabilityNotSupported,`Cannot fulfil input request '${o}': no handler is registered for '${i}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:o,method:i});const a=rr(n.params)?n.params:void 0;return await s({jsonrpc:"2.0",id:o,method:i,...a!==void 0&&{params:a}},e.buildContext(rg(o,i,a,r,e.sessionId)))}function ig(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function ag(e,t,o,n){const{codec:r,request:i,options:s,flowStartedAt:a}=n,u={inputRequests:o.inputRequests,...o.requestState!==void 0&&{requestState:o.requestState}},l={dispatchInputRequest:(d,h,m)=>sg(e,r,d,h,m),retry:(d,h)=>n.retry(d,ig(s,h))};return B_({config:t,method:i.method,originalParams:i.params,firstPayload:u,flowStartedAt:a,signal:s?.signal,requestOptions:{...s?.timeout!==void 0&&{timeout:s.timeout},...s?.maxTotalTimeout!==void 0&&{maxTotalTimeout:s.maxTotalTimeout},...s?.onprogress!==void 0&&{onprogress:s.onprogress}},hooks:l})}function cg(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}var ug=zf((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,o=/\\([\u000b\u0020-\u00ff])/g,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=r;function r(a){if(!a)throw new TypeError("argument string is required");var u=typeof a=="object"?i(a):a;if(typeof u!="string")throw new TypeError("argument string is required to be a string");var l=u.indexOf(";"),d=l!==-1?u.slice(0,l).trim():u.trim();if(!n.test(d))throw new TypeError("invalid media type");var h=new s(d.toLowerCase());if(l!==-1){var m,f,v;for(t.lastIndex=l;f=t.exec(u);){if(f.index!==l)throw new TypeError("invalid parameter format");l+=f[0].length,m=f[1].toLowerCase(),v=f[2],v.charCodeAt(0)===34&&(v=v.slice(1,-1),v.indexOf("\\")!==-1&&(v=v.replace(o,"$1"))),h.parameters[m]=v}if(l!==u.length)throw new TypeError("invalid parameter format")}return h}function i(a){var u;if(typeof a.getHeader=="function"?u=a.getHeader("content-type"):typeof a.headers=="object"&&(u=a.headers&&a.headers["content-type"]),typeof u!="string")throw new TypeError("content-type header is missing from object");return u}function s(a){this.parameters=Object.create(null),this.type=a}})),lg=Lf(ug());function dg(e){if(e)try{return lg.parse(e).type}catch{const t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}function Zi(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function pg(e=fetch,t){return t?async(o,n)=>e(o,{...t,...n,headers:n?.headers?{...Zi(t.headers),...Zi(n.headers)}:t.headers}):e}const hg=new Set([301,302,303,307,308]),mg=5;function fg(e,t){return e.protocol===t.protocol&&e.host===t.host?!0:e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}function kl(e,t){const o=hg.has(t.status)?t.headers?.get("location"):void 0;if(o)try{return new URL(o,e)}catch{return}}const Pl=new WeakSet;function Sg(e){const t=(o,n)=>e(o,n);return Pl.add(t),t}function Rr(e){return Pl.has(e)?e:async(t,o)=>{if(o?.redirect==="error"||o?.redirect==="manual")return e(t,o);const n=(o?.method??"GET").toUpperCase();let r=t;for(let i=0;;i++){const s=await e(r,{...o,redirect:"manual"}),a=kl(r,s);if(!a||i===mg)return s;const u=new URL(r),l=n==="GET"||s.status===307||s.status===308,d=!(a.username||a.password)||a.username===u.username&&a.password===u.password;if(!l||!d||!fg(u,a))return s;await s.text?.().catch(()=>{}),r=a}}}function _g(e,t){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";const o=kl(t.url||e,t);if(o)return o.username=o.password=o.search=o.hash="",o.protocol==="http:"&&new URL(t.url||e).protocol==="https:"?(o.protocol="https:",`Redirect from https to plain http not followed; try ${o.href} as the endpoint`):`Redirect to ${o.href} not followed; use that URL as the endpoint if it is the intended server`}function sn(e,t){const o=typeof e;if(o!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!sn(e[r],t[r]))return!1;return!0}if(o==="object"){if(!e||!t)return e===t;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const i of n)if(!sn(e[i],t[i]))return!1;return!0}return e===t}function Fe(e){return encodeURI(gg(e))}function gg(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}const vg={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},yg={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},bg={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};let Rg=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 It(e,t=Object.create(null),o=Rg,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){const i=e.$id||e.id;if(i){const s=new URL(i,o.href);s.hash.length>1?t[s.href]=e:(s.hash="",n===""?o=s:It(e,t,o))}}else if(e!==!0&&e!==!1)return t;const r=o.href+(n?"#"+n:"");if(t[r]!==void 0)throw new Error(`Duplicate schema URI "${r}".`);if(t[r]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:r}),e.$ref&&e.__absolute_ref__===void 0){const i=new URL(e.$ref,o.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){const i=new URL(e.$recursiveRef,o.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){const i=new URL("#"+e.$anchor,o.href);t[i.href]=e}for(let i in e){if(bg[i])continue;const s=`${n}/${Fe(i)}`,a=e[i];if(Array.isArray(a)){if(vg[i]){const u=a.length;for(let l=0;l<u;l++)It(a[l],t,o,`${s}/${l}`)}}else if(yg[i])for(let u in a)It(a[u],t,o,`${s}/${Fe(u)}`);else It(a,t,o,s)}return t}const wg=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Tg=[0,31,28,31,30,31,30,31,31,30,31,30,31],$g=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,kg=/^(?=.{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,Pg=/^(?:[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,Eg=/^(?:(?:[^\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,Cg=/^(?:(?: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,Ig=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,qg=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Og=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Ng=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Mg=e=>{if(e[0]==='"')return!1;const[t,o,...n]=e.split("@");return!t||!o||n.length!==0||t.length>64||o.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(o)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:o.split(".").every(r=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(r))},zg=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,xg=/^((([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,Ag=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 et(e){return e.test.bind(e)}const Vi={date:El,time:Cl.bind(void 0,!1),"date-time":Ug,duration:Ag,uri:Vg,"uri-reference":et(Pg),"uri-template":et(Eg),url:et(Cg),email:Mg,hostname:et(kg),ipv4:et(zg),ipv6:et(xg),regex:Hg,uuid:et(Ig),"json-pointer":et(qg),"json-pointer-uri-fragment":et(Og),"relative-json-pointer":et(Ng)};function Lg(e){return e%4===0&&(e%100!==0||e%400===0)}function El(e){const t=e.match(wg);if(!t)return!1;const o=+t[1],n=+t[2],r=+t[3];return n>=1&&n<=12&&r>=1&&r<=(n==2&&Lg(o)?29:Tg[n])}function Cl(e,t){const o=t.match($g);if(!o)return!1;const n=+o[1],r=+o[2],i=+o[3],s=!!o[5];return(n<=23&&r<=59&&i<=59||n==23&&r==59&&i==60)&&(!e||s)}const jg=/t|\s/i;function Ug(e){const t=e.split(jg);return t.length==2&&El(t[0])&&Cl(!0,t[1])}const Dg=/\/|:/,Zg=/^(?:[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 Dg.test(e)&&Zg.test(e)}const Fg=/[^\\]\\Z/;function Hg(e){if(Fg.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}function Jg(e){let t=0,o=e.length,n=0,r;for(;n<o;)t++,r=e.charCodeAt(n++),r>=55296&&r<=56319&&n<o&&(r=e.charCodeAt(n),(r&64512)==56320&&n++);return t}function ne(e,t,o="2019-09",n=It(t),r=!0,i=null,s="#",a="#",u=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};const l=typeof e;let d;switch(l){case"boolean":case"number":case"string":d=l;break;case"object":e===null?d="null":Array.isArray(e)?d="array":d="object";break;default:throw new Error(`Instances of "${l}" type are not supported.`)}const{$ref:h,$recursiveRef:m,$recursiveAnchor:f,type:v,const:R,enum:y,required:Z,not:V,anyOf:I,allOf:L,oneOf:W,if:J,then:te,else:ae,format:se,properties:Re,patternProperties:Ce,additionalProperties:Y,unevaluatedProperties:oe,minProperties:He,maxProperties:ze,propertyNames:Je,dependentRequired:we,dependentSchemas:xe,dependencies:Be,prefixItems:Ie,items:_e,additionalItems:nt,unevaluatedItems:rt,contains:We,minContains:he,maxContains:ge,minItems:ve,maxItems:Ze,uniqueItems:vt,minimum:qe,maximum:Oe,exclusiveMinimum:Te,exclusiveMaximum:Ae,multipleOf:Le,minLength:Ge,maxLength:Ke,pattern:ct,__absolute_ref__:Ye,__absolute_recursive_ref__:yt}=t,$=[];if(f===!0&&i===null&&(i=t),m==="#"){const x=i===null?n[yt]:i,O=`${a}/$recursiveRef`,H=ne(e,i===null?t:i,o,n,r,x,s,O,u);H.valid||$.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:O,error:"A subschema had errors."},...H.errors)}if(h!==void 0){const x=n[Ye||h];if(x===void 0){let k=`Unresolved $ref "${h}".`;throw Ye&&Ye!==h&&(k+=` Absolute URI "${Ye}".`),k+=`
65
- Known schemas:
66
- - ${Object.keys(n).join(`
67
- - `)}`,new Error(k)}const O=`${a}/$ref`,H=ne(e,x,o,n,r,i,s,O,u);if(H.valid||$.push({instanceLocation:s,keyword:"$ref",keywordLocation:O,error:"A subschema had errors."},...H.errors),o==="4"||o==="7")return{valid:$.length===0,errors:$}}if(Array.isArray(v)){let x=v.length,O=!1;for(let H=0;H<x;H++)if(d===v[H]||v[H]==="integer"&&d==="number"&&e%1===0&&e===e){O=!0;break}O||$.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${v.join('", "')}".`})}else v==="integer"?(d!=="number"||e%1||e!==e)&&$.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${v}".`}):v!==void 0&&d!==v&&$.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${v}".`});if(R!==void 0&&(d==="object"||d==="array"?sn(e,R)||$.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(R)}.`}):e!==R&&$.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(R)}.`})),y!==void 0&&(d==="object"||d==="array"?y.some(x=>sn(e,x))||$.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(x=>e===x)||$.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),V!==void 0){const x=`${a}/not`;ne(e,V,o,n,r,i,s,x).valid&&$.push({instanceLocation:s,keyword:"not",keywordLocation:x,error:'Instance matched "not" schema.'})}let Xe=[];if(I!==void 0){const x=`${a}/anyOf`,O=$.length;let H=!1;for(let k=0;k<I.length;k++){const w=I[k],U=Object.create(u),j=ne(e,w,o,n,r,f===!0?i:null,s,`${x}/${k}`,U);$.push(...j.errors),H=H||j.valid,j.valid&&Xe.push(U)}H?$.length=O:$.splice(O,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:x,error:"Instance does not match any subschemas."})}if(L!==void 0){const x=`${a}/allOf`,O=$.length;let H=!0;for(let k=0;k<L.length;k++){const w=L[k],U=Object.create(u),j=ne(e,w,o,n,r,f===!0?i:null,s,`${x}/${k}`,U);$.push(...j.errors),H=H&&j.valid,j.valid&&Xe.push(U)}H?$.length=O:$.splice(O,0,{instanceLocation:s,keyword:"allOf",keywordLocation:x,error:"Instance does not match every subschema."})}if(W!==void 0){const x=`${a}/oneOf`,O=$.length,H=W.filter((k,w)=>{const U=Object.create(u),j=ne(e,k,o,n,r,f===!0?i:null,s,`${x}/${w}`,U);return $.push(...j.errors),j.valid&&Xe.push(U),j.valid}).length;H===1?$.length=O:$.splice(O,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:x,error:`Instance does not match exactly one subschema (${H} matches).`})}if((d==="object"||d==="array")&&Object.assign(u,...Xe),J!==void 0){const x=`${a}/if`;if(ne(e,J,o,n,r,i,s,x,u).valid){if(te!==void 0){const O=ne(e,te,o,n,r,i,s,`${a}/then`,u);O.valid||$.push({instanceLocation:s,keyword:"if",keywordLocation:x,error:'Instance does not match "then" schema.'},...O.errors)}}else if(ae!==void 0){const O=ne(e,ae,o,n,r,i,s,`${a}/else`,u);O.valid||$.push({instanceLocation:s,keyword:"if",keywordLocation:x,error:'Instance does not match "else" schema.'},...O.errors)}}if(d==="object"){if(Z!==void 0)for(const k of Z)k in e||$.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${k}".`});const x=Object.keys(e);if(He!==void 0&&x.length<He&&$.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${He} properties.`}),ze!==void 0&&x.length>ze&&$.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${ze} properties.`}),Je!==void 0){const k=`${a}/propertyNames`;for(const w in e){const U=`${s}/${Fe(w)}`,j=ne(w,Je,o,n,r,i,U,k);j.valid||$.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:k,error:`Property name "${w}" does not match schema.`},...j.errors)}}if(we!==void 0){const k=`${a}/dependantRequired`;for(const w in we)if(w in e){const U=we[w];for(const j of U)j in e||$.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:k,error:`Instance has "${w}" but does not have "${j}".`})}}if(xe!==void 0)for(const k in xe){const w=`${a}/dependentSchemas`;if(k in e){const U=ne(e,xe[k],o,n,r,i,s,`${w}/${Fe(k)}`,u);U.valid||$.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:w,error:`Instance has "${k}" but does not match dependant schema.`},...U.errors)}}if(Be!==void 0){const k=`${a}/dependencies`;for(const w in Be)if(w in e){const U=Be[w];if(Array.isArray(U))for(const j of U)j in e||$.push({instanceLocation:s,keyword:"dependencies",keywordLocation:k,error:`Instance has "${w}" but does not have "${j}".`});else{const j=ne(e,U,o,n,r,i,s,`${k}/${Fe(w)}`);j.valid||$.push({instanceLocation:s,keyword:"dependencies",keywordLocation:k,error:`Instance has "${w}" but does not match dependant schema.`},...j.errors)}}}const O=Object.create(null);let H=!1;if(Re!==void 0){const k=`${a}/properties`;for(const w in Re){if(!(w in e))continue;const U=`${s}/${Fe(w)}`,j=ne(e[w],Re[w],o,n,r,i,U,`${k}/${Fe(w)}`);if(j.valid)u[w]=O[w]=!0;else if(H=r,$.push({instanceLocation:s,keyword:"properties",keywordLocation:k,error:`Property "${w}" does not match schema.`},...j.errors),H)break}}if(!H&&Ce!==void 0){const k=`${a}/patternProperties`;for(const w in Ce){const U=new RegExp(w,"u"),j=Ce[w];for(const ce in e){if(!U.test(ce))continue;const bt=`${s}/${Fe(ce)}`,Qe=ne(e[ce],j,o,n,r,i,bt,`${k}/${Fe(w)}`);Qe.valid?u[ce]=O[ce]=!0:(H=r,$.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:k,error:`Property "${ce}" matches pattern "${w}" but does not match associated schema.`},...Qe.errors))}}}if(!H&&Y!==void 0){const k=`${a}/additionalProperties`;for(const w in e){if(O[w])continue;const U=`${s}/${Fe(w)}`,j=ne(e[w],Y,o,n,r,i,U,k);j.valid?u[w]=!0:(H=r,$.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:k,error:`Property "${w}" does not match additional properties schema.`},...j.errors))}}else if(!H&&oe!==void 0){const k=`${a}/unevaluatedProperties`;for(const w in e)if(!u[w]){const U=`${s}/${Fe(w)}`,j=ne(e[w],oe,o,n,r,i,U,k);j.valid?u[w]=!0:$.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:k,error:`Property "${w}" does not match unevaluated properties schema.`},...j.errors)}}}else if(d==="array"){Ze!==void 0&&e.length>Ze&&$.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${Ze}).`}),ve!==void 0&&e.length<ve&&$.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${ve}).`});const x=e.length;let O=0,H=!1;if(Ie!==void 0){const k=`${a}/prefixItems`,w=Math.min(Ie.length,x);for(;O<w;O++){const U=ne(e[O],Ie[O],o,n,r,i,`${s}/${O}`,`${k}/${O}`);if(u[O]=!0,!U.valid&&(H=r,$.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:k,error:"Items did not match schema."},...U.errors),H))break}}if(_e!==void 0){const k=`${a}/items`;if(Array.isArray(_e)){const w=Math.min(_e.length,x);for(;O<w;O++){const U=ne(e[O],_e[O],o,n,r,i,`${s}/${O}`,`${k}/${O}`);if(u[O]=!0,!U.valid&&(H=r,$.push({instanceLocation:s,keyword:"items",keywordLocation:k,error:"Items did not match schema."},...U.errors),H))break}}else for(;O<x;O++){const w=ne(e[O],_e,o,n,r,i,`${s}/${O}`,k);if(u[O]=!0,!w.valid&&(H=r,$.push({instanceLocation:s,keyword:"items",keywordLocation:k,error:"Items did not match schema."},...w.errors),H))break}if(!H&&nt!==void 0){const w=`${a}/additionalItems`;for(;O<x;O++){const U=ne(e[O],nt,o,n,r,i,`${s}/${O}`,w);u[O]=!0,U.valid||(H=r,$.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:w,error:"Items did not match additional items schema."},...U.errors))}}}if(We!==void 0)if(x===0&&he===void 0)$.push({instanceLocation:s,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(he!==void 0&&x<he)$.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${x}) than minContains (${he}).`});else{const k=`${a}/contains`,w=$.length;let U=0;for(let j=0;j<x;j++){const ce=ne(e[j],We,o,n,r,i,`${s}/${j}`,k);ce.valid?(u[j]=!0,U++):$.push(...ce.errors)}U>=(he||0)&&($.length=w),he===void 0&&ge===void 0&&U===0?$.splice(w,0,{instanceLocation:s,keyword:"contains",keywordLocation:k,error:"Array does not contain item matching schema."}):he!==void 0&&U<he?$.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${he} items matching schema. Only ${U} items were found.`}):ge!==void 0&&U>ge&&$.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${ge} items matching schema. ${U} items were found.`})}if(!H&&rt!==void 0){const k=`${a}/unevaluatedItems`;for(;O<x;O++){if(u[O])continue;const w=ne(e[O],rt,o,n,r,i,`${s}/${O}`,k);u[O]=!0,w.valid||$.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:k,error:"Items did not match unevaluated items schema."},...w.errors)}}if(vt)for(let k=0;k<x;k++){const w=e[k],U=typeof w=="object"&&w!==null;for(let j=0;j<x;j++){if(k===j)continue;const ce=e[j];(w===ce||U&&typeof ce=="object"&&ce!==null&&sn(w,ce))&&($.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${k} and ${j}.`}),k=Number.MAX_SAFE_INTEGER,j=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(o==="4"?(qe!==void 0&&(Te===!0&&e<=qe||e<qe)&&$.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Te?"or equal to ":""} ${qe}.`}),Oe!==void 0&&(Ae===!0&&e>=Oe||e>Oe)&&$.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Ae?"or equal to ":""} ${Oe}.`})):(qe!==void 0&&e<qe&&$.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${qe}.`}),Oe!==void 0&&e>Oe&&$.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Oe}.`}),Te!==void 0&&e<=Te&&$.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${Te}.`}),Ae!==void 0&&e>=Ae&&$.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ae}.`})),Le!==void 0){const x=e%Le;Math.abs(0-x)>=11920929e-14&&Math.abs(Le-x)>=11920929e-14&&$.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Le}.`})}}else if(d==="string"){const x=Ge===void 0&&Ke===void 0?0:Jg(e);Ge!==void 0&&x<Ge&&$.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${x} < ${Ge}).`}),Ke!==void 0&&x>Ke&&$.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${x} > ${Ke}).`}),ct!==void 0&&!new RegExp(ct,"u").test(e)&&$.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),se!==void 0&&Vi[se]&&!Vi[se](e)&&$.push({instanceLocation:s,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${se}".`})}return{valid:$.length===0,errors:$}}var Bg=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",o=!0){this.schema=e,this.draft=t,this.shortCircuit=o,this.lookup=It(e)}validate(e){return ne(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),It(e,this.lookup)}},Wg=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){const t=Vf(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){const t=new Bg(e,this.draft??this._draftFor(e),this.shortcircuit);return o=>{const n=t.validate(o);return n.valid?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:n.errors.map(r=>`${r.instanceLocation}: ${r.error}`).join("; ")}}}},ro,vn=(ro=class extends Error{static[Symbol.hasInstance](t){return ot(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 ot(this,t)}constructor(t){super(t),this.name=new.target.name,gn(this,new.target)}},Object.defineProperty(ro,"mcpBrand",{value:"mcp.OAuthClientFlowError"}),ro),so,Hr=(so=class extends vn{kind;expected;received;constructor(t,o,n){super(`Issuer mismatch in ${t==="metadata"?"authorization server metadata (RFC 8414 §3.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(o)}, received ${JSON.stringify(n)}`),this.kind=t,this.expected=o,this.received=n}},Object.defineProperty(so,"mcpBrand",{value:"mcp.IssuerMismatchError"}),so),io,Gg=(io=class extends vn{status;body;submittedMetadata;constructor(t){super(`Dynamic Client Registration rejected (HTTP ${t.status}): ${t.body}`),this.status=t.status,this.body=t.body,this.submittedMetadata=t.submittedMetadata}},Object.defineProperty(io,"mcpBrand",{value:"mcp.RegistrationRejectedError"}),io),ao,Il=(ao=class extends vn{tokenEndpoint;constructor(t){super(`Refusing to send credentials to non-https token endpoint '${t}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=t}},Object.defineProperty(ao,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"}),ao),co,Bn=(co=class extends vn{constructor(t,o){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(t)} but this call resolved ${JSON.stringify(o)}; refusing to present them to a different authorization server`),this.recordedIssuer=t,this.currentIssuer=o}},Object.defineProperty(co,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"}),co),uo,Fi=(uo=class extends vn{requiredScope;resourceMetadataUrl;errorDescription;constructor(t){super(`Insufficient scope${t.requiredScope?`: required "${t.requiredScope}"`:""}`),this.requiredScope=t.requiredScope,this.resourceMetadataUrl=t.resourceMetadataUrl,this.errorDescription=t.errorDescription}},Object.defineProperty(uo,"mcpBrand",{value:"mcp.InsufficientScopeError"}),uo);function Jr(e,t,o){if(e)return typeof e.issuer!="string"?(o?.canPersistStamp!==!1&&console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."),e.issuer===void 0?e:{...e,issuer:void 0}):ql(e.issuer,t)?e:void 0}function ql(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function Kg(e){if(e==null)return!1;const t=e;return typeof t.tokens=="function"&&typeof t.clientInformation=="function"}async function Yg(e,t,o){const{resourceMetadataUrl:n,scope:r}=on(t.response);if(await Br(e,{serverUrl:t.serverUrl,resourceMetadataUrl:n,scope:r,fetchFn:t.fetchFn,...o})!=="AUTHORIZED")throw new tt}function Xg(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async o=>Yg(e,o,t)}}var lo,tt=(lo=class extends Error{static[Symbol.hasInstance](t){return ot(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 ot(this,t)}constructor(t){super(t??"Unauthorized"),this.name="UnauthorizedError",gn(this,new.target)}},Object.defineProperty(lo,"mcpBrand",{value:"mcp.UnauthorizedError"}),lo);function Gs(e){return e?.authorization_response_iss_parameter_supported===!0}function Ks({iss:e,expectedIssuer:t,issParameterSupported:o}){if(t!==void 0){if(e===void 0){if(o)throw new Hr("authorization_response",t,void 0);return}if(e!==t)throw new Hr("authorization_response",t,e)}}function Ir(...e){const t=new Set;for(const o of e)if(o)for(const n of o.split(/\s+/))n&&t.add(n);return t.size>0?[...t].join(" "):void 0}function Qg(e,t){if(!e)return!1;const o=new Set((t??"").split(/\s+/).filter(Boolean));for(const n of e.split(/\s+/))if(n&&!o.has(n))return!0;return!1}async function ev(e,t,o,n,r){if(typeof e=="string")return{authorizationCode:e,iss:t};const i=e.get("iss")??void 0,s=e.get("code");if(s)return{authorizationCode:s,iss:i};let a=(await o.discoveryState?.())?.authorizationServerMetadata;if(!a)try{a=(await xl(n,r)).authorizationServerMetadata}catch{a=void 0}if(!a)throw new tt("Authorization callback failed and the issuer could not be verified");Ks({iss:i,expectedIssuer:a.issuer,issParameterSupported:Gs(a)});const u=e.get("error");throw u?new So(u,e.get("error_description")??u,e.get("error_uri")??void 0):new tt("Authorization callback contained neither `code` nor `error`")}function tv(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const qr="code",Or="S256";function ov(e,t){const o=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&tv(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?o?"client_secret_basic":"none":o&&t.includes("client_secret_basic")?"client_secret_basic":o&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":o?"client_secret_post":"none"}function nv(e,t,o,n){const{client_id:r,client_secret:i}=t;switch(e){case"client_secret_basic":rv(r,i,o);return;case"client_secret_post":sv(r,i,n);return;case"none":iv(r,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function rv(e,t,o){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);o.set("Authorization",`Basic ${n}`)}function sv(e,t,o){o.set("client_id",e),t&&o.set("client_secret",t)}function iv(e,t){t.set("client_id",e)}function Ol(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function av(e){const t=new URL(String(e));if(t.protocol!=="https:"&&!Ol(t.hostname))throw new Il(t.href);return t}function cv(e){for(const t of e??[]){let o;try{o=new URL(t)}catch{continue}if(o.protocol!=="http:"&&o.protocol!=="https:"||Ol(o.hostname))return"native"}return"web"}function uv(e){const t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??cv(t.redirect_uris)}}async function Hi(e){const t=e instanceof Response?e.status:void 0,o=e instanceof Response?await e.text():e;try{const n=Yu.parse(JSON.parse(o));return So.fromResponse(n)}catch(n){const r=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${o}`;return new So(ht.ServerError,r)}}function Ji(e,t,o){const n=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${o} (provider implements no invalidateCredentials())`:`invalidating the stored ${o} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} — ${n}. Cause: ${JSON.stringify(t.message)}`)}async function Br(e,t){try{return await Nr(e,t)}catch(o){if(o instanceof So){if(o.code===ht.InvalidClient||o.code===ht.UnauthorizedClient)return Ji(e,o,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Nr(e,t);if(o.code===ht.InvalidGrant||o.code===ht.InvalidDpopProof)return Ji(e,o,"tokens"),await e.invalidateCredentials?.("tokens"),await Nr(e,t)}throw o}}function lv(e){const{requestedScope:t,resourceMetadata:o,authServerMetadata:n,clientMetadata:r}=e;let i=t||o?.scopes_supported?.join(" ")||r.scope;return i&&n?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&r.grant_types?.includes("refresh_token")&&(i=`${i} offline_access`),i}async function Nr(e,{serverUrl:t,authorizationCode:o,iss:n,scope:r,resourceMetadataUrl:i,fetchFn:s,skipIssuerMetadataValidation:a,forceReauthorization:u}){const l=uv(e),d=await e.discoveryState?.();let h,m,f,v,R=i;if(!R&&d?.resourceMetadataUrl&&(R=new URL(d.resourceMetadataUrl)),d?.authorizationServerUrl){if(m=d.authorizationServerUrl,h=d.resourceMetadata,f=d.authorizationServerMetadata??await zl(m,{fetchFn:s,skipIssuerValidation:a}),!h)try{h=await Nl(t,{resourceMetadataUrl:R},s)}catch(Y){if(Y instanceof TypeError)throw Y}(f!==d.authorizationServerMetadata||h!==d.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(m),resourceMetadataUrl:R?.toString(),resourceMetadata:h,authorizationServerMetadata:f})}else{const Y=await xl(t,{resourceMetadataUrl:R,fetchFn:s,skipIssuerMetadataValidation:a});m=Y.authorizationServerUrl,f=Y.authorizationServerMetadata,h=Y.resourceMetadata,v={authorizationServerUrl:String(m),resourceMetadataUrl:R?.toString(),resourceMetadata:h,authorizationServerMetadata:f}}const y=f?.issuer??String(m),Z={issuer:y};if(await e.saveAuthorizationServerUrl?.(y),o!==void 0){const Y=d?.authorizationServerMetadata?.issuer??d?.authorizationServerUrl;if(Y===void 0){if(e.saveDiscoveryState!==void 0)throw new Bn("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",y);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.")}else if(!ql(Y,y))throw new Bn(Y,y)}v&&await e.saveDiscoveryState?.(v);const V=await pv(t,e,h),I=V&&h&&!e.validateResourceURL?h.resource:V;I&&await e.saveResourceUrl?.(Ys(I));const L=lv({requestedScope:r,resourceMetadata:h,authServerMetadata:f,clientMetadata:e.clientMetadata}),W=await Promise.resolve(e.clientInformation(Z));let J=Jr(W,y,{canPersistStamp:e.saveClientInformation!==void 0});if(J===void 0&&W?.issuer&&e.saveClientInformation===void 0)throw new Bn(W.issuer,y);if(J&&J.issuer===void 0&&(J={...J,issuer:y},await e.saveClientInformation?.(J,Z)),!J){if(o!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const Y=f?.client_id_metadata_document_supported===!0,oe=e.clientMetadataUrl;if(oe&&!dv(oe))throw new So(ht.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${oe}`);if(Y&&oe)J={client_id:oe,issuer:y},await e.saveClientInformation?.(J,Z);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");J={...await Rv(m,{metadata:f,clientMetadata:l,scope:L,fetchFn:s}),issuer:y},await e.saveClientInformation(J,Z)}}const te=!e.redirectUrl;if(o!==void 0||te){o!==void 0&&Ks({iss:n,expectedIssuer:f?.issuer,issParameterSupported:Gs(f)});const Y=await bv(e,m,{metadata:f,resource:I,authorizationCode:o,iss:n,scope:L,fetchFn:s});return await e.saveTokens({...Y,issuer:y},Z),"AUTHORIZED"}let ae=Jr(await e.tokens(Z),y);if(ae&&ae.issuer===void 0&&(ae={...ae,issuer:y},await e.saveTokens(ae,Z)),ae?.refresh_token&&!u){let Y;try{Y=await yv(m,{metadata:f,clientInformation:J,refreshToken:ae.refresh_token,resource:I,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:s})}catch(oe){if(oe instanceof Il)throw oe;if(!(oe instanceof So)||oe.code===ht.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(oe instanceof Error?oe.message:String(oe))}`);else throw oe}if(Y)return await e.saveTokens({...Y,issuer:y},Z),"AUTHORIZED"}const se=e.state?await e.state():void 0,{authorizationUrl:Re,codeVerifier:Ce}=await gv(m,{metadata:f,clientInformation:J,state:se,redirectUrl:e.redirectUrl,scope:L,resource:I});return await e.saveCodeVerifier(Ce),await e.redirectToAuthorization(Re),"REDIRECT"}function dv(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function pv(e,t,o){const n=_S(e);if(t.validateResourceURL)return await t.validateResourceURL(n,o?.resource);if(o){if(!gS({requestedResource:n,configuredResource:o.resource}))throw new Error(`Protected resource ${o.resource} does not match expected ${n} (or origin)`);return new URL(o.resource)}}const hv=new Set(["bearer","dpop"]);function on(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[o,n]=t.split(" ");if(!o||!hv.has(o.toLowerCase())||!n)return{};const r=Fn(e,"resource_metadata")||void 0;let i;if(r)try{i=new URL(r)}catch{}const s=Fn(e,"scope")||void 0,a=Fn(e,"error")||void 0,u=Fn(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:s,error:a,errorDescription:u}}function Fn(e,t){const o=e.headers.get("WWW-Authenticate");if(!o)return null;const n=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),r=o.match(n);if(r){const i=r[1]||r[2];if(i)return i}return null}async function Nl(e,t,o=fetch){const n=await Sv(e,"oauth-protected-resource",o,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.text?.().catch(()=>{}),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Bu.parse(await n.json())}async function Ml(e,t,o=fetch){const n=Rr(o);try{return await n(e,{headers:t})}catch(r){if(!(r instanceof TypeError))throw r;if(t)try{return await n(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}function mv(e,t="",o={}){return t.endsWith("/")&&(t=t.slice(0,-1)),o.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Bi(e,t,o=fetch){return await Ml(e,{"MCP-Protocol-Version":t},o)}function fv(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}async function Sv(e,t,o,n){const r=new URL(e),i=n?.protocolVersion??as;let s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{const u=mv(t,r.pathname);s=new URL(u,n?.metadataServerUrl??r),s.search=r.search}let a=await Bi(s,i,o);return!n?.metadataUrl&&fv(a,r.pathname)&&(a=await Bi(new URL(`/.well-known/${t}`,r),i,o)),a}function _v(e){const t=typeof e=="string"?new URL(e):e,o=t.pathname!=="/",n=[];if(!o)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let r=t.pathname;return r.endsWith("/")&&(r=r.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"},{url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function zl(e,{fetchFn:t=fetch,protocolVersion:o=as,skipIssuerValidation:n=!1}={}){const r={"MCP-Protocol-Version":o,Accept:"application/json"},i=_v(e);for(const{url:s,type:a}of i){const u=await Ml(s,r,t);if(!u)continue;if(!u.ok){if(await u.text?.().catch(()=>{}),u.status<500||u.status===502)continue;throw new Error(`HTTP ${u.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}const l=a==="oauth"?js.parse(await u.json()):Gu.parse(await u.json());if(!n){const d=typeof e=="string"?e:e.href;if(!(l.issuer===d||d.endsWith("/")&&l.issuer===d.slice(0,-1)))throw new Hr("metadata",d,l.issuer)}return l}}async function xl(e,t){let o,n;try{o=await Nl(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),o.authorization_servers&&o.authorization_servers.length>0&&(n=o.authorization_servers[0])}catch(i){if(i instanceof TypeError)throw i}n||(n=String(new URL("/",e)));const r=await zl(n,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:n,authorizationServerMetadata:r,resourceMetadata:o}}function Ys(e){return typeof e=="string"?e:e.href}async function gv(e,{metadata:t,clientInformation:o,redirectUrl:n,scope:r,state:i,resource:s}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(qr))throw new Error(`Incompatible auth server: does not support response type ${qr}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Or))throw new Error(`Incompatible auth server: does not support code challenge method ${Or}`)}else a=new URL("/authorize",e);const u=await Hl(),l=u.code_verifier,d=u.code_challenge;return a.searchParams.set("response_type",qr),a.searchParams.set("client_id",o.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Or),a.searchParams.set("redirect_uri",String(n)),i&&a.searchParams.set("state",i),r&&a.searchParams.set("scope",r),r?.split(" ").includes("offline_access")&&a.searchParams.append("prompt","consent"),s&&a.searchParams.set("resource",Ys(s)),{authorizationUrl:a,codeVerifier:l}}function vv(e,t,o){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(o)})}async function Al(e,{metadata:t,tokenRequestParams:o,clientInformation:n,addClientAuthentication:r,resource:i,dpop:s,fetchFn:a}){const u=av(t?.token_endpoint??new URL("/token",e)),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&o.set("resource",Ys(i)),!r&&n&&nv(ov(n,t?.token_endpoint_auth_methods_supported??[]),n,l,o);const d=async()=>{const f=new Headers(l);return r&&await r(f,o,u,t),s&&f.set("DPoP",await s.buildProof({htm:"POST",htu:u})),Rr(a??fetch)(u,{method:"POST",headers:f,body:o})};let h=await d();if(s&&h.status===400&&(await h.clone().json().catch(()=>{}))?.error===ht.UseDpopNonce&&(s.observeNonce(h,u),h=await d()),s?.observeNonce(h,u),!h.ok)throw await Hi(h);const m=await h.json();try{return Ku.parse(tl(m))}catch(f){throw typeof m=="object"&&m!==null&&"error"in m?await Hi(JSON.stringify(m)):f}}async function yv(e,{metadata:t,clientInformation:o,refreshToken:n,resource:r,addClientAuthentication:i,dpop:s,fetchFn:a}){return{refresh_token:n,...await Al(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),clientInformation:o,addClientAuthentication:i,resource:r,dpop:s,fetchFn:a})}}async function bv(e,t,{metadata:o,resource:n,authorizationCode:r,iss:i,scope:s,fetchFn:a}={}){r!==void 0&&Ks({iss:i,expectedIssuer:o?.issuer,issParameterSupported:Gs(o)});const u=o?.issuer??String(t),l=async()=>{const f=await e.clientInformation({issuer:u}),v=Jr(f,u,{canPersistStamp:!1});if(f&&v===void 0)throw new Bn(String(f.issuer),u);return v};let d=await l();const h=s??e.clientMetadata.scope;let m;if(e.prepareTokenRequest&&(m=await e.prepareTokenRequest(h)),!m){if(!r)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");m=vv(r,await e.codeVerifier(),e.redirectUrl)}return d??=await l(),Al(t,{metadata:o,tokenRequestParams:m,clientInformation:d,addClientAuthentication:e.addClientAuthentication,resource:n,dpop:await e.dpop?.(),fetchFn:a})}async function Rv(e,{metadata:t,clientMetadata:o,scope:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);const s={...o,...n===void 0?{}:{scope:n}},a=await Rr(r??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok)throw new Gg({status:a.status,body:await a.text(),submittedMetadata:s});return el.parse(tl(await a.json()))}const Hn=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]);var wv=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(Mr(e))}set(e,t){const o=Mr(e),n=Hn.has(e.method),r=!this._entries.has(o);if(!n&&r&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(const s of this._entries.keys())if(!Hn.has(s.slice(0,s.indexOf("\0")))){this._entries.delete(s),this._cappedSize--;break}}const i=++this._stamp;return this._entries.set(o,{...t,stamp:i}),r&&!n&&this._cappedSize++,i}delete(e){this._entries.delete(Mr(e))&&!Hn.has(e.method)&&this._cappedSize--}evict(e){const t=`${e}\0`,o=Hn.has(e);for(const n of this._entries.keys())n.startsWith(t)&&(this._entries.delete(n),o||this._cappedSize--)}clear(){this._entries.clear(),this._cappedSize=0}};function Mr(e){return`${e.method}\0${JSON.stringify([e.partition??"",e.params??""])}`}function zr(e,t){return t===void 0?e:`${e}\0${t}`}const Tv=864e5;var $v=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,o=()=>{},n="",r=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=o,this._cachePartition=n,this._now=r}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){const o={method:e,params:t??""},n=this._partitionFor("private"),r=await this._store.get({...o,partition:n});if(r!==void 0)return r;const i=this._partitionFor("public");if(i===n)return;const s=await this._store.get({...o,partition:i});return s?.scope==="public"?s:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){const o=this._partitionFor("private"),n=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:o})}catch(r){this._reportError(r)}if(n!==o)try{await this._store.delete({method:e,params:t,partition:n})}catch(r){this._reportError(r)}}async evictKey(e,t){const o=zr(e,t),n=this._evictionGeneration.get(o);n!==void 0&&this._evictionGeneration.set(o,n+1),await this._deleteBoth(e,t)}captureGeneration(e,t){const o=zr(e,t),n=this._evictionGeneration.get(o)??0;return this._evictionGeneration.set(o,n),n}async write(e,t,o,n){if((this._evictionGeneration.get(zr(e,n?.params))??0)!==o)return;const r=n?.params??"",i=this._partitionFor("private"),s=this._partitionFor("public"),a=(n?.scope??"private")==="public"?s:i;try{await this._store.set({method:e,params:r,partition:a},{value:kv(t),expiresAt:n?.expiresAt,scope:n?.scope})}catch(u){this._reportError(u)}if(s!==i)try{await this._store.delete({method:e,params:r,partition:a===i?s:i})}catch(u){this._reportError(u)}}async read(e,t){const o=await this._probe(e,t);if(!(o?.expiresAt===void 0||!(o.expiresAt>this.now())))try{const n=JSON.parse(o.value);if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("cached document is not an object");return{value:n}}catch(n){this._reportError(n),await this._deleteBoth(e,t??"");return}}resetForReconnect(){this._isUserSupplied||this._store.clear(),this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){const t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){const o=this._decodeListTools(t),n=new Map;if(o!==void 0)for(const r of o.tools)n.set(r.name,r);this._toolIndex={stamp:t.stamp,byName:n}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){const o=await this._probe("tools/list");if(o===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==o.stamp){const n=this._decodeListTools(o)??{tools:[]},r=new Map;for(const i of n.tools){const s=t(i);s!==void 0&&r.set(i.name,s)}this._toolOutputValidatorIndex={stamp:o.stamp,byName:r}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{const t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every(o=>o!==null&&typeof o=="object"))throw new TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};function kv(e){let t;try{t=JSON.stringify(e)}catch(o){throw new TypeError(`cache value is not JSON-serializable: ${o instanceof Error?o.message:String(o)}`)}if(typeof t!="string")throw new TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}const Ll=Symbol.for("mcp.authSeamEscape");function Ue(e){if(typeof e=="object"&&e!==null||typeof e=="function")try{Object.defineProperty(e,Ll,{value:!0,configurable:!0})}catch{}return e}function Pv(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&e[Ll]===!0}const Ev=-32022,Cv=new Set([-32001,-32020,-32021]);function Iv(e,t){switch(e.kind){case"result":return qv(e.result,t);case"rpc-error":return jl(e,t);case"http-error":return Ov(e,t);case"network-error":return Wi(e.error,t);case"unusable-reply":return{kind:"error",error:new q(C.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${Ul(e.error)})`,{cause:e.error},{cause:e.error})};case"auth-required":return{kind:"error",error:e.error};case"closed":return t.transportKind==="stdio"?{kind:"legacy"}:Wi(new Error("Connection closed during the version negotiation probe"),t);case"timeout":return t.transportKind==="stdio"?{kind:"legacy"}:{kind:"error",error:new q(C.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function qv(e,t){const o=St(Hs).validateResult("server/discover",e);if(!o.ok)return{kind:"legacy"};const n=o.value.supportedVersions,r=t.clientModernVersions.find(i=>n.includes(i));return r!==void 0?{kind:"modern",version:r,discover:o.value}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:new Vs({supported:[...n],requested:t.requestedVersion})}}function jl(e,t){const{code:o,message:n,data:r}=e;if(o===Ev){const i=Mv(r);if(i===void 0)return{kind:"legacy"};const s=new Vs({supported:i,requested:zv(r)??t.requestedVersion},n),a=nr(i),u=t.clientModernVersions.find(l=>a.includes(l));return u!==void 0?{kind:"corrective",version:u,error:s}:a.length>0?{kind:"error",error:s}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:s}}return Cv.has(o)?{kind:"legacy"}:{kind:"legacy"}}function Ov(e,t){if(e.status===401||e.status===403){const n=e.status===403;return{kind:"error",error:new st(n?C.ClientHttpForbidden:C.ClientHttpAuthentication,`Version negotiation failed: ${n?"the server denied access (HTTP 403)":"the server requires authorization (HTTP 401)"}`,{status:e.status,statusText:e.statusText,text:e.body})}}if(e.status>=500)return{kind:"error",error:new st(C.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};const o=xv(e.body);return o!==void 0?jl(o,t):{kind:"legacy"}}function Wi(e,t){return t.environment==="browser"&&Nv(e)?{kind:"legacy"}:{kind:"error",error:new q(C.EraNegotiationFailed,`Version negotiation probe failed: ${Ul(e)}`,{cause:e},{cause:e})}}function Nv(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function Ul(e){return e instanceof Error?e.message:String(e)}function Mv(e){if(typeof e!="object"||e===null)return;const t=e.supported;if(!(!Array.isArray(t)||t.length===0||!t.every(o=>typeof o=="string")))return t}function zv(e){if(typeof e!="object"||e===null)return;const t=e.requested;return typeof t=="string"?t:void 0}function xv(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null)return;const o=t.error;if(typeof o!="object"||o===null)return;const{code:n,message:r,data:i}=o;if(typeof n=="number")return{code:n,message:typeof r=="string"?r:"",data:i}}const Av="legacy";function Lv(e,t){const o=e?.mode??Av;if(o==="legacy")return{kind:"legacy"};const n=e?.probe??{};if(typeof o=="object"){if(!mt(o.pin))throw new TypeError(`versionNegotiation: { pin: '${o.pin}' } is not a modern protocol revision — pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:o.pin,probe:n}}const r=t?nr(t):[];return{kind:"auto",modernVersions:r.length>0?r:[...nl],fallbackAvailable:t?rl(t).length>0:!0,probe:n}}function Gi(){const e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function Ki(e){return"stderr"in e&&"pid"in e?"stdio":"http"}var jv=class Dl{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(t){this._transport=t,this._savedOnMessage=t.onmessage,this._savedOnError=t.onerror,this._savedOnClose=t.onclose}static async open(t){const o=new Dl(t);t.onmessage=n=>{const r=o._pending;if(r!==void 0&&(pn(n)||hn(n))&&n.id===r.id){o._pending=void 0,pn(n)?r.resolve({kind:"response",result:n.result}):r.resolve({kind:"response",error:n.error});return}},t.onerror=n=>{o._savedOnError?.(n)},t.onclose=()=>{const n=o._pending;n!==void 0&&(o._pending=void 0,n.resolve({kind:"closed"})),o._closeDelivered=!0,o._savedOnClose?.()};try{await t.start()}catch(n){throw o.detach(),n}return o}async exchange(t,o){const n=`server-discover-probe-${++this._probeCounter}`;return new Promise(r=>{let i=!1;const s=u=>{i||(i=!0,clearTimeout(a),this._pending?.id===n&&(this._pending=void 0),r(u))},a=setTimeout(()=>s({kind:"timeout"}),o);this._pending={id:n,resolve:s},this._transport.send(t(n)).catch(u=>s({kind:"send-error",error:u}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){const t=this._savedOnClose,o=this._transport;let n=!1;const r=()=>{if(!n){n=!0;return}t()};o.onclose=r,Wr.set(o,()=>{o.onclose===r&&(o.onclose=t)})}else this._transport.onclose=this._savedOnClose}release(){this.detach();const t=this._transport,o=t.start;let n=!0;t.start=async function(){if(n){n=!1,t.start=o;return}return o.call(t)}}};const Wr=new WeakMap;function Yi(e){const t=Wr.get(e);Wr.delete(e),t?.()}function Uv(e,t,o,n){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:St(t).outboundEnvelope({protocolVersion:t,clientInfo:o,clientCapabilities:n})}}}function Dv(e){return e instanceof q&&e.code===C.ClientHttpUnexpectedContent?!0:e instanceof Error&&e.name==="SyntaxError"}function Zv(e,t){switch(e.kind){case"response":return e.error===void 0?{kind:"result",result:e.result}:{kind:"rpc-error",...e.error};case"send-error":{const o=e.error;if(Pv(o)||o instanceof tt||o instanceof Error&&o.name==="UnauthorizedError")return{kind:"auth-required",error:o};if(o instanceof st){const n=o.data?.text;return{kind:"http-error",status:o.data.status,body:typeof n=="string"?n:void 0,statusText:o.data.statusText}}return Dv(o)?{kind:"unusable-reply",error:o}:{kind:"network-error",error:o}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function Zl(e,t){const o=e.probe.timeoutMs??t.defaultTimeoutMs,n=Math.max(0,e.probe.maxRetries??0),r=e.kind==="pin"?[e.version]:e.modernVersions,i=e.kind==="auto"&&e.fallbackAvailable,s=await jv.open(t.transport),a=async()=>{let l=r[0],d=!1,h=n;for(;;){const m=await s.exchange(R=>Uv(R,l,t.clientInfo,t.capabilities),o);if(m.kind==="timeout"&&h>0){h--;continue}const f=Zv(m,o),v=Iv(f,{clientModernVersions:r,requestedVersion:l,fallbackAvailable:i,environment:t.environment,transportKind:t.transportKind});switch(v.kind){case"modern":return{era:"modern",version:v.version,discover:v.discover};case"corrective":if(d)throw v.error;d=!0,l=v.version;continue;case"legacy":{const R=f.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new q(C.EraNegotiationFailed,R===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${R} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new q(C.EraNegotiationFailed,R===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${R} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(R!==void 0&&t.disposableProbe!==!0)throw new q(C.EraNegotiationFailed,`Version negotiation failed: ${R} (this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw v.error}}};let u;try{u=await a()}catch(l){throw s.detach(),l}return s.release(),u}function Vv(e){const t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;const o=e._serverParams;return typeof o=="object"&&o!==null&&typeof o.command=="string"?o:void 0}async function Fv(e,t,o,n){const r=t.constructor,i=new r({...o,stderr:"ignore"}),s=t.close;let a=!1,u;const l=new Promise((h,m)=>{u=()=>m(Xi())});t.close=async function(){return a=!0,u?.(),s.call(t)};let d;try{const h=Zl(e,{...n,transport:i,transportKind:"stdio",disposableProbe:!0});h.catch(()=>{}),d=await Promise.race([h,l])}finally{await Hv(i),t.close=s}if(a)throw Xi();return d}function Xi(){return new q(C.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function Hv(e){try{const t=e._dispose;await(typeof t=="function"?t.call(e):e.close())}catch{}}function Qi(e){const t=e._meta?.[Yt];return K_.Implementation(t)?t:void 0}function Wn(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const o=t,n=e.properties;for(const r of Object.keys(n)){const i=n[r];o[r]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(o[r]=i.default),o[r]!==void 0&&Wn(i,o[r])}}if(Array.isArray(e.anyOf))for(const o of e.anyOf)typeof o!="boolean"&&Wn(o,t);if(Array.isArray(e.oneOf))for(const o of e.oneOf)typeof o!="boolean"&&Wn(o,t)}}function Jv(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,o=e.url!==void 0;return{supportsFormMode:t||!t&&!o,supportsUrlMode:o}}function Bv(e){if(typeof e=="object"&&e!==null&&(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e)||e.kind==="modern"&&mr.safeParse(e.discover).success))return e;throw new q(C.EraNegotiationFailed,"connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }")}const ea={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},Wv=64;var ay=class extends tg{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){const e=new q(C.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(const t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(const e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t),this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Wg,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=Z_(t?.inputRequired),this._cache=new $v(t?.responseCacheStore??new wv,t?.responseCacheStore!==void 0,o=>this._reportStoreError(o),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??Wv,t?.listChanged&&(this._listChangedConfig=t.listChanged)}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&mt(this._negotiatedProtocolVersion)&&Gt(e))return"drop"}_outboundMetaEnvelope(){const e=this._negotiatedProtocolVersion;if(e!==void 0)return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){return this._inputRequiredDriverConfig.autoFulfill?ag({getRequestHandler:o=>this._getRequestHandler(o),buildContext:o=>this.buildContext(o,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t):Promise.reject(new q(C.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance — pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:t.request.method}))}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources","notifications/resources/list_changed",e.resources,async()=>(await this.listResources(void 0,{cacheMode:"refresh"})).resources)}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=og(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw new Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){return e==="elicitation/create"?async(o,n)=>{const r=St(this._negotiatedProtocolVersion);let i=r.validateRequest("elicitation/create",o);if(!i.ok&&i.reason==="not-in-era"&&(i=r.validateInputRequest("elicitation/create",o)),!i.ok)throw new G(i.reason==="not-in-era"?D.InternalError:D.InvalidParams,i.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${i.message}`);const{params:s}=i.value;s.mode=s.mode??"form";const{supportsFormMode:a,supportsUrlMode:u}=Jv(this._capabilities.elicitation);if(s.mode==="form"&&!a)throw new G(D.InvalidParams,"Client does not support form-mode elicitation requests");if(s.mode==="url"&&!u)throw new G(D.InvalidParams,"Client does not support URL-mode elicitation requests");const l=await t(o,n);let d=r.validateResult("elicitation/create",l);if(!d.ok&&d.reason==="not-in-era"&&(d=r.validateInputResponse("elicitation/create",l)),!d.ok)throw new G(d.reason==="not-in-era"?D.InternalError:D.InvalidParams,d.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${d.message}`);const h=d.value,m=s.mode==="form"?s.requestedSchema:void 0;if(s.mode==="form"&&h.action==="accept"&&h.content&&m&&this._capabilities.elicitation?.form?.applyDefaults)try{Wn(m,h.content)}catch{}return h}:e==="sampling/createMessage"?async(o,n)=>{const r=St(this._negotiatedProtocolVersion);let i=r.validateRequest("sampling/createMessage",o);if(!i.ok&&i.reason==="not-in-era"&&(i=r.validateInputRequest("sampling/createMessage",o)),!i.ok)throw new G(i.reason==="not-in-era"?D.InternalError:D.InvalidParams,i.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${i.message}`);const{params:s}=i.value,a=await t(o,n),u=!!(s.tools||s.toolChoice);let l=r.samplingResultVariant(u,a);if(!l.ok&&l.reason==="not-in-era"&&(l=r.validateInputResponse("sampling/createMessage",a)),!l.ok)throw new G(l.reason==="not-in-era"?D.InternalError:D.InvalidParams,l.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${l.message}`);return l.value}:t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new q(C.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,Bv(t.prior),t);const o=Lv(this._versionNegotiation,this._supportedProtocolVersionsOption);return o.kind!=="legacy"?this._connectNegotiated(e,o,t):this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){const o=this._negotiatedProtocolVersion;o!==void 0&&e.setProtocolVersion?.(o);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){const o=rl(this._supportedProtocolVersions);try{const n=o[0];if(n===void 0)throw new q(C.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");const r=await this.request({method:"initialize",params:{protocolVersion:n,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(r===void 0)throw new Error(`Server sent invalid initialize result: ${r}`);if(!o.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=r.protocolVersion,this._listChangedConfig&&this._setupListChangedHandlers(this._listChangedConfig)}catch(n){throw this.close(),n}}async _connectNegotiated(e,t,o){if(e.sessionId!==void 0){await super.connect(e);const r=this._negotiatedProtocolVersion;r!==void 0&&e.setProtocolVersion&&e.setProtocolVersion(r);return}this._resetConnectionState();let n;try{const r=Ki(e),i={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:Gi(),defaultTimeoutMs:o?.timeout??Fr},s=r==="stdio"?Vv(e):void 0;n=s===void 0?await Zl(t,{...i,transport:e,transportKind:r}):await Fv(t,e,s,i)}catch(r){throw await e.close().catch(()=>{}),Yi(e),r}if(Yi(e),await super.connect(e),n.era==="legacy"){await this._legacyHandshake(e,o);return}if(this._serverCapabilities=n.discover.capabilities,this._serverVersion=Qi(n.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=n.discover.instructions,this._discoverResult=n.discover,this._negotiatedProtocolVersion=n.version,e.setProtocolVersion&&e.setProtocolVersion(n.version),this._listChangedConfig){const r=this._listChangedConfig,i=this._serverCapabilities,s={...r.tools&&i?.tools?.listChanged&&{tools:r.tools},...r.prompts&&i?.prompts?.listChanged&&{prompts:r.prompts},...r.resources&&i?.resources?.listChanged&&{resources:r.resources}};let a=!0;try{this._setupListChangedHandlers(s)}catch(l){a=!1,this.onerror?.(l instanceof Error?l:new Error(String(l)))}const u=a?{...s.tools&&{toolsListChanged:!0},...s.prompts&&{promptsListChanged:!0},...s.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(u).length>0){const l=new AbortController,d=()=>l.abort(o?.signal?.reason);o?.signal?.aborted&&d(),o?.signal?.addEventListener("abort",d);try{this._autoOpenedSubscription=await this.listen(u,{timeout:o?.timeout,signal:l.signal})}catch(h){if(o?.signal?.aborted)throw await this.close().catch(()=>{}),h;this.onerror?.(h instanceof Error?h:new Error(String(h)))}finally{o?.signal?.removeEventListener("abort",d)}}}}async _connectFromPrior(e,t,o){if(t.kind==="legacy")return this._connectPlainLegacy(e,o);const n=t.discover;this._resetConnectionState();const r=this._supportedProtocolVersionsOption,i=(r&&nr(r).length>0?nr(r):nl).find(s=>n.supportedVersions.includes(s));if(i===void 0)throw new q(C.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(e),this._discoverResult=n,this._serverCapabilities=n.capabilities,this._serverVersion=Qi(n),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=n.instructions,this._negotiatedProtocolVersion=i,e.setProtocolVersion?.(i),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(s){this.onerror?.(s instanceof Error?s:new Error(String(s)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){const t=this._serverVersion;return t!==void 0?`${t.name}@${t.version}`:e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){const e=this._negotiatedProtocolVersion;if(e!==void 0)return mt(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new q(C.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new q(C.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new q(C.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new q(C.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new q(C.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new q(C.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new q(C.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new q(C.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new q(C.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new q(C.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){const t=await this._requestWithSchema({method:"server/discover"},mr,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:"completion/complete",params:e},t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:"prompts/list",params:e},t);const o=await this._serveFromCache("prompts/list",void 0,t);return o!==void 0?o:this._listAllPages("prompts/list",e,t,n=>n.prompts)}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(e?.cursor!==void 0)return this.request({method:"resources/list",params:e},t);const o=await this._serveFromCache("resources/list",void 0,t);return o!==void 0?o:this._listAllPages("resources/list",e,t,n=>n.resources)}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:"resources/templates/list",params:e},t);const o=await this._serveFromCache("resources/templates/list",void 0,t);return o!==void 0?o:this._listAllPages("resources/templates/list",e,t,n=>n.resourceTemplates)}async _listAllPages(e,t,o,n,r){const i=o?.cacheMode==="bypass",s=this._cache.captureGeneration(e),a=await this.request({method:e,...t&&{params:{...t}}},o);let u=a.nextCursor,l=a,d=1;for(;u!==void 0;){if(this._listMaxPages!==0&&d>=this._listMaxPages)throw new q(C.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});const h=await this.request({method:e,params:{...t,cursor:u}},o);if(h.nextCursor===u&&JSON.stringify(n(h))===JSON.stringify(n(l)))break;n(a).push(...n(h)),l=h,u=h.nextCursor,d++}return delete a.nextCursor,r?.(a),i||await this._cache.write(e,a,s,this._freshness(a)),a}_freshness(e,t){const o=e,n=typeof o.ttlMs=="number"?o.ttlMs:this._defaultCacheTtlMs,r=o.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,n),Tv),scope:r,params:t}}async _serveFromCache(e,t,o){if(o?.cacheMode==="bypass"||o?.cacheMode==="refresh")return;const n=await this._cache.read(e,t).catch(r=>{this._reportStoreError(r)});if(n!==void 0){if(o?.signal?.aborted){const r=o.signal.reason;throw r instanceof q?r:new q(C.RequestTimeout,String(r))}return n.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:new Error(String(e)))}_compileOutputValidator(e){if(e.outputSchema)try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){const o=t??await this._cache.toolDefinition(e);return o===void 0?void 0:zi(o.inputSchema)}async readResource(e,t){const o=await this._serveFromCache("resources/read",e.uri,t);if(o!==void 0)return o;const n=this._cache.captureGeneration("resources/read",e.uri),r=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){const i=this._freshness(r,e.uri);i.expiresAt>this._cache.now()?await this._cache.write("resources/read",r,n,i):t?.cacheMode==="refresh"&&await this._cache.evictKey("resources/read",e.uri)}return r}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},t)}async listen(e,t){if(this.transport===void 0)throw new q(C.NotConnected,"Not connected");const o=this._negotiatedProtocolVersion;if(o===void 0||!mt(o))throw new q(C.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${o??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:o});if(t?.signal?.aborted){const I=t.signal.reason;throw I instanceof q?I:new q(C.RequestTimeout,String(I))}const n=new AbortController,r=`listen:${this._nextListenId++}`;let i="opening",s,a,u,l;const d=new Promise((I,L)=>{u=I,l=L});let h;const m=new Promise(I=>{h=I}),f=I=>{if(i==="closed")return;const L=i==="opening";if(s!==void 0&&(clearTimeout(s),s=void 0),"ack"in I){i="open",u(I.ack);return}i="closed",a!==void 0&&t?.signal?.removeEventListener("abort",a),this._listenState.delete(r),n.abort(),h(I.cause),L&&l(I.error??new q(C.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},v=async()=>{n.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:r}}).catch(()=>{})},R=async()=>{i!=="closed"&&(f({cause:"local"}),await v())};this._listenState.set(r,{settle:f});const y=t?.timeout??Fr;if(s=setTimeout(()=>{f({cause:"remote",error:new q(C.RequestTimeout,"subscriptions/listen ack timed out",{timeout:y})}),v().catch(()=>{})},y),t?.signal){const I=t.signal;a=()=>{if(i==="closed")return;const L=I.reason;f({cause:"local",error:L instanceof Error?L:new Error(String(L??"Aborted"))}),v().catch(()=>{})},I.addEventListener("abort",a,{once:!0})}const Z={jsonrpc:"2.0",id:r,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}},V=I=>{f({cause:"remote",error:I instanceof Error?I:new Error(String(I))})};try{this.transport.send(Z,{requestSignal:n.signal,onRequestStreamEnd:()=>f({cause:"remote",error:new Error("subscriptions/listen: stream ended")})}).catch(V)}catch(I){V(I)}return{honoredFilter:await d,close:R,closed:m}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){const o=Object.hasOwn(ea,e.method)?ea[e.method]:void 0;if(e.method==="notifications/resources/updated"){const n=e.params?.uri;typeof n=="string"&&this._cache.evictKey("resources/read",n)}else if(o!==void 0)for(const n of o)this._cache.evict(n);if(e.method==="notifications/subscriptions/acknowledged"){const n=e.params?._meta?.[pc],r=typeof n=="string"?this._listenState.get(n):void 0;if(r!==void 0){const i=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);r.settle({ack:i.ok?i.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){const n=e.params?.requestId,r=typeof n=="string"?this._listenState.get(n):void 0;if(r!==void 0){r.settle({cause:"remote",error:new Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){const t=e.id,o=typeof t=="string"?this._listenState.get(t):void 0;if(o!==void 0){hn(e)?o.settle({cause:"remote",error:G.fromError(e.error.code,e.error.message,e.error.data)}):o.settle({cause:"graceful",error:new q(C.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){const e=new q(C.ConnectionClosed,"Connection closed");for(const t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){const o=this.getProtocolEra()==="modern"&&Gi()!=="browser",n=async()=>{if(!o)return t;let u;try{u=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(d){this._reportStoreError(d)}if(!u?.valid||u.declarations.length===0)return t;const l=y_(u.declarations,e.arguments);return Object.keys(l).length===0?t:{...t,headers:{...t?.headers,...l}}};let r=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,u=>this._compileOutputValidator(u)).catch(u=>{this._reportStoreError(u)}):this._compileOutputValidator(t.toolDefinition);const i=()=>{if(r===void 0||r.ok)return;const u=r.compileError,l=(u instanceof Error?u.message:String(u)).slice(0,200);throw new G(D.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${l}`)};i();let s;try{s=await this.request({method:"tools/call",params:e},await n())}catch(u){const l=u instanceof G&&u.code===Jn;if(!o||!l||t?.toolDefinition!==void 0)throw u;const d={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,d).catch(h=>this._reportStoreError(h)),r=await this._cache.outputValidator(e.name,h=>this._compileOutputValidator(h)).catch(h=>{this._reportStoreError(h)}),i(),s=await this.request({method:"tools/call",params:e},await n())}const a=r!==void 0&&r.ok?r.validator:void 0;if(a){if(s.structuredContent===void 0&&!s.isError)throw new G(D.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent!==void 0&&!s.isError)try{const u=a(s.structuredContent);if(!u.valid)throw new G(D.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)}catch(u){throw u instanceof G?u:new G(D.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)}}return s}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){const n=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(n),n}const o=await this._serveFromCache("tools/list",void 0,t);return o!==void 0?o:this._listAllPages("tools/list",e,t,n=>n.tools,n=>this._excludeInvalidXMcpHeaderTools(n))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||Ki(this.transport)==="stdio")return;const t=e.tools.filter(o=>{const n=zi(o.inputSchema);return n.valid?!0:(console.warn(`[mcp-sdk] excluding tool '${o.name}' from tools/list: invalid x-mcp-header declaration — ${n.reason}`),!1)});t.length!==e.tools.length&&(e.tools=t)}_setupListChangedHandler(e,t,o,n){const r=Js(pu,o);if(!r.success)throw new Error(`Invalid ${e} listChanged options: ${r.error.message}`);if(typeof o.onChanged!="function")throw new TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:i,debounceMs:s}=r.data,{onChanged:a}=o,u=async()=>{if(!i){a(null,null);return}try{a(null,await n())}catch(d){a(d instanceof Error?d:new Error(String(d)),null)}},l=()=>{if(s){const d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);const h=setTimeout(u,s);this._listChangedDebounceTimers.set(e,h)}else u()};this.setNotificationHandler(t,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function Gv(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function Kv(e){if(e.status!==401)return!1;const t=e.headers.get("www-authenticate")??"";return Gv(t)&&/use_dpop_nonce/i.test(t)}const Yv=(e,t)=>o=>{const n=typeof e=="function"?e:()=>e;return async(r,i)=>{const s=(i?.method??"GET").toUpperCase(),a=new URL(r.toString()),u=await n();if(!u)return o(r,i);const l=async()=>{const h=await t();if(!h)return o(r,i);const m=new Headers(i?.headers),f=await u.buildProof({htm:s,htu:a,accessToken:h});return m.set("Authorization",`DPoP ${h}`),m.set("DPoP",f),o(r,{...i,headers:m})};let d=await l();return Kv(d)&&d.headers.has("dpop-nonce")&&(u.observeNonce(d,a),await d.text?.().catch(()=>{}),d=await l()),u.observeNonce(d,a),d}},Xv=e=>Yv(async()=>{try{return await e.dpop?.()}catch(t){throw Ue(t)}},async()=>{let t;try{t=await e.tokens()}catch(o){throw Ue(o)}return t?.token_type?.toLowerCase()==="dpop"?t.access_token:void 0}),Qv=1,ey={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},ty=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function ta(e,t){if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);const o=new AbortController;if(e.aborted)return o.abort(e.reason),o.signal;if(t.aborted)return o.abort(t.reason),o.signal;const n=()=>{e.removeEventListener("abort",r),t.removeEventListener("abort",i)};function r(){n(),o.abort(e.reason)}function i(){n(),o.abort(t.reason)}return e.addEventListener("abort",r,{once:!0}),t.addEventListener("abort",i,{once:!0}),o.signal}var cy=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,Kg(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=Xg(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop&&(this._fetch=Xv(t.authProvider)(t.fetch??fetch))):this._authProvider=t?.authProvider,this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=pg(t?.fetch,t?.requestInit),this._redirectPolicy==="follow"&&(this._fetchWithInit=Sg(this._fetchWithInit)),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??ey,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??Qv)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(o){throw Ue(o)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new Fi({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new Fi({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new st(C.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);const o=await this._oauthProvider.tokens(),n=Ir(this._scope,o?.scope,e.scope);this._scope=n;const r=Qg(n,o?.scope);return Br(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:n,forceReauthorization:r,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return this._redirectPolicy==="follow"?e:Rr(e)}_unfollowedRedirect(e,t){const o=this._redirectPolicy==="follow"?void 0:_g(e,t);return o&&`${o} (redirectPolicy: 'same-origin')`}async _commonHeaders(){const e=new Headers(this._requestInit?.headers||void 0);let t;try{t=await this._authProvider?.token()}catch(o){throw Ue(o)}return t&&e.set("Authorization",`Bearer ${t}`),this._sessionId&&e.set("mcp-session-id",this._sessionId),this._protocolVersion&&e.set("mcp-protocol-version",this._protocolVersion),e}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!Gt(t))return;const o=t.params?._meta?.[mo];if(typeof o!="string")return;e.set("mcp-protocol-version",o),e.set("mcp-method",t.method);const n=b_(t.method,t.params);n?.value!==void 0&&e.set("mcp-name",bl(n.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Gt(e))return!1;const t=e.params?._meta?.[mo];return typeof t=="string"&&mt(t)}async _startOrAuthSse(e,t=!1,o=0){const{resumptionToken:n,requestSignal:r}=e,i=()=>this._abortController?.signal.aborted===!0||r?.aborted===!0;try{const s=await this._commonHeaders(),a=[...s.get("accept")?.split(",").map(h=>h.trim().toLowerCase())??[],"text/event-stream"];s.set("accept",[...new Set(a)].join(", ")),n&&s.set("last-event-id",n);const u=this._abortController?.signal,l=r!==void 0&&u!==void 0?ta(u,r):r??u,d=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:s,signal:l});if(!d.ok){if(d.status===401&&this._authProvider){if(d.headers.has("www-authenticate")){const{resourceMetadataUrl:m,scope:f}=on(d);this._resourceMetadataUrl=m,this._scope=Ir(this._scope,f)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:d,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(m){throw Ue(m)}return await d.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,o)}throw await d.text?.().catch(()=>{}),Ue(t?new st(C.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:d.statusText}):new tt)}if(d.status===403){const{resourceMetadataUrl:m,scope:f,error:v,errorDescription:R}=on(d);if(v==="insufficient_scope"){const y=await d.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:f,resourceMetadataUrl:m,errorDescription:R,statusText:d.statusText,text:y},o)!=="AUTHORIZED")throw Ue(new tt);return this._startOrAuthSse(e,t,o+1)}}if(await d.text?.().catch(()=>{}),d.status===405){e.onRequestStreamEnd?.();return}const h=this._unfollowedRedirect(this._url,d)??d.statusText;throw new st(C.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${h}`,{status:d.status,statusText:d.statusText})}this._handleSseStream(d.body,e,!0)}catch(s){throw i()||this.onerror?.(s),s}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,o=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(o,e),n)}_scheduleReconnection(e,t=0){const o=this._reconnectionOptions.maxRetries;if(t>=o){this.onerror?.(new Error(`Maximum reconnection attempts (${o}) exceeded.`)),e.onRequestStreamEnd?.();return}const n=this._getNextReconnectionDelay(t),r=()=>{this._cancelReconnection=void 0,!(this._abortController?.signal.aborted||e.requestSignal?.aborted)&&this._startOrAuthSse(e).catch(i=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`));try{this._scheduleReconnection(e,t+1)}catch(s){this.onerror?.(s instanceof Error?s:new Error(String(s)))}}})};if(this._reconnectionScheduler){const i=this._reconnectionScheduler(r,n,t);this._cancelReconnection=typeof i=="function"?i:void 0}else{const i=setTimeout(r,n);this._cancelReconnection=()=>clearTimeout(i)}}_handleSseStream(e,t,o){if(!e){t.onRequestStreamEnd?.();return}const{onresumptiontoken:n,replayMessageId:r,requestSignal:i,onRequestStreamEnd:s}=t,a=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0;let u,l=!1,d=!1;(async()=>{try{const m=e.pipeThrough(new TextDecoderStream).pipeThrough(new Fl({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){const{value:f,done:v}=await m.read();if(v)break;if(f.id&&(u=f.id,l=!0,n?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{const R=tn.parse(JSON.parse(f.data));(pn(R)||hn(R))&&(d=!0,r!==void 0&&(R.id=r)),this.onmessage?.(R)}catch(R){this.onerror?.(R)}}(o||l)&&!d&&this._abortController&&!a()?this._scheduleReconnection({resumptionToken:u,onresumptiontoken:n,replayMessageId:r,requestSignal:i,onRequestStreamEnd:s},0):a()||s?.()}catch(m){if(a())return;if(this.onerror?.(new Error(`SSE stream disconnected: ${m}`)),(o||l)&&!d&&this._abortController&&!a())try{this._scheduleReconnection({resumptionToken:u,onresumptiontoken:n,replayMessageId:r,requestSignal:i,onRequestStreamEnd:s},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`)),s?.()}else s?.()}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new tt("finishAuth requires an OAuthClientProvider");const{authorizationCode:o,iss:n}=await ev(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await Br(this._oauthProvider,{serverUrl:this._url,authorizationCode:o,iss:n,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new tt("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,o,n=0){try{const{resumptionToken:r,onresumptiontoken:i}=t||{};if(r){this._startOrAuthSse({resumptionToken:r,replayMessageId:Gt(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch(y=>this.onerror?.(y));return}const s=await this._commonHeaders();this._applyBodyDerivedHeaders(s,e);const a=Array.isArray(e)?e.some(y=>Ni(y)):Ni(e);if(a&&s.delete("mcp-session-id"),t?.headers!==void 0)for(const[y,Z]of Object.entries(t.headers))ty.has(y.toLowerCase())||s.set(y,Z);s.set("content-type","application/json");const u=[...s.get("accept")?.split(",").map(y=>y.trim().toLowerCase())??[],"application/json","text/event-stream"];s.set("accept",[...new Set(u)].join(", "));const l=this._abortController?.signal,d=t?.requestSignal!==void 0&&l!==void 0?ta(l,t.requestSignal):t?.requestSignal??l,h={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:d},m=await this._redirects(this._fetch??fetch)(this._url,h);if(a&&m.ok&&(this._sessionId=m.headers.get("mcp-session-id")||void 0),!m.ok){if(m.status===401&&this._authProvider){if(m.headers.has("www-authenticate")){const{resourceMetadataUrl:V,scope:I}=on(m);this._resourceMetadataUrl=V,this._scope=Ir(this._scope,I)}if(this._authProvider.onUnauthorized&&!o){try{await this._authProvider.onUnauthorized({response:m,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(V){throw Ue(V)}return await m.text?.().catch(()=>{}),this._send(e,t,!0,n)}throw await m.text?.().catch(()=>{}),Ue(o?new st(C.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:m.statusText}):new tt)}const y=await m.text?.().catch(()=>null);if(m.status===403){const{resourceMetadataUrl:V,scope:I,error:L,errorDescription:W}=on(m);if(L==="insufficient_scope"){if(await this._stepUpAuthorize({scope:I,resourceMetadataUrl:V,errorDescription:W,statusText:m.statusText,text:y},n)!=="AUTHORIZED")throw Ue(new tt);return this._send(e,t,o,n+1)}}if(m.status===400&&typeof y=="string"&&this._isModernEnvelopedRequest(e))try{const V=tn.parse(JSON.parse(y)),I=(Array.isArray(e)?e:[e]).filter(L=>Gt(L));if(hn(V)&&I.some(L=>L.id===V.id)){this.onmessage?.(V);return}}catch{}const Z=this._unfollowedRedirect(this._url,m)??y;throw new st(C.ClientHttpNotImplemented,`Error POSTing to endpoint: ${Z}`,{status:m.status,statusText:m.statusText,text:y})}if(m.status===202){await m.text?.().catch(()=>{}),l_(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(y=>this.onerror?.(y));return}const f=(Array.isArray(e)?e:[e]).some(y=>"method"in y&&"id"in y&&y.id!==void 0),v=m.headers.get("content-type"),R=dg(v);if(f)if(R==="text/event-stream")this._handleSseStream(m.body,{onresumptiontoken:i,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(R==="application/json"){const y=await m.json(),Z=Array.isArray(y)?y.map(V=>tn.parse(V)):[tn.parse(y)];for(const V of Z)this.onmessage?.(V)}else throw await m.text?.().catch(()=>{}),new q(C.ClientHttpUnexpectedContent,`Unexpected content type: ${v}`,{contentType:v});else await m.text?.().catch(()=>{})}catch(r){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(r),r}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},o=await this._redirects(this._fetch??fetch)(this._url,t);if(await o.text?.().catch(()=>{}),!o.ok&&o.status!==405)throw new st(C.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,o)??o.statusText}`,{status:o.status,statusText:o.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};export{ay as C,cy as S,F as _,S as a,P as b,E as c,tr as d,iy as e,sy as f,ny as g,_ as l,b as n,p as o,T as r,c as s,ry as t,z as u};