@reqvire-org/ads 0.3.38 → 0.3.40

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 (64) hide show
  1. package/README.md +2 -0
  2. package/dist/bootstrap-ds/ds.config.json +2 -0
  3. package/dist/bun-compiler.mjs +1 -1
  4. package/dist/cli.mjs +7 -4
  5. package/dist/config.mjs +11 -6
  6. package/dist/mcp/build-status.mjs +27 -16
  7. package/dist/mcp/context.mjs +4 -3
  8. package/dist/mcp/drafts.mjs +127 -11
  9. package/dist/mcp/execution-results.mjs +2 -2
  10. package/dist/mcp/mutations.mjs +3 -2
  11. package/dist/mcp/preview-widget.bundle.js +2 -2
  12. package/dist/mcp/resource-loader.js +3 -2
  13. package/dist/mcp/server.mjs +15 -7
  14. package/dist/preview-failure.mjs +20 -0
  15. package/dist/preview-resources.mjs +69 -21
  16. package/dist/scenarios-compiler.mjs +7 -6
  17. package/dist/showcase/client.bundle.js +43 -41
  18. package/dist/showcase/index.html +15 -1
  19. package/dist/showcase/preview-state.js +2 -1
  20. package/dist/showcase/style.css +4 -1
  21. package/dist/skills/ads-break-ui/references/behaviors.md +8 -4
  22. package/dist/skills/ads-break-ui/references/drafts.md +26 -5
  23. package/dist/skills/ads-break-ui/references/guarded-editing.md +4 -2
  24. package/dist/skills/ads-break-ui/references/runtimes.md +4 -3
  25. package/dist/skills/ads-break-ui/references/validation.md +43 -25
  26. package/dist/skills/ads-break-ui/references/workflows.md +4 -3
  27. package/dist/skills/ads-designer/SKILL.md +7 -3
  28. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +2 -0
  29. package/dist/skills/ads-designer/references/behaviors.md +8 -4
  30. package/dist/skills/ads-designer/references/cli.md +1 -1
  31. package/dist/skills/ads-designer/references/drafts.md +26 -5
  32. package/dist/skills/ads-designer/references/guarded-editing.md +4 -2
  33. package/dist/skills/ads-designer/references/runtimes.md +4 -3
  34. package/dist/skills/ads-designer/references/validation.md +43 -25
  35. package/dist/skills/ads-designer/references/workflows.md +4 -3
  36. package/dist/skills/ads-import/references/behaviors.md +8 -4
  37. package/dist/skills/ads-import/references/cli.md +1 -1
  38. package/dist/skills/ads-import/references/drafts.md +26 -5
  39. package/dist/skills/ads-import/references/guarded-editing.md +4 -2
  40. package/dist/skills/ads-import/references/runtimes.md +4 -3
  41. package/dist/skills/ads-import/references/validation.md +43 -25
  42. package/dist/skills/ads-import/references/workflows.md +4 -3
  43. package/dist/skills/ads-motion/references/behaviors.md +8 -4
  44. package/dist/skills/ads-motion/references/drafts.md +26 -5
  45. package/dist/skills/ads-motion/references/guarded-editing.md +4 -2
  46. package/dist/skills/ads-motion/references/runtimes.md +4 -3
  47. package/dist/skills/ads-motion/references/validation.md +43 -25
  48. package/dist/skills/ads-motion/references/workflows.md +4 -3
  49. package/dist/skills/ads-port/references/behaviors.md +8 -4
  50. package/dist/skills/ads-port/references/cli.md +1 -1
  51. package/dist/skills/ads-port/references/drafts.md +26 -5
  52. package/dist/skills/ads-port/references/guarded-editing.md +4 -2
  53. package/dist/skills/ads-port/references/runtimes.md +4 -3
  54. package/dist/skills/ads-port/references/validation.md +43 -25
  55. package/dist/skills/ads-port/references/workflows.md +4 -3
  56. package/dist/units.mjs +1 -1
  57. package/dist/validation-checks.mjs +10 -5
  58. package/dist/validation.mjs +16 -31
  59. package/docs/ARCHITECTURE.md +15 -4
  60. package/docs/BEHAVIORS.md +6 -3
  61. package/docs/CHANGELOG.md +48 -12
  62. package/docs/GUIDE.md +12 -6
  63. package/docs/MCP.md +39 -18
  64. package/package.json +1 -1
@@ -1,32 +1,33 @@
1
- var{create:qS,defineProperty:pa,getOwnPropertyDescriptor:AS,getOwnPropertyNames:MS,getPrototypeOf:jS}=Object,LS=Object.prototype.hasOwnProperty,rd=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),od=(e,t)=>{let r={};for(var o in e)pa(r,o,{get:e[o],enumerable:!0});if(t)pa(r,Symbol.toStringTag,{value:"Module"});return r},US=(e,t,r,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(var n=MS(t),s=0,i=n.length,a;s<i;s++)if(a=n[s],!LS.call(e,a)&&a!==r)pa(e,a,{get:((l)=>t[l]).bind(null,a),enumerable:!(o=AS(t,a))||o.enumerable})}return e},nd=(e,t,r)=>(r=e!=null?qS(jS(e)):{},US(t||!e||!e.__esModule?pa(r,"default",{value:e,enumerable:!0}):r,e));var ZS=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),sd=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),DS=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),FS=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function id(e){return typeof e==="string"&&sd.has(e.replace(/#$/,""))}function ad(e,t){if(!("$schema"in e)||typeof e.$schema!=="string")return"2020-12";let r=e.$schema.replace(/#$/,"");if(ZS.has(r))return"2020-12";if(sd.has(r))return"2019-09";if(DS.has(r)||FS.has(r))return"draft-7";throw 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}`)}var cd,Ac=Object.freeze({status:"aborted"});function _(e,t,r){function o(a,l){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let u=i.prototype,d=Object.keys(u);for(let m=0;m<d.length;m++){let f=d[m];if(!(f in a))a[f]=u[f].bind(a)}}let n=r?.Parent??Object;class s extends n{}Object.defineProperty(s,"name",{value:e});function i(a){var l;let u=r?.Parent?new s:this;o(u,a),(l=u._zod).deferred??(l.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:o}),Object.defineProperty(i,Symbol.hasInstance,{value:(a)=>{if(r?.Parent&&a instanceof r.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(i,"name",{value:e}),i}var HS=Symbol("zod_brand");class kt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class On extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(cd=globalThis).__zod_globalConfig??(cd.__zod_globalConfig={});var io=globalThis.__zod_globalConfig;function je(e){if(e)Object.assign(io,e);return io}function ma(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function jc(e,t="|"){return e.map((r)=>Dc(r)).join(t)}function Nn(e,t){if(typeof t==="bigint")return t.toString();return t}function qn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function fa(e){return e===null||e===void 0}function ga(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ud(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-o)<n)return 0;return r-o}var ld=Symbol("evaluating");function Q(e,t,r){let o=void 0;Object.defineProperty(e,t,{get(){if(o===ld)return;if(o===void 0)o=ld,o=r();return o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function yr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Wt(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function Lc(e){return JSON.stringify(e)}function dd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Uc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ao(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var pd=qn(()=>{if(io.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function vr(e){if(ao(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(ao(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Zc(e){if(vr(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var hd=new Set(["string","number","symbol"]);function Kt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(e,t,r){let o=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)o._zod.parent=e;return o}function M(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Dc(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function md(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var fd={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function VS(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s=Wt(e._zod.def,{get shape(){let i={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;i[a]=r.shape[a]}return yr(this,"shape",i),i},checks:[]});return rt(e,s)}function JS(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=Wt(e._zod.def,{get shape(){let i={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete i[a]}return yr(this,"shape",i),i},checks:[]});return rt(e,s)}function BS(e,t){if(!vr(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=Wt(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return yr(this,"shape",s),s}});return rt(e,n)}function WS(e,t){if(!vr(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=Wt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return yr(this,"shape",o),o}});return rt(e,r)}function KS(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Wt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return yr(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return rt(e,r)}function GS(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let i=Wt(t._zod.def,{get shape(){let a=t._zod.def.shape,l={...a};if(r)for(let u in r){if(!(u in a))throw Error(`Unrecognized key: "${u}"`);if(!r[u])continue;l[u]=e?new e({type:"optional",innerType:a[u]}):a[u]}else for(let u in a)l[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return yr(this,"shape",l),l},checks:[]});return rt(t,i)}function YS(e,t,r){let o=Wt(t._zod.def,{get shape(){let n=t._zod.def.shape,s={...n};if(r)for(let i in r){if(!(i in s))throw Error(`Unrecognized key: "${i}"`);if(!r[i])continue;s[i]=new e({type:"nonoptional",innerType:n[i]})}else for(let i in n)s[i]=new e({type:"nonoptional",innerType:n[i]});return yr(this,"shape",s),s}});return rt(t,o)}function zr(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function gd(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Gt(e,t){return t.map((r)=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function ha(e){return typeof e==="string"?e:e?.message}function ot(e,t,r){let o=e.message?e.message:ha(e.inst?._zod.def?.error?.(e))??ha(t?.error?.(e))??ha(r.customError?.(e))??ha(r.localeError?.(e))??"Invalid input",{inst:n,continue:s,input:i,...a}=e;if(a.path??(a.path=[]),a.message=o,t?.reportInput)a.input=i;return a}function Sa(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Sd(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function wr(...e){let[t,r,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:o};return{...t}}var _d=(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,Nn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},_a=_("$ZodError",_d),Fc=_("$ZodError",_d,{Parent:Error});function Hc(e,t=(r)=>r.message){let r={},o=[];for(let n of e.issues)if(n.path.length>0)r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n));else o.push(t(n));return{formErrors:o,fieldErrors:r}}function Vc(e,t=(r)=>r.message){let r={_errors:[]},o=(n,s=[])=>{for(let i of n.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map((a)=>o({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")o({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")o({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(t(i));else{let l=r,u=0;while(u<a.length){let d=a[u];if(u!==a.length-1)l[d]=l[d]||{_errors:[]};else l[d]=l[d]||{_errors:[]},l[d]._errors.push(t(i));l=l[d],u++}}}};return o(e),r}var ba=(e)=>(t,r,o,n)=>{let s=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new kt;if(i.issues.length){let a=new(n?.Err??e)(i.issues.map((l)=>ot(l,s,je())));throw Uc(a,n?.callee),a}return i.value};var ya=(e)=>async(t,r,o,n)=>{let s=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)i=await i;if(i.issues.length){let a=new(n?.Err??e)(i.issues.map((l)=>ot(l,s,je())));throw Uc(a,n?.callee),a}return i.value};var An=(e)=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new kt;return s.issues.length?{success:!1,error:new(e??_a)(s.issues.map((i)=>ot(i,n,je())))}:{success:!0,data:s.value}},bd=An(Fc),Mn=(e)=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)s=await s;return s.issues.length?{success:!1,error:new e(s.issues.map((i)=>ot(i,n,je())))}:{success:!0,data:s.value}},yd=Mn(Fc),vd=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return ba(e)(t,r,n)};var zd=(e)=>(t,r,o)=>ba(e)(t,r,o);var wd=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return ya(e)(t,r,n)};var Rd=(e)=>async(t,r,o)=>ya(e)(t,r,o);var xd=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return An(e)(t,r,n)};var Pd=(e)=>(t,r,o)=>An(e)(t,r,o);var Td=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Mn(e)(t,r,n)};var Ed=(e)=>async(t,r,o)=>Mn(e)(t,r,o);var kd=/^[cC][0-9a-z]{6,}$/,$d=/^[0-9a-z]+$/,Cd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Id=/^[0-9a-vA-V]{20}$/,Od=/^[A-Za-z0-9]{27}$/,Nd=/^[a-zA-Z0-9_-]{21}$/,qd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Ad=/^([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})$/,Jc=(e)=>{if(!e)return/^([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)$/;return 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})$`)};var Md=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var QS="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function jd(){return new RegExp(QS,"u")}var Ld=/^(?:(?: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])$/,Ud=/^(([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}|:))$/;var Zd=/^((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])$/,Dd=/^(([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])$/,Fd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Bc=/^[A-Za-z0-9_-]*$/;var Hd=/^https?$/,Vd=/^\+[1-9]\d{6,14}$/,Jd="(?:(?:\\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])))",Bd=new RegExp(`^${Jd}$`);function Wd(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Kd(e){return new RegExp(`^${Wd(e)}$`)}function Gd(e){let t=Wd({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${Jd}T(?:${o})$`)}var Yd=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Xd=/^-?\d+$/,Wc=/^-?\d+(?:\.\d+)?$/,Qd=/^(?:true|false)$/i,ep=/^null$/i;var tp=/^undefined$/i;var rp=/^[^A-Z]*$/,op=/^[^a-z]*$/;var ze=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),np={number:"number",bigint:"bigint",object:"date"},Kc=_("$ZodCheckLessThan",(e,t)=>{ze.init(e,t);let r=np[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,s=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<s)if(t.inclusive)n.maximum=t.value;else n.exclusiveMaximum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value<=t.value:o.value<t.value)return;o.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Gc=_("$ZodCheckGreaterThan",(e,t)=>{ze.init(e,t);let r=np[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,s=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>s)if(t.inclusive)n.minimum=t.value;else n.exclusiveMinimum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value>=t.value:o.value>t.value)return;o.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),sp=_("$ZodCheckMultipleOf",(e,t)=>{ze.init(e,t),e._zod.onattach.push((r)=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):ud(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),ip=_("$ZodCheckNumberFormat",(e,t)=>{ze.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,s]=fd[t.format];e._zod.onattach.push((i)=>{let a=i._zod.bag;if(a.format=t.format,a.minimum=n,a.maximum=s,r)a.pattern=Xd}),e._zod.check=(i)=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});else i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}if(a<n)i.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort});if(a>s)i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var ap=_("$ZodCheckMaxLength",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!fa(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<n)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let n=o.value;if(n.length<=t.maximum)return;let i=Sa(n);o.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),cp=_("$ZodCheckMinLength",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!fa(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>n)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let n=o.value;if(n.length>=t.minimum)return;let i=Sa(n);o.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),lp=_("$ZodCheckLengthEquals",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!fa(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=(o)=>{let n=o.value,s=n.length;if(s===t.length)return;let i=Sa(n),a=s>t.length;o.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Ln=_("$ZodCheckStringFormat",(e,t)=>{var r,o;if(ze.init(e,t),e._zod.onattach.push((n)=>{let s=n._zod.bag;if(s.format=t.format,t.pattern)s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(o=e._zod).check??(o.check=()=>{})}),up=_("$ZodCheckRegex",(e,t)=>{Ln.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),dp=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=rp),Ln.init(e,t)}),pp=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=op),Ln.init(e,t)}),hp=_("$ZodCheckIncludes",(e,t)=>{ze.init(e,t);let r=Kt(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push((n)=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),e._zod.check=(n)=>{if(n.value.includes(t.includes,t.position))return;n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),mp=_("$ZodCheckStartsWith",(e,t)=>{ze.init(e,t);let r=new RegExp(`^${Kt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.startsWith(t.prefix))return;o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),fp=_("$ZodCheckEndsWith",(e,t)=>{ze.init(e,t);let r=new RegExp(`.*${Kt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.endsWith(t.suffix))return;o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var gp=_("$ZodCheckOverwrite",(e,t)=>{ze.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class Yc{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
1
+ function pa(e){if(e?.failure?.scope!=="project")return"Preview build failed";if(e.failure.phase==="validation")return"Project validation failed";if(e.failure.phase==="discovery")return"Project scenario discovery failed";return"Project preview build failed"}function od(e=[]){return e.map((t)=>{let r=t.file?t.file+(t.line?`:${t.line}`:"")+(t.column?`:${t.column}`:""):"";return(r?`${r}: `:"")+t.message}).join(`
2
+ `)}var{create:MS,defineProperty:ha,getOwnPropertyDescriptor:jS,getOwnPropertyNames:LS,getPrototypeOf:US}=Object,ZS=Object.prototype.hasOwnProperty,nd=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),sd=(e,t)=>{let r={};for(var o in e)ha(r,o,{get:e[o],enumerable:!0});if(t)ha(r,Symbol.toStringTag,{value:"Module"});return r},DS=(e,t,r,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(var n=LS(t),s=0,i=n.length,a;s<i;s++)if(a=n[s],!ZS.call(e,a)&&a!==r)ha(e,a,{get:((l)=>t[l]).bind(null,a),enumerable:!(o=jS(t,a))||o.enumerable})}return e},id=(e,t,r)=>(r=e!=null?MS(US(e)):{},DS(t||!e||!e.__esModule?ha(r,"default",{value:e,enumerable:!0}):r,e));var FS=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),ad=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),HS=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),VS=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function cd(e){return typeof e==="string"&&ad.has(e.replace(/#$/,""))}function ld(e,t){if(!("$schema"in e)||typeof e.$schema!=="string")return"2020-12";let r=e.$schema.replace(/#$/,"");if(FS.has(r))return"2020-12";if(ad.has(r))return"2019-09";if(HS.has(r)||VS.has(r))return"draft-7";throw 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}`)}var ud,Mc=Object.freeze({status:"aborted"});function _(e,t,r){function o(a,l){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let u=i.prototype,d=Object.keys(u);for(let m=0;m<d.length;m++){let f=d[m];if(!(f in a))a[f]=u[f].bind(a)}}let n=r?.Parent??Object;class s extends n{}Object.defineProperty(s,"name",{value:e});function i(a){var l;let u=r?.Parent?new s:this;o(u,a),(l=u._zod).deferred??(l.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:o}),Object.defineProperty(i,Symbol.hasInstance,{value:(a)=>{if(r?.Parent&&a instanceof r.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(i,"name",{value:e}),i}var JS=Symbol("zod_brand");class kt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class On extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(ud=globalThis).__zod_globalConfig??(ud.__zod_globalConfig={});var io=globalThis.__zod_globalConfig;function je(e){if(e)Object.assign(io,e);return io}function fa(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function Lc(e,t="|"){return e.map((r)=>Fc(r)).join(t)}function Nn(e,t){if(typeof t==="bigint")return t.toString();return t}function qn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function ga(e){return e===null||e===void 0}function Sa(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function pd(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-o)<n)return 0;return r-o}var dd=Symbol("evaluating");function Q(e,t,r){let o=void 0;Object.defineProperty(e,t,{get(){if(o===dd)return;if(o===void 0)o=dd,o=r();return o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function yr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Wt(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function Uc(e){return JSON.stringify(e)}function hd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Zc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ao(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var md=qn(()=>{if(io.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function vr(e){if(ao(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(ao(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Dc(e){if(vr(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var fd=new Set(["string","number","symbol"]);function Kt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(e,t,r){let o=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)o._zod.parent=e;return o}function M(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Fc(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function gd(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Sd={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function BS(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s=Wt(e._zod.def,{get shape(){let i={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;i[a]=r.shape[a]}return yr(this,"shape",i),i},checks:[]});return rt(e,s)}function WS(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=Wt(e._zod.def,{get shape(){let i={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete i[a]}return yr(this,"shape",i),i},checks:[]});return rt(e,s)}function KS(e,t){if(!vr(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=Wt(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return yr(this,"shape",s),s}});return rt(e,n)}function GS(e,t){if(!vr(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=Wt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return yr(this,"shape",o),o}});return rt(e,r)}function YS(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Wt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return yr(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return rt(e,r)}function XS(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let i=Wt(t._zod.def,{get shape(){let a=t._zod.def.shape,l={...a};if(r)for(let u in r){if(!(u in a))throw Error(`Unrecognized key: "${u}"`);if(!r[u])continue;l[u]=e?new e({type:"optional",innerType:a[u]}):a[u]}else for(let u in a)l[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return yr(this,"shape",l),l},checks:[]});return rt(t,i)}function QS(e,t,r){let o=Wt(t._zod.def,{get shape(){let n=t._zod.def.shape,s={...n};if(r)for(let i in r){if(!(i in s))throw Error(`Unrecognized key: "${i}"`);if(!r[i])continue;s[i]=new e({type:"nonoptional",innerType:n[i]})}else for(let i in n)s[i]=new e({type:"nonoptional",innerType:n[i]});return yr(this,"shape",s),s}});return rt(t,o)}function zr(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function _d(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Gt(e,t){return t.map((r)=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function ma(e){return typeof e==="string"?e:e?.message}function ot(e,t,r){let o=e.message?e.message:ma(e.inst?._zod.def?.error?.(e))??ma(t?.error?.(e))??ma(r.customError?.(e))??ma(r.localeError?.(e))??"Invalid input",{inst:n,continue:s,input:i,...a}=e;if(a.path??(a.path=[]),a.message=o,t?.reportInput)a.input=i;return a}function _a(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function bd(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function wr(...e){let[t,r,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:o};return{...t}}var yd=(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,Nn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ba=_("$ZodError",yd),Hc=_("$ZodError",yd,{Parent:Error});function Vc(e,t=(r)=>r.message){let r={},o=[];for(let n of e.issues)if(n.path.length>0)r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n));else o.push(t(n));return{formErrors:o,fieldErrors:r}}function Jc(e,t=(r)=>r.message){let r={_errors:[]},o=(n,s=[])=>{for(let i of n.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map((a)=>o({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")o({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")o({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(t(i));else{let l=r,u=0;while(u<a.length){let d=a[u];if(u!==a.length-1)l[d]=l[d]||{_errors:[]};else l[d]=l[d]||{_errors:[]},l[d]._errors.push(t(i));l=l[d],u++}}}};return o(e),r}var ya=(e)=>(t,r,o,n)=>{let s=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new kt;if(i.issues.length){let a=new(n?.Err??e)(i.issues.map((l)=>ot(l,s,je())));throw Zc(a,n?.callee),a}return i.value};var va=(e)=>async(t,r,o,n)=>{let s=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)i=await i;if(i.issues.length){let a=new(n?.Err??e)(i.issues.map((l)=>ot(l,s,je())));throw Zc(a,n?.callee),a}return i.value};var An=(e)=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new kt;return s.issues.length?{success:!1,error:new(e??ba)(s.issues.map((i)=>ot(i,n,je())))}:{success:!0,data:s.value}},vd=An(Hc),Mn=(e)=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)s=await s;return s.issues.length?{success:!1,error:new e(s.issues.map((i)=>ot(i,n,je())))}:{success:!0,data:s.value}},zd=Mn(Hc),wd=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return ya(e)(t,r,n)};var Rd=(e)=>(t,r,o)=>ya(e)(t,r,o);var xd=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return va(e)(t,r,n)};var Pd=(e)=>async(t,r,o)=>va(e)(t,r,o);var Td=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return An(e)(t,r,n)};var Ed=(e)=>(t,r,o)=>An(e)(t,r,o);var kd=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Mn(e)(t,r,n)};var $d=(e)=>async(t,r,o)=>Mn(e)(t,r,o);var Cd=/^[cC][0-9a-z]{6,}$/,Id=/^[0-9a-z]+$/,Od=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Nd=/^[0-9a-vA-V]{20}$/,qd=/^[A-Za-z0-9]{27}$/,Ad=/^[a-zA-Z0-9_-]{21}$/,Md=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var jd=/^([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})$/,Bc=(e)=>{if(!e)return/^([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)$/;return 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})$`)};var Ld=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var t_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Ud(){return new RegExp(t_,"u")}var Zd=/^(?:(?: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])$/,Dd=/^(([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}|:))$/;var Fd=/^((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])$/,Hd=/^(([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])$/,Vd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Wc=/^[A-Za-z0-9_-]*$/;var Jd=/^https?$/,Bd=/^\+[1-9]\d{6,14}$/,Wd="(?:(?:\\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])))",Kd=new RegExp(`^${Wd}$`);function Gd(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Yd(e){return new RegExp(`^${Gd(e)}$`)}function Xd(e){let t=Gd({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${Wd}T(?:${o})$`)}var Qd=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var ep=/^-?\d+$/,Kc=/^-?\d+(?:\.\d+)?$/,tp=/^(?:true|false)$/i,rp=/^null$/i;var op=/^undefined$/i;var np=/^[^A-Z]*$/,sp=/^[^a-z]*$/;var ze=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),ip={number:"number",bigint:"bigint",object:"date"},Gc=_("$ZodCheckLessThan",(e,t)=>{ze.init(e,t);let r=ip[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,s=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<s)if(t.inclusive)n.maximum=t.value;else n.exclusiveMaximum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value<=t.value:o.value<t.value)return;o.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Yc=_("$ZodCheckGreaterThan",(e,t)=>{ze.init(e,t);let r=ip[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,s=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>s)if(t.inclusive)n.minimum=t.value;else n.exclusiveMinimum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value>=t.value:o.value>t.value)return;o.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ap=_("$ZodCheckMultipleOf",(e,t)=>{ze.init(e,t),e._zod.onattach.push((r)=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):pd(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),cp=_("$ZodCheckNumberFormat",(e,t)=>{ze.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,s]=Sd[t.format];e._zod.onattach.push((i)=>{let a=i._zod.bag;if(a.format=t.format,a.minimum=n,a.maximum=s,r)a.pattern=ep}),e._zod.check=(i)=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});else i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}if(a<n)i.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort});if(a>s)i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var lp=_("$ZodCheckMaxLength",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!ga(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<n)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let n=o.value;if(n.length<=t.maximum)return;let i=_a(n);o.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),up=_("$ZodCheckMinLength",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!ga(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>n)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let n=o.value;if(n.length>=t.minimum)return;let i=_a(n);o.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),dp=_("$ZodCheckLengthEquals",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!ga(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=(o)=>{let n=o.value,s=n.length;if(s===t.length)return;let i=_a(n),a=s>t.length;o.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Ln=_("$ZodCheckStringFormat",(e,t)=>{var r,o;if(ze.init(e,t),e._zod.onattach.push((n)=>{let s=n._zod.bag;if(s.format=t.format,t.pattern)s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(o=e._zod).check??(o.check=()=>{})}),pp=_("$ZodCheckRegex",(e,t)=>{Ln.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),hp=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=np),Ln.init(e,t)}),mp=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=sp),Ln.init(e,t)}),fp=_("$ZodCheckIncludes",(e,t)=>{ze.init(e,t);let r=Kt(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push((n)=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),e._zod.check=(n)=>{if(n.value.includes(t.includes,t.position))return;n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),gp=_("$ZodCheckStartsWith",(e,t)=>{ze.init(e,t);let r=new RegExp(`^${Kt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.startsWith(t.prefix))return;o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Sp=_("$ZodCheckEndsWith",(e,t)=>{ze.init(e,t);let r=new RegExp(`.*${Kt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.endsWith(t.suffix))return;o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var _p=_("$ZodCheckOverwrite",(e,t)=>{ze.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class Xc{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
2
3
  `).filter((s)=>s),o=Math.min(...r.map((s)=>s.length-s.trimStart().length)),n=r.map((s)=>s.slice(o)).map((s)=>" ".repeat(this.indent*2)+s);for(let s of n)this.content.push(s)}compile(){let e=Function,t=this?.args,o=[...(this?.content??[""]).map((n)=>` ${n}`)];return new e(...t,o.join(`
3
- `))}}var _p={major:4,minor:4,patch:3};var re=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=_p;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let n of o)for(let s of n._zod.onattach)s(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(i,a,l)=>{let u=zr(i),d;for(let m of a){if(m._zod.def.when){if(gd(i))continue;if(!m._zod.def.when(i))continue}else if(u)continue;let f=i.issues.length,S=m._zod.check(i);if(S instanceof Promise&&l?.async===!1)throw new kt;if(d||S instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await S,i.issues.length===f)return;if(!u)u=zr(i,f)});else{if(i.issues.length===f)continue;if(!u)u=zr(i,f)}}if(d)return d.then(()=>i);return i},s=(i,a,l)=>{if(zr(i))return i.aborted=!0,i;let u=n(a,o,l);if(u instanceof Promise){if(l.async===!1)throw new kt;return u.then((d)=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction==="backward"){let u=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>s(d,i,a));return s(u,i,a)}let l=e._zod.parse(i,a);if(l instanceof Promise){if(a.async===!1)throw new kt;return l.then((u)=>n(u,o,a))}return n(l,o,a)}}Q(e,"~standard",()=>({validate:(n)=>{try{let s=bd(e,n);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return yd(e,n).then((i)=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),wa=_("$ZodString",(e,t)=>{re.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Yd(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ie=_("$ZodStringFormat",(e,t)=>{Ln.init(e,t),wa.init(e,t)}),Tp=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Ad),ie.init(e,t)}),Ep=_("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Jc(o))}else t.pattern??(t.pattern=Jc());ie.init(e,t)}),kp=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Md),ie.init(e,t)}),$p=_("$ZodURL",(e,t)=>{ie.init(e,t),e._zod.check=(r)=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===Hd.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let n=new URL(o);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(n.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})}if(t.normalize)r.value=n.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Cp=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=jd()),ie.init(e,t)}),Ip=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Nd),ie.init(e,t)}),Op=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=kd),ie.init(e,t)}),Np=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=$d),ie.init(e,t)}),qp=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Cd),ie.init(e,t)}),Ap=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Id),ie.init(e,t)}),Mp=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Od),ie.init(e,t)}),jp=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Gd(t)),ie.init(e,t)}),Lp=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Bd),ie.init(e,t)}),Up=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Kd(t)),ie.init(e,t)}),Zp=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=qd),ie.init(e,t)}),Dp=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ld),ie.init(e,t),e._zod.bag.format="ipv4"}),Fp=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Ud),ie.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var Hp=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Zd),ie.init(e,t)}),Vp=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Dd),ie.init(e,t),e._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[n,s]=o;if(!s)throw Error();let i=Number(s);if(`${i}`!==s)throw Error();if(i<0||i>128)throw Error();new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Jp(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Bp=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Fd),ie.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(Jp(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function e_(e){if(!Bc.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Jp(r)}var Wp=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Bc),ie.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(e_(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Kp=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Vd),ie.init(e,t)});function t_(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(t&&(!("alg"in n)||n.alg!==t))return!1;return!0}catch{return!1}}var Gp=_("$ZodJWT",(e,t)=>{ie.init(e,t),e._zod.check=(r)=>{if(t_(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Qc=_("$ZodNumber",(e,t)=>{re.init(e,t),e._zod.pattern=e._zod.bag.pattern??Wc,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(i){}let n=r.value;if(typeof n==="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let s=typeof n==="number"?Number.isNaN(n)?"NaN":!Number.isFinite(n)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...s?{received:s}:{}}),r}}),Yp=_("$ZodNumberFormat",(e,t)=>{ip.init(e,t),Qc.init(e,t)}),Xp=_("$ZodBoolean",(e,t)=>{re.init(e,t),e._zod.pattern=Qd,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(s){}let n=r.value;if(typeof n==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}});var Qp=_("$ZodUndefined",(e,t)=>{re.init(e,t),e._zod.pattern=tp,e._zod.values=new Set([void 0]),e._zod.parse=(r,o)=>{let n=r.value;if(typeof n>"u")return r;return r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),r}}),eh=_("$ZodNull",(e,t)=>{re.init(e,t),e._zod.pattern=ep,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;if(n===null)return r;return r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),th=_("$ZodAny",(e,t)=>{re.init(e,t),e._zod.parse=(r)=>r}),rh=_("$ZodUnknown",(e,t)=>{re.init(e,t),e._zod.parse=(r)=>r}),oh=_("$ZodNever",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function bp(e,t,r){if(e.issues.length)t.issues.push(...Gt(r,e.issues));t.value[r]=e.value}var nh=_("$ZodArray",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let s=[];for(let i=0;i<n.length;i++){let a=n[i],l=t.element._zod.run({value:a,issues:[]},o);if(l instanceof Promise)s.push(l.then((u)=>bp(u,r,i)));else bp(l,r,i)}if(s.length)return Promise.all(s).then(()=>r);return r}});function za(e,t,r,o,n,s){let i=r in o;if(e.issues.length){if(n&&s&&!i)return;t.issues.push(...Gt(r,e.issues))}if(!i&&!n){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(i)t.value[r]=void 0}else t.value[r]=e.value}function sh(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${o}": expected a Zod schema`);let r=md(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function ih(e,t,r,o,n,s){let i=[],a=n.keySet,l=n.catchall._zod,u=l.def.type,d=l.optin==="optional",m=l.optout==="optional";for(let f in t){if(f==="__proto__")continue;if(a.has(f))continue;if(u==="never"){i.push(f);continue}let S=l.run({value:t[f],issues:[]},o);if(S instanceof Promise)e.push(S.then((b)=>za(b,r,f,t,d,m)));else za(S,r,f,t,d,m)}if(i.length)r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s});if(!e.length)return r;return Promise.all(e).then(()=>r)}var r_=_("$ZodObject",(e,t)=>{if(re.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}let o=qn(()=>sh(t));Q(e._zod,"propValues",()=>{let a=t.shape,l={};for(let u in a){let d=a[u]._zod;if(d.values){l[u]??(l[u]=new Set);for(let m of d.values)l[u].add(m)}}return l});let n=ao,s=t.catchall,i;e._zod.parse=(a,l)=>{i??(i=o.value);let u=a.value;if(!n(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};let d=[],m=i.shape;for(let f of i.keys){let S=m[f],b=S._zod.optin==="optional",y=S._zod.optout==="optional",v=S._zod.run({value:u[f],issues:[]},l);if(v instanceof Promise)d.push(v.then((L)=>za(L,a,f,u,b,y)));else za(v,a,f,u,b,y)}if(!s)return d.length?Promise.all(d).then(()=>a):a;return ih(d,u,a,l,o.value,e)}}),ah=_("$ZodObjectJIT",(e,t)=>{r_.init(e,t);let r=e._zod.parse,o=qn(()=>sh(t)),n=(f)=>{let S=new Yc(["shape","payload","ctx"]),b=o.value,y=(x)=>{let U=Lc(x);return`shape[${U}]._zod.run({ value: input[${U}], issues: [] }, ctx)`};S.write("const input = payload.value;");let v=Object.create(null),L=0;for(let x of b.keys)v[x]=`key_${L++}`;S.write("const newResult = {};");for(let x of b.keys){let U=v[x],R=Lc(x),w=f[x],Z=w?._zod?.optin==="optional",X=w?._zod?.optout==="optional";if(S.write(`const ${U} = ${y(x)};`),Z&&X)S.write(`
4
- if (${U}.issues.length) {
4
+ `))}}var yp={major:4,minor:4,patch:3};var re=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=yp;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let n of o)for(let s of n._zod.onattach)s(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(i,a,l)=>{let u=zr(i),d;for(let m of a){if(m._zod.def.when){if(_d(i))continue;if(!m._zod.def.when(i))continue}else if(u)continue;let f=i.issues.length,S=m._zod.check(i);if(S instanceof Promise&&l?.async===!1)throw new kt;if(d||S instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await S,i.issues.length===f)return;if(!u)u=zr(i,f)});else{if(i.issues.length===f)continue;if(!u)u=zr(i,f)}}if(d)return d.then(()=>i);return i},s=(i,a,l)=>{if(zr(i))return i.aborted=!0,i;let u=n(a,o,l);if(u instanceof Promise){if(l.async===!1)throw new kt;return u.then((d)=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction==="backward"){let u=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>s(d,i,a));return s(u,i,a)}let l=e._zod.parse(i,a);if(l instanceof Promise){if(a.async===!1)throw new kt;return l.then((u)=>n(u,o,a))}return n(l,o,a)}}Q(e,"~standard",()=>({validate:(n)=>{try{let s=vd(e,n);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return zd(e,n).then((i)=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Ra=_("$ZodString",(e,t)=>{re.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Qd(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ie=_("$ZodStringFormat",(e,t)=>{Ln.init(e,t),Ra.init(e,t)}),kp=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=jd),ie.init(e,t)}),$p=_("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Bc(o))}else t.pattern??(t.pattern=Bc());ie.init(e,t)}),Cp=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ld),ie.init(e,t)}),Ip=_("$ZodURL",(e,t)=>{ie.init(e,t),e._zod.check=(r)=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===Jd.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let n=new URL(o);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(n.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})}if(t.normalize)r.value=n.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Op=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ud()),ie.init(e,t)}),Np=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ad),ie.init(e,t)}),qp=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Cd),ie.init(e,t)}),Ap=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Id),ie.init(e,t)}),Mp=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Od),ie.init(e,t)}),jp=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Nd),ie.init(e,t)}),Lp=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=qd),ie.init(e,t)}),Up=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Xd(t)),ie.init(e,t)}),Zp=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Kd),ie.init(e,t)}),Dp=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Yd(t)),ie.init(e,t)}),Fp=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Md),ie.init(e,t)}),Hp=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Zd),ie.init(e,t),e._zod.bag.format="ipv4"}),Vp=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Dd),ie.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var Jp=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Fd),ie.init(e,t)}),Bp=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Hd),ie.init(e,t),e._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[n,s]=o;if(!s)throw Error();let i=Number(s);if(`${i}`!==s)throw Error();if(i<0||i>128)throw Error();new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Wp(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Kp=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Vd),ie.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(Wp(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function r_(e){if(!Wc.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Wp(r)}var Gp=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Wc),ie.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(r_(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Yp=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Bd),ie.init(e,t)});function o_(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(t&&(!("alg"in n)||n.alg!==t))return!1;return!0}catch{return!1}}var Xp=_("$ZodJWT",(e,t)=>{ie.init(e,t),e._zod.check=(r)=>{if(o_(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var el=_("$ZodNumber",(e,t)=>{re.init(e,t),e._zod.pattern=e._zod.bag.pattern??Kc,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(i){}let n=r.value;if(typeof n==="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let s=typeof n==="number"?Number.isNaN(n)?"NaN":!Number.isFinite(n)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...s?{received:s}:{}}),r}}),Qp=_("$ZodNumberFormat",(e,t)=>{cp.init(e,t),el.init(e,t)}),eh=_("$ZodBoolean",(e,t)=>{re.init(e,t),e._zod.pattern=tp,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(s){}let n=r.value;if(typeof n==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}});var th=_("$ZodUndefined",(e,t)=>{re.init(e,t),e._zod.pattern=op,e._zod.values=new Set([void 0]),e._zod.parse=(r,o)=>{let n=r.value;if(typeof n>"u")return r;return r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),r}}),rh=_("$ZodNull",(e,t)=>{re.init(e,t),e._zod.pattern=rp,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;if(n===null)return r;return r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),oh=_("$ZodAny",(e,t)=>{re.init(e,t),e._zod.parse=(r)=>r}),nh=_("$ZodUnknown",(e,t)=>{re.init(e,t),e._zod.parse=(r)=>r}),sh=_("$ZodNever",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function vp(e,t,r){if(e.issues.length)t.issues.push(...Gt(r,e.issues));t.value[r]=e.value}var ih=_("$ZodArray",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let s=[];for(let i=0;i<n.length;i++){let a=n[i],l=t.element._zod.run({value:a,issues:[]},o);if(l instanceof Promise)s.push(l.then((u)=>vp(u,r,i)));else vp(l,r,i)}if(s.length)return Promise.all(s).then(()=>r);return r}});function wa(e,t,r,o,n,s){let i=r in o;if(e.issues.length){if(n&&s&&!i)return;t.issues.push(...Gt(r,e.issues))}if(!i&&!n){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(i)t.value[r]=void 0}else t.value[r]=e.value}function ah(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${o}": expected a Zod schema`);let r=gd(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function ch(e,t,r,o,n,s){let i=[],a=n.keySet,l=n.catchall._zod,u=l.def.type,d=l.optin==="optional",m=l.optout==="optional";for(let f in t){if(f==="__proto__")continue;if(a.has(f))continue;if(u==="never"){i.push(f);continue}let S=l.run({value:t[f],issues:[]},o);if(S instanceof Promise)e.push(S.then((b)=>wa(b,r,f,t,d,m)));else wa(S,r,f,t,d,m)}if(i.length)r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s});if(!e.length)return r;return Promise.all(e).then(()=>r)}var n_=_("$ZodObject",(e,t)=>{if(re.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}let o=qn(()=>ah(t));Q(e._zod,"propValues",()=>{let a=t.shape,l={};for(let u in a){let d=a[u]._zod;if(d.values){l[u]??(l[u]=new Set);for(let m of d.values)l[u].add(m)}}return l});let n=ao,s=t.catchall,i;e._zod.parse=(a,l)=>{i??(i=o.value);let u=a.value;if(!n(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};let d=[],m=i.shape;for(let f of i.keys){let S=m[f],b=S._zod.optin==="optional",y=S._zod.optout==="optional",v=S._zod.run({value:u[f],issues:[]},l);if(v instanceof Promise)d.push(v.then((U)=>wa(U,a,f,u,b,y)));else wa(v,a,f,u,b,y)}if(!s)return d.length?Promise.all(d).then(()=>a):a;return ch(d,u,a,l,o.value,e)}}),lh=_("$ZodObjectJIT",(e,t)=>{n_.init(e,t);let r=e._zod.parse,o=qn(()=>ah(t)),n=(f)=>{let S=new Xc(["shape","payload","ctx"]),b=o.value,y=(x)=>{let Z=Uc(x);return`shape[${Z}]._zod.run({ value: input[${Z}], issues: [] }, ctx)`};S.write("const input = payload.value;");let v=Object.create(null),U=0;for(let x of b.keys)v[x]=`key_${U++}`;S.write("const newResult = {};");for(let x of b.keys){let Z=v[x],R=Uc(x),w=f[x],D=w?._zod?.optin==="optional",X=w?._zod?.optout==="optional";if(S.write(`const ${Z} = ${y(x)};`),D&&X)S.write(`
5
+ if (${Z}.issues.length) {
5
6
  if (${R} in input) {
6
- payload.issues = payload.issues.concat(${U}.issues.map(iss => ({
7
+ payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
7
8
  ...iss,
8
9
  path: iss.path ? [${R}, ...iss.path] : [${R}]
9
10
  })));
10
11
  }
11
12
  }
12
13
 
13
- if (${U}.value === undefined) {
14
+ if (${Z}.value === undefined) {
14
15
  if (${R} in input) {
15
16
  newResult[${R}] = undefined;
16
17
  }
17
18
  } else {
18
- newResult[${R}] = ${U}.value;
19
+ newResult[${R}] = ${Z}.value;
19
20
  }
20
21
 
21
- `);else if(!Z)S.write(`
22
- const ${U}_present = ${R} in input;
23
- if (${U}.issues.length) {
24
- payload.issues = payload.issues.concat(${U}.issues.map(iss => ({
22
+ `);else if(!D)S.write(`
23
+ const ${Z}_present = ${R} in input;
24
+ if (${Z}.issues.length) {
25
+ payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
25
26
  ...iss,
26
27
  path: iss.path ? [${R}, ...iss.path] : [${R}]
27
28
  })));
28
29
  }
29
- if (!${U}_present && !${U}.issues.length) {
30
+ if (!${Z}_present && !${Z}.issues.length) {
30
31
  payload.issues.push({
31
32
  code: "invalid_type",
32
33
  expected: "nonoptional",
@@ -35,55 +36,55 @@ var{create:qS,defineProperty:pa,getOwnPropertyDescriptor:AS,getOwnPropertyNames:
35
36
  });
36
37
  }
37
38
 
38
- if (${U}_present) {
39
- if (${U}.value === undefined) {
39
+ if (${Z}_present) {
40
+ if (${Z}.value === undefined) {
40
41
  newResult[${R}] = undefined;
41
42
  } else {
42
- newResult[${R}] = ${U}.value;
43
+ newResult[${R}] = ${Z}.value;
43
44
  }
44
45
  }
45
46
 
46
47
  `);else S.write(`
47
- if (${U}.issues.length) {
48
- payload.issues = payload.issues.concat(${U}.issues.map(iss => ({
48
+ if (${Z}.issues.length) {
49
+ payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
49
50
  ...iss,
50
51
  path: iss.path ? [${R}, ...iss.path] : [${R}]
51
52
  })));
52
53
  }
53
54
 
54
- if (${U}.value === undefined) {
55
+ if (${Z}.value === undefined) {
55
56
  if (${R} in input) {
56
57
  newResult[${R}] = undefined;
57
58
  }
58
59
  } else {
59
- newResult[${R}] = ${U}.value;
60
+ newResult[${R}] = ${Z}.value;
60
61
  }
61
62
 
62
- `)}S.write("payload.value = newResult;"),S.write("return payload;");let F=S.compile();return(x,U)=>F(f,x,U)},s,i=ao,a=!io.jitless,u=a&&pd.value,d=t.catchall,m;e._zod.parse=(f,S)=>{m??(m=o.value);let b=f.value;if(!i(b))return f.issues.push({expected:"object",code:"invalid_type",input:b,inst:e}),f;if(a&&u&&S?.async===!1&&S.jitless!==!0){if(!s)s=n(t.shape);if(f=s(f,S),!d)return f;return ih([],b,f,S,m,e)}return r(f,S)}});function yp(e,t,r,o){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let n=e.filter((s)=>!zr(s));if(n.length===1)return t.value=n[0].value,n[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((s)=>s.issues.map((i)=>ot(i,o,je())))}),t}var el=_("$ZodUnion",(e,t)=>{re.init(e,t),Q(e._zod,"optin",()=>t.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),Q(e._zod,"optout",()=>t.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),Q(e._zod,"values",()=>{if(t.options.every((o)=>o._zod.values))return new Set(t.options.flatMap((o)=>Array.from(o._zod.values)));return}),Q(e._zod,"pattern",()=>{if(t.options.every((o)=>o._zod.pattern)){let o=t.options.map((n)=>n._zod.pattern);return new RegExp(`^(${o.map((n)=>ga(n.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,n)=>{if(r)return r(o,n);let s=!1,i=[];for(let a of t.options){let l=a._zod.run({value:o.value,issues:[]},n);if(l instanceof Promise)i.push(l),s=!0;else{if(l.issues.length===0)return l;i.push(l)}}if(!s)return yp(i,o,e,n);return Promise.all(i).then((a)=>yp(a,o,e,n))}});var ch=_("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,el.init(e,t);let r=e._zod.parse;Q(e._zod,"propValues",()=>{let n={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[a,l]of Object.entries(i)){if(!n[a])n[a]=new Set;for(let u of l)n[a].add(u)}}return n});let o=qn(()=>{let n=t.options,s=new Map;for(let i of n){let a=i._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let l of a){if(s.has(l))throw Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,i)}}return s});e._zod.parse=(n,s)=>{let i=n.value;if(!ao(i))return n.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),n;let a=o.value.get(i?.[t.discriminator]);if(a)return a._zod.run(n,s);if(t.unionFallback||s.direction==="backward")return r(n,s);return n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(o.value.keys()),input:i,path:[t.discriminator],inst:e}),n}}),lh=_("$ZodIntersection",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value,s=t.left._zod.run({value:n,issues:[]},o),i=t.right._zod.run({value:n,issues:[]},o);if(s instanceof Promise||i instanceof Promise)return Promise.all([s,i]).then(([l,u])=>vp(r,l,u));return vp(r,s,i)}});function Xc(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(vr(e)&&vr(t)){let r=Object.keys(t),o=Object.keys(e).filter((s)=>r.indexOf(s)!==-1),n={...e,...t};for(let s of o){let i=Xc(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};n[s]=i.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<e.length;o++){let n=e[o],s=t[o],i=Xc(n,s);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function vp(e,t,r){let o=new Map,n;for(let a of t.issues)if(a.code==="unrecognized_keys"){n??(n=a);for(let l of a.keys){if(!o.has(l))o.set(l,{});o.get(l).l=!0}}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let l of a.keys){if(!o.has(l))o.set(l,{});o.get(l).r=!0}else e.issues.push(a);let s=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&n)e.issues.push({...n,keys:s});if(zr(e))return e;let i=Xc(t.value,r.value);if(!i.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}var uh=_("$ZodRecord",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!vr(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let s=[],i=t.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){a.add(typeof u==="number"?u.toString():u);let d=t.keyType._zod.run({value:u,issues:[]},o);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((S)=>ot(S,o,je())),input:u,path:[u],inst:e});continue}let m=d.value,f=t.valueType._zod.run({value:n[u],issues:[]},o);if(f instanceof Promise)s.push(f.then((S)=>{if(S.issues.length)r.issues.push(...Gt(u,S.issues));r.value[m]=S.value}));else{if(f.issues.length)r.issues.push(...Gt(u,f.issues));r.value[m]=f.value}}let l;for(let u in n)if(!a.has(u))l=l??[],l.push(u);if(l&&l.length>0)r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:l})}else{r.value={};for(let a of Reflect.ownKeys(n)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(n,a))continue;let l=t.keyType._zod.run({value:a,issues:[]},o);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&Wc.test(a)&&l.issues.length){let m=t.keyType._zod.run({value:Number(a),issues:[]},o);if(m instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(m.issues.length===0)l=m}if(l.issues.length){if(t.mode==="loose")r.value[a]=n[a];else r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((m)=>ot(m,o,je())),input:a,path:[a],inst:e});continue}let d=t.valueType._zod.run({value:n[a],issues:[]},o);if(d instanceof Promise)s.push(d.then((m)=>{if(m.issues.length)r.issues.push(...Gt(a,m.issues));r.value[l.value]=m.value}));else{if(d.issues.length)r.issues.push(...Gt(a,d.issues));r.value[l.value]=d.value}}}if(s.length)return Promise.all(s).then(()=>r);return r}});var dh=_("$ZodEnum",(e,t)=>{re.init(e,t);let r=ma(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter((n)=>hd.has(typeof n)).map((n)=>typeof n==="string"?Kt(n):n.toString()).join("|")})$`),e._zod.parse=(n,s)=>{let i=n.value;if(o.has(i))return n;return n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),ph=_("$ZodLiteral",(e,t)=>{if(re.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map((o)=>typeof o==="string"?Kt(o):o?Kt(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,n)=>{let s=o.value;if(r.has(s))return o;return o.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),o}});var hh=_("$ZodTransform",(e,t)=>{re.init(e,t),e._zod.optin="optional",e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new On(e.constructor.name);let n=t.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then((i)=>(r.value=i,r.fallback=!0,r));if(n instanceof Promise)throw new kt;return r.value=n,r.fallback=!0,r}});function zp(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var tl=_("$ZodOptional",(e,t)=>{re.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Q(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${ga(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(t.innerType._zod.optin==="optional"){let n=r.value,s=t.innerType._zod.run(r,o);if(s instanceof Promise)return s.then((i)=>zp(i,n));return zp(s,n)}if(r.value===void 0)return r;return t.innerType._zod.run(r,o)}}),mh=_("$ZodExactOptional",(e,t)=>{tl.init(e,t),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,o)=>t.innerType._zod.run(r,o)}),fh=_("$ZodNullable",(e,t)=>{re.init(e,t),Q(e._zod,"optin",()=>t.innerType._zod.optin),Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${ga(r.source)}|null)$`):void 0}),Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>{if(r.value===null)return r;return t.innerType._zod.run(r,o)}}),gh=_("$ZodDefault",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>wp(s,t));return wp(n,t)}});function wp(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Sh=_("$ZodPrefault",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,o)}}),_h=_("$ZodNonOptional",(e,t)=>{re.init(e,t),Q(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>Rp(s,e));return Rp(n,e)}});function Rp(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var bh=_("$ZodCatch",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>{if(r.value=s.value,s.issues.length)r.value=t.catchValue({...r,error:{issues:s.issues.map((i)=>ot(i,o,je()))},input:r.value}),r.issues=[],r.fallback=!0;return r});if(r.value=n.value,n.issues.length)r.value=t.catchValue({...r,error:{issues:n.issues.map((s)=>ot(s,o,je()))},input:r.value}),r.issues=[],r.fallback=!0;return r}});var rl=_("$ZodPipe",(e,t)=>{re.init(e,t),Q(e._zod,"values",()=>t.in._zod.values),Q(e._zod,"optin",()=>t.in._zod.optin),Q(e._zod,"optout",()=>t.out._zod.optout),Q(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if(o.direction==="backward"){let s=t.out._zod.run(r,o);if(s instanceof Promise)return s.then((i)=>va(i,t.in,o));return va(s,t.in,o)}let n=t.in._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>va(s,t.out,o));return va(n,t.out,o)}});function va(e,t,r){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var yh=_("$ZodPreprocess",(e,t)=>{rl.init(e,t)}),vh=_("$ZodReadonly",(e,t)=>{re.init(e,t),Q(e._zod,"propValues",()=>t.innerType._zod.propValues),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"optin",()=>t.innerType?._zod?.optin),Q(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then(xp);return xp(n)}});function xp(e){return e.value=Object.freeze(e.value),e}var zh=_("$ZodLazy",(e,t)=>{re.init(e,t),Q(e._zod,"innerType",()=>{let r=t;if(!r._cachedInner)r._cachedInner=t.getter();return r._cachedInner}),Q(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Q(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Q(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Q(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,o)=>e._zod.innerType._zod.run(r,o)}),wh=_("$ZodCustom",(e,t)=>{ze.init(e,t),re.init(e,t),e._zod.parse=(r,o)=>r,e._zod.check=(r)=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then((s)=>Pp(s,r,o,e));Pp(n,r,o,e);return}});function Pp(e,t,r,o){if(!e){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};if(o._zod.def.params)n.params=o._zod.def.params;t.issues.push(wr(n))}}var o_=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let s=o[n.expected]??n.expected,i=Sd(n.input),a=o[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":if(n.values.length===1)return`Invalid input: expected ${Dc(n.values[0])}`;return`Invalid option: expected one of ${jc(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",i=t(n.origin);if(i)return`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${i.unit??"elements"}`;return`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",i=t(n.origin);if(i)return`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${i.unit}`;return`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;if(s.format==="starts_with")return`Invalid string: must start with "${s.prefix}"`;if(s.format==="ends_with")return`Invalid string: must end with "${s.suffix}"`;if(s.format==="includes")return`Invalid string: must include "${s.includes}"`;if(s.format==="regex")return`Invalid string: must match pattern ${s.pattern}`;return`Invalid ${r[s.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${jc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":if(n.options&&Array.isArray(n.options)&&n.options.length>0)return`Invalid discriminator value. Expected ${n.options.map((i)=>`'${i}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function ol(){return{localeError:o_()}}var Rh,n_=Symbol("ZodOutput"),s_=Symbol("ZodInput");class xh{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Ph(){return new xh}(Rh=globalThis).__zod_globalRegistry??(Rh.__zod_globalRegistry=Ph());var Yt=globalThis.__zod_globalRegistry;function Th(e,t){return new e({type:"string",...M(t)})}function nl(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...M(t)})}function sl(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...M(t)})}function Eh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...M(t)})}function kh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(t)})}function $h(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(t)})}function Ch(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(t)})}function il(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...M(t)})}function Ih(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...M(t)})}function Oh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(t)})}function Nh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...M(t)})}function qh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(t)})}function Ah(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...M(t)})}function Mh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...M(t)})}function jh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(t)})}function Lh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(t)})}function Uh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(t)})}function Zh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(t)})}function Dh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(t)})}function Fh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...M(t)})}function Hh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...M(t)})}function Vh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...M(t)})}function Jh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...M(t)})}function Bh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(t)})}function Wh(e,t){return new e({type:"string",format:"date",check:"string_format",...M(t)})}function Kh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...M(t)})}function Gh(e,t){return new e({type:"string",format:"duration",check:"string_format",...M(t)})}function Yh(e,t){return new e({type:"number",checks:[],...M(t)})}function Xh(e,t){return new e({type:"number",coerce:!0,checks:[],...M(t)})}function Qh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...M(t)})}function em(e,t){return new e({type:"boolean",...M(t)})}function tm(e,t){return new e({type:"undefined",...M(t)})}function rm(e,t){return new e({type:"null",...M(t)})}function om(e){return new e({type:"any"})}function nm(e){return new e({type:"unknown"})}function sm(e,t){return new e({type:"never",...M(t)})}function Ra(e,t){return new Kc({check:"less_than",...M(t),value:e,inclusive:!1})}function Un(e,t){return new Kc({check:"less_than",...M(t),value:e,inclusive:!0})}function xa(e,t){return new Gc({check:"greater_than",...M(t),value:e,inclusive:!1})}function Zn(e,t){return new Gc({check:"greater_than",...M(t),value:e,inclusive:!0})}function Pa(e,t){return new sp({check:"multiple_of",...M(t),value:e})}function Ta(e,t){return new ap({check:"max_length",...M(t),maximum:e})}function co(e,t){return new cp({check:"min_length",...M(t),minimum:e})}function Ea(e,t){return new lp({check:"length_equals",...M(t),length:e})}function al(e,t){return new up({check:"string_format",format:"regex",...M(t),pattern:e})}function cl(e){return new dp({check:"string_format",format:"lowercase",...M(e)})}function ll(e){return new pp({check:"string_format",format:"uppercase",...M(e)})}function ul(e,t){return new hp({check:"string_format",format:"includes",...M(t),includes:e})}function dl(e,t){return new mp({check:"string_format",format:"starts_with",...M(t),prefix:e})}function pl(e,t){return new fp({check:"string_format",format:"ends_with",...M(t),suffix:e})}function Xt(e){return new gp({check:"overwrite",tx:e})}function hl(e){return Xt((t)=>t.normalize(e))}function ml(){return Xt((e)=>e.trim())}function fl(){return Xt((e)=>e.toLowerCase())}function gl(){return Xt((e)=>e.toUpperCase())}function Sl(){return Xt((e)=>dd(e))}function im(e,t,r){return new e({type:"array",element:t,...M(r)})}function am(e,t,r){return new e({type:"custom",check:"custom",fn:t,...M(r)})}function cm(e,t){let r=i_((o)=>(o.addIssue=(n)=>{if(typeof n==="string")o.issues.push(wr(n,o.value,r._zod.def));else{let s=n;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=o.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),o.issues.push(wr(s))}},e(o.value,o)),t);return r}function i_(e,t){let r=new ze({check:"custom",...M(t)});return r._zod.check=e,r}function Fn(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??Yt,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 oe(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,r.schemaPath.includes(e))s.cycle=r.path;return s.schema}let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,d);else{let f=i.schema,S=t.processors[n.type];if(!S)throw Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);S(e,t,f,d)}let m=e._zod.parent;if(m){if(!i.ref)i.ref=m;oe(m,t,d),t.seen.get(m).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Object.assign(i.schema,l);if(t.io==="input"&&Ne(e))delete i.schema.examples,delete i.schema.default;if(t.io==="input"&&"_prefault"in i.schema)(o=i.schema).default??(o.default=i.schema._prefault);return delete i.schema._prefault,t.seen.get(e).schema}function Hn(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let l=o.get(a);if(l&&l!==i[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,i[0])}}let n=(i)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let m=e.external.registry.get(i[0])?.id,f=e.external.uri??((b)=>b);if(m)return{ref:f(m)};let S=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=S,{defId:S,ref:`${f("__shared")}#/${a}/${S}`}}if(i[1]===r)return{ref:"#"};let u=`${"#"}/${a}/`,d=i[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},s=(i)=>{if(i[1].schema.$ref)return;let a=i[1],{ref:l,defId:u}=n(i);if(a.def={...a.schema},u)a.defId=u;let d=a.schema;for(let m in d)delete d[m];d.$ref=l};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
63
+ `)}S.write("payload.value = newResult;"),S.write("return payload;");let H=S.compile();return(x,Z)=>H(f,x,Z)},s,i=ao,a=!io.jitless,u=a&&md.value,d=t.catchall,m;e._zod.parse=(f,S)=>{m??(m=o.value);let b=f.value;if(!i(b))return f.issues.push({expected:"object",code:"invalid_type",input:b,inst:e}),f;if(a&&u&&S?.async===!1&&S.jitless!==!0){if(!s)s=n(t.shape);if(f=s(f,S),!d)return f;return ch([],b,f,S,m,e)}return r(f,S)}});function zp(e,t,r,o){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let n=e.filter((s)=>!zr(s));if(n.length===1)return t.value=n[0].value,n[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((s)=>s.issues.map((i)=>ot(i,o,je())))}),t}var tl=_("$ZodUnion",(e,t)=>{re.init(e,t),Q(e._zod,"optin",()=>t.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),Q(e._zod,"optout",()=>t.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),Q(e._zod,"values",()=>{if(t.options.every((o)=>o._zod.values))return new Set(t.options.flatMap((o)=>Array.from(o._zod.values)));return}),Q(e._zod,"pattern",()=>{if(t.options.every((o)=>o._zod.pattern)){let o=t.options.map((n)=>n._zod.pattern);return new RegExp(`^(${o.map((n)=>Sa(n.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,n)=>{if(r)return r(o,n);let s=!1,i=[];for(let a of t.options){let l=a._zod.run({value:o.value,issues:[]},n);if(l instanceof Promise)i.push(l),s=!0;else{if(l.issues.length===0)return l;i.push(l)}}if(!s)return zp(i,o,e,n);return Promise.all(i).then((a)=>zp(a,o,e,n))}});var uh=_("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,tl.init(e,t);let r=e._zod.parse;Q(e._zod,"propValues",()=>{let n={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[a,l]of Object.entries(i)){if(!n[a])n[a]=new Set;for(let u of l)n[a].add(u)}}return n});let o=qn(()=>{let n=t.options,s=new Map;for(let i of n){let a=i._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let l of a){if(s.has(l))throw Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,i)}}return s});e._zod.parse=(n,s)=>{let i=n.value;if(!ao(i))return n.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),n;let a=o.value.get(i?.[t.discriminator]);if(a)return a._zod.run(n,s);if(t.unionFallback||s.direction==="backward")return r(n,s);return n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(o.value.keys()),input:i,path:[t.discriminator],inst:e}),n}}),dh=_("$ZodIntersection",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value,s=t.left._zod.run({value:n,issues:[]},o),i=t.right._zod.run({value:n,issues:[]},o);if(s instanceof Promise||i instanceof Promise)return Promise.all([s,i]).then(([l,u])=>wp(r,l,u));return wp(r,s,i)}});function Qc(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(vr(e)&&vr(t)){let r=Object.keys(t),o=Object.keys(e).filter((s)=>r.indexOf(s)!==-1),n={...e,...t};for(let s of o){let i=Qc(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};n[s]=i.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<e.length;o++){let n=e[o],s=t[o],i=Qc(n,s);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function wp(e,t,r){let o=new Map,n;for(let a of t.issues)if(a.code==="unrecognized_keys"){n??(n=a);for(let l of a.keys){if(!o.has(l))o.set(l,{});o.get(l).l=!0}}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let l of a.keys){if(!o.has(l))o.set(l,{});o.get(l).r=!0}else e.issues.push(a);let s=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&n)e.issues.push({...n,keys:s});if(zr(e))return e;let i=Qc(t.value,r.value);if(!i.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}var ph=_("$ZodRecord",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!vr(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let s=[],i=t.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){a.add(typeof u==="number"?u.toString():u);let d=t.keyType._zod.run({value:u,issues:[]},o);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((S)=>ot(S,o,je())),input:u,path:[u],inst:e});continue}let m=d.value,f=t.valueType._zod.run({value:n[u],issues:[]},o);if(f instanceof Promise)s.push(f.then((S)=>{if(S.issues.length)r.issues.push(...Gt(u,S.issues));r.value[m]=S.value}));else{if(f.issues.length)r.issues.push(...Gt(u,f.issues));r.value[m]=f.value}}let l;for(let u in n)if(!a.has(u))l=l??[],l.push(u);if(l&&l.length>0)r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:l})}else{r.value={};for(let a of Reflect.ownKeys(n)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(n,a))continue;let l=t.keyType._zod.run({value:a,issues:[]},o);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&Kc.test(a)&&l.issues.length){let m=t.keyType._zod.run({value:Number(a),issues:[]},o);if(m instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(m.issues.length===0)l=m}if(l.issues.length){if(t.mode==="loose")r.value[a]=n[a];else r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((m)=>ot(m,o,je())),input:a,path:[a],inst:e});continue}let d=t.valueType._zod.run({value:n[a],issues:[]},o);if(d instanceof Promise)s.push(d.then((m)=>{if(m.issues.length)r.issues.push(...Gt(a,m.issues));r.value[l.value]=m.value}));else{if(d.issues.length)r.issues.push(...Gt(a,d.issues));r.value[l.value]=d.value}}}if(s.length)return Promise.all(s).then(()=>r);return r}});var hh=_("$ZodEnum",(e,t)=>{re.init(e,t);let r=fa(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter((n)=>fd.has(typeof n)).map((n)=>typeof n==="string"?Kt(n):n.toString()).join("|")})$`),e._zod.parse=(n,s)=>{let i=n.value;if(o.has(i))return n;return n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),mh=_("$ZodLiteral",(e,t)=>{if(re.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map((o)=>typeof o==="string"?Kt(o):o?Kt(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,n)=>{let s=o.value;if(r.has(s))return o;return o.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),o}});var fh=_("$ZodTransform",(e,t)=>{re.init(e,t),e._zod.optin="optional",e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new On(e.constructor.name);let n=t.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then((i)=>(r.value=i,r.fallback=!0,r));if(n instanceof Promise)throw new kt;return r.value=n,r.fallback=!0,r}});function Rp(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var rl=_("$ZodOptional",(e,t)=>{re.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Q(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Sa(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(t.innerType._zod.optin==="optional"){let n=r.value,s=t.innerType._zod.run(r,o);if(s instanceof Promise)return s.then((i)=>Rp(i,n));return Rp(s,n)}if(r.value===void 0)return r;return t.innerType._zod.run(r,o)}}),gh=_("$ZodExactOptional",(e,t)=>{rl.init(e,t),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,o)=>t.innerType._zod.run(r,o)}),Sh=_("$ZodNullable",(e,t)=>{re.init(e,t),Q(e._zod,"optin",()=>t.innerType._zod.optin),Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Sa(r.source)}|null)$`):void 0}),Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>{if(r.value===null)return r;return t.innerType._zod.run(r,o)}}),_h=_("$ZodDefault",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>xp(s,t));return xp(n,t)}});function xp(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var bh=_("$ZodPrefault",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,o)}}),yh=_("$ZodNonOptional",(e,t)=>{re.init(e,t),Q(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>Pp(s,e));return Pp(n,e)}});function Pp(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var vh=_("$ZodCatch",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>{if(r.value=s.value,s.issues.length)r.value=t.catchValue({...r,error:{issues:s.issues.map((i)=>ot(i,o,je()))},input:r.value}),r.issues=[],r.fallback=!0;return r});if(r.value=n.value,n.issues.length)r.value=t.catchValue({...r,error:{issues:n.issues.map((s)=>ot(s,o,je()))},input:r.value}),r.issues=[],r.fallback=!0;return r}});var ol=_("$ZodPipe",(e,t)=>{re.init(e,t),Q(e._zod,"values",()=>t.in._zod.values),Q(e._zod,"optin",()=>t.in._zod.optin),Q(e._zod,"optout",()=>t.out._zod.optout),Q(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if(o.direction==="backward"){let s=t.out._zod.run(r,o);if(s instanceof Promise)return s.then((i)=>za(i,t.in,o));return za(s,t.in,o)}let n=t.in._zod.run(r,o);if(n instanceof Promise)return n.then((s)=>za(s,t.out,o));return za(n,t.out,o)}});function za(e,t,r){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var zh=_("$ZodPreprocess",(e,t)=>{ol.init(e,t)}),wh=_("$ZodReadonly",(e,t)=>{re.init(e,t),Q(e._zod,"propValues",()=>t.innerType._zod.propValues),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"optin",()=>t.innerType?._zod?.optin),Q(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then(Tp);return Tp(n)}});function Tp(e){return e.value=Object.freeze(e.value),e}var Rh=_("$ZodLazy",(e,t)=>{re.init(e,t),Q(e._zod,"innerType",()=>{let r=t;if(!r._cachedInner)r._cachedInner=t.getter();return r._cachedInner}),Q(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Q(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Q(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Q(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,o)=>e._zod.innerType._zod.run(r,o)}),xh=_("$ZodCustom",(e,t)=>{ze.init(e,t),re.init(e,t),e._zod.parse=(r,o)=>r,e._zod.check=(r)=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then((s)=>Ep(s,r,o,e));Ep(n,r,o,e);return}});function Ep(e,t,r,o){if(!e){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};if(o._zod.def.params)n.params=o._zod.def.params;t.issues.push(wr(n))}}var s_=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let s=o[n.expected]??n.expected,i=bd(n.input),a=o[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":if(n.values.length===1)return`Invalid input: expected ${Fc(n.values[0])}`;return`Invalid option: expected one of ${Lc(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",i=t(n.origin);if(i)return`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${i.unit??"elements"}`;return`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",i=t(n.origin);if(i)return`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${i.unit}`;return`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;if(s.format==="starts_with")return`Invalid string: must start with "${s.prefix}"`;if(s.format==="ends_with")return`Invalid string: must end with "${s.suffix}"`;if(s.format==="includes")return`Invalid string: must include "${s.includes}"`;if(s.format==="regex")return`Invalid string: must match pattern ${s.pattern}`;return`Invalid ${r[s.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Lc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":if(n.options&&Array.isArray(n.options)&&n.options.length>0)return`Invalid discriminator value. Expected ${n.options.map((i)=>`'${i}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function nl(){return{localeError:s_()}}var Ph,i_=Symbol("ZodOutput"),a_=Symbol("ZodInput");class Th{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Eh(){return new Th}(Ph=globalThis).__zod_globalRegistry??(Ph.__zod_globalRegistry=Eh());var Yt=globalThis.__zod_globalRegistry;function kh(e,t){return new e({type:"string",...M(t)})}function sl(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...M(t)})}function il(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...M(t)})}function $h(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...M(t)})}function Ch(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(t)})}function Ih(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(t)})}function Oh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(t)})}function al(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...M(t)})}function Nh(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...M(t)})}function qh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(t)})}function Ah(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...M(t)})}function Mh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(t)})}function jh(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...M(t)})}function Lh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...M(t)})}function Uh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(t)})}function Zh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(t)})}function Dh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(t)})}function Fh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(t)})}function Hh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(t)})}function Vh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...M(t)})}function Jh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...M(t)})}function Bh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...M(t)})}function Wh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...M(t)})}function Kh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(t)})}function Gh(e,t){return new e({type:"string",format:"date",check:"string_format",...M(t)})}function Yh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...M(t)})}function Xh(e,t){return new e({type:"string",format:"duration",check:"string_format",...M(t)})}function Qh(e,t){return new e({type:"number",checks:[],...M(t)})}function em(e,t){return new e({type:"number",coerce:!0,checks:[],...M(t)})}function tm(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...M(t)})}function rm(e,t){return new e({type:"boolean",...M(t)})}function om(e,t){return new e({type:"undefined",...M(t)})}function nm(e,t){return new e({type:"null",...M(t)})}function sm(e){return new e({type:"any"})}function im(e){return new e({type:"unknown"})}function am(e,t){return new e({type:"never",...M(t)})}function xa(e,t){return new Gc({check:"less_than",...M(t),value:e,inclusive:!1})}function Un(e,t){return new Gc({check:"less_than",...M(t),value:e,inclusive:!0})}function Pa(e,t){return new Yc({check:"greater_than",...M(t),value:e,inclusive:!1})}function Zn(e,t){return new Yc({check:"greater_than",...M(t),value:e,inclusive:!0})}function Ta(e,t){return new ap({check:"multiple_of",...M(t),value:e})}function Ea(e,t){return new lp({check:"max_length",...M(t),maximum:e})}function co(e,t){return new up({check:"min_length",...M(t),minimum:e})}function ka(e,t){return new dp({check:"length_equals",...M(t),length:e})}function cl(e,t){return new pp({check:"string_format",format:"regex",...M(t),pattern:e})}function ll(e){return new hp({check:"string_format",format:"lowercase",...M(e)})}function ul(e){return new mp({check:"string_format",format:"uppercase",...M(e)})}function dl(e,t){return new fp({check:"string_format",format:"includes",...M(t),includes:e})}function pl(e,t){return new gp({check:"string_format",format:"starts_with",...M(t),prefix:e})}function hl(e,t){return new Sp({check:"string_format",format:"ends_with",...M(t),suffix:e})}function Xt(e){return new _p({check:"overwrite",tx:e})}function ml(e){return Xt((t)=>t.normalize(e))}function fl(){return Xt((e)=>e.trim())}function gl(){return Xt((e)=>e.toLowerCase())}function Sl(){return Xt((e)=>e.toUpperCase())}function _l(){return Xt((e)=>hd(e))}function cm(e,t,r){return new e({type:"array",element:t,...M(r)})}function lm(e,t,r){return new e({type:"custom",check:"custom",fn:t,...M(r)})}function um(e,t){let r=c_((o)=>(o.addIssue=(n)=>{if(typeof n==="string")o.issues.push(wr(n,o.value,r._zod.def));else{let s=n;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=o.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),o.issues.push(wr(s))}},e(o.value,o)),t);return r}function c_(e,t){let r=new ze({check:"custom",...M(t)});return r._zod.check=e,r}function Fn(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??Yt,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 oe(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,r.schemaPath.includes(e))s.cycle=r.path;return s.schema}let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,d);else{let f=i.schema,S=t.processors[n.type];if(!S)throw Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);S(e,t,f,d)}let m=e._zod.parent;if(m){if(!i.ref)i.ref=m;oe(m,t,d),t.seen.get(m).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Object.assign(i.schema,l);if(t.io==="input"&&Ne(e))delete i.schema.examples,delete i.schema.default;if(t.io==="input"&&"_prefault"in i.schema)(o=i.schema).default??(o.default=i.schema._prefault);return delete i.schema._prefault,t.seen.get(e).schema}function Hn(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let l=o.get(a);if(l&&l!==i[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,i[0])}}let n=(i)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let m=e.external.registry.get(i[0])?.id,f=e.external.uri??((b)=>b);if(m)return{ref:f(m)};let S=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=S,{defId:S,ref:`${f("__shared")}#/${a}/${S}`}}if(i[1]===r)return{ref:"#"};let u=`${"#"}/${a}/`,d=i[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},s=(i)=>{if(i[1].schema.$ref)return;let a=i[1],{ref:l,defId:u}=n(i);if(a.def={...a.schema},u)a.defId=u;let d=a.schema;for(let m in d)delete d[m];d.$ref=l};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
63
64
 
64
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1){if(e.reused==="ref"){s(i);continue}}}}function Vn(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(a)=>{let l=e.seen.get(a);if(l.ref===null)return;let u=l.def??l.schema,d={...u},m=l.ref;if(l.ref=null,m){o(m);let S=e.seen.get(m),b=S.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))u.allOf=u.allOf??[],u.allOf.push(b);else Object.assign(u,b);if(Object.assign(u,d),a._zod.parent===m)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(!(v in d))delete u[v]}if(b.$ref&&S.def)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(v in S.def&&JSON.stringify(u[v])===JSON.stringify(S.def[v]))delete u[v]}}let f=a._zod.parent;if(f&&f!==m){o(f);let S=e.seen.get(f);if(S?.schema.$ref){if(u.$ref=S.schema.$ref,S.def)for(let b in u){if(b==="$ref"||b==="allOf")continue;if(b in S.def&&JSON.stringify(u[b])===JSON.stringify(S.def[b]))delete u[b]}}}e.override({zodSchema:a,jsonSchema:u,path:l.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let n={};if(e.target==="draft-2020-12")n.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")n.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")n.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");n.$id=e.external.uri(a)}Object.assign(n,r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&n.id===s)delete n.id;let i=e.external?.defs??{};for(let a of e.seen.entries()){let l=a[1];if(l.def&&l.defId){if(l.def.id===l.defId)delete l.def.id;i[l.defId]=l.def}}if(e.external);else if(Object.keys(i).length>0)if(e.target==="draft-2020-12")n.$defs=i;else n.definitions=i;try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dn(t,"input",e.processors),output:Dn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Ne(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Ne(o.element,r);if(o.type==="set")return Ne(o.valueType,r);if(o.type==="lazy")return Ne(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return Ne(o.innerType,r);if(o.type==="intersection")return Ne(o.left,r)||Ne(o.right,r);if(o.type==="record"||o.type==="map")return Ne(o.keyType,r)||Ne(o.valueType,r);if(o.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Ne(o.in,r)||Ne(o.out,r)}if(o.type==="object"){for(let n in o.shape)if(Ne(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Ne(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Ne(n,r))return!0;if(o.rest&&Ne(o.rest,r))return!0;return!1}return!1}var lm=(e,t={})=>(r)=>{let o=Fn({...r,processors:t});return oe(e,o),Hn(o,e),Vn(o,e)},Dn=(e,t,r={})=>(o)=>{let{libraryOptions:n,target:s}=o??{},i=Fn({...n??{},target:s,io:t,processors:r});return oe(e,i),Hn(i,e),Vn(i,e)};var a_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},_l=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:s,maximum:i,format:a,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof s==="number")n.minLength=s;if(typeof i==="number")n.maxLength=i;if(a){if(n.format=a_[a]??a,n.format==="")delete n.format;if(a==="time")delete n.format}if(u)n.contentEncoding=u;if(l&&l.size>0){let d=[...l];if(d.length===1)n.pattern=d[0].source;else if(d.length>1)n.allOf=[...d.map((m)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))]}},bl=(e,t,r,o)=>{let n=r,{minimum:s,maximum:i,format:a,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))n.type="integer";else n.type="number";let m=typeof d==="number"&&d>=(s??Number.NEGATIVE_INFINITY),f=typeof u==="number"&&u<=(i??Number.POSITIVE_INFINITY),S=t.target==="draft-04"||t.target==="openapi-3.0";if(m)if(S)n.minimum=d,n.exclusiveMinimum=!0;else n.exclusiveMinimum=d;else if(typeof s==="number")n.minimum=s;if(f)if(S)n.maximum=u,n.exclusiveMaximum=!0;else n.exclusiveMaximum=u;else if(typeof i==="number")n.maximum=i;if(typeof l==="number")n.multipleOf=l},yl=(e,t,r,o)=>{r.type="boolean"},dm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},pm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},vl=(e,t,r,o)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},zl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},hm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},wl=(e,t,r,o)=>{r.not={}},Rl=(e,t,r,o)=>{},xl=(e,t,r,o)=>{},mm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},Pl=(e,t,r,o)=>{let n=e._zod.def,s=ma(n.entries);if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";r.enum=s},Tl=(e,t,r,o)=>{let n=e._zod.def,s=[];for(let i of n.values)if(i===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else s.push(Number(i));else s.push(i);if(s.length===0);else if(s.length===1){let i=s[0];if(r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[i];else r.const=i}else{if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";if(s.every((i)=>typeof i==="boolean"))r.type="boolean";if(s.every((i)=>i===null))r.type="null";r.enum=s}},fm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},gm=(e,t,r,o)=>{let n=r,s=e._zod.pattern;if(!s)throw Error("Pattern not found in template literal");n.type="string",n.pattern=s.source},Sm=(e,t,r,o)=>{let n=r,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:a,mime:l}=e._zod.bag;if(i!==void 0)s.minLength=i;if(a!==void 0)s.maxLength=a;if(l)if(l.length===1)s.contentMediaType=l[0],Object.assign(n,s);else Object.assign(n,s),n.anyOf=l.map((u)=>({contentMediaType:u}));else Object.assign(n,s)},_m=(e,t,r,o)=>{r.type="boolean"},El=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},bm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},kl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},ym=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},vm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},$l=(e,t,r,o)=>{let n=r,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;if(typeof i==="number")n.minItems=i;if(typeof a==="number")n.maxItems=a;n.type="array",n.items=oe(s.element,t,{...o,path:[...o.path,"items"]})},Cl=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="object",n.properties={};let i=s.shape;for(let u in i)n.properties[u]=oe(i[u],t,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(i)),l=new Set([...a].filter((u)=>{let d=s.shape[u]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(l.size>0)n.required=Array.from(l);if(s.catchall?._zod.def.type==="never")n.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")n.additionalProperties=!1}else if(s.catchall)n.additionalProperties=oe(s.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Il=(e,t,r,o)=>{let n=e._zod.def,s=n.inclusive===!1,i=n.options.map((a,l)=>oe(a,t,{...o,path:[...o.path,s?"oneOf":"anyOf",l]}));if(s)r.oneOf=i;else r.anyOf=i},Ol=(e,t,r,o)=>{let n=e._zod.def,s=oe(n.left,t,{...o,path:[...o.path,"allOf",0]}),i=oe(n.right,t,{...o,path:[...o.path,"allOf",1]}),a=(u)=>("allOf"in u)&&Object.keys(u).length===1,l=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=l},zm=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",l=s.items.map((f,S)=>oe(f,t,{...o,path:[...o.path,i,S]})),u=s.rest?oe(s.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(n.prefixItems=l,u)n.items=u}else if(t.target==="openapi-3.0"){if(n.items={anyOf:l},u)n.items.anyOf.push(u);if(n.minItems=l.length,!u)n.maxItems=l.length}else if(n.items=l,u)n.additionalItems=u;let{minimum:d,maximum:m}=e._zod.bag;if(typeof d==="number")n.minItems=d;if(typeof m==="number")n.maxItems=m},Nl=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="object";let i=s.keyType,l=i._zod.bag?.patterns;if(s.mode==="loose"&&l&&l.size>0){let d=oe(s.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let m of l)n.patternProperties[m.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")n.propertyNames=oe(s.keyType,t,{...o,path:[...o.path,"propertyNames"]});n.additionalProperties=oe(s.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=i._zod.values;if(u){let d=[...u].filter((m)=>typeof m==="string"||typeof m==="number");if(d.length>0)n.required=d}},ql=(e,t,r,o)=>{let n=e._zod.def,s=oe(n.innerType,t,o),i=t.seen.get(e);if(t.target==="openapi-3.0")i.ref=n.innerType,r.nullable=!0;else r.anyOf=[s,{type:"null"}]},Al=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},Ml=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},jl=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);if(s.ref=n.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(n.defaultValue))},Ll=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType;let i;try{i=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},Ul=(e,t,r,o)=>{let n=e._zod.def,s=n.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?n.out:n.in:n.out;oe(i,t,o);let a=t.seen.get(e);a.ref=i},Zl=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType,r.readOnly=!0},wm=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},ka=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},Dl=(e,t,r,o)=>{let n=e._zod.innerType;oe(n,t,o);let s=t.seen.get(e);s.ref=n},um={string:_l,number:bl,boolean:yl,bigint:dm,symbol:pm,null:vl,undefined:zl,void:hm,never:wl,any:Rl,unknown:xl,date:mm,enum:Pl,literal:Tl,nan:fm,template_literal:gm,file:Sm,success:_m,custom:El,function:bm,transform:kl,map:ym,set:vm,array:$l,object:Cl,union:Il,intersection:Ol,tuple:zm,record:Nl,nullable:ql,nonoptional:Al,default:Ml,prefault:jl,catch:Ll,pipe:Ul,readonly:Zl,promise:wm,optional:ka,lazy:Dl};function $a(e,t){if("_idmap"in e){let o=e,n=Fn({...t,processors:um}),s={};for(let l of o._idmap.entries()){let[u,d]=l;oe(d,n)}let i={},a={registry:o,uri:t?.uri,defs:s};n.external=a;for(let l of o._idmap.entries()){let[u,d]=l;Hn(n,d),i[u]=Vn(n,d)}if(Object.keys(s).length>0){let l=n.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[l]:s}}return{schemas:i}}let r=Fn({...t,processors:um});return oe(e,r),Hn(r,e),Vn(r,e)}var f_=_("ZodISODateTime",(e,t)=>{jp.init(e,t),ae.init(e,t)});function uo(e){return Bh(f_,e)}var g_=_("ZodISODate",(e,t)=>{Lp.init(e,t),ae.init(e,t)});function Fl(e){return Wh(g_,e)}var S_=_("ZodISOTime",(e,t)=>{Up.init(e,t),ae.init(e,t)});function Rm(e){return Kh(S_,e)}var __=_("ZodISODuration",(e,t)=>{Zp.init(e,t),ae.init(e,t)});function xm(e){return Gh(__,e)}var b_=(e,t)=>{_a.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>Vc(e,r)},flatten:{value:(r)=>Hc(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Nn,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Nn,2)}},isEmpty:{get(){return e.issues.length===0}}})};var Je=_("ZodError",b_,{Parent:Error});var Tm=ba(Je),Em=ya(Je),Ia=An(Je),km=Mn(Je),$m=vd(Je),Cm=zd(Je),Im=wd(Je),Om=Rd(Je),Nm=xd(Je),qm=Pd(Je),Am=Td(Je),Mm=Ed(Je);var jm=new WeakMap;function Jn(e,t,r){let o=Object.getPrototypeOf(e),n=jm.get(o);if(!n)n=new Set,jm.set(o,n);if(n.has(t))return;n.add(t);for(let s in r){let i=r[s];Object.defineProperty(o,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var ne=_("ZodType",(e,t)=>(re.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dn(e,"input"),output:Dn(e,"output")}}),e.toJSONSchema=lm(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,o)=>Tm(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Ia(e,r,o),e.parseAsync=async(r,o)=>Em(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>km(e,r,o),e.spa=e.safeParseAsync,e.encode=(r,o)=>$m(e,r,o),e.decode=(r,o)=>Cm(e,r,o),e.encodeAsync=async(r,o)=>Im(e,r,o),e.decodeAsync=async(r,o)=>Om(e,r,o),e.safeEncode=(r,o)=>Nm(e,r,o),e.safeDecode=(r,o)=>qm(e,r,o),e.safeEncodeAsync=async(r,o)=>Am(e,r,o),e.safeDecodeAsync=async(r,o)=>Mm(e,r,o),Jn(e,"ZodType",{check(...r){let o=this.def;return this.clone(Wt(o,{checks:[...o.checks??[],...r.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,o){return rt(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(cb(r,o))},superRefine(r,o){return this.check(lb(r,o))},overwrite(r){return this.check(Xt(r))},optional(){return j(this)},exactOptional(){return W_(this)},nullable(){return Dm(this)},nullish(){return j(Dm(this))},nonoptional(r){return eb(this,r)},array(){return g(this)},or(r){return T([this,r])},and(r){return $t(this,r)},transform(r){return Fm(this,Xm(r))},default(r){return Y_(this,r)},prefault(r){return Q_(this,r)},catch(r){return rb(this,r)},pipe(r){return Fm(this,r)},readonly(){return sb(this)},describe(r){let o=this.clone();return Yt.add(o,{description:r}),o},meta(...r){if(r.length===0)return Yt.get(this);let o=this.clone();return Yt.add(o,r[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return Yt.get(e)?.description},configurable:!0}),e)),Hm=_("_ZodString",(e,t)=>{wa.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,s)=>_l(e,o,n,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Jn(e,"_ZodString",{regex(...o){return this.check(al(...o))},includes(...o){return this.check(ul(...o))},startsWith(...o){return this.check(dl(...o))},endsWith(...o){return this.check(pl(...o))},min(...o){return this.check(co(...o))},max(...o){return this.check(Ta(...o))},length(...o){return this.check(Ea(...o))},nonempty(...o){return this.check(co(1,...o))},lowercase(o){return this.check(cl(o))},uppercase(o){return this.check(ll(o))},trim(){return this.check(ml())},normalize(...o){return this.check(hl(...o))},toLowerCase(){return this.check(fl())},toUpperCase(){return this.check(gl())},slugify(){return this.check(Sl())}})}),Vm=_("ZodString",(e,t)=>{wa.init(e,t),Hm.init(e,t),e.email=(r)=>e.check(nl(Jm,r)),e.url=(r)=>e.check(il(Wm,r)),e.jwt=(r)=>e.check(Jh(q_,r)),e.emoji=(r)=>e.check(Ih(v_,r)),e.guid=(r)=>e.check(sl(Lm,r)),e.uuid=(r)=>e.check(Eh(Oa,r)),e.uuidv4=(r)=>e.check(kh(Oa,r)),e.uuidv6=(r)=>e.check($h(Oa,r)),e.uuidv7=(r)=>e.check(Ch(Oa,r)),e.nanoid=(r)=>e.check(Oh(z_,r)),e.guid=(r)=>e.check(sl(Lm,r)),e.cuid=(r)=>e.check(Nh(w_,r)),e.cuid2=(r)=>e.check(qh(R_,r)),e.ulid=(r)=>e.check(Ah(x_,r)),e.base64=(r)=>e.check(Fh(I_,r)),e.base64url=(r)=>e.check(Hh(O_,r)),e.xid=(r)=>e.check(Mh(P_,r)),e.ksuid=(r)=>e.check(jh(T_,r)),e.ipv4=(r)=>e.check(Lh(E_,r)),e.ipv6=(r)=>e.check(Uh(k_,r)),e.cidrv4=(r)=>e.check(Zh($_,r)),e.cidrv6=(r)=>e.check(Dh(C_,r)),e.e164=(r)=>e.check(Vh(N_,r)),e.datetime=(r)=>e.check(uo(r)),e.date=(r)=>e.check(Fl(r)),e.time=(r)=>e.check(Rm(r)),e.duration=(r)=>e.check(xm(r))});function c(e){return Th(Vm,e)}var ae=_("ZodStringFormat",(e,t)=>{ie.init(e,t),Hm.init(e,t)}),Jm=_("ZodEmail",(e,t)=>{kp.init(e,t),ae.init(e,t)});function Bm(e){return nl(Jm,e)}var Lm=_("ZodGUID",(e,t)=>{Tp.init(e,t),ae.init(e,t)});var Oa=_("ZodUUID",(e,t)=>{Ep.init(e,t),ae.init(e,t)});var Wm=_("ZodURL",(e,t)=>{$p.init(e,t),ae.init(e,t)});function Na(e){return il(Wm,e)}var v_=_("ZodEmoji",(e,t)=>{Cp.init(e,t),ae.init(e,t)});var z_=_("ZodNanoID",(e,t)=>{Ip.init(e,t),ae.init(e,t)});var w_=_("ZodCUID",(e,t)=>{Op.init(e,t),ae.init(e,t)});var R_=_("ZodCUID2",(e,t)=>{Np.init(e,t),ae.init(e,t)});var x_=_("ZodULID",(e,t)=>{qp.init(e,t),ae.init(e,t)});var P_=_("ZodXID",(e,t)=>{Ap.init(e,t),ae.init(e,t)});var T_=_("ZodKSUID",(e,t)=>{Mp.init(e,t),ae.init(e,t)});var E_=_("ZodIPv4",(e,t)=>{Dp.init(e,t),ae.init(e,t)});var k_=_("ZodIPv6",(e,t)=>{Fp.init(e,t),ae.init(e,t)});var $_=_("ZodCIDRv4",(e,t)=>{Hp.init(e,t),ae.init(e,t)});var C_=_("ZodCIDRv6",(e,t)=>{Vp.init(e,t),ae.init(e,t)});var I_=_("ZodBase64",(e,t)=>{Bp.init(e,t),ae.init(e,t)});var O_=_("ZodBase64URL",(e,t)=>{Wp.init(e,t),ae.init(e,t)});var N_=_("ZodE164",(e,t)=>{Kp.init(e,t),ae.init(e,t)});var q_=_("ZodJWT",(e,t)=>{Gp.init(e,t),ae.init(e,t)});var qa=_("ZodNumber",(e,t)=>{Qc.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,s)=>bl(e,o,n,s),Jn(e,"ZodNumber",{gt(o,n){return this.check(xa(o,n))},gte(o,n){return this.check(Zn(o,n))},min(o,n){return this.check(Zn(o,n))},lt(o,n){return this.check(Ra(o,n))},lte(o,n){return this.check(Un(o,n))},max(o,n){return this.check(Un(o,n))},int(o){return this.check(Um(o))},safe(o){return this.check(Um(o))},positive(o){return this.check(xa(0,o))},nonnegative(o){return this.check(Zn(0,o))},negative(o){return this.check(Ra(0,o))},nonpositive(o){return this.check(Un(0,o))},multipleOf(o,n){return this.check(Pa(o,n))},step(o,n){return this.check(Pa(o,n))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??0.5),e.isFinite=!0,e.format=r.format??null});function z(e){return Yh(qa,e)}var A_=_("ZodNumberFormat",(e,t)=>{Yp.init(e,t),qa.init(e,t)});function Um(e){return Qh(A_,e)}var Km=_("ZodBoolean",(e,t)=>{Xp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>yl(e,r,o,n)});function E(e){return em(Km,e)}var M_=_("ZodUndefined",(e,t)=>{Qp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zl(e,r,o,n)});function Vl(e){return tm(M_,e)}var j_=_("ZodNull",(e,t)=>{eh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vl(e,r,o,n)});function Rr(e){return rm(j_,e)}var L_=_("ZodAny",(e,t)=>{th.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rl(e,r,o,n)});function Aa(){return om(L_)}var U_=_("ZodUnknown",(e,t)=>{rh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xl(e,r,o,n)});function A(){return nm(U_)}var Z_=_("ZodNever",(e,t)=>{oh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wl(e,r,o,n)});function Jl(e){return sm(Z_,e)}var D_=_("ZodArray",(e,t)=>{nh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$l(e,r,o,n),e.element=t.element,Jn(e,"ZodArray",{min(r,o){return this.check(co(r,o))},nonempty(r){return this.check(co(1,r))},max(r,o){return this.check(Ta(r,o))},length(r,o){return this.check(Ea(r,o))},unwrap(){return this.element}})});function g(e,t){return im(D_,e,t)}var Gm=_("ZodObject",(e,t)=>{ah.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cl(e,r,o,n),Q(e,"shape",()=>t.shape),Jn(e,"ZodObject",{keyof(){return K(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:A()})},loose(){return this.clone({...this._zod.def,catchall:A()})},strict(){return this.clone({...this._zod.def,catchall:Jl()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return BS(this,r)},safeExtend(r){return WS(this,r)},merge(r){return KS(this,r)},pick(r){return VS(this,r)},omit(r){return JS(this,r)},partial(...r){return GS(Qm,this,r[0])},required(...r){return YS(ef,this,r[0])}})});function p(e,t){let r={type:"object",shape:e??{},...M(t)};return new Gm(r)}function D(e,t){return new Gm({type:"object",shape:e,catchall:A(),...M(t)})}var Ym=_("ZodUnion",(e,t)=>{el.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n),e.options=t.options});function T(e,t){return new Ym({type:"union",options:e,...M(t)})}var F_=_("ZodDiscriminatedUnion",(e,t)=>{Ym.init(e,t),ch.init(e,t)});function po(e,t,r){return new F_({type:"union",options:t,discriminator:e,...M(r)})}var H_=_("ZodIntersection",(e,t)=>{lh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n)});function $t(e,t){return new H_({type:"intersection",left:e,right:t})}var Zm=_("ZodRecord",(e,t)=>{uh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nl(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function P(e,t,r){if(!t||!t._zod)return new Zm({type:"record",keyType:c(),valueType:e,...M(t)});return new Zm({type:"record",keyType:e,valueType:t,...M(r)})}var Hl=_("ZodEnum",(e,t)=>{dh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,s)=>Pl(e,o,n,s),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let s={};for(let i of o)if(r.has(i))s[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new Hl({...t,checks:[],...M(n),entries:s})},e.exclude=(o,n)=>{let s={...t.entries};for(let i of o)if(r.has(i))delete s[i];else throw Error(`Key ${i} not found in enum`);return new Hl({...t,checks:[],...M(n),entries:s})}});function K(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new Hl({type:"enum",entries:r,...M(t)})}var V_=_("ZodLiteral",(e,t)=>{ph.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Tl(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function h(e,t){return new V_({type:"literal",values:Array.isArray(e)?e:[e],...M(t)})}var J_=_("ZodTransform",(e,t)=>{hh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kl(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new On(e.constructor.name);r.addIssue=(s)=>{if(typeof s==="string")r.issues.push(wr(s,r.value,t));else{let i=s;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(wr(i))}};let n=t.transform(r.value,r);if(n instanceof Promise)return n.then((s)=>(r.value=s,r.fallback=!0,r));return r.value=n,r.fallback=!0,r}});function Xm(e){return new J_({type:"transform",transform:e})}var Qm=_("ZodOptional",(e,t)=>{tl.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ka(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function j(e){return new Qm({type:"optional",innerType:e})}var B_=_("ZodExactOptional",(e,t)=>{mh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ka(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function W_(e){return new B_({type:"optional",innerType:e})}var K_=_("ZodNullable",(e,t)=>{fh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Dm(e){return new K_({type:"nullable",innerType:e})}var G_=_("ZodDefault",(e,t)=>{gh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Y_(e,t){return new G_({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Zc(t)}})}var X_=_("ZodPrefault",(e,t)=>{Sh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Q_(e,t){return new X_({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Zc(t)}})}var ef=_("ZodNonOptional",(e,t)=>{_h.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function eb(e,t){return new ef({type:"nonoptional",innerType:e,...M(t)})}var tb=_("ZodCatch",(e,t)=>{bh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function rb(e,t){return new tb({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var tf=_("ZodPipe",(e,t)=>{rl.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n),e.in=t.in,e.out=t.out});function Fm(e,t){return new tf({type:"pipe",in:e,out:t})}var ob=_("ZodPreprocess",(e,t)=>{tf.init(e,t),yh.init(e,t)}),nb=_("ZodReadonly",(e,t)=>{vh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function sb(e){return new nb({type:"readonly",innerType:e})}var ib=_("ZodLazy",(e,t)=>{zh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dl(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function Bn(e){return new ib({type:"lazy",getter:e})}var ab=_("ZodCustom",(e,t)=>{wh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>El(e,r,o,n)});function cb(e,t={}){return am(ab,e,t)}function lb(e,t){return cm(e,t)}function xr(e,t){return new ob({type:"pipe",in:Xm(e),out:t})}var of={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var rf;(function(e){})(rf||(rf={}));function ub(e){return Xh(qa,e)}je(ol());var ho="2025-11-25";var Ma=[ho,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ja="io.modelcontextprotocol/related-task",It="io.modelcontextprotocol/protocolVersion",mo="io.modelcontextprotocol/clientInfo",Ot="io.modelcontextprotocol/serverInfo",Pr="io.modelcontextprotocol/clientCapabilities",Wn="io.modelcontextprotocol/subscriptionId",fo="io.modelcontextprotocol/logLevel";var Tr="2.0";var Ct=Bn(()=>T([c(),z(),E(),Rr(),P(c(),Ct),g(Ct)])),le=P(c(),Ct),La=g(Ct),go=T([c(),z().int()]),So=c(),Kn=p({ttl:z().optional()}),Gn=p({taskId:c()}),_o=D({progressToken:go.optional(),[ja]:Gn.optional()}),ye=p({_meta:_o.optional()}),er=ye.extend({task:Kn.optional()}),ue=p({method:c(),params:ye.loose().optional()}),Te=p({_meta:_o.optional()}),we=p({method:c(),params:Te.loose().optional()}),bo=D({get[Ot](){return _t.optional().catch(void 0)}}),de=D({_meta:bo.optional()}),nt=T([c(),z().int()]),yo=p({jsonrpc:h(Tr),id:nt,...ue.shape}).strict(),vo=p({jsonrpc:h(Tr),...we.shape}).strict(),Er=p({jsonrpc:h(Tr),id:nt,result:de}).strict(),kr=p({jsonrpc:h(Tr),id:nt.optional(),error:p({code:z().int(),message:c(),data:A().optional()})}).strict(),st=T([yo,vo,Er,kr]),Ua=T([Er,kr]),tr=de.strict(),Yn=Te.extend({requestId:nt.optional(),reason:c().optional()}),zo=we.extend({method:h("notifications/cancelled"),params:Yn}),Xn=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),Nt=p({icons:g(Xn).optional()}),St=p({name:c(),title:c().optional()}),_t=St.extend({...St.shape,...Nt.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),pb=$t(p({applyDefaults:E().optional()}),le),hb=xr((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)&&Object.keys(e).length===0)return{form:{}};return e},$t(p({form:pb.optional(),url:le.optional()}),le.optional())),Za=D({list:le.optional(),cancel:le.optional(),requests:D({sampling:D({createMessage:le.optional()}).optional(),elicitation:D({create:le.optional()}).optional()}).optional()}),Da=D({list:le.optional(),cancel:le.optional(),requests:D({tools:D({call:le.optional()}).optional()}).optional()}),Qn=p({experimental:P(c(),le).optional(),sampling:p({context:le.optional(),tools:le.optional()}).optional(),elicitation:hb.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:Za.optional(),extensions:P(c(),le).optional()}),es=ye.extend({protocolVersion:c(),capabilities:Qn,clientInfo:_t}),wo=ue.extend({method:h("initialize"),params:es}),Ro=p({experimental:P(c(),le).optional(),logging:le.optional(),completions:le.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:Da.optional(),extensions:P(c(),le).optional()}),ts=de.extend({protocolVersion:c(),capabilities:Ro,serverInfo:_t,instructions:c().optional()}),xo=we.extend({method:h("notifications/initialized"),params:Te.optional()}),rs=ue.extend({method:h("server/discover"),params:ye.optional()}),rr=de.extend({supportedVersions:g(c()),capabilities:Ro,instructions:c().optional()}),Po=ue.extend({method:h("ping"),params:ye.optional()}),os=p({progress:z(),total:j(z()),message:j(c())}),ns=p({...Te.shape,...os.shape,progressToken:go}),To=we.extend({method:h("notifications/progress"),params:ns}),ss=ye.extend({cursor:So.optional()}),qt=ue.extend({params:ss.optional()}),At=de.extend({nextCursor:So.optional()}),Eo=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),ko=Eo.extend({text:c()}),Wl=c().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),$o=Eo.extend({blob:Wl}),Mt=K(["user","assistant"]),bt=p({audience:g(Mt).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),Co=p({...St.shape,...Nt.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:bt.optional(),_meta:j(D({}))}),is=p({...St.shape,...Nt.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:bt.optional(),_meta:j(D({}))}),as=qt.extend({method:h("resources/list")}),cs=At.extend({resources:g(Co)}),ls=qt.extend({method:h("resources/templates/list")}),us=At.extend({resourceTemplates:g(is)}),$r=ye.extend({uri:c()}),ds=$r,ps=ue.extend({method:h("resources/read"),params:ds}),hs=de.extend({contents:g(T([ko,$o]))}),ms=we.extend({method:h("notifications/resources/list_changed"),params:Te.optional()}),fs=$r,gs=ue.extend({method:h("resources/subscribe"),params:fs}),Ss=$r,_s=ue.extend({method:h("resources/unsubscribe"),params:Ss}),Io=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:g(c()).optional()}),bs=ye.extend({notifications:Io}),ys=ue.extend({method:h("subscriptions/listen"),params:bs}),vs=Te.extend({notifications:Io}),zs=we.extend({method:h("notifications/subscriptions/acknowledged"),params:vs}),ws=bo.extend({[Wn]:nt}),Rs=de.extend({_meta:ws}),xs=Te.extend({uri:c()}),Ps=we.extend({method:h("notifications/resources/updated"),params:xs}),Ts=p({name:c(),description:j(c()),required:j(E())}),Es=p({...St.shape,...Nt.shape,description:j(c()),arguments:j(g(Ts)),_meta:j(D({}))}),ks=qt.extend({method:h("prompts/list")}),$s=At.extend({prompts:g(Es)}),Cs=ye.extend({name:c(),arguments:P(c(),c()).optional()}),Is=ue.extend({method:h("prompts/get"),params:Cs}),Cr=p({type:h("text"),text:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Ir=p({type:h("image"),data:Wl,mimeType:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Or=p({type:h("audio"),data:Wl,mimeType:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Os=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),Nr=p({type:h("resource"),resource:T([ko,$o]),annotations:bt.optional(),_meta:P(c(),A()).optional()}),qr=Co.extend({type:h("resource_link")}),yt=T([Cr,Ir,Or,qr,Nr]),Ns=p({role:Mt,content:yt}),qs=de.extend({description:c().optional(),messages:g(Ns)}),As=we.extend({method:h("notifications/prompts/list_changed"),params:Te.optional()}),Ms=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),js=p({taskSupport:K(["required","optional","forbidden"]).optional()}),or=p({...St.shape,...Nt.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),Ct).optional(),required:g(c()).optional()}).catchall(A()),outputSchema:D({$schema:c().optional()}).optional(),annotations:Ms.optional(),execution:js.optional(),_meta:P(c(),A()).optional()}),Ls=qt.extend({method:h("tools/list")}),Us=At.extend({tools:g(or)}),nr=de.extend({content:g(yt).default([]),structuredContent:A().optional(),isError:E().optional()}),Fa=nr.or(de.extend({toolResult:A()})),Zs=er.extend({name:c(),arguments:P(c(),A()).optional()}),Ds=ue.extend({method:h("tools/call"),params:Zs}),Fs=we.extend({method:h("notifications/tools/list_changed"),params:Te.optional()}),Hs=p({autoRefresh:E().default(!0),debounceMs:z().int().nonnegative().default(300)}),Oo=K(["debug","info","notice","warning","error","critical","alert","emergency"]),Vs=ye.extend({level:Oo}),Js=ue.extend({method:h("logging/setLevel"),params:Vs}),Bs=Te.extend({level:Oo,logger:c().optional(),data:A()}),Ar=we.extend({method:h("notifications/message"),params:Bs}),Ws=p({name:c().optional()}),Ks=p({hints:g(Ws).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),Gs=p({mode:K(["auto","required","none"]).optional()}),Ys=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:g(yt),structuredContent:A().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),Xs=po("type",[Cr,Ir,Or]),Qt=po("type",[Cr,Ir,Or,Os,Ys]),Qs=p({role:Mt,content:T([Qt,g(Qt)]),_meta:P(c(),A()).optional()}),ei=er.extend({messages:g(Qs),modelPreferences:Ks.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:le.optional(),tools:g(or).optional(),toolChoice:Gs.optional()}),ti=ue.extend({method:h("sampling/createMessage"),params:ei}),ri=de.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Mt,content:Xs}),oi=de.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Mt,content:T([Qt,g(Qt)])}),No=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),Mr=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),jr=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),qo=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),Ao=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),Mo=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),ni=T([qo,Ao]),jo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),Lo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),si=T([jo,Lo]),ii=T([Mo,ni,si]),Uo=T([ii,No,Mr,jr]),Lr=er.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),Uo),required:g(c()).optional()}).catchall(A())}),ai=er.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),ci=T([Lr,ai]),li=ue.extend({method:h("elicitation/create"),params:ci}),ui=Te.extend({elicitationId:c()}),di=we.extend({method:h("notifications/elicitation/complete"),params:ui}),pi=de.extend({action:K(["accept","decline","cancel"]),content:xr((e)=>e===null?void 0:e,P(c(),T([c(),z(),E(),g(c())])).optional())}),hi=p({type:h("ref/resource"),uri:c()}),mi=p({type:h("ref/prompt"),name:c()}),fi=ye.extend({ref:T([mi,hi]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),gi=ue.extend({method:h("completion/complete"),params:fi}),Si=de.extend({completion:D({values:g(c()).max(100),total:j(z().int()),hasMore:j(E())})}),_i=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),bi=ue.extend({method:h("roots/list"),params:ye.optional()}),yi=de.extend({roots:g(_i)}),vi=we.extend({method:h("notifications/roots/list_changed"),params:Te.optional()}),Ha=D({ttl:z().optional(),pollInterval:z().optional()}),zi=K(["working","input_required","completed","failed","cancelled"]),jt=p({taskId:c(),status:zi,ttl:T([z(),Rr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:j(z()),statusMessage:j(c())}),Va=de.extend({task:jt}),wi=Te.merge(jt),Ja=we.extend({method:h("notifications/tasks/status"),params:wi}),Ba=ue.extend({method:h("tasks/get"),params:ye.extend({taskId:c()})}),Wa=de.merge(jt),Ka=ue.extend({method:h("tasks/result"),params:ye.extend({taskId:c()})}),Ga=de.loose(),Ya=qt.extend({method:h("tasks/list")}),Xa=At.extend({tasks:g(jt)}),Qa=ue.extend({method:h("tasks/cancel"),params:ye.extend({taskId:c()})}),ec=de.merge(jt),tc=T([Po,wo,rs,gi,Js,Is,ks,as,ls,ps,gs,_s,ys,Ds,Ls]),rc=T([zo,To,xo,vi]),oc=T([tr,ri,oi,pi,yi]),nc=T([Po,ti,li,bi]),sc=T([zo,To,Ar,Ps,ms,Fs,As,zs,di]),ic=T([tr,ts,rr,Si,qs,$s,cs,us,hs,nr,Us,Rs]),be=Na().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:of.custom,message:"URL must be parseable",fatal:!0}),Ac}).refine((e)=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Zo=D({resource:c().url(),authorization_servers:g(be).optional(),jwks_uri:c().url().optional(),scopes_supported:g(c()).optional(),bearer_methods_supported:g(c()).optional(),resource_signing_alg_values_supported:g(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:E().optional(),authorization_details_types_supported:g(c()).optional(),dpop_signing_alg_values_supported:g(c()).optional(),dpop_bound_access_tokens_required:E().optional()}),Ur=D({issuer:c(),authorization_endpoint:be,token_endpoint:be,registration_endpoint:be.optional(),scopes_supported:g(c()).optional(),response_types_supported:g(c()),response_modes_supported:g(c()).optional(),grant_types_supported:g(c()).optional(),token_endpoint_auth_methods_supported:g(c()).optional(),token_endpoint_auth_signing_alg_values_supported:g(c()).optional(),service_documentation:be.optional(),revocation_endpoint:be.optional(),revocation_endpoint_auth_methods_supported:g(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:g(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:g(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:g(c()).optional(),code_challenge_methods_supported:g(c()).optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0),dpop_signing_alg_values_supported:g(c()).optional()}),Ri=D({issuer:c(),authorization_endpoint:be,token_endpoint:be,userinfo_endpoint:be.optional(),jwks_uri:be,registration_endpoint:be.optional(),scopes_supported:g(c()).optional(),response_types_supported:g(c()),response_modes_supported:g(c()).optional(),grant_types_supported:g(c()).optional(),acr_values_supported:g(c()).optional(),subject_types_supported:g(c()),id_token_signing_alg_values_supported:g(c()),id_token_encryption_alg_values_supported:g(c()).optional(),id_token_encryption_enc_values_supported:g(c()).optional(),userinfo_signing_alg_values_supported:g(c()).optional(),userinfo_encryption_alg_values_supported:g(c()).optional(),userinfo_encryption_enc_values_supported:g(c()).optional(),request_object_signing_alg_values_supported:g(c()).optional(),request_object_encryption_alg_values_supported:g(c()).optional(),request_object_encryption_enc_values_supported:g(c()).optional(),token_endpoint_auth_methods_supported:g(c()).optional(),token_endpoint_auth_signing_alg_values_supported:g(c()).optional(),display_values_supported:g(c()).optional(),claim_types_supported:g(c()).optional(),claims_supported:g(c()).optional(),service_documentation:c().optional(),claims_locales_supported:g(c()).optional(),ui_locales_supported:g(c()).optional(),claims_parameter_supported:E().optional(),request_parameter_supported:E().optional(),request_uri_parameter_supported:E().optional(),require_request_uri_registration:E().optional(),op_policy_uri:be.optional(),op_tos_uri:be.optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0)}),Do=p({...Ri.shape,...Ur.pick({code_challenge_methods_supported:!0}).shape}),Fo=p({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:ub().optional(),scope:c().optional(),refresh_token:c().optional(),issuer:c().optional().catch(void 0)}).strip(),xi=p({issued_token_type:h("urn:ietf:params:oauth:token-type:id-jag"),access_token:c(),token_type:c().optional(),expires_in:z().optional(),scope:c().optional()}).strip(),Ho=p({error:c(),error_description:c().optional(),error_uri:c().optional()}),Bl=be.optional().or(h("").transform(()=>{return})),Pi=p({redirect_uris:g(be),token_endpoint_auth_method:c().optional(),grant_types:g(c()).optional(),response_types:g(c()).optional(),application_type:c().optional(),client_name:c().optional(),client_uri:be.optional(),logo_uri:Bl,scope:c().optional(),contacts:g(c()).optional(),tos_uri:Bl,policy_uri:c().optional(),jwks_uri:be.optional(),jwks:Aa().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Ti=p({client_id:c(),client_secret:c().optional(),client_id_issued_at:z().optional(),client_secret_expires_at:z().optional(),issuer:c().optional().catch(void 0)}).strip(),Vo=Pi.merge(Ti),ac=p({error:c(),error_description:c().optional()}).strip(),cc=p({token:c(),token_type_hint:c().optional()}).strip();var Ql=Symbol.for("mcp.sdk.errorBrands");function Zr(e,t){let r=new Set,o=t;while(typeof o==="function"){let n=o.mcpBrand;if(Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof n==="string")r.add(n);o=Object.getPrototypeOf(o)}if(r.size===0)return;Object.defineProperty(e,Ql,{value:r,enumerable:!1,configurable:!0})}function Be(e,t){try{if(typeof t==="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand==="string"&&Object.prototype.hasOwnProperty.call(t,Ql)){let r=t[Ql];if(r&&typeof r.has==="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var Ut=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}({}),Dr=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Be(this,t)}static isInstance(t){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,t)}constructor(t,r,o){super(r);this.code=t,this.errorUri=o,this.name="OAuthError",Zr(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};if(this.errorUri)t.error_uri=this.errorUri;return t}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}},O=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}({}),N=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e,t,r,o){super(t,o);this.code=e,this.data=r,this.name="SdkError",Zr(this,new.target)}},vt=class extends N{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,o){super(e,t,r,o);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function $f(e){let t=typeof e==="string"?new URL(e):new URL(e.href);return t.hash="",t}function nu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}function Cf({requestedResource:e,configuredResource:t}){let r=typeof e==="string"?new URL(e):new URL(e.href),o=typeof t==="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin)return!1;if(r.pathname.length<o.pathname.length)return!1;let n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(s)}var If="2026-07-28",su=[If];function Zt(e){return e>=If}function iu(e){return e.filter((t)=>!Zt(t))}function Oi(e){return e.filter((t)=>Zt(t))}function Of(e){let t=e.structuredContent;if(t===void 0)return e;if(!(typeof t!=="object"||t===null||Array.isArray(t)))return e;if(e.content?.some((r)=>r.type==="text")??!1)return e;return{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}var Nf=["task","inputRequests","requestState"];function mb(e){if(e===null||typeof e!=="object"||Array.isArray(e)||e.content!==void 0||Nf.some((t)=>(t in e)))return e;return{...e,content:[]}}function fb(){let e=Bn(()=>T([c(),z(),E(),Rr(),P(c(),e),g(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=p({ttl:z().optional()}),s=p({taskId:c()}),i=D({progressToken:r.optional(),"io.modelcontextprotocol/related-task":s.optional()}),a=p({_meta:i.optional()}),l=a.extend({task:n.optional()}),u=p({method:c(),params:a.loose().optional()}),d=p({_meta:i.optional()}),m=p({method:c(),params:d.loose().optional()}),f=D({_meta:i.optional()}),S=T([c(),z().int()]),b=f.strict(),y=d.extend({requestId:S.optional(),reason:c().optional()}),v=m.extend({method:h("notifications/cancelled"),params:y}),L=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),F=p({icons:g(L).optional()}),x=p({name:c(),title:c().optional()}),U=x.extend({...x.shape,...F.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),R=$t(p({applyDefaults:E().optional()}),t),w=xr((Pe)=>{if(Pe&&typeof Pe==="object"&&!Array.isArray(Pe)&&Object.keys(Pe).length===0)return{form:{}};return Pe},$t(p({form:R.optional(),url:t.optional()}),t.optional())),Z=D({list:t.optional(),cancel:t.optional(),requests:D({sampling:D({createMessage:t.optional()}).optional(),elicitation:D({create:t.optional()}).optional()}).optional()}),X=D({list:t.optional(),cancel:t.optional(),requests:D({tools:D({call:t.optional()}).optional()}).optional()}),Y=p({experimental:P(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:w.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:Z.optional(),extensions:P(c(),t).optional()}),ce=a.extend({protocolVersion:c(),capabilities:Y,clientInfo:U}),Ee=u.extend({method:h("initialize"),params:ce}),te=p({experimental:P(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:X.optional(),extensions:P(c(),t).optional()}),se=f.extend({protocolVersion:c(),capabilities:te,serverInfo:U,instructions:c().optional()}),ve=m.extend({method:h("notifications/initialized"),params:d.optional()}),ke=u.extend({method:h("ping"),params:a.optional()}),ct=p({progress:z(),total:j(z()),message:j(c())}),qe=p({...d.shape,...ct.shape,progressToken:r}),We=m.extend({method:h("notifications/progress"),params:qe}),lt=a.extend({cursor:o.optional()}),Ze=u.extend({params:lt.optional()}),$e=f.extend({nextCursor:o.optional()}),Tt=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),Et=Tt.extend({text:c()}),ut=c().refine((Pe)=>{try{return atob(Pe),!0}catch{return!1}},{message:"Invalid Base64 string"}),Re=Tt.extend({blob:ut}),Ce=K(["user","assistant"]),Ie=p({audience:g(Ce).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),et=p({...x.shape,...F.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:Ie.optional(),_meta:j(D({}))}),lr=p({...x.shape,...F.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:Ie.optional(),_meta:j(D({}))}),De=Ze.extend({method:h("resources/list")}),Fe=$e.extend({resources:g(et)}),Ae=Ze.extend({method:h("resources/templates/list")}),Ke=$e.extend({resourceTemplates:g(lr)}),Ge=a.extend({uri:c()}),dt=Ge,pt=u.extend({method:h("resources/read"),params:dt}),Ht=f.extend({contents:g(T([Et,Re]))}),ht=m.extend({method:h("notifications/resources/list_changed"),params:d.optional()}),ur=Ge,C=u.extend({method:h("resources/subscribe"),params:ur}),mt=Ge,H=u.extend({method:h("resources/unsubscribe"),params:mt}),q=d.extend({uri:c()}),G=m.extend({method:h("notifications/resources/updated"),params:q}),I=p({name:c(),description:j(c()),required:j(E())}),k=p({...x.shape,...F.shape,description:j(c()),arguments:j(g(I)),_meta:j(D({}))}),B=Ze.extend({method:h("prompts/list")}),J=$e.extend({prompts:g(k)}),ge=a.extend({name:c(),arguments:P(c(),c()).optional()}),dr=u.extend({method:h("prompts/get"),params:ge}),ft=p({type:h("text"),text:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),pr=p({type:h("image"),data:ut,mimeType:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),hr=p({type:h("audio"),data:ut,mimeType:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),nn=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),Vt=p({type:h("resource"),resource:T([Et,Re]),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),sn=et.extend({type:h("resource_link")}),Ye=T([ft,pr,hr,sn,Vt]),Kr=p({role:Ce,content:Ye}),Gr=f.extend({description:c().optional(),messages:g(Kr)}),mr=m.extend({method:h("notifications/prompts/list_changed"),params:d.optional()}),an=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Yr=p({taskSupport:K(["required","optional","forbidden"]).optional()}),fr=p({...x.shape,...F.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:g(c()).optional()}).catchall(A()),outputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:g(c()).optional()}).catchall(A()).optional(),annotations:an.optional(),execution:Yr.optional(),_meta:P(c(),A()).optional()}),Xr=Ze.extend({method:h("tools/list")}),Qr=$e.extend({tools:g(fr)}),eo=f.extend({content:g(Ye),structuredContent:P(c(),A()).optional(),isError:E().optional()}),xe=l.extend({name:c(),arguments:P(c(),A()).optional()}),cn=u.extend({method:h("tools/call"),params:xe}),Gi=m.extend({method:h("notifications/tools/list_changed"),params:d.optional()}),to=K(["debug","info","notice","warning","error","critical","alert","emergency"]),ln=a.extend({level:to}),un=u.extend({method:h("logging/setLevel"),params:ln}),dn=d.extend({level:to,logger:c().optional(),data:A()}),pn=m.extend({method:h("notifications/message"),params:dn}),hn=p({name:c().optional()}),mn=p({hints:g(hn).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),fn=p({mode:K(["auto","required","none"]).optional()}),Yi=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:g(Ye),structuredContent:p({}).loose().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),gn=po("type",[ft,pr,hr]),Jt=po("type",[ft,pr,hr,nn,Yi]),Sn=p({role:Ce,content:T([Jt,g(Jt)]),_meta:P(c(),A()).optional()}),_n=l.extend({messages:g(Sn),modelPreferences:mn.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:t.optional(),tools:g(fr).optional(),toolChoice:fn.optional()}),bn=u.extend({method:h("sampling/createMessage"),params:_n}),yn=f.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Ce,content:gn}),vn=f.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Ce,content:T([Jt,g(Jt)])}),zn=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),wn=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),Rn=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),xn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),Pn=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),Tn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),En=T([xn,Pn]),gr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),Sr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),Xi=T([gr,Sr]),Qi=T([Tn,En,Xi]),He=T([Qi,zn,wn,Rn]),Ve=l.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),He),required:g(c()).optional()}).catchall(A())}),kn=l.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),tt=T([Ve,kn]),ea=u.extend({method:h("elicitation/create"),params:tt}),ta=d.extend({elicitationId:c()}),ra=m.extend({method:h("notifications/elicitation/complete"),params:ta}),oa=f.extend({action:K(["accept","decline","cancel"]),content:xr((Pe)=>Pe===null?void 0:Pe,P(c(),T([c(),z(),E(),g(c())])).optional())}),na=p({type:h("ref/resource"),uri:c()}),sa=p({type:h("ref/prompt"),name:c()}),ia=a.extend({ref:T([sa,na]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),$n=u.extend({method:h("completion/complete"),params:ia}),aa=f.extend({completion:D({values:g(c()).max(100),total:j(z().int()),hasMore:j(E())})}),ca=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),ro=u.extend({method:h("roots/list"),params:a.optional()}),Cn=f.extend({roots:g(ca)}),la=m.extend({method:h("notifications/roots/list_changed"),params:d.optional()}),ua=D({ttl:z().optional(),pollInterval:z().optional()}),In=K(["working","input_required","completed","failed","cancelled"]),Bt=p({taskId:c(),status:In,ttl:T([z(),Rr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:j(z()),statusMessage:j(c())}),Me=f.extend({task:Bt}),da=d.merge(Bt),_r=m.extend({method:h("notifications/tasks/status"),params:da}),oo=u.extend({method:h("tasks/get"),params:a.extend({taskId:c()})}),no=f.merge(Bt),so=u.extend({method:h("tasks/result"),params:a.extend({taskId:c()})}),qc=f.loose(),Oe=Ze.extend({method:h("tasks/list")}),fe=$e.extend({tasks:g(Bt)}),br=u.extend({method:h("tasks/cancel"),params:a.extend({taskId:c()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:n,RelatedTaskMetadataSchema:s,RequestMetaSchema:i,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:l,RequestSchema:u,NotificationsParamsSchema:d,NotificationSchema:m,ResultSchema:f,RequestIdSchema:S,EmptyResultSchema:b,CancelledNotificationParamsSchema:y,CancelledNotificationSchema:v,IconSchema:L,IconsSchema:F,BaseMetadataSchema:x,ImplementationSchema:U,ClientTasksCapabilitySchema:Z,ServerTasksCapabilitySchema:X,ClientCapabilitiesSchema:Y,InitializeRequestParamsSchema:ce,InitializeRequestSchema:Ee,ServerCapabilitiesSchema:te,InitializeResultSchema:se,InitializedNotificationSchema:ve,PingRequestSchema:ke,ProgressSchema:ct,ProgressNotificationParamsSchema:qe,ProgressNotificationSchema:We,PaginatedRequestParamsSchema:lt,PaginatedRequestSchema:Ze,PaginatedResultSchema:$e,ResourceContentsSchema:Tt,TextResourceContentsSchema:Et,BlobResourceContentsSchema:Re,RoleSchema:Ce,AnnotationsSchema:Ie,ResourceSchema:et,ResourceTemplateSchema:lr,ListResourcesRequestSchema:De,ListResourcesResultSchema:Fe,ListResourceTemplatesRequestSchema:Ae,ListResourceTemplatesResultSchema:Ke,ResourceRequestParamsSchema:Ge,ReadResourceRequestParamsSchema:dt,ReadResourceRequestSchema:pt,ReadResourceResultSchema:Ht,ResourceListChangedNotificationSchema:ht,SubscribeRequestParamsSchema:ur,SubscribeRequestSchema:C,UnsubscribeRequestParamsSchema:mt,UnsubscribeRequestSchema:H,ResourceUpdatedNotificationParamsSchema:q,ResourceUpdatedNotificationSchema:G,PromptArgumentSchema:I,PromptSchema:k,ListPromptsRequestSchema:B,ListPromptsResultSchema:J,GetPromptRequestParamsSchema:ge,GetPromptRequestSchema:dr,TextContentSchema:ft,ImageContentSchema:pr,AudioContentSchema:hr,ToolUseContentSchema:nn,EmbeddedResourceSchema:Vt,ResourceLinkSchema:sn,ContentBlockSchema:Ye,PromptMessageSchema:Kr,GetPromptResultSchema:Gr,PromptListChangedNotificationSchema:mr,ToolAnnotationsSchema:an,ToolExecutionSchema:Yr,ToolSchema:fr,ListToolsRequestSchema:Xr,ListToolsResultSchema:Qr,CallToolResultSchema:eo,CallToolRequestParamsSchema:xe,CallToolRequestSchema:cn,ToolListChangedNotificationSchema:Gi,LoggingLevelSchema:to,SetLevelRequestParamsSchema:ln,SetLevelRequestSchema:un,LoggingMessageNotificationParamsSchema:dn,LoggingMessageNotificationSchema:pn,ModelHintSchema:hn,ModelPreferencesSchema:mn,ToolChoiceSchema:fn,ToolResultContentSchema:Yi,SamplingContentSchema:gn,SamplingMessageContentBlockSchema:Jt,SamplingMessageSchema:Sn,CreateMessageRequestParamsSchema:_n,CreateMessageRequestSchema:bn,CreateMessageResultSchema:yn,CreateMessageResultWithToolsSchema:vn,BooleanSchemaSchema:zn,StringSchemaSchema:wn,NumberSchemaSchema:Rn,UntitledSingleSelectEnumSchemaSchema:xn,TitledSingleSelectEnumSchemaSchema:Pn,LegacyTitledEnumSchemaSchema:Tn,SingleSelectEnumSchemaSchema:En,UntitledMultiSelectEnumSchemaSchema:gr,TitledMultiSelectEnumSchemaSchema:Sr,MultiSelectEnumSchemaSchema:Xi,EnumSchemaSchema:Qi,PrimitiveSchemaDefinitionSchema:He,ElicitRequestFormParamsSchema:Ve,ElicitRequestURLParamsSchema:kn,ElicitRequestParamsSchema:tt,ElicitRequestSchema:ea,ElicitationCompleteNotificationParamsSchema:ta,ElicitationCompleteNotificationSchema:ra,ElicitResultSchema:oa,ResourceTemplateReferenceSchema:na,PromptReferenceSchema:sa,CompleteRequestParamsSchema:ia,CompleteRequestSchema:$n,CompleteResultSchema:aa,RootSchema:ca,ListRootsRequestSchema:ro,ListRootsResultSchema:Cn,RootsListChangedNotificationSchema:la,TaskCreationParamsSchema:ua,TaskStatusSchema:In,TaskSchema:Bt,CreateTaskResultSchema:Me,TaskStatusNotificationParamsSchema:da,TaskStatusNotificationSchema:_r,GetTaskRequestSchema:oo,GetTaskResultSchema:no,GetTaskPayloadRequestSchema:so,GetTaskPayloadResultSchema:qc,ListTasksRequestSchema:Oe,ListTasksResultSchema:fe,CancelTaskRequestSchema:br,CancelTaskResultSchema:f.merge(Bt),ClientRequestSchema:T([ke,Ee,$n,un,dr,B,De,Ae,pt,C,H,cn,Xr,oo,so,Oe,br]),ClientNotificationSchema:T([v,We,ve,la,_r]),ClientResultSchema:T([b,yn,vn,oa,Cn,no,fe,Me]),ServerRequestSchema:T([ke,bn,ea,ro,oo,so,Oe,br]),ServerNotificationSchema:T([v,We,pn,G,ht,Gi,mr,_r,ra]),ServerResultSchema:T([b,se,aa,Gr,J,Fe,Ke,Ht,eo,Qr,no,fe,Me]),CallToolResultWireSchema:A().superRefine((Pe,NS)=>{if(typeof Pe!=="object"||Pe===null||Array.isArray(Pe)||Pe.content!==void 0)return;for(let td of Nf)if(td in Pe){NS.addIssue({code:"custom",message:`content is required when the body carries '${td}' — another result family cannot default into an empty tools/call success`});return}}).transform(mb).pipe(eo)}}var gb;function qf(){return gb??=fb()}function Af(e){return e.type!=="object"}var Sb=new Set(["const","enum","default","examples"]),_b=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function gf(e){return e!==void 0&&!(typeof e==="string"&&e.startsWith("#"))}function bb(e){let t=typeof e.$schema==="string"?e.$schema:void 0;if(gf(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=id(e.$schema)&&e.$recursiveAnchor!==!0,o=(n,s)=>{if(Array.isArray(n))return n.map((l)=>o(l,!1));if(n===null||typeof n!=="object")return n;if(!s&&gf(n.$id))return n;let i={},a=!1;for(let[l,u]of Object.entries(n))if(s)i[l]=o(u,!1);else if((l==="$ref"||l==="$dynamicRef")&&typeof u==="string")i[l]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u;else if(l==="$recursiveRef"&&u==="#"&&r)a=!0;else if(Sb.has(l))i[l]=u;else if(_b.has(l))i[l]=o(u,!0);else i[l]=o(u,!1);if(a)if("$ref"in i)i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:"#/properties/result"}];else i.$ref="#/properties/result";return i};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}var Mf={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},jf={"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},yb={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},lc;function au(){if(lc)return lc;let e=qf();return lc={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}},lc}function Lf(e){return Object.prototype.hasOwnProperty.call(Mf,e)}function Uf(e){return Object.prototype.hasOwnProperty.call(jf,e)}function vb(e){return Object.prototype.hasOwnProperty.call(yb,e)}function zb(e){return vb(e)?au().resultSchemas[e]:void 0}function wb(e){return Lf(e)?au().requestSchemas[e]:void 0}function Rb(e){return Uf(e)?au().notificationSchemas[e]:void 0}var Px=Object.keys(Mf),Tx=Object.keys(jf);function eu(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function uc(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var Sf={ok:!1,reason:"not-in-era"};function _f(e){return eu(e)&&eu(e.outputSchema)&&Af(e.outputSchema)}function bf(e){return e}var cu={era:"2025-11-25",hasRequestMethod:Lf,hasNotificationMethod:Uf,validateRequest:(e,t)=>uc(wb(e),t),validateResult:(e,t)=>uc(zb(e),t),validateNotification:(e,t)=>uc(Rb(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>Sf,validateInputResponse:()=>Sf,samplingResultVariant:(e,t)=>{let r=qf();return uc(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)},outboundEnvelope:(e)=>{return},validateEnvelopeMeta:(e)=>[],projectCallToolResult(e,t){let r=Of(e),o=r.structuredContent;if(o===void 0)return r;let n=typeof o!=="object"||o===null||Array.isArray(o),s=t!==void 0&&Af(t);if(!n&&!s)return r;return{...r,structuredContent:{result:o}}},decodeResult(e,t){if(eu(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:bf(r)}}return{kind:"complete",result:bf(t)}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;if(!Array.isArray(r)||!r.some((o)=>_f(o)))return t;return{...t,tools:r.map((o)=>_f(o)?{...o,outputSchema:bb(o.outputSchema)}:o)}},encodeErrorCode:(e)=>e===-32002?-32602:e,checkInboundEnvelope:(e)=>{return}};function xb(){let e=Bn(()=>T([c(),z(),E(),Rr(),P(c(),e),g(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=T([c(),z().int()]),s=K(["user","assistant"]),i=K(["debug","info","notice","warning","error","critical","alert","emergency"]),a=c().refine((fe)=>{try{return atob(fe),!0}catch{return!1}},{message:"Invalid Base64 string"}),l=p({ttl:z().optional()}),u=p({taskId:c()}),d=D({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),m=p({_meta:d.optional()}),f=m.extend({task:l.optional()}),S=p({_meta:d.optional()}),b=p({method:c(),params:S.loose().optional()}),y=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),v=p({icons:g(y).optional()}),L=p({name:c(),title:c().optional()}),F=L.extend({...L.shape,...v.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),x=$t(p({applyDefaults:E().optional()}),t),U=xr((fe)=>{if(fe&&typeof fe==="object"&&!Array.isArray(fe)&&Object.keys(fe).length===0)return{form:{}};return fe},$t(p({form:x.optional(),url:t.optional()}),t.optional())),R=D({list:t.optional(),cancel:t.optional(),requests:D({sampling:D({createMessage:t.optional()}).optional(),elicitation:D({create:t.optional()}).optional()}).optional()}),w=D({list:t.optional(),cancel:t.optional(),requests:D({tools:D({call:t.optional()}).optional()}).optional()}),Z=p({experimental:P(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:U.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:R.optional(),extensions:P(c(),t).optional()}),X=p({experimental:P(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:w.optional(),extensions:P(c(),t).optional()}),Y=p({progress:z(),total:j(z()),message:j(c())}),ce=p({...S.shape,...Y.shape,progressToken:r}),Ee=b.extend({method:h("notifications/progress"),params:ce}),te=S.extend({level:i,logger:c().optional(),data:A()}),se=b.extend({method:h("notifications/message"),params:te}),ve=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),ke=ve.extend({text:c()}),ct=ve.extend({blob:a}),qe=p({audience:g(s).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),We=p({...L.shape,...v.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:qe.optional(),_meta:j(D({}))}),lt=p({...L.shape,...v.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:qe.optional(),_meta:j(D({}))}),Ze=b.extend({method:h("notifications/resources/list_changed"),params:S.optional()}),$e=S.extend({uri:c()}),Tt=b.extend({method:h("notifications/resources/updated"),params:$e}),Et=p({name:c(),description:j(c()),required:j(E())}),ut=p({...L.shape,...v.shape,description:j(c()),arguments:j(g(Et)),_meta:j(D({}))}),Re=b.extend({method:h("notifications/prompts/list_changed"),params:S.optional()}),Ce=p({type:h("text"),text:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),Ie=p({type:h("image"),data:a,mimeType:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),et=p({type:h("audio"),data:a,mimeType:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),lr=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),De=p({type:h("resource"),resource:T([ke,ct]),annotations:qe.optional(),_meta:P(c(),A()).optional()}),Fe=We.extend({type:h("resource_link")}),Ae=T([Ce,Ie,et,Fe,De]),Ke=p({role:s,content:Ae}),Ge=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),dt=b.extend({method:h("notifications/tools/list_changed"),params:S.optional()}),pt=p({name:c().optional()}),Ht=p({hints:g(pt).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),ht=p({mode:K(["auto","required","none"]).optional()}),ur=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),C=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),mt=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),H=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),q=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),G=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),I=T([H,q]),k=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),B=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),J=T([k,B]),ge=T([G,I,J]),dr=T([ge,ur,C,mt]),ft=f.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),dr),required:g(c()).optional()}).catchall(A())}),pr=p({type:h("ref/resource"),uri:c()}),hr=p({type:h("ref/prompt"),name:c()}),nn=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),Vt=Z.shape,sn=p({experimental:Vt.experimental,sampling:Vt.sampling,elicitation:Vt.elicitation,roots:Vt.roots,extensions:Vt.extensions}),Ye=X.shape,Kr=p({experimental:Ye.experimental,logging:Ye.logging,completions:Ye.completions,prompts:Ye.prompts,resources:Ye.resources,tools:Ye.tools,extensions:Ye.extensions}),Gr=D({progressToken:r.optional(),[It]:c(),[mo]:F.optional(),[Pr]:sn,[fo]:i.optional()}),mr=p({...L.shape,...v.shape,description:c().optional(),inputSchema:D({$schema:c().optional(),type:h("object")}),outputSchema:D({$schema:c().optional()}).optional(),annotations:Ge.optional(),_meta:P(c(),A()).optional()}),an=p({type:h("tool_result"),toolUseId:c(),content:g(Ae),structuredContent:A().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),Yr=T([Ce,Ie,et,lr,an]),fr=p({role:s,content:T([Yr,g(Yr)]),_meta:P(c(),A()).optional()}),Xr=c(),Qr=D({[Ot]:F.optional().catch(void 0)}),eo=Qr.optional();function xe(fe){return D({_meta:eo,resultType:Xr.default("complete"),...fe})}let cn=xe({}),Gi=xe({nextCursor:o.optional()}),to=xe({content:g(Ae),structuredContent:A().optional(),isError:E().optional()}),ln=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:g(mr),nextCursor:o.optional()}),un=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:g(ut),nextCursor:o.optional()}),dn=xe({description:c().optional(),messages:g(Ke)}),pn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:g(We),nextCursor:o.optional()}),hn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:g(lt),nextCursor:o.optional()}),mn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:g(T([ke,ct]))}),fn=xe({completion:p({values:g(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),Yi=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"])}),gn=xe({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:g(c()),capabilities:Kr,instructions:c().optional()}),Jt=p({messages:g(fr),modelPreferences:Ht.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:t.optional(),tools:g(mr).optional(),toolChoice:ht.optional()}),Sn=p({method:h("sampling/createMessage"),params:Jt}),_n=p({method:h("roots/list"),params:p({_meta:P(c(),A()).optional()}).optional()}),bn=p({...fr.shape,model:c(),stopReason:c().optional()}),yn=p({roots:g(nn)}),vn=p({action:K(["accept","decline","cancel"]),content:P(c(),T([c(),z(),E(),g(c())])).optional()}),zn=p({mode:h("url"),message:c(),url:c().url()}),wn=T([ft,zn]),Rn=p({method:h("elicitation/create"),params:wn}),xn=T([Sn,_n,Rn]),Pn=T([bn,yn,vn]),Tn=P(c(),xn),En=P(c(),Pn),gr=xe({inputRequests:Tn.optional(),requestState:c().optional()}),Sr={inputResponses:En.optional(),requestState:c().optional()},Xi=p({_meta:Gr,...Sr}),Qi=D({progressToken:r.optional()});function He(fe,br){return p({method:h(fe),params:p({_meta:Gr,...br})})}function Ve(fe,br){return p({method:h(fe),params:p({_meta:Qi.optional(),...br}).optional()})}let kn={name:c(),arguments:P(c(),A()).optional(),...Sr},tt={cursor:o.optional()},ea=He("tools/call",kn),ta=He("tools/list",tt),ra=He("prompts/list",tt),oa=He("prompts/get",{name:c(),arguments:P(c(),c()).optional(),...Sr}),na=He("resources/list",tt),sa=He("resources/templates/list",tt),ia=He("resources/read",{uri:c(),...Sr}),$n={ref:T([hr,pr]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()},aa=He("completion/complete",$n),ca=He("server/discover",{}),ro=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:g(c()).optional()}),Cn={notifications:ro},la=He("subscriptions/listen",Cn),ua=Qr.extend({"io.modelcontextprotocol/subscriptionId":n}),In=D({_meta:ua,resultType:Xr.default("complete")}),Bt={"tools/call":Ve("tools/call",kn),"tools/list":Ve("tools/list",tt),"prompts/get":Ve("prompts/get",{name:c(),arguments:P(c(),c()).optional()}),"prompts/list":Ve("prompts/list",tt),"resources/list":Ve("resources/list",tt),"resources/templates/list":Ve("resources/templates/list",tt),"resources/read":Ve("resources/read",{uri:c()}),"completion/complete":Ve("completion/complete",$n),"server/discover":Ve("server/discover",{}),"subscriptions/listen":Ve("subscriptions/listen",Cn)};function Me(fe){return D({_meta:eo,...fe})}let da={"tools/call":Me({content:g(Ae),structuredContent:A().optional(),isError:E().optional()}),"tools/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:g(mr),nextCursor:o.optional()}),"prompts/get":Me({description:c().optional(),messages:g(Ke)}),"prompts/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:g(ut),nextCursor:o.optional()}),"resources/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:g(We),nextCursor:o.optional()}),"resources/templates/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:g(lt),nextCursor:o.optional()}),"resources/read":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:g(T([ke,ct]))}),"completion/complete":Me({completion:p({values:g(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":Me({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:g(c()),capabilities:Kr,instructions:c().optional()}),"subscriptions/listen":Me({})},_r=D({"io.modelcontextprotocol/subscriptionId":n.optional()}),oo=p({method:h("notifications/subscriptions/acknowledged"),params:p({_meta:_r.optional(),notifications:ro})}),no=p({_meta:_r.optional(),requestId:n,reason:c().optional()}),so=p({method:h("notifications/cancelled"),params:no}),qc={"notifications/cancelled":so,"notifications/progress":Ee,"notifications/message":se,"notifications/resources/updated":Tt,"notifications/resources/list_changed":Ze,"notifications/tools/list_changed":dt,"notifications/prompts/list_changed":Re,"notifications/subscriptions/acknowledged":oo},Oe=(fe)=>p({jsonrpc:h("2.0"),id:T([c(),z().int()]),result:fe}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:n,RoleSchema:s,LoggingLevelSchema:i,TaskMetadataSchema:l,RelatedTaskMetadataSchema:u,RequestMetaSchema:d,BaseRequestParamsSchema:m,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:S,NotificationSchema:b,IconSchema:y,IconsSchema:v,BaseMetadataSchema:L,ImplementationSchema:F,ClientTasksCapabilitySchema:R,ServerTasksCapabilitySchema:w,ClientCapabilitiesSchema:Z,ServerCapabilitiesSchema:X,ProgressSchema:Y,ProgressNotificationParamsSchema:ce,ProgressNotificationSchema:Ee,LoggingMessageNotificationParamsSchema:te,LoggingMessageNotificationSchema:se,ResourceContentsSchema:ve,TextResourceContentsSchema:ke,BlobResourceContentsSchema:ct,AnnotationsSchema:qe,ResourceSchema:We,ResourceTemplateSchema:lt,ResourceListChangedNotificationSchema:Ze,ResourceUpdatedNotificationParamsSchema:$e,ResourceUpdatedNotificationSchema:Tt,PromptArgumentSchema:Et,PromptSchema:ut,PromptListChangedNotificationSchema:Re,TextContentSchema:Ce,ImageContentSchema:Ie,AudioContentSchema:et,ToolUseContentSchema:lr,EmbeddedResourceSchema:De,ResourceLinkSchema:Fe,ContentBlockSchema:Ae,PromptMessageSchema:Ke,ToolAnnotationsSchema:Ge,ToolListChangedNotificationSchema:dt,ModelHintSchema:pt,ModelPreferencesSchema:Ht,ToolChoiceSchema:ht,BooleanSchemaSchema:ur,StringSchemaSchema:C,NumberSchemaSchema:mt,UntitledSingleSelectEnumSchemaSchema:H,TitledSingleSelectEnumSchemaSchema:q,LegacyTitledEnumSchemaSchema:G,SingleSelectEnumSchemaSchema:I,UntitledMultiSelectEnumSchemaSchema:k,TitledMultiSelectEnumSchemaSchema:B,MultiSelectEnumSchemaSchema:J,EnumSchemaSchema:ge,PrimitiveSchemaDefinitionSchema:dr,ElicitRequestFormParamsSchema:ft,ResourceTemplateReferenceSchema:pr,PromptReferenceSchema:hr,RootSchema:nn,ClientCapabilities2026Schema:sn,ServerCapabilities2026Schema:Kr,RequestMetaEnvelopeSchema:Gr,ToolSchema:mr,ToolResultContentSchema:an,SamplingMessageContentBlockSchema:Yr,SamplingMessageSchema:fr,ResultTypeSchema:Xr,ResultMetaSchema:Qr,ResultSchema:cn,PaginatedResultSchema:Gi,CallToolResultSchema:to,ListToolsResultSchema:ln,ListPromptsResultSchema:un,GetPromptResultSchema:dn,ListResourcesResultSchema:pn,ListResourceTemplatesResultSchema:hn,ReadResourceResultSchema:mn,CompleteResultSchema:fn,CacheableResultSchema:Yi,DiscoverResultSchema:gn,CreateMessageRequestParamsSchema:Jt,CreateMessageRequestSchema:Sn,ListRootsRequestSchema:_n,CreateMessageResultSchema:bn,ListRootsResultSchema:yn,ElicitResultSchema:vn,ElicitRequestURLParamsSchema:zn,ElicitRequestParamsSchema:wn,ElicitRequestSchema:Rn,InputRequestSchema:xn,InputResponseSchema:Pn,InputRequestsSchema:Tn,InputResponsesSchema:En,InputRequiredResultSchema:gr,InputResponseRequestParamsSchema:Xi,CallToolRequestSchema:ea,ListToolsRequestSchema:ta,ListPromptsRequestSchema:ra,GetPromptRequestSchema:oa,ListResourcesRequestSchema:na,ListResourceTemplatesRequestSchema:sa,ReadResourceRequestSchema:ia,CompleteRequestSchema:aa,DiscoverRequestSchema:ca,SubscriptionFilterSchema:ro,SubscriptionsListenRequestSchema:la,SubscriptionsListenResultMetaSchema:ua,SubscriptionsListenResultSchema:In,dispatchRequestSchemas:Bt,dispatchResultSchemas:da,NotificationMetaSchema:_r,SubscriptionsAcknowledgedNotificationSchema:oo,CancelledNotificationParamsSchema:no,CancelledNotificationSchema:so,notificationSchemas2026:qc,JSONRPCResultResponseSchema:Oe(cn),CallToolResultResponseSchema:Oe(T([to,gr])),ListToolsResultResponseSchema:Oe(ln),ListPromptsResultResponseSchema:Oe(un),GetPromptResultResponseSchema:Oe(T([dn,gr])),ListResourcesResultResponseSchema:Oe(pn),ListResourceTemplatesResultResponseSchema:Oe(hn),ReadResourceResultResponseSchema:Oe(T([mn,gr])),CompleteResultResponseSchema:Oe(fn),DiscoverResultResponseSchema:Oe(gn),SubscriptionsListenResultResponseSchema:Oe(In)}}var Pb;function sr(){return Pb??=xb()}var Tb=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function Eb(e){return Tb.includes(e)}var lu=Symbol("modelcontextprotocol.resultCacheHintFallback");function kb(e){return e[lu]}function Zf(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function Df(e){return e==="public"||e==="private"}var W=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}({}),ee=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Be(this,t)}static isInstance(t){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,t)}constructor(t,r,o){super(r);this.code=t,this.data=o,this.name="ProtocolError",Zr(this,new.target)}static fromError(t,r,o){if(t===W.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new Hf(n.elicitations,r)}if(t===W.UnsupportedProtocolVersion&&o){let n=o;if(Array.isArray(n.supported)&&typeof n.requested==="string")return new fc({supported:n.supported,requested:n.requested},r)}if(t===W.InvalidParams||t===W.ResourceNotFound){let n=o;if(typeof n?.uri==="string"&&(t===W.ResourceNotFound||Object.keys(n).length===1))return new Ff(n.uri,r)}if(t===W.MissingRequiredClientCapability&&o){let n=o;if(n.requiredCapabilities!==null&&typeof n.requiredCapabilities==="object"&&!Array.isArray(n.requiredCapabilities))return new Vf({requiredCapabilities:n.requiredCapabilities},r)}return new e(t,r,o)}},Ff=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(W.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Hf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(W.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},fc=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(W.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Vf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(W.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},$b=0,Cb="private",Ib=["tools/call","prompts/get","resources/read"];function Ob(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete")return t;if(Ib.includes(e))return t;throw new ee(W.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function Nb(e,t){let r=kb(t);if(t.resultType!=="complete"||!Eb(e))return r===void 0?t:Lb(t);let o=t,n=Zf(o.ttlMs)?o.ttlMs:Mb(r),s=Df(o.cacheScope)?o.cacheScope:jb(r),i={...o,ttlMs:n,cacheScope:s};return delete i[lu],i}function qb(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Ab(e,t){if(t===void 0)return e;let r=e._meta;if(r===void 0)return{...e,_meta:{[Ot]:t}};if(!qb(r))return e;if(r[Ot]!==void 0)return e;return{...e,_meta:{...r,[Ot]:t}}}function Mb(e){return e!==void 0&&Zf(e.ttlMs)?e.ttlMs:$b}function jb(e){return e!==void 0&&Df(e.cacheScope)?e.cacheScope:Cb}function Lb(e){let t={...e};return delete t[lu],t}var Ub=["elicitation/create","sampling/createMessage","roots/list"],dc;function Jf(){if(dc)return dc;let e=sr();return dc={request:{"elicitation/create":p({method:h("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":p({method:h("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":p({method:h("roots/list"),params:D({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},dc}function Bf(e){return Ub.includes(e)}function Kl(e){return Bf(e)?Jf().request[e]:void 0}function Zb(e){return Bf(e)?Jf().response[e]:void 0}var uu={"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},Wf={"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 Kf(e){return Object.prototype.hasOwnProperty.call(uu,e)}function Gf(e){return Object.prototype.hasOwnProperty.call(Wf,e)}function Db(e){return Object.prototype.hasOwnProperty.call(uu,e)}function Fb(e){return Kf(e)?sr().dispatchRequestSchemas[e]:void 0}function Hb(e){return Db(e)?sr().dispatchResultSchemas[e]:void 0}function Vb(e){return Gf(e)?sr().notificationSchemas2026[e]:void 0}var Ex=Object.keys(uu),kx=Object.keys(Wf);function $i(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Ei(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var Jb={ok:!1,reason:"not-in-era"},Bb=[It,Pr];function Wb(e,t){let r=t,o=!1,n=()=>{if(!o)r={...r},o=!0;return r},s=t.tools;if(e==="tools/list"&&Array.isArray(s)&&s.some((a)=>$i(a)&&("execution"in a)))n().tools=s.map((a)=>{if(!$i(a)||!("execution"in a))return a;let l={...a};return delete l.execution,l});let i=t.capabilities;if($i(i)&&"tasks"in i){let a={...i};delete a.tasks,n().capabilities=a}return r}var du={era:"2026-07-28",hasRequestMethod:Kf,hasNotificationMethod:Gf,hasInputRequestMethod:(e)=>Kl(e)!==void 0,validateRequest:(e,t)=>Ei(Fb(e),t),validateResult:(e,t)=>Ei(Hb(e),t),validateNotification:(e,t)=>Ei(Vb(e),t),validateInputRequest:(e,t)=>Ei(Kl(e),t),validateInputResponse:(e,t)=>Ei(Zb(e),t),samplingResultVariant:()=>Jb,outboundEnvelope(e){return{[It]:e.protocolVersion,[mo]:e.clientInfo,[Pr]:e.clientCapabilities,...e.logLevel!==void 0&&{[fo]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of Bb)if(!(o in e))t.push({key:o,problem:"missing"});let r=sr().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let n=o.path.map(String),s=n.length>0?n.join("."):"_meta";if(n.length===1&&t.some((i)=>i.key===s&&i.problem==="missing"))continue;t.push({key:s,problem:o.message})}return t},projectCallToolResult:(e)=>Of(e),inputRequestSchema:Kl,decodeResult(e,t){if(!$i(t))return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new N(O.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 r!=="string")return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let i=t.inputRequests,a=$i(i)?i:{},l=t.requestState,u=t._meta===void 0?void 0:sr().ResultMetaSchema.safeParse(t._meta),d=u?.success?u.data:void 0;if(Object.keys(a).length===0&&typeof l!=="string")return{kind:"invalid",error:new N(O.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"})};return{kind:"input_required",inputRequests:a,...typeof l==="string"&&{requestState:l},...d!==void 0&&{_meta:d}}}if(r!=="complete")return{kind:"invalid",error:new N(O.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=Kb(),n=Object.hasOwn(o,e)?o[e]:void 0;if(n!==void 0){let i=n.safeParse(t);if(!i.success)return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: ${i.error}`,{method:e})}}let s={...t};return delete s.resultType,{kind:"complete",result:s}},encodeResult(e,t,r){return Ab(Nb(e,Ob(e,Wb(e,t))),r)},encodeErrorCode:(e)=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=sr().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map((r)=>r.message).join("; ")}`}},pc;function Kb(){if(pc)return pc;let e=sr();return pc={"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},pc}var gc="2026-07-28";function Lt(e){return e!==void 0&&Zt(e)?du:cu}function yf(e){if(e.revision!==void 0)return Lt(e.revision).era;return e.era==="modern"?du.era:cu.era}function Gl(e){return Yf.some((t)=>t.hasRequestMethod(e))}function Yl(e){return Yf.some((t)=>t.hasNotificationMethod(e))}function vf(e){return e==="tasks/get"||e==="tasks/cancel"}var Yf=[cu,du],Gb=od({AnnotationsSchema:()=>bt,AudioContentSchema:()=>Or,BaseMetadataSchema:()=>St,BaseRequestParamsSchema:()=>ye,BlobResourceContentsSchema:()=>$o,BooleanSchemaSchema:()=>No,CallToolRequestParamsSchema:()=>Zs,CallToolRequestSchema:()=>Ds,CallToolResultSchema:()=>nr,CancelTaskRequestSchema:()=>Qa,CancelTaskResultSchema:()=>ec,CancelledNotificationParamsSchema:()=>Yn,CancelledNotificationSchema:()=>zo,ClientCapabilitiesSchema:()=>Qn,ClientNotificationSchema:()=>rc,ClientRequestSchema:()=>tc,ClientResultSchema:()=>oc,ClientTasksCapabilitySchema:()=>Za,CompatibilityCallToolResultSchema:()=>Fa,CompleteRequestParamsSchema:()=>fi,CompleteRequestSchema:()=>gi,CompleteResultSchema:()=>Si,ContentBlockSchema:()=>yt,CreateMessageRequestParamsSchema:()=>ei,CreateMessageRequestSchema:()=>ti,CreateMessageResultSchema:()=>ri,CreateMessageResultWithToolsSchema:()=>oi,CreateTaskResultSchema:()=>Va,CursorSchema:()=>So,DiscoverRequestSchema:()=>rs,DiscoverResultSchema:()=>rr,ElicitRequestFormParamsSchema:()=>Lr,ElicitRequestParamsSchema:()=>ci,ElicitRequestSchema:()=>li,ElicitRequestURLParamsSchema:()=>ai,ElicitResultSchema:()=>pi,ElicitationCompleteNotificationParamsSchema:()=>ui,ElicitationCompleteNotificationSchema:()=>di,EmbeddedResourceSchema:()=>Nr,EmptyResultSchema:()=>tr,EnumSchemaSchema:()=>ii,GetPromptRequestParamsSchema:()=>Cs,GetPromptRequestSchema:()=>Is,GetPromptResultSchema:()=>qs,GetTaskPayloadRequestSchema:()=>Ka,GetTaskPayloadResultSchema:()=>Ga,GetTaskRequestSchema:()=>Ba,GetTaskResultSchema:()=>Wa,IconSchema:()=>Xn,IconsSchema:()=>Nt,ImageContentSchema:()=>Ir,ImplementationSchema:()=>_t,InitializeRequestParamsSchema:()=>es,InitializeRequestSchema:()=>wo,InitializeResultSchema:()=>ts,InitializedNotificationSchema:()=>xo,JSONArraySchema:()=>La,JSONObjectSchema:()=>le,JSONRPCErrorResponseSchema:()=>kr,JSONRPCMessageSchema:()=>st,JSONRPCNotificationSchema:()=>vo,JSONRPCRequestSchema:()=>yo,JSONRPCResponseSchema:()=>Ua,JSONRPCResultResponseSchema:()=>Er,JSONValueSchema:()=>Ct,LegacyTitledEnumSchemaSchema:()=>Mo,ListChangedOptionsBaseSchema:()=>Hs,ListPromptsRequestSchema:()=>ks,ListPromptsResultSchema:()=>$s,ListResourceTemplatesRequestSchema:()=>ls,ListResourceTemplatesResultSchema:()=>us,ListResourcesRequestSchema:()=>as,ListResourcesResultSchema:()=>cs,ListRootsRequestSchema:()=>bi,ListRootsResultSchema:()=>yi,ListTasksRequestSchema:()=>Ya,ListTasksResultSchema:()=>Xa,ListToolsRequestSchema:()=>Ls,ListToolsResultSchema:()=>Us,LoggingLevelSchema:()=>Oo,LoggingMessageNotificationParamsSchema:()=>Bs,LoggingMessageNotificationSchema:()=>Ar,ModelHintSchema:()=>Ws,ModelPreferencesSchema:()=>Ks,MultiSelectEnumSchemaSchema:()=>si,NotificationSchema:()=>we,NotificationsParamsSchema:()=>Te,NumberSchemaSchema:()=>jr,PaginatedRequestParamsSchema:()=>ss,PaginatedRequestSchema:()=>qt,PaginatedResultSchema:()=>At,PingRequestSchema:()=>Po,PrimitiveSchemaDefinitionSchema:()=>Uo,ProgressNotificationParamsSchema:()=>ns,ProgressNotificationSchema:()=>To,ProgressSchema:()=>os,ProgressTokenSchema:()=>go,PromptArgumentSchema:()=>Ts,PromptListChangedNotificationSchema:()=>As,PromptMessageSchema:()=>Ns,PromptReferenceSchema:()=>mi,PromptSchema:()=>Es,ReadResourceRequestParamsSchema:()=>ds,ReadResourceRequestSchema:()=>ps,ReadResourceResultSchema:()=>hs,RelatedTaskMetadataSchema:()=>Gn,RequestIdSchema:()=>nt,RequestMetaSchema:()=>_o,RequestSchema:()=>ue,ResourceContentsSchema:()=>Eo,ResourceLinkSchema:()=>qr,ResourceListChangedNotificationSchema:()=>ms,ResourceRequestParamsSchema:()=>$r,ResourceSchema:()=>Co,ResourceTemplateReferenceSchema:()=>hi,ResourceTemplateSchema:()=>is,ResourceUpdatedNotificationParamsSchema:()=>xs,ResourceUpdatedNotificationSchema:()=>Ps,ResultMetaObjectSchema:()=>bo,ResultSchema:()=>de,RoleSchema:()=>Mt,RootSchema:()=>_i,RootsListChangedNotificationSchema:()=>vi,SamplingContentSchema:()=>Xs,SamplingMessageContentBlockSchema:()=>Qt,SamplingMessageSchema:()=>Qs,ServerCapabilitiesSchema:()=>Ro,ServerNotificationSchema:()=>sc,ServerRequestSchema:()=>nc,ServerResultSchema:()=>ic,ServerTasksCapabilitySchema:()=>Da,SetLevelRequestParamsSchema:()=>Vs,SetLevelRequestSchema:()=>Js,SingleSelectEnumSchemaSchema:()=>ni,StringSchemaSchema:()=>Mr,SubscribeRequestParamsSchema:()=>fs,SubscribeRequestSchema:()=>gs,SubscriptionFilterSchema:()=>Io,SubscriptionsAcknowledgedNotificationParamsSchema:()=>vs,SubscriptionsAcknowledgedNotificationSchema:()=>zs,SubscriptionsListenRequestParamsSchema:()=>bs,SubscriptionsListenRequestSchema:()=>ys,SubscriptionsListenResultMetaSchema:()=>ws,SubscriptionsListenResultSchema:()=>Rs,TaskAugmentedRequestParamsSchema:()=>er,TaskCreationParamsSchema:()=>Ha,TaskMetadataSchema:()=>Kn,TaskSchema:()=>jt,TaskStatusNotificationParamsSchema:()=>wi,TaskStatusNotificationSchema:()=>Ja,TaskStatusSchema:()=>zi,TextContentSchema:()=>Cr,TextResourceContentsSchema:()=>ko,TitledMultiSelectEnumSchemaSchema:()=>Lo,TitledSingleSelectEnumSchemaSchema:()=>Ao,ToolAnnotationsSchema:()=>Ms,ToolChoiceSchema:()=>Gs,ToolExecutionSchema:()=>js,ToolListChangedNotificationSchema:()=>Fs,ToolResultContentSchema:()=>Ys,ToolSchema:()=>or,ToolUseContentSchema:()=>Os,UnsubscribeRequestParamsSchema:()=>Ss,UnsubscribeRequestSchema:()=>_s,UntitledMultiSelectEnumSchemaSchema:()=>jo,UntitledSingleSelectEnumSchemaSchema:()=>qo});var Fr=(e)=>yo.safeParse(e).success,Xf=(e)=>vo.safeParse(e).success,Bo=(e)=>Er.safeParse(e).success,Wo=(e)=>kr.safeParse(e).success;var Qf=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var pu=(e)=>wo.safeParse(e).success,eg=(e)=>xo.safeParse(e).success;var Yb="Mcp-Param-",zf="x-mcp-header",Xb=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Qb=new Set(["string","integer","boolean","number"]);function hu(e){let t=[],r=new Map,o=(s,i,a)=>{if(s===null||typeof s!=="object")return;let l=s;if(zf in l){if(!a||i.length===0)return`${hc(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let d=l[zf];if(typeof d!=="string"||d.length===0)return`${hc(i)}: x-mcp-header MUST be a non-empty string`;if(!Xb.test(d))return`${hc(i)}: x-mcp-header '${d}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let m=typeof l.type==="string"?l.type:void 0;if(m===void 0||!Qb.has(m))return`${hc(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${m??"<none>"}`;let f=d.toLowerCase(),S=r.get(f);if(S!==void 0)return`x-mcp-header '${d}' is not case-insensitively unique (also declared as '${S}')`;r.set(f,d),t.push({path:i,headerName:d,type:m})}let u=l.properties;if(u!==null&&typeof u==="object")for(let[d,m]of Object.entries(u)){let f=o(m,[...i,d],a);if(f!==void 0)return f}for(let d of ey){let m=l[d];if(m===void 0)continue;let f=Array.isArray(m)?m:m!==null&&typeof m==="object"&&ty.has(d)?Object.values(m):[m];for(let S of f){let b=o(S,[...i,`<${d}>`],!1);if(b!==void 0)return b}}},n=o(e,[],!0);return n===void 0?{valid:!0,declarations:t}:{valid:!1,reason:n}}var ey=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],ty=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function hc(e){return e.length===0?"<root>":e.join(".")}var tg="=?base64?",rg="?=";function ry(e){if(typeof e==="string")return e;if(typeof e==="boolean")return e?"true":"false";if(typeof e==="number"){if(!Number.isFinite(e))return;if(Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}function oy(e){if(e.length===0)return!0;if(e.startsWith(tg)&&e.endsWith(rg))return!0;if(e!==e.trim())return!0;for(let t=0;t<e.length;t++){let r=e.codePointAt(t);if(r===9||r>=32&&r<=126)continue;return!0}return!1}function ny(e){let t=new TextEncoder().encode(e),r="";for(let o of t)r+=String.fromCodePoint(o);return btoa(r)}function mu(e){return oy(e)?`${tg}${ny(e)}${rg}`:e}function sy(e,t){let r=e;for(let o of t){if(r===null||typeof r!=="object")return;r=r[o]}return r}function og(e,t){let r={};for(let o of e){let n=sy(t,o.path);if(n===void 0||n===null)continue;let s=ry(n);if(s===void 0)continue;r[`${Yb}${o.headerName}`]=mu(s)}return r}var Jo=-32020,$x=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32000],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[W.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Jo,W.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[W.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[W.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[W.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Jo],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half — including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[W.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Jo],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],Cx={[W.ParseError]:400,[W.InvalidRequest]:400,[W.MethodNotFound]:404,[W.UnsupportedProtocolVersion]:400,[W.MissingRequiredClientCapability]:400,[Jo]:400},wf={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function ng(e,t){let r=Object.hasOwn(wf,e)?wf[e]:void 0;if(r===void 0)return;let o=iy(t)?t[r]:void 0;return{field:r,value:typeof o==="string"?o:void 0}}function iy(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Sc(e,t){return Ia(e,t)}function ki(e){return new Set(e.flatMap((t)=>Object.keys(t.shape)))}function tu(e){if(e==null)return!1;let t=typeof e;if(t!=="object"&&t!=="function")return!1;if(!("~standard"in e))return!1;return typeof e["~standard"]?.validate==="function"}var Rf=!1,ru="draft-2020-12";function ay(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:ru});else if(r.vendor==="zod"){if(!("_zod"in e))throw 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().");if(!Rf)Rf=!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.");o=$a(e,{target:ru,io:t})}else throw Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output"){if(o.type!==void 0)return o;return sg(o)?{type:"object",...o}:o}if(o.type!==void 0&&o.type!=="object")throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}function sg(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every((o)=>o!==null&&typeof o==="object"&&(o.type==="object"||sg(o)))}return!1}function cy(e){if(!e.path?.length)return e.message;return`${e.path.map((t)=>String(typeof t==="object"?t.key:t)).join(".")}: ${e.message}`}async function Xl(e,t){let r=await e["~standard"].validate(t);if(r.issues&&r.issues.length>0)return{success:!1,error:r.issues.map((o)=>cy(o)).join(", ")};return{success:!0,data:r.value}}function ly(e){let t=$a(e,{target:ru,io:"input"});return typeof t.pattern==="string"?t.pattern:void 0}var uy=/\\\.\\d\{(\d+)\}/;function dy(e){let t=uy.exec(e),r=[void 0,-1,0];if(t)r.push(Number(t[1]));return[!1,!0].flatMap((o)=>[!1,!0].flatMap((n)=>r.map((s)=>uo({local:o,offset:n,precision:s}))))}function py(e,t){let r;switch(e){case"email":r=[Bm()];break;case"uri":r=[Na()];break;case"date":r=[Fl()];break;case"date-time":r=dy(t);break}return new Set(r.map((o)=>ly(o)).filter((o)=>o!==void 0))}function hy(e,t,r){if(r!=="zod")return!0;return py(e,t).has(t)}function Ii(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function my(e){try{return ay(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new ee(W.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}var fy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function fu(e){return fy.has(e)||e.startsWith("x-")}var gy=new Set(["$schema",...Object.keys(Lr.shape.requestedSchema.shape)]),xf={string:ki([Mr,qo,Ao,Mo]),number:ki([jr]),integer:ki([jr]),boolean:ki([No]),array:ki([jo,Lo])},Sy=new Set(Mr.shape.format.unwrap().options);function _y(e,t,r,o){if(!Ii(e))return e;let n=typeof e.type==="string"&&Object.hasOwn(xf,e.type)?xf[e.type]:void 0;if(n===void 0)return e;let s={};for(let[i,a]of Object.entries(e))if(n.has(i)||fu(i))s[i]=a;else if(i==="pattern"&&e.type==="string"&&typeof e.format==="string"){if(!Sy.has(e.format))s[i]=a;else if(typeof a!=="string"||!hy(e.format,a,r))o.push(`${t}.${i}`)}else o.push(`${t}.${i}`);return s}function by(e,t){let r={},o=[];for(let[n,s]of Object.entries(e))if(n==="properties"&&Ii(s))r[n]=Object.fromEntries(Object.entries(s).map(([i,a])=>[i,_y(a,`properties.${i}`,t,o)]));else if(gy.has(n))r[n]=s;else if(!fu(n))o.push(n);if(o.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}function yy(e,t){if(!Ii(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!Sc(Uo,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}function ou(e,t,r=""){if(Array.isArray(e)&&Array.isArray(t))return e.flatMap((o,n)=>ou(o,t[n],`${r}[${n}]`));if(!Ii(e)||!Ii(t))return[];return Object.entries(e).flatMap(([o,n])=>{let s=r?`${r}.${o}`:o;if(!Object.prototype.hasOwnProperty.call(t,o))return fu(o)?[]:[s];return ou(n,t[o],s)})}function vy(e){if(!tu(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=by(my(e.requestedSchema),t),o=Sc(Lr.shape.requestedSchema,r);if(!o.success)throw new ee(W.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${yy(r,o.error.message)}`);let n=ou(r,o.data);if(n.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);let s=(o.data.required??[]).filter((i)=>!Object.prototype.hasOwnProperty.call(o.data.properties,i));if(s.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function zy(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState==="string";if(!t&&!r)throw TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}var Ix=Object.assign(zy,{elicit(e){try{return{method:"elicitation/create",params:vy(e)}}catch(t){throw t instanceof ee?TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var wy=!0,Ry=10,xy=250;function ig(e){return{autoFulfill:e?.autoFulfill??wy,maxRounds:e?.maxRounds??Ry}}function Py(e,t,r){let o=t!==void 0&&Object.keys(t).length>0;if(!o&&r===void 0)return e;return{...e,...o&&{inputResponses:t},...r!==void 0&&{requestState:r}}}function Ty(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Ey(e,t){return new Promise((r,o)=>{if(t?.aborted){o(t.reason instanceof N?t.reason:new N(O.RequestTimeout,String(t.reason)));return}let n=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),s=()=>{clearTimeout(n),o(t?.reason instanceof N?t.reason:new N(O.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",s,{once:!0})})}function ky(e){let t=new AbortController,r=()=>t.abort(e?.reason);if(e?.addEventListener("abort",r,{once:!0}),e?.aborted)t.abort(e.reason);return{signal:t.signal,abort:(o)=>t.abort(o),dispose:()=>e?.removeEventListener("abort",r)}}async function $y(e){let{config:t,method:r,originalParams:o,requestOptions:n,hooks:s,signal:i}=e,a=e.flowStartedAt??Date.now(),l=e.firstPayload,u=0;while(!0){if(u+=1,u>t.maxRounds)throw new N(O.InputRequiredRoundsExceeded,Ty(r,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:l.inputRequests,...l.requestState!==void 0&&{requestState:l.requestState}}});n.onprogress?.({progress:u,message:`Fulfilling input required by '${r}' (round ${u})`});let d=Object.entries(l.inputRequests??{}),m;if(d.length>0){let b=ky(i);try{let y=await Promise.all(d.map(async([v,L])=>{try{return[v,await s.dispatchInputRequest(v,L,b.signal)]}catch(F){throw b.abort(F),F}}));m=Object.fromEntries(y)}finally{b.dispose()}}else await Ey(xy,i);let f={...n.timeout!==void 0&&{timeout:n.timeout}};if(n.maxTotalTimeout!==void 0){let b=Date.now()-a,y=n.maxTotalTimeout-b;if(y<=0)throw new N(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:b});f.maxTotalTimeout=y}let S=await s.retry(Py(o,m,l.requestState),f);if(Qf(S)){l={inputRequests:S.inputRequests??{},...S.requestState!==void 0&&{requestState:S.requestState}};continue}return S}}var Cy=["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"],Iy={IdJagTokenExchangeResponseSchema:xi,OAuthClientInformationFullSchema:Vo,OAuthClientInformationSchema:Ti,OAuthClientMetadataSchema:Pi,OAuthClientRegistrationErrorSchema:ac,OAuthErrorResponseSchema:Ho,OAuthMetadataSchema:Ur,OAuthProtectedResourceMetadataSchema:Zo,OAuthTokenRevocationRequestSchema:cc,OAuthTokensSchema:Fo,OpenIdProviderDiscoveryMetadataSchema:Do,OpenIdProviderMetadataSchema:Ri},ag={},cg={};function lg(e,t){let r=e.slice(0,-6);ag[r]=t,cg[r]=(o)=>t.safeParse(o).success}for(let e of Cy)lg(e,Gb[e]);for(let[e,t]of Object.entries(Iy))lg(e,t);var Oy=Object.freeze(ag),ug=Object.freeze(cg);function Ny(e){switch(e){case"initialize":case"notifications/initialized":return Lt(void 0);case"server/discover":return Lt(gc);default:return}}var _c=60000,qy=[It,mo,Pr,fo],Ay=["inputResponses","requestState"];function Pf(e,t){let r=e.params;if(!Ci(r))return{message:e,lifted:{}};let o=r._meta,n=Ci(o)?qy.filter((l)=>(l in o)):[],s=t==="request"?Ay.filter((l)=>(l in r)):[];if(n.length===0&&s.length===0)return{message:e,lifted:{}};let i={},a={...r};if(n.length>0&&Ci(o)){let l={},u={...o};for(let d of n)l[d]=o[d],delete u[d];if(i.envelope=l,Object.keys(u).length>0)a._meta=u;else delete a._meta}for(let l of s){if(l==="inputResponses")i.inputResponses=a[l];if(l==="requestState")i.requestState=a[l];delete a[l]}return{message:{...e,params:a},lifted:i}}function Tf(e,t){let r=e.validateResult(t,void 0);if(!r.ok&&r.reason==="not-in-era")return;return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let n=e.validateResult(t,o);if(n.ok)return{value:n.value};return{issues:[{message:n.reason==="invalid"?n.message:`not-in-era: ${t}`}]}}}}}function gu(e){return()=>e}var My=gu(void 0),jy,bc=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{jy=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Ma,this.setNotificationHandler("notifications/cancelled",(t)=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",(t)=>{this._onprogress(t)}),this.setRequestHandler("ping",(t)=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new N(O.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){if(e.params.requestId===void 0)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new N(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=(n)=>{r?.(n),this._onerror(n)};let o=this._transport?.onmessage;this._transport.onmessage=(n,s)=>{if(o?.(n,s),Bo(n)||Wo(n))this._onresponse(n);else if(Fr(n))this._onrequest(n,s);else if(Xf(n))this._onnotification(n,s);else this._onerror(Error(`Unknown message type: ${JSON.stringify(n)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new N(O.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(r);for(let o of t.values())o.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=Pf(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let i=yf(t.classification);if(i!==o.era){this._onerror(Error(`Era mismatch on inbound notification '${r.method}': classified as ${i} but this instance serves ${o.era}`));return}}if(Yl(r.method)&&!o.hasNotificationMethod(r.method))return;let n=this._notificationHandlers.get(r.method),s=this.fallbackNotificationHandler;if(n===void 0&&s===void 0)return;Promise.resolve().then(()=>n===void 0?s(r):n(r,o)).catch((i)=>this._onerror(Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,t){let{message:r,lifted:o}=Pf(e,"request"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let s=this._transport,i=(y,v,L)=>{let F={jsonrpc:"2.0",id:r.id,error:{code:y,message:v,...L!==void 0&&{data:L}}};s?.send(F).catch((x)=>this._onerror(Error(`Failed to send an error response: ${x}`)))};if(t?.classification!==void 0){let y=yf(t.classification);if(y!==n.era){this._onerror(Error(`Era mismatch on inbound request '${r.method}': classified as ${y} but this instance serves ${n.era}`));let v=t.classification.revision??y;i(W.UnsupportedProtocolVersion,`Unsupported protocol version: ${v}`,{supported:this._supportedProtocolVersions,requested:v});return}}if(Gl(r.method)&&!n.hasRequestMethod(r.method)&&!(vf(r.method)&&this._customSchemaRequestMethods.has(r.method))){i(W.MethodNotFound,"Method not found");return}let a=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(a===void 0){i(W.MethodNotFound,"Method not found");return}let l=n.checkInboundEnvelope(o);if(l!==void 0){i(W.InvalidParams,l);return}let u=(y,v)=>this._notificationViaCodec(this._resolveOutboundCodec(y.method),y,{...v,relatedRequestId:r.id}),d=(y,v,L)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(y.method),y,v,{...L,relatedRequestId:r.id}),m=new AbortController;this._requestHandlerAbortControllers.set(r.id,m);let f=o.inputResponses===void 0?void 0:Ly(o.inputResponses),S={sessionId:s?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:o.requestState===void 0?My:gu(o.requestState),signal:m.signal,send:(y,v,L)=>{let F=this._resolveOutboundCodec(y.method);if(this._assertOutboundRequestInEra(F,y.method),tu(v))return d(y,v,L);let x=Tf(F,y.method);if(x===void 0)throw TypeError(`'${y.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return d(y,x,v)},notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},b=this.buildContext(S,t);Promise.resolve().then(()=>a(r,b)).then(async(y)=>{if(m.signal.aborted)return;let v;try{v=n.encodeResult(r.method,y,this._outboundServerInfo())}catch(F){this._onerror(Error(`Failed to encode result for ${r.method}: ${F}`)),i(W.InternalError,"Internal error");return}let L={result:v,jsonrpc:"2.0",id:r.id};await s?.send(L)},async(y)=>{if(m.signal.aborted)return;let v=Number.isSafeInteger(y.code)?y.code:W.InternalError,L={jsonrpc:"2.0",id:r.id,error:{code:n.encodeErrorCode(v),message:y.message??"Internal error",...y.data!==void 0&&{data:y.data}}};await s?.send(L)}).catch((y)=>this._onerror(Error(`Failed to send response: ${y}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(r.id)===m)this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),n=this._progressHandlers.get(o);if(!n){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(a);return}n(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Bo(e))r(e);else r(ee.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let o=this._resolveOutboundCodec(e.method);if(tu(t)){if(!vf(e.method))this._assertOutboundRequestInEra(o,e.method);return this._requestWithSchemaViaCodec(o,e,t,r)}this._assertOutboundRequestInEra(o,e.method);let n=Tf(o,e.method);if(n===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(o,e,n,t)}_negotiatedWireCodec(){return Lt(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Ny(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Gl(t)&&!e.hasRequestMethod(t))throw new N(O.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r)}_requestWithSchemaViaCodec(e,t,r,o){let{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,headers:a}=o??{},l=Date.now(),u,d;return new Promise((m,f)=>{let S=(w)=>{f(w)};if(!this._transport){S(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(w){S(w);return}if(o?.signal?.aborted){let w=o.signal.reason;throw w instanceof N?w:new N(O.RequestTimeout,String(w))}let b=e.era===gc&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,y=this._requestMessageId++;d=y;let v={...t,jsonrpc:"2.0",id:y};if(o?.onprogress)this._progressHandlers.set(y,o.onprogress),v.params={...t.params,_meta:{...t.params?._meta,progressToken:y}};let L=this._envelopeOutbound(v),F=!1,x=(w)=>{if(F)return;if(this._progressHandlers.delete(y),b===void 0){if(t.method!=="initialize")this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:y,reason:String(w)}}),{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch((Z)=>this._onerror(Error(`Failed to send cancellation: ${Z}`)))}else b.abort();f(w instanceof N?w:new N(O.RequestTimeout,String(w)))};this._responseHandlers.set(y,(w)=>{if(o?.signal?.aborted)return;if(F=!0,w instanceof Error)return f(w);let Z;try{Z=e.decodeResult(t.method,w.result)}catch(Y){return f(Y instanceof Error?Y:Error(String(Y)))}if(Z.kind==="invalid")return f(Z.error);if(Z.kind==="input_required"){if(o?.allowInputRequired===!0)return m(Fy(Z));let Y={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:l,retry:(ce,Ee)=>this._requestWithSchemaViaCodec(e,ce===void 0?{method:t.method}:{method:t.method,params:ce},r,Ee)};return m(this._resolveNonCompleteResult(Z,Y))}let X=Z.result;Xl(r,X).then((Y)=>{if(Y.success)m(Y.data);else f(new N(O.InvalidResult,`Invalid result for ${t.method}: ${Y.error}`))},f)}),u=()=>x(o?.signal?.reason),o?.signal?.addEventListener("abort",u,{once:!0});let U=o?.timeout??_c,R=()=>x(new N(O.RequestTimeout,"Request timed out",{timeout:U}));this._setupTimeout(y,U,o?.maxTotalTimeout,R,o?.resetTimeoutOnProgress??!1),this._transport.send(L,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,headers:a,requestSignal:b?.signal}).catch((w)=>{this._progressHandlers.delete(y),f(w)})}).finally(()=>{if(u)o?.signal?.removeEventListener("abort",u);if(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,r){if(!this._transport)throw new N(O.NotConnected,"Not connected");if(Yl(t.method)&&!e.hasNotificationMethod(t.method))throw new N(O.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;this._transport?.send(o,r).catch((n)=>this._onerror(n))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t==="function"){if(!Gl(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=(n,s)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason==="not-in-era")a=i.validateInputRequest(e,n);if(!a.ok){if(a.reason==="not-in-era")throw new ee(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(a.message)}return Promise.resolve(t(a.value,s))}}else if(r)o=async(n,s)=>{let i=await Xl(t.params,{...n.params});if(!i.success)throw new ee(W.InvalidParams,`Invalid params for ${e}: ${i.error}`);return r(i.data,s)};else throw TypeError("setRequestHandler: handler is required");if(typeof t==="function")this._customSchemaRequestMethods.delete(e);else this._customSchemaRequestMethods.add(e);this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t==="function"){if(!Yl(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,n)=>{let s=n.validateNotification(e,o);if(!s.ok){if(s.reason==="not-in-era")throw new ee(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(s.message)}return Promise.resolve(t(s.value))});return}if(!r)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async(o)=>{let n=await Xl(t.params,{...o.params});if(!n.success)throw new ee(W.InvalidParams,`Invalid params for notification ${e}: ${n.error}`);await r(n.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Ci(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function dg(e,t){let r={...e};for(let o in t){let n=o,s=t[n];if(s===void 0)continue;let i=r[n];r[n]=Ci(i)&&Ci(s)?{...i,...s}:s}return r}function mc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Ly(e){let t={},r=[];if(!mc(e))return{accepted:t,droppedKeys:r};for(let[o,n]of Object.entries(e)){if(!mc(n)||"method"in n||"result"in n){r.push(o);continue}t[o]=n}return{accepted:t,droppedKeys:r}}function Ef(e){throw new N(O.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 Uy(e,t,r,o,n){return{sessionId:n,mcpReq:{id:e,method:t,_meta:r?._meta,requestState:gu(void 0),signal:o,send:()=>Ef("send"),notify:()=>Ef("notify")}}}async function Zy(e,t,r,o,n){if(!mc(o)||typeof o.method!=="string")throw new N(O.InvalidResult,`Invalid input request '${r}': each inputRequests entry must be an embedded request object with a method`,{key:r});let s=o.method;if(!t.hasInputRequestMethod(s))throw new N(O.InvalidResult,`Invalid input request '${r}': '${s}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:r,method:s});let i=e.getRequestHandler(s);if(i===void 0)throw new N(O.CapabilityNotSupported,`Cannot fulfil input request '${r}': no handler is registered for '${s}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:r,method:s});let a=mc(o.params)?o.params:void 0;return await i({jsonrpc:"2.0",id:r,method:s,...a!==void 0&&{params:a}},e.buildContext(Uy(r,s,a,n,e.sessionId)))}function Dy(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 pg(e,t,r,o){let{codec:n,request:s,options:i,flowStartedAt:a}=o,l={inputRequests:r.inputRequests,...r.requestState!==void 0&&{requestState:r.requestState}},u={dispatchInputRequest:(d,m,f)=>Zy(e,n,d,m,f),retry:(d,m)=>o.retry(d,Dy(i,m))};return $y({config:t,method:s.method,originalParams:s.params,firstPayload:l,flowStartedAt:a,signal:i?.signal,requestOptions:{...i?.timeout!==void 0&&{timeout:i.timeout},...i?.maxTotalTimeout!==void 0&&{maxTotalTimeout:i.maxTotalTimeout},...i?.onprogress!==void 0&&{onprogress:i.onprogress}},hooks:u})}function Fy(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}/*!
65
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1){if(e.reused==="ref"){s(i);continue}}}}function Vn(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(a)=>{let l=e.seen.get(a);if(l.ref===null)return;let u=l.def??l.schema,d={...u},m=l.ref;if(l.ref=null,m){o(m);let S=e.seen.get(m),b=S.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))u.allOf=u.allOf??[],u.allOf.push(b);else Object.assign(u,b);if(Object.assign(u,d),a._zod.parent===m)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(!(v in d))delete u[v]}if(b.$ref&&S.def)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(v in S.def&&JSON.stringify(u[v])===JSON.stringify(S.def[v]))delete u[v]}}let f=a._zod.parent;if(f&&f!==m){o(f);let S=e.seen.get(f);if(S?.schema.$ref){if(u.$ref=S.schema.$ref,S.def)for(let b in u){if(b==="$ref"||b==="allOf")continue;if(b in S.def&&JSON.stringify(u[b])===JSON.stringify(S.def[b]))delete u[b]}}}e.override({zodSchema:a,jsonSchema:u,path:l.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let n={};if(e.target==="draft-2020-12")n.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")n.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")n.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");n.$id=e.external.uri(a)}Object.assign(n,r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&n.id===s)delete n.id;let i=e.external?.defs??{};for(let a of e.seen.entries()){let l=a[1];if(l.def&&l.defId){if(l.def.id===l.defId)delete l.def.id;i[l.defId]=l.def}}if(e.external);else if(Object.keys(i).length>0)if(e.target==="draft-2020-12")n.$defs=i;else n.definitions=i;try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dn(t,"input",e.processors),output:Dn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Ne(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Ne(o.element,r);if(o.type==="set")return Ne(o.valueType,r);if(o.type==="lazy")return Ne(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return Ne(o.innerType,r);if(o.type==="intersection")return Ne(o.left,r)||Ne(o.right,r);if(o.type==="record"||o.type==="map")return Ne(o.keyType,r)||Ne(o.valueType,r);if(o.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Ne(o.in,r)||Ne(o.out,r)}if(o.type==="object"){for(let n in o.shape)if(Ne(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Ne(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Ne(n,r))return!0;if(o.rest&&Ne(o.rest,r))return!0;return!1}return!1}var dm=(e,t={})=>(r)=>{let o=Fn({...r,processors:t});return oe(e,o),Hn(o,e),Vn(o,e)},Dn=(e,t,r={})=>(o)=>{let{libraryOptions:n,target:s}=o??{},i=Fn({...n??{},target:s,io:t,processors:r});return oe(e,i),Hn(i,e),Vn(i,e)};var l_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},bl=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:s,maximum:i,format:a,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof s==="number")n.minLength=s;if(typeof i==="number")n.maxLength=i;if(a){if(n.format=l_[a]??a,n.format==="")delete n.format;if(a==="time")delete n.format}if(u)n.contentEncoding=u;if(l&&l.size>0){let d=[...l];if(d.length===1)n.pattern=d[0].source;else if(d.length>1)n.allOf=[...d.map((m)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))]}},yl=(e,t,r,o)=>{let n=r,{minimum:s,maximum:i,format:a,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))n.type="integer";else n.type="number";let m=typeof d==="number"&&d>=(s??Number.NEGATIVE_INFINITY),f=typeof u==="number"&&u<=(i??Number.POSITIVE_INFINITY),S=t.target==="draft-04"||t.target==="openapi-3.0";if(m)if(S)n.minimum=d,n.exclusiveMinimum=!0;else n.exclusiveMinimum=d;else if(typeof s==="number")n.minimum=s;if(f)if(S)n.maximum=u,n.exclusiveMaximum=!0;else n.exclusiveMaximum=u;else if(typeof i==="number")n.maximum=i;if(typeof l==="number")n.multipleOf=l},vl=(e,t,r,o)=>{r.type="boolean"},hm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},mm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},zl=(e,t,r,o)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},wl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},fm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},Rl=(e,t,r,o)=>{r.not={}},xl=(e,t,r,o)=>{},Pl=(e,t,r,o)=>{},gm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},Tl=(e,t,r,o)=>{let n=e._zod.def,s=fa(n.entries);if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";r.enum=s},El=(e,t,r,o)=>{let n=e._zod.def,s=[];for(let i of n.values)if(i===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else s.push(Number(i));else s.push(i);if(s.length===0);else if(s.length===1){let i=s[0];if(r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[i];else r.const=i}else{if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";if(s.every((i)=>typeof i==="boolean"))r.type="boolean";if(s.every((i)=>i===null))r.type="null";r.enum=s}},Sm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},_m=(e,t,r,o)=>{let n=r,s=e._zod.pattern;if(!s)throw Error("Pattern not found in template literal");n.type="string",n.pattern=s.source},bm=(e,t,r,o)=>{let n=r,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:a,mime:l}=e._zod.bag;if(i!==void 0)s.minLength=i;if(a!==void 0)s.maxLength=a;if(l)if(l.length===1)s.contentMediaType=l[0],Object.assign(n,s);else Object.assign(n,s),n.anyOf=l.map((u)=>({contentMediaType:u}));else Object.assign(n,s)},ym=(e,t,r,o)=>{r.type="boolean"},kl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},vm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},$l=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},zm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},wm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},Cl=(e,t,r,o)=>{let n=r,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;if(typeof i==="number")n.minItems=i;if(typeof a==="number")n.maxItems=a;n.type="array",n.items=oe(s.element,t,{...o,path:[...o.path,"items"]})},Il=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="object",n.properties={};let i=s.shape;for(let u in i)n.properties[u]=oe(i[u],t,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(i)),l=new Set([...a].filter((u)=>{let d=s.shape[u]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(l.size>0)n.required=Array.from(l);if(s.catchall?._zod.def.type==="never")n.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")n.additionalProperties=!1}else if(s.catchall)n.additionalProperties=oe(s.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Ol=(e,t,r,o)=>{let n=e._zod.def,s=n.inclusive===!1,i=n.options.map((a,l)=>oe(a,t,{...o,path:[...o.path,s?"oneOf":"anyOf",l]}));if(s)r.oneOf=i;else r.anyOf=i},Nl=(e,t,r,o)=>{let n=e._zod.def,s=oe(n.left,t,{...o,path:[...o.path,"allOf",0]}),i=oe(n.right,t,{...o,path:[...o.path,"allOf",1]}),a=(u)=>("allOf"in u)&&Object.keys(u).length===1,l=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=l},Rm=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",l=s.items.map((f,S)=>oe(f,t,{...o,path:[...o.path,i,S]})),u=s.rest?oe(s.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(n.prefixItems=l,u)n.items=u}else if(t.target==="openapi-3.0"){if(n.items={anyOf:l},u)n.items.anyOf.push(u);if(n.minItems=l.length,!u)n.maxItems=l.length}else if(n.items=l,u)n.additionalItems=u;let{minimum:d,maximum:m}=e._zod.bag;if(typeof d==="number")n.minItems=d;if(typeof m==="number")n.maxItems=m},ql=(e,t,r,o)=>{let n=r,s=e._zod.def;n.type="object";let i=s.keyType,l=i._zod.bag?.patterns;if(s.mode==="loose"&&l&&l.size>0){let d=oe(s.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let m of l)n.patternProperties[m.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")n.propertyNames=oe(s.keyType,t,{...o,path:[...o.path,"propertyNames"]});n.additionalProperties=oe(s.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=i._zod.values;if(u){let d=[...u].filter((m)=>typeof m==="string"||typeof m==="number");if(d.length>0)n.required=d}},Al=(e,t,r,o)=>{let n=e._zod.def,s=oe(n.innerType,t,o),i=t.seen.get(e);if(t.target==="openapi-3.0")i.ref=n.innerType,r.nullable=!0;else r.anyOf=[s,{type:"null"}]},Ml=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},jl=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},Ll=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);if(s.ref=n.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(n.defaultValue))},Ul=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType;let i;try{i=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},Zl=(e,t,r,o)=>{let n=e._zod.def,s=n.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?n.out:n.in:n.out;oe(i,t,o);let a=t.seen.get(e);a.ref=i},Dl=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType,r.readOnly=!0},xm=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},$a=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let s=t.seen.get(e);s.ref=n.innerType},Fl=(e,t,r,o)=>{let n=e._zod.innerType;oe(n,t,o);let s=t.seen.get(e);s.ref=n},pm={string:bl,number:yl,boolean:vl,bigint:hm,symbol:mm,null:zl,undefined:wl,void:fm,never:Rl,any:xl,unknown:Pl,date:gm,enum:Tl,literal:El,nan:Sm,template_literal:_m,file:bm,success:ym,custom:kl,function:vm,transform:$l,map:zm,set:wm,array:Cl,object:Il,union:Ol,intersection:Nl,tuple:Rm,record:ql,nullable:Al,nonoptional:Ml,default:jl,prefault:Ll,catch:Ul,pipe:Zl,readonly:Dl,promise:xm,optional:$a,lazy:Fl};function Ca(e,t){if("_idmap"in e){let o=e,n=Fn({...t,processors:pm}),s={};for(let l of o._idmap.entries()){let[u,d]=l;oe(d,n)}let i={},a={registry:o,uri:t?.uri,defs:s};n.external=a;for(let l of o._idmap.entries()){let[u,d]=l;Hn(n,d),i[u]=Vn(n,d)}if(Object.keys(s).length>0){let l=n.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[l]:s}}return{schemas:i}}let r=Fn({...t,processors:pm});return oe(e,r),Hn(r,e),Vn(r,e)}var S_=_("ZodISODateTime",(e,t)=>{Up.init(e,t),ae.init(e,t)});function uo(e){return Kh(S_,e)}var __=_("ZodISODate",(e,t)=>{Zp.init(e,t),ae.init(e,t)});function Hl(e){return Gh(__,e)}var b_=_("ZodISOTime",(e,t)=>{Dp.init(e,t),ae.init(e,t)});function Pm(e){return Yh(b_,e)}var y_=_("ZodISODuration",(e,t)=>{Fp.init(e,t),ae.init(e,t)});function Tm(e){return Xh(y_,e)}var v_=(e,t)=>{ba.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>Jc(e,r)},flatten:{value:(r)=>Vc(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Nn,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Nn,2)}},isEmpty:{get(){return e.issues.length===0}}})};var Je=_("ZodError",v_,{Parent:Error});var km=ya(Je),$m=va(Je),Oa=An(Je),Cm=Mn(Je),Im=wd(Je),Om=Rd(Je),Nm=xd(Je),qm=Pd(Je),Am=Td(Je),Mm=Ed(Je),jm=kd(Je),Lm=$d(Je);var Um=new WeakMap;function Jn(e,t,r){let o=Object.getPrototypeOf(e),n=Um.get(o);if(!n)n=new Set,Um.set(o,n);if(n.has(t))return;n.add(t);for(let s in r){let i=r[s];Object.defineProperty(o,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var ne=_("ZodType",(e,t)=>(re.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dn(e,"input"),output:Dn(e,"output")}}),e.toJSONSchema=dm(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,o)=>km(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Oa(e,r,o),e.parseAsync=async(r,o)=>$m(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>Cm(e,r,o),e.spa=e.safeParseAsync,e.encode=(r,o)=>Im(e,r,o),e.decode=(r,o)=>Om(e,r,o),e.encodeAsync=async(r,o)=>Nm(e,r,o),e.decodeAsync=async(r,o)=>qm(e,r,o),e.safeEncode=(r,o)=>Am(e,r,o),e.safeDecode=(r,o)=>Mm(e,r,o),e.safeEncodeAsync=async(r,o)=>jm(e,r,o),e.safeDecodeAsync=async(r,o)=>Lm(e,r,o),Jn(e,"ZodType",{check(...r){let o=this.def;return this.clone(Wt(o,{checks:[...o.checks??[],...r.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,o){return rt(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(ub(r,o))},superRefine(r,o){return this.check(db(r,o))},overwrite(r){return this.check(Xt(r))},optional(){return j(this)},exactOptional(){return G_(this)},nullable(){return Hm(this)},nullish(){return j(Hm(this))},nonoptional(r){return rb(this,r)},array(){return g(this)},or(r){return T([this,r])},and(r){return $t(this,r)},transform(r){return Vm(this,ef(r))},default(r){return Q_(this,r)},prefault(r){return tb(this,r)},catch(r){return nb(this,r)},pipe(r){return Vm(this,r)},readonly(){return ab(this)},describe(r){let o=this.clone();return Yt.add(o,{description:r}),o},meta(...r){if(r.length===0)return Yt.get(this);let o=this.clone();return Yt.add(o,r[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return Yt.get(e)?.description},configurable:!0}),e)),Jm=_("_ZodString",(e,t)=>{Ra.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,s)=>bl(e,o,n,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Jn(e,"_ZodString",{regex(...o){return this.check(cl(...o))},includes(...o){return this.check(dl(...o))},startsWith(...o){return this.check(pl(...o))},endsWith(...o){return this.check(hl(...o))},min(...o){return this.check(co(...o))},max(...o){return this.check(Ea(...o))},length(...o){return this.check(ka(...o))},nonempty(...o){return this.check(co(1,...o))},lowercase(o){return this.check(ll(o))},uppercase(o){return this.check(ul(o))},trim(){return this.check(fl())},normalize(...o){return this.check(ml(...o))},toLowerCase(){return this.check(gl())},toUpperCase(){return this.check(Sl())},slugify(){return this.check(_l())}})}),Bm=_("ZodString",(e,t)=>{Ra.init(e,t),Jm.init(e,t),e.email=(r)=>e.check(sl(Wm,r)),e.url=(r)=>e.check(al(Gm,r)),e.jwt=(r)=>e.check(Wh(M_,r)),e.emoji=(r)=>e.check(Nh(w_,r)),e.guid=(r)=>e.check(il(Zm,r)),e.uuid=(r)=>e.check($h(Na,r)),e.uuidv4=(r)=>e.check(Ch(Na,r)),e.uuidv6=(r)=>e.check(Ih(Na,r)),e.uuidv7=(r)=>e.check(Oh(Na,r)),e.nanoid=(r)=>e.check(qh(R_,r)),e.guid=(r)=>e.check(il(Zm,r)),e.cuid=(r)=>e.check(Ah(x_,r)),e.cuid2=(r)=>e.check(Mh(P_,r)),e.ulid=(r)=>e.check(jh(T_,r)),e.base64=(r)=>e.check(Vh(N_,r)),e.base64url=(r)=>e.check(Jh(q_,r)),e.xid=(r)=>e.check(Lh(E_,r)),e.ksuid=(r)=>e.check(Uh(k_,r)),e.ipv4=(r)=>e.check(Zh($_,r)),e.ipv6=(r)=>e.check(Dh(C_,r)),e.cidrv4=(r)=>e.check(Fh(I_,r)),e.cidrv6=(r)=>e.check(Hh(O_,r)),e.e164=(r)=>e.check(Bh(A_,r)),e.datetime=(r)=>e.check(uo(r)),e.date=(r)=>e.check(Hl(r)),e.time=(r)=>e.check(Pm(r)),e.duration=(r)=>e.check(Tm(r))});function c(e){return kh(Bm,e)}var ae=_("ZodStringFormat",(e,t)=>{ie.init(e,t),Jm.init(e,t)}),Wm=_("ZodEmail",(e,t)=>{Cp.init(e,t),ae.init(e,t)});function Km(e){return sl(Wm,e)}var Zm=_("ZodGUID",(e,t)=>{kp.init(e,t),ae.init(e,t)});var Na=_("ZodUUID",(e,t)=>{$p.init(e,t),ae.init(e,t)});var Gm=_("ZodURL",(e,t)=>{Ip.init(e,t),ae.init(e,t)});function qa(e){return al(Gm,e)}var w_=_("ZodEmoji",(e,t)=>{Op.init(e,t),ae.init(e,t)});var R_=_("ZodNanoID",(e,t)=>{Np.init(e,t),ae.init(e,t)});var x_=_("ZodCUID",(e,t)=>{qp.init(e,t),ae.init(e,t)});var P_=_("ZodCUID2",(e,t)=>{Ap.init(e,t),ae.init(e,t)});var T_=_("ZodULID",(e,t)=>{Mp.init(e,t),ae.init(e,t)});var E_=_("ZodXID",(e,t)=>{jp.init(e,t),ae.init(e,t)});var k_=_("ZodKSUID",(e,t)=>{Lp.init(e,t),ae.init(e,t)});var $_=_("ZodIPv4",(e,t)=>{Hp.init(e,t),ae.init(e,t)});var C_=_("ZodIPv6",(e,t)=>{Vp.init(e,t),ae.init(e,t)});var I_=_("ZodCIDRv4",(e,t)=>{Jp.init(e,t),ae.init(e,t)});var O_=_("ZodCIDRv6",(e,t)=>{Bp.init(e,t),ae.init(e,t)});var N_=_("ZodBase64",(e,t)=>{Kp.init(e,t),ae.init(e,t)});var q_=_("ZodBase64URL",(e,t)=>{Gp.init(e,t),ae.init(e,t)});var A_=_("ZodE164",(e,t)=>{Yp.init(e,t),ae.init(e,t)});var M_=_("ZodJWT",(e,t)=>{Xp.init(e,t),ae.init(e,t)});var Aa=_("ZodNumber",(e,t)=>{el.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,s)=>yl(e,o,n,s),Jn(e,"ZodNumber",{gt(o,n){return this.check(Pa(o,n))},gte(o,n){return this.check(Zn(o,n))},min(o,n){return this.check(Zn(o,n))},lt(o,n){return this.check(xa(o,n))},lte(o,n){return this.check(Un(o,n))},max(o,n){return this.check(Un(o,n))},int(o){return this.check(Dm(o))},safe(o){return this.check(Dm(o))},positive(o){return this.check(Pa(0,o))},nonnegative(o){return this.check(Zn(0,o))},negative(o){return this.check(xa(0,o))},nonpositive(o){return this.check(Un(0,o))},multipleOf(o,n){return this.check(Ta(o,n))},step(o,n){return this.check(Ta(o,n))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??0.5),e.isFinite=!0,e.format=r.format??null});function z(e){return Qh(Aa,e)}var j_=_("ZodNumberFormat",(e,t)=>{Qp.init(e,t),Aa.init(e,t)});function Dm(e){return tm(j_,e)}var Ym=_("ZodBoolean",(e,t)=>{eh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>vl(e,r,o,n)});function E(e){return rm(Ym,e)}var L_=_("ZodUndefined",(e,t)=>{th.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wl(e,r,o,n)});function Jl(e){return om(L_,e)}var U_=_("ZodNull",(e,t)=>{rh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zl(e,r,o,n)});function Rr(e){return nm(U_,e)}var Z_=_("ZodAny",(e,t)=>{oh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xl(e,r,o,n)});function Ma(){return sm(Z_)}var D_=_("ZodUnknown",(e,t)=>{nh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Pl(e,r,o,n)});function A(){return im(D_)}var F_=_("ZodNever",(e,t)=>{sh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rl(e,r,o,n)});function Bl(e){return am(F_,e)}var H_=_("ZodArray",(e,t)=>{ih.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cl(e,r,o,n),e.element=t.element,Jn(e,"ZodArray",{min(r,o){return this.check(co(r,o))},nonempty(r){return this.check(co(1,r))},max(r,o){return this.check(Ea(r,o))},length(r,o){return this.check(ka(r,o))},unwrap(){return this.element}})});function g(e,t){return cm(H_,e,t)}var Xm=_("ZodObject",(e,t)=>{lh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n),Q(e,"shape",()=>t.shape),Jn(e,"ZodObject",{keyof(){return K(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:A()})},loose(){return this.clone({...this._zod.def,catchall:A()})},strict(){return this.clone({...this._zod.def,catchall:Bl()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return KS(this,r)},safeExtend(r){return GS(this,r)},merge(r){return YS(this,r)},pick(r){return BS(this,r)},omit(r){return WS(this,r)},partial(...r){return XS(tf,this,r[0])},required(...r){return QS(rf,this,r[0])}})});function p(e,t){let r={type:"object",shape:e??{},...M(t)};return new Xm(r)}function F(e,t){return new Xm({type:"object",shape:e,catchall:A(),...M(t)})}var Qm=_("ZodUnion",(e,t)=>{tl.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n),e.options=t.options});function T(e,t){return new Qm({type:"union",options:e,...M(t)})}var V_=_("ZodDiscriminatedUnion",(e,t)=>{Qm.init(e,t),uh.init(e,t)});function po(e,t,r){return new V_({type:"union",options:t,discriminator:e,...M(r)})}var J_=_("ZodIntersection",(e,t)=>{dh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nl(e,r,o,n)});function $t(e,t){return new J_({type:"intersection",left:e,right:t})}var Fm=_("ZodRecord",(e,t)=>{ph.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function P(e,t,r){if(!t||!t._zod)return new Fm({type:"record",keyType:c(),valueType:e,...M(t)});return new Fm({type:"record",keyType:e,valueType:t,...M(r)})}var Vl=_("ZodEnum",(e,t)=>{hh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,s)=>Tl(e,o,n,s),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let s={};for(let i of o)if(r.has(i))s[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new Vl({...t,checks:[],...M(n),entries:s})},e.exclude=(o,n)=>{let s={...t.entries};for(let i of o)if(r.has(i))delete s[i];else throw Error(`Key ${i} not found in enum`);return new Vl({...t,checks:[],...M(n),entries:s})}});function K(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new Vl({type:"enum",entries:r,...M(t)})}var B_=_("ZodLiteral",(e,t)=>{mh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>El(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function h(e,t){return new B_({type:"literal",values:Array.isArray(e)?e:[e],...M(t)})}var W_=_("ZodTransform",(e,t)=>{fh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$l(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new On(e.constructor.name);r.addIssue=(s)=>{if(typeof s==="string")r.issues.push(wr(s,r.value,t));else{let i=s;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(wr(i))}};let n=t.transform(r.value,r);if(n instanceof Promise)return n.then((s)=>(r.value=s,r.fallback=!0,r));return r.value=n,r.fallback=!0,r}});function ef(e){return new W_({type:"transform",transform:e})}var tf=_("ZodOptional",(e,t)=>{rl.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$a(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function j(e){return new tf({type:"optional",innerType:e})}var K_=_("ZodExactOptional",(e,t)=>{gh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$a(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function G_(e){return new K_({type:"optional",innerType:e})}var Y_=_("ZodNullable",(e,t)=>{Sh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Hm(e){return new Y_({type:"nullable",innerType:e})}var X_=_("ZodDefault",(e,t)=>{_h.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Q_(e,t){return new X_({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Dc(t)}})}var eb=_("ZodPrefault",(e,t)=>{bh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function tb(e,t){return new eb({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Dc(t)}})}var rf=_("ZodNonOptional",(e,t)=>{yh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function rb(e,t){return new rf({type:"nonoptional",innerType:e,...M(t)})}var ob=_("ZodCatch",(e,t)=>{vh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function nb(e,t){return new ob({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var of=_("ZodPipe",(e,t)=>{ol.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n),e.in=t.in,e.out=t.out});function Vm(e,t){return new of({type:"pipe",in:e,out:t})}var sb=_("ZodPreprocess",(e,t)=>{of.init(e,t),zh.init(e,t)}),ib=_("ZodReadonly",(e,t)=>{wh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ab(e){return new ib({type:"readonly",innerType:e})}var cb=_("ZodLazy",(e,t)=>{Rh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function Bn(e){return new cb({type:"lazy",getter:e})}var lb=_("ZodCustom",(e,t)=>{xh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kl(e,r,o,n)});function ub(e,t={}){return lm(lb,e,t)}function db(e,t){return um(e,t)}function xr(e,t){return new sb({type:"pipe",in:ef(e),out:t})}var sf={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var nf;(function(e){})(nf||(nf={}));function pb(e){return em(Aa,e)}je(nl());var ho="2025-11-25";var ja=[ho,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],La="io.modelcontextprotocol/related-task",It="io.modelcontextprotocol/protocolVersion",mo="io.modelcontextprotocol/clientInfo",Ot="io.modelcontextprotocol/serverInfo",Pr="io.modelcontextprotocol/clientCapabilities",Wn="io.modelcontextprotocol/subscriptionId",fo="io.modelcontextprotocol/logLevel";var Tr="2.0";var Ct=Bn(()=>T([c(),z(),E(),Rr(),P(c(),Ct),g(Ct)])),le=P(c(),Ct),Ua=g(Ct),go=T([c(),z().int()]),So=c(),Kn=p({ttl:z().optional()}),Gn=p({taskId:c()}),_o=F({progressToken:go.optional(),[La]:Gn.optional()}),ye=p({_meta:_o.optional()}),er=ye.extend({task:Kn.optional()}),ue=p({method:c(),params:ye.loose().optional()}),Te=p({_meta:_o.optional()}),we=p({method:c(),params:Te.loose().optional()}),bo=F({get[Ot](){return _t.optional().catch(void 0)}}),de=F({_meta:bo.optional()}),nt=T([c(),z().int()]),yo=p({jsonrpc:h(Tr),id:nt,...ue.shape}).strict(),vo=p({jsonrpc:h(Tr),...we.shape}).strict(),Er=p({jsonrpc:h(Tr),id:nt,result:de}).strict(),kr=p({jsonrpc:h(Tr),id:nt.optional(),error:p({code:z().int(),message:c(),data:A().optional()})}).strict(),st=T([yo,vo,Er,kr]),Za=T([Er,kr]),tr=de.strict(),Yn=Te.extend({requestId:nt.optional(),reason:c().optional()}),zo=we.extend({method:h("notifications/cancelled"),params:Yn}),Xn=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),Nt=p({icons:g(Xn).optional()}),St=p({name:c(),title:c().optional()}),_t=St.extend({...St.shape,...Nt.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),mb=$t(p({applyDefaults:E().optional()}),le),fb=xr((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)&&Object.keys(e).length===0)return{form:{}};return e},$t(p({form:mb.optional(),url:le.optional()}),le.optional())),Da=F({list:le.optional(),cancel:le.optional(),requests:F({sampling:F({createMessage:le.optional()}).optional(),elicitation:F({create:le.optional()}).optional()}).optional()}),Fa=F({list:le.optional(),cancel:le.optional(),requests:F({tools:F({call:le.optional()}).optional()}).optional()}),Qn=p({experimental:P(c(),le).optional(),sampling:p({context:le.optional(),tools:le.optional()}).optional(),elicitation:fb.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:Da.optional(),extensions:P(c(),le).optional()}),es=ye.extend({protocolVersion:c(),capabilities:Qn,clientInfo:_t}),wo=ue.extend({method:h("initialize"),params:es}),Ro=p({experimental:P(c(),le).optional(),logging:le.optional(),completions:le.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:Fa.optional(),extensions:P(c(),le).optional()}),ts=de.extend({protocolVersion:c(),capabilities:Ro,serverInfo:_t,instructions:c().optional()}),xo=we.extend({method:h("notifications/initialized"),params:Te.optional()}),rs=ue.extend({method:h("server/discover"),params:ye.optional()}),rr=de.extend({supportedVersions:g(c()),capabilities:Ro,instructions:c().optional()}),Po=ue.extend({method:h("ping"),params:ye.optional()}),os=p({progress:z(),total:j(z()),message:j(c())}),ns=p({...Te.shape,...os.shape,progressToken:go}),To=we.extend({method:h("notifications/progress"),params:ns}),ss=ye.extend({cursor:So.optional()}),qt=ue.extend({params:ss.optional()}),At=de.extend({nextCursor:So.optional()}),Eo=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),ko=Eo.extend({text:c()}),Kl=c().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),$o=Eo.extend({blob:Kl}),Mt=K(["user","assistant"]),bt=p({audience:g(Mt).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),Co=p({...St.shape,...Nt.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:bt.optional(),_meta:j(F({}))}),is=p({...St.shape,...Nt.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:bt.optional(),_meta:j(F({}))}),as=qt.extend({method:h("resources/list")}),cs=At.extend({resources:g(Co)}),ls=qt.extend({method:h("resources/templates/list")}),us=At.extend({resourceTemplates:g(is)}),$r=ye.extend({uri:c()}),ds=$r,ps=ue.extend({method:h("resources/read"),params:ds}),hs=de.extend({contents:g(T([ko,$o]))}),ms=we.extend({method:h("notifications/resources/list_changed"),params:Te.optional()}),fs=$r,gs=ue.extend({method:h("resources/subscribe"),params:fs}),Ss=$r,_s=ue.extend({method:h("resources/unsubscribe"),params:Ss}),Io=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:g(c()).optional()}),bs=ye.extend({notifications:Io}),ys=ue.extend({method:h("subscriptions/listen"),params:bs}),vs=Te.extend({notifications:Io}),zs=we.extend({method:h("notifications/subscriptions/acknowledged"),params:vs}),ws=bo.extend({[Wn]:nt}),Rs=de.extend({_meta:ws}),xs=Te.extend({uri:c()}),Ps=we.extend({method:h("notifications/resources/updated"),params:xs}),Ts=p({name:c(),description:j(c()),required:j(E())}),Es=p({...St.shape,...Nt.shape,description:j(c()),arguments:j(g(Ts)),_meta:j(F({}))}),ks=qt.extend({method:h("prompts/list")}),$s=At.extend({prompts:g(Es)}),Cs=ye.extend({name:c(),arguments:P(c(),c()).optional()}),Is=ue.extend({method:h("prompts/get"),params:Cs}),Cr=p({type:h("text"),text:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Ir=p({type:h("image"),data:Kl,mimeType:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Or=p({type:h("audio"),data:Kl,mimeType:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Os=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),Nr=p({type:h("resource"),resource:T([ko,$o]),annotations:bt.optional(),_meta:P(c(),A()).optional()}),qr=Co.extend({type:h("resource_link")}),yt=T([Cr,Ir,Or,qr,Nr]),Ns=p({role:Mt,content:yt}),qs=de.extend({description:c().optional(),messages:g(Ns)}),As=we.extend({method:h("notifications/prompts/list_changed"),params:Te.optional()}),Ms=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),js=p({taskSupport:K(["required","optional","forbidden"]).optional()}),or=p({...St.shape,...Nt.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),Ct).optional(),required:g(c()).optional()}).catchall(A()),outputSchema:F({$schema:c().optional()}).optional(),annotations:Ms.optional(),execution:js.optional(),_meta:P(c(),A()).optional()}),Ls=qt.extend({method:h("tools/list")}),Us=At.extend({tools:g(or)}),nr=de.extend({content:g(yt).default([]),structuredContent:A().optional(),isError:E().optional()}),Ha=nr.or(de.extend({toolResult:A()})),Zs=er.extend({name:c(),arguments:P(c(),A()).optional()}),Ds=ue.extend({method:h("tools/call"),params:Zs}),Fs=we.extend({method:h("notifications/tools/list_changed"),params:Te.optional()}),Hs=p({autoRefresh:E().default(!0),debounceMs:z().int().nonnegative().default(300)}),Oo=K(["debug","info","notice","warning","error","critical","alert","emergency"]),Vs=ye.extend({level:Oo}),Js=ue.extend({method:h("logging/setLevel"),params:Vs}),Bs=Te.extend({level:Oo,logger:c().optional(),data:A()}),Ar=we.extend({method:h("notifications/message"),params:Bs}),Ws=p({name:c().optional()}),Ks=p({hints:g(Ws).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),Gs=p({mode:K(["auto","required","none"]).optional()}),Ys=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:g(yt),structuredContent:A().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),Xs=po("type",[Cr,Ir,Or]),Qt=po("type",[Cr,Ir,Or,Os,Ys]),Qs=p({role:Mt,content:T([Qt,g(Qt)]),_meta:P(c(),A()).optional()}),ei=er.extend({messages:g(Qs),modelPreferences:Ks.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:le.optional(),tools:g(or).optional(),toolChoice:Gs.optional()}),ti=ue.extend({method:h("sampling/createMessage"),params:ei}),ri=de.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Mt,content:Xs}),oi=de.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Mt,content:T([Qt,g(Qt)])}),No=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),Mr=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),jr=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),qo=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),Ao=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),Mo=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),ni=T([qo,Ao]),jo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),Lo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),si=T([jo,Lo]),ii=T([Mo,ni,si]),Uo=T([ii,No,Mr,jr]),Lr=er.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),Uo),required:g(c()).optional()}).catchall(A())}),ai=er.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),ci=T([Lr,ai]),li=ue.extend({method:h("elicitation/create"),params:ci}),ui=Te.extend({elicitationId:c()}),di=we.extend({method:h("notifications/elicitation/complete"),params:ui}),pi=de.extend({action:K(["accept","decline","cancel"]),content:xr((e)=>e===null?void 0:e,P(c(),T([c(),z(),E(),g(c())])).optional())}),hi=p({type:h("ref/resource"),uri:c()}),mi=p({type:h("ref/prompt"),name:c()}),fi=ye.extend({ref:T([mi,hi]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),gi=ue.extend({method:h("completion/complete"),params:fi}),Si=de.extend({completion:F({values:g(c()).max(100),total:j(z().int()),hasMore:j(E())})}),_i=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),bi=ue.extend({method:h("roots/list"),params:ye.optional()}),yi=de.extend({roots:g(_i)}),vi=we.extend({method:h("notifications/roots/list_changed"),params:Te.optional()}),Va=F({ttl:z().optional(),pollInterval:z().optional()}),zi=K(["working","input_required","completed","failed","cancelled"]),jt=p({taskId:c(),status:zi,ttl:T([z(),Rr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:j(z()),statusMessage:j(c())}),Ja=de.extend({task:jt}),wi=Te.merge(jt),Ba=we.extend({method:h("notifications/tasks/status"),params:wi}),Wa=ue.extend({method:h("tasks/get"),params:ye.extend({taskId:c()})}),Ka=de.merge(jt),Ga=ue.extend({method:h("tasks/result"),params:ye.extend({taskId:c()})}),Ya=de.loose(),Xa=qt.extend({method:h("tasks/list")}),Qa=At.extend({tasks:g(jt)}),ec=ue.extend({method:h("tasks/cancel"),params:ye.extend({taskId:c()})}),tc=de.merge(jt),rc=T([Po,wo,rs,gi,Js,Is,ks,as,ls,ps,gs,_s,ys,Ds,Ls]),oc=T([zo,To,xo,vi]),nc=T([tr,ri,oi,pi,yi]),sc=T([Po,ti,li,bi]),ic=T([zo,To,Ar,Ps,ms,Fs,As,zs,di]),ac=T([tr,ts,rr,Si,qs,$s,cs,us,hs,nr,Us,Rs]),be=qa().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:sf.custom,message:"URL must be parseable",fatal:!0}),Mc}).refine((e)=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Zo=F({resource:c().url(),authorization_servers:g(be).optional(),jwks_uri:c().url().optional(),scopes_supported:g(c()).optional(),bearer_methods_supported:g(c()).optional(),resource_signing_alg_values_supported:g(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:E().optional(),authorization_details_types_supported:g(c()).optional(),dpop_signing_alg_values_supported:g(c()).optional(),dpop_bound_access_tokens_required:E().optional()}),Ur=F({issuer:c(),authorization_endpoint:be,token_endpoint:be,registration_endpoint:be.optional(),scopes_supported:g(c()).optional(),response_types_supported:g(c()),response_modes_supported:g(c()).optional(),grant_types_supported:g(c()).optional(),token_endpoint_auth_methods_supported:g(c()).optional(),token_endpoint_auth_signing_alg_values_supported:g(c()).optional(),service_documentation:be.optional(),revocation_endpoint:be.optional(),revocation_endpoint_auth_methods_supported:g(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:g(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:g(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:g(c()).optional(),code_challenge_methods_supported:g(c()).optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0),dpop_signing_alg_values_supported:g(c()).optional()}),Ri=F({issuer:c(),authorization_endpoint:be,token_endpoint:be,userinfo_endpoint:be.optional(),jwks_uri:be,registration_endpoint:be.optional(),scopes_supported:g(c()).optional(),response_types_supported:g(c()),response_modes_supported:g(c()).optional(),grant_types_supported:g(c()).optional(),acr_values_supported:g(c()).optional(),subject_types_supported:g(c()),id_token_signing_alg_values_supported:g(c()),id_token_encryption_alg_values_supported:g(c()).optional(),id_token_encryption_enc_values_supported:g(c()).optional(),userinfo_signing_alg_values_supported:g(c()).optional(),userinfo_encryption_alg_values_supported:g(c()).optional(),userinfo_encryption_enc_values_supported:g(c()).optional(),request_object_signing_alg_values_supported:g(c()).optional(),request_object_encryption_alg_values_supported:g(c()).optional(),request_object_encryption_enc_values_supported:g(c()).optional(),token_endpoint_auth_methods_supported:g(c()).optional(),token_endpoint_auth_signing_alg_values_supported:g(c()).optional(),display_values_supported:g(c()).optional(),claim_types_supported:g(c()).optional(),claims_supported:g(c()).optional(),service_documentation:c().optional(),claims_locales_supported:g(c()).optional(),ui_locales_supported:g(c()).optional(),claims_parameter_supported:E().optional(),request_parameter_supported:E().optional(),request_uri_parameter_supported:E().optional(),require_request_uri_registration:E().optional(),op_policy_uri:be.optional(),op_tos_uri:be.optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0)}),Do=p({...Ri.shape,...Ur.pick({code_challenge_methods_supported:!0}).shape}),Fo=p({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:pb().optional(),scope:c().optional(),refresh_token:c().optional(),issuer:c().optional().catch(void 0)}).strip(),xi=p({issued_token_type:h("urn:ietf:params:oauth:token-type:id-jag"),access_token:c(),token_type:c().optional(),expires_in:z().optional(),scope:c().optional()}).strip(),Ho=p({error:c(),error_description:c().optional(),error_uri:c().optional()}),Wl=be.optional().or(h("").transform(()=>{return})),Pi=p({redirect_uris:g(be),token_endpoint_auth_method:c().optional(),grant_types:g(c()).optional(),response_types:g(c()).optional(),application_type:c().optional(),client_name:c().optional(),client_uri:be.optional(),logo_uri:Wl,scope:c().optional(),contacts:g(c()).optional(),tos_uri:Wl,policy_uri:c().optional(),jwks_uri:be.optional(),jwks:Ma().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Ti=p({client_id:c(),client_secret:c().optional(),client_id_issued_at:z().optional(),client_secret_expires_at:z().optional(),issuer:c().optional().catch(void 0)}).strip(),Vo=Pi.merge(Ti),cc=p({error:c(),error_description:c().optional()}).strip(),lc=p({token:c(),token_type_hint:c().optional()}).strip();var eu=Symbol.for("mcp.sdk.errorBrands");function Zr(e,t){let r=new Set,o=t;while(typeof o==="function"){let n=o.mcpBrand;if(Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof n==="string")r.add(n);o=Object.getPrototypeOf(o)}if(r.size===0)return;Object.defineProperty(e,eu,{value:r,enumerable:!1,configurable:!0})}function Be(e,t){try{if(typeof t==="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand==="string"&&Object.prototype.hasOwnProperty.call(t,eu)){let r=t[eu];if(r&&typeof r.has==="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var Ut=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}({}),Dr=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Be(this,t)}static isInstance(t){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,t)}constructor(t,r,o){super(r);this.code=t,this.errorUri=o,this.name="OAuthError",Zr(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};if(this.errorUri)t.error_uri=this.errorUri;return t}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}},O=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}({}),N=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e,t,r,o){super(t,o);this.code=e,this.data=r,this.name="SdkError",Zr(this,new.target)}},vt=class extends N{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,o){super(e,t,r,o);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function If(e){let t=typeof e==="string"?new URL(e):new URL(e.href);return t.hash="",t}function su(e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}function Of({requestedResource:e,configuredResource:t}){let r=typeof e==="string"?new URL(e):new URL(e.href),o=typeof t==="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin)return!1;if(r.pathname.length<o.pathname.length)return!1;let n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(s)}var Nf="2026-07-28",iu=[Nf];function Zt(e){return e>=Nf}function au(e){return e.filter((t)=>!Zt(t))}function Oi(e){return e.filter((t)=>Zt(t))}function qf(e){let t=e.structuredContent;if(t===void 0)return e;if(!(typeof t!=="object"||t===null||Array.isArray(t)))return e;if(e.content?.some((r)=>r.type==="text")??!1)return e;return{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}var Af=["task","inputRequests","requestState"];function gb(e){if(e===null||typeof e!=="object"||Array.isArray(e)||e.content!==void 0||Af.some((t)=>(t in e)))return e;return{...e,content:[]}}function Sb(){let e=Bn(()=>T([c(),z(),E(),Rr(),P(c(),e),g(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=p({ttl:z().optional()}),s=p({taskId:c()}),i=F({progressToken:r.optional(),"io.modelcontextprotocol/related-task":s.optional()}),a=p({_meta:i.optional()}),l=a.extend({task:n.optional()}),u=p({method:c(),params:a.loose().optional()}),d=p({_meta:i.optional()}),m=p({method:c(),params:d.loose().optional()}),f=F({_meta:i.optional()}),S=T([c(),z().int()]),b=f.strict(),y=d.extend({requestId:S.optional(),reason:c().optional()}),v=m.extend({method:h("notifications/cancelled"),params:y}),U=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),H=p({icons:g(U).optional()}),x=p({name:c(),title:c().optional()}),Z=x.extend({...x.shape,...H.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),R=$t(p({applyDefaults:E().optional()}),t),w=xr((Pe)=>{if(Pe&&typeof Pe==="object"&&!Array.isArray(Pe)&&Object.keys(Pe).length===0)return{form:{}};return Pe},$t(p({form:R.optional(),url:t.optional()}),t.optional())),D=F({list:t.optional(),cancel:t.optional(),requests:F({sampling:F({createMessage:t.optional()}).optional(),elicitation:F({create:t.optional()}).optional()}).optional()}),X=F({list:t.optional(),cancel:t.optional(),requests:F({tools:F({call:t.optional()}).optional()}).optional()}),Y=p({experimental:P(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:w.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:D.optional(),extensions:P(c(),t).optional()}),ce=a.extend({protocolVersion:c(),capabilities:Y,clientInfo:Z}),Ee=u.extend({method:h("initialize"),params:ce}),te=p({experimental:P(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:X.optional(),extensions:P(c(),t).optional()}),se=f.extend({protocolVersion:c(),capabilities:te,serverInfo:Z,instructions:c().optional()}),ve=m.extend({method:h("notifications/initialized"),params:d.optional()}),ke=u.extend({method:h("ping"),params:a.optional()}),ct=p({progress:z(),total:j(z()),message:j(c())}),qe=p({...d.shape,...ct.shape,progressToken:r}),We=m.extend({method:h("notifications/progress"),params:qe}),lt=a.extend({cursor:o.optional()}),Ze=u.extend({params:lt.optional()}),$e=f.extend({nextCursor:o.optional()}),Tt=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),Et=Tt.extend({text:c()}),ut=c().refine((Pe)=>{try{return atob(Pe),!0}catch{return!1}},{message:"Invalid Base64 string"}),Re=Tt.extend({blob:ut}),Ce=K(["user","assistant"]),Ie=p({audience:g(Ce).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),et=p({...x.shape,...H.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:Ie.optional(),_meta:j(F({}))}),lr=p({...x.shape,...H.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:Ie.optional(),_meta:j(F({}))}),De=Ze.extend({method:h("resources/list")}),Fe=$e.extend({resources:g(et)}),Ae=Ze.extend({method:h("resources/templates/list")}),Ke=$e.extend({resourceTemplates:g(lr)}),Ge=a.extend({uri:c()}),dt=Ge,pt=u.extend({method:h("resources/read"),params:dt}),Ht=f.extend({contents:g(T([Et,Re]))}),ht=m.extend({method:h("notifications/resources/list_changed"),params:d.optional()}),ur=Ge,C=u.extend({method:h("resources/subscribe"),params:ur}),mt=Ge,V=u.extend({method:h("resources/unsubscribe"),params:mt}),q=d.extend({uri:c()}),G=m.extend({method:h("notifications/resources/updated"),params:q}),I=p({name:c(),description:j(c()),required:j(E())}),k=p({...x.shape,...H.shape,description:j(c()),arguments:j(g(I)),_meta:j(F({}))}),B=Ze.extend({method:h("prompts/list")}),J=$e.extend({prompts:g(k)}),ge=a.extend({name:c(),arguments:P(c(),c()).optional()}),dr=u.extend({method:h("prompts/get"),params:ge}),ft=p({type:h("text"),text:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),pr=p({type:h("image"),data:ut,mimeType:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),hr=p({type:h("audio"),data:ut,mimeType:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),nn=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),Vt=p({type:h("resource"),resource:T([Et,Re]),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),sn=et.extend({type:h("resource_link")}),Ye=T([ft,pr,hr,sn,Vt]),Kr=p({role:Ce,content:Ye}),Gr=f.extend({description:c().optional(),messages:g(Kr)}),mr=m.extend({method:h("notifications/prompts/list_changed"),params:d.optional()}),an=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Yr=p({taskSupport:K(["required","optional","forbidden"]).optional()}),fr=p({...x.shape,...H.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:g(c()).optional()}).catchall(A()),outputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:g(c()).optional()}).catchall(A()).optional(),annotations:an.optional(),execution:Yr.optional(),_meta:P(c(),A()).optional()}),Xr=Ze.extend({method:h("tools/list")}),Qr=$e.extend({tools:g(fr)}),eo=f.extend({content:g(Ye),structuredContent:P(c(),A()).optional(),isError:E().optional()}),xe=l.extend({name:c(),arguments:P(c(),A()).optional()}),cn=u.extend({method:h("tools/call"),params:xe}),Gi=m.extend({method:h("notifications/tools/list_changed"),params:d.optional()}),to=K(["debug","info","notice","warning","error","critical","alert","emergency"]),ln=a.extend({level:to}),un=u.extend({method:h("logging/setLevel"),params:ln}),dn=d.extend({level:to,logger:c().optional(),data:A()}),pn=m.extend({method:h("notifications/message"),params:dn}),hn=p({name:c().optional()}),mn=p({hints:g(hn).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),fn=p({mode:K(["auto","required","none"]).optional()}),Yi=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:g(Ye),structuredContent:p({}).loose().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),gn=po("type",[ft,pr,hr]),Jt=po("type",[ft,pr,hr,nn,Yi]),Sn=p({role:Ce,content:T([Jt,g(Jt)]),_meta:P(c(),A()).optional()}),_n=l.extend({messages:g(Sn),modelPreferences:mn.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:t.optional(),tools:g(fr).optional(),toolChoice:fn.optional()}),bn=u.extend({method:h("sampling/createMessage"),params:_n}),yn=f.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Ce,content:gn}),vn=f.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Ce,content:T([Jt,g(Jt)])}),zn=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),wn=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),Rn=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),xn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),Pn=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),Tn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),En=T([xn,Pn]),gr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),Sr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),Xi=T([gr,Sr]),Qi=T([Tn,En,Xi]),He=T([Qi,zn,wn,Rn]),Ve=l.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),He),required:g(c()).optional()}).catchall(A())}),kn=l.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),tt=T([Ve,kn]),ea=u.extend({method:h("elicitation/create"),params:tt}),ta=d.extend({elicitationId:c()}),ra=m.extend({method:h("notifications/elicitation/complete"),params:ta}),oa=f.extend({action:K(["accept","decline","cancel"]),content:xr((Pe)=>Pe===null?void 0:Pe,P(c(),T([c(),z(),E(),g(c())])).optional())}),na=p({type:h("ref/resource"),uri:c()}),sa=p({type:h("ref/prompt"),name:c()}),ia=a.extend({ref:T([sa,na]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),$n=u.extend({method:h("completion/complete"),params:ia}),aa=f.extend({completion:F({values:g(c()).max(100),total:j(z().int()),hasMore:j(E())})}),ca=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),ro=u.extend({method:h("roots/list"),params:a.optional()}),Cn=f.extend({roots:g(ca)}),la=m.extend({method:h("notifications/roots/list_changed"),params:d.optional()}),ua=F({ttl:z().optional(),pollInterval:z().optional()}),In=K(["working","input_required","completed","failed","cancelled"]),Bt=p({taskId:c(),status:In,ttl:T([z(),Rr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:j(z()),statusMessage:j(c())}),Me=f.extend({task:Bt}),da=d.merge(Bt),_r=m.extend({method:h("notifications/tasks/status"),params:da}),oo=u.extend({method:h("tasks/get"),params:a.extend({taskId:c()})}),no=f.merge(Bt),so=u.extend({method:h("tasks/result"),params:a.extend({taskId:c()})}),Ac=f.loose(),Oe=Ze.extend({method:h("tasks/list")}),fe=$e.extend({tasks:g(Bt)}),br=u.extend({method:h("tasks/cancel"),params:a.extend({taskId:c()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:n,RelatedTaskMetadataSchema:s,RequestMetaSchema:i,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:l,RequestSchema:u,NotificationsParamsSchema:d,NotificationSchema:m,ResultSchema:f,RequestIdSchema:S,EmptyResultSchema:b,CancelledNotificationParamsSchema:y,CancelledNotificationSchema:v,IconSchema:U,IconsSchema:H,BaseMetadataSchema:x,ImplementationSchema:Z,ClientTasksCapabilitySchema:D,ServerTasksCapabilitySchema:X,ClientCapabilitiesSchema:Y,InitializeRequestParamsSchema:ce,InitializeRequestSchema:Ee,ServerCapabilitiesSchema:te,InitializeResultSchema:se,InitializedNotificationSchema:ve,PingRequestSchema:ke,ProgressSchema:ct,ProgressNotificationParamsSchema:qe,ProgressNotificationSchema:We,PaginatedRequestParamsSchema:lt,PaginatedRequestSchema:Ze,PaginatedResultSchema:$e,ResourceContentsSchema:Tt,TextResourceContentsSchema:Et,BlobResourceContentsSchema:Re,RoleSchema:Ce,AnnotationsSchema:Ie,ResourceSchema:et,ResourceTemplateSchema:lr,ListResourcesRequestSchema:De,ListResourcesResultSchema:Fe,ListResourceTemplatesRequestSchema:Ae,ListResourceTemplatesResultSchema:Ke,ResourceRequestParamsSchema:Ge,ReadResourceRequestParamsSchema:dt,ReadResourceRequestSchema:pt,ReadResourceResultSchema:Ht,ResourceListChangedNotificationSchema:ht,SubscribeRequestParamsSchema:ur,SubscribeRequestSchema:C,UnsubscribeRequestParamsSchema:mt,UnsubscribeRequestSchema:V,ResourceUpdatedNotificationParamsSchema:q,ResourceUpdatedNotificationSchema:G,PromptArgumentSchema:I,PromptSchema:k,ListPromptsRequestSchema:B,ListPromptsResultSchema:J,GetPromptRequestParamsSchema:ge,GetPromptRequestSchema:dr,TextContentSchema:ft,ImageContentSchema:pr,AudioContentSchema:hr,ToolUseContentSchema:nn,EmbeddedResourceSchema:Vt,ResourceLinkSchema:sn,ContentBlockSchema:Ye,PromptMessageSchema:Kr,GetPromptResultSchema:Gr,PromptListChangedNotificationSchema:mr,ToolAnnotationsSchema:an,ToolExecutionSchema:Yr,ToolSchema:fr,ListToolsRequestSchema:Xr,ListToolsResultSchema:Qr,CallToolResultSchema:eo,CallToolRequestParamsSchema:xe,CallToolRequestSchema:cn,ToolListChangedNotificationSchema:Gi,LoggingLevelSchema:to,SetLevelRequestParamsSchema:ln,SetLevelRequestSchema:un,LoggingMessageNotificationParamsSchema:dn,LoggingMessageNotificationSchema:pn,ModelHintSchema:hn,ModelPreferencesSchema:mn,ToolChoiceSchema:fn,ToolResultContentSchema:Yi,SamplingContentSchema:gn,SamplingMessageContentBlockSchema:Jt,SamplingMessageSchema:Sn,CreateMessageRequestParamsSchema:_n,CreateMessageRequestSchema:bn,CreateMessageResultSchema:yn,CreateMessageResultWithToolsSchema:vn,BooleanSchemaSchema:zn,StringSchemaSchema:wn,NumberSchemaSchema:Rn,UntitledSingleSelectEnumSchemaSchema:xn,TitledSingleSelectEnumSchemaSchema:Pn,LegacyTitledEnumSchemaSchema:Tn,SingleSelectEnumSchemaSchema:En,UntitledMultiSelectEnumSchemaSchema:gr,TitledMultiSelectEnumSchemaSchema:Sr,MultiSelectEnumSchemaSchema:Xi,EnumSchemaSchema:Qi,PrimitiveSchemaDefinitionSchema:He,ElicitRequestFormParamsSchema:Ve,ElicitRequestURLParamsSchema:kn,ElicitRequestParamsSchema:tt,ElicitRequestSchema:ea,ElicitationCompleteNotificationParamsSchema:ta,ElicitationCompleteNotificationSchema:ra,ElicitResultSchema:oa,ResourceTemplateReferenceSchema:na,PromptReferenceSchema:sa,CompleteRequestParamsSchema:ia,CompleteRequestSchema:$n,CompleteResultSchema:aa,RootSchema:ca,ListRootsRequestSchema:ro,ListRootsResultSchema:Cn,RootsListChangedNotificationSchema:la,TaskCreationParamsSchema:ua,TaskStatusSchema:In,TaskSchema:Bt,CreateTaskResultSchema:Me,TaskStatusNotificationParamsSchema:da,TaskStatusNotificationSchema:_r,GetTaskRequestSchema:oo,GetTaskResultSchema:no,GetTaskPayloadRequestSchema:so,GetTaskPayloadResultSchema:Ac,ListTasksRequestSchema:Oe,ListTasksResultSchema:fe,CancelTaskRequestSchema:br,CancelTaskResultSchema:f.merge(Bt),ClientRequestSchema:T([ke,Ee,$n,un,dr,B,De,Ae,pt,C,V,cn,Xr,oo,so,Oe,br]),ClientNotificationSchema:T([v,We,ve,la,_r]),ClientResultSchema:T([b,yn,vn,oa,Cn,no,fe,Me]),ServerRequestSchema:T([ke,bn,ea,ro,oo,so,Oe,br]),ServerNotificationSchema:T([v,We,pn,G,ht,Gi,mr,_r,ra]),ServerResultSchema:T([b,se,aa,Gr,J,Fe,Ke,Ht,eo,Qr,no,fe,Me]),CallToolResultWireSchema:A().superRefine((Pe,AS)=>{if(typeof Pe!=="object"||Pe===null||Array.isArray(Pe)||Pe.content!==void 0)return;for(let rd of Af)if(rd in Pe){AS.addIssue({code:"custom",message:`content is required when the body carries '${rd}' — another result family cannot default into an empty tools/call success`});return}}).transform(gb).pipe(eo)}}var _b;function Mf(){return _b??=Sb()}function jf(e){return e.type!=="object"}var bb=new Set(["const","enum","default","examples"]),yb=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function _f(e){return e!==void 0&&!(typeof e==="string"&&e.startsWith("#"))}function vb(e){let t=typeof e.$schema==="string"?e.$schema:void 0;if(_f(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=cd(e.$schema)&&e.$recursiveAnchor!==!0,o=(n,s)=>{if(Array.isArray(n))return n.map((l)=>o(l,!1));if(n===null||typeof n!=="object")return n;if(!s&&_f(n.$id))return n;let i={},a=!1;for(let[l,u]of Object.entries(n))if(s)i[l]=o(u,!1);else if((l==="$ref"||l==="$dynamicRef")&&typeof u==="string")i[l]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u;else if(l==="$recursiveRef"&&u==="#"&&r)a=!0;else if(bb.has(l))i[l]=u;else if(yb.has(l))i[l]=o(u,!0);else i[l]=o(u,!1);if(a)if("$ref"in i)i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:"#/properties/result"}];else i.$ref="#/properties/result";return i};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}var Lf={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},Uf={"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},zb={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},uc;function cu(){if(uc)return uc;let e=Mf();return uc={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}},uc}function Zf(e){return Object.prototype.hasOwnProperty.call(Lf,e)}function Df(e){return Object.prototype.hasOwnProperty.call(Uf,e)}function wb(e){return Object.prototype.hasOwnProperty.call(zb,e)}function Rb(e){return wb(e)?cu().resultSchemas[e]:void 0}function xb(e){return Zf(e)?cu().requestSchemas[e]:void 0}function Pb(e){return Df(e)?cu().notificationSchemas[e]:void 0}var kx=Object.keys(Lf),$x=Object.keys(Uf);function tu(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function dc(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var bf={ok:!1,reason:"not-in-era"};function yf(e){return tu(e)&&tu(e.outputSchema)&&jf(e.outputSchema)}function vf(e){return e}var lu={era:"2025-11-25",hasRequestMethod:Zf,hasNotificationMethod:Df,validateRequest:(e,t)=>dc(xb(e),t),validateResult:(e,t)=>dc(Rb(e),t),validateNotification:(e,t)=>dc(Pb(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>bf,validateInputResponse:()=>bf,samplingResultVariant:(e,t)=>{let r=Mf();return dc(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)},outboundEnvelope:(e)=>{return},validateEnvelopeMeta:(e)=>[],projectCallToolResult(e,t){let r=qf(e),o=r.structuredContent;if(o===void 0)return r;let n=typeof o!=="object"||o===null||Array.isArray(o),s=t!==void 0&&jf(t);if(!n&&!s)return r;return{...r,structuredContent:{result:o}}},decodeResult(e,t){if(tu(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:vf(r)}}return{kind:"complete",result:vf(t)}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;if(!Array.isArray(r)||!r.some((o)=>yf(o)))return t;return{...t,tools:r.map((o)=>yf(o)?{...o,outputSchema:vb(o.outputSchema)}:o)}},encodeErrorCode:(e)=>e===-32002?-32602:e,checkInboundEnvelope:(e)=>{return}};function Tb(){let e=Bn(()=>T([c(),z(),E(),Rr(),P(c(),e),g(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=T([c(),z().int()]),s=K(["user","assistant"]),i=K(["debug","info","notice","warning","error","critical","alert","emergency"]),a=c().refine((fe)=>{try{return atob(fe),!0}catch{return!1}},{message:"Invalid Base64 string"}),l=p({ttl:z().optional()}),u=p({taskId:c()}),d=F({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),m=p({_meta:d.optional()}),f=m.extend({task:l.optional()}),S=p({_meta:d.optional()}),b=p({method:c(),params:S.loose().optional()}),y=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),v=p({icons:g(y).optional()}),U=p({name:c(),title:c().optional()}),H=U.extend({...U.shape,...v.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),x=$t(p({applyDefaults:E().optional()}),t),Z=xr((fe)=>{if(fe&&typeof fe==="object"&&!Array.isArray(fe)&&Object.keys(fe).length===0)return{form:{}};return fe},$t(p({form:x.optional(),url:t.optional()}),t.optional())),R=F({list:t.optional(),cancel:t.optional(),requests:F({sampling:F({createMessage:t.optional()}).optional(),elicitation:F({create:t.optional()}).optional()}).optional()}),w=F({list:t.optional(),cancel:t.optional(),requests:F({tools:F({call:t.optional()}).optional()}).optional()}),D=p({experimental:P(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:Z.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:R.optional(),extensions:P(c(),t).optional()}),X=p({experimental:P(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:w.optional(),extensions:P(c(),t).optional()}),Y=p({progress:z(),total:j(z()),message:j(c())}),ce=p({...S.shape,...Y.shape,progressToken:r}),Ee=b.extend({method:h("notifications/progress"),params:ce}),te=S.extend({level:i,logger:c().optional(),data:A()}),se=b.extend({method:h("notifications/message"),params:te}),ve=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),ke=ve.extend({text:c()}),ct=ve.extend({blob:a}),qe=p({audience:g(s).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),We=p({...U.shape,...v.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:qe.optional(),_meta:j(F({}))}),lt=p({...U.shape,...v.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:qe.optional(),_meta:j(F({}))}),Ze=b.extend({method:h("notifications/resources/list_changed"),params:S.optional()}),$e=S.extend({uri:c()}),Tt=b.extend({method:h("notifications/resources/updated"),params:$e}),Et=p({name:c(),description:j(c()),required:j(E())}),ut=p({...U.shape,...v.shape,description:j(c()),arguments:j(g(Et)),_meta:j(F({}))}),Re=b.extend({method:h("notifications/prompts/list_changed"),params:S.optional()}),Ce=p({type:h("text"),text:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),Ie=p({type:h("image"),data:a,mimeType:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),et=p({type:h("audio"),data:a,mimeType:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),lr=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),De=p({type:h("resource"),resource:T([ke,ct]),annotations:qe.optional(),_meta:P(c(),A()).optional()}),Fe=We.extend({type:h("resource_link")}),Ae=T([Ce,Ie,et,Fe,De]),Ke=p({role:s,content:Ae}),Ge=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),dt=b.extend({method:h("notifications/tools/list_changed"),params:S.optional()}),pt=p({name:c().optional()}),Ht=p({hints:g(pt).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),ht=p({mode:K(["auto","required","none"]).optional()}),ur=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),C=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),mt=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),V=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),q=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),G=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),I=T([V,q]),k=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),B=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),J=T([k,B]),ge=T([G,I,J]),dr=T([ge,ur,C,mt]),ft=f.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),dr),required:g(c()).optional()}).catchall(A())}),pr=p({type:h("ref/resource"),uri:c()}),hr=p({type:h("ref/prompt"),name:c()}),nn=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),Vt=D.shape,sn=p({experimental:Vt.experimental,sampling:Vt.sampling,elicitation:Vt.elicitation,roots:Vt.roots,extensions:Vt.extensions}),Ye=X.shape,Kr=p({experimental:Ye.experimental,logging:Ye.logging,completions:Ye.completions,prompts:Ye.prompts,resources:Ye.resources,tools:Ye.tools,extensions:Ye.extensions}),Gr=F({progressToken:r.optional(),[It]:c(),[mo]:H.optional(),[Pr]:sn,[fo]:i.optional()}),mr=p({...U.shape,...v.shape,description:c().optional(),inputSchema:F({$schema:c().optional(),type:h("object")}),outputSchema:F({$schema:c().optional()}).optional(),annotations:Ge.optional(),_meta:P(c(),A()).optional()}),an=p({type:h("tool_result"),toolUseId:c(),content:g(Ae),structuredContent:A().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),Yr=T([Ce,Ie,et,lr,an]),fr=p({role:s,content:T([Yr,g(Yr)]),_meta:P(c(),A()).optional()}),Xr=c(),Qr=F({[Ot]:H.optional().catch(void 0)}),eo=Qr.optional();function xe(fe){return F({_meta:eo,resultType:Xr.default("complete"),...fe})}let cn=xe({}),Gi=xe({nextCursor:o.optional()}),to=xe({content:g(Ae),structuredContent:A().optional(),isError:E().optional()}),ln=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:g(mr),nextCursor:o.optional()}),un=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:g(ut),nextCursor:o.optional()}),dn=xe({description:c().optional(),messages:g(Ke)}),pn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:g(We),nextCursor:o.optional()}),hn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:g(lt),nextCursor:o.optional()}),mn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:g(T([ke,ct]))}),fn=xe({completion:p({values:g(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),Yi=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"])}),gn=xe({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:g(c()),capabilities:Kr,instructions:c().optional()}),Jt=p({messages:g(fr),modelPreferences:Ht.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:t.optional(),tools:g(mr).optional(),toolChoice:ht.optional()}),Sn=p({method:h("sampling/createMessage"),params:Jt}),_n=p({method:h("roots/list"),params:p({_meta:P(c(),A()).optional()}).optional()}),bn=p({...fr.shape,model:c(),stopReason:c().optional()}),yn=p({roots:g(nn)}),vn=p({action:K(["accept","decline","cancel"]),content:P(c(),T([c(),z(),E(),g(c())])).optional()}),zn=p({mode:h("url"),message:c(),url:c().url()}),wn=T([ft,zn]),Rn=p({method:h("elicitation/create"),params:wn}),xn=T([Sn,_n,Rn]),Pn=T([bn,yn,vn]),Tn=P(c(),xn),En=P(c(),Pn),gr=xe({inputRequests:Tn.optional(),requestState:c().optional()}),Sr={inputResponses:En.optional(),requestState:c().optional()},Xi=p({_meta:Gr,...Sr}),Qi=F({progressToken:r.optional()});function He(fe,br){return p({method:h(fe),params:p({_meta:Gr,...br})})}function Ve(fe,br){return p({method:h(fe),params:p({_meta:Qi.optional(),...br}).optional()})}let kn={name:c(),arguments:P(c(),A()).optional(),...Sr},tt={cursor:o.optional()},ea=He("tools/call",kn),ta=He("tools/list",tt),ra=He("prompts/list",tt),oa=He("prompts/get",{name:c(),arguments:P(c(),c()).optional(),...Sr}),na=He("resources/list",tt),sa=He("resources/templates/list",tt),ia=He("resources/read",{uri:c(),...Sr}),$n={ref:T([hr,pr]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()},aa=He("completion/complete",$n),ca=He("server/discover",{}),ro=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:g(c()).optional()}),Cn={notifications:ro},la=He("subscriptions/listen",Cn),ua=Qr.extend({"io.modelcontextprotocol/subscriptionId":n}),In=F({_meta:ua,resultType:Xr.default("complete")}),Bt={"tools/call":Ve("tools/call",kn),"tools/list":Ve("tools/list",tt),"prompts/get":Ve("prompts/get",{name:c(),arguments:P(c(),c()).optional()}),"prompts/list":Ve("prompts/list",tt),"resources/list":Ve("resources/list",tt),"resources/templates/list":Ve("resources/templates/list",tt),"resources/read":Ve("resources/read",{uri:c()}),"completion/complete":Ve("completion/complete",$n),"server/discover":Ve("server/discover",{}),"subscriptions/listen":Ve("subscriptions/listen",Cn)};function Me(fe){return F({_meta:eo,...fe})}let da={"tools/call":Me({content:g(Ae),structuredContent:A().optional(),isError:E().optional()}),"tools/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:g(mr),nextCursor:o.optional()}),"prompts/get":Me({description:c().optional(),messages:g(Ke)}),"prompts/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:g(ut),nextCursor:o.optional()}),"resources/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:g(We),nextCursor:o.optional()}),"resources/templates/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:g(lt),nextCursor:o.optional()}),"resources/read":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:g(T([ke,ct]))}),"completion/complete":Me({completion:p({values:g(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":Me({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:g(c()),capabilities:Kr,instructions:c().optional()}),"subscriptions/listen":Me({})},_r=F({"io.modelcontextprotocol/subscriptionId":n.optional()}),oo=p({method:h("notifications/subscriptions/acknowledged"),params:p({_meta:_r.optional(),notifications:ro})}),no=p({_meta:_r.optional(),requestId:n,reason:c().optional()}),so=p({method:h("notifications/cancelled"),params:no}),Ac={"notifications/cancelled":so,"notifications/progress":Ee,"notifications/message":se,"notifications/resources/updated":Tt,"notifications/resources/list_changed":Ze,"notifications/tools/list_changed":dt,"notifications/prompts/list_changed":Re,"notifications/subscriptions/acknowledged":oo},Oe=(fe)=>p({jsonrpc:h("2.0"),id:T([c(),z().int()]),result:fe}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:n,RoleSchema:s,LoggingLevelSchema:i,TaskMetadataSchema:l,RelatedTaskMetadataSchema:u,RequestMetaSchema:d,BaseRequestParamsSchema:m,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:S,NotificationSchema:b,IconSchema:y,IconsSchema:v,BaseMetadataSchema:U,ImplementationSchema:H,ClientTasksCapabilitySchema:R,ServerTasksCapabilitySchema:w,ClientCapabilitiesSchema:D,ServerCapabilitiesSchema:X,ProgressSchema:Y,ProgressNotificationParamsSchema:ce,ProgressNotificationSchema:Ee,LoggingMessageNotificationParamsSchema:te,LoggingMessageNotificationSchema:se,ResourceContentsSchema:ve,TextResourceContentsSchema:ke,BlobResourceContentsSchema:ct,AnnotationsSchema:qe,ResourceSchema:We,ResourceTemplateSchema:lt,ResourceListChangedNotificationSchema:Ze,ResourceUpdatedNotificationParamsSchema:$e,ResourceUpdatedNotificationSchema:Tt,PromptArgumentSchema:Et,PromptSchema:ut,PromptListChangedNotificationSchema:Re,TextContentSchema:Ce,ImageContentSchema:Ie,AudioContentSchema:et,ToolUseContentSchema:lr,EmbeddedResourceSchema:De,ResourceLinkSchema:Fe,ContentBlockSchema:Ae,PromptMessageSchema:Ke,ToolAnnotationsSchema:Ge,ToolListChangedNotificationSchema:dt,ModelHintSchema:pt,ModelPreferencesSchema:Ht,ToolChoiceSchema:ht,BooleanSchemaSchema:ur,StringSchemaSchema:C,NumberSchemaSchema:mt,UntitledSingleSelectEnumSchemaSchema:V,TitledSingleSelectEnumSchemaSchema:q,LegacyTitledEnumSchemaSchema:G,SingleSelectEnumSchemaSchema:I,UntitledMultiSelectEnumSchemaSchema:k,TitledMultiSelectEnumSchemaSchema:B,MultiSelectEnumSchemaSchema:J,EnumSchemaSchema:ge,PrimitiveSchemaDefinitionSchema:dr,ElicitRequestFormParamsSchema:ft,ResourceTemplateReferenceSchema:pr,PromptReferenceSchema:hr,RootSchema:nn,ClientCapabilities2026Schema:sn,ServerCapabilities2026Schema:Kr,RequestMetaEnvelopeSchema:Gr,ToolSchema:mr,ToolResultContentSchema:an,SamplingMessageContentBlockSchema:Yr,SamplingMessageSchema:fr,ResultTypeSchema:Xr,ResultMetaSchema:Qr,ResultSchema:cn,PaginatedResultSchema:Gi,CallToolResultSchema:to,ListToolsResultSchema:ln,ListPromptsResultSchema:un,GetPromptResultSchema:dn,ListResourcesResultSchema:pn,ListResourceTemplatesResultSchema:hn,ReadResourceResultSchema:mn,CompleteResultSchema:fn,CacheableResultSchema:Yi,DiscoverResultSchema:gn,CreateMessageRequestParamsSchema:Jt,CreateMessageRequestSchema:Sn,ListRootsRequestSchema:_n,CreateMessageResultSchema:bn,ListRootsResultSchema:yn,ElicitResultSchema:vn,ElicitRequestURLParamsSchema:zn,ElicitRequestParamsSchema:wn,ElicitRequestSchema:Rn,InputRequestSchema:xn,InputResponseSchema:Pn,InputRequestsSchema:Tn,InputResponsesSchema:En,InputRequiredResultSchema:gr,InputResponseRequestParamsSchema:Xi,CallToolRequestSchema:ea,ListToolsRequestSchema:ta,ListPromptsRequestSchema:ra,GetPromptRequestSchema:oa,ListResourcesRequestSchema:na,ListResourceTemplatesRequestSchema:sa,ReadResourceRequestSchema:ia,CompleteRequestSchema:aa,DiscoverRequestSchema:ca,SubscriptionFilterSchema:ro,SubscriptionsListenRequestSchema:la,SubscriptionsListenResultMetaSchema:ua,SubscriptionsListenResultSchema:In,dispatchRequestSchemas:Bt,dispatchResultSchemas:da,NotificationMetaSchema:_r,SubscriptionsAcknowledgedNotificationSchema:oo,CancelledNotificationParamsSchema:no,CancelledNotificationSchema:so,notificationSchemas2026:Ac,JSONRPCResultResponseSchema:Oe(cn),CallToolResultResponseSchema:Oe(T([to,gr])),ListToolsResultResponseSchema:Oe(ln),ListPromptsResultResponseSchema:Oe(un),GetPromptResultResponseSchema:Oe(T([dn,gr])),ListResourcesResultResponseSchema:Oe(pn),ListResourceTemplatesResultResponseSchema:Oe(hn),ReadResourceResultResponseSchema:Oe(T([mn,gr])),CompleteResultResponseSchema:Oe(fn),DiscoverResultResponseSchema:Oe(gn),SubscriptionsListenResultResponseSchema:Oe(In)}}var Eb;function sr(){return Eb??=Tb()}var kb=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function $b(e){return kb.includes(e)}var uu=Symbol("modelcontextprotocol.resultCacheHintFallback");function Cb(e){return e[uu]}function Ff(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function Hf(e){return e==="public"||e==="private"}var W=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}({}),ee=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Be(this,t)}static isInstance(t){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,t)}constructor(t,r,o){super(r);this.code=t,this.data=o,this.name="ProtocolError",Zr(this,new.target)}static fromError(t,r,o){if(t===W.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new Jf(n.elicitations,r)}if(t===W.UnsupportedProtocolVersion&&o){let n=o;if(Array.isArray(n.supported)&&typeof n.requested==="string")return new gc({supported:n.supported,requested:n.requested},r)}if(t===W.InvalidParams||t===W.ResourceNotFound){let n=o;if(typeof n?.uri==="string"&&(t===W.ResourceNotFound||Object.keys(n).length===1))return new Vf(n.uri,r)}if(t===W.MissingRequiredClientCapability&&o){let n=o;if(n.requiredCapabilities!==null&&typeof n.requiredCapabilities==="object"&&!Array.isArray(n.requiredCapabilities))return new Bf({requiredCapabilities:n.requiredCapabilities},r)}return new e(t,r,o)}},Vf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(W.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Jf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(W.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},gc=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(W.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Bf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(W.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},Ib=0,Ob="private",Nb=["tools/call","prompts/get","resources/read"];function qb(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete")return t;if(Nb.includes(e))return t;throw new ee(W.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function Ab(e,t){let r=Cb(t);if(t.resultType!=="complete"||!$b(e))return r===void 0?t:Zb(t);let o=t,n=Ff(o.ttlMs)?o.ttlMs:Lb(r),s=Hf(o.cacheScope)?o.cacheScope:Ub(r),i={...o,ttlMs:n,cacheScope:s};return delete i[uu],i}function Mb(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function jb(e,t){if(t===void 0)return e;let r=e._meta;if(r===void 0)return{...e,_meta:{[Ot]:t}};if(!Mb(r))return e;if(r[Ot]!==void 0)return e;return{...e,_meta:{...r,[Ot]:t}}}function Lb(e){return e!==void 0&&Ff(e.ttlMs)?e.ttlMs:Ib}function Ub(e){return e!==void 0&&Hf(e.cacheScope)?e.cacheScope:Ob}function Zb(e){let t={...e};return delete t[uu],t}var Db=["elicitation/create","sampling/createMessage","roots/list"],pc;function Wf(){if(pc)return pc;let e=sr();return pc={request:{"elicitation/create":p({method:h("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":p({method:h("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":p({method:h("roots/list"),params:F({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},pc}function Kf(e){return Db.includes(e)}function Gl(e){return Kf(e)?Wf().request[e]:void 0}function Fb(e){return Kf(e)?Wf().response[e]:void 0}var du={"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},Gf={"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 Yf(e){return Object.prototype.hasOwnProperty.call(du,e)}function Xf(e){return Object.prototype.hasOwnProperty.call(Gf,e)}function Hb(e){return Object.prototype.hasOwnProperty.call(du,e)}function Vb(e){return Yf(e)?sr().dispatchRequestSchemas[e]:void 0}function Jb(e){return Hb(e)?sr().dispatchResultSchemas[e]:void 0}function Bb(e){return Xf(e)?sr().notificationSchemas2026[e]:void 0}var Cx=Object.keys(du),Ix=Object.keys(Gf);function $i(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Ei(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var Wb={ok:!1,reason:"not-in-era"},Kb=[It,Pr];function Gb(e,t){let r=t,o=!1,n=()=>{if(!o)r={...r},o=!0;return r},s=t.tools;if(e==="tools/list"&&Array.isArray(s)&&s.some((a)=>$i(a)&&("execution"in a)))n().tools=s.map((a)=>{if(!$i(a)||!("execution"in a))return a;let l={...a};return delete l.execution,l});let i=t.capabilities;if($i(i)&&"tasks"in i){let a={...i};delete a.tasks,n().capabilities=a}return r}var pu={era:"2026-07-28",hasRequestMethod:Yf,hasNotificationMethod:Xf,hasInputRequestMethod:(e)=>Gl(e)!==void 0,validateRequest:(e,t)=>Ei(Vb(e),t),validateResult:(e,t)=>Ei(Jb(e),t),validateNotification:(e,t)=>Ei(Bb(e),t),validateInputRequest:(e,t)=>Ei(Gl(e),t),validateInputResponse:(e,t)=>Ei(Fb(e),t),samplingResultVariant:()=>Wb,outboundEnvelope(e){return{[It]:e.protocolVersion,[mo]:e.clientInfo,[Pr]:e.clientCapabilities,...e.logLevel!==void 0&&{[fo]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of Kb)if(!(o in e))t.push({key:o,problem:"missing"});let r=sr().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let n=o.path.map(String),s=n.length>0?n.join("."):"_meta";if(n.length===1&&t.some((i)=>i.key===s&&i.problem==="missing"))continue;t.push({key:s,problem:o.message})}return t},projectCallToolResult:(e)=>qf(e),inputRequestSchema:Gl,decodeResult(e,t){if(!$i(t))return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new N(O.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 r!=="string")return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let i=t.inputRequests,a=$i(i)?i:{},l=t.requestState,u=t._meta===void 0?void 0:sr().ResultMetaSchema.safeParse(t._meta),d=u?.success?u.data:void 0;if(Object.keys(a).length===0&&typeof l!=="string")return{kind:"invalid",error:new N(O.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"})};return{kind:"input_required",inputRequests:a,...typeof l==="string"&&{requestState:l},...d!==void 0&&{_meta:d}}}if(r!=="complete")return{kind:"invalid",error:new N(O.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=Yb(),n=Object.hasOwn(o,e)?o[e]:void 0;if(n!==void 0){let i=n.safeParse(t);if(!i.success)return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: ${i.error}`,{method:e})}}let s={...t};return delete s.resultType,{kind:"complete",result:s}},encodeResult(e,t,r){return jb(Ab(e,qb(e,Gb(e,t))),r)},encodeErrorCode:(e)=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=sr().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map((r)=>r.message).join("; ")}`}},hc;function Yb(){if(hc)return hc;let e=sr();return hc={"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},hc}var Sc="2026-07-28";function Lt(e){return e!==void 0&&Zt(e)?pu:lu}function zf(e){if(e.revision!==void 0)return Lt(e.revision).era;return e.era==="modern"?pu.era:lu.era}function Yl(e){return Qf.some((t)=>t.hasRequestMethod(e))}function Xl(e){return Qf.some((t)=>t.hasNotificationMethod(e))}function wf(e){return e==="tasks/get"||e==="tasks/cancel"}var Qf=[lu,pu],Xb=sd({AnnotationsSchema:()=>bt,AudioContentSchema:()=>Or,BaseMetadataSchema:()=>St,BaseRequestParamsSchema:()=>ye,BlobResourceContentsSchema:()=>$o,BooleanSchemaSchema:()=>No,CallToolRequestParamsSchema:()=>Zs,CallToolRequestSchema:()=>Ds,CallToolResultSchema:()=>nr,CancelTaskRequestSchema:()=>ec,CancelTaskResultSchema:()=>tc,CancelledNotificationParamsSchema:()=>Yn,CancelledNotificationSchema:()=>zo,ClientCapabilitiesSchema:()=>Qn,ClientNotificationSchema:()=>oc,ClientRequestSchema:()=>rc,ClientResultSchema:()=>nc,ClientTasksCapabilitySchema:()=>Da,CompatibilityCallToolResultSchema:()=>Ha,CompleteRequestParamsSchema:()=>fi,CompleteRequestSchema:()=>gi,CompleteResultSchema:()=>Si,ContentBlockSchema:()=>yt,CreateMessageRequestParamsSchema:()=>ei,CreateMessageRequestSchema:()=>ti,CreateMessageResultSchema:()=>ri,CreateMessageResultWithToolsSchema:()=>oi,CreateTaskResultSchema:()=>Ja,CursorSchema:()=>So,DiscoverRequestSchema:()=>rs,DiscoverResultSchema:()=>rr,ElicitRequestFormParamsSchema:()=>Lr,ElicitRequestParamsSchema:()=>ci,ElicitRequestSchema:()=>li,ElicitRequestURLParamsSchema:()=>ai,ElicitResultSchema:()=>pi,ElicitationCompleteNotificationParamsSchema:()=>ui,ElicitationCompleteNotificationSchema:()=>di,EmbeddedResourceSchema:()=>Nr,EmptyResultSchema:()=>tr,EnumSchemaSchema:()=>ii,GetPromptRequestParamsSchema:()=>Cs,GetPromptRequestSchema:()=>Is,GetPromptResultSchema:()=>qs,GetTaskPayloadRequestSchema:()=>Ga,GetTaskPayloadResultSchema:()=>Ya,GetTaskRequestSchema:()=>Wa,GetTaskResultSchema:()=>Ka,IconSchema:()=>Xn,IconsSchema:()=>Nt,ImageContentSchema:()=>Ir,ImplementationSchema:()=>_t,InitializeRequestParamsSchema:()=>es,InitializeRequestSchema:()=>wo,InitializeResultSchema:()=>ts,InitializedNotificationSchema:()=>xo,JSONArraySchema:()=>Ua,JSONObjectSchema:()=>le,JSONRPCErrorResponseSchema:()=>kr,JSONRPCMessageSchema:()=>st,JSONRPCNotificationSchema:()=>vo,JSONRPCRequestSchema:()=>yo,JSONRPCResponseSchema:()=>Za,JSONRPCResultResponseSchema:()=>Er,JSONValueSchema:()=>Ct,LegacyTitledEnumSchemaSchema:()=>Mo,ListChangedOptionsBaseSchema:()=>Hs,ListPromptsRequestSchema:()=>ks,ListPromptsResultSchema:()=>$s,ListResourceTemplatesRequestSchema:()=>ls,ListResourceTemplatesResultSchema:()=>us,ListResourcesRequestSchema:()=>as,ListResourcesResultSchema:()=>cs,ListRootsRequestSchema:()=>bi,ListRootsResultSchema:()=>yi,ListTasksRequestSchema:()=>Xa,ListTasksResultSchema:()=>Qa,ListToolsRequestSchema:()=>Ls,ListToolsResultSchema:()=>Us,LoggingLevelSchema:()=>Oo,LoggingMessageNotificationParamsSchema:()=>Bs,LoggingMessageNotificationSchema:()=>Ar,ModelHintSchema:()=>Ws,ModelPreferencesSchema:()=>Ks,MultiSelectEnumSchemaSchema:()=>si,NotificationSchema:()=>we,NotificationsParamsSchema:()=>Te,NumberSchemaSchema:()=>jr,PaginatedRequestParamsSchema:()=>ss,PaginatedRequestSchema:()=>qt,PaginatedResultSchema:()=>At,PingRequestSchema:()=>Po,PrimitiveSchemaDefinitionSchema:()=>Uo,ProgressNotificationParamsSchema:()=>ns,ProgressNotificationSchema:()=>To,ProgressSchema:()=>os,ProgressTokenSchema:()=>go,PromptArgumentSchema:()=>Ts,PromptListChangedNotificationSchema:()=>As,PromptMessageSchema:()=>Ns,PromptReferenceSchema:()=>mi,PromptSchema:()=>Es,ReadResourceRequestParamsSchema:()=>ds,ReadResourceRequestSchema:()=>ps,ReadResourceResultSchema:()=>hs,RelatedTaskMetadataSchema:()=>Gn,RequestIdSchema:()=>nt,RequestMetaSchema:()=>_o,RequestSchema:()=>ue,ResourceContentsSchema:()=>Eo,ResourceLinkSchema:()=>qr,ResourceListChangedNotificationSchema:()=>ms,ResourceRequestParamsSchema:()=>$r,ResourceSchema:()=>Co,ResourceTemplateReferenceSchema:()=>hi,ResourceTemplateSchema:()=>is,ResourceUpdatedNotificationParamsSchema:()=>xs,ResourceUpdatedNotificationSchema:()=>Ps,ResultMetaObjectSchema:()=>bo,ResultSchema:()=>de,RoleSchema:()=>Mt,RootSchema:()=>_i,RootsListChangedNotificationSchema:()=>vi,SamplingContentSchema:()=>Xs,SamplingMessageContentBlockSchema:()=>Qt,SamplingMessageSchema:()=>Qs,ServerCapabilitiesSchema:()=>Ro,ServerNotificationSchema:()=>ic,ServerRequestSchema:()=>sc,ServerResultSchema:()=>ac,ServerTasksCapabilitySchema:()=>Fa,SetLevelRequestParamsSchema:()=>Vs,SetLevelRequestSchema:()=>Js,SingleSelectEnumSchemaSchema:()=>ni,StringSchemaSchema:()=>Mr,SubscribeRequestParamsSchema:()=>fs,SubscribeRequestSchema:()=>gs,SubscriptionFilterSchema:()=>Io,SubscriptionsAcknowledgedNotificationParamsSchema:()=>vs,SubscriptionsAcknowledgedNotificationSchema:()=>zs,SubscriptionsListenRequestParamsSchema:()=>bs,SubscriptionsListenRequestSchema:()=>ys,SubscriptionsListenResultMetaSchema:()=>ws,SubscriptionsListenResultSchema:()=>Rs,TaskAugmentedRequestParamsSchema:()=>er,TaskCreationParamsSchema:()=>Va,TaskMetadataSchema:()=>Kn,TaskSchema:()=>jt,TaskStatusNotificationParamsSchema:()=>wi,TaskStatusNotificationSchema:()=>Ba,TaskStatusSchema:()=>zi,TextContentSchema:()=>Cr,TextResourceContentsSchema:()=>ko,TitledMultiSelectEnumSchemaSchema:()=>Lo,TitledSingleSelectEnumSchemaSchema:()=>Ao,ToolAnnotationsSchema:()=>Ms,ToolChoiceSchema:()=>Gs,ToolExecutionSchema:()=>js,ToolListChangedNotificationSchema:()=>Fs,ToolResultContentSchema:()=>Ys,ToolSchema:()=>or,ToolUseContentSchema:()=>Os,UnsubscribeRequestParamsSchema:()=>Ss,UnsubscribeRequestSchema:()=>_s,UntitledMultiSelectEnumSchemaSchema:()=>jo,UntitledSingleSelectEnumSchemaSchema:()=>qo});var Fr=(e)=>yo.safeParse(e).success,eg=(e)=>vo.safeParse(e).success,Bo=(e)=>Er.safeParse(e).success,Wo=(e)=>kr.safeParse(e).success;var tg=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var hu=(e)=>wo.safeParse(e).success,rg=(e)=>xo.safeParse(e).success;var Qb="Mcp-Param-",Rf="x-mcp-header",ey=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,ty=new Set(["string","integer","boolean","number"]);function mu(e){let t=[],r=new Map,o=(s,i,a)=>{if(s===null||typeof s!=="object")return;let l=s;if(Rf in l){if(!a||i.length===0)return`${mc(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let d=l[Rf];if(typeof d!=="string"||d.length===0)return`${mc(i)}: x-mcp-header MUST be a non-empty string`;if(!ey.test(d))return`${mc(i)}: x-mcp-header '${d}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let m=typeof l.type==="string"?l.type:void 0;if(m===void 0||!ty.has(m))return`${mc(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${m??"<none>"}`;let f=d.toLowerCase(),S=r.get(f);if(S!==void 0)return`x-mcp-header '${d}' is not case-insensitively unique (also declared as '${S}')`;r.set(f,d),t.push({path:i,headerName:d,type:m})}let u=l.properties;if(u!==null&&typeof u==="object")for(let[d,m]of Object.entries(u)){let f=o(m,[...i,d],a);if(f!==void 0)return f}for(let d of ry){let m=l[d];if(m===void 0)continue;let f=Array.isArray(m)?m:m!==null&&typeof m==="object"&&oy.has(d)?Object.values(m):[m];for(let S of f){let b=o(S,[...i,`<${d}>`],!1);if(b!==void 0)return b}}},n=o(e,[],!0);return n===void 0?{valid:!0,declarations:t}:{valid:!1,reason:n}}var ry=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],oy=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function mc(e){return e.length===0?"<root>":e.join(".")}var og="=?base64?",ng="?=";function ny(e){if(typeof e==="string")return e;if(typeof e==="boolean")return e?"true":"false";if(typeof e==="number"){if(!Number.isFinite(e))return;if(Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}function sy(e){if(e.length===0)return!0;if(e.startsWith(og)&&e.endsWith(ng))return!0;if(e!==e.trim())return!0;for(let t=0;t<e.length;t++){let r=e.codePointAt(t);if(r===9||r>=32&&r<=126)continue;return!0}return!1}function iy(e){let t=new TextEncoder().encode(e),r="";for(let o of t)r+=String.fromCodePoint(o);return btoa(r)}function fu(e){return sy(e)?`${og}${iy(e)}${ng}`:e}function ay(e,t){let r=e;for(let o of t){if(r===null||typeof r!=="object")return;r=r[o]}return r}function sg(e,t){let r={};for(let o of e){let n=ay(t,o.path);if(n===void 0||n===null)continue;let s=ny(n);if(s===void 0)continue;r[`${Qb}${o.headerName}`]=fu(s)}return r}var Jo=-32020,Ox=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32000],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[W.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Jo,W.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[W.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[W.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[W.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Jo],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half — including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[W.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Jo],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],Nx={[W.ParseError]:400,[W.InvalidRequest]:400,[W.MethodNotFound]:404,[W.UnsupportedProtocolVersion]:400,[W.MissingRequiredClientCapability]:400,[Jo]:400},xf={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function ig(e,t){let r=Object.hasOwn(xf,e)?xf[e]:void 0;if(r===void 0)return;let o=cy(t)?t[r]:void 0;return{field:r,value:typeof o==="string"?o:void 0}}function cy(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function _c(e,t){return Oa(e,t)}function ki(e){return new Set(e.flatMap((t)=>Object.keys(t.shape)))}function ru(e){if(e==null)return!1;let t=typeof e;if(t!=="object"&&t!=="function")return!1;if(!("~standard"in e))return!1;return typeof e["~standard"]?.validate==="function"}var Pf=!1,ou="draft-2020-12";function ly(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:ou});else if(r.vendor==="zod"){if(!("_zod"in e))throw 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().");if(!Pf)Pf=!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.");o=Ca(e,{target:ou,io:t})}else throw Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output"){if(o.type!==void 0)return o;return ag(o)?{type:"object",...o}:o}if(o.type!==void 0&&o.type!=="object")throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}function ag(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every((o)=>o!==null&&typeof o==="object"&&(o.type==="object"||ag(o)))}return!1}function uy(e){if(!e.path?.length)return e.message;return`${e.path.map((t)=>String(typeof t==="object"?t.key:t)).join(".")}: ${e.message}`}async function Ql(e,t){let r=await e["~standard"].validate(t);if(r.issues&&r.issues.length>0)return{success:!1,error:r.issues.map((o)=>uy(o)).join(", ")};return{success:!0,data:r.value}}function dy(e){let t=Ca(e,{target:ou,io:"input"});return typeof t.pattern==="string"?t.pattern:void 0}var py=/\\\.\\d\{(\d+)\}/;function hy(e){let t=py.exec(e),r=[void 0,-1,0];if(t)r.push(Number(t[1]));return[!1,!0].flatMap((o)=>[!1,!0].flatMap((n)=>r.map((s)=>uo({local:o,offset:n,precision:s}))))}function my(e,t){let r;switch(e){case"email":r=[Km()];break;case"uri":r=[qa()];break;case"date":r=[Hl()];break;case"date-time":r=hy(t);break}return new Set(r.map((o)=>dy(o)).filter((o)=>o!==void 0))}function fy(e,t,r){if(r!=="zod")return!0;return my(e,t).has(t)}function Ii(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function gy(e){try{return ly(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new ee(W.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}var Sy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function gu(e){return Sy.has(e)||e.startsWith("x-")}var _y=new Set(["$schema",...Object.keys(Lr.shape.requestedSchema.shape)]),Tf={string:ki([Mr,qo,Ao,Mo]),number:ki([jr]),integer:ki([jr]),boolean:ki([No]),array:ki([jo,Lo])},by=new Set(Mr.shape.format.unwrap().options);function yy(e,t,r,o){if(!Ii(e))return e;let n=typeof e.type==="string"&&Object.hasOwn(Tf,e.type)?Tf[e.type]:void 0;if(n===void 0)return e;let s={};for(let[i,a]of Object.entries(e))if(n.has(i)||gu(i))s[i]=a;else if(i==="pattern"&&e.type==="string"&&typeof e.format==="string"){if(!by.has(e.format))s[i]=a;else if(typeof a!=="string"||!fy(e.format,a,r))o.push(`${t}.${i}`)}else o.push(`${t}.${i}`);return s}function vy(e,t){let r={},o=[];for(let[n,s]of Object.entries(e))if(n==="properties"&&Ii(s))r[n]=Object.fromEntries(Object.entries(s).map(([i,a])=>[i,yy(a,`properties.${i}`,t,o)]));else if(_y.has(n))r[n]=s;else if(!gu(n))o.push(n);if(o.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}function zy(e,t){if(!Ii(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!_c(Uo,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}function nu(e,t,r=""){if(Array.isArray(e)&&Array.isArray(t))return e.flatMap((o,n)=>nu(o,t[n],`${r}[${n}]`));if(!Ii(e)||!Ii(t))return[];return Object.entries(e).flatMap(([o,n])=>{let s=r?`${r}.${o}`:o;if(!Object.prototype.hasOwnProperty.call(t,o))return gu(o)?[]:[s];return nu(n,t[o],s)})}function wy(e){if(!ru(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=vy(gy(e.requestedSchema),t),o=_c(Lr.shape.requestedSchema,r);if(!o.success)throw new ee(W.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${zy(r,o.error.message)}`);let n=nu(r,o.data);if(n.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);let s=(o.data.required??[]).filter((i)=>!Object.prototype.hasOwnProperty.call(o.data.properties,i));if(s.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function Ry(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState==="string";if(!t&&!r)throw TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}var qx=Object.assign(Ry,{elicit(e){try{return{method:"elicitation/create",params:wy(e)}}catch(t){throw t instanceof ee?TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var xy=!0,Py=10,Ty=250;function cg(e){return{autoFulfill:e?.autoFulfill??xy,maxRounds:e?.maxRounds??Py}}function Ey(e,t,r){let o=t!==void 0&&Object.keys(t).length>0;if(!o&&r===void 0)return e;return{...e,...o&&{inputResponses:t},...r!==void 0&&{requestState:r}}}function ky(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function $y(e,t){return new Promise((r,o)=>{if(t?.aborted){o(t.reason instanceof N?t.reason:new N(O.RequestTimeout,String(t.reason)));return}let n=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),s=()=>{clearTimeout(n),o(t?.reason instanceof N?t.reason:new N(O.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",s,{once:!0})})}function Cy(e){let t=new AbortController,r=()=>t.abort(e?.reason);if(e?.addEventListener("abort",r,{once:!0}),e?.aborted)t.abort(e.reason);return{signal:t.signal,abort:(o)=>t.abort(o),dispose:()=>e?.removeEventListener("abort",r)}}async function Iy(e){let{config:t,method:r,originalParams:o,requestOptions:n,hooks:s,signal:i}=e,a=e.flowStartedAt??Date.now(),l=e.firstPayload,u=0;while(!0){if(u+=1,u>t.maxRounds)throw new N(O.InputRequiredRoundsExceeded,ky(r,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:l.inputRequests,...l.requestState!==void 0&&{requestState:l.requestState}}});n.onprogress?.({progress:u,message:`Fulfilling input required by '${r}' (round ${u})`});let d=Object.entries(l.inputRequests??{}),m;if(d.length>0){let b=Cy(i);try{let y=await Promise.all(d.map(async([v,U])=>{try{return[v,await s.dispatchInputRequest(v,U,b.signal)]}catch(H){throw b.abort(H),H}}));m=Object.fromEntries(y)}finally{b.dispose()}}else await $y(Ty,i);let f={...n.timeout!==void 0&&{timeout:n.timeout}};if(n.maxTotalTimeout!==void 0){let b=Date.now()-a,y=n.maxTotalTimeout-b;if(y<=0)throw new N(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:b});f.maxTotalTimeout=y}let S=await s.retry(Ey(o,m,l.requestState),f);if(tg(S)){l={inputRequests:S.inputRequests??{},...S.requestState!==void 0&&{requestState:S.requestState}};continue}return S}}var Oy=["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"],Ny={IdJagTokenExchangeResponseSchema:xi,OAuthClientInformationFullSchema:Vo,OAuthClientInformationSchema:Ti,OAuthClientMetadataSchema:Pi,OAuthClientRegistrationErrorSchema:cc,OAuthErrorResponseSchema:Ho,OAuthMetadataSchema:Ur,OAuthProtectedResourceMetadataSchema:Zo,OAuthTokenRevocationRequestSchema:lc,OAuthTokensSchema:Fo,OpenIdProviderDiscoveryMetadataSchema:Do,OpenIdProviderMetadataSchema:Ri},lg={},ug={};function dg(e,t){let r=e.slice(0,-6);lg[r]=t,ug[r]=(o)=>t.safeParse(o).success}for(let e of Oy)dg(e,Xb[e]);for(let[e,t]of Object.entries(Ny))dg(e,t);var qy=Object.freeze(lg),pg=Object.freeze(ug);function Ay(e){switch(e){case"initialize":case"notifications/initialized":return Lt(void 0);case"server/discover":return Lt(Sc);default:return}}var bc=60000,My=[It,mo,Pr,fo],jy=["inputResponses","requestState"];function Ef(e,t){let r=e.params;if(!Ci(r))return{message:e,lifted:{}};let o=r._meta,n=Ci(o)?My.filter((l)=>(l in o)):[],s=t==="request"?jy.filter((l)=>(l in r)):[];if(n.length===0&&s.length===0)return{message:e,lifted:{}};let i={},a={...r};if(n.length>0&&Ci(o)){let l={},u={...o};for(let d of n)l[d]=o[d],delete u[d];if(i.envelope=l,Object.keys(u).length>0)a._meta=u;else delete a._meta}for(let l of s){if(l==="inputResponses")i.inputResponses=a[l];if(l==="requestState")i.requestState=a[l];delete a[l]}return{message:{...e,params:a},lifted:i}}function kf(e,t){let r=e.validateResult(t,void 0);if(!r.ok&&r.reason==="not-in-era")return;return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let n=e.validateResult(t,o);if(n.ok)return{value:n.value};return{issues:[{message:n.reason==="invalid"?n.message:`not-in-era: ${t}`}]}}}}}function Su(e){return()=>e}var Ly=Su(void 0),Uy,yc=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{Uy=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??ja,this.setNotificationHandler("notifications/cancelled",(t)=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",(t)=>{this._onprogress(t)}),this.setRequestHandler("ping",(t)=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new N(O.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){if(e.params.requestId===void 0)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new N(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=(n)=>{r?.(n),this._onerror(n)};let o=this._transport?.onmessage;this._transport.onmessage=(n,s)=>{if(o?.(n,s),Bo(n)||Wo(n))this._onresponse(n);else if(Fr(n))this._onrequest(n,s);else if(eg(n))this._onnotification(n,s);else this._onerror(Error(`Unknown message type: ${JSON.stringify(n)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new N(O.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(r);for(let o of t.values())o.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=Ef(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let i=zf(t.classification);if(i!==o.era){this._onerror(Error(`Era mismatch on inbound notification '${r.method}': classified as ${i} but this instance serves ${o.era}`));return}}if(Xl(r.method)&&!o.hasNotificationMethod(r.method))return;let n=this._notificationHandlers.get(r.method),s=this.fallbackNotificationHandler;if(n===void 0&&s===void 0)return;Promise.resolve().then(()=>n===void 0?s(r):n(r,o)).catch((i)=>this._onerror(Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,t){let{message:r,lifted:o}=Ef(e,"request"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let s=this._transport,i=(y,v,U)=>{let H={jsonrpc:"2.0",id:r.id,error:{code:y,message:v,...U!==void 0&&{data:U}}};s?.send(H).catch((x)=>this._onerror(Error(`Failed to send an error response: ${x}`)))};if(t?.classification!==void 0){let y=zf(t.classification);if(y!==n.era){this._onerror(Error(`Era mismatch on inbound request '${r.method}': classified as ${y} but this instance serves ${n.era}`));let v=t.classification.revision??y;i(W.UnsupportedProtocolVersion,`Unsupported protocol version: ${v}`,{supported:this._supportedProtocolVersions,requested:v});return}}if(Yl(r.method)&&!n.hasRequestMethod(r.method)&&!(wf(r.method)&&this._customSchemaRequestMethods.has(r.method))){i(W.MethodNotFound,"Method not found");return}let a=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(a===void 0){i(W.MethodNotFound,"Method not found");return}let l=n.checkInboundEnvelope(o);if(l!==void 0){i(W.InvalidParams,l);return}let u=(y,v)=>this._notificationViaCodec(this._resolveOutboundCodec(y.method),y,{...v,relatedRequestId:r.id}),d=(y,v,U)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(y.method),y,v,{...U,relatedRequestId:r.id}),m=new AbortController;this._requestHandlerAbortControllers.set(r.id,m);let f=o.inputResponses===void 0?void 0:Zy(o.inputResponses),S={sessionId:s?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:o.requestState===void 0?Ly:Su(o.requestState),signal:m.signal,send:(y,v,U)=>{let H=this._resolveOutboundCodec(y.method);if(this._assertOutboundRequestInEra(H,y.method),ru(v))return d(y,v,U);let x=kf(H,y.method);if(x===void 0)throw TypeError(`'${y.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return d(y,x,v)},notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},b=this.buildContext(S,t);Promise.resolve().then(()=>a(r,b)).then(async(y)=>{if(m.signal.aborted)return;let v;try{v=n.encodeResult(r.method,y,this._outboundServerInfo())}catch(H){this._onerror(Error(`Failed to encode result for ${r.method}: ${H}`)),i(W.InternalError,"Internal error");return}let U={result:v,jsonrpc:"2.0",id:r.id};await s?.send(U)},async(y)=>{if(m.signal.aborted)return;let v=Number.isSafeInteger(y.code)?y.code:W.InternalError,U={jsonrpc:"2.0",id:r.id,error:{code:n.encodeErrorCode(v),message:y.message??"Internal error",...y.data!==void 0&&{data:y.data}}};await s?.send(U)}).catch((y)=>this._onerror(Error(`Failed to send response: ${y}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(r.id)===m)this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),n=this._progressHandlers.get(o);if(!n){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(a);return}n(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Bo(e))r(e);else r(ee.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let o=this._resolveOutboundCodec(e.method);if(ru(t)){if(!wf(e.method))this._assertOutboundRequestInEra(o,e.method);return this._requestWithSchemaViaCodec(o,e,t,r)}this._assertOutboundRequestInEra(o,e.method);let n=kf(o,e.method);if(n===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(o,e,n,t)}_negotiatedWireCodec(){return Lt(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Ay(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Yl(t)&&!e.hasRequestMethod(t))throw new N(O.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r)}_requestWithSchemaViaCodec(e,t,r,o){let{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,headers:a}=o??{},l=Date.now(),u,d;return new Promise((m,f)=>{let S=(w)=>{f(w)};if(!this._transport){S(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(w){S(w);return}if(o?.signal?.aborted){let w=o.signal.reason;throw w instanceof N?w:new N(O.RequestTimeout,String(w))}let b=e.era===Sc&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,y=this._requestMessageId++;d=y;let v={...t,jsonrpc:"2.0",id:y};if(o?.onprogress)this._progressHandlers.set(y,o.onprogress),v.params={...t.params,_meta:{...t.params?._meta,progressToken:y}};let U=this._envelopeOutbound(v),H=!1,x=(w)=>{if(H)return;if(this._progressHandlers.delete(y),b===void 0){if(t.method!=="initialize")this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:y,reason:String(w)}}),{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch((D)=>this._onerror(Error(`Failed to send cancellation: ${D}`)))}else b.abort();f(w instanceof N?w:new N(O.RequestTimeout,String(w)))};this._responseHandlers.set(y,(w)=>{if(o?.signal?.aborted)return;if(H=!0,w instanceof Error)return f(w);let D;try{D=e.decodeResult(t.method,w.result)}catch(Y){return f(Y instanceof Error?Y:Error(String(Y)))}if(D.kind==="invalid")return f(D.error);if(D.kind==="input_required"){if(o?.allowInputRequired===!0)return m(Vy(D));let Y={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:l,retry:(ce,Ee)=>this._requestWithSchemaViaCodec(e,ce===void 0?{method:t.method}:{method:t.method,params:ce},r,Ee)};return m(this._resolveNonCompleteResult(D,Y))}let X=D.result;Ql(r,X).then((Y)=>{if(Y.success)m(Y.data);else f(new N(O.InvalidResult,`Invalid result for ${t.method}: ${Y.error}`))},f)}),u=()=>x(o?.signal?.reason),o?.signal?.addEventListener("abort",u,{once:!0});let Z=o?.timeout??bc,R=()=>x(new N(O.RequestTimeout,"Request timed out",{timeout:Z}));this._setupTimeout(y,Z,o?.maxTotalTimeout,R,o?.resetTimeoutOnProgress??!1),this._transport.send(U,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,headers:a,requestSignal:b?.signal}).catch((w)=>{this._progressHandlers.delete(y),f(w)})}).finally(()=>{if(u)o?.signal?.removeEventListener("abort",u);if(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,r){if(!this._transport)throw new N(O.NotConnected,"Not connected");if(Xl(t.method)&&!e.hasNotificationMethod(t.method))throw new N(O.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;this._transport?.send(o,r).catch((n)=>this._onerror(n))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t==="function"){if(!Yl(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=(n,s)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason==="not-in-era")a=i.validateInputRequest(e,n);if(!a.ok){if(a.reason==="not-in-era")throw new ee(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(a.message)}return Promise.resolve(t(a.value,s))}}else if(r)o=async(n,s)=>{let i=await Ql(t.params,{...n.params});if(!i.success)throw new ee(W.InvalidParams,`Invalid params for ${e}: ${i.error}`);return r(i.data,s)};else throw TypeError("setRequestHandler: handler is required");if(typeof t==="function")this._customSchemaRequestMethods.delete(e);else this._customSchemaRequestMethods.add(e);this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t==="function"){if(!Xl(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,n)=>{let s=n.validateNotification(e,o);if(!s.ok){if(s.reason==="not-in-era")throw new ee(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(s.message)}return Promise.resolve(t(s.value))});return}if(!r)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async(o)=>{let n=await Ql(t.params,{...o.params});if(!n.success)throw new ee(W.InvalidParams,`Invalid params for notification ${e}: ${n.error}`);await r(n.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Ci(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function hg(e,t){let r={...e};for(let o in t){let n=o,s=t[n];if(s===void 0)continue;let i=r[n];r[n]=Ci(i)&&Ci(s)?{...i,...s}:s}return r}function fc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Zy(e){let t={},r=[];if(!fc(e))return{accepted:t,droppedKeys:r};for(let[o,n]of Object.entries(e)){if(!fc(n)||"method"in n||"result"in n){r.push(o);continue}t[o]=n}return{accepted:t,droppedKeys:r}}function $f(e){throw new N(O.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 Dy(e,t,r,o,n){return{sessionId:n,mcpReq:{id:e,method:t,_meta:r?._meta,requestState:Su(void 0),signal:o,send:()=>$f("send"),notify:()=>$f("notify")}}}async function Fy(e,t,r,o,n){if(!fc(o)||typeof o.method!=="string")throw new N(O.InvalidResult,`Invalid input request '${r}': each inputRequests entry must be an embedded request object with a method`,{key:r});let s=o.method;if(!t.hasInputRequestMethod(s))throw new N(O.InvalidResult,`Invalid input request '${r}': '${s}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:r,method:s});let i=e.getRequestHandler(s);if(i===void 0)throw new N(O.CapabilityNotSupported,`Cannot fulfil input request '${r}': no handler is registered for '${s}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:r,method:s});let a=fc(o.params)?o.params:void 0;return await i({jsonrpc:"2.0",id:r,method:s,...a!==void 0&&{params:a}},e.buildContext(Dy(r,s,a,n,e.sessionId)))}function Hy(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 mg(e,t,r,o){let{codec:n,request:s,options:i,flowStartedAt:a}=o,l={inputRequests:r.inputRequests,...r.requestState!==void 0&&{requestState:r.requestState}},u={dispatchInputRequest:(d,m,f)=>Fy(e,n,d,m,f),retry:(d,m)=>o.retry(d,Hy(i,m))};return Iy({config:t,method:s.method,originalParams:s.params,firstPayload:l,flowStartedAt:a,signal:i?.signal,requestOptions:{...i?.timeout!==void 0&&{timeout:i.timeout},...i?.maxTotalTimeout!==void 0&&{maxTotalTimeout:i.maxTotalTimeout},...i?.onprogress!==void 0&&{onprogress:i.onprogress}},hooks:u})}function Vy(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}/*!
65
66
  * content-type
66
67
  * Copyright(c) 2015 Douglas Christopher Wilson
67
68
  * MIT Licensed
68
- */var Hy=rd((e)=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=n;function n(a){if(!a)throw TypeError("argument string is required");var l=typeof a==="object"?s(a):a;if(typeof l!=="string")throw TypeError("argument string is required to be a string");var u=l.indexOf(";"),d=u!==-1?l.slice(0,u).trim():l.trim();if(!o.test(d))throw TypeError("invalid media type");var m=new i(d.toLowerCase());if(u!==-1){var f,S,b;t.lastIndex=u;while(S=t.exec(l)){if(S.index!==u)throw TypeError("invalid parameter format");if(u+=S[0].length,f=S[1].toLowerCase(),b=S[2],b.charCodeAt(0)===34){if(b=b.slice(1,-1),b.indexOf("\\")!==-1)b=b.replace(r,"$1")}m.parameters[f]=b}if(u!==l.length)throw TypeError("invalid parameter format")}return m}function s(a){var l;if(typeof a.getHeader==="function")l=a.getHeader("content-type");else if(typeof a.headers==="object")l=a.headers&&a.headers["content-type"];if(typeof l!=="string")throw TypeError("content-type header is missing from object");return l}function i(a){this.parameters=Object.create(null),this.type=a}}),Vy=nd(Hy(),1);function hg(e){if(!e)return;try{return Vy.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();if(t===""||e.slice(t.length).includes(","))return;return t}}function kf(e){if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Array.isArray(e))return Object.fromEntries(e);return{...e}}function mg(e=fetch,t){if(!t)return e;return async(r,o)=>e(r,{...t,...o,headers:o?.headers?{...kf(t.headers),...kf(o.headers)}:t.headers})}var Jy=new Set([301,302,303,307,308]),By=5;function Wy(e,t){if(e.protocol===t.protocol&&e.host===t.host)return!0;return e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}function fg(e,t){let r=Jy.has(t.status)?t.headers?.get("location"):void 0;if(!r)return;try{return new URL(r,e)}catch{return}}var gg=new WeakSet;function Sg(e){let t=(r,o)=>e(r,o);return gg.add(t),t}function Ni(e){if(gg.has(e))return e;return async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let o=(r?.method??"GET").toUpperCase(),n=t;for(let s=0;;s++){let i=await e(n,{...r,redirect:"manual"}),a=fg(n,i);if(!a||s===By)return i;let l=new URL(n),u=o==="GET"||i.status===307||i.status===308,d=!(a.username||a.password)||a.username===l.username&&a.password===l.password;if(!u||!d||!Wy(l,a))return i;await i.text?.().catch(()=>{}),n=a}}}function _g(e,t){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";let r=fg(t.url||e,t);if(!r)return;if(r.username=r.password=r.search=r.hash="",r.protocol==="http:"&&new URL(t.url||e).protocol==="https:")return r.protocol="https:",`Redirect from https to plain http not followed; try ${r.href} as the endpoint`;return`Redirect to ${r.href} not followed; use that URL as the endpoint if it is the intended server`}function qi(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let o=e.length;if(o!==t.length)return!1;for(let n=0;n<o;n++)if(!qi(e[n],t[n]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)return!1;for(let s of o)if(!qi(e[s],t[s]))return!1;return!0}return e===t}function it(e){return encodeURI(Ky(e))}function Ky(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Gy={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Yy={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Xy={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},Qy=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 Hr(e,t=Object.create(null),r=Qy,o=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e.$id||e.id;if(s){let i=new URL(s,r.href);if(i.hash.length>1)t[i.href]=e;else if(i.hash="",o==="")r=i;else Hr(e,t,r)}}else if(e!==!0&&e!==!1)return t;let n=r.href+(o?"#"+o:"");if(t[n]!==void 0)throw Error(`Duplicate schema URI "${n}".`);if(t[n]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:n});if(e.$ref&&e.__absolute_ref__===void 0){let s=new URL(e.$ref,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let s=new URL(e.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){let s=new URL("#"+e.$anchor,r.href);t[s.href]=e}for(let s in e){if(Xy[s])continue;let i=`${o}/${it(s)}`,a=e[s];if(Array.isArray(a)){if(Gy[s]){let l=a.length;for(let u=0;u<l;u++)Hr(a[u],t,r,`${i}/${u}`)}}else if(Yy[s])for(let l in a)Hr(a[l],t,r,`${i}/${it(l)}`);else Hr(a,t,r,i)}return t}var ev=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,tv=[0,31,28,31,30,31,30,31,31,30,31,30,31],rv=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,ov=/^(?=.{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,nv=/^(?:[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,sv=/^(?:(?:[^\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,iv=/^(?:(?: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,av=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,cv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,lv=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,uv=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,dv=(e)=>{if(e[0]==='"')return!1;let[t,r,...o]=e.split("@");if(!t||!r||o.length!==0||t.length>64||r.length>253)return!1;if(t[0]==="."||t.endsWith(".")||t.includes(".."))return!1;if(!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))return!1;return r.split(".").every((n)=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(n))},pv=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,hv=/^((([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,mv=(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 zt(e){return e.test.bind(e)}var bg={date:yg,time:vg.bind(void 0,!1),"date-time":Sv,duration:mv,uri:yv,"uri-reference":zt(nv),"uri-template":zt(sv),url:zt(iv),email:dv,hostname:zt(ov),ipv4:zt(pv),ipv6:zt(hv),regex:zv,uuid:zt(av),"json-pointer":zt(cv),"json-pointer-uri-fragment":zt(lv),"relative-json-pointer":zt(uv)};function fv(e){return e%4===0&&(e%100!==0||e%400===0)}function yg(e){let t=e.match(ev);if(!t)return!1;let r=+t[1],o=+t[2],n=+t[3];return o>=1&&o<=12&&n>=1&&n<=(o==2&&fv(r)?29:tv[o])}function vg(e,t){let r=t.match(rv);if(!r)return!1;let o=+r[1],n=+r[2],s=+r[3],i=!!r[5];return(o<=23&&n<=59&&s<=59||o==23&&n==59&&s==60)&&(!e||i)}var gv=/t|\s/i;function Sv(e){let t=e.split(gv);return t.length==2&&yg(t[0])&&vg(!0,t[1])}var _v=/\/|:/,bv=/^(?:[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 yv(e){return _v.test(e)&&bv.test(e)}var vv=/[^\\]\\Z/;function zv(e){if(vv.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function wv(e){let t=0,r=e.length,o=0,n;while(o<r)if(t++,n=e.charCodeAt(o++),n>=55296&&n<=56319&&o<r){if(n=e.charCodeAt(o),(n&64512)==56320)o++}return t}function pe(e,t,r="2019-09",o=Hr(t),n=!0,s=null,i="#",a="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};let u=typeof e,d;switch(u){case"boolean":case"number":case"string":d=u;break;case"object":if(e===null)d="null";else if(Array.isArray(e))d="array";else d="object";break;default:throw Error(`Instances of "${u}" type are not supported.`)}let{$ref:m,$recursiveRef:f,$recursiveAnchor:S,type:b,const:y,enum:v,required:L,not:F,anyOf:x,allOf:U,oneOf:R,if:w,then:Z,else:X,format:Y,properties:ce,patternProperties:Ee,additionalProperties:te,unevaluatedProperties:se,minProperties:ve,maxProperties:ke,propertyNames:ct,dependentRequired:qe,dependentSchemas:We,dependencies:lt,prefixItems:Ze,items:$e,additionalItems:Tt,unevaluatedItems:Et,contains:ut,minContains:Re,maxContains:Ce,minItems:Ie,maxItems:et,uniqueItems:lr,minimum:De,maximum:Fe,exclusiveMinimum:Ae,exclusiveMaximum:Ke,multipleOf:Ge,minLength:dt,maxLength:pt,pattern:Ht,__absolute_ref__:ht,__absolute_recursive_ref__:ur}=t,C=[];if(S===!0&&s===null)s=t;if(f==="#"){let H=s===null?o[ur]:s,q=`${a}/$recursiveRef`,G=pe(e,s===null?t:s,r,o,n,H,i,q,l);if(!G.valid)C.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:q,error:"A subschema had errors."},...G.errors)}if(m!==void 0){let H=o[ht||m];if(H===void 0){let I=`Unresolved $ref "${m}".`;if(ht&&ht!==m)I+=` Absolute URI "${ht}".`;throw I+=`
69
+ */var Jy=nd((e)=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=n;function n(a){if(!a)throw TypeError("argument string is required");var l=typeof a==="object"?s(a):a;if(typeof l!=="string")throw TypeError("argument string is required to be a string");var u=l.indexOf(";"),d=u!==-1?l.slice(0,u).trim():l.trim();if(!o.test(d))throw TypeError("invalid media type");var m=new i(d.toLowerCase());if(u!==-1){var f,S,b;t.lastIndex=u;while(S=t.exec(l)){if(S.index!==u)throw TypeError("invalid parameter format");if(u+=S[0].length,f=S[1].toLowerCase(),b=S[2],b.charCodeAt(0)===34){if(b=b.slice(1,-1),b.indexOf("\\")!==-1)b=b.replace(r,"$1")}m.parameters[f]=b}if(u!==l.length)throw TypeError("invalid parameter format")}return m}function s(a){var l;if(typeof a.getHeader==="function")l=a.getHeader("content-type");else if(typeof a.headers==="object")l=a.headers&&a.headers["content-type"];if(typeof l!=="string")throw TypeError("content-type header is missing from object");return l}function i(a){this.parameters=Object.create(null),this.type=a}}),By=id(Jy(),1);function fg(e){if(!e)return;try{return By.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();if(t===""||e.slice(t.length).includes(","))return;return t}}function Cf(e){if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Array.isArray(e))return Object.fromEntries(e);return{...e}}function gg(e=fetch,t){if(!t)return e;return async(r,o)=>e(r,{...t,...o,headers:o?.headers?{...Cf(t.headers),...Cf(o.headers)}:t.headers})}var Wy=new Set([301,302,303,307,308]),Ky=5;function Gy(e,t){if(e.protocol===t.protocol&&e.host===t.host)return!0;return e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}function Sg(e,t){let r=Wy.has(t.status)?t.headers?.get("location"):void 0;if(!r)return;try{return new URL(r,e)}catch{return}}var _g=new WeakSet;function bg(e){let t=(r,o)=>e(r,o);return _g.add(t),t}function Ni(e){if(_g.has(e))return e;return async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let o=(r?.method??"GET").toUpperCase(),n=t;for(let s=0;;s++){let i=await e(n,{...r,redirect:"manual"}),a=Sg(n,i);if(!a||s===Ky)return i;let l=new URL(n),u=o==="GET"||i.status===307||i.status===308,d=!(a.username||a.password)||a.username===l.username&&a.password===l.password;if(!u||!d||!Gy(l,a))return i;await i.text?.().catch(()=>{}),n=a}}}function yg(e,t){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";let r=Sg(t.url||e,t);if(!r)return;if(r.username=r.password=r.search=r.hash="",r.protocol==="http:"&&new URL(t.url||e).protocol==="https:")return r.protocol="https:",`Redirect from https to plain http not followed; try ${r.href} as the endpoint`;return`Redirect to ${r.href} not followed; use that URL as the endpoint if it is the intended server`}function qi(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let o=e.length;if(o!==t.length)return!1;for(let n=0;n<o;n++)if(!qi(e[n],t[n]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)return!1;for(let s of o)if(!qi(e[s],t[s]))return!1;return!0}return e===t}function it(e){return encodeURI(Yy(e))}function Yy(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Xy={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Qy={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},ev={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},tv=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 Hr(e,t=Object.create(null),r=tv,o=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e.$id||e.id;if(s){let i=new URL(s,r.href);if(i.hash.length>1)t[i.href]=e;else if(i.hash="",o==="")r=i;else Hr(e,t,r)}}else if(e!==!0&&e!==!1)return t;let n=r.href+(o?"#"+o:"");if(t[n]!==void 0)throw Error(`Duplicate schema URI "${n}".`);if(t[n]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:n});if(e.$ref&&e.__absolute_ref__===void 0){let s=new URL(e.$ref,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let s=new URL(e.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){let s=new URL("#"+e.$anchor,r.href);t[s.href]=e}for(let s in e){if(ev[s])continue;let i=`${o}/${it(s)}`,a=e[s];if(Array.isArray(a)){if(Xy[s]){let l=a.length;for(let u=0;u<l;u++)Hr(a[u],t,r,`${i}/${u}`)}}else if(Qy[s])for(let l in a)Hr(a[l],t,r,`${i}/${it(l)}`);else Hr(a,t,r,i)}return t}var rv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ov=[0,31,28,31,30,31,30,31,31,30,31,30,31],nv=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,sv=/^(?=.{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,iv=/^(?:[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,av=/^(?:(?:[^\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,cv=/^(?:(?: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,lv=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,uv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,dv=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,pv=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,hv=(e)=>{if(e[0]==='"')return!1;let[t,r,...o]=e.split("@");if(!t||!r||o.length!==0||t.length>64||r.length>253)return!1;if(t[0]==="."||t.endsWith(".")||t.includes(".."))return!1;if(!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))return!1;return r.split(".").every((n)=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(n))},mv=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,fv=/^((([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,gv=(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 zt(e){return e.test.bind(e)}var vg={date:zg,time:wg.bind(void 0,!1),"date-time":bv,duration:gv,uri:zv,"uri-reference":zt(iv),"uri-template":zt(av),url:zt(cv),email:hv,hostname:zt(sv),ipv4:zt(mv),ipv6:zt(fv),regex:Rv,uuid:zt(lv),"json-pointer":zt(uv),"json-pointer-uri-fragment":zt(dv),"relative-json-pointer":zt(pv)};function Sv(e){return e%4===0&&(e%100!==0||e%400===0)}function zg(e){let t=e.match(rv);if(!t)return!1;let r=+t[1],o=+t[2],n=+t[3];return o>=1&&o<=12&&n>=1&&n<=(o==2&&Sv(r)?29:ov[o])}function wg(e,t){let r=t.match(nv);if(!r)return!1;let o=+r[1],n=+r[2],s=+r[3],i=!!r[5];return(o<=23&&n<=59&&s<=59||o==23&&n==59&&s==60)&&(!e||i)}var _v=/t|\s/i;function bv(e){let t=e.split(_v);return t.length==2&&zg(t[0])&&wg(!0,t[1])}var yv=/\/|:/,vv=/^(?:[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 zv(e){return yv.test(e)&&vv.test(e)}var wv=/[^\\]\\Z/;function Rv(e){if(wv.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function xv(e){let t=0,r=e.length,o=0,n;while(o<r)if(t++,n=e.charCodeAt(o++),n>=55296&&n<=56319&&o<r){if(n=e.charCodeAt(o),(n&64512)==56320)o++}return t}function pe(e,t,r="2019-09",o=Hr(t),n=!0,s=null,i="#",a="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};let u=typeof e,d;switch(u){case"boolean":case"number":case"string":d=u;break;case"object":if(e===null)d="null";else if(Array.isArray(e))d="array";else d="object";break;default:throw Error(`Instances of "${u}" type are not supported.`)}let{$ref:m,$recursiveRef:f,$recursiveAnchor:S,type:b,const:y,enum:v,required:U,not:H,anyOf:x,allOf:Z,oneOf:R,if:w,then:D,else:X,format:Y,properties:ce,patternProperties:Ee,additionalProperties:te,unevaluatedProperties:se,minProperties:ve,maxProperties:ke,propertyNames:ct,dependentRequired:qe,dependentSchemas:We,dependencies:lt,prefixItems:Ze,items:$e,additionalItems:Tt,unevaluatedItems:Et,contains:ut,minContains:Re,maxContains:Ce,minItems:Ie,maxItems:et,uniqueItems:lr,minimum:De,maximum:Fe,exclusiveMinimum:Ae,exclusiveMaximum:Ke,multipleOf:Ge,minLength:dt,maxLength:pt,pattern:Ht,__absolute_ref__:ht,__absolute_recursive_ref__:ur}=t,C=[];if(S===!0&&s===null)s=t;if(f==="#"){let V=s===null?o[ur]:s,q=`${a}/$recursiveRef`,G=pe(e,s===null?t:s,r,o,n,V,i,q,l);if(!G.valid)C.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:q,error:"A subschema had errors."},...G.errors)}if(m!==void 0){let V=o[ht||m];if(V===void 0){let I=`Unresolved $ref "${m}".`;if(ht&&ht!==m)I+=` Absolute URI "${ht}".`;throw I+=`
69
70
  Known schemas:
70
71
  - ${Object.keys(o).join(`
71
- - `)}`,Error(I)}let q=`${a}/$ref`,G=pe(e,H,r,o,n,s,i,q,l);if(!G.valid)C.push({instanceLocation:i,keyword:"$ref",keywordLocation:q,error:"A subschema had errors."},...G.errors);if(r==="4"||r==="7")return{valid:C.length===0,errors:C}}if(Array.isArray(b)){let H=b.length,q=!1;for(let G=0;G<H;G++)if(d===b[G]||b[G]==="integer"&&d==="number"&&e%1===0&&e===e){q=!0;break}if(!q)C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b.join('", "')}".`})}else if(b==="integer"){if(d!=="number"||e%1||e!==e)C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`})}else if(b!==void 0&&d!==b)C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`});if(y!==void 0){if(d==="object"||d==="array"){if(!qi(e,y))C.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}else if(e!==y)C.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}if(v!==void 0){if(d==="object"||d==="array"){if(!v.some((H)=>qi(e,H)))C.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}else if(!v.some((H)=>e===H))C.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}if(F!==void 0){let H=`${a}/not`;if(pe(e,F,r,o,n,s,i,H).valid)C.push({instanceLocation:i,keyword:"not",keywordLocation:H,error:'Instance matched "not" schema.'})}let mt=[];if(x!==void 0){let H=`${a}/anyOf`,q=C.length,G=!1;for(let I=0;I<x.length;I++){let k=x[I],B=Object.create(l),J=pe(e,k,r,o,n,S===!0?s:null,i,`${H}/${I}`,B);if(C.push(...J.errors),G=G||J.valid,J.valid)mt.push(B)}if(G)C.length=q;else C.splice(q,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:H,error:"Instance does not match any subschemas."})}if(U!==void 0){let H=`${a}/allOf`,q=C.length,G=!0;for(let I=0;I<U.length;I++){let k=U[I],B=Object.create(l),J=pe(e,k,r,o,n,S===!0?s:null,i,`${H}/${I}`,B);if(C.push(...J.errors),G=G&&J.valid,J.valid)mt.push(B)}if(G)C.length=q;else C.splice(q,0,{instanceLocation:i,keyword:"allOf",keywordLocation:H,error:"Instance does not match every subschema."})}if(R!==void 0){let H=`${a}/oneOf`,q=C.length,G=R.filter((I,k)=>{let B=Object.create(l),J=pe(e,I,r,o,n,S===!0?s:null,i,`${H}/${k}`,B);if(C.push(...J.errors),J.valid)mt.push(B);return J.valid}).length;if(G===1)C.length=q;else C.splice(q,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:H,error:`Instance does not match exactly one subschema (${G} matches).`})}if(d==="object"||d==="array")Object.assign(l,...mt);if(w!==void 0){let H=`${a}/if`;if(pe(e,w,r,o,n,s,i,H,l).valid){if(Z!==void 0){let q=pe(e,Z,r,o,n,s,i,`${a}/then`,l);if(!q.valid)C.push({instanceLocation:i,keyword:"if",keywordLocation:H,error:'Instance does not match "then" schema.'},...q.errors)}}else if(X!==void 0){let q=pe(e,X,r,o,n,s,i,`${a}/else`,l);if(!q.valid)C.push({instanceLocation:i,keyword:"if",keywordLocation:H,error:'Instance does not match "else" schema.'},...q.errors)}}if(d==="object"){if(L!==void 0){for(let I of L)if(!(I in e))C.push({instanceLocation:i,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${I}".`})}let H=Object.keys(e);if(ve!==void 0&&H.length<ve)C.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${ve} properties.`});if(ke!==void 0&&H.length>ke)C.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${ke} properties.`});if(ct!==void 0){let I=`${a}/propertyNames`;for(let k in e){let B=`${i}/${it(k)}`,J=pe(k,ct,r,o,n,s,B,I);if(!J.valid)C.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:I,error:`Property name "${k}" does not match schema.`},...J.errors)}}if(qe!==void 0){let I=`${a}/dependantRequired`;for(let k in qe)if(k in e){let B=qe[k];for(let J of B)if(!(J in e))C.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:I,error:`Instance has "${k}" but does not have "${J}".`})}}if(We!==void 0)for(let I in We){let k=`${a}/dependentSchemas`;if(I in e){let B=pe(e,We[I],r,o,n,s,i,`${k}/${it(I)}`,l);if(!B.valid)C.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:k,error:`Instance has "${I}" but does not match dependant schema.`},...B.errors)}}if(lt!==void 0){let I=`${a}/dependencies`;for(let k in lt)if(k in e){let B=lt[k];if(Array.isArray(B)){for(let J of B)if(!(J in e))C.push({instanceLocation:i,keyword:"dependencies",keywordLocation:I,error:`Instance has "${k}" but does not have "${J}".`})}else{let J=pe(e,B,r,o,n,s,i,`${I}/${it(k)}`);if(!J.valid)C.push({instanceLocation:i,keyword:"dependencies",keywordLocation:I,error:`Instance has "${k}" but does not match dependant schema.`},...J.errors)}}}let q=Object.create(null),G=!1;if(ce!==void 0){let I=`${a}/properties`;for(let k in ce){if(!(k in e))continue;let B=`${i}/${it(k)}`,J=pe(e[k],ce[k],r,o,n,s,B,`${I}/${it(k)}`);if(J.valid)l[k]=q[k]=!0;else if(G=n,C.push({instanceLocation:i,keyword:"properties",keywordLocation:I,error:`Property "${k}" does not match schema.`},...J.errors),G)break}}if(!G&&Ee!==void 0){let I=`${a}/patternProperties`;for(let k in Ee){let B=new RegExp(k,"u"),J=Ee[k];for(let ge in e){if(!B.test(ge))continue;let dr=`${i}/${it(ge)}`,ft=pe(e[ge],J,r,o,n,s,dr,`${I}/${it(k)}`);if(ft.valid)l[ge]=q[ge]=!0;else G=n,C.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:I,error:`Property "${ge}" matches pattern "${k}" but does not match associated schema.`},...ft.errors)}}}if(!G&&te!==void 0){let I=`${a}/additionalProperties`;for(let k in e){if(q[k])continue;let B=`${i}/${it(k)}`,J=pe(e[k],te,r,o,n,s,B,I);if(J.valid)l[k]=!0;else G=n,C.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:I,error:`Property "${k}" does not match additional properties schema.`},...J.errors)}}else if(!G&&se!==void 0){let I=`${a}/unevaluatedProperties`;for(let k in e)if(!l[k]){let B=`${i}/${it(k)}`,J=pe(e[k],se,r,o,n,s,B,I);if(J.valid)l[k]=!0;else C.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:I,error:`Property "${k}" does not match unevaluated properties schema.`},...J.errors)}}}else if(d==="array"){if(et!==void 0&&e.length>et)C.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${et}).`});if(Ie!==void 0&&e.length<Ie)C.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Ie}).`});let H=e.length,q=0,G=!1;if(Ze!==void 0){let I=`${a}/prefixItems`,k=Math.min(Ze.length,H);for(;q<k;q++){let B=pe(e[q],Ze[q],r,o,n,s,`${i}/${q}`,`${I}/${q}`);if(l[q]=!0,!B.valid){if(G=n,C.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:I,error:"Items did not match schema."},...B.errors),G)break}}}if($e!==void 0){let I=`${a}/items`;if(Array.isArray($e)){let k=Math.min($e.length,H);for(;q<k;q++){let B=pe(e[q],$e[q],r,o,n,s,`${i}/${q}`,`${I}/${q}`);if(l[q]=!0,!B.valid){if(G=n,C.push({instanceLocation:i,keyword:"items",keywordLocation:I,error:"Items did not match schema."},...B.errors),G)break}}}else for(;q<H;q++){let k=pe(e[q],$e,r,o,n,s,`${i}/${q}`,I);if(l[q]=!0,!k.valid){if(G=n,C.push({instanceLocation:i,keyword:"items",keywordLocation:I,error:"Items did not match schema."},...k.errors),G)break}}if(!G&&Tt!==void 0){let k=`${a}/additionalItems`;for(;q<H;q++){let B=pe(e[q],Tt,r,o,n,s,`${i}/${q}`,k);if(l[q]=!0,!B.valid)G=n,C.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:k,error:"Items did not match additional items schema."},...B.errors)}}}if(ut!==void 0)if(H===0&&Re===void 0)C.push({instanceLocation:i,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Re!==void 0&&H<Re)C.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${H}) than minContains (${Re}).`});else{let I=`${a}/contains`,k=C.length,B=0;for(let J=0;J<H;J++){let ge=pe(e[J],ut,r,o,n,s,`${i}/${J}`,I);if(ge.valid)l[J]=!0,B++;else C.push(...ge.errors)}if(B>=(Re||0))C.length=k;if(Re===void 0&&Ce===void 0&&B===0)C.splice(k,0,{instanceLocation:i,keyword:"contains",keywordLocation:I,error:"Array does not contain item matching schema."});else if(Re!==void 0&&B<Re)C.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Re} items matching schema. Only ${B} items were found.`});else if(Ce!==void 0&&B>Ce)C.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Ce} items matching schema. ${B} items were found.`})}if(!G&&Et!==void 0){let I=`${a}/unevaluatedItems`;for(;q<H;q++){if(l[q])continue;let k=pe(e[q],Et,r,o,n,s,`${i}/${q}`,I);if(l[q]=!0,!k.valid)C.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:I,error:"Items did not match unevaluated items schema."},...k.errors)}}if(lr)for(let I=0;I<H;I++){let k=e[I],B=typeof k==="object"&&k!==null;for(let J=0;J<H;J++){if(I===J)continue;let ge=e[J];if(k===ge||B&&typeof ge==="object"&&ge!==null&&qi(k,ge))C.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${I} and ${J}.`}),I=Number.MAX_SAFE_INTEGER,J=Number.MAX_SAFE_INTEGER}}}else if(d==="number"){if(r==="4"){if(De!==void 0&&(Ae===!0&&e<=De||e<De))C.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Ae?"or equal to ":""} ${De}.`});if(Fe!==void 0&&(Ke===!0&&e>=Fe||e>Fe))C.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Ke?"or equal to ":""} ${Fe}.`})}else{if(De!==void 0&&e<De)C.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${De}.`});if(Fe!==void 0&&e>Fe)C.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Fe}.`});if(Ae!==void 0&&e<=Ae)C.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${Ae}.`});if(Ke!==void 0&&e>=Ke)C.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ke}.`})}if(Ge!==void 0){let H=e%Ge;if(Math.abs(0-H)>=0.00000011920929&&Math.abs(Ge-H)>=0.00000011920929)C.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Ge}.`})}}else if(d==="string"){let H=dt===void 0&&pt===void 0?0:wv(e);if(dt!==void 0&&H<dt)C.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${H} < ${dt}).`});if(pt!==void 0&&H>pt)C.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${H} > ${pt}).`});if(Ht!==void 0&&!new RegExp(Ht,"u").test(e))C.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(Y!==void 0&&bg[Y]&&!bg[Y](e))C.push({instanceLocation:i,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${Y}".`})}return{valid:C.length===0,errors:C}}var Rv=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=Hr(e)}validate(e){return pe(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){if(t)e={...e,$id:t};Hr(e,this.lookup)}},Su=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=ad(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){let t=new Rv(e,this.draft??this._draftFor(e),this.shortcircuit);return(r)=>{let o=t.validate(r);return o.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:o.errors.map((n)=>`${n.instanceLocation}: ${n.error}`).join("; ")}}}};var zg=!0;var _u;_u=globalThis.crypto;async function xv(e){return(await _u).getRandomValues(new Uint8Array(e))}async function Pv(e){let r=Math.pow(2,8)-Math.pow(2,8)%66,o="";while(o.length<e){let n=await xv(e-o.length);for(let s of n)if(s<r)o+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[s%66]}return o}async function Tv(e){return await Pv(e)}async function Ev(e){let t=await(await _u).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function bu(e){if(!e)e=43;if(e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Tv(e),r=await Ev(t);return{code_verifier:t,code_challenge:r}}class yc extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}var wg=10,kv=13,Vr=32;function yu(e){}function Pg(e){if(typeof e=="function")throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=yu,onError:r=yu,onRetry:o=yu,onComment:n,maxBufferSize:s}=e,i=[],a=0,l=!0,u,d="",m=0,f,S=!1;function b(R){if(S)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,R.charCodeAt(0)===239&&R.charCodeAt(1)===187&&R.charCodeAt(2)===191&&(R=R.slice(3))),i.length===0){let X=v(R);X!==""&&(i.push(X),a=X.length),y();return}if(R.indexOf(`
72
- `)===-1&&R.indexOf("\r")===-1){i.push(R),a+=R.length,y();return}i.push(R);let w=i.join("");i.length=0,a=0;let Z=v(w);Z!==""&&(i.push(Z),a=Z.length),y()}function y(){s!==void 0&&(a+d.length<=s||(S=!0,i.length=0,a=0,u=void 0,d="",m=0,f=void 0,r(new yc(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function v(R){let w=0;if(R.indexOf("\r")===-1){let Z=R.indexOf(`
73
- `,w);for(;Z!==-1;){if(w===Z){m>0&&t({id:u,event:f,data:d}),u=void 0,d="",m=0,f=void 0,w=Z+1,Z=R.indexOf(`
74
- `,w);continue}let X=R.charCodeAt(w);if(Rg(R,w,X)){let Y=R.charCodeAt(w+5)===Vr?w+6:w+5,ce=R.slice(Y,Z);if(m===0&&R.charCodeAt(Z+1)===wg){t({id:u,event:f,data:ce}),u=void 0,d="",f=void 0,w=Z+2,Z=R.indexOf(`
72
+ - `)}`,Error(I)}let q=`${a}/$ref`,G=pe(e,V,r,o,n,s,i,q,l);if(!G.valid)C.push({instanceLocation:i,keyword:"$ref",keywordLocation:q,error:"A subschema had errors."},...G.errors);if(r==="4"||r==="7")return{valid:C.length===0,errors:C}}if(Array.isArray(b)){let V=b.length,q=!1;for(let G=0;G<V;G++)if(d===b[G]||b[G]==="integer"&&d==="number"&&e%1===0&&e===e){q=!0;break}if(!q)C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b.join('", "')}".`})}else if(b==="integer"){if(d!=="number"||e%1||e!==e)C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`})}else if(b!==void 0&&d!==b)C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`});if(y!==void 0){if(d==="object"||d==="array"){if(!qi(e,y))C.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}else if(e!==y)C.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}if(v!==void 0){if(d==="object"||d==="array"){if(!v.some((V)=>qi(e,V)))C.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}else if(!v.some((V)=>e===V))C.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}if(H!==void 0){let V=`${a}/not`;if(pe(e,H,r,o,n,s,i,V).valid)C.push({instanceLocation:i,keyword:"not",keywordLocation:V,error:'Instance matched "not" schema.'})}let mt=[];if(x!==void 0){let V=`${a}/anyOf`,q=C.length,G=!1;for(let I=0;I<x.length;I++){let k=x[I],B=Object.create(l),J=pe(e,k,r,o,n,S===!0?s:null,i,`${V}/${I}`,B);if(C.push(...J.errors),G=G||J.valid,J.valid)mt.push(B)}if(G)C.length=q;else C.splice(q,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:V,error:"Instance does not match any subschemas."})}if(Z!==void 0){let V=`${a}/allOf`,q=C.length,G=!0;for(let I=0;I<Z.length;I++){let k=Z[I],B=Object.create(l),J=pe(e,k,r,o,n,S===!0?s:null,i,`${V}/${I}`,B);if(C.push(...J.errors),G=G&&J.valid,J.valid)mt.push(B)}if(G)C.length=q;else C.splice(q,0,{instanceLocation:i,keyword:"allOf",keywordLocation:V,error:"Instance does not match every subschema."})}if(R!==void 0){let V=`${a}/oneOf`,q=C.length,G=R.filter((I,k)=>{let B=Object.create(l),J=pe(e,I,r,o,n,S===!0?s:null,i,`${V}/${k}`,B);if(C.push(...J.errors),J.valid)mt.push(B);return J.valid}).length;if(G===1)C.length=q;else C.splice(q,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:V,error:`Instance does not match exactly one subschema (${G} matches).`})}if(d==="object"||d==="array")Object.assign(l,...mt);if(w!==void 0){let V=`${a}/if`;if(pe(e,w,r,o,n,s,i,V,l).valid){if(D!==void 0){let q=pe(e,D,r,o,n,s,i,`${a}/then`,l);if(!q.valid)C.push({instanceLocation:i,keyword:"if",keywordLocation:V,error:'Instance does not match "then" schema.'},...q.errors)}}else if(X!==void 0){let q=pe(e,X,r,o,n,s,i,`${a}/else`,l);if(!q.valid)C.push({instanceLocation:i,keyword:"if",keywordLocation:V,error:'Instance does not match "else" schema.'},...q.errors)}}if(d==="object"){if(U!==void 0){for(let I of U)if(!(I in e))C.push({instanceLocation:i,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${I}".`})}let V=Object.keys(e);if(ve!==void 0&&V.length<ve)C.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${ve} properties.`});if(ke!==void 0&&V.length>ke)C.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${ke} properties.`});if(ct!==void 0){let I=`${a}/propertyNames`;for(let k in e){let B=`${i}/${it(k)}`,J=pe(k,ct,r,o,n,s,B,I);if(!J.valid)C.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:I,error:`Property name "${k}" does not match schema.`},...J.errors)}}if(qe!==void 0){let I=`${a}/dependantRequired`;for(let k in qe)if(k in e){let B=qe[k];for(let J of B)if(!(J in e))C.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:I,error:`Instance has "${k}" but does not have "${J}".`})}}if(We!==void 0)for(let I in We){let k=`${a}/dependentSchemas`;if(I in e){let B=pe(e,We[I],r,o,n,s,i,`${k}/${it(I)}`,l);if(!B.valid)C.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:k,error:`Instance has "${I}" but does not match dependant schema.`},...B.errors)}}if(lt!==void 0){let I=`${a}/dependencies`;for(let k in lt)if(k in e){let B=lt[k];if(Array.isArray(B)){for(let J of B)if(!(J in e))C.push({instanceLocation:i,keyword:"dependencies",keywordLocation:I,error:`Instance has "${k}" but does not have "${J}".`})}else{let J=pe(e,B,r,o,n,s,i,`${I}/${it(k)}`);if(!J.valid)C.push({instanceLocation:i,keyword:"dependencies",keywordLocation:I,error:`Instance has "${k}" but does not match dependant schema.`},...J.errors)}}}let q=Object.create(null),G=!1;if(ce!==void 0){let I=`${a}/properties`;for(let k in ce){if(!(k in e))continue;let B=`${i}/${it(k)}`,J=pe(e[k],ce[k],r,o,n,s,B,`${I}/${it(k)}`);if(J.valid)l[k]=q[k]=!0;else if(G=n,C.push({instanceLocation:i,keyword:"properties",keywordLocation:I,error:`Property "${k}" does not match schema.`},...J.errors),G)break}}if(!G&&Ee!==void 0){let I=`${a}/patternProperties`;for(let k in Ee){let B=new RegExp(k,"u"),J=Ee[k];for(let ge in e){if(!B.test(ge))continue;let dr=`${i}/${it(ge)}`,ft=pe(e[ge],J,r,o,n,s,dr,`${I}/${it(k)}`);if(ft.valid)l[ge]=q[ge]=!0;else G=n,C.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:I,error:`Property "${ge}" matches pattern "${k}" but does not match associated schema.`},...ft.errors)}}}if(!G&&te!==void 0){let I=`${a}/additionalProperties`;for(let k in e){if(q[k])continue;let B=`${i}/${it(k)}`,J=pe(e[k],te,r,o,n,s,B,I);if(J.valid)l[k]=!0;else G=n,C.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:I,error:`Property "${k}" does not match additional properties schema.`},...J.errors)}}else if(!G&&se!==void 0){let I=`${a}/unevaluatedProperties`;for(let k in e)if(!l[k]){let B=`${i}/${it(k)}`,J=pe(e[k],se,r,o,n,s,B,I);if(J.valid)l[k]=!0;else C.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:I,error:`Property "${k}" does not match unevaluated properties schema.`},...J.errors)}}}else if(d==="array"){if(et!==void 0&&e.length>et)C.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${et}).`});if(Ie!==void 0&&e.length<Ie)C.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Ie}).`});let V=e.length,q=0,G=!1;if(Ze!==void 0){let I=`${a}/prefixItems`,k=Math.min(Ze.length,V);for(;q<k;q++){let B=pe(e[q],Ze[q],r,o,n,s,`${i}/${q}`,`${I}/${q}`);if(l[q]=!0,!B.valid){if(G=n,C.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:I,error:"Items did not match schema."},...B.errors),G)break}}}if($e!==void 0){let I=`${a}/items`;if(Array.isArray($e)){let k=Math.min($e.length,V);for(;q<k;q++){let B=pe(e[q],$e[q],r,o,n,s,`${i}/${q}`,`${I}/${q}`);if(l[q]=!0,!B.valid){if(G=n,C.push({instanceLocation:i,keyword:"items",keywordLocation:I,error:"Items did not match schema."},...B.errors),G)break}}}else for(;q<V;q++){let k=pe(e[q],$e,r,o,n,s,`${i}/${q}`,I);if(l[q]=!0,!k.valid){if(G=n,C.push({instanceLocation:i,keyword:"items",keywordLocation:I,error:"Items did not match schema."},...k.errors),G)break}}if(!G&&Tt!==void 0){let k=`${a}/additionalItems`;for(;q<V;q++){let B=pe(e[q],Tt,r,o,n,s,`${i}/${q}`,k);if(l[q]=!0,!B.valid)G=n,C.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:k,error:"Items did not match additional items schema."},...B.errors)}}}if(ut!==void 0)if(V===0&&Re===void 0)C.push({instanceLocation:i,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Re!==void 0&&V<Re)C.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${V}) than minContains (${Re}).`});else{let I=`${a}/contains`,k=C.length,B=0;for(let J=0;J<V;J++){let ge=pe(e[J],ut,r,o,n,s,`${i}/${J}`,I);if(ge.valid)l[J]=!0,B++;else C.push(...ge.errors)}if(B>=(Re||0))C.length=k;if(Re===void 0&&Ce===void 0&&B===0)C.splice(k,0,{instanceLocation:i,keyword:"contains",keywordLocation:I,error:"Array does not contain item matching schema."});else if(Re!==void 0&&B<Re)C.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Re} items matching schema. Only ${B} items were found.`});else if(Ce!==void 0&&B>Ce)C.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Ce} items matching schema. ${B} items were found.`})}if(!G&&Et!==void 0){let I=`${a}/unevaluatedItems`;for(;q<V;q++){if(l[q])continue;let k=pe(e[q],Et,r,o,n,s,`${i}/${q}`,I);if(l[q]=!0,!k.valid)C.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:I,error:"Items did not match unevaluated items schema."},...k.errors)}}if(lr)for(let I=0;I<V;I++){let k=e[I],B=typeof k==="object"&&k!==null;for(let J=0;J<V;J++){if(I===J)continue;let ge=e[J];if(k===ge||B&&typeof ge==="object"&&ge!==null&&qi(k,ge))C.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${I} and ${J}.`}),I=Number.MAX_SAFE_INTEGER,J=Number.MAX_SAFE_INTEGER}}}else if(d==="number"){if(r==="4"){if(De!==void 0&&(Ae===!0&&e<=De||e<De))C.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Ae?"or equal to ":""} ${De}.`});if(Fe!==void 0&&(Ke===!0&&e>=Fe||e>Fe))C.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Ke?"or equal to ":""} ${Fe}.`})}else{if(De!==void 0&&e<De)C.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${De}.`});if(Fe!==void 0&&e>Fe)C.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Fe}.`});if(Ae!==void 0&&e<=Ae)C.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${Ae}.`});if(Ke!==void 0&&e>=Ke)C.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ke}.`})}if(Ge!==void 0){let V=e%Ge;if(Math.abs(0-V)>=0.00000011920929&&Math.abs(Ge-V)>=0.00000011920929)C.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Ge}.`})}}else if(d==="string"){let V=dt===void 0&&pt===void 0?0:xv(e);if(dt!==void 0&&V<dt)C.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${V} < ${dt}).`});if(pt!==void 0&&V>pt)C.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${V} > ${pt}).`});if(Ht!==void 0&&!new RegExp(Ht,"u").test(e))C.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(Y!==void 0&&vg[Y]&&!vg[Y](e))C.push({instanceLocation:i,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${Y}".`})}return{valid:C.length===0,errors:C}}var Pv=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=Hr(e)}validate(e){return pe(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){if(t)e={...e,$id:t};Hr(e,this.lookup)}},_u=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=ld(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){let t=new Pv(e,this.draft??this._draftFor(e),this.shortcircuit);return(r)=>{let o=t.validate(r);return o.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:o.errors.map((n)=>`${n.instanceLocation}: ${n.error}`).join("; ")}}}};var Rg=!0;var bu;bu=globalThis.crypto;async function Tv(e){return(await bu).getRandomValues(new Uint8Array(e))}async function Ev(e){let r=Math.pow(2,8)-Math.pow(2,8)%66,o="";while(o.length<e){let n=await Tv(e-o.length);for(let s of n)if(s<r)o+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[s%66]}return o}async function kv(e){return await Ev(e)}async function $v(e){let t=await(await bu).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function yu(e){if(!e)e=43;if(e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await kv(e),r=await $v(t);return{code_verifier:t,code_challenge:r}}class vc extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}var xg=10,Cv=13,Vr=32;function vu(e){}function Eg(e){if(typeof e=="function")throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=vu,onError:r=vu,onRetry:o=vu,onComment:n,maxBufferSize:s}=e,i=[],a=0,l=!0,u,d="",m=0,f,S=!1;function b(R){if(S)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,R.charCodeAt(0)===239&&R.charCodeAt(1)===187&&R.charCodeAt(2)===191&&(R=R.slice(3))),i.length===0){let X=v(R);X!==""&&(i.push(X),a=X.length),y();return}if(R.indexOf(`
73
+ `)===-1&&R.indexOf("\r")===-1){i.push(R),a+=R.length,y();return}i.push(R);let w=i.join("");i.length=0,a=0;let D=v(w);D!==""&&(i.push(D),a=D.length),y()}function y(){s!==void 0&&(a+d.length<=s||(S=!0,i.length=0,a=0,u=void 0,d="",m=0,f=void 0,r(new vc(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function v(R){let w=0;if(R.indexOf("\r")===-1){let D=R.indexOf(`
74
+ `,w);for(;D!==-1;){if(w===D){m>0&&t({id:u,event:f,data:d}),u=void 0,d="",m=0,f=void 0,w=D+1,D=R.indexOf(`
75
+ `,w);continue}let X=R.charCodeAt(w);if(Pg(R,w,X)){let Y=R.charCodeAt(w+5)===Vr?w+6:w+5,ce=R.slice(Y,D);if(m===0&&R.charCodeAt(D+1)===xg){t({id:u,event:f,data:ce}),u=void 0,d="",f=void 0,w=D+2,D=R.indexOf(`
75
76
  `,w);continue}d=m===0?ce:`${d}
76
- ${ce}`,m++}else xg(R,w,X)?f=R.slice(R.charCodeAt(w+6)===Vr?w+7:w+6,Z)||void 0:L(R,w,Z);w=Z+1,Z=R.indexOf(`
77
- `,w)}return R.slice(w)}for(;w<R.length;){let Z=R.indexOf("\r",w),X=R.indexOf(`
78
- `,w),Y=-1;if(Z!==-1&&X!==-1?Y=Z<X?Z:X:Z!==-1?Z===R.length-1?Y=-1:Y=Z:X!==-1&&(Y=X),Y===-1)break;L(R,w,Y),w=Y+1,R.charCodeAt(w-1)===kv&&R.charCodeAt(w)===wg&&w++}return R.slice(w)}function L(R,w,Z){if(w===Z){x();return}let X=R.charCodeAt(w);if(Rg(R,w,X)){let ve=R.charCodeAt(w+5)===Vr?w+6:w+5,ke=R.slice(ve,Z);d=m===0?ke:`${d}
79
- ${ke}`,m++;return}if(xg(R,w,X)){f=R.slice(R.charCodeAt(w+6)===Vr?w+7:w+6,Z)||void 0;return}if(X===105&&R.charCodeAt(w+1)===100&&R.charCodeAt(w+2)===58){let ve=R.slice(R.charCodeAt(w+3)===Vr?w+4:w+3,Z);ve.includes("\x00")||(u=ve);return}if(X===58){if(n){let ve=R.slice(w,Z);n(ve.slice(R.charCodeAt(w+1)===Vr?2:1))}return}let Y=R.slice(w,Z),ce=Y.indexOf(":");if(ce===-1){F(Y,"",Y);return}let Ee=Y.slice(0,ce),te=Y.charCodeAt(ce+1)===Vr?2:1,se=Y.slice(ce+te);F(Ee,se,Y)}function F(R,w,Z){switch(R){case"event":f=w||void 0;break;case"data":d=m===0?w:`${d}
80
- ${w}`,m++;break;case"id":w.includes("\x00")||(u=w);break;case"retry":/^\d+$/.test(w)?o(parseInt(w,10)):r(new yc(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:Z}));break;default:r(new yc(`Unknown field "${R.length>20?`${R.slice(0,20)}…`:R}"`,{type:"unknown-field",field:R,value:w,line:Z}));break}}function x(){m>0&&t({id:u,event:f,data:d}),u=void 0,d="",m=0,f=void 0}function U(R={}){if(R.consume&&i.length>0){let w=i.join("");L(w,0,w.length)}l=!0,u=void 0,d="",m=0,f=void 0,i.length=0,a=0,S=!1}return{feed:b,reset:U}}function Rg(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function xg(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}class vu extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:o}={}){let n;super({start(s){n=Pg({onEvent:(i)=>{s.enqueue(i)},onError(i){typeof e=="function"&&e(i),(e==="terminate"||i.type==="max-buffer-size-exceeded")&&s.error(i)},onRetry:t,onComment:r,maxBufferSize:o})},transform(s){n.feed(s)}})}}var Mi=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e){super(e);this.name=new.target.name,Zr(this,new.target)}},Eu=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 §3.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`);this.kind=e,this.expected=t,this.received=r}},$v=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`);this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},Lg=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`);this.tokenEndpoint=e}},wc=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`);this.recordedIssuer=e,this.currentIssuer=t}},Tg=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`);this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function ku(e,t,r){if(!e)return;if(typeof e.issuer!=="string"){if(r?.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.");return e.issuer===void 0?e:{...e,issuer:void 0}}return Ug(e.issuer,t)?e:void 0}function Ug(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function Cv(e){if(e==null)return!1;let t=e;return typeof t.tokens==="function"&&typeof t.clientInformation==="function"}async function Iv(e,t,r){let{resourceMetadataUrl:o,scope:n}=Ai(t.response);if(await $u(e,{serverUrl:t.serverUrl,resourceMetadataUrl:o,scope:n,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new wt}function Ov(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async(r)=>Iv(e,r,t)}}var wt=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e){super(e??"Unauthorized");this.name="UnauthorizedError",Zr(this,new.target)}};function Iu(e){return e?.authorization_response_iss_parameter_supported===!0}function Ou({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t===void 0)return;if(e===void 0){if(r)throw new Eu("authorization_response",t,void 0);return}if(e!==t)throw new Eu("authorization_response",t,e)}function zu(...e){let t=new Set;for(let r of e){if(!r)continue;for(let o of r.split(/\s+/))if(o)t.add(o)}return t.size>0?[...t].join(" "):void 0}function Nv(e,t){if(!e)return!1;let r=new Set((t??"").split(/\s+/).filter(Boolean));for(let o of e.split(/\s+/))if(o&&!r.has(o))return!0;return!1}async function qv(e,t,r,o,n){if(typeof e==="string")return{authorizationCode:e,iss:t};let s=e.get("iss")??void 0,i=e.get("code");if(i)return{authorizationCode:i,iss:s};let a=(await r.discoveryState?.())?.authorizationServerMetadata;if(!a)try{a=(await Vg(o,n)).authorizationServerMetadata}catch{a=void 0}if(!a)throw new wt("Authorization callback failed and the issuer could not be verified");Ou({iss:s,expectedIssuer:a.issuer,issParameterSupported:Iu(a)});let l=e.get("error");if(l)throw new Dr(l,e.get("error_description")??l,e.get("error_uri")??void 0);throw new wt("Authorization callback contained neither `code` nor `error`")}function Av(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var wu="code",Ru="S256";function Mv(e,t){let r=e.client_secret!==void 0;if("token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Av(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method)))return e.token_endpoint_auth_method;if(t.length===0)return r?"client_secret_basic":"none";if(r&&t.includes("client_secret_basic"))return"client_secret_basic";if(r&&t.includes("client_secret_post"))return"client_secret_post";if(t.includes("none"))return"none";return r?"client_secret_post":"none"}function jv(e,t,r,o){let{client_id:n,client_secret:s}=t;switch(e){case"client_secret_basic":Lv(n,s,r);return;case"client_secret_post":Uv(n,s,o);return;case"none":Zv(n,o);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Lv(e,t,r){if(!t)throw Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}function Uv(e,t,r){if(r.set("client_id",e),t)r.set("client_secret",t)}function Zv(e,t){t.set("client_id",e)}function Zg(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function Dv(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!Zg(t.hostname))throw new Lg(t.href);return t}function Fv(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:")return"native";if(Zg(r.hostname))return"native"}return"web"}function Hv(e){let 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??Fv(t.redirect_uris)}}async function Eg(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Ho.parse(JSON.parse(r));return Dr.fromResponse(o)}catch(o){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Dr(Ut.ServerError,n)}}function kg(e,t,r){let o=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} — ${o}. Cause: ${JSON.stringify(t.message)}`)}async function $u(e,t){try{return await xu(e,t)}catch(r){if(r instanceof Dr){if(r.code===Ut.InvalidClient||r.code===Ut.UnauthorizedClient)return kg(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await xu(e,t);else if(r.code===Ut.InvalidGrant||r.code===Ut.InvalidDpopProof)return kg(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await xu(e,t)}throw r}}function Vv(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:n}=e,s=t||r?.scopes_supported?.join(" ")||n.scope;if(s&&o?.scopes_supported?.includes("offline_access")&&!s.split(" ").includes("offline_access")&&n.grant_types?.includes("refresh_token"))s=`${s} offline_access`;return s}async function xu(e,{serverUrl:t,authorizationCode:r,iss:o,scope:n,resourceMetadataUrl:s,fetchFn:i,skipIssuerMetadataValidation:a,forceReauthorization:l}){let u=Hv(e),d=await e.discoveryState?.(),m,f,S,b,y=s;if(!y&&d?.resourceMetadataUrl)y=new URL(d.resourceMetadataUrl);if(d?.authorizationServerUrl){if(f=d.authorizationServerUrl,m=d.resourceMetadata,S=d.authorizationServerMetadata??await Hg(f,{fetchFn:i,skipIssuerValidation:a}),!m)try{m=await Dg(t,{resourceMetadataUrl:y},i)}catch(te){if(te instanceof TypeError)throw te}if(S!==d.authorizationServerMetadata||m!==d.resourceMetadata)await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:S})}else{let te=await Vg(t,{resourceMetadataUrl:y,fetchFn:i,skipIssuerMetadataValidation:a});f=te.authorizationServerUrl,S=te.authorizationServerMetadata,m=te.resourceMetadata,b={authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:S}}let v=S?.issuer??String(f),L={issuer:v};if(await e.saveAuthorizationServerUrl?.(v),r!==void 0){let te=d?.authorizationServerMetadata?.issuer??d?.authorizationServerUrl;if(te===void 0){if(e.saveDiscoveryState!==void 0)throw new wc("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",v);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(!Ug(te,v))throw new wc(te,v)}if(b)await e.saveDiscoveryState?.(b);let F=await Bv(t,e,m),x=F&&m&&!e.validateResourceURL?m.resource:F;if(x)await e.saveResourceUrl?.(Nu(x));let U=Vv({requestedScope:n,resourceMetadata:m,authServerMetadata:S,clientMetadata:e.clientMetadata}),R=await Promise.resolve(e.clientInformation(L)),w=ku(R,v,{canPersistStamp:e.saveClientInformation!==void 0});if(w===void 0&&R?.issuer&&e.saveClientInformation===void 0)throw new wc(R.issuer,v);if(w&&w.issuer===void 0)w={...w,issuer:v},await e.saveClientInformation?.(w,L);if(!w){if(r!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let te=S?.client_id_metadata_document_supported===!0,se=e.clientMetadataUrl;if(se&&!Jv(se))throw new Dr(Ut.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${se}`);if(te&&se)w={client_id:se,issuer:v},await e.saveClientInformation?.(w,L);else{if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");w={...await oz(f,{metadata:S,clientMetadata:u,scope:U,fetchFn:i}),issuer:v},await e.saveClientInformation(w,L)}}let Z=!e.redirectUrl;if(r!==void 0||Z){if(r!==void 0)Ou({iss:o,expectedIssuer:S?.issuer,issParameterSupported:Iu(S)});let te=await rz(e,f,{metadata:S,resource:x,authorizationCode:r,iss:o,scope:U,fetchFn:i});return await e.saveTokens({...te,issuer:v},L),"AUTHORIZED"}let X=ku(await e.tokens(L),v);if(X&&X.issuer===void 0)X={...X,issuer:v},await e.saveTokens(X,L);if(X?.refresh_token&&!l){let te;try{te=await tz(f,{metadata:S,clientInformation:w,refreshToken:X.refresh_token,resource:x,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:i})}catch(se){if(se instanceof Lg)throw se;if(!(se instanceof Dr)||se.code===Ut.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(se instanceof Error?se.message:String(se))}`);else throw se}if(te)return await e.saveTokens({...te,issuer:v},L),"AUTHORIZED"}let Y=e.state?await e.state():void 0,{authorizationUrl:ce,codeVerifier:Ee}=await Qv(f,{metadata:S,clientInformation:w,state:Y,redirectUrl:e.redirectUrl,scope:U,resource:x});return await e.saveCodeVerifier(Ee),await e.redirectToAuthorization(ce),"REDIRECT"}function Jv(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Bv(e,t,r){let o=$f(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(!r)return;if(!Cf({requestedResource:o,configuredResource:r.resource}))throw Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}var Wv=new Set(["bearer","dpop"]);function Ai(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!Wv.has(r.toLowerCase())||!o)return{};let n=vc(e,"resource_metadata")||void 0,s;if(n)try{s=new URL(n)}catch{}let i=vc(e,"scope")||void 0,a=vc(e,"error")||void 0,l=vc(e,"error_description")||void 0;return{resourceMetadataUrl:s,scope:i,error:a,errorDescription:l}}function vc(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),n=r.match(o);if(n){let s=n[1]||n[2];if(s)return s}return null}async function Dg(e,t,r=fetch){let o=await Yv(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.text?.().catch(()=>{}),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.text?.().catch(()=>{}),Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Zo.parse(await o.json())}async function Fg(e,t,r=fetch){let o=Ni(r);try{return await o(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!zg)throw n;if(t)try{return await o(e,{})}catch(s){if(!(s instanceof TypeError))throw s;return}return}}function Kv(e,t="",r={}){if(t.endsWith("/"))t=t.slice(0,-1);return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function $g(e,t,r=fetch){return await Fg(e,{"MCP-Protocol-Version":t},r)}function Gv(e,t){if(!e)return!0;if(t==="/")return!1;return!e.ok&&e.status<500||e.status===502}async function Yv(e,t,r,o){let n=new URL(e),s=o?.protocolVersion??ho,i;if(o?.metadataUrl)i=new URL(o.metadataUrl);else{let l=Kv(t,n.pathname);i=new URL(l,o?.metadataServerUrl??n),i.search=n.search}let a=await $g(i,s,r);if(!o?.metadataUrl&&Gv(a,n.pathname))a=await $g(new URL(`/.well-known/${t}`,n),s,r);return a}function Xv(e){let t=typeof e==="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;if(n.endsWith("/"))n=n.slice(0,-1);return o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"},{url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function Hg(e,{fetchFn:t=fetch,protocolVersion:r=ho,skipIssuerValidation:o=!1}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},s=Xv(e);for(let{url:i,type:a}of s){let l=await Fg(i,n,t);if(!l)continue;if(!l.ok){if(await l.text?.().catch(()=>{}),l.status<500||l.status===502)continue;throw Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}let u=a==="oauth"?Ur.parse(await l.json()):Do.parse(await l.json());if(!o){let d=typeof e==="string"?e:e.href;if(!(u.issuer===d||d.endsWith("/")&&u.issuer===d.slice(0,-1)))throw new Eu("metadata",d,u.issuer)}return u}}async function Vg(e,t){let r,o;try{if(r=await Dg(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0)o=r.authorization_servers[0]}catch(s){if(s instanceof TypeError)throw s}if(!o)o=String(new URL("/",e));let n=await Hg(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function Nu(e){return typeof e==="string"?e:e.href}async function Qv(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(wu))throw Error(`Incompatible auth server: does not support response type ${wu}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Ru))throw Error(`Incompatible auth server: does not support code challenge method ${Ru}`)}else a=new URL("/authorize",e);let l=await bu(),{code_verifier:u,code_challenge:d}=l;if(a.searchParams.set("response_type",wu),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Ru),a.searchParams.set("redirect_uri",String(o)),s)a.searchParams.set("state",s);if(n)a.searchParams.set("scope",n);if(n?.split(" ").includes("offline_access"))a.searchParams.append("prompt","consent");if(i)a.searchParams.set("resource",Nu(i));return{authorizationUrl:a,codeVerifier:u}}function ez(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function Jg(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:s,dpop:i,fetchFn:a}){let l=Dv(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s)r.set("resource",Nu(s));if(!n&&o)jv(Mv(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let d=async()=>{let S=new Headers(u);if(n)await n(S,r,l,t);if(i)S.set("DPoP",await i.buildProof({htm:"POST",htu:l}));return Ni(a??fetch)(l,{method:"POST",headers:S,body:r})},m=await d();if(i&&m.status===400){if((await m.clone().json().catch(()=>{}))?.error===Ut.UseDpopNonce)i.observeNonce(m,l),m=await d()}if(i?.observeNonce(m,l),!m.ok)throw await Eg(m);let f=await m.json();try{return Fo.parse(nu(f))}catch(S){if(typeof f==="object"&&f!==null&&"error"in f)throw await Eg(JSON.stringify(f));throw S}}async function tz(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:s,dpop:i,fetchFn:a}){return{refresh_token:o,...await Jg(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:s,resource:n,dpop:i,fetchFn:a})}}async function rz(e,t,{metadata:r,resource:o,authorizationCode:n,iss:s,scope:i,fetchFn:a}={}){if(n!==void 0)Ou({iss:s,expectedIssuer:r?.issuer,issParameterSupported:Iu(r)});let l=r?.issuer??String(t),u=async()=>{let S=await e.clientInformation({issuer:l}),b=ku(S,l,{canPersistStamp:!1});if(S&&b===void 0)throw new wc(String(S.issuer),l);return b},d=await u(),m=i??e.clientMetadata.scope,f;if(e.prepareTokenRequest)f=await e.prepareTokenRequest(m);if(!f){if(!n)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");f=ez(n,await e.codeVerifier(),e.redirectUrl)}return d??=await u(),Jg(t,{metadata:r,tokenRequestParams:f,clientInformation:d,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:a})}async function oz(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:n}){let s;if(t){if(!t.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);let i={...r,...o===void 0?{}:{scope:o}},a=await Ni(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!a.ok)throw new $v({status:a.status,body:await a.text(),submittedMetadata:i});return Vo.parse(nu(await a.json()))}var zc=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),nz=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(Pu(e))}set(e,t){let r=Pu(e),o=zc.has(e.method),n=!this._entries.has(r);if(!o&&n&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let i of this._entries.keys())if(!zc.has(i.slice(0,i.indexOf("\x00")))){this._entries.delete(i),this._cappedSize--;break}}let s=++this._stamp;if(this._entries.set(r,{...t,stamp:s}),n&&!o)this._cappedSize++;return s}delete(e){if(this._entries.delete(Pu(e))&&!zc.has(e.method))this._cappedSize--}evict(e){let t=`${e}\x00`,r=zc.has(e);for(let o of this._entries.keys())if(o.startsWith(t)){if(this._entries.delete(o),!r)this._cappedSize--}}clear(){this._entries.clear(),this._cappedSize=0}};function Pu(e){return`${e.method}\x00${JSON.stringify([e.partition??"",e.params??""])}`}function Tu(e,t){return t===void 0?e:`${e}\x00${t}`}var sz=86400000,iz=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,r=()=>{},o="",n=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=r,this._cachePartition=o,this._now=n}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){let r={method:e,params:t??""},o=this._partitionFor("private"),n=await this._store.get({...r,partition:o});if(n!==void 0)return n;let s=this._partitionFor("public");if(s===o)return;let i=await this._store.get({...r,partition:s});return i?.scope==="public"?i:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){let r=this._partitionFor("private"),o=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:r})}catch(n){this._reportError(n)}if(o!==r)try{await this._store.delete({method:e,params:t,partition:o})}catch(n){this._reportError(n)}}async evictKey(e,t){let r=Tu(e,t),o=this._evictionGeneration.get(r);if(o!==void 0)this._evictionGeneration.set(r,o+1);await this._deleteBoth(e,t)}captureGeneration(e,t){let r=Tu(e,t),o=this._evictionGeneration.get(r)??0;return this._evictionGeneration.set(r,o),o}async write(e,t,r,o){if((this._evictionGeneration.get(Tu(e,o?.params))??0)!==r)return;let n=o?.params??"",s=this._partitionFor("private"),i=this._partitionFor("public"),a=(o?.scope??"private")==="public"?i:s;try{await this._store.set({method:e,params:n,partition:a},{value:az(t),expiresAt:o?.expiresAt,scope:o?.scope})}catch(l){this._reportError(l)}if(i!==s)try{await this._store.delete({method:e,params:n,partition:a===s?i:s})}catch(l){this._reportError(l)}}async read(e,t){let r=await this._probe(e,t);if(r?.expiresAt===void 0||!(r.expiresAt>this.now()))return;try{let o=JSON.parse(r.value);if(typeof o!=="object"||o===null||Array.isArray(o))throw TypeError("cached document is not an object");return{value:o}}catch(o){this._reportError(o),await this._deleteBoth(e,t??"");return}}resetForReconnect(){if(!this._isUserSupplied)this._store.clear();this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){let t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let r=this._decodeListTools(t),o=new Map;if(r!==void 0)for(let n of r.tools)o.set(n.name,n);this._toolIndex={stamp:t.stamp,byName:o}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let r=await this._probe("tools/list");if(r===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==r.stamp){let o=this._decodeListTools(r)??{tools:[]},n=new Map;for(let s of o.tools){let i=t(s);if(i!==void 0)n.set(s.name,i)}this._toolOutputValidatorIndex={stamp:r.stamp,byName:n}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every((r)=>r!==null&&typeof r==="object"))throw TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};function az(e){let t;try{t=JSON.stringify(e)}catch(r){throw TypeError(`cache value is not JSON-serializable: ${r instanceof Error?r.message:String(r)}`)}if(typeof t!=="string")throw TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}var Bg=Symbol.for("mcp.authSeamEscape");function Xe(e){if(typeof e==="object"&&e!==null||typeof e==="function")try{Object.defineProperty(e,Bg,{value:!0,configurable:!0})}catch{}return e}function cz(e){return(typeof e==="object"&&e!==null||typeof e==="function")&&e[Bg]===!0}var lz=-32022,uz=new Set([-32001,-32020,-32021]);function dz(e,t){switch(e.kind){case"result":return pz(e.result,t);case"rpc-error":return Wg(e,t);case"http-error":return hz(e,t);case"network-error":return Cg(e.error,t);case"unusable-reply":return{kind:"error",error:new N(O.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${Kg(e.error)})`,{cause:e.error},{cause:e.error})};case"auth-required":return{kind:"error",error:e.error};case"closed":if(t.transportKind==="stdio")return{kind:"legacy"};return Cg(Error("Connection closed during the version negotiation probe"),t);case"timeout":if(t.transportKind==="stdio")return{kind:"legacy"};return{kind:"error",error:new N(O.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function pz(e,t){let r=Lt(gc).validateResult("server/discover",e);if(!r.ok)return{kind:"legacy"};let o=r.value.supportedVersions,n=t.clientModernVersions.find((s)=>o.includes(s));if(n!==void 0)return{kind:"modern",version:n,discover:r.value};if(t.fallbackAvailable)return{kind:"legacy"};return{kind:"error",error:new fc({supported:[...o],requested:t.requestedVersion})}}function Wg(e,t){let{code:r,message:o,data:n}=e;if(r===lz){let s=fz(n);if(s===void 0)return{kind:"legacy"};let i=new fc({supported:s,requested:gz(n)??t.requestedVersion},o),a=Oi(s),l=t.clientModernVersions.find((u)=>a.includes(u));if(l!==void 0)return{kind:"corrective",version:l,error:i};if(a.length>0)return{kind:"error",error:i};return t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:i}}if(uz.has(r))return{kind:"legacy"};return{kind:"legacy"}}function hz(e,t){if(e.status===401||e.status===403){let o=e.status===403;return{kind:"error",error:new vt(o?O.ClientHttpForbidden:O.ClientHttpAuthentication,`Version negotiation failed: ${o?"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 vt(O.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let r=Sz(e.body);if(r!==void 0)return Wg(r,t);return{kind:"legacy"}}function Cg(e,t){if(t.environment==="browser"&&mz(e))return{kind:"legacy"};return{kind:"error",error:new N(O.EraNegotiationFailed,`Version negotiation probe failed: ${Kg(e)}`,{cause:e},{cause:e})}}function mz(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function Kg(e){return e instanceof Error?e.message:String(e)}function fz(e){if(typeof e!=="object"||e===null)return;let t=e.supported;if(!Array.isArray(t)||t.length===0||!t.every((r)=>typeof r==="string"))return;return t}function gz(e){if(typeof e!=="object"||e===null)return;let t=e.requested;return typeof t==="string"?t:void 0}function Sz(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=="object"||t===null)return;let r=t.error;if(typeof r!=="object"||r===null)return;let{code:o,message:n,data:s}=r;if(typeof o!=="number")return;return{code:o,message:typeof n==="string"?n:"",data:s}}var _z="legacy";function bz(e,t){let r=e?.mode??_z;if(r==="legacy")return{kind:"legacy"};let o=e?.probe??{};if(typeof r==="object"){if(!Zt(r.pin))throw TypeError(`versionNegotiation: { pin: '${r.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:r.pin,probe:o}}let n=t?Oi(t):[];return{kind:"auto",modernVersions:n.length>0?n:[...su],fallbackAvailable:t?iu(t).length>0:!0,probe:o}}function Ig(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function Og(e){return"stderr"in e&&"pid"in e?"stdio":"http"}var yz=class e{_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){let r=new e(t);t.onmessage=(o)=>{let n=r._pending;if(n!==void 0&&(Bo(o)||Wo(o))&&o.id===n.id){if(r._pending=void 0,Bo(o))n.resolve({kind:"response",result:o.result});else n.resolve({kind:"response",error:o.error});return}},t.onerror=(o)=>{r._savedOnError?.(o)},t.onclose=()=>{let o=r._pending;if(o!==void 0)r._pending=void 0,o.resolve({kind:"closed"});r._closeDelivered=!0,r._savedOnClose?.()};try{await t.start()}catch(o){throw r.detach(),o}return r}async exchange(t,r){let o=`server-discover-probe-${++this._probeCounter}`;return new Promise((n)=>{let s=!1,i=(l)=>{if(s)return;if(s=!0,clearTimeout(a),this._pending?.id===o)this._pending=void 0;n(l)},a=setTimeout(()=>i({kind:"timeout"}),r);this._pending={id:o,resolve:i},this._transport.send(t(o)).catch((l)=>i({kind:"send-error",error:l}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let t=this._savedOnClose,r=this._transport,o=!1,n=()=>{if(!o){o=!0;return}t()};r.onclose=n,Cu.set(r,()=>{if(r.onclose===n)r.onclose=t})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let t=this._transport,r=t.start,o=!0;t.start=async function(){if(o){o=!1,t.start=r;return}return r.call(t)}}},Cu=new WeakMap;function Ng(e){let t=Cu.get(e);Cu.delete(e),t?.()}function vz(e,t,r,o){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:Lt(t).outboundEnvelope({protocolVersion:t,clientInfo:r,clientCapabilities:o})}}}function zz(e){if(e instanceof N&&e.code===O.ClientHttpUnexpectedContent)return!0;return e instanceof Error&&e.name==="SyntaxError"}function wz(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":{let r=e.error;if(cz(r)||r instanceof wt||r instanceof Error&&r.name==="UnauthorizedError")return{kind:"auth-required",error:r};if(r instanceof vt){let o=r.data?.text;return{kind:"http-error",status:r.data.status,body:typeof o==="string"?o:void 0,statusText:r.data.statusText}}if(zz(r))return{kind:"unusable-reply",error:r};return{kind:"network-error",error:r}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function Gg(e,t){let r=e.probe.timeoutMs??t.defaultTimeoutMs,o=Math.max(0,e.probe.maxRetries??0),n=e.kind==="pin"?[e.version]:e.modernVersions,s=e.kind==="auto"&&e.fallbackAvailable,i=await yz.open(t.transport),a=async()=>{let u=n[0],d=!1,m=o;for(;;){let f=await i.exchange((y)=>vz(y,u,t.clientInfo,t.capabilities),r);if(f.kind==="timeout"&&m>0){m--;continue}let S=wz(f,r),b=dz(S,{clientModernVersions:n,requestedVersion:u,fallbackAvailable:s,environment:t.environment,transportKind:t.transportKind});switch(b.kind){case"modern":return{era:"modern",version:b.version,discover:b.discover};case"corrective":if(d)throw b.error;d=!0,u=b.version;continue;case"legacy":{let y=S.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new N(O.EraNegotiationFailed,y===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: ${y} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new N(O.EraNegotiationFailed,y===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: ${y} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(y!==void 0&&t.disposableProbe!==!0)throw new N(O.EraNegotiationFailed,`Version negotiation failed: ${y} (this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw b.error}}},l;try{l=await a()}catch(u){throw i.detach(),u}return i.release(),l}function Rz(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;let r=e._serverParams;return typeof r==="object"&&r!==null&&typeof r.command==="string"?r:void 0}async function xz(e,t,r,o){let s=new t.constructor({...r,stderr:"ignore"}),i=t.close,a=!1,l,u=new Promise((m,f)=>{l=()=>f(qg())});t.close=async function(){return a=!0,l?.(),i.call(t)};let d;try{let m=Gg(e,{...o,transport:s,transportKind:"stdio",disposableProbe:!0});m.catch(()=>{}),d=await Promise.race([m,u])}finally{await Pz(s),t.close=i}if(a)throw qg();return d}function qg(){return new N(O.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function Pz(e){try{let t=e._dispose;await(typeof t==="function"?t.call(e):e.close())}catch{}}function Ag(e){let t=e._meta?.[Ot];return ug.Implementation(t)?t:void 0}function Rc(e,t){if(!e||t===null||typeof t!=="object")return;if(e.type==="object"&&e.properties&&typeof e.properties==="object"){let r=t,o=e.properties;for(let n of Object.keys(o)){let s=o[n];if(r[n]===void 0&&Object.prototype.hasOwnProperty.call(s,"default"))r[n]=s.default;if(r[n]!==void 0)Rc(s,r[n])}}if(Array.isArray(e.anyOf)){for(let r of e.anyOf)if(typeof r!=="boolean")Rc(r,t)}if(Array.isArray(e.oneOf)){for(let r of e.oneOf)if(typeof r!=="boolean")Rc(r,t)}}function Tz(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}function Ez(e){if(typeof e==="object"&&e!==null){if(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e))return e;if(e.kind==="modern"&&rr.safeParse(e.discover).success)return e}throw new N(O.EraNegotiationFailed,"connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }")}var Mg={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},kz=64,Yg=class extends bc{_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){let e=new N(O.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(let 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);if(this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Su,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=ig(t?.inputRequired),this._cache=new iz(t?.responseCacheStore??new nz,t?.responseCacheStore!==void 0,(r)=>this._reportStoreError(r),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??kz,t?.listChanged)this._listChangedConfig=t.listChanged}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&Zt(this._negotiatedProtocolVersion)&&Fr(e))return"drop"}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){if(!this._inputRequiredDriverConfig.autoFulfill)return Promise.reject(new N(O.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}));return pg({getRequestHandler:(r)=>this._getRequestHandler(r),buildContext:(r)=>this.buildContext(r,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t)}_setupListChangedHandlers(e){if(e.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools);if(e.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts);if(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 Error("Cannot register capabilities after connecting to transport");this._capabilities=dg(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){if(e==="elicitation/create")return async(r,o)=>{let n=Lt(this._negotiatedProtocolVersion),s=n.validateRequest("elicitation/create",r);if(!s.ok&&s.reason==="not-in-era")s=n.validateInputRequest("elicitation/create",r);if(!s.ok)throw new ee(s.reason==="not-in-era"?W.InternalError:W.InvalidParams,s.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${s.message}`);let{params:i}=s.value;i.mode=i.mode??"form";let{supportsFormMode:a,supportsUrlMode:l}=Tz(this._capabilities.elicitation);if(i.mode==="form"&&!a)throw new ee(W.InvalidParams,"Client does not support form-mode elicitation requests");if(i.mode==="url"&&!l)throw new ee(W.InvalidParams,"Client does not support URL-mode elicitation requests");let u=await t(r,o),d=n.validateResult("elicitation/create",u);if(!d.ok&&d.reason==="not-in-era")d=n.validateInputResponse("elicitation/create",u);if(!d.ok)throw new ee(d.reason==="not-in-era"?W.InternalError:W.InvalidParams,d.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${d.message}`);let m=d.value,f=i.mode==="form"?i.requestedSchema:void 0;if(i.mode==="form"&&m.action==="accept"&&m.content&&f&&this._capabilities.elicitation?.form?.applyDefaults)try{Rc(f,m.content)}catch{}return m};if(e==="sampling/createMessage")return async(r,o)=>{let n=Lt(this._negotiatedProtocolVersion),s=n.validateRequest("sampling/createMessage",r);if(!s.ok&&s.reason==="not-in-era")s=n.validateInputRequest("sampling/createMessage",r);if(!s.ok)throw new ee(s.reason==="not-in-era"?W.InternalError:W.InvalidParams,s.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${s.message}`);let{params:i}=s.value,a=await t(r,o),l=Boolean(i.tools||i.toolChoice),u=n.samplingResultVariant(l,a);if(!u.ok&&u.reason==="not-in-era")u=n.validateInputResponse("sampling/createMessage",a);if(!u.ok)throw new ee(u.reason==="not-in-era"?W.InternalError:W.InvalidParams,u.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${u.message}`);return u.value};return t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new N(O.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,Ez(t.prior),t);let r=bz(this._versionNegotiation,this._supportedProtocolVersionsOption);if(r.kind!=="legacy")return this._connectNegotiated(e,r,t);return this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let r=this._negotiatedProtocolVersion;if(r!==void 0)e.setProtocolVersion?.(r);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let r=iu(this._supportedProtocolVersions);try{let o=r[0];if(o===void 0)throw new N(O.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let n=await this.request({method:"initialize",params:{protocolVersion:o,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!r.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);if(this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion)e.setProtocolVersion(n.protocolVersion);if(this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=n.protocolVersion,this._listChangedConfig)this._setupListChangedHandlers(this._listChangedConfig)}catch(o){throw this.close(),o}}async _connectNegotiated(e,t,r){if(e.sessionId!==void 0){await super.connect(e);let n=this._negotiatedProtocolVersion;if(n!==void 0&&e.setProtocolVersion)e.setProtocolVersion(n);return}this._resetConnectionState();let o;try{let n=Og(e),s={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:Ig(),defaultTimeoutMs:r?.timeout??_c},i=n==="stdio"?Rz(e):void 0;o=i===void 0?await Gg(t,{...s,transport:e,transportKind:n}):await xz(t,e,i,s)}catch(n){throw await e.close().catch(()=>{}),Ng(e),n}if(Ng(e),await super.connect(e),o.era==="legacy"){await this._legacyHandshake(e,r);return}if(this._serverCapabilities=o.discover.capabilities,this._serverVersion=Ag(o.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.discover.instructions,this._discoverResult=o.discover,this._negotiatedProtocolVersion=o.version,e.setProtocolVersion)e.setProtocolVersion(o.version);if(this._listChangedConfig){let n=this._listChangedConfig,s=this._serverCapabilities,i={...n.tools&&s?.tools?.listChanged&&{tools:n.tools},...n.prompts&&s?.prompts?.listChanged&&{prompts:n.prompts},...n.resources&&s?.resources?.listChanged&&{resources:n.resources}},a=!0;try{this._setupListChangedHandlers(i)}catch(u){a=!1,this.onerror?.(u instanceof Error?u:Error(String(u)))}let l=a?{...i.tools&&{toolsListChanged:!0},...i.prompts&&{promptsListChanged:!0},...i.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(l).length>0){let u=new AbortController,d=()=>u.abort(r?.signal?.reason);if(r?.signal?.aborted)d();r?.signal?.addEventListener("abort",d);try{this._autoOpenedSubscription=await this.listen(l,{timeout:r?.timeout,signal:u.signal})}catch(m){if(r?.signal?.aborted)throw await this.close().catch(()=>{}),m;this.onerror?.(m instanceof Error?m:Error(String(m)))}finally{r?.signal?.removeEventListener("abort",d)}}}}async _connectFromPrior(e,t,r){if(t.kind==="legacy")return this._connectPlainLegacy(e,r);let o=t.discover;this._resetConnectionState();let n=this._supportedProtocolVersionsOption,s=(n&&Oi(n).length>0?Oi(n):su).find((i)=>o.supportedVersions.includes(i));if(s===void 0)throw new N(O.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=o,this._serverCapabilities=o.capabilities,this._serverVersion=Ag(o),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.instructions,this._negotiatedProtocolVersion=s,e.setProtocolVersion?.(s),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(i){this.onerror?.(i instanceof Error?i:Error(String(i)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;if(t!==void 0)return`${t.name}@${t.version}`;return e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return Zt(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new N(O.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new N(O.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 N(O.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new N(O.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new N(O.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new N(O.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new N(O.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new N(O.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new N(O.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new N(O.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){let t=await this._requestWithSchema({method:"server/discover"},rr,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);let r=await this._serveFromCache("prompts/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("prompts/list",e,t,(o)=>o.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);let r=await this._serveFromCache("resources/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("resources/list",e,t,(o)=>o.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);let r=await this._serveFromCache("resources/templates/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("resources/templates/list",e,t,(o)=>o.resourceTemplates)}async _listAllPages(e,t,r,o,n){let s=r?.cacheMode==="bypass",i=this._cache.captureGeneration(e),a=await this.request({method:e,...t&&{params:{...t}}},r),l=a.nextCursor,u=a,d=1;while(l!==void 0){if(this._listMaxPages!==0&&d>=this._listMaxPages)throw new N(O.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});let m=await this.request({method:e,params:{...t,cursor:l}},r);if(m.nextCursor===l&&JSON.stringify(o(m))===JSON.stringify(o(u)))break;o(a).push(...o(m)),u=m,l=m.nextCursor,d++}if(delete a.nextCursor,n?.(a),s)return a;return await this._cache.write(e,a,i,this._freshness(a)),a}_freshness(e,t){let r=e,o=typeof r.ttlMs==="number"?r.ttlMs:this._defaultCacheTtlMs,n=r.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,o),sz),scope:n,params:t}}async _serveFromCache(e,t,r){if(r?.cacheMode==="bypass"||r?.cacheMode==="refresh")return;let o=await this._cache.read(e,t).catch((n)=>void this._reportStoreError(n));if(o!==void 0){if(r?.signal?.aborted){let n=r.signal.reason;throw n instanceof N?n:new N(O.RequestTimeout,String(n))}return o.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}_compileOutputValidator(e){if(!e.outputSchema)return;try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){let r=t??await this._cache.toolDefinition(e);return r===void 0?void 0:hu(r.inputSchema)}async readResource(e,t){let r=await this._serveFromCache("resources/read",e.uri,t);if(r!==void 0)return r;let o=this._cache.captureGeneration("resources/read",e.uri),n=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){let s=this._freshness(n,e.uri);if(s.expiresAt>this._cache.now())await this._cache.write("resources/read",n,o,s);else if(t?.cacheMode==="refresh")await this._cache.evictKey("resources/read",e.uri)}return n}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 N(O.NotConnected,"Not connected");let r=this._negotiatedProtocolVersion;if(r===void 0||!Zt(r))throw new N(O.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${r??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:r});if(t?.signal?.aborted){let x=t.signal.reason;throw x instanceof N?x:new N(O.RequestTimeout,String(x))}let o=new AbortController,n=`listen:${this._nextListenId++}`,s="opening",i,a,l,u,d=new Promise((x,U)=>{l=x,u=U}),m,f=new Promise((x)=>{m=x}),S=(x)=>{if(s==="closed")return;let U=s==="opening";if(i!==void 0)clearTimeout(i),i=void 0;if("ack"in x){s="open",l(x.ack);return}if(s="closed",a!==void 0)t?.signal?.removeEventListener("abort",a);if(this._listenState.delete(n),o.abort(),m(x.cause),U)u(x.error??new N(O.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},b=async()=>{o.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:n}}).catch(()=>{})},y=async()=>{if(s==="closed")return;S({cause:"local"}),await b()};this._listenState.set(n,{settle:S});let v=t?.timeout??_c;if(i=setTimeout(()=>{S({cause:"remote",error:new N(O.RequestTimeout,"subscriptions/listen ack timed out",{timeout:v})}),b().catch(()=>{})},v),t?.signal){let x=t.signal;a=()=>{if(s==="closed")return;let U=x.reason;S({cause:"local",error:U instanceof Error?U:Error(String(U??"Aborted"))}),b().catch(()=>{})},x.addEventListener("abort",a,{once:!0})}let L={jsonrpc:"2.0",id:n,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}},F=(x)=>{S({cause:"remote",error:x instanceof Error?x:Error(String(x))})};try{this.transport.send(L,{requestSignal:o.signal,onRequestStreamEnd:()=>S({cause:"remote",error:Error("subscriptions/listen: stream ended")})}).catch(F)}catch(x){F(x)}return{honoredFilter:await d,close:y,closed:f}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let r=Object.hasOwn(Mg,e.method)?Mg[e.method]:void 0;if(e.method==="notifications/resources/updated"){let o=e.params?.uri;if(typeof o==="string")this._cache.evictKey("resources/read",o)}else if(r!==void 0)for(let o of r)this._cache.evict(o);if(e.method==="notifications/subscriptions/acknowledged"){let o=e.params?._meta?.[Wn],n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){let s=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);n.settle({ack:s.ok?s.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){let o=e.params?.requestId,n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){n.settle({cause:"remote",error:Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,r=typeof t==="string"?this._listenState.get(t):void 0;if(r!==void 0){if(Wo(e))r.settle({cause:"remote",error:ee.fromError(e.error.code,e.error.message,e.error.data)});else r.settle({cause:"graceful",error:new N(O.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new N(O.ConnectionClosed,"Connection closed");for(let t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let r=this.getProtocolEra()==="modern"&&Ig()!=="browser",o=async()=>{if(!r)return t;let l;try{l=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(d){this._reportStoreError(d)}if(!l?.valid||l.declarations.length===0)return t;let u=og(l.declarations,e.arguments);return Object.keys(u).length===0?t:{...t,headers:{...t?.headers,...u}}},n=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,(l)=>this._compileOutputValidator(l)).catch((l)=>void this._reportStoreError(l)):this._compileOutputValidator(t.toolDefinition),s=()=>{if(n===void 0||n.ok)return;let l=n.compileError,u=(l instanceof Error?l.message:String(l)).slice(0,200);throw new ee(W.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${u}`)};s();let i;try{i=await this.request({method:"tools/call",params:e},await o())}catch(l){let u=l instanceof ee&&l.code===Jo;if(!r||!u||t?.toolDefinition!==void 0)throw l;let d={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,d).catch((m)=>this._reportStoreError(m)),n=await this._cache.outputValidator(e.name,(m)=>this._compileOutputValidator(m)).catch((m)=>void this._reportStoreError(m)),s(),i=await this.request({method:"tools/call",params:e},await o())}let a=n!==void 0&&n.ok?n.validator:void 0;if(a){if(i.structuredContent===void 0&&!i.isError)throw new ee(W.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent!==void 0&&!i.isError)try{let l=a(i.structuredContent);if(!l.valid)throw new ee(W.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)}catch(l){if(l instanceof ee)throw l;throw new ee(W.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)}}return i}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){let o=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(o),o}let r=await this._serveFromCache("tools/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("tools/list",e,t,(o)=>o.tools,(o)=>this._excludeInvalidXMcpHeaderTools(o))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||Og(this.transport)==="stdio")return;let t=e.tools.filter((r)=>{let o=hu(r.inputSchema);if(!o.valid)return console.warn(`[mcp-sdk] excluding tool '${r.name}' from tools/list: invalid x-mcp-header declaration — ${o.reason}`),!1;return!0});if(t.length!==e.tools.length)e.tools=t}_setupListChangedHandler(e,t,r,o){let n=Sc(Hs,r);if(!n.success)throw Error(`Invalid ${e} listChanged options: ${n.error.message}`);if(typeof r.onChanged!=="function")throw TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:i}=n.data,{onChanged:a}=r,l=async()=>{if(!s){a(null,null);return}try{a(null,await o())}catch(d){a(d instanceof Error?d:Error(String(d)),null)}},u=()=>{if(i){let d=this._listChangedDebounceTimers.get(e);if(d)clearTimeout(d);let m=setTimeout(l,i);this._listChangedDebounceTimers.set(e,m)}else l()};this.setNotificationHandler(t,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function $z(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function Cz(e){if(e.status!==401)return!1;let t=e.headers.get("www-authenticate")??"";return $z(t)&&/use_dpop_nonce/i.test(t)}var Iz=(e,t)=>(r)=>{let o=typeof e==="function"?e:()=>e;return async(n,s)=>{let i=(s?.method??"GET").toUpperCase(),a=new URL(n.toString()),l=await o();if(!l)return r(n,s);let u=async()=>{let m=await t();if(!m)return r(n,s);let f=new Headers(s?.headers),S=await l.buildProof({htm:i,htu:a,accessToken:m});return f.set("Authorization",`DPoP ${m}`),f.set("DPoP",S),r(n,{...s,headers:f})},d=await u();if(Cz(d)&&d.headers.has("dpop-nonce"))l.observeNonce(d,a),await d.text?.().catch(()=>{}),d=await u();return l.observeNonce(d,a),d}},Oz=(e)=>Iz(async()=>{try{return await e.dpop?.()}catch(t){throw Xe(t)}},async()=>{let t;try{t=await e.tokens()}catch(r){throw Xe(r)}return t?.token_type?.toLowerCase()==="dpop"?t.access_token:void 0});var _P=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e,t,r){super(`SSE error: ${t}`);this.code=e,this.event=r,Zr(this,new.target)}};var Nz=1,qz={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2},Az=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function jg(e,t){if(typeof AbortSignal.any==="function")return AbortSignal.any([e,t]);let r=new AbortController;if(e.aborted)return r.abort(e.reason),r.signal;if(t.aborted)return r.abort(t.reason),r.signal;let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",s)};function n(){o(),r.abort(e.reason)}function s(){o(),r.abort(t.reason)}return e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",s,{once:!0}),r.signal}var Xg=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){if(this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,Cv(t?.authProvider)){if(this._oauthProvider=t.authProvider,this._authProvider=Ov(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop)this._fetch=Oz(t.authProvider)(t.fetch??fetch)}else this._authProvider=t?.authProvider;if(this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=mg(t?.fetch,t?.requestInit),this._redirectPolicy==="follow")this._fetchWithInit=Sg(this._fetchWithInit);this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??qz,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??Nz)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(r){throw Xe(r)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new Tg({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new Tg({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new vt(O.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});if(e.resourceMetadataUrl)this._resourceMetadataUrl=e.resourceMetadataUrl;let r=await this._oauthProvider.tokens(),o=zu(this._scope,r?.scope,e.scope);this._scope=o;let n=Nv(o,r?.scope);return $u(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:o,forceReauthorization:n,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return this._redirectPolicy==="follow"?e:Ni(e)}_unfollowedRedirect(e,t){let r=this._redirectPolicy==="follow"?void 0:_g(e,t);return r&&`${r} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let e=new Headers(this._requestInit?.headers||void 0),t;try{t=await this._authProvider?.token()}catch(r){throw Xe(r)}if(t)e.set("Authorization",`Bearer ${t}`);if(this._sessionId)e.set("mcp-session-id",this._sessionId);if(this._protocolVersion)e.set("mcp-protocol-version",this._protocolVersion);return e}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!Fr(t))return;let r=t.params?._meta?.[It];if(typeof r!=="string")return;e.set("mcp-protocol-version",r),e.set("mcp-method",t.method);let o=ng(t.method,t.params);if(o?.value!==void 0)e.set("mcp-name",mu(o.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Fr(e))return!1;let t=e.params?._meta?.[It];return typeof t==="string"&&Zt(t)}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:o,requestSignal:n}=e,s=()=>this._abortController?.signal.aborted===!0||n?.aborted===!0;try{let i=await this._commonHeaders(),a=[...i.get("accept")?.split(",").map((m)=>m.trim().toLowerCase())??[],"text/event-stream"];if(i.set("accept",[...new Set(a)].join(", ")),o)i.set("last-event-id",o);let l=this._abortController?.signal,u=n!==void 0&&l!==void 0?jg(l,n):n??l,d=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:i,signal:u});if(!d.ok){if(d.status===401&&this._authProvider){if(d.headers.has("www-authenticate")){let{resourceMetadataUrl:f,scope:S}=Ai(d);this._resourceMetadataUrl=f,this._scope=zu(this._scope,S)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:d,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(f){throw Xe(f)}return await d.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r)}if(await d.text?.().catch(()=>{}),t)throw Xe(new vt(O.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:d.statusText}));throw Xe(new wt)}if(d.status===403){let{resourceMetadataUrl:f,scope:S,error:b,errorDescription:y}=Ai(d);if(b==="insufficient_scope"){let v=await d.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:S,resourceMetadataUrl:f,errorDescription:y,statusText:d.statusText,text:v},r)!=="AUTHORIZED")throw Xe(new wt);return this._startOrAuthSse(e,t,r+1)}}if(await d.text?.().catch(()=>{}),d.status===405){e.onRequestStreamEnd?.();return}let m=this._unfollowedRedirect(this._url,d)??d.statusText;throw new vt(O.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${m}`,{status:d.status,statusText:d.statusText})}this._handleSseStream(d.body,e,!0)}catch(i){if(!s())this.onerror?.(i);throw i}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(Error(`Maximum reconnection attempts (${r}) exceeded.`)),e.onRequestStreamEnd?.();return}let o=this._getNextReconnectionDelay(t),n=()=>{if(this._cancelReconnection=void 0,this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this._startOrAuthSse(e).catch((s)=>{if(this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this.onerror?.(Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`));try{this._scheduleReconnection(e,t+1)}catch(i){this.onerror?.(i instanceof Error?i:Error(String(i)))}})};if(this._reconnectionScheduler){let s=this._reconnectionScheduler(n,o,t);this._cancelReconnection=typeof s==="function"?s:void 0}else{let s=setTimeout(n,o);this._cancelReconnection=()=>clearTimeout(s)}}_handleSseStream(e,t,r){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i}=t,a=()=>this._abortController?.signal.aborted===!0||s?.aborted===!0,l,u=!1,d=!1;(async()=>{try{let f=e.pipeThrough(new TextDecoderStream).pipeThrough(new vu({onRetry:(S)=>{this._serverRetryMs=S}})).getReader();while(!0){let{value:S,done:b}=await f.read();if(b)break;if(S.id)l=S.id,u=!0,o?.(S.id);if(!S.data)continue;if(!S.event||S.event==="message")try{let y=st.parse(JSON.parse(S.data));if(Bo(y)||Wo(y)){if(d=!0,n!==void 0)y.id=n}this.onmessage?.(y)}catch(y){this.onerror?.(y)}}if((r||u)&&!d&&this._abortController&&!a())this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i},0);else if(!a())i?.()}catch(f){if(a())return;if(this.onerror?.(Error(`SSE stream disconnected: ${f}`)),(r||u)&&!d&&this._abortController&&!a())try{this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i},0)}catch(S){this.onerror?.(Error(`Failed to reconnect: ${S instanceof Error?S.message:String(S)}`)),i?.()}else i?.()}})()}async start(){if(this._abortController)throw 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 wt("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:o}=await qv(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await $u(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:o,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new wt("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,r,o=0){try{let{resumptionToken:n,onresumptiontoken:s}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Fr(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch((v)=>this.onerror?.(v));return}let i=await this._commonHeaders();this._applyBodyDerivedHeaders(i,e);let a=Array.isArray(e)?e.some((v)=>pu(v)):pu(e);if(a)i.delete("mcp-session-id");if(t?.headers!==void 0)for(let[v,L]of Object.entries(t.headers)){if(Az.has(v.toLowerCase()))continue;i.set(v,L)}i.set("content-type","application/json");let l=[...i.get("accept")?.split(",").map((v)=>v.trim().toLowerCase())??[],"application/json","text/event-stream"];i.set("accept",[...new Set(l)].join(", "));let u=this._abortController?.signal,d=t?.requestSignal!==void 0&&u!==void 0?jg(u,t.requestSignal):t?.requestSignal??u,m={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(e),signal:d},f=await this._redirects(this._fetch??fetch)(this._url,m);if(a&&f.ok)this._sessionId=f.headers.get("mcp-session-id")||void 0;if(!f.ok){if(f.status===401&&this._authProvider){if(f.headers.has("www-authenticate")){let{resourceMetadataUrl:F,scope:x}=Ai(f);this._resourceMetadataUrl=F,this._scope=zu(this._scope,x)}if(this._authProvider.onUnauthorized&&!r){try{await this._authProvider.onUnauthorized({response:f,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(F){throw Xe(F)}return await f.text?.().catch(()=>{}),this._send(e,t,!0,o)}if(await f.text?.().catch(()=>{}),r)throw Xe(new vt(O.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:f.statusText}));throw Xe(new wt)}let v=await f.text?.().catch(()=>null);if(f.status===403){let{resourceMetadataUrl:F,scope:x,error:U,errorDescription:R}=Ai(f);if(U==="insufficient_scope"){if(await this._stepUpAuthorize({scope:x,resourceMetadataUrl:F,errorDescription:R,statusText:f.statusText,text:v},o)!=="AUTHORIZED")throw Xe(new wt);return this._send(e,t,r,o+1)}}if(f.status===400&&typeof v==="string"&&this._isModernEnvelopedRequest(e))try{let F=st.parse(JSON.parse(v)),x=(Array.isArray(e)?e:[e]).filter((U)=>Fr(U));if(Wo(F)&&x.some((U)=>U.id===F.id)){this.onmessage?.(F);return}}catch{}let L=this._unfollowedRedirect(this._url,f)??v;throw new vt(O.ClientHttpNotImplemented,`Error POSTing to endpoint: ${L}`,{status:f.status,statusText:f.statusText,text:v})}if(f.status===202){if(await f.text?.().catch(()=>{}),eg(e))this._startOrAuthSse({resumptionToken:void 0}).catch((v)=>this.onerror?.(v));return}let S=(Array.isArray(e)?e:[e]).some((v)=>("method"in v)&&("id"in v)&&v.id!==void 0),b=f.headers.get("content-type"),y=hg(b);if(S)if(y==="text/event-stream")this._handleSseStream(f.body,{onresumptiontoken:s,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(y==="application/json"){let v=await f.json(),L=Array.isArray(v)?v.map((F)=>st.parse(F)):[st.parse(v)];for(let F of L)this.onmessage?.(F)}else throw await f.text?.().catch(()=>{}),new N(O.ClientHttpUnexpectedContent,`Unexpected content type: ${b}`,{contentType:b});else await f.text?.().catch(()=>{})}catch(n){if(t?.requestSignal?.aborted!==!0)this.onerror?.(n);throw n}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await this._redirects(this._fetch??fetch)(this._url,t);if(await r.text?.().catch(()=>{}),!r.ok&&r.status!==405)throw new vt(O.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,r)??r.statusText}`,{status:r.status,statusText:r.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})}};class nS{_eventSlots=new Map;setHandler(e,t){let r=this._ensureEventSlot(e);if(r.onHandler&&t)console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`);r.onHandler=t}getHandler(e){return this._eventSlots.get(e)?.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let r=this._eventSlots.get(e);if(!r)return;let o=r.listeners.indexOf(t);if(o!==-1)r.listeners.splice(o,1)}dispatch(e,t){let r=this._eventSlots.get(e);if(!r)return;r.onHandler?.(t);for(let o of[...r.listeners])o(t)}_ensureEventSlot(e){let t=this._eventSlots.get(e);if(!t)t={listeners:[]},this._eventSlots.set(e,t);return t}}class sS{_methods=new Set;claim(e,t){if(this._methods.has(e))throw Error(`Handler for "${e}" already registered (via ${t}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._methods.add(e)}replace(e){this._methods.add(e)}release(e){this._methods.delete(e)}has(e){return this._methods.has(e)}}var Qg=new Set;function eS(e,t){let[r,o]=t,n=r?.shape;if(typeof n?.method?.value!=="string")return;let s=n.method.value,i=e==="request"?"setRequestHandler":"setNotificationHandler";if(!Qg.has(i))Qg.add(i),console.warn(`[ext-apps] ${i}(Schema, handler) is deprecated; use ${i}("${s}", { params: Schema.shape.params }, handler).`);let a=o;return[s,{params:n.params},e==="request"?(l,u)=>a({method:s,params:l},Mz(u)):(l)=>a({method:s,params:l})]}function Mz(e){return{signal:e.mcpReq.signal,requestId:e.mcpReq.id,sessionId:e.sessionId,_meta:e.mcpReq._meta,sendRequest:e.mcpReq.send,sendNotification:e.mcpReq.notify,authInfo:e.http?.authInfo}}var iS="2026-01-26";var jz="ui/notifications/tool-input-partial";var Lz=T([h("light"),h("dark")]).describe("Color theme preference for the host environment."),ji=T([h("inline"),h("fullscreen"),h("pip")]).describe("Display mode for UI presentation."),Uz=T([h("--color-background-primary"),h("--color-background-secondary"),h("--color-background-tertiary"),h("--color-background-inverse"),h("--color-background-ghost"),h("--color-background-info"),h("--color-background-danger"),h("--color-background-success"),h("--color-background-warning"),h("--color-background-disabled"),h("--color-text-primary"),h("--color-text-secondary"),h("--color-text-tertiary"),h("--color-text-inverse"),h("--color-text-ghost"),h("--color-text-info"),h("--color-text-danger"),h("--color-text-success"),h("--color-text-warning"),h("--color-text-disabled"),h("--color-border-primary"),h("--color-border-secondary"),h("--color-border-tertiary"),h("--color-border-inverse"),h("--color-border-ghost"),h("--color-border-info"),h("--color-border-danger"),h("--color-border-success"),h("--color-border-warning"),h("--color-border-disabled"),h("--color-ring-primary"),h("--color-ring-secondary"),h("--color-ring-inverse"),h("--color-ring-info"),h("--color-ring-danger"),h("--color-ring-success"),h("--color-ring-warning"),h("--font-sans"),h("--font-mono"),h("--font-weight-normal"),h("--font-weight-medium"),h("--font-weight-semibold"),h("--font-weight-bold"),h("--font-text-xs-size"),h("--font-text-sm-size"),h("--font-text-md-size"),h("--font-text-lg-size"),h("--font-heading-xs-size"),h("--font-heading-sm-size"),h("--font-heading-md-size"),h("--font-heading-lg-size"),h("--font-heading-xl-size"),h("--font-heading-2xl-size"),h("--font-heading-3xl-size"),h("--font-text-xs-line-height"),h("--font-text-sm-line-height"),h("--font-text-md-line-height"),h("--font-text-lg-line-height"),h("--font-heading-xs-line-height"),h("--font-heading-sm-line-height"),h("--font-heading-md-line-height"),h("--font-heading-lg-line-height"),h("--font-heading-xl-line-height"),h("--font-heading-2xl-line-height"),h("--font-heading-3xl-line-height"),h("--border-radius-xs"),h("--border-radius-sm"),h("--border-radius-md"),h("--border-radius-lg"),h("--border-radius-xl"),h("--border-radius-full"),h("--border-width-regular"),h("--shadow-hairline"),h("--shadow-sm"),h("--shadow-md"),h("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),Zz=P(Uz.describe(`Style variables for theming MCP apps.
77
+ ${ce}`,m++}else Tg(R,w,X)?f=R.slice(R.charCodeAt(w+6)===Vr?w+7:w+6,D)||void 0:U(R,w,D);w=D+1,D=R.indexOf(`
78
+ `,w)}return R.slice(w)}for(;w<R.length;){let D=R.indexOf("\r",w),X=R.indexOf(`
79
+ `,w),Y=-1;if(D!==-1&&X!==-1?Y=D<X?D:X:D!==-1?D===R.length-1?Y=-1:Y=D:X!==-1&&(Y=X),Y===-1)break;U(R,w,Y),w=Y+1,R.charCodeAt(w-1)===Cv&&R.charCodeAt(w)===xg&&w++}return R.slice(w)}function U(R,w,D){if(w===D){x();return}let X=R.charCodeAt(w);if(Pg(R,w,X)){let ve=R.charCodeAt(w+5)===Vr?w+6:w+5,ke=R.slice(ve,D);d=m===0?ke:`${d}
80
+ ${ke}`,m++;return}if(Tg(R,w,X)){f=R.slice(R.charCodeAt(w+6)===Vr?w+7:w+6,D)||void 0;return}if(X===105&&R.charCodeAt(w+1)===100&&R.charCodeAt(w+2)===58){let ve=R.slice(R.charCodeAt(w+3)===Vr?w+4:w+3,D);ve.includes("\x00")||(u=ve);return}if(X===58){if(n){let ve=R.slice(w,D);n(ve.slice(R.charCodeAt(w+1)===Vr?2:1))}return}let Y=R.slice(w,D),ce=Y.indexOf(":");if(ce===-1){H(Y,"",Y);return}let Ee=Y.slice(0,ce),te=Y.charCodeAt(ce+1)===Vr?2:1,se=Y.slice(ce+te);H(Ee,se,Y)}function H(R,w,D){switch(R){case"event":f=w||void 0;break;case"data":d=m===0?w:`${d}
81
+ ${w}`,m++;break;case"id":w.includes("\x00")||(u=w);break;case"retry":/^\d+$/.test(w)?o(parseInt(w,10)):r(new vc(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:D}));break;default:r(new vc(`Unknown field "${R.length>20?`${R.slice(0,20)}…`:R}"`,{type:"unknown-field",field:R,value:w,line:D}));break}}function x(){m>0&&t({id:u,event:f,data:d}),u=void 0,d="",m=0,f=void 0}function Z(R={}){if(R.consume&&i.length>0){let w=i.join("");U(w,0,w.length)}l=!0,u=void 0,d="",m=0,f=void 0,i.length=0,a=0,S=!1}return{feed:b,reset:Z}}function Pg(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Tg(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}class zu extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:o}={}){let n;super({start(s){n=Eg({onEvent:(i)=>{s.enqueue(i)},onError(i){typeof e=="function"&&e(i),(e==="terminate"||i.type==="max-buffer-size-exceeded")&&s.error(i)},onRetry:t,onComment:r,maxBufferSize:o})},transform(s){n.feed(s)}})}}var Mi=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e){super(e);this.name=new.target.name,Zr(this,new.target)}},ku=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 §3.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`);this.kind=e,this.expected=t,this.received=r}},Iv=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`);this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},Zg=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`);this.tokenEndpoint=e}},Rc=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`);this.recordedIssuer=e,this.currentIssuer=t}},kg=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`);this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function $u(e,t,r){if(!e)return;if(typeof e.issuer!=="string"){if(r?.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.");return e.issuer===void 0?e:{...e,issuer:void 0}}return Dg(e.issuer,t)?e:void 0}function Dg(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function Ov(e){if(e==null)return!1;let t=e;return typeof t.tokens==="function"&&typeof t.clientInformation==="function"}async function Nv(e,t,r){let{resourceMetadataUrl:o,scope:n}=Ai(t.response);if(await Cu(e,{serverUrl:t.serverUrl,resourceMetadataUrl:o,scope:n,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new wt}function qv(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async(r)=>Nv(e,r,t)}}var wt=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e){super(e??"Unauthorized");this.name="UnauthorizedError",Zr(this,new.target)}};function Ou(e){return e?.authorization_response_iss_parameter_supported===!0}function Nu({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t===void 0)return;if(e===void 0){if(r)throw new ku("authorization_response",t,void 0);return}if(e!==t)throw new ku("authorization_response",t,e)}function wu(...e){let t=new Set;for(let r of e){if(!r)continue;for(let o of r.split(/\s+/))if(o)t.add(o)}return t.size>0?[...t].join(" "):void 0}function Av(e,t){if(!e)return!1;let r=new Set((t??"").split(/\s+/).filter(Boolean));for(let o of e.split(/\s+/))if(o&&!r.has(o))return!0;return!1}async function Mv(e,t,r,o,n){if(typeof e==="string")return{authorizationCode:e,iss:t};let s=e.get("iss")??void 0,i=e.get("code");if(i)return{authorizationCode:i,iss:s};let a=(await r.discoveryState?.())?.authorizationServerMetadata;if(!a)try{a=(await Bg(o,n)).authorizationServerMetadata}catch{a=void 0}if(!a)throw new wt("Authorization callback failed and the issuer could not be verified");Nu({iss:s,expectedIssuer:a.issuer,issParameterSupported:Ou(a)});let l=e.get("error");if(l)throw new Dr(l,e.get("error_description")??l,e.get("error_uri")??void 0);throw new wt("Authorization callback contained neither `code` nor `error`")}function jv(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var Ru="code",xu="S256";function Lv(e,t){let r=e.client_secret!==void 0;if("token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&jv(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method)))return e.token_endpoint_auth_method;if(t.length===0)return r?"client_secret_basic":"none";if(r&&t.includes("client_secret_basic"))return"client_secret_basic";if(r&&t.includes("client_secret_post"))return"client_secret_post";if(t.includes("none"))return"none";return r?"client_secret_post":"none"}function Uv(e,t,r,o){let{client_id:n,client_secret:s}=t;switch(e){case"client_secret_basic":Zv(n,s,r);return;case"client_secret_post":Dv(n,s,o);return;case"none":Fv(n,o);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Zv(e,t,r){if(!t)throw Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}function Dv(e,t,r){if(r.set("client_id",e),t)r.set("client_secret",t)}function Fv(e,t){t.set("client_id",e)}function Fg(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function Hv(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!Fg(t.hostname))throw new Zg(t.href);return t}function Vv(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:")return"native";if(Fg(r.hostname))return"native"}return"web"}function Jv(e){let 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??Vv(t.redirect_uris)}}async function $g(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Ho.parse(JSON.parse(r));return Dr.fromResponse(o)}catch(o){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Dr(Ut.ServerError,n)}}function Cg(e,t,r){let o=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} — ${o}. Cause: ${JSON.stringify(t.message)}`)}async function Cu(e,t){try{return await Pu(e,t)}catch(r){if(r instanceof Dr){if(r.code===Ut.InvalidClient||r.code===Ut.UnauthorizedClient)return Cg(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Pu(e,t);else if(r.code===Ut.InvalidGrant||r.code===Ut.InvalidDpopProof)return Cg(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await Pu(e,t)}throw r}}function Bv(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:n}=e,s=t||r?.scopes_supported?.join(" ")||n.scope;if(s&&o?.scopes_supported?.includes("offline_access")&&!s.split(" ").includes("offline_access")&&n.grant_types?.includes("refresh_token"))s=`${s} offline_access`;return s}async function Pu(e,{serverUrl:t,authorizationCode:r,iss:o,scope:n,resourceMetadataUrl:s,fetchFn:i,skipIssuerMetadataValidation:a,forceReauthorization:l}){let u=Jv(e),d=await e.discoveryState?.(),m,f,S,b,y=s;if(!y&&d?.resourceMetadataUrl)y=new URL(d.resourceMetadataUrl);if(d?.authorizationServerUrl){if(f=d.authorizationServerUrl,m=d.resourceMetadata,S=d.authorizationServerMetadata??await Jg(f,{fetchFn:i,skipIssuerValidation:a}),!m)try{m=await Hg(t,{resourceMetadataUrl:y},i)}catch(te){if(te instanceof TypeError)throw te}if(S!==d.authorizationServerMetadata||m!==d.resourceMetadata)await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:S})}else{let te=await Bg(t,{resourceMetadataUrl:y,fetchFn:i,skipIssuerMetadataValidation:a});f=te.authorizationServerUrl,S=te.authorizationServerMetadata,m=te.resourceMetadata,b={authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:S}}let v=S?.issuer??String(f),U={issuer:v};if(await e.saveAuthorizationServerUrl?.(v),r!==void 0){let te=d?.authorizationServerMetadata?.issuer??d?.authorizationServerUrl;if(te===void 0){if(e.saveDiscoveryState!==void 0)throw new Rc("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",v);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(!Dg(te,v))throw new Rc(te,v)}if(b)await e.saveDiscoveryState?.(b);let H=await Kv(t,e,m),x=H&&m&&!e.validateResourceURL?m.resource:H;if(x)await e.saveResourceUrl?.(qu(x));let Z=Bv({requestedScope:n,resourceMetadata:m,authServerMetadata:S,clientMetadata:e.clientMetadata}),R=await Promise.resolve(e.clientInformation(U)),w=$u(R,v,{canPersistStamp:e.saveClientInformation!==void 0});if(w===void 0&&R?.issuer&&e.saveClientInformation===void 0)throw new Rc(R.issuer,v);if(w&&w.issuer===void 0)w={...w,issuer:v},await e.saveClientInformation?.(w,U);if(!w){if(r!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let te=S?.client_id_metadata_document_supported===!0,se=e.clientMetadataUrl;if(se&&!Wv(se))throw new Dr(Ut.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${se}`);if(te&&se)w={client_id:se,issuer:v},await e.saveClientInformation?.(w,U);else{if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");w={...await sz(f,{metadata:S,clientMetadata:u,scope:Z,fetchFn:i}),issuer:v},await e.saveClientInformation(w,U)}}let D=!e.redirectUrl;if(r!==void 0||D){if(r!==void 0)Nu({iss:o,expectedIssuer:S?.issuer,issParameterSupported:Ou(S)});let te=await nz(e,f,{metadata:S,resource:x,authorizationCode:r,iss:o,scope:Z,fetchFn:i});return await e.saveTokens({...te,issuer:v},U),"AUTHORIZED"}let X=$u(await e.tokens(U),v);if(X&&X.issuer===void 0)X={...X,issuer:v},await e.saveTokens(X,U);if(X?.refresh_token&&!l){let te;try{te=await oz(f,{metadata:S,clientInformation:w,refreshToken:X.refresh_token,resource:x,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:i})}catch(se){if(se instanceof Zg)throw se;if(!(se instanceof Dr)||se.code===Ut.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(se instanceof Error?se.message:String(se))}`);else throw se}if(te)return await e.saveTokens({...te,issuer:v},U),"AUTHORIZED"}let Y=e.state?await e.state():void 0,{authorizationUrl:ce,codeVerifier:Ee}=await tz(f,{metadata:S,clientInformation:w,state:Y,redirectUrl:e.redirectUrl,scope:Z,resource:x});return await e.saveCodeVerifier(Ee),await e.redirectToAuthorization(ce),"REDIRECT"}function Wv(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Kv(e,t,r){let o=If(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(!r)return;if(!Of({requestedResource:o,configuredResource:r.resource}))throw Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}var Gv=new Set(["bearer","dpop"]);function Ai(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!Gv.has(r.toLowerCase())||!o)return{};let n=zc(e,"resource_metadata")||void 0,s;if(n)try{s=new URL(n)}catch{}let i=zc(e,"scope")||void 0,a=zc(e,"error")||void 0,l=zc(e,"error_description")||void 0;return{resourceMetadataUrl:s,scope:i,error:a,errorDescription:l}}function zc(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),n=r.match(o);if(n){let s=n[1]||n[2];if(s)return s}return null}async function Hg(e,t,r=fetch){let o=await Qv(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.text?.().catch(()=>{}),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.text?.().catch(()=>{}),Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Zo.parse(await o.json())}async function Vg(e,t,r=fetch){let o=Ni(r);try{return await o(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!Rg)throw n;if(t)try{return await o(e,{})}catch(s){if(!(s instanceof TypeError))throw s;return}return}}function Yv(e,t="",r={}){if(t.endsWith("/"))t=t.slice(0,-1);return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Ig(e,t,r=fetch){return await Vg(e,{"MCP-Protocol-Version":t},r)}function Xv(e,t){if(!e)return!0;if(t==="/")return!1;return!e.ok&&e.status<500||e.status===502}async function Qv(e,t,r,o){let n=new URL(e),s=o?.protocolVersion??ho,i;if(o?.metadataUrl)i=new URL(o.metadataUrl);else{let l=Yv(t,n.pathname);i=new URL(l,o?.metadataServerUrl??n),i.search=n.search}let a=await Ig(i,s,r);if(!o?.metadataUrl&&Xv(a,n.pathname))a=await Ig(new URL(`/.well-known/${t}`,n),s,r);return a}function ez(e){let t=typeof e==="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;if(n.endsWith("/"))n=n.slice(0,-1);return o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"},{url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function Jg(e,{fetchFn:t=fetch,protocolVersion:r=ho,skipIssuerValidation:o=!1}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},s=ez(e);for(let{url:i,type:a}of s){let l=await Vg(i,n,t);if(!l)continue;if(!l.ok){if(await l.text?.().catch(()=>{}),l.status<500||l.status===502)continue;throw Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}let u=a==="oauth"?Ur.parse(await l.json()):Do.parse(await l.json());if(!o){let d=typeof e==="string"?e:e.href;if(!(u.issuer===d||d.endsWith("/")&&u.issuer===d.slice(0,-1)))throw new ku("metadata",d,u.issuer)}return u}}async function Bg(e,t){let r,o;try{if(r=await Hg(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0)o=r.authorization_servers[0]}catch(s){if(s instanceof TypeError)throw s}if(!o)o=String(new URL("/",e));let n=await Jg(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function qu(e){return typeof e==="string"?e:e.href}async function tz(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Ru))throw Error(`Incompatible auth server: does not support response type ${Ru}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(xu))throw Error(`Incompatible auth server: does not support code challenge method ${xu}`)}else a=new URL("/authorize",e);let l=await yu(),{code_verifier:u,code_challenge:d}=l;if(a.searchParams.set("response_type",Ru),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",xu),a.searchParams.set("redirect_uri",String(o)),s)a.searchParams.set("state",s);if(n)a.searchParams.set("scope",n);if(n?.split(" ").includes("offline_access"))a.searchParams.append("prompt","consent");if(i)a.searchParams.set("resource",qu(i));return{authorizationUrl:a,codeVerifier:u}}function rz(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function Wg(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:s,dpop:i,fetchFn:a}){let l=Hv(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s)r.set("resource",qu(s));if(!n&&o)Uv(Lv(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let d=async()=>{let S=new Headers(u);if(n)await n(S,r,l,t);if(i)S.set("DPoP",await i.buildProof({htm:"POST",htu:l}));return Ni(a??fetch)(l,{method:"POST",headers:S,body:r})},m=await d();if(i&&m.status===400){if((await m.clone().json().catch(()=>{}))?.error===Ut.UseDpopNonce)i.observeNonce(m,l),m=await d()}if(i?.observeNonce(m,l),!m.ok)throw await $g(m);let f=await m.json();try{return Fo.parse(su(f))}catch(S){if(typeof f==="object"&&f!==null&&"error"in f)throw await $g(JSON.stringify(f));throw S}}async function oz(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:s,dpop:i,fetchFn:a}){return{refresh_token:o,...await Wg(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:s,resource:n,dpop:i,fetchFn:a})}}async function nz(e,t,{metadata:r,resource:o,authorizationCode:n,iss:s,scope:i,fetchFn:a}={}){if(n!==void 0)Nu({iss:s,expectedIssuer:r?.issuer,issParameterSupported:Ou(r)});let l=r?.issuer??String(t),u=async()=>{let S=await e.clientInformation({issuer:l}),b=$u(S,l,{canPersistStamp:!1});if(S&&b===void 0)throw new Rc(String(S.issuer),l);return b},d=await u(),m=i??e.clientMetadata.scope,f;if(e.prepareTokenRequest)f=await e.prepareTokenRequest(m);if(!f){if(!n)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");f=rz(n,await e.codeVerifier(),e.redirectUrl)}return d??=await u(),Wg(t,{metadata:r,tokenRequestParams:f,clientInformation:d,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:a})}async function sz(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:n}){let s;if(t){if(!t.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);let i={...r,...o===void 0?{}:{scope:o}},a=await Ni(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!a.ok)throw new Iv({status:a.status,body:await a.text(),submittedMetadata:i});return Vo.parse(su(await a.json()))}var wc=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),iz=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(Tu(e))}set(e,t){let r=Tu(e),o=wc.has(e.method),n=!this._entries.has(r);if(!o&&n&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let i of this._entries.keys())if(!wc.has(i.slice(0,i.indexOf("\x00")))){this._entries.delete(i),this._cappedSize--;break}}let s=++this._stamp;if(this._entries.set(r,{...t,stamp:s}),n&&!o)this._cappedSize++;return s}delete(e){if(this._entries.delete(Tu(e))&&!wc.has(e.method))this._cappedSize--}evict(e){let t=`${e}\x00`,r=wc.has(e);for(let o of this._entries.keys())if(o.startsWith(t)){if(this._entries.delete(o),!r)this._cappedSize--}}clear(){this._entries.clear(),this._cappedSize=0}};function Tu(e){return`${e.method}\x00${JSON.stringify([e.partition??"",e.params??""])}`}function Eu(e,t){return t===void 0?e:`${e}\x00${t}`}var az=86400000,cz=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,r=()=>{},o="",n=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=r,this._cachePartition=o,this._now=n}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){let r={method:e,params:t??""},o=this._partitionFor("private"),n=await this._store.get({...r,partition:o});if(n!==void 0)return n;let s=this._partitionFor("public");if(s===o)return;let i=await this._store.get({...r,partition:s});return i?.scope==="public"?i:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){let r=this._partitionFor("private"),o=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:r})}catch(n){this._reportError(n)}if(o!==r)try{await this._store.delete({method:e,params:t,partition:o})}catch(n){this._reportError(n)}}async evictKey(e,t){let r=Eu(e,t),o=this._evictionGeneration.get(r);if(o!==void 0)this._evictionGeneration.set(r,o+1);await this._deleteBoth(e,t)}captureGeneration(e,t){let r=Eu(e,t),o=this._evictionGeneration.get(r)??0;return this._evictionGeneration.set(r,o),o}async write(e,t,r,o){if((this._evictionGeneration.get(Eu(e,o?.params))??0)!==r)return;let n=o?.params??"",s=this._partitionFor("private"),i=this._partitionFor("public"),a=(o?.scope??"private")==="public"?i:s;try{await this._store.set({method:e,params:n,partition:a},{value:lz(t),expiresAt:o?.expiresAt,scope:o?.scope})}catch(l){this._reportError(l)}if(i!==s)try{await this._store.delete({method:e,params:n,partition:a===s?i:s})}catch(l){this._reportError(l)}}async read(e,t){let r=await this._probe(e,t);if(r?.expiresAt===void 0||!(r.expiresAt>this.now()))return;try{let o=JSON.parse(r.value);if(typeof o!=="object"||o===null||Array.isArray(o))throw TypeError("cached document is not an object");return{value:o}}catch(o){this._reportError(o),await this._deleteBoth(e,t??"");return}}resetForReconnect(){if(!this._isUserSupplied)this._store.clear();this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){let t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let r=this._decodeListTools(t),o=new Map;if(r!==void 0)for(let n of r.tools)o.set(n.name,n);this._toolIndex={stamp:t.stamp,byName:o}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let r=await this._probe("tools/list");if(r===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==r.stamp){let o=this._decodeListTools(r)??{tools:[]},n=new Map;for(let s of o.tools){let i=t(s);if(i!==void 0)n.set(s.name,i)}this._toolOutputValidatorIndex={stamp:r.stamp,byName:n}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every((r)=>r!==null&&typeof r==="object"))throw TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};function lz(e){let t;try{t=JSON.stringify(e)}catch(r){throw TypeError(`cache value is not JSON-serializable: ${r instanceof Error?r.message:String(r)}`)}if(typeof t!=="string")throw TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}var Kg=Symbol.for("mcp.authSeamEscape");function Xe(e){if(typeof e==="object"&&e!==null||typeof e==="function")try{Object.defineProperty(e,Kg,{value:!0,configurable:!0})}catch{}return e}function uz(e){return(typeof e==="object"&&e!==null||typeof e==="function")&&e[Kg]===!0}var dz=-32022,pz=new Set([-32001,-32020,-32021]);function hz(e,t){switch(e.kind){case"result":return mz(e.result,t);case"rpc-error":return Gg(e,t);case"http-error":return fz(e,t);case"network-error":return Og(e.error,t);case"unusable-reply":return{kind:"error",error:new N(O.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${Yg(e.error)})`,{cause:e.error},{cause:e.error})};case"auth-required":return{kind:"error",error:e.error};case"closed":if(t.transportKind==="stdio")return{kind:"legacy"};return Og(Error("Connection closed during the version negotiation probe"),t);case"timeout":if(t.transportKind==="stdio")return{kind:"legacy"};return{kind:"error",error:new N(O.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function mz(e,t){let r=Lt(Sc).validateResult("server/discover",e);if(!r.ok)return{kind:"legacy"};let o=r.value.supportedVersions,n=t.clientModernVersions.find((s)=>o.includes(s));if(n!==void 0)return{kind:"modern",version:n,discover:r.value};if(t.fallbackAvailable)return{kind:"legacy"};return{kind:"error",error:new gc({supported:[...o],requested:t.requestedVersion})}}function Gg(e,t){let{code:r,message:o,data:n}=e;if(r===dz){let s=Sz(n);if(s===void 0)return{kind:"legacy"};let i=new gc({supported:s,requested:_z(n)??t.requestedVersion},o),a=Oi(s),l=t.clientModernVersions.find((u)=>a.includes(u));if(l!==void 0)return{kind:"corrective",version:l,error:i};if(a.length>0)return{kind:"error",error:i};return t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:i}}if(pz.has(r))return{kind:"legacy"};return{kind:"legacy"}}function fz(e,t){if(e.status===401||e.status===403){let o=e.status===403;return{kind:"error",error:new vt(o?O.ClientHttpForbidden:O.ClientHttpAuthentication,`Version negotiation failed: ${o?"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 vt(O.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let r=bz(e.body);if(r!==void 0)return Gg(r,t);return{kind:"legacy"}}function Og(e,t){if(t.environment==="browser"&&gz(e))return{kind:"legacy"};return{kind:"error",error:new N(O.EraNegotiationFailed,`Version negotiation probe failed: ${Yg(e)}`,{cause:e},{cause:e})}}function gz(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function Yg(e){return e instanceof Error?e.message:String(e)}function Sz(e){if(typeof e!=="object"||e===null)return;let t=e.supported;if(!Array.isArray(t)||t.length===0||!t.every((r)=>typeof r==="string"))return;return t}function _z(e){if(typeof e!=="object"||e===null)return;let t=e.requested;return typeof t==="string"?t:void 0}function bz(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=="object"||t===null)return;let r=t.error;if(typeof r!=="object"||r===null)return;let{code:o,message:n,data:s}=r;if(typeof o!=="number")return;return{code:o,message:typeof n==="string"?n:"",data:s}}var yz="legacy";function vz(e,t){let r=e?.mode??yz;if(r==="legacy")return{kind:"legacy"};let o=e?.probe??{};if(typeof r==="object"){if(!Zt(r.pin))throw TypeError(`versionNegotiation: { pin: '${r.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:r.pin,probe:o}}let n=t?Oi(t):[];return{kind:"auto",modernVersions:n.length>0?n:[...iu],fallbackAvailable:t?au(t).length>0:!0,probe:o}}function Ng(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function qg(e){return"stderr"in e&&"pid"in e?"stdio":"http"}var zz=class e{_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){let r=new e(t);t.onmessage=(o)=>{let n=r._pending;if(n!==void 0&&(Bo(o)||Wo(o))&&o.id===n.id){if(r._pending=void 0,Bo(o))n.resolve({kind:"response",result:o.result});else n.resolve({kind:"response",error:o.error});return}},t.onerror=(o)=>{r._savedOnError?.(o)},t.onclose=()=>{let o=r._pending;if(o!==void 0)r._pending=void 0,o.resolve({kind:"closed"});r._closeDelivered=!0,r._savedOnClose?.()};try{await t.start()}catch(o){throw r.detach(),o}return r}async exchange(t,r){let o=`server-discover-probe-${++this._probeCounter}`;return new Promise((n)=>{let s=!1,i=(l)=>{if(s)return;if(s=!0,clearTimeout(a),this._pending?.id===o)this._pending=void 0;n(l)},a=setTimeout(()=>i({kind:"timeout"}),r);this._pending={id:o,resolve:i},this._transport.send(t(o)).catch((l)=>i({kind:"send-error",error:l}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let t=this._savedOnClose,r=this._transport,o=!1,n=()=>{if(!o){o=!0;return}t()};r.onclose=n,Iu.set(r,()=>{if(r.onclose===n)r.onclose=t})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let t=this._transport,r=t.start,o=!0;t.start=async function(){if(o){o=!1,t.start=r;return}return r.call(t)}}},Iu=new WeakMap;function Ag(e){let t=Iu.get(e);Iu.delete(e),t?.()}function wz(e,t,r,o){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:Lt(t).outboundEnvelope({protocolVersion:t,clientInfo:r,clientCapabilities:o})}}}function Rz(e){if(e instanceof N&&e.code===O.ClientHttpUnexpectedContent)return!0;return e instanceof Error&&e.name==="SyntaxError"}function xz(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":{let r=e.error;if(uz(r)||r instanceof wt||r instanceof Error&&r.name==="UnauthorizedError")return{kind:"auth-required",error:r};if(r instanceof vt){let o=r.data?.text;return{kind:"http-error",status:r.data.status,body:typeof o==="string"?o:void 0,statusText:r.data.statusText}}if(Rz(r))return{kind:"unusable-reply",error:r};return{kind:"network-error",error:r}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function Xg(e,t){let r=e.probe.timeoutMs??t.defaultTimeoutMs,o=Math.max(0,e.probe.maxRetries??0),n=e.kind==="pin"?[e.version]:e.modernVersions,s=e.kind==="auto"&&e.fallbackAvailable,i=await zz.open(t.transport),a=async()=>{let u=n[0],d=!1,m=o;for(;;){let f=await i.exchange((y)=>wz(y,u,t.clientInfo,t.capabilities),r);if(f.kind==="timeout"&&m>0){m--;continue}let S=xz(f,r),b=hz(S,{clientModernVersions:n,requestedVersion:u,fallbackAvailable:s,environment:t.environment,transportKind:t.transportKind});switch(b.kind){case"modern":return{era:"modern",version:b.version,discover:b.discover};case"corrective":if(d)throw b.error;d=!0,u=b.version;continue;case"legacy":{let y=S.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new N(O.EraNegotiationFailed,y===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: ${y} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new N(O.EraNegotiationFailed,y===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: ${y} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(y!==void 0&&t.disposableProbe!==!0)throw new N(O.EraNegotiationFailed,`Version negotiation failed: ${y} (this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw b.error}}},l;try{l=await a()}catch(u){throw i.detach(),u}return i.release(),l}function Pz(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;let r=e._serverParams;return typeof r==="object"&&r!==null&&typeof r.command==="string"?r:void 0}async function Tz(e,t,r,o){let s=new t.constructor({...r,stderr:"ignore"}),i=t.close,a=!1,l,u=new Promise((m,f)=>{l=()=>f(Mg())});t.close=async function(){return a=!0,l?.(),i.call(t)};let d;try{let m=Xg(e,{...o,transport:s,transportKind:"stdio",disposableProbe:!0});m.catch(()=>{}),d=await Promise.race([m,u])}finally{await Ez(s),t.close=i}if(a)throw Mg();return d}function Mg(){return new N(O.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function Ez(e){try{let t=e._dispose;await(typeof t==="function"?t.call(e):e.close())}catch{}}function jg(e){let t=e._meta?.[Ot];return pg.Implementation(t)?t:void 0}function xc(e,t){if(!e||t===null||typeof t!=="object")return;if(e.type==="object"&&e.properties&&typeof e.properties==="object"){let r=t,o=e.properties;for(let n of Object.keys(o)){let s=o[n];if(r[n]===void 0&&Object.prototype.hasOwnProperty.call(s,"default"))r[n]=s.default;if(r[n]!==void 0)xc(s,r[n])}}if(Array.isArray(e.anyOf)){for(let r of e.anyOf)if(typeof r!=="boolean")xc(r,t)}if(Array.isArray(e.oneOf)){for(let r of e.oneOf)if(typeof r!=="boolean")xc(r,t)}}function kz(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}function $z(e){if(typeof e==="object"&&e!==null){if(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e))return e;if(e.kind==="modern"&&rr.safeParse(e.discover).success)return e}throw new N(O.EraNegotiationFailed,"connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }")}var Lg={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},Cz=64,Qg=class extends yc{_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){let e=new N(O.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(let 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);if(this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new _u,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=cg(t?.inputRequired),this._cache=new cz(t?.responseCacheStore??new iz,t?.responseCacheStore!==void 0,(r)=>this._reportStoreError(r),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??Cz,t?.listChanged)this._listChangedConfig=t.listChanged}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&Zt(this._negotiatedProtocolVersion)&&Fr(e))return"drop"}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){if(!this._inputRequiredDriverConfig.autoFulfill)return Promise.reject(new N(O.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}));return mg({getRequestHandler:(r)=>this._getRequestHandler(r),buildContext:(r)=>this.buildContext(r,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t)}_setupListChangedHandlers(e){if(e.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools);if(e.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts);if(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 Error("Cannot register capabilities after connecting to transport");this._capabilities=hg(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){if(e==="elicitation/create")return async(r,o)=>{let n=Lt(this._negotiatedProtocolVersion),s=n.validateRequest("elicitation/create",r);if(!s.ok&&s.reason==="not-in-era")s=n.validateInputRequest("elicitation/create",r);if(!s.ok)throw new ee(s.reason==="not-in-era"?W.InternalError:W.InvalidParams,s.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${s.message}`);let{params:i}=s.value;i.mode=i.mode??"form";let{supportsFormMode:a,supportsUrlMode:l}=kz(this._capabilities.elicitation);if(i.mode==="form"&&!a)throw new ee(W.InvalidParams,"Client does not support form-mode elicitation requests");if(i.mode==="url"&&!l)throw new ee(W.InvalidParams,"Client does not support URL-mode elicitation requests");let u=await t(r,o),d=n.validateResult("elicitation/create",u);if(!d.ok&&d.reason==="not-in-era")d=n.validateInputResponse("elicitation/create",u);if(!d.ok)throw new ee(d.reason==="not-in-era"?W.InternalError:W.InvalidParams,d.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${d.message}`);let m=d.value,f=i.mode==="form"?i.requestedSchema:void 0;if(i.mode==="form"&&m.action==="accept"&&m.content&&f&&this._capabilities.elicitation?.form?.applyDefaults)try{xc(f,m.content)}catch{}return m};if(e==="sampling/createMessage")return async(r,o)=>{let n=Lt(this._negotiatedProtocolVersion),s=n.validateRequest("sampling/createMessage",r);if(!s.ok&&s.reason==="not-in-era")s=n.validateInputRequest("sampling/createMessage",r);if(!s.ok)throw new ee(s.reason==="not-in-era"?W.InternalError:W.InvalidParams,s.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${s.message}`);let{params:i}=s.value,a=await t(r,o),l=Boolean(i.tools||i.toolChoice),u=n.samplingResultVariant(l,a);if(!u.ok&&u.reason==="not-in-era")u=n.validateInputResponse("sampling/createMessage",a);if(!u.ok)throw new ee(u.reason==="not-in-era"?W.InternalError:W.InvalidParams,u.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${u.message}`);return u.value};return t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new N(O.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,$z(t.prior),t);let r=vz(this._versionNegotiation,this._supportedProtocolVersionsOption);if(r.kind!=="legacy")return this._connectNegotiated(e,r,t);return this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let r=this._negotiatedProtocolVersion;if(r!==void 0)e.setProtocolVersion?.(r);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let r=au(this._supportedProtocolVersions);try{let o=r[0];if(o===void 0)throw new N(O.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let n=await this.request({method:"initialize",params:{protocolVersion:o,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!r.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);if(this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion)e.setProtocolVersion(n.protocolVersion);if(this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=n.protocolVersion,this._listChangedConfig)this._setupListChangedHandlers(this._listChangedConfig)}catch(o){throw this.close(),o}}async _connectNegotiated(e,t,r){if(e.sessionId!==void 0){await super.connect(e);let n=this._negotiatedProtocolVersion;if(n!==void 0&&e.setProtocolVersion)e.setProtocolVersion(n);return}this._resetConnectionState();let o;try{let n=qg(e),s={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:Ng(),defaultTimeoutMs:r?.timeout??bc},i=n==="stdio"?Pz(e):void 0;o=i===void 0?await Xg(t,{...s,transport:e,transportKind:n}):await Tz(t,e,i,s)}catch(n){throw await e.close().catch(()=>{}),Ag(e),n}if(Ag(e),await super.connect(e),o.era==="legacy"){await this._legacyHandshake(e,r);return}if(this._serverCapabilities=o.discover.capabilities,this._serverVersion=jg(o.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.discover.instructions,this._discoverResult=o.discover,this._negotiatedProtocolVersion=o.version,e.setProtocolVersion)e.setProtocolVersion(o.version);if(this._listChangedConfig){let n=this._listChangedConfig,s=this._serverCapabilities,i={...n.tools&&s?.tools?.listChanged&&{tools:n.tools},...n.prompts&&s?.prompts?.listChanged&&{prompts:n.prompts},...n.resources&&s?.resources?.listChanged&&{resources:n.resources}},a=!0;try{this._setupListChangedHandlers(i)}catch(u){a=!1,this.onerror?.(u instanceof Error?u:Error(String(u)))}let l=a?{...i.tools&&{toolsListChanged:!0},...i.prompts&&{promptsListChanged:!0},...i.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(l).length>0){let u=new AbortController,d=()=>u.abort(r?.signal?.reason);if(r?.signal?.aborted)d();r?.signal?.addEventListener("abort",d);try{this._autoOpenedSubscription=await this.listen(l,{timeout:r?.timeout,signal:u.signal})}catch(m){if(r?.signal?.aborted)throw await this.close().catch(()=>{}),m;this.onerror?.(m instanceof Error?m:Error(String(m)))}finally{r?.signal?.removeEventListener("abort",d)}}}}async _connectFromPrior(e,t,r){if(t.kind==="legacy")return this._connectPlainLegacy(e,r);let o=t.discover;this._resetConnectionState();let n=this._supportedProtocolVersionsOption,s=(n&&Oi(n).length>0?Oi(n):iu).find((i)=>o.supportedVersions.includes(i));if(s===void 0)throw new N(O.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=o,this._serverCapabilities=o.capabilities,this._serverVersion=jg(o),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.instructions,this._negotiatedProtocolVersion=s,e.setProtocolVersion?.(s),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(i){this.onerror?.(i instanceof Error?i:Error(String(i)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;if(t!==void 0)return`${t.name}@${t.version}`;return e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return Zt(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new N(O.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new N(O.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 N(O.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new N(O.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new N(O.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new N(O.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new N(O.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new N(O.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new N(O.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new N(O.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){let t=await this._requestWithSchema({method:"server/discover"},rr,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);let r=await this._serveFromCache("prompts/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("prompts/list",e,t,(o)=>o.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);let r=await this._serveFromCache("resources/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("resources/list",e,t,(o)=>o.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);let r=await this._serveFromCache("resources/templates/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("resources/templates/list",e,t,(o)=>o.resourceTemplates)}async _listAllPages(e,t,r,o,n){let s=r?.cacheMode==="bypass",i=this._cache.captureGeneration(e),a=await this.request({method:e,...t&&{params:{...t}}},r),l=a.nextCursor,u=a,d=1;while(l!==void 0){if(this._listMaxPages!==0&&d>=this._listMaxPages)throw new N(O.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});let m=await this.request({method:e,params:{...t,cursor:l}},r);if(m.nextCursor===l&&JSON.stringify(o(m))===JSON.stringify(o(u)))break;o(a).push(...o(m)),u=m,l=m.nextCursor,d++}if(delete a.nextCursor,n?.(a),s)return a;return await this._cache.write(e,a,i,this._freshness(a)),a}_freshness(e,t){let r=e,o=typeof r.ttlMs==="number"?r.ttlMs:this._defaultCacheTtlMs,n=r.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,o),az),scope:n,params:t}}async _serveFromCache(e,t,r){if(r?.cacheMode==="bypass"||r?.cacheMode==="refresh")return;let o=await this._cache.read(e,t).catch((n)=>void this._reportStoreError(n));if(o!==void 0){if(r?.signal?.aborted){let n=r.signal.reason;throw n instanceof N?n:new N(O.RequestTimeout,String(n))}return o.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}_compileOutputValidator(e){if(!e.outputSchema)return;try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){let r=t??await this._cache.toolDefinition(e);return r===void 0?void 0:mu(r.inputSchema)}async readResource(e,t){let r=await this._serveFromCache("resources/read",e.uri,t);if(r!==void 0)return r;let o=this._cache.captureGeneration("resources/read",e.uri),n=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){let s=this._freshness(n,e.uri);if(s.expiresAt>this._cache.now())await this._cache.write("resources/read",n,o,s);else if(t?.cacheMode==="refresh")await this._cache.evictKey("resources/read",e.uri)}return n}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 N(O.NotConnected,"Not connected");let r=this._negotiatedProtocolVersion;if(r===void 0||!Zt(r))throw new N(O.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${r??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:r});if(t?.signal?.aborted){let x=t.signal.reason;throw x instanceof N?x:new N(O.RequestTimeout,String(x))}let o=new AbortController,n=`listen:${this._nextListenId++}`,s="opening",i,a,l,u,d=new Promise((x,Z)=>{l=x,u=Z}),m,f=new Promise((x)=>{m=x}),S=(x)=>{if(s==="closed")return;let Z=s==="opening";if(i!==void 0)clearTimeout(i),i=void 0;if("ack"in x){s="open",l(x.ack);return}if(s="closed",a!==void 0)t?.signal?.removeEventListener("abort",a);if(this._listenState.delete(n),o.abort(),m(x.cause),Z)u(x.error??new N(O.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},b=async()=>{o.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:n}}).catch(()=>{})},y=async()=>{if(s==="closed")return;S({cause:"local"}),await b()};this._listenState.set(n,{settle:S});let v=t?.timeout??bc;if(i=setTimeout(()=>{S({cause:"remote",error:new N(O.RequestTimeout,"subscriptions/listen ack timed out",{timeout:v})}),b().catch(()=>{})},v),t?.signal){let x=t.signal;a=()=>{if(s==="closed")return;let Z=x.reason;S({cause:"local",error:Z instanceof Error?Z:Error(String(Z??"Aborted"))}),b().catch(()=>{})},x.addEventListener("abort",a,{once:!0})}let U={jsonrpc:"2.0",id:n,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}},H=(x)=>{S({cause:"remote",error:x instanceof Error?x:Error(String(x))})};try{this.transport.send(U,{requestSignal:o.signal,onRequestStreamEnd:()=>S({cause:"remote",error:Error("subscriptions/listen: stream ended")})}).catch(H)}catch(x){H(x)}return{honoredFilter:await d,close:y,closed:f}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let r=Object.hasOwn(Lg,e.method)?Lg[e.method]:void 0;if(e.method==="notifications/resources/updated"){let o=e.params?.uri;if(typeof o==="string")this._cache.evictKey("resources/read",o)}else if(r!==void 0)for(let o of r)this._cache.evict(o);if(e.method==="notifications/subscriptions/acknowledged"){let o=e.params?._meta?.[Wn],n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){let s=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);n.settle({ack:s.ok?s.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){let o=e.params?.requestId,n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){n.settle({cause:"remote",error:Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,r=typeof t==="string"?this._listenState.get(t):void 0;if(r!==void 0){if(Wo(e))r.settle({cause:"remote",error:ee.fromError(e.error.code,e.error.message,e.error.data)});else r.settle({cause:"graceful",error:new N(O.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new N(O.ConnectionClosed,"Connection closed");for(let t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let r=this.getProtocolEra()==="modern"&&Ng()!=="browser",o=async()=>{if(!r)return t;let l;try{l=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(d){this._reportStoreError(d)}if(!l?.valid||l.declarations.length===0)return t;let u=sg(l.declarations,e.arguments);return Object.keys(u).length===0?t:{...t,headers:{...t?.headers,...u}}},n=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,(l)=>this._compileOutputValidator(l)).catch((l)=>void this._reportStoreError(l)):this._compileOutputValidator(t.toolDefinition),s=()=>{if(n===void 0||n.ok)return;let l=n.compileError,u=(l instanceof Error?l.message:String(l)).slice(0,200);throw new ee(W.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${u}`)};s();let i;try{i=await this.request({method:"tools/call",params:e},await o())}catch(l){let u=l instanceof ee&&l.code===Jo;if(!r||!u||t?.toolDefinition!==void 0)throw l;let d={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,d).catch((m)=>this._reportStoreError(m)),n=await this._cache.outputValidator(e.name,(m)=>this._compileOutputValidator(m)).catch((m)=>void this._reportStoreError(m)),s(),i=await this.request({method:"tools/call",params:e},await o())}let a=n!==void 0&&n.ok?n.validator:void 0;if(a){if(i.structuredContent===void 0&&!i.isError)throw new ee(W.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent!==void 0&&!i.isError)try{let l=a(i.structuredContent);if(!l.valid)throw new ee(W.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)}catch(l){if(l instanceof ee)throw l;throw new ee(W.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)}}return i}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){let o=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(o),o}let r=await this._serveFromCache("tools/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("tools/list",e,t,(o)=>o.tools,(o)=>this._excludeInvalidXMcpHeaderTools(o))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||qg(this.transport)==="stdio")return;let t=e.tools.filter((r)=>{let o=mu(r.inputSchema);if(!o.valid)return console.warn(`[mcp-sdk] excluding tool '${r.name}' from tools/list: invalid x-mcp-header declaration — ${o.reason}`),!1;return!0});if(t.length!==e.tools.length)e.tools=t}_setupListChangedHandler(e,t,r,o){let n=_c(Hs,r);if(!n.success)throw Error(`Invalid ${e} listChanged options: ${n.error.message}`);if(typeof r.onChanged!=="function")throw TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:i}=n.data,{onChanged:a}=r,l=async()=>{if(!s){a(null,null);return}try{a(null,await o())}catch(d){a(d instanceof Error?d:Error(String(d)),null)}},u=()=>{if(i){let d=this._listChangedDebounceTimers.get(e);if(d)clearTimeout(d);let m=setTimeout(l,i);this._listChangedDebounceTimers.set(e,m)}else l()};this.setNotificationHandler(t,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function Iz(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function Oz(e){if(e.status!==401)return!1;let t=e.headers.get("www-authenticate")??"";return Iz(t)&&/use_dpop_nonce/i.test(t)}var Nz=(e,t)=>(r)=>{let o=typeof e==="function"?e:()=>e;return async(n,s)=>{let i=(s?.method??"GET").toUpperCase(),a=new URL(n.toString()),l=await o();if(!l)return r(n,s);let u=async()=>{let m=await t();if(!m)return r(n,s);let f=new Headers(s?.headers),S=await l.buildProof({htm:i,htu:a,accessToken:m});return f.set("Authorization",`DPoP ${m}`),f.set("DPoP",S),r(n,{...s,headers:f})},d=await u();if(Oz(d)&&d.headers.has("dpop-nonce"))l.observeNonce(d,a),await d.text?.().catch(()=>{}),d=await u();return l.observeNonce(d,a),d}},qz=(e)=>Nz(async()=>{try{return await e.dpop?.()}catch(t){throw Xe(t)}},async()=>{let t;try{t=await e.tokens()}catch(r){throw Xe(r)}return t?.token_type?.toLowerCase()==="dpop"?t.access_token:void 0});var vP=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e,t,r){super(`SSE error: ${t}`);this.code=e,this.event=r,Zr(this,new.target)}};var Az=1,Mz={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2},jz=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function Ug(e,t){if(typeof AbortSignal.any==="function")return AbortSignal.any([e,t]);let r=new AbortController;if(e.aborted)return r.abort(e.reason),r.signal;if(t.aborted)return r.abort(t.reason),r.signal;let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",s)};function n(){o(),r.abort(e.reason)}function s(){o(),r.abort(t.reason)}return e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",s,{once:!0}),r.signal}var eS=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){if(this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,Ov(t?.authProvider)){if(this._oauthProvider=t.authProvider,this._authProvider=qv(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop)this._fetch=qz(t.authProvider)(t.fetch??fetch)}else this._authProvider=t?.authProvider;if(this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=gg(t?.fetch,t?.requestInit),this._redirectPolicy==="follow")this._fetchWithInit=bg(this._fetchWithInit);this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??Mz,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??Az)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(r){throw Xe(r)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new kg({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new kg({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new vt(O.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});if(e.resourceMetadataUrl)this._resourceMetadataUrl=e.resourceMetadataUrl;let r=await this._oauthProvider.tokens(),o=wu(this._scope,r?.scope,e.scope);this._scope=o;let n=Av(o,r?.scope);return Cu(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:o,forceReauthorization:n,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return this._redirectPolicy==="follow"?e:Ni(e)}_unfollowedRedirect(e,t){let r=this._redirectPolicy==="follow"?void 0:yg(e,t);return r&&`${r} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let e=new Headers(this._requestInit?.headers||void 0),t;try{t=await this._authProvider?.token()}catch(r){throw Xe(r)}if(t)e.set("Authorization",`Bearer ${t}`);if(this._sessionId)e.set("mcp-session-id",this._sessionId);if(this._protocolVersion)e.set("mcp-protocol-version",this._protocolVersion);return e}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!Fr(t))return;let r=t.params?._meta?.[It];if(typeof r!=="string")return;e.set("mcp-protocol-version",r),e.set("mcp-method",t.method);let o=ig(t.method,t.params);if(o?.value!==void 0)e.set("mcp-name",fu(o.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Fr(e))return!1;let t=e.params?._meta?.[It];return typeof t==="string"&&Zt(t)}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:o,requestSignal:n}=e,s=()=>this._abortController?.signal.aborted===!0||n?.aborted===!0;try{let i=await this._commonHeaders(),a=[...i.get("accept")?.split(",").map((m)=>m.trim().toLowerCase())??[],"text/event-stream"];if(i.set("accept",[...new Set(a)].join(", ")),o)i.set("last-event-id",o);let l=this._abortController?.signal,u=n!==void 0&&l!==void 0?Ug(l,n):n??l,d=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:i,signal:u});if(!d.ok){if(d.status===401&&this._authProvider){if(d.headers.has("www-authenticate")){let{resourceMetadataUrl:f,scope:S}=Ai(d);this._resourceMetadataUrl=f,this._scope=wu(this._scope,S)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:d,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(f){throw Xe(f)}return await d.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r)}if(await d.text?.().catch(()=>{}),t)throw Xe(new vt(O.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:d.statusText}));throw Xe(new wt)}if(d.status===403){let{resourceMetadataUrl:f,scope:S,error:b,errorDescription:y}=Ai(d);if(b==="insufficient_scope"){let v=await d.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:S,resourceMetadataUrl:f,errorDescription:y,statusText:d.statusText,text:v},r)!=="AUTHORIZED")throw Xe(new wt);return this._startOrAuthSse(e,t,r+1)}}if(await d.text?.().catch(()=>{}),d.status===405){e.onRequestStreamEnd?.();return}let m=this._unfollowedRedirect(this._url,d)??d.statusText;throw new vt(O.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${m}`,{status:d.status,statusText:d.statusText})}this._handleSseStream(d.body,e,!0)}catch(i){if(!s())this.onerror?.(i);throw i}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(Error(`Maximum reconnection attempts (${r}) exceeded.`)),e.onRequestStreamEnd?.();return}let o=this._getNextReconnectionDelay(t),n=()=>{if(this._cancelReconnection=void 0,this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this._startOrAuthSse(e).catch((s)=>{if(this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this.onerror?.(Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`));try{this._scheduleReconnection(e,t+1)}catch(i){this.onerror?.(i instanceof Error?i:Error(String(i)))}})};if(this._reconnectionScheduler){let s=this._reconnectionScheduler(n,o,t);this._cancelReconnection=typeof s==="function"?s:void 0}else{let s=setTimeout(n,o);this._cancelReconnection=()=>clearTimeout(s)}}_handleSseStream(e,t,r){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i}=t,a=()=>this._abortController?.signal.aborted===!0||s?.aborted===!0,l,u=!1,d=!1;(async()=>{try{let f=e.pipeThrough(new TextDecoderStream).pipeThrough(new zu({onRetry:(S)=>{this._serverRetryMs=S}})).getReader();while(!0){let{value:S,done:b}=await f.read();if(b)break;if(S.id)l=S.id,u=!0,o?.(S.id);if(!S.data)continue;if(!S.event||S.event==="message")try{let y=st.parse(JSON.parse(S.data));if(Bo(y)||Wo(y)){if(d=!0,n!==void 0)y.id=n}this.onmessage?.(y)}catch(y){this.onerror?.(y)}}if((r||u)&&!d&&this._abortController&&!a())this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i},0);else if(!a())i?.()}catch(f){if(a())return;if(this.onerror?.(Error(`SSE stream disconnected: ${f}`)),(r||u)&&!d&&this._abortController&&!a())try{this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:s,onRequestStreamEnd:i},0)}catch(S){this.onerror?.(Error(`Failed to reconnect: ${S instanceof Error?S.message:String(S)}`)),i?.()}else i?.()}})()}async start(){if(this._abortController)throw 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 wt("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:o}=await Mv(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await Cu(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:o,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new wt("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,r,o=0){try{let{resumptionToken:n,onresumptiontoken:s}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Fr(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch((v)=>this.onerror?.(v));return}let i=await this._commonHeaders();this._applyBodyDerivedHeaders(i,e);let a=Array.isArray(e)?e.some((v)=>hu(v)):hu(e);if(a)i.delete("mcp-session-id");if(t?.headers!==void 0)for(let[v,U]of Object.entries(t.headers)){if(jz.has(v.toLowerCase()))continue;i.set(v,U)}i.set("content-type","application/json");let l=[...i.get("accept")?.split(",").map((v)=>v.trim().toLowerCase())??[],"application/json","text/event-stream"];i.set("accept",[...new Set(l)].join(", "));let u=this._abortController?.signal,d=t?.requestSignal!==void 0&&u!==void 0?Ug(u,t.requestSignal):t?.requestSignal??u,m={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(e),signal:d},f=await this._redirects(this._fetch??fetch)(this._url,m);if(a&&f.ok)this._sessionId=f.headers.get("mcp-session-id")||void 0;if(!f.ok){if(f.status===401&&this._authProvider){if(f.headers.has("www-authenticate")){let{resourceMetadataUrl:H,scope:x}=Ai(f);this._resourceMetadataUrl=H,this._scope=wu(this._scope,x)}if(this._authProvider.onUnauthorized&&!r){try{await this._authProvider.onUnauthorized({response:f,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(H){throw Xe(H)}return await f.text?.().catch(()=>{}),this._send(e,t,!0,o)}if(await f.text?.().catch(()=>{}),r)throw Xe(new vt(O.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:f.statusText}));throw Xe(new wt)}let v=await f.text?.().catch(()=>null);if(f.status===403){let{resourceMetadataUrl:H,scope:x,error:Z,errorDescription:R}=Ai(f);if(Z==="insufficient_scope"){if(await this._stepUpAuthorize({scope:x,resourceMetadataUrl:H,errorDescription:R,statusText:f.statusText,text:v},o)!=="AUTHORIZED")throw Xe(new wt);return this._send(e,t,r,o+1)}}if(f.status===400&&typeof v==="string"&&this._isModernEnvelopedRequest(e))try{let H=st.parse(JSON.parse(v)),x=(Array.isArray(e)?e:[e]).filter((Z)=>Fr(Z));if(Wo(H)&&x.some((Z)=>Z.id===H.id)){this.onmessage?.(H);return}}catch{}let U=this._unfollowedRedirect(this._url,f)??v;throw new vt(O.ClientHttpNotImplemented,`Error POSTing to endpoint: ${U}`,{status:f.status,statusText:f.statusText,text:v})}if(f.status===202){if(await f.text?.().catch(()=>{}),rg(e))this._startOrAuthSse({resumptionToken:void 0}).catch((v)=>this.onerror?.(v));return}let S=(Array.isArray(e)?e:[e]).some((v)=>("method"in v)&&("id"in v)&&v.id!==void 0),b=f.headers.get("content-type"),y=fg(b);if(S)if(y==="text/event-stream")this._handleSseStream(f.body,{onresumptiontoken:s,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(y==="application/json"){let v=await f.json(),U=Array.isArray(v)?v.map((H)=>st.parse(H)):[st.parse(v)];for(let H of U)this.onmessage?.(H)}else throw await f.text?.().catch(()=>{}),new N(O.ClientHttpUnexpectedContent,`Unexpected content type: ${b}`,{contentType:b});else await f.text?.().catch(()=>{})}catch(n){if(t?.requestSignal?.aborted!==!0)this.onerror?.(n);throw n}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await this._redirects(this._fetch??fetch)(this._url,t);if(await r.text?.().catch(()=>{}),!r.ok&&r.status!==405)throw new vt(O.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,r)??r.statusText}`,{status:r.status,statusText:r.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})}};class iS{_eventSlots=new Map;setHandler(e,t){let r=this._ensureEventSlot(e);if(r.onHandler&&t)console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`);r.onHandler=t}getHandler(e){return this._eventSlots.get(e)?.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let r=this._eventSlots.get(e);if(!r)return;let o=r.listeners.indexOf(t);if(o!==-1)r.listeners.splice(o,1)}dispatch(e,t){let r=this._eventSlots.get(e);if(!r)return;r.onHandler?.(t);for(let o of[...r.listeners])o(t)}_ensureEventSlot(e){let t=this._eventSlots.get(e);if(!t)t={listeners:[]},this._eventSlots.set(e,t);return t}}class aS{_methods=new Set;claim(e,t){if(this._methods.has(e))throw Error(`Handler for "${e}" already registered (via ${t}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._methods.add(e)}replace(e){this._methods.add(e)}release(e){this._methods.delete(e)}has(e){return this._methods.has(e)}}var tS=new Set;function rS(e,t){let[r,o]=t,n=r?.shape;if(typeof n?.method?.value!=="string")return;let s=n.method.value,i=e==="request"?"setRequestHandler":"setNotificationHandler";if(!tS.has(i))tS.add(i),console.warn(`[ext-apps] ${i}(Schema, handler) is deprecated; use ${i}("${s}", { params: Schema.shape.params }, handler).`);let a=o;return[s,{params:n.params},e==="request"?(l,u)=>a({method:s,params:l},Lz(u)):(l)=>a({method:s,params:l})]}function Lz(e){return{signal:e.mcpReq.signal,requestId:e.mcpReq.id,sessionId:e.sessionId,_meta:e.mcpReq._meta,sendRequest:e.mcpReq.send,sendNotification:e.mcpReq.notify,authInfo:e.http?.authInfo}}var cS="2026-01-26";var Uz="ui/notifications/tool-input-partial";var Zz=T([h("light"),h("dark")]).describe("Color theme preference for the host environment."),ji=T([h("inline"),h("fullscreen"),h("pip")]).describe("Display mode for UI presentation."),Dz=T([h("--color-background-primary"),h("--color-background-secondary"),h("--color-background-tertiary"),h("--color-background-inverse"),h("--color-background-ghost"),h("--color-background-info"),h("--color-background-danger"),h("--color-background-success"),h("--color-background-warning"),h("--color-background-disabled"),h("--color-text-primary"),h("--color-text-secondary"),h("--color-text-tertiary"),h("--color-text-inverse"),h("--color-text-ghost"),h("--color-text-info"),h("--color-text-danger"),h("--color-text-success"),h("--color-text-warning"),h("--color-text-disabled"),h("--color-border-primary"),h("--color-border-secondary"),h("--color-border-tertiary"),h("--color-border-inverse"),h("--color-border-ghost"),h("--color-border-info"),h("--color-border-danger"),h("--color-border-success"),h("--color-border-warning"),h("--color-border-disabled"),h("--color-ring-primary"),h("--color-ring-secondary"),h("--color-ring-inverse"),h("--color-ring-info"),h("--color-ring-danger"),h("--color-ring-success"),h("--color-ring-warning"),h("--font-sans"),h("--font-mono"),h("--font-weight-normal"),h("--font-weight-medium"),h("--font-weight-semibold"),h("--font-weight-bold"),h("--font-text-xs-size"),h("--font-text-sm-size"),h("--font-text-md-size"),h("--font-text-lg-size"),h("--font-heading-xs-size"),h("--font-heading-sm-size"),h("--font-heading-md-size"),h("--font-heading-lg-size"),h("--font-heading-xl-size"),h("--font-heading-2xl-size"),h("--font-heading-3xl-size"),h("--font-text-xs-line-height"),h("--font-text-sm-line-height"),h("--font-text-md-line-height"),h("--font-text-lg-line-height"),h("--font-heading-xs-line-height"),h("--font-heading-sm-line-height"),h("--font-heading-md-line-height"),h("--font-heading-lg-line-height"),h("--font-heading-xl-line-height"),h("--font-heading-2xl-line-height"),h("--font-heading-3xl-line-height"),h("--border-radius-xs"),h("--border-radius-sm"),h("--border-radius-md"),h("--border-radius-lg"),h("--border-radius-xl"),h("--border-radius-full"),h("--border-width-regular"),h("--shadow-hairline"),h("--shadow-sm"),h("--shadow-md"),h("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),Fz=P(Dz.describe(`Style variables for theming MCP apps.
81
82
 
82
83
  Individual style keys are optional - hosts may provide any subset of these values.
83
84
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
84
85
 
85
86
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
86
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),T([c(),Vl()]).describe(`Style variables for theming MCP apps.
87
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),T([c(),Jl()]).describe(`Style variables for theming MCP apps.
87
88
 
88
89
  Individual style keys are optional - hosts may provide any subset of these values.
89
90
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
@@ -95,10 +96,10 @@ Individual style keys are optional - hosts may provide any subset of these value
95
96
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
96
97
 
97
98
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
98
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Dz=p({method:h("ui/open-link"),params:p({url:c().describe("URL to open in the host's browser")})}),Fz=p({isError:E().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),Hz=p({isError:E().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),Vz=p({isError:E().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),Jz=p({method:h("ui/notifications/sandbox-proxy-ready"),params:p({})}),qu=p({connectDomains:g(c()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
99
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Hz=p({method:h("ui/open-link"),params:p({url:c().describe("URL to open in the host's browser")})}),Vz=p({isError:E().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),Jz=p({isError:E().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),Bz=p({isError:E().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),Wz=p({method:h("ui/notifications/sandbox-proxy-ready"),params:p({})}),Au=p({connectDomains:g(c()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
99
100
 
100
101
  - Maps to CSP \`connect-src\` directive
101
- - Empty or omitted → no network connections (secure default)`),resourceDomains:g(c()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:g(c()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:g(c()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),Au=p({camera:p({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:p({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:p({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:p({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),Bz=p({method:h("ui/notifications/size-changed"),params:p({width:z().optional().describe("New width in pixels."),height:z().optional().describe("New height in pixels.")})}),jP=p({method:h("ui/notifications/tool-input"),params:p({arguments:P(c(),A().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),LP=p({method:h("ui/notifications/tool-input-partial"),params:p({arguments:P(c(),A().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),UP=p({method:h("ui/notifications/tool-cancelled"),params:p({reason:c().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),Wz=p({fonts:c().optional()}),Kz=p({variables:Zz.optional().describe("CSS variables for theming the app."),css:Wz.optional().describe("CSS blocks that apps can inject.")}),ZP=p({method:h("ui/resource-teardown"),params:p({})}),Gz=P(c(),A()),tS=p({text:p({}).optional().describe("Host supports text content blocks."),image:p({}).optional().describe("Host supports image content blocks."),audio:p({}).optional().describe("Host supports audio content blocks."),resource:p({}).optional().describe("Host supports resource content blocks."),resourceLink:p({}).optional().describe("Host supports resource link content blocks."),structuredContent:p({}).optional().describe("Host supports structured content.")}),Yz=p({method:h("ui/notifications/request-teardown"),params:p({}).optional()}),Xz=p({experimental:P(c(),P(c(),Aa()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:p({}).optional().describe("Host supports opening external URLs."),downloadFile:p({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:p({listChanged:E().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:p({listChanged:E().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:p({}).optional().describe("Host accepts log messages."),sandbox:p({permissions:Au.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:qu.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:tS.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:tS.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:p({tools:p({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),Qz=p({experimental:P(c(),P(c(),Aa()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:p({listChanged:E().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:g(ji).optional().describe("Display modes the app supports.")}),ew=p({method:h("ui/notifications/initialized"),params:p({}).optional()}),DP=p({csp:qu.optional().describe("Content Security Policy configuration for UI resources."),permissions:Au.optional().describe("Sandbox permissions requested by the UI resource."),domain:c().optional().describe(`Dedicated origin for view sandbox.
102
+ - Empty or omitted → no network connections (secure default)`),resourceDomains:g(c()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:g(c()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:g(c()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),Mu=p({camera:p({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:p({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:p({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:p({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),Kz=p({method:h("ui/notifications/size-changed"),params:p({width:z().optional().describe("New width in pixels."),height:z().optional().describe("New height in pixels.")})}),ZP=p({method:h("ui/notifications/tool-input"),params:p({arguments:P(c(),A().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),DP=p({method:h("ui/notifications/tool-input-partial"),params:p({arguments:P(c(),A().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),FP=p({method:h("ui/notifications/tool-cancelled"),params:p({reason:c().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),Gz=p({fonts:c().optional()}),Yz=p({variables:Fz.optional().describe("CSS variables for theming the app."),css:Gz.optional().describe("CSS blocks that apps can inject.")}),HP=p({method:h("ui/resource-teardown"),params:p({})}),Xz=P(c(),A()),oS=p({text:p({}).optional().describe("Host supports text content blocks."),image:p({}).optional().describe("Host supports image content blocks."),audio:p({}).optional().describe("Host supports audio content blocks."),resource:p({}).optional().describe("Host supports resource content blocks."),resourceLink:p({}).optional().describe("Host supports resource link content blocks."),structuredContent:p({}).optional().describe("Host supports structured content.")}),Qz=p({method:h("ui/notifications/request-teardown"),params:p({}).optional()}),ew=p({experimental:P(c(),P(c(),Ma()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:p({}).optional().describe("Host supports opening external URLs."),downloadFile:p({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:p({listChanged:E().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:p({listChanged:E().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:p({}).optional().describe("Host accepts log messages."),sandbox:p({permissions:Mu.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:Au.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:oS.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:oS.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:p({tools:p({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),tw=p({experimental:P(c(),P(c(),Ma()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:p({listChanged:E().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:g(ji).optional().describe("Display modes the app supports.")}),rw=p({method:h("ui/notifications/initialized"),params:p({}).optional()}),VP=p({csp:Au.optional().describe("Content Security Policy configuration for UI resources."),permissions:Mu.optional().describe("Sandbox permissions requested by the UI resource."),domain:c().optional().describe(`Dedicated origin for view sandbox.
102
103
 
103
104
  Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
104
105
 
@@ -112,12 +113,13 @@ Boolean requesting whether a visible border and background is provided by the ho
112
113
 
113
114
  - \`true\`: request visible border + background
114
115
  - \`false\`: request no visible border + background
115
- - omitted: host decides border`)}),rS=p({method:h("ui/request-display-mode"),params:p({mode:ji.describe("The display mode being requested.")})}),oS=p({mode:ji.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),tw=T([h("model"),h("app")]).describe("Tool visibility scope - who can access the tool."),FP=p({resourceUri:c().optional(),visibility:g(tw).optional().describe(`Who can access this tool. Default: ["model", "app"]
116
+ - omitted: host decides border`)}),nS=p({method:h("ui/request-display-mode"),params:p({mode:ji.describe("The display mode being requested.")})}),sS=p({mode:ji.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),ow=T([h("model"),h("app")]).describe("Tool visibility scope - who can access the tool."),JP=p({resourceUri:c().optional(),visibility:g(ow).optional().describe(`Who can access this tool. Default: ["model", "app"]
116
117
  - "model": Tool visible to and callable by the agent
117
- - "app": Tool callable by the app from this server only`),csp:Jl().optional(),permissions:Jl().optional()}),HP=p({mimeTypes:g(c()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),rw=p({method:h("ui/download-file"),params:p({contents:g(T([Nr,qr])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),ow=p({method:h("ui/message"),params:p({role:h("user").describe('Message role, currently only "user" is supported.'),content:g(yt).describe("Message content blocks (text, image, etc.).")})}),VP=p({method:h("ui/notifications/sandbox-resource-ready"),params:p({html:c().describe("HTML content to load into the inner iframe."),sandbox:c().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:qu.optional().describe("CSP configuration from resource metadata."),permissions:Au.optional().describe("Sandbox permissions from resource metadata.")})}),JP=p({method:h("ui/notifications/tool-result"),params:nr.describe("Standard MCP tool execution result.")}),aS=p({toolInfo:p({id:nt.optional().describe("JSON-RPC id of the tools/call request."),tool:or.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:Lz.optional().describe("Current color theme preference."),styles:Kz.optional().describe("Style configuration for theming the app."),displayMode:ji.optional().describe("How the UI is currently displayed."),availableDisplayModes:g(ji).optional().describe("Display modes the host supports."),containerDimensions:T([p({height:z().describe("Fixed container height in pixels.")}),p({maxHeight:T([z(),Vl()]).optional().describe("Maximum container height in pixels.")})]).and(T([p({width:z().describe("Fixed container width in pixels.")}),p({maxWidth:T([z(),Vl()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
118
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:c().optional().describe("User's language and region preference in BCP 47 format."),timeZone:c().optional().describe("User's timezone in IANA format."),userAgent:c().optional().describe("Host application identifier."),platform:T([h("web"),h("desktop"),h("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p({touch:E().optional().describe("Whether the device supports touch input."),hover:E().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p({top:z().describe("Top safe area inset in pixels."),right:z().describe("Right safe area inset in pixels."),bottom:z().describe("Bottom safe area inset in pixels."),left:z().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),BP=p({method:h("ui/notifications/host-context-changed"),params:aS.describe("Partial context update containing only changed fields.")}),nw=p({method:h("ui/update-model-context"),params:p({content:g(yt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:P(c(),A().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),sw=p({method:h("ui/initialize"),params:p({appInfo:_t.describe("App identification (name and version)."),appCapabilities:Qz.describe("Features and capabilities this app provides."),protocolVersion:c().describe("Protocol version this app supports.")})}),iw=p({protocolVersion:c().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:_t.describe("Host application identification and version."),hostCapabilities:Xz.describe("Features and capabilities provided by the host."),hostContext:aS.describe("Rich context about the host environment.")}).passthrough();class Li{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=(r)=>{if(t&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let o=st.safeParse(r.data);if(o.success)console.debug("Parsed message",o.data),this.onmessage?.(o.data);else if(r.data?.jsonrpc!=="2.0")console.debug("Ignoring non-JSON-RPC message",o.error.message,r);else console.error("Failed to parse message",o.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+o.error.message))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,t){if(e.method!==jz)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var aw=[iS];class Ui extends bc{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new nS;_methods=new sS;setRequestHandler=(...e)=>{let[t,...r]=eS("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...r)};setNotificationHandler=(...e)=>{let[t,...r]=eS("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...r)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_wrapHandler(e,t){let r=super._wrapHandler(e,t);if(e==="ui/initialize"||e==="ping")return r;return async(o,n)=>{if(!this._initializedReceived)console.warn(`[ext-apps] AppBridge received '${e}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`);return r(o,n)}}eventSchemas={sizechange:Bz,sandboxready:Jz,initialized:ew,requestteardown:Yz,loggingmessage:Ar};setEventHandler(e,t){this._ensureEventSlot(e),this._events.setHandler(e,t)}getEventHandler(e){return this._events.getHandler(e)}addEventListener(e,t){this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);let r=(o)=>{if(e==="initialized")this._initializedReceived=!0;this._events.dispatch(e,o)};if(e==="loggingmessage")this.setNotificationHandler("notifications/message",(o)=>{r(o.params)});else this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(o)=>r(o));this._registeredEvents.add(e)}warnIfRequestHandlerReplaced(e,t,r){if(t&&r)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t,r,o){super(o);this._client=e,this._hostInfo=t,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=o?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:sw.shape.params,result:iw},(n)=>this._onAppsInitialize(n)),this.replaceRequestHandler("ping",(n,s)=>(this.onping?.(n.params,s),{})),this.replaceRequestHandler("ui/request-display-mode",{params:rS.shape.params,result:oS},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(e){return e}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(e){this.setEventHandler("sizechange",e)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(e){this.setEventHandler("sandboxready",e)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(e){this.setEventHandler("initialized",e)}_onmessage;get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,e),this._onmessage=e,this.replaceRequestHandler("ui/message",{params:ow.shape.params,result:Vz},async(t,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(t,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler("ui/open-link",{params:Dz.shape.params,result:Fz},async(t,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(t,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler("ui/download-file",{params:rw.shape.params,result:Hz},async(t,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(t,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(e){this.setEventHandler("requestteardown",e)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler("ui/request-display-mode",{params:rS.shape.params,result:oS},async(t,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(t,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(e){this.setEventHandler("loggingmessage",e)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler("ui/update-model-context",{params:nw.shape.params,result:tr},async(t,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(t,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",async(t,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(e){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,e),this._oncreatesamplingmessage=e,this.replaceRequestHandler("sampling/createMessage",async(t,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(t.params,r)})}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler("resources/list",async(t,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(t.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler("resources/templates/list",async(t,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(t.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler("resources/read",async(t,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(t.params,r)})}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler("prompts/list",async(t,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(t.params,r)})}sendPromptListChanged(e={}){return this.notification({method:"notifications/prompts/list_changed",params:e})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(e){let t=e.protocolVersion;if(this._appInfo!==void 0)console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values.");return this._appCapabilities=e.appCapabilities,this._appInfo=e.appInfo,{protocolVersion:aw.includes(t)?t:iS,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},r=!1;for(let o of Object.keys(e)){let n=this._hostContext[o],s=e[o];if(cw(n,s))continue;t[o]=s,r=!0}if(r)this._hostContext=e,this.sendHostContextChange(t)}sendHostContextChange(e){return this.notification({method:"ui/notifications/host-context-changed",params:e})}sendToolInput(e){return this.notification({method:"ui/notifications/tool-input",params:e})}sendToolInputPartial(e){return this.notification({method:"ui/notifications/tool-input-partial",params:e})}sendToolResult(e){return this.notification({method:"ui/notifications/tool-result",params:e})}sendToolCancelled(e){return this.notification({method:"ui/notifications/tool-cancelled",params:e})}sendSandboxResourceReady(e){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:e})}teardownResource(e,t){return this.request({method:"ui/resource-teardown",params:e},Gz,t)}sendResourceTeardown=this.teardownResource;callTool(e,t){return this.request({method:"tools/call",params:e},t)}listTools(e,t){return this.request({method:"tools/list",params:e},t)}async connect(e){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let t=this._client.getServerCapabilities();if(!t)throw Error("Client server capabilities not available");if(t.tools){if(this.oncalltool=async(r,o)=>this._client.request({method:"tools/call",params:r},{signal:o.mcpReq.signal}),t.tools.listChanged)this._client.setNotificationHandler("notifications/tools/list_changed",(r)=>this.sendToolListChanged(r.params))}if(t.resources){if(this.onlistresources=async(r,o)=>this._client.request({method:"resources/list",params:r},{signal:o.mcpReq.signal}),this.onlistresourcetemplates=async(r,o)=>this._client.request({method:"resources/templates/list",params:r},{signal:o.mcpReq.signal}),this.onreadresource=async(r,o)=>this._client.request({method:"resources/read",params:r},{signal:o.mcpReq.signal}),t.resources.listChanged)this._client.setNotificationHandler("notifications/resources/list_changed",(r)=>this.sendResourceListChanged(r.params))}if(t.prompts){if(this.onlistprompts=async(r,o)=>this._client.request({method:"prompts/list",params:r},{signal:o.mcpReq.signal}),t.prompts.listChanged)this._client.setNotificationHandler("notifications/prompts/list_changed",(r)=>this.sendPromptListChanged(r.params))}}return super.connect(e)}}function cw(e,t){return JSON.stringify(e)===JSON.stringify(t)}var cS=[200,800],lw=(e)=>e?.name==="TypeError"&&/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.)$/.test(e.message);function uw(e,t){return new Promise((r,o)=>{t?.throwIfAborted();let s=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(s),t.removeEventListener("abort",i),o(t.reason)};t?.addEventListener("abort",i,{once:!0})})}function lS(e,{signal:t,onDiagnostic:r,wait:o=uw}={}){return async(n)=>{for(let s=1;;s++){t?.throwIfAborted();try{let i=await e(n);if(t?.throwIfAborted(),s>1)r?.({state:"recovered",uri:n.uri,attempt:s});return i}catch(i){if(t?.throwIfAborted(),!lw(i))throw i;if(s>cS.length)throw r?.({state:"exhausted",uri:n.uri,attempt:s,message:i.message}),Object.assign(Error(`MCP resource transport failed for ${n.uri} after ${s} attempts: ${i.message}. Inspect the host connection and browser network diagnostics; this resource-loading error does not establish a component assertion failure.`,{cause:i}),{code:"ADS_RESOURCE_TRANSPORT"});let a=cS[s-1];r?.({state:"retry",uri:n.uri,attempt:s,nextAttempt:s+1,delayMs:a,message:i.message}),await o(a,t)}}}}function uS(e){let t=[],r=new Map;for(let o of e){if(!o.group){t.push(o);continue}if(!r.has(o.group))r.set(o.group,[]);r.get(o.group).push(o)}return[...t.length?[{label:null,entries:t}]:[],...[...r].sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>({label:o,entries:n}))]}async function pS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:s,callTool:i,context:a,onError:l,onState:u}){let d={slot:e,title:t,sandboxUrl:r,resourceUri:o,readResource:s,callTool:i,context:a,onError:l,onState:u},m=n,f,S,b,y=!1;function v(){if(y||b)return;u?.({state:"loading"}),b=Promise.resolve().then(async()=>{if(await S,await f?.close(),y)return;S=dS({...d,result:m,onReopen:v});try{f=await S}finally{S=void 0}}).catch((L)=>{if(!y)l(L)}).finally(()=>{b=void 0})}S=dS({...d,result:m,onReopen:v});try{f=await S}finally{S=void 0}return{async updateResult(L){if(m=L,await b,!y)await f.updateResult(m)},refreshContext(){if(!y&&!b)f.refreshContext()},async close(){y=!0,await b,await f?.close()}}}async function dS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:s,callTool:i,context:a,onError:l,onState:u,onReopen:d}){let m=!1,S=(await s({uri:o})).contents.find((x)=>x.mimeType==="text/html;profile=mcp-app"&&typeof x.text==="string");if(!S)throw Error("Comparison preview App is unavailable.");let b=document.createElement("iframe");b.title=t,b.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),b.src=r,e.append(b);let y=new Ui(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:a(b)});y.onreadresource=s,y.oncalltool=i,y.onerror=(x)=>{if(!m)l(x)},y.onloggingmessage=(x)=>{if(m||x.logger!=="ads-preview")return;if(x.data?.code==="ADS_PREVIEW_REOPEN"){d();return}if(u?.(x.data),x.data?.state==="error")l(Error(x.data.message))};let v,L=new Promise((x,U)=>{v=setTimeout(()=>U(Error("Comparison App initialization timed out.")),15000),y.oninitialized=()=>{clearTimeout(v),x()}});y.onsandboxready=()=>y.sendSandboxResourceReady({html:S.text,csp:S._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});let F=new ResizeObserver(()=>y.setHostContext(a(b)));try{await Promise.all([y.connect(new Li(b.contentWindow,b.contentWindow)),L]),F.observe(b),await y.sendToolInput({arguments:{}}),await y.sendToolResult(n)}catch(x){throw F.disconnect(),b.remove(),await y.close(),x}finally{clearTimeout(v)}return{updateResult:(x)=>y.sendToolResult(x),refreshContext:()=>y.setHostContext(a(b)),async close(){m=!0,F.disconnect();try{await y.teardownResource({},{timeout:500})}catch{}await y.close(),b.remove()}}}function Mu(e,t){return t===e||t.startsWith(e+"/")||t.startsWith(e+".")}function hS(e,t,r,o=new Map){let n=new Map(r.map(({id:l,title:u,revision:d,state:m,preview:f})=>[l,{id:l,title:u,revision:d,state:m,...f?{preview:f}:{}}])),s=new Map(e.map((l)=>[l.id,{...l,drafts:(l.drafts??[]).flatMap((u)=>n.has(u.id)?[n.get(u.id)]:[])}]));for(let l of t){let u=s.get(l.id);s.set(l.id,{...u,...l,kind:"tokens",drafts:u?.drafts??[]})}let i=(l,u)=>l==="tokens"&&u.kind==="tokens"||(u.unit?u.unit===l:Mu(l,u.id)),a=(l,u)=>{if(!l.drafts.some((d)=>d.id===u.id))l.drafts.push(n.get(u.id))};for(let l of r){let u=o.get(l.id);for(let d of u?.scenarios??[]){if(!l.units.some((f)=>i(f,d)))continue;let m=s.get(d.id);if(!m)m={...d,draftOnly:!0,drafts:[]},s.set(d.id,m);a(m,l)}}for(let l of r)for(let u of l.units){let d=u.split("/")[0];if(!["tokens","components","patterns","composition"].includes(d))continue;let m=[...s.values()].filter((f)=>i(u,f));if(m.length)for(let f of m)a(f,l);else s.set(u,{id:u,unit:u,title:u.split("/").at(-1),kind:d,draftOnly:!0,pendingDraftScenario:!0,drafts:[n.get(l.id)]})}return{scenarios:[...s.values()],categories:[...s.values()].filter((l)=>l.kind==="tokens")}}function mS(e,t,r){let o=e.drafts?.find((l)=>l.id===r)??e.drafts?.[0],n=o&&(t?.drafts?.find((l)=>l.id===o.id)??o.preview),s=o?n?.scenarios?.find((l)=>l.id===e.id)??n:t?.previews?.find((l)=>l.id===e.id)??e.build,i=s?.state==="error"?"error":s?.state==="checking"||s?.live?"checking":s?.building||["queued","building"].includes(s?.state)?"building":s?.current?"ready":s?.stale?"stale":"unreported";return{state:i,label:`${o?"Draft · ":""}${{error:"Preview build failed",checking:"Preview compiled; checking changes",building:"Preview build in progress",ready:"Preview build complete",stale:"Previous preview; current source not built",unreported:"Preview not built"}[i]}${o&&i==="ready"?" · unaccepted":""}`}}var fS={unreported:'<circle cx="8" cy="8" r="3"/>',building:'<circle cx="8" cy="8" r="5" stroke-dasharray="22 10"/>',checking:'<circle cx="8" cy="8" r="5" stroke-dasharray="3 3"/><path d="m6 8 1.5 1.5L10 6"/>',ready:'<circle cx="8" cy="8" r="5"/><path d="m5.5 8 1.7 1.7 3.3-3.4"/>',stale:'<circle cx="8" cy="8" r="5" stroke-dasharray="2 3"/>',error:'<circle cx="8" cy="8" r="5"/><path d="M8 5.5v3M8 10.5h.01"/>'};var V=(e)=>document.getElementById(e),at=new URLSearchParams(location.search),gS=at.get("scenario")??at.get("category"),dw=["tokens","components","patterns","composition"],Yo=[],_e,Ec=at.get("draft"),Vu=[],bS=[],Ju=new Map,en=at.get("split")==="1",Uu,tn=[],Dt=0,Cc;async function Ic(){let e=tn;tn=[],await Promise.allSettled(e.map((t)=>t.close()))}var Qe=document.createElement("button");Qe.id="split-view";Qe.setAttribute("aria-label","Split view");Qe.setAttribute("aria-pressed","false");Qe.disabled=!0;Qe.title="Select a draft with an accepted version to compare";Qe.innerHTML='<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1" y="2" width="14" height="12" rx="1"/><path d="M8 2v12"/></svg>';V("viewport").before(Qe);var he="tokens",Le={},SS=new Map,xc=!0,Bu=[],Wu=[],Oc=[],Go,Ji,me,Ue,Ko,Fi,Xo,Zu,Zi,Rt=0,Qo=at.get("capture")!=="1"&&at.get("viewport")==="phone",ar=at.get("capture")==="1"&&at.get("theme")==="dark"?"dark":"light";if(at.get("capture")==="1")document.documentElement.dataset.capture="true";document.documentElement.dataset.theme=ar;var ju,yS=!0,Pc=!1,kc,Du,Nc=!1,Hi=!1,Jr,ir,Lu=0,Di,Wr=new AbortController,xt=new Yg({name:"ads-showcase",version:"1.0.0"},{versionNegotiation:{mode:"auto"},capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}),vS=(e,t={},r={})=>xt.callTool({name:e,arguments:t},{signal:Wr.signal,...r}),$c=lS((e)=>xt.readResource(e,{signal:Wr.signal}),{signal:Wr.signal,onDiagnostic:(e)=>{if(e.state==="retry")document.documentElement.dataset.adsResourceRetries=String(Number(document.documentElement.dataset.adsResourceRetries??0)+1);console.warn("ADS resource transport",e)}}),zS=async(e)=>JSON.parse((await $c({uri:e})).contents.find((t)=>typeof t.text==="string").text);function wS(e){let t=Oc.find((r)=>r.name===e.name);if(!t||!(t._meta?.ui?.visibility??["model","app"]).includes("app"))throw Error("This tool is not callable from an App.");return xt.callTool(e)}function Se(e,t=!1,r=t?"error":e?"checking":"ready"){let o=e||"Preview is up to date.";if(V("preview-error").hidden=!t,V("preview-error-message").textContent=t?o:"",V("status").textContent=o,V("status").dataset.error=String(t),t)V("status").removeAttribute("role");else V("status").setAttribute("role","status");V("preview-status").dataset.phase=r,V("preview-status").title=o,V("preview-status").setAttribute("aria-label",`Preview status: ${o.split(`
119
- `)[0]}`),RS()}function RS(){let e=Ji?.warmup,t=e?`Background views: ${e.completed}/${e.total} compiled${e.failed?`; ${e.failed} failed`:""}.`:"";V("warmup-status").hidden=!e,V("warmup-status").textContent=t,V("preview-status").dataset.warmup=e?.state??"disabled",V("preview-status").title=[V("status").textContent,t].filter(Boolean).join(`
120
- `)}function xS(){Se(me?"Updating preview…":"Opening preview…",!1,"reloading")}function rn(){return Bi().find((e)=>e.id===Le[he])}function on(e=rn()){let t=Yo.find((r)=>r.id===Ec&&Ju.get(r.id)?.scenario===e?.id);return e?.drafts?.find((r)=>r.id===Ec)??t??e?.drafts?.[0]}function Ku(){return Boolean(on()&&(rn()?.draftOnly||en))}function Vi(){return`${he}:${Le[he]}${Ku()?`:draft:${on().id}`:""}`}function Tc(e=me){return e?.key===Vi()}function PS(e=Ji){if(Ku()){let t=e?.drafts?.find((r)=>r.id===on()?.id);return t?.scenarios?.find((r)=>r.id===Le[he])??t}return e?.previews?.find((t)=>t.id===Le[he])}var TS=(e)=>JSON.stringify(e&&[e.session,e.revision,e.current,e.live]);function ES(){({scenarios:Wu,categories:Bu}=hS(Vu,bS,Yo,Ju))}function pw(e){Ju.set(e.structuredContent.id,e.structuredContent),ES()}async function Fu(e,t,r=Wr.signal){let o=(Go?.previewWatch?.buildTimeoutMs??30000)+15000;try{return await vS(e,t,{signal:AbortSignal.any([Wr.signal,r]),timeout:o})}catch(n){if(n.code!=="REQUEST_TIMEOUT")throw n;throw Object.assign(Error(`The preview request timed out after ${Math.ceil(o/1000)} seconds. No preview result was received. Retry the preview.`,{cause:n}),{code:"ADS_PREVIEW_REQUEST_TIMEOUT",category:"transport"})}}async function Gu(e,t,r){let o=rn()?.id===t&&rn().pendingDraftScenario||e.units?.includes(t)&&!Vu.some((s)=>s.id===t),n=await Fu("ads_show_draft",{id:e.id,...!o&&t?{scenario:t}:{}},r);if(n.isError)throw Error(n.content?.find((s)=>s.type==="text")?.text??"Draft preview failed.");if(o){let s=n.structuredContent.scenarios.find((i)=>t==="tokens"?i.kind==="tokens":i.unit?i.unit===t:Mu(t,i.id));if(!s)throw Error("Draft owner has no scenario yet. Add an independently mountable scenario before previewing it.");if(s.id!==n.structuredContent.scenario)n=await Fu("ads_show_draft",{id:e.id,scenario:s.id},r);if(n.isError)throw Error(n.content?.find((i)=>i.type==="text")?.text??"Draft preview failed.")}return pw(n),n}function cr(e=!1){if(e)Zi=me?.key;Xo=void 0,V("loader").hidden=!0,V("preview").setAttribute("aria-busy","false")}function _S(e){let t=new URL(location.href);for(let n of["scenario","category","draft","split"])t.searchParams.delete(n);if(e)t.searchParams.set("scenario",e);let r=Bi().find((n)=>n.id===e),o=on(r);if(o&&(r.draftOnly||en)){if(t.searchParams.set("draft",o.id),!r.draftOnly)t.searchParams.set("split","1")}return t.pathname+t.search+t.hash}function Bi(){return he==="tokens"?Bu:Wu.filter((e)=>e.kind===he)}function kS(e,t){let{state:r,label:o}=mS(t,Ji,Ec),n=e.querySelector(".entry-preview");if(!n)n=document.createElement("span"),n.className="entry-preview",n.setAttribute("aria-hidden","true"),e.append(n);n.dataset.state=r,n.title=o,n.innerHTML=`<svg viewBox="0 0 16 16">${fS[r]}</svg>`,e.dataset.buildState=r,e.setAttribute("aria-description",o)}function Yu(){return{theme:ar,displayMode:"inline",containerDimensions:{width:V("frame-slot").clientWidth,height:V("frame-slot").clientHeight}}}function Wi(){let e=Bi();if(!e.some((o)=>o.id===Le[he]))Le[he]=e[0]?.id??null;history.replaceState(null,"",_S(Le[he]));let t=V("sidebar").scrollTop;V("entries").setAttribute("aria-label",he[0].toUpperCase()+he.slice(1));let r=(o)=>{let n=document.createElement("a");if(n.textContent=o.title,o.drafts?.length){let s=document.createElement("span");s.className="draft-badge",s.textContent=o.drafts.length>1?`Drafts ${o.drafts.length}`:"Draft",s.title=o.draftOnly?"Draft only; no accepted version yet":"Draft available; use Split view to compare",n.append(" ",s)}if(n.href=_S(o.id),n.dataset.scenario=o.id,kS(n,o),o.id===Le[he])n.setAttribute("aria-current","page");return n.addEventListener("click",(s)=>{if(s.button||s.metaKey||s.ctrlKey||s.shiftKey||s.altKey)return;s.preventDefault(),Le[he]=o.id,Wi(),Ft().catch(Pt)}),n};V("entries").replaceChildren(...uS(e).flatMap((o)=>{if(!o.label)return o.entries.map(r);let n=`${he}:${o.label}`,s=document.createElement("details");s.className="entry-group",s.open=SS.get(n)??!0;let i=document.createElement("summary");i.textContent=o.label;let a=document.createElement("div");return a.setAttribute("role","group"),a.setAttribute("aria-label",o.label),a.append(...o.entries.map(r)),s.append(i,a),s.addEventListener("toggle",()=>{if(s.isConnected)SS.set(n,s.open)}),[s]})),V("sidebar").scrollTop=t;for(let o of V("sections").querySelectorAll("button"))if(o.dataset.section===he)o.setAttribute("aria-current","page");else o.removeAttribute("aria-current");Hu()}function Pt(e){if(!Nc&&!Hi)cr(),V("status").dataset.errorCategory=e.category??(e.code==="ADS_RESOURCE_TRANSPORT"?"transport":"runner"),V("status").dataset.errorCode=e.code??"ADS_HOST_STARTUP",Se(`${e.message}${me?`
121
- The retained preview is not verified against the current source.`:""}`,!0)}async function Br(e){if(!e)return;try{await e.teardownResource({},{timeout:500})}catch{}await e.close()}function $S(){if(Nc||Hi)return;Hi=!0,Wr.abort(),++Rt,clearTimeout(kc),cr(),Se("MCP disconnected. The retained preview is stale. Refresh the page after restarting ADS.",!0);let e=Ue;Ue=void 0,Br(e),++Dt,Ic()}async function Xu(){let e=await zS("ads://project/explorer");Go=e.status,Ji=Go.build,Oc=e.tools,bS=e.categories,Vu=e.scenarios,Yo=e.drafts,V("title").textContent=(Go.drafts?.previewOnly?"Draft · ":"")+Go.project.showcase.title,V("title").title=Go.projectRoot,ES();let t=xc?gS:Le[he],r=xc&&Yo.find((s)=>s.id===Ec),o=me?.draft&&Yo.find((s)=>s.id===me.draftId);if(r||o&&_e&&(o.revision!==_e.revision||_e.discovery?.state==="pending")){let s=await Gu(r||o,r?gS:_e.scenario);if(r)t=s.structuredContent.scenario;if(me?.draft&&o){_e=s.structuredContent,Cc=s;for(let i of tn)if(i.side==="draft")await i.updateResult(s)}}let n=Wu.find((s)=>s.id===t);if(n&&dw.includes(n.kind))he=n.kind,Le[he]=n.id;else if(xc&&Bu.some((s)=>s.id===t))Le.tokens=t;xc=!1,Wi()}function Ft({force:e=!1}={}){if(Hi)return Promise.resolve();let t=Le[he],r=Vi();if(Ko?.key===r)return Ko.promise;if(!e&&Fi?.key===r)return Promise.resolve();if(!e&&!Ko&&me?.key===r)return Promise.resolve();Fi=void 0;let o={key:r};return Ko=o,o.promise=hw(t,r,he==="tokens").finally(()=>{if(Ko===o)Ko=void 0}),o.promise}async function hw(e,t,r){Zu?.abort();let o=Zu=new AbortController,n=++Rt;Xo=!0,V("loader").hidden=t===Zi,V("preview").setAttribute("aria-busy","true");try{if(++Dt,await Ic(),n!==Rt)return;if(Ku()){await Br(Ue),Ue=void 0,Jr=void 0,ir=void 0;let u=on(),d=await Gu(u,e,o.signal);if(n!==Rt)return;if(_e=d.structuredContent,Cc=d,rn()?.pendingDraftScenario||!Bi().some((m)=>m.id===e))Le[he]=_e.scenario;me={key:Vi(),id:_e.scenario,draftId:u.id,generation:n,draft:!0},Hu(),await gw(),Wi(),cr(!0),Se("Draft preview only. Acceptance checks have not run.",!1,"ready");return}if(_e=void 0,Hu(),!e&&!r){if(await Br(Ue),n!==Rt)return;Ue=void 0,me=void 0,Zi=void 0,Jr=void 0,ir=void 0,V("frame-slot").replaceChildren(),cr(),Se("No scenarios discovered. Colocate an independently mountable scenario and fixture with the public implementation.");return}let s=Oc.find((u)=>u.name===(r?"ads_show_tokens":"ads_show_scenario"));if(!s?._meta?.ui?.resourceUri)throw Error("The server did not expose a preview App tool.");let i=r?e?{category:e}:{}:{id:e};if(s.inputSchema?.properties?.waitFor)i.waitFor=at.get("capture")==="1"||at.get("waitFor")==="verified"?"verified":"compiled";xS();let a=await Fu(s.name,i,o.signal);if(n!==Rt)return;if(a.isError)throw Object.assign(Error(a.content?.find((u)=>u.type==="text")?.text??"Preview build failed."),a.structuredContent?.failure);me={key:t,id:e,generation:n,token:r&&!a.structuredContent?.scenario,build:a.structuredContent?.build,manifestRevision:a.structuredContent?.manifestRevision};let l=await mw(s._meta.ui.resourceUri);if(n!==Rt)return;if(Jr==="ui://ads/preview"&&!me.manifestRevision)throw Error("The resource preview has no manifest revision.");if(Zi!==t)Zi=void 0;if(await l.sendToolInput({arguments:i}),await l.sendToolResult(a),n===Rt&&!a.structuredContent?.manifestUri)cr(!0),Se("")}catch(s){if(n===Rt)Fi={key:Vi(),build:TS(PS())},Pt(s)}}async function mw(e){if(Jr===e&&ir)return ir;let t=++Lu,r=Ue;Ue=void 0,Jr=e,ir=(async()=>{await Br(r);let o=await $c({uri:e});if(t!==Lu||Nc||Hi)throw Error("Preview opening was superseded.");let n=o.contents.find((u)=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text==="string");if(!n)throw Error("The preview resource contains no MCP App.");let s=document.createElement("iframe");s.title="Design-system preview",s.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),s.src=Di,V("frame-slot").replaceChildren(s);let i=new Ui(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:Yu()});Ue=i,i.onreadresource=(u)=>$c(u),i.oncalltool=wS,i.onloggingmessage=(u)=>{if(i!==Ue||u.logger!=="ads-preview"||me?.generation!==Rt||!Tc()||u.data?.id!==me?.id)return;let d=u.data.revision===me.manifestRevision||u.data.selectionRevision===me.manifestRevision;if(u.data.state==="ready"&&d)me.manifestRevision=u.data.revision,cr(!0),Se("");else if(u.data.state==="checking"&&(!Xo||d))cr(!0),Se("Checking changes…");else if(u.data.state==="loading")Se("Updating preview…",!1,"reloading");else if(u.data.state==="reverting")Se("Restoring the last verified preview…",!1,"reverting");else if(u.data.code==="ADS_PREVIEW_REOPEN")Ue=void 0,Jr=void 0,ir=void 0,xS(),Br(i).then(()=>Ft({force:!0})).catch(Pt);else if(u.data.state==="error")cr(),Se(u.data.message,!0)},i.onerror=Pt;let a,l=new Promise((u,d)=>{a=setTimeout(()=>d(Error("MCP App initialization timed out.")),15000),i.oninitialized=()=>{clearTimeout(a),u()}});i.onsandboxready=()=>i.sendSandboxResourceReady({html:n.text,csp:n._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});try{await Promise.all([i.connect(new Li(s.contentWindow,s.contentWindow)),l])}catch(u){throw await Br(i),u}finally{clearTimeout(a)}return i})();try{return await ir}catch(o){if(t===Lu)Jr=void 0,ir=void 0;throw o}}async function fw(){let e=me,t=await zS("ads://project/build");Ji=t,RS();for(let o of V("entries").querySelectorAll("a[data-scenario]")){let n=Bi().find((s)=>s.id===o.dataset.scenario);if(n)kS(o,n)}if(Fi?.key===Vi()){let o=PS(t);if(o&&(o.current||o.live)&&TS(o)!==Fi.build)await Ft({force:!0});return}if(!e||e.token||Xo||!Tc(e))return;if(e.draft){let o=t.drafts?.find((i)=>i.id===e.draftId),n=o?.scenarios?.find((i)=>i.id===_e?.scenario)??o,s=n&&JSON.stringify([o?.session,n.revision,n.live?.revision,n.current]);if(n&&(n.current||n.live)&&e.buildSignature!==s){e.buildSignature=s;let i=Yo.find((a)=>a.id===e.draftId);if(i){let a=await Gu(i,_e.scenario);if(me!==e||Xo||!Tc(e))return;_e=a.structuredContent,Cc=a;for(let l of tn)if(l.side==="draft")await l.updateResult(a)}}if(n?.state==="error")Se("Draft preview build failed. Showing the previous preview.",!0);else if(n?.building)Se(n.live||n.state==="checking"?"Draft preview compiled; checking changes…":"Building draft preview… Showing the previous preview.",!1,n.live||n.state==="checking"?"checking":"compiling");else if(n?.current&&Uu?.state==="ready")Se("Draft preview ready · unaccepted.");return}if(me!==e||Xo||!Tc(e))return;let r=t.previews.find((o)=>o.id===e.id);if(!r){Se("The selected scenario is no longer registered.",!0);return}if(["idle","building"].includes(r.state)&&e.build?.current&&r.session===e.build.session&&r.revision<=e.build.revision)return;if(r.state==="error"){Se(`Preview build failed. Showing an earlier view.
122
- ${r.diagnostics.map((o)=>`${o.file??""}${o.line?`:${o.line}`:""}: ${o.message}`).join(`
123
- `)}`,!0);return}if(["idle","building"].includes(r.state)){Se(r.live?"Checking changes…":"Compiling changes… The current view is the previous preview.",!1,r.live?"checking":"compiling");return}if(r.current&&(r.revision!==e.build?.revision||r.session!==e.build?.session))await Ft({force:!0})}function Ki(e=!1,t=!1){if(Pc||=e,t&&me?.token)me.key="invalidated";if(clearTimeout(kc),yS)return;kc=setTimeout(()=>{if(ju){Ki(e,t);return}ju=(async()=>{if(Pc)Pc=!1,await Xu();await Ft(),await fw()})().catch(Pt).finally(()=>{ju=void 0})},150)}async function gw(){if(!_e)return;let e=_e,t=Cc;Uu=void 0;let r=++Dt;if(await Ic(),r!==Dt)return;let o=en&&e.acceptedExists;Qe.setAttribute("aria-pressed",String(o));let n=document.createElement("div");n.className="draft-comparison",n.dataset.split=String(o);for(let s of o?["accepted","draft"]:["draft"]){let i=document.createElement("section");i.className="draft-version";let a=document.createElement("h2");a.dataset.version=s,a.textContent=s==="accepted"?"Accepted":"Draft · unaccepted";let l=document.createElement("div");l.className="draft-stage",l.dataset.version=s,i.append(a,l),n.append(i)}V("frame-slot").replaceChildren(n),await Promise.all([...n.querySelectorAll(".draft-stage")].map(async(s)=>{let i=s.dataset.version,a=i==="draft"?t:await vS("ads_show_scenario",{id:e.scenario,waitFor:"compiled"});if(a.isError)throw Error(a.content?.find((d)=>d.type==="text")?.text??"Comparison build failed.");if(r!==Dt)return;let l=Oc.find((d)=>d.name===(i==="draft"?"ads_show_draft":"ads_show_scenario")),u=await pS({slot:s,title:i==="draft"?"Draft version":"Accepted version",sandboxUrl:Di,resourceUri:l._meta.ui.resourceUri,result:a,readResource:$c,callTool:wS,context:(d)=>({theme:ar,displayMode:"inline",containerDimensions:{width:d.clientWidth,height:d.clientHeight}}),onError:(d)=>{if(r===Dt)Pt(d)},onState:(d)=>{if(r!==Dt||i!=="draft")return;if(Uu=d,d.state==="ready")Se("Draft preview ready · unaccepted.");else if(d.state==="checking")Se("Draft preview compiled; checking changes…",!1,"checking");else if(["loading","reverting"].includes(d.state))Se("Updating draft preview…",!1,"reloading")}});if(r!==Dt)await u.close();else tn.push({...u,side:i})}))}function Hu(){let e=rn(),t=Boolean(on(e))&&!e?.draftOnly;Qe.disabled=!t,Qe.title=e?.draftOnly?"No accepted version yet":t?"Compare accepted and draft versions":"No draft for this entry",Qe.setAttribute("aria-pressed",String(t&&en));let r=document.querySelector('.draft-version h2[data-version="draft"]');if(r&&_e){let o={draft:"unaccepted",checking:"checking acceptance",failed:"acceptance failed",conflict:"source conflict",interrupted:"acceptance interrupted","dependency-error":"dependency needs attention"};r.textContent=`Draft · ${o[_e.state]??_e.state}`,r.title=_e.dependencies?.length?`Draft dependencies: ${_e.dependencies.join(", ")}`:""}}Qe.addEventListener("click",()=>{en=!en,Wi(),Ft().catch(Pt)});for(let e of V("sections").querySelectorAll("button"))e.addEventListener("click",()=>{he=e.dataset.section,Wi(),Ft().catch(Pt)});var Qu=window.matchMedia("(max-width: 760px)");function CS(e){document.body.classList.toggle("collapsed",e),V("pane-toggle").setAttribute("aria-expanded",String(!e)),V("pane-toggle").setAttribute("aria-label",e?"Show navigation pane":"Hide navigation pane"),V("pane-toggle").title=e?"Show navigation pane":"Hide navigation pane",V("pane-toggle").querySelector("path").setAttribute("d",e?"M6 4l4 4-4 4":"M10 4l-4 4 4 4")}var ed=()=>CS(V("header").hidden||Qu.matches);ed();Qu.addEventListener("change",ed);V("pane-toggle").addEventListener("click",()=>CS(!document.body.classList.contains("collapsed")));function IS(){document.documentElement.dataset.viewport=Qo?"phone":"auto",V("viewport").setAttribute("aria-pressed",String(Qo)),V("viewport").title=Qo?"Use available preview width":"Preview at phone width (390 px)"}IS();V("viewport").addEventListener("click",()=>{Qo=!Qo,IS();let e=new URL(location.href);if(Qo)e.searchParams.set("viewport","phone");else e.searchParams.delete("viewport");history.replaceState(null,"",e.pathname+e.search+e.hash)});V("theme").addEventListener("click",()=>{ar=ar==="light"?"dark":"light",document.documentElement.dataset.theme=ar,V("theme").setAttribute("aria-label",ar==="dark"?"Use light theme":"Use dark theme"),V("theme").title=V("theme").getAttribute("aria-label"),V("theme").querySelector("svg").innerHTML=ar==="dark"?'<circle cx="8" cy="8" r="3"/><path d="M8 1v1M8 14v1M1 8h1M14 8h1M3 3l1 1M12 12l1 1M3 13l1-1M12 4l1-1"/>':'<path d="M13.5 9a5.5 5.5 0 0 1-6.5-6.5A5.5 5.5 0 1 0 13.5 9Z"/>',Ue?.setHostContext(Yu())});V("theme").addEventListener("click",()=>{for(let e of tn)e.refreshContext()});V("minimize").addEventListener("click",()=>{V("header").hidden=!0,document.body.classList.add("collapsed")});var OS=new ResizeObserver(()=>Ue?.setHostContext(Yu()));OS.observe(V("frame-slot"));V("retry-preview").addEventListener("click",()=>{(async()=>{await Xu(),await Ft({force:!0})})().catch(Pt)});window.addEventListener("pagehide",()=>{Nc=!0,Zu?.abort(),Wr.abort(),clearTimeout(kc),OS.disconnect(),Qu.removeEventListener("change",ed),Br(Ue),++Dt,Ic(),Du?.close(),xt.close()},{once:!0});xt.onclose=$S;xt.setNotificationHandler("notifications/resources/list_changed",()=>Ki(!0));xt.setNotificationHandler("notifications/tools/list_changed",()=>Ki(!0));xt.setNotificationHandler("notifications/resources/updated",({params:e})=>Ki(e.uri==="ads://project/explorer",e.uri==="ads://project/tokens"));try{if(Di=(await fetch("/host.json").then((e)=>e.json())).sandboxUrl,!Di||new URL(Di).origin===location.origin)throw Error("The separate-origin MCP App sandbox is unavailable.");if(await xt.connect(new Xg(new URL("/mcp",location.href))),Du=await xt.listen({resourcesListChanged:!0,toolsListChanged:!0,resourceSubscriptions:["ads://project/build","ads://project/tokens","ads://project/explorer"]}),Du.closed.then((e)=>{if(e!=="local")$S()}),await Xu(),yS=!1,await Ft(),Pc)Ki()}catch(e){Pt(e)}
118
+ - "app": Tool callable by the app from this server only`),csp:Bl().optional(),permissions:Bl().optional()}),BP=p({mimeTypes:g(c()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),nw=p({method:h("ui/download-file"),params:p({contents:g(T([Nr,qr])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),sw=p({method:h("ui/message"),params:p({role:h("user").describe('Message role, currently only "user" is supported.'),content:g(yt).describe("Message content blocks (text, image, etc.).")})}),WP=p({method:h("ui/notifications/sandbox-resource-ready"),params:p({html:c().describe("HTML content to load into the inner iframe."),sandbox:c().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Au.optional().describe("CSP configuration from resource metadata."),permissions:Mu.optional().describe("Sandbox permissions from resource metadata.")})}),KP=p({method:h("ui/notifications/tool-result"),params:nr.describe("Standard MCP tool execution result.")}),lS=p({toolInfo:p({id:nt.optional().describe("JSON-RPC id of the tools/call request."),tool:or.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:Zz.optional().describe("Current color theme preference."),styles:Yz.optional().describe("Style configuration for theming the app."),displayMode:ji.optional().describe("How the UI is currently displayed."),availableDisplayModes:g(ji).optional().describe("Display modes the host supports."),containerDimensions:T([p({height:z().describe("Fixed container height in pixels.")}),p({maxHeight:T([z(),Jl()]).optional().describe("Maximum container height in pixels.")})]).and(T([p({width:z().describe("Fixed container width in pixels.")}),p({maxWidth:T([z(),Jl()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
119
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:c().optional().describe("User's language and region preference in BCP 47 format."),timeZone:c().optional().describe("User's timezone in IANA format."),userAgent:c().optional().describe("Host application identifier."),platform:T([h("web"),h("desktop"),h("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p({touch:E().optional().describe("Whether the device supports touch input."),hover:E().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p({top:z().describe("Top safe area inset in pixels."),right:z().describe("Right safe area inset in pixels."),bottom:z().describe("Bottom safe area inset in pixels."),left:z().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),GP=p({method:h("ui/notifications/host-context-changed"),params:lS.describe("Partial context update containing only changed fields.")}),iw=p({method:h("ui/update-model-context"),params:p({content:g(yt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:P(c(),A().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),aw=p({method:h("ui/initialize"),params:p({appInfo:_t.describe("App identification (name and version)."),appCapabilities:tw.describe("Features and capabilities this app provides."),protocolVersion:c().describe("Protocol version this app supports.")})}),cw=p({protocolVersion:c().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:_t.describe("Host application identification and version."),hostCapabilities:ew.describe("Features and capabilities provided by the host."),hostContext:lS.describe("Rich context about the host environment.")}).passthrough();class Li{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=(r)=>{if(t&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let o=st.safeParse(r.data);if(o.success)console.debug("Parsed message",o.data),this.onmessage?.(o.data);else if(r.data?.jsonrpc!=="2.0")console.debug("Ignoring non-JSON-RPC message",o.error.message,r);else console.error("Failed to parse message",o.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+o.error.message))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,t){if(e.method!==Uz)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var lw=[cS];class Ui extends yc{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new iS;_methods=new aS;setRequestHandler=(...e)=>{let[t,...r]=rS("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...r)};setNotificationHandler=(...e)=>{let[t,...r]=rS("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...r)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_wrapHandler(e,t){let r=super._wrapHandler(e,t);if(e==="ui/initialize"||e==="ping")return r;return async(o,n)=>{if(!this._initializedReceived)console.warn(`[ext-apps] AppBridge received '${e}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`);return r(o,n)}}eventSchemas={sizechange:Kz,sandboxready:Wz,initialized:rw,requestteardown:Qz,loggingmessage:Ar};setEventHandler(e,t){this._ensureEventSlot(e),this._events.setHandler(e,t)}getEventHandler(e){return this._events.getHandler(e)}addEventListener(e,t){this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);let r=(o)=>{if(e==="initialized")this._initializedReceived=!0;this._events.dispatch(e,o)};if(e==="loggingmessage")this.setNotificationHandler("notifications/message",(o)=>{r(o.params)});else this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(o)=>r(o));this._registeredEvents.add(e)}warnIfRequestHandlerReplaced(e,t,r){if(t&&r)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t,r,o){super(o);this._client=e,this._hostInfo=t,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=o?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:aw.shape.params,result:cw},(n)=>this._onAppsInitialize(n)),this.replaceRequestHandler("ping",(n,s)=>(this.onping?.(n.params,s),{})),this.replaceRequestHandler("ui/request-display-mode",{params:nS.shape.params,result:sS},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(e){return e}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(e){this.setEventHandler("sizechange",e)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(e){this.setEventHandler("sandboxready",e)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(e){this.setEventHandler("initialized",e)}_onmessage;get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,e),this._onmessage=e,this.replaceRequestHandler("ui/message",{params:sw.shape.params,result:Bz},async(t,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(t,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler("ui/open-link",{params:Hz.shape.params,result:Vz},async(t,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(t,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler("ui/download-file",{params:nw.shape.params,result:Jz},async(t,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(t,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(e){this.setEventHandler("requestteardown",e)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler("ui/request-display-mode",{params:nS.shape.params,result:sS},async(t,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(t,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(e){this.setEventHandler("loggingmessage",e)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler("ui/update-model-context",{params:iw.shape.params,result:tr},async(t,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(t,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",async(t,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(e){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,e),this._oncreatesamplingmessage=e,this.replaceRequestHandler("sampling/createMessage",async(t,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(t.params,r)})}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler("resources/list",async(t,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(t.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler("resources/templates/list",async(t,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(t.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler("resources/read",async(t,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(t.params,r)})}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler("prompts/list",async(t,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(t.params,r)})}sendPromptListChanged(e={}){return this.notification({method:"notifications/prompts/list_changed",params:e})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(e){let t=e.protocolVersion;if(this._appInfo!==void 0)console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values.");return this._appCapabilities=e.appCapabilities,this._appInfo=e.appInfo,{protocolVersion:lw.includes(t)?t:cS,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},r=!1;for(let o of Object.keys(e)){let n=this._hostContext[o],s=e[o];if(uw(n,s))continue;t[o]=s,r=!0}if(r)this._hostContext=e,this.sendHostContextChange(t)}sendHostContextChange(e){return this.notification({method:"ui/notifications/host-context-changed",params:e})}sendToolInput(e){return this.notification({method:"ui/notifications/tool-input",params:e})}sendToolInputPartial(e){return this.notification({method:"ui/notifications/tool-input-partial",params:e})}sendToolResult(e){return this.notification({method:"ui/notifications/tool-result",params:e})}sendToolCancelled(e){return this.notification({method:"ui/notifications/tool-cancelled",params:e})}sendSandboxResourceReady(e){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:e})}teardownResource(e,t){return this.request({method:"ui/resource-teardown",params:e},Xz,t)}sendResourceTeardown=this.teardownResource;callTool(e,t){return this.request({method:"tools/call",params:e},t)}listTools(e,t){return this.request({method:"tools/list",params:e},t)}async connect(e){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let t=this._client.getServerCapabilities();if(!t)throw Error("Client server capabilities not available");if(t.tools){if(this.oncalltool=async(r,o)=>this._client.request({method:"tools/call",params:r},{signal:o.mcpReq.signal}),t.tools.listChanged)this._client.setNotificationHandler("notifications/tools/list_changed",(r)=>this.sendToolListChanged(r.params))}if(t.resources){if(this.onlistresources=async(r,o)=>this._client.request({method:"resources/list",params:r},{signal:o.mcpReq.signal}),this.onlistresourcetemplates=async(r,o)=>this._client.request({method:"resources/templates/list",params:r},{signal:o.mcpReq.signal}),this.onreadresource=async(r,o)=>this._client.request({method:"resources/read",params:r},{signal:o.mcpReq.signal}),t.resources.listChanged)this._client.setNotificationHandler("notifications/resources/list_changed",(r)=>this.sendResourceListChanged(r.params))}if(t.prompts){if(this.onlistprompts=async(r,o)=>this._client.request({method:"prompts/list",params:r},{signal:o.mcpReq.signal}),t.prompts.listChanged)this._client.setNotificationHandler("notifications/prompts/list_changed",(r)=>this.sendPromptListChanged(r.params))}}return super.connect(e)}}function uw(e,t){return JSON.stringify(e)===JSON.stringify(t)}var uS=[200,800],dw=(e)=>e?.name==="TypeError"&&/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.)$/.test(e.message);function pw(e,t){return new Promise((r,o)=>{t?.throwIfAborted();let s=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(s),t.removeEventListener("abort",i),o(t.reason)};t?.addEventListener("abort",i,{once:!0})})}function dS(e,{signal:t,onDiagnostic:r,wait:o=pw}={}){return async(n)=>{for(let s=1;;s++){t?.throwIfAborted();try{let i=await e(n);if(t?.throwIfAborted(),s>1)r?.({state:"recovered",uri:n.uri,attempt:s});return i}catch(i){if(t?.throwIfAborted(),!dw(i))throw i;if(s>uS.length)throw r?.({state:"exhausted",uri:n.uri,attempt:s,message:i.message}),Object.assign(Error(`MCP resource transport failed for ${n.uri} after ${s} attempts: ${i.message}. Inspect the host connection and browser network diagnostics; this resource-loading error does not establish a component assertion failure.`,{cause:i}),{code:"ADS_RESOURCE_TRANSPORT"});let a=uS[s-1];r?.({state:"retry",uri:n.uri,attempt:s,nextAttempt:s+1,delayMs:a,message:i.message}),await o(a,t)}}}}function pS(e){let t=[],r=new Map;for(let o of e){if(!o.group){t.push(o);continue}if(!r.has(o.group))r.set(o.group,[]);r.get(o.group).push(o)}return[...t.length?[{label:null,entries:t}]:[],...[...r].sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>({label:o,entries:n}))]}async function mS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:s,callTool:i,context:a,onError:l,onState:u}){let d={slot:e,title:t,sandboxUrl:r,resourceUri:o,readResource:s,callTool:i,context:a,onError:l,onState:u},m=n,f,S,b,y=!1;function v(){if(y||b)return;u?.({state:"loading"}),b=Promise.resolve().then(async()=>{if(await S,await f?.close(),y)return;S=hS({...d,result:m,onReopen:v});try{f=await S}finally{S=void 0}}).catch((U)=>{if(!y)l(U)}).finally(()=>{b=void 0})}S=hS({...d,result:m,onReopen:v});try{f=await S}finally{S=void 0}return{async updateResult(U){if(m=U,await b,!y)await f.updateResult(m)},refreshContext(){if(!y&&!b)f.refreshContext()},async close(){y=!0,await b,await f?.close()}}}async function hS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:s,callTool:i,context:a,onError:l,onState:u,onReopen:d}){let m=!1,S=(await s({uri:o})).contents.find((x)=>x.mimeType==="text/html;profile=mcp-app"&&typeof x.text==="string");if(!S)throw Error("Comparison preview App is unavailable.");let b=document.createElement("iframe");b.title=t,b.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),b.src=r,e.append(b);let y=new Ui(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:a(b)});y.onreadresource=s,y.oncalltool=i,y.onerror=(x)=>{if(!m)l(x)},y.onloggingmessage=(x)=>{if(m||x.logger!=="ads-preview")return;if(x.data?.code==="ADS_PREVIEW_REOPEN"){d();return}if(u?.(x.data),x.data?.state==="error")l(Error(x.data.message))};let v,U=new Promise((x,Z)=>{v=setTimeout(()=>Z(Error("Comparison App initialization timed out.")),15000),y.oninitialized=()=>{clearTimeout(v),x()}});y.onsandboxready=()=>y.sendSandboxResourceReady({html:S.text,csp:S._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});let H=new ResizeObserver(()=>y.setHostContext(a(b)));try{await Promise.all([y.connect(new Li(b.contentWindow,b.contentWindow)),U]),H.observe(b),await y.sendToolInput({arguments:{}}),await y.sendToolResult(n)}catch(x){throw H.disconnect(),b.remove(),await y.close(),x}finally{clearTimeout(v)}return{updateResult:(x)=>y.sendToolResult(x),refreshContext:()=>y.setHostContext(a(b)),async close(){m=!0,H.disconnect();try{await y.teardownResource({},{timeout:500})}catch{}await y.close(),b.remove()}}}function ju(e,t){return t===e||t.startsWith(e+"/")||t.startsWith(e+".")}function fS(e,t,r,o=new Map){let n=new Map(r.map(({id:l,title:u,revision:d,state:m,preview:f})=>[l,{id:l,title:u,revision:d,state:m,...f?{preview:f}:{}}])),s=new Map(e.map((l)=>[l.id,{...l,drafts:(l.drafts??[]).flatMap((u)=>n.has(u.id)?[n.get(u.id)]:[])}]));for(let l of t){let u=s.get(l.id);s.set(l.id,{...u,...l,kind:"tokens",drafts:u?.drafts??[]})}let i=(l,u)=>l==="tokens"&&u.kind==="tokens"||(u.unit?u.unit===l:ju(l,u.id)),a=(l,u)=>{if(!l.drafts.some((d)=>d.id===u.id))l.drafts.push(n.get(u.id))};for(let l of r){let u=o.get(l.id);for(let d of u?.scenarios??[]){if(!l.units.some((f)=>i(f,d)))continue;let m=s.get(d.id);if(!m)m={...d,draftOnly:!0,drafts:[]},s.set(d.id,m);a(m,l)}}for(let l of r)for(let u of l.units){let d=u.split("/")[0];if(!["tokens","components","patterns","composition"].includes(d))continue;let m=[...s.values()].filter((f)=>i(u,f));if(m.length)for(let f of m)a(f,l);else s.set(u,{id:u,unit:u,title:u.split("/").at(-1),kind:d,draftOnly:!0,pendingDraftScenario:!0,drafts:[n.get(l.id)]})}return{scenarios:[...s.values()],categories:[...s.values()].filter((l)=>l.kind==="tokens")}}function gS(e,t,r){let o=e.drafts?.find((l)=>l.id===r)??e.drafts?.[0],n=o&&(t?.drafts?.find((l)=>l.id===o.id)??o.preview),s=o?n?.scenarios?.find((l)=>l.id===e.id)??n:t?.previews?.find((l)=>l.id===e.id)??e.build,i=s?.state==="error"?"error":s?.state==="checking"||s?.live?"checking":s?.building||["queued","building"].includes(s?.state)?"building":s?.current?"ready":s?.stale?"stale":"unreported",a={error:pa(s),checking:"Preview compiled; checking changes",building:"Preview build in progress",ready:"Preview build complete",stale:"Previous preview; current source not built",unreported:"Preview not built"};return{state:i,label:`${o?"Draft · ":""}${a[i]}${o&&i==="ready"?" · unaccepted":""}`}}var SS={unreported:'<circle cx="8" cy="8" r="3"/>',building:'<circle cx="8" cy="8" r="5" stroke-dasharray="22 10"/>',checking:'<circle cx="8" cy="8" r="5" stroke-dasharray="3 3"/><path d="m6 8 1.5 1.5L10 6"/>',ready:'<circle cx="8" cy="8" r="5"/><path d="m5.5 8 1.7 1.7 3.3-3.4"/>',stale:'<circle cx="8" cy="8" r="5" stroke-dasharray="2 3"/>',error:'<circle cx="8" cy="8" r="5"/><path d="M8 5.5v3M8 10.5h.01"/>'};var L=(e)=>document.getElementById(e),at=new URLSearchParams(location.search),_S=at.get("scenario")??at.get("category"),hw=["tokens","components","patterns","composition"],Yo=[],_e,kc=at.get("draft"),Ju=[],vS=[],Bu=new Map,en=at.get("split")==="1",Zu,tn=[],Dt=0,Ic;async function Oc(){let e=tn;tn=[],await Promise.allSettled(e.map((t)=>t.close()))}var Qe=document.createElement("button");Qe.id="split-view";Qe.setAttribute("aria-label","Split view");Qe.setAttribute("aria-pressed","false");Qe.disabled=!0;Qe.title="Select a draft with an accepted version to compare";Qe.innerHTML='<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1" y="2" width="14" height="12" rx="1"/><path d="M8 2v12"/></svg>';L("viewport").before(Qe);var he="tokens",Le={},bS=new Map,Pc=!0,Wu=[],Ku=[],Nc=[],Go,Ji,me,Ue,Ko,Fi,Xo,Du,Zi,Rt=0,Qo=at.get("capture")!=="1"&&at.get("viewport")==="phone",ar=at.get("capture")==="1"&&at.get("theme")==="dark"?"dark":"light";if(at.get("capture")==="1")document.documentElement.dataset.capture="true";document.documentElement.dataset.theme=ar;var Lu,zS=!0,Tc=!1,$c,Fu,qc=!1,Hi=!1,Jr,ir,Uu=0,Di,Wr=new AbortController,xt=new Qg({name:"ads-showcase",version:"1.0.0"},{versionNegotiation:{mode:"auto"},capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}),wS=(e,t={},r={})=>xt.callTool({name:e,arguments:t},{signal:Wr.signal,...r}),Cc=dS((e)=>xt.readResource(e,{signal:Wr.signal}),{signal:Wr.signal,onDiagnostic:(e)=>{if(e.state==="retry")document.documentElement.dataset.adsResourceRetries=String(Number(document.documentElement.dataset.adsResourceRetries??0)+1);console.warn("ADS resource transport",e)}}),RS=async(e)=>JSON.parse((await Cc({uri:e})).contents.find((t)=>typeof t.text==="string").text);function xS(e){let t=Nc.find((r)=>r.name===e.name);if(!t||!(t._meta?.ui?.visibility??["model","app"]).includes("app"))throw Error("This tool is not callable from an App.");return xt.callTool(e)}function Se(e,t=!1,r=t?"error":e?"checking":"ready"){let o=e||"Preview is up to date.";if(L("preview-error").hidden=!t,L("preview-error-message").textContent=t?o.split(`
120
+ `)[0]:"",L("preview-error-message").title=t?o:"",L("status").textContent=o,L("status").dataset.error=String(t),!t)for(let n of["errorCategory","errorCode","resourceUri"])delete L("status").dataset[n];if(t)L("status").removeAttribute("role");else L("status").setAttribute("role","status");L("preview-status").dataset.phase=r,L("preview-status").title=o,L("preview-status").setAttribute("aria-label",`Preview status: ${o.split(`
121
+ `)[0]}`),PS()}function PS(){let e=Ji?.warmup,t=e?`Background views: ${e.completed}/${e.total} compiled${e.failed?`; ${e.failed} failed`:""}.`:"";L("warmup-status").hidden=!e,L("warmup-status").textContent=t,L("preview-status").dataset.warmup=e?.state??"disabled",L("preview-status").title=[L("status").textContent,t].filter(Boolean).join(`
122
+ `)}function TS(){Se(me?"Updating preview…":"Opening preview…",!1,"reloading")}function rn(){return Bi().find((e)=>e.id===Le[he])}function on(e=rn()){let t=Yo.find((r)=>r.id===kc&&Bu.get(r.id)?.scenario===e?.id);return e?.drafts?.find((r)=>r.id===kc)??t??e?.drafts?.[0]}function Gu(){return Boolean(on()&&(rn()?.draftOnly||en))}function Vi(){return`${he}:${Le[he]}${Gu()?`:draft:${on().id}`:""}`}function Ec(e=me){return e?.key===Vi()}function ES(e=Ji){if(Gu()){let t=e?.drafts?.find((r)=>r.id===on()?.id);return t?.scenarios?.find((r)=>r.id===Le[he])??t}return e?.previews?.find((t)=>t.id===Le[he])}var kS=(e)=>JSON.stringify(e&&[e.session,e.revision,e.current,e.live]);function $S(){({scenarios:Ku,categories:Wu}=fS(Ju,vS,Yo,Bu))}function mw(e){Bu.set(e.structuredContent.id,e.structuredContent),$S()}async function Hu(e,t,r=Wr.signal){let o=(Go?.previewWatch?.buildTimeoutMs??30000)+15000;try{return await wS(e,t,{signal:AbortSignal.any([Wr.signal,r]),timeout:o})}catch(n){if(n.code!=="REQUEST_TIMEOUT")throw n;throw Object.assign(Error(`The preview request timed out after ${Math.ceil(o/1000)} seconds. No preview result was received. Retry the preview.`,{cause:n}),{code:"ADS_PREVIEW_REQUEST_TIMEOUT",category:"transport"})}}async function Yu(e,t,r){let o=rn()?.id===t&&rn().pendingDraftScenario||e.units?.includes(t)&&!Ju.some((s)=>s.id===t),n=await Hu("ads_show_draft",{id:e.id,...!o&&t?{scenario:t}:{}},r);if(n.isError)throw Error(n.content?.find((s)=>s.type==="text")?.text??"Draft preview failed.");if(o){let s=n.structuredContent.scenarios.find((i)=>t==="tokens"?i.kind==="tokens":i.unit?i.unit===t:ju(t,i.id));if(!s)throw Error("Draft owner has no scenario yet. Add an independently mountable scenario before previewing it.");if(s.id!==n.structuredContent.scenario)n=await Hu("ads_show_draft",{id:e.id,scenario:s.id},r);if(n.isError)throw Error(n.content?.find((i)=>i.type==="text")?.text??"Draft preview failed.")}return mw(n),n}function cr(e=!1){if(e)Zi=me?.key;Xo=void 0,L("loader").hidden=!0,L("preview").setAttribute("aria-busy","false")}function yS(e){let t=new URL(location.href);for(let n of["scenario","category","draft","split"])t.searchParams.delete(n);if(e)t.searchParams.set("scenario",e);let r=Bi().find((n)=>n.id===e),o=on(r);if(o&&(r.draftOnly||en)){if(t.searchParams.set("draft",o.id),!r.draftOnly)t.searchParams.set("split","1")}return t.pathname+t.search+t.hash}function Bi(){return he==="tokens"?Wu:Ku.filter((e)=>e.kind===he)}function CS(e,t){let{state:r,label:o}=gS(t,Ji,kc),n=e.querySelector(".entry-preview");if(!n)n=document.createElement("span"),n.className="entry-preview",n.setAttribute("aria-hidden","true"),e.append(n);n.dataset.state=r,n.title=o,n.innerHTML=`<svg viewBox="0 0 16 16">${SS[r]}</svg>`,e.dataset.buildState=r,e.setAttribute("aria-description",o)}function Xu(){return{theme:ar,displayMode:"inline",containerDimensions:{width:L("frame-slot").clientWidth,height:L("frame-slot").clientHeight}}}function Wi(){let e=Bi();if(!e.some((o)=>o.id===Le[he]))Le[he]=e[0]?.id??null;history.replaceState(null,"",yS(Le[he]));let t=L("sidebar").scrollTop;L("entries").setAttribute("aria-label",he[0].toUpperCase()+he.slice(1));let r=(o)=>{let n=document.createElement("a");if(n.textContent=o.title,o.drafts?.length){let s=document.createElement("span");s.className="draft-badge",s.textContent=o.drafts.length>1?`Drafts ${o.drafts.length}`:"Draft",s.title=o.draftOnly?"Draft only; no accepted version yet":"Draft available; use Split view to compare",n.append(" ",s)}if(n.href=yS(o.id),n.dataset.scenario=o.id,CS(n,o),o.id===Le[he])n.setAttribute("aria-current","page");return n.addEventListener("click",(s)=>{if(s.button||s.metaKey||s.ctrlKey||s.shiftKey||s.altKey)return;s.preventDefault(),Le[he]=o.id,Wi(),Ft().catch(Pt)}),n};L("entries").replaceChildren(...pS(e).flatMap((o)=>{if(!o.label)return o.entries.map(r);let n=`${he}:${o.label}`,s=document.createElement("details");s.className="entry-group",s.open=bS.get(n)??!0;let i=document.createElement("summary");i.textContent=o.label;let a=document.createElement("div");return a.setAttribute("role","group"),a.setAttribute("aria-label",o.label),a.append(...o.entries.map(r)),s.append(i,a),s.addEventListener("toggle",()=>{if(s.isConnected)bS.set(n,s.open)}),[s]})),L("sidebar").scrollTop=t;for(let o of L("sections").querySelectorAll("button"))if(o.dataset.section===he)o.setAttribute("aria-current","page");else o.removeAttribute("aria-current");Vu()}function Pt(e){if(!qc&&!Hi)cr(),L("status").dataset.errorCategory=e.category??(e.code==="ADS_RESOURCE_TRANSPORT"?"transport":"runner"),L("status").dataset.errorCode=e.code??"ADS_HOST_STARTUP",Se(`${e.message}${me?`
123
+ The retained preview is not verified against the current source.`:""}`,!0)}async function Br(e){if(!e)return;try{await e.teardownResource({},{timeout:500})}catch{}await e.close()}function IS(){if(qc||Hi)return;Hi=!0,Wr.abort(),++Rt,clearTimeout($c),cr(),Se("MCP disconnected. The retained preview is stale. Refresh the page after restarting ADS.",!0);let e=Ue;Ue=void 0,Br(e),++Dt,Oc()}async function Qu(){let e=await RS("ads://project/explorer");Go=e.status,Ji=Go.build,Nc=e.tools,vS=e.categories,Ju=e.scenarios,Yo=e.drafts,L("title").textContent=(Go.drafts?.previewOnly?"Draft · ":"")+Go.project.showcase.title,L("title").title=Go.projectRoot,$S();let t=Pc?_S:Le[he],r=Pc&&Yo.find((s)=>s.id===kc),o=me?.draft&&Yo.find((s)=>s.id===me.draftId);if(r||o&&_e&&(o.revision!==_e.revision||_e.discovery?.state==="pending")){let s=await Yu(r||o,r?_S:_e.scenario);if(r)t=s.structuredContent.scenario;if(me?.draft&&o){_e=s.structuredContent,Ic=s;for(let i of tn)if(i.side==="draft")await i.updateResult(s)}}let n=Ku.find((s)=>s.id===t);if(n&&hw.includes(n.kind))he=n.kind,Le[he]=n.id;else if(Pc&&Wu.some((s)=>s.id===t))Le.tokens=t;Pc=!1,Wi()}function Ft({force:e=!1}={}){if(Hi)return Promise.resolve();let t=Le[he],r=Vi();if(Ko?.key===r)return Ko.promise;if(!e&&Fi?.key===r)return Promise.resolve();if(!e&&!Ko&&me?.key===r)return Promise.resolve();Fi=void 0;let o={key:r};return Ko=o,o.promise=fw(t,r,he==="tokens").finally(()=>{if(Ko===o)Ko=void 0}),o.promise}async function fw(e,t,r){Du?.abort();let o=Du=new AbortController,n=++Rt;Xo=!0,L("loader").hidden=t===Zi,L("preview").setAttribute("aria-busy","true");try{if(++Dt,await Oc(),n!==Rt)return;if(Gu()){await Br(Ue),Ue=void 0,Jr=void 0,ir=void 0;let u=on(),d=await Yu(u,e,o.signal);if(n!==Rt)return;if(_e=d.structuredContent,Ic=d,rn()?.pendingDraftScenario||!Bi().some((m)=>m.id===e))Le[he]=_e.scenario;me={key:Vi(),id:_e.scenario,draftId:u.id,generation:n,draft:!0},Vu(),await _w(),Wi(),cr(!0),Se("Draft preview only. Acceptance checks have not run.",!1,"ready");return}if(_e=void 0,Vu(),!e&&!r){if(await Br(Ue),n!==Rt)return;Ue=void 0,me=void 0,Zi=void 0,Jr=void 0,ir=void 0,L("frame-slot").replaceChildren(),cr(),Se("No scenarios discovered. Colocate an independently mountable scenario and fixture with the public implementation.");return}let s=Nc.find((u)=>u.name===(r?"ads_show_tokens":"ads_show_scenario"));if(!s?._meta?.ui?.resourceUri)throw Error("The server did not expose a preview App tool.");let i=r?e?{category:e}:{}:{id:e};if(s.inputSchema?.properties?.waitFor)i.waitFor=at.get("capture")==="1"||at.get("waitFor")==="verified"?"verified":"compiled";TS();let a=await Hu(s.name,i,o.signal);if(n!==Rt)return;if(a.isError)throw Object.assign(Error(a.content?.find((u)=>u.type==="text")?.text??"Preview build failed."),a.structuredContent?.failure);me={key:t,id:e,generation:n,token:r&&!a.structuredContent?.scenario,build:a.structuredContent?.build,manifestRevision:a.structuredContent?.manifestRevision};let l=await gw(s._meta.ui.resourceUri);if(n!==Rt)return;if(Jr==="ui://ads/preview"&&!me.manifestRevision)throw Error("The resource preview has no manifest revision.");if(Zi!==t)Zi=void 0;if(await l.sendToolInput({arguments:i}),await l.sendToolResult(a),n===Rt&&!a.structuredContent?.manifestUri)cr(!0),Se("")}catch(s){if(n===Rt)Fi={key:Vi(),build:kS(ES())},Pt(s)}}async function gw(e){if(Jr===e&&ir)return ir;let t=++Uu,r=Ue;Ue=void 0,Jr=e,ir=(async()=>{await Br(r);let o=await Cc({uri:e});if(t!==Uu||qc||Hi)throw Error("Preview opening was superseded.");let n=o.contents.find((u)=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text==="string");if(!n)throw Error("The preview resource contains no MCP App.");let s=document.createElement("iframe");s.title="Design-system preview",s.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),s.src=Di,L("frame-slot").replaceChildren(s);let i=new Ui(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:Xu()});Ue=i,i.onreadresource=(u)=>Cc(u),i.oncalltool=xS,i.onloggingmessage=(u)=>{if(i!==Ue||u.logger!=="ads-preview"||me?.generation!==Rt||!Ec()||u.data?.id!==me?.id)return;let d=u.data.revision===me.manifestRevision||u.data.selectionRevision===me.manifestRevision;if(u.data.state==="ready"&&d)me.manifestRevision=u.data.revision,cr(!0),Se("");else if(u.data.state==="checking"&&(!Xo||d))cr(!0),Se("Checking changes…");else if(u.data.state==="loading")Se("Updating preview…",!1,"reloading");else if(u.data.state==="reverting")Se("Restoring the last verified preview…",!1,"reverting");else if(u.data.code==="ADS_PREVIEW_REOPEN")Ue=void 0,Jr=void 0,ir=void 0,TS(),Br(i).then(()=>Ft({force:!0})).catch(Pt);else if(u.data.state==="error"){if(cr(),L("status").dataset.errorCategory=u.data.category??"build",L("status").dataset.errorCode=u.data.code??"ADS_PREVIEW_BUILD",u.data.resourceUri)L("status").dataset.resourceUri=u.data.resourceUri;else delete L("status").dataset.resourceUri;Se([u.data.message,u.data.code,u.data.resourceUri].filter(Boolean).join(`
124
+ `),!0)}},i.onerror=Pt;let a,l=new Promise((u,d)=>{a=setTimeout(()=>d(Error("MCP App initialization timed out.")),15000),i.oninitialized=()=>{clearTimeout(a),u()}});i.onsandboxready=()=>i.sendSandboxResourceReady({html:n.text,csp:n._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});try{await Promise.all([i.connect(new Li(s.contentWindow,s.contentWindow)),l])}catch(u){throw await Br(i),u}finally{clearTimeout(a)}return i})();try{return await ir}catch(o){if(t===Uu)Jr=void 0,ir=void 0;throw o}}async function Sw(){let e=me,t=await RS("ads://project/build");Ji=t,PS();for(let o of L("entries").querySelectorAll("a[data-scenario]")){let n=Bi().find((s)=>s.id===o.dataset.scenario);if(n)CS(o,n)}if(Fi?.key===Vi()){let o=ES(t);if(o&&(o.current||o.live)&&kS(o)!==Fi.build)await Ft({force:!0});return}if(!e||e.token||Xo||!Ec(e))return;if(e.draft){let o=t.drafts?.find((i)=>i.id===e.draftId),n=o?.scenarios?.find((i)=>i.id===_e?.scenario)??o,s=n&&JSON.stringify([o?.session,n.revision,n.live?.revision,n.current]);if(n&&(n.current||n.live)&&e.buildSignature!==s){e.buildSignature=s;let i=Yo.find((a)=>a.id===e.draftId);if(i){let a=await Yu(i,_e.scenario);if(me!==e||Xo||!Ec(e))return;_e=a.structuredContent,Ic=a;for(let l of tn)if(l.side==="draft")await l.updateResult(a)}}if(n?.state==="error")Se("Draft preview build failed. Showing the previous preview.",!0);else if(n?.building)Se(n.live||n.state==="checking"?"Draft preview compiled; checking changes…":"Building draft preview… Showing the previous preview.",!1,n.live||n.state==="checking"?"checking":"compiling");else if(n?.current&&Zu?.state==="ready")Se("Draft preview ready · unaccepted.");return}if(me!==e||Xo||!Ec(e))return;let r=t.previews.find((o)=>o.id===e.id);if(!r){Se("The selected scenario is no longer registered.",!0);return}if(["idle","building"].includes(r.state)&&e.build?.current&&r.session===e.build.session&&r.revision<=e.build.revision)return;if(r.state==="error"){Se(`${pa(r)}. Showing an earlier view.
125
+ ${od(r.diagnostics)}`,!0);return}if(["idle","building"].includes(r.state)){Se(r.live?"Checking changes…":"Compiling changes… The current view is the previous preview.",!1,r.live?"checking":"compiling");return}if(r.current&&(r.revision!==e.build?.revision||r.session!==e.build?.session))await Ft({force:!0})}function Ki(e=!1,t=!1){if(Tc||=e,t&&me?.token)me.key="invalidated";if(clearTimeout($c),zS)return;$c=setTimeout(()=>{if(Lu){Ki(e,t);return}Lu=(async()=>{if(Tc)Tc=!1,await Qu();await Ft(),await Sw()})().catch(Pt).finally(()=>{Lu=void 0})},150)}async function _w(){if(!_e)return;let e=_e,t=Ic;Zu=void 0;let r=++Dt;if(await Oc(),r!==Dt)return;let o=en&&e.acceptedExists;Qe.setAttribute("aria-pressed",String(o));let n=document.createElement("div");n.className="draft-comparison",n.dataset.split=String(o);for(let s of o?["accepted","draft"]:["draft"]){let i=document.createElement("section");i.className="draft-version";let a=document.createElement("h2");a.dataset.version=s,a.textContent=s==="accepted"?"Accepted":"Draft · unaccepted";let l=document.createElement("div");l.className="draft-stage",l.dataset.version=s,i.append(a,l),n.append(i)}L("frame-slot").replaceChildren(n),await Promise.all([...n.querySelectorAll(".draft-stage")].map(async(s)=>{let i=s.dataset.version,a=i==="draft"?t:await wS("ads_show_scenario",{id:e.scenario,waitFor:"compiled"});if(a.isError)throw Error(a.content?.find((d)=>d.type==="text")?.text??"Comparison build failed.");if(r!==Dt)return;let l=Nc.find((d)=>d.name===(i==="draft"?"ads_show_draft":"ads_show_scenario")),u=await mS({slot:s,title:i==="draft"?"Draft version":"Accepted version",sandboxUrl:Di,resourceUri:l._meta.ui.resourceUri,result:a,readResource:Cc,callTool:xS,context:(d)=>({theme:ar,displayMode:"inline",containerDimensions:{width:d.clientWidth,height:d.clientHeight}}),onError:(d)=>{if(r===Dt)Pt(d)},onState:(d)=>{if(r!==Dt||i!=="draft")return;if(Zu=d,d.state==="ready")Se("Draft preview ready · unaccepted.");else if(d.state==="checking")Se("Draft preview compiled; checking changes…",!1,"checking");else if(["loading","reverting"].includes(d.state))Se("Updating draft preview…",!1,"reloading")}});if(r!==Dt)await u.close();else tn.push({...u,side:i})}))}function Vu(){let e=rn(),t=Boolean(on(e))&&!e?.draftOnly;Qe.disabled=!t,Qe.title=e?.draftOnly?"No accepted version yet":t?"Compare accepted and draft versions":"No draft for this entry",Qe.setAttribute("aria-pressed",String(t&&en));let r=document.querySelector('.draft-version h2[data-version="draft"]');if(r&&_e){let o={draft:"unaccepted",checking:"checking acceptance",failed:"acceptance failed",conflict:"source conflict",interrupted:"acceptance interrupted","dependency-error":"dependency needs attention"};r.textContent=`Draft · ${o[_e.state]??_e.state}`,r.title=_e.dependencies?.length?`Draft dependencies: ${_e.dependencies.join(", ")}`:""}}Qe.addEventListener("click",()=>{en=!en,Wi(),Ft().catch(Pt)});for(let e of L("sections").querySelectorAll("button"))e.addEventListener("click",()=>{he=e.dataset.section,Wi(),Ft().catch(Pt)});var ed=window.matchMedia("(max-width: 760px)");function OS(e){document.body.classList.toggle("collapsed",e),L("pane-toggle").setAttribute("aria-expanded",String(!e)),L("pane-toggle").setAttribute("aria-label",e?"Show navigation pane":"Hide navigation pane"),L("pane-toggle").title=e?"Show navigation pane":"Hide navigation pane",L("pane-toggle").querySelector("path").setAttribute("d",e?"M6 4l4 4-4 4":"M10 4l-4 4 4 4")}var td=()=>OS(L("header").hidden||ed.matches);td();ed.addEventListener("change",td);L("pane-toggle").addEventListener("click",()=>OS(!document.body.classList.contains("collapsed")));function NS(){document.documentElement.dataset.viewport=Qo?"phone":"auto",L("viewport").setAttribute("aria-pressed",String(Qo)),L("viewport").title=Qo?"Use available preview width":"Preview at phone width (390 px)"}NS();L("viewport").addEventListener("click",()=>{Qo=!Qo,NS();let e=new URL(location.href);if(Qo)e.searchParams.set("viewport","phone");else e.searchParams.delete("viewport");history.replaceState(null,"",e.pathname+e.search+e.hash)});L("theme").addEventListener("click",()=>{ar=ar==="light"?"dark":"light",document.documentElement.dataset.theme=ar,L("theme").setAttribute("aria-label",ar==="dark"?"Use light theme":"Use dark theme"),L("theme").title=L("theme").getAttribute("aria-label"),L("theme").querySelector("svg").innerHTML=ar==="dark"?'<circle cx="8" cy="8" r="3"/><path d="M8 1v1M8 14v1M1 8h1M14 8h1M3 3l1 1M12 12l1 1M3 13l1-1M12 4l1-1"/>':'<path d="M13.5 9a5.5 5.5 0 0 1-6.5-6.5A5.5 5.5 0 1 0 13.5 9Z"/>',Ue?.setHostContext(Xu())});L("theme").addEventListener("click",()=>{for(let e of tn)e.refreshContext()});L("minimize").addEventListener("click",()=>{L("header").hidden=!0,document.body.classList.add("collapsed")});var qS=new ResizeObserver(()=>Ue?.setHostContext(Xu()));qS.observe(L("frame-slot"));L("retry-preview").addEventListener("click",()=>{(async()=>{await Qu(),await Ft({force:!0})})().catch(Pt)});window.addEventListener("pagehide",()=>{qc=!0,Du?.abort(),Wr.abort(),clearTimeout($c),qS.disconnect(),ed.removeEventListener("change",td),Br(Ue),++Dt,Oc(),Fu?.close(),xt.close()},{once:!0});xt.onclose=IS;xt.setNotificationHandler("notifications/resources/list_changed",()=>Ki(!0));xt.setNotificationHandler("notifications/tools/list_changed",()=>Ki(!0));xt.setNotificationHandler("notifications/resources/updated",({params:e})=>Ki(e.uri==="ads://project/explorer",e.uri==="ads://project/tokens"));try{if(Di=(await fetch("/host.json").then((e)=>e.json())).sandboxUrl,!Di||new URL(Di).origin===location.origin)throw Error("The separate-origin MCP App sandbox is unavailable.");if(await xt.connect(new eS(new URL("/mcp",location.href))),Fu=await xt.listen({resourcesListChanged:!0,toolsListChanged:!0,resourceSubscriptions:["ads://project/build","ads://project/tokens","ads://project/explorer"]}),Fu.closed.then((e)=>{if(e!=="local")IS()}),await Qu(),zS=!1,await Ft(),Tc)Ki()}catch(e){Pt(e)}