@reqvire-org/ads 0.3.48 → 0.3.50

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 (94) hide show
  1. package/README.md +36 -6
  2. package/dist/active-clock.mjs +34 -0
  3. package/dist/assets.mjs +20 -2
  4. package/dist/boundaries.mjs +2 -0
  5. package/dist/browser-audit/layout-overflow.mjs +57 -0
  6. package/dist/browser-audit/layout-shift.mjs +32 -0
  7. package/dist/browser-audit/non-text-contrast.mjs +87 -0
  8. package/dist/browser-audit/worker.mjs +36 -7
  9. package/dist/browser-audit.mjs +198 -22
  10. package/dist/check.mjs +14 -1
  11. package/dist/cli.mjs +7 -4
  12. package/dist/component-contrast.mjs +138 -0
  13. package/dist/config.mjs +12 -6
  14. package/dist/finding-rules.mjs +13 -1
  15. package/dist/fonts-generated.mjs +85 -0
  16. package/dist/image-attributes.mjs +110 -0
  17. package/dist/init.mjs +2 -0
  18. package/dist/layout-widths.mjs +184 -0
  19. package/dist/mcp/context.mjs +1 -1
  20. package/dist/mcp/mutations.mjs +7 -5
  21. package/dist/mcp/preview-watch.mjs +9 -8
  22. package/dist/mcp/server.mjs +6 -4
  23. package/dist/palette-generated.mjs +6 -3
  24. package/dist/preview-files.mjs +3 -0
  25. package/dist/project-boundary.mjs +23 -0
  26. package/dist/project-documents.mjs +2 -1
  27. package/dist/scenarios-compiler.mjs +23 -3
  28. package/dist/showcase/client.bundle.js +11 -11
  29. package/dist/showcase/icons.js +5 -5
  30. package/dist/showcase/style.css +1 -1
  31. package/dist/skills/ads-break-ui/SKILL.md +8 -0
  32. package/dist/skills/ads-break-ui/references/atomic-styles.md +2 -0
  33. package/dist/skills/ads-break-ui/references/design-data.md +47 -1
  34. package/dist/skills/ads-break-ui/references/drafts.md +1 -1
  35. package/dist/skills/ads-break-ui/references/guarded-editing.md +1 -1
  36. package/dist/skills/ads-break-ui/references/validation.md +9 -5
  37. package/dist/skills/ads-designer/SKILL.md +24 -4
  38. package/dist/skills/ads-designer/references/accessibility.md +31 -14
  39. package/dist/skills/ads-designer/references/atomic-styles.md +2 -0
  40. package/dist/skills/ads-designer/references/branding.md +10 -5
  41. package/dist/skills/ads-designer/references/cli.md +2 -1
  42. package/dist/skills/ads-designer/references/design-data.md +47 -1
  43. package/dist/skills/ads-designer/references/drafts.md +1 -1
  44. package/dist/skills/ads-designer/references/guarded-editing.md +1 -1
  45. package/dist/skills/ads-designer/references/mobile.md +3 -0
  46. package/dist/skills/ads-designer/references/performance.md +89 -0
  47. package/dist/skills/ads-designer/references/validation.md +9 -5
  48. package/dist/skills/ads-import/references/atomic-styles.md +2 -0
  49. package/dist/skills/ads-import/references/cli.md +2 -1
  50. package/dist/skills/ads-import/references/design-data.md +47 -1
  51. package/dist/skills/ads-import/references/drafts.md +1 -1
  52. package/dist/skills/ads-import/references/guarded-editing.md +1 -1
  53. package/dist/skills/ads-import/references/validation.md +9 -5
  54. package/dist/skills/ads-motion/references/atomic-styles.md +2 -0
  55. package/dist/skills/ads-motion/references/design-data.md +47 -1
  56. package/dist/skills/ads-motion/references/drafts.md +1 -1
  57. package/dist/skills/ads-motion/references/guarded-editing.md +1 -1
  58. package/dist/skills/ads-motion/references/validation.md +9 -5
  59. package/dist/skills/ads-port/references/atomic-styles.md +2 -0
  60. package/dist/skills/ads-port/references/cli.md +2 -1
  61. package/dist/skills/ads-port/references/design-data.md +47 -1
  62. package/dist/skills/ads-port/references/drafts.md +1 -1
  63. package/dist/skills/ads-port/references/guarded-editing.md +1 -1
  64. package/dist/skills/ads-port/references/validation.md +9 -5
  65. package/dist/starters/preact/ds.config.json +1 -0
  66. package/dist/starters/preact/package.json +1 -0
  67. package/dist/starters/react/ADS.md +1 -1
  68. package/dist/starters/react/README.md +14 -2
  69. package/dist/starters/react/design-system/components/Actions/Button/Button.tsx +1 -1
  70. package/dist/starters/react/design-system/components/Content/Image/Image.ads.fixture.ts +2 -0
  71. package/dist/starters/react/design-system/components/Content/Image/Image.ads.scenario.tsx +13 -0
  72. package/dist/starters/react/design-system/components/Content/Image/Image.tsx +48 -0
  73. package/dist/starters/react/design-system/components/Content/Image/README.md +20 -0
  74. package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +2 -2
  75. package/dist/starters/react/design-system/index.ts +1 -0
  76. package/dist/starters/react/design-system/tokens/Layout.ads.fixture.ts +16 -0
  77. package/dist/starters/react/design-system/tokens/spacing.css +18 -0
  78. package/dist/starters/react/ds.config.json +1 -0
  79. package/dist/starters/react/package-lock.json +47 -0
  80. package/dist/starters/react/package.json +2 -1
  81. package/dist/test-boundaries.mjs +30 -1
  82. package/dist/themes-generated.mjs +15 -4
  83. package/dist/token-quality.mjs +61 -24
  84. package/dist/units.mjs +2 -1
  85. package/dist/validation-checks.mjs +5 -4
  86. package/dist/validation.mjs +1 -1
  87. package/dist/verification/browser.mjs +28 -2
  88. package/dist/verification.mjs +5 -4
  89. package/docs/ADS.md +4 -1
  90. package/docs/ARCHITECTURE.md +13 -3
  91. package/docs/CHANGELOG.md +111 -12
  92. package/docs/GUIDE.md +208 -14
  93. package/docs/MCP.md +14 -10
  94. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  function ya(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 md(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
2
  `)}var{create:YS,defineProperty:va,getOwnPropertyDescriptor:XS,getOwnPropertyNames:QS,getPrototypeOf:e_}=Object,t_=Object.prototype.hasOwnProperty,fd=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),gd=(e,t)=>{let r={};for(var o in e)va(r,o,{get:e[o],enumerable:!0});if(t)va(r,Symbol.toStringTag,{value:"Module"});return r},r_=(e,t,r,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(var n=QS(t),i=0,s=n.length,a;i<s;i++)if(a=n[i],!t_.call(e,a)&&a!==r)va(e,a,{get:((l)=>t[l]).bind(null,a),enumerable:!(o=XS(t,a))||o.enumerable})}return e},Sd=(e,t,r)=>(r=e!=null?YS(e_(e)):{},r_(t||!e||!e.__esModule?va(r,"default",{value:e,enumerable:!0}):r,e));var o_=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),_d=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),n_=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),s_=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function bd(e){return typeof e==="string"&&_d.has(e.replace(/#$/,""))}function yd(e,t){if(!("$schema"in e)||typeof e.$schema!=="string")return"2020-12";let r=e.$schema.replace(/#$/,"");if(o_.has(r))return"2020-12";if(_d.has(r))return"2019-09";if(n_.has(r)||s_.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 vd,Wc=Object.freeze({status:"aborted"});function _(e,t,r){function o(a,l){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let u=s.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 i extends n{}Object.defineProperty(i,"name",{value:e});function s(a){var l;let u=r?.Parent?new i:this;o(u,a),(l=u._zod).deferred??(l.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:(a)=>{if(r?.Parent&&a instanceof r.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var i_=Symbol("zod_brand");class Nt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Un extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(vd=globalThis).__zod_globalConfig??(vd.__zod_globalConfig={});var mo=globalThis.__zod_globalConfig;function Ue(e){if(e)Object.assign(mo,e);return mo}function wa(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 Gc(e,t="|"){return e.map((r)=>el(r)).join(t)}function Zn(e,t){if(typeof t==="bigint")return t.toString();return t}function Dn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function Ra(e){return e===null||e===void 0}function xa(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function wd(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 zd=Symbol("evaluating");function ee(e,t,r){let o=void 0;Object.defineProperty(e,t,{get(){if(o===zd)return;if(o===void 0)o=zd,o=r();return o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Tr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function tr(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function Yc(e){return JSON.stringify(e)}function Rd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Xc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function fo(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var xd=Dn(()=>{if(mo.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Er(e){if(fo(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(fo(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Qc(e){if(Er(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 Pd=new Set(["string","number","symbol"]);function rr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function at(e,t,r){let o=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)o._zod.parent=e;return o}function j(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 el(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Td(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Ed={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 a_(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 i=tr(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;s[a]=r.shape[a]}return Tr(this,"shape",s),s},checks:[]});return at(e,i)}function c_(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 i=tr(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete s[a]}return Tr(this,"shape",s),s},checks:[]});return at(e,i)}function l_(e,t){if(!Er(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=tr(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Tr(this,"shape",i),i}});return at(e,n)}function u_(e,t){if(!Er(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=tr(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return Tr(this,"shape",o),o}});return at(e,r)}function d_(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=tr(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return Tr(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return at(e,r)}function p_(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 s=tr(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 Tr(this,"shape",l),l},checks:[]});return at(t,s)}function h_(e,t,r){let o=tr(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in i))throw Error(`Unrecognized key: "${s}"`);if(!r[s])continue;i[s]=new e({type:"nonoptional",innerType:n[s]})}else for(let s in n)i[s]=new e({type:"nonoptional",innerType:n[s]});return Tr(this,"shape",i),i}});return at(t,o)}function kr(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 kd(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 or(e,t){return t.map((r)=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function za(e){return typeof e==="string"?e:e?.message}function ct(e,t,r){let o=e.message?e.message:za(e.inst?._zod.def?.error?.(e))??za(t?.error?.(e))??za(r.customError?.(e))??za(r.localeError?.(e))??"Invalid input",{inst:n,continue:i,input:s,...a}=e;if(a.path??(a.path=[]),a.message=o,t?.reportInput)a.input=s;return a}function Pa(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function $d(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 $r(...e){let[t,r,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:o};return{...t}}var Cd=(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,Zn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ta=_("$ZodError",Cd),tl=_("$ZodError",Cd,{Parent:Error});function rl(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 ol(e,t=(r)=>r.message){let r={_errors:[]},o=(n,i=[])=>{for(let s of n.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>o({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")o({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));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(s));l=l[d],u++}}}};return o(e),r}var Ea=(e)=>(t,r,o,n)=>{let i=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Nt;if(s.issues.length){let a=new(n?.Err??e)(s.issues.map((l)=>ct(l,i,Ue())));throw Xc(a,n?.callee),a}return s.value};var ka=(e)=>async(t,r,o,n)=>{let i=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)s=await s;if(s.issues.length){let a=new(n?.Err??e)(s.issues.map((l)=>ct(l,i,Ue())));throw Xc(a,n?.callee),a}return s.value};var Fn=(e)=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new Nt;return i.issues.length?{success:!1,error:new(e??Ta)(i.issues.map((s)=>ct(s,n,Ue())))}:{success:!0,data:i.value}},Id=Fn(tl),Hn=(e)=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)i=await i;return i.issues.length?{success:!1,error:new e(i.issues.map((s)=>ct(s,n,Ue())))}:{success:!0,data:i.value}},Od=Hn(tl),Nd=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Ea(e)(t,r,n)};var Ad=(e)=>(t,r,o)=>Ea(e)(t,r,o);var qd=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return ka(e)(t,r,n)};var Md=(e)=>async(t,r,o)=>ka(e)(t,r,o);var jd=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Fn(e)(t,r,n)};var Ld=(e)=>(t,r,o)=>Fn(e)(t,r,o);var Ud=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Hn(e)(t,r,n)};var Zd=(e)=>async(t,r,o)=>Hn(e)(t,r,o);var Dd=/^[cC][0-9a-z]{6,}$/,Fd=/^[0-9a-z]+$/,Hd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Vd=/^[0-9a-vA-V]{20}$/,Jd=/^[A-Za-z0-9]{27}$/,Bd=/^[a-zA-Z0-9_-]{21}$/,Wd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Kd=/^([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})$/,nl=(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 Gd=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var f_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Yd(){return new RegExp(f_,"u")}var Xd=/^(?:(?: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])$/,Qd=/^(([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 ep=/^((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])$/,tp=/^(([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])$/,rp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,sl=/^[A-Za-z0-9_-]*$/;var op=/^https?$/,np=/^\+[1-9]\d{6,14}$/,sp="(?:(?:\\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])))",ip=new RegExp(`^${sp}$`);function ap(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 cp(e){return new RegExp(`^${ap(e)}$`)}function lp(e){let t=ap({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(`^${sp}T(?:${o})$`)}var up=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var dp=/^-?\d+$/,il=/^-?\d+(?:\.\d+)?$/,pp=/^(?:true|false)$/i,hp=/^null$/i;var mp=/^undefined$/i;var fp=/^[^A-Z]*$/,gp=/^[^a-z]*$/;var Re=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Sp={number:"number",bigint:"bigint",object:"date"},al=_("$ZodCheckLessThan",(e,t)=>{Re.init(e,t);let r=Sp[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,i=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<i)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})}}),cl=_("$ZodCheckGreaterThan",(e,t)=>{Re.init(e,t);let r=Sp[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>i)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})}}),_p=_("$ZodCheckMultipleOf",(e,t)=>{Re.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):wd(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})}}),bp=_("$ZodCheckNumberFormat",(e,t)=>{Re.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,i]=Ed[t.format];e._zod.onattach.push((s)=>{let a=s._zod.bag;if(a.format=t.format,a.minimum=n,a.maximum=i,r)a.pattern=dp}),e._zod.check=(s)=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}if(a<n)s.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort});if(a>i)s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var yp=_("$ZodCheckMaxLength",(e,t)=>{var r;Re.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!Ra(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 s=Pa(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),vp=_("$ZodCheckMinLength",(e,t)=>{var r;Re.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!Ra(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 s=Pa(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),zp=_("$ZodCheckLengthEquals",(e,t)=>{var r;Re.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!Ra(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,i=n.length;if(i===t.length)return;let s=Pa(n),a=i>t.length;o.issues.push({origin:s,...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})}}),Jn=_("$ZodCheckStringFormat",(e,t)=>{var r,o;if(Re.init(e,t),e._zod.onattach.push((n)=>{let i=n._zod.bag;if(i.format=t.format,t.pattern)i.patterns??(i.patterns=new Set),i.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=()=>{})}),wp=_("$ZodCheckRegex",(e,t)=>{Jn.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})}}),Rp=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=fp),Jn.init(e,t)}),xp=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=gp),Jn.init(e,t)}),Pp=_("$ZodCheckIncludes",(e,t)=>{Re.init(e,t);let r=rr(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push((n)=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.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})}}),Tp=_("$ZodCheckStartsWith",(e,t)=>{Re.init(e,t);let r=new RegExp(`^${rr(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})}}),Ep=_("$ZodCheckEndsWith",(e,t)=>{Re.init(e,t);let r=new RegExp(`.*${rr(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 kp=_("$ZodCheckOverwrite",(e,t)=>{Re.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class ll{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(`
3
3
  `).filter((i)=>i),o=Math.min(...r.map((i)=>i.length-i.trimStart().length)),n=r.map((i)=>i.slice(o)).map((i)=>" ".repeat(this.indent*2)+i);for(let i of n)this.content.push(i)}compile(){let e=Function,t=this?.args,o=[...(this?.content??[""]).map((n)=>` ${n}`)];return new e(...t,o.join(`
4
- `))}}var Cp={major:4,minor:4,patch:3};var ne=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Cp;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let n of o)for(let i of n._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(s,a,l)=>{let u=kr(s),d;for(let m of a){if(m._zod.def.when){if(kd(s))continue;if(!m._zod.def.when(s))continue}else if(u)continue;let f=s.issues.length,g=m._zod.check(s);if(g instanceof Promise&&l?.async===!1)throw new Nt;if(d||g instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await g,s.issues.length===f)return;if(!u)u=kr(s,f)});else{if(s.issues.length===f)continue;if(!u)u=kr(s,f)}}if(d)return d.then(()=>s);return s},i=(s,a,l)=>{if(kr(s))return s.aborted=!0,s;let u=n(a,o,l);if(u instanceof Promise){if(l.async===!1)throw new Nt;return u.then((d)=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let u=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>i(d,s,a));return i(u,s,a)}let l=e._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new Nt;return l.then((u)=>n(u,o,a))}return n(l,o,a)}}ee(e,"~standard",()=>({validate:(n)=>{try{let i=Id(e,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch(i){return Od(e,n).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Ia=_("$ZodString",(e,t)=>{ne.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??up(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}}),ce=_("$ZodStringFormat",(e,t)=>{Jn.init(e,t),Ia.init(e,t)}),Up=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Kd),ce.init(e,t)}),Zp=_("$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=nl(o))}else t.pattern??(t.pattern=nl());ce.init(e,t)}),Dp=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Gd),ce.init(e,t)}),Fp=_("$ZodURL",(e,t)=>{ce.init(e,t),e._zod.check=(r)=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===op.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})}}}),Hp=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Yd()),ce.init(e,t)}),Vp=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Bd),ce.init(e,t)}),Jp=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Dd),ce.init(e,t)}),Bp=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Fd),ce.init(e,t)}),Wp=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Hd),ce.init(e,t)}),Kp=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Vd),ce.init(e,t)}),Gp=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Jd),ce.init(e,t)}),Yp=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=lp(t)),ce.init(e,t)}),Xp=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ip),ce.init(e,t)}),Qp=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=cp(t)),ce.init(e,t)}),eh=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Wd),ce.init(e,t)}),th=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Xd),ce.init(e,t),e._zod.bag.format="ipv4"}),rh=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Qd),ce.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 oh=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ep),ce.init(e,t)}),nh=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=tp),ce.init(e,t),e._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[n,i]=o;if(!i)throw Error();let s=Number(i);if(`${s}`!==i)throw Error();if(s<0||s>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 sh(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 ih=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=rp),ce.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(sh(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function g_(e){if(!sl.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return sh(r)}var ah=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=sl),ce.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(g_(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),ch=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=np),ce.init(e,t)});function S_(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 lh=_("$ZodJWT",(e,t)=>{ce.init(e,t),e._zod.check=(r)=>{if(S_(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var dl=_("$ZodNumber",(e,t)=>{ne.init(e,t),e._zod.pattern=e._zod.bag.pattern??il,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(s){}let n=r.value;if(typeof n==="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i=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,...i?{received:i}:{}}),r}}),uh=_("$ZodNumberFormat",(e,t)=>{bp.init(e,t),dl.init(e,t)}),dh=_("$ZodBoolean",(e,t)=>{ne.init(e,t),e._zod.pattern=pp,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(i){}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 ph=_("$ZodUndefined",(e,t)=>{ne.init(e,t),e._zod.pattern=mp,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}}),hh=_("$ZodNull",(e,t)=>{ne.init(e,t),e._zod.pattern=hp,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}}),mh=_("$ZodAny",(e,t)=>{ne.init(e,t),e._zod.parse=(r)=>r}),fh=_("$ZodUnknown",(e,t)=>{ne.init(e,t),e._zod.parse=(r)=>r}),gh=_("$ZodNever",(e,t)=>{ne.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Ip(e,t,r){if(e.issues.length)t.issues.push(...or(r,e.issues));t.value[r]=e.value}var Sh=_("$ZodArray",(e,t)=>{ne.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 i=[];for(let s=0;s<n.length;s++){let a=n[s],l=t.element._zod.run({value:a,issues:[]},o);if(l instanceof Promise)i.push(l.then((u)=>Ip(u,r,s)));else Ip(l,r,s)}if(i.length)return Promise.all(i).then(()=>r);return r}});function Ca(e,t,r,o,n,i){let s=r in o;if(e.issues.length){if(n&&i&&!s)return;t.issues.push(...or(r,e.issues))}if(!s&&!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(s)t.value[r]=void 0}else t.value[r]=e.value}function _h(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=Td(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function bh(e,t,r,o,n,i){let s=[],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"){s.push(f);continue}let g=l.run({value:t[f],issues:[]},o);if(g instanceof Promise)e.push(g.then((b)=>Ca(b,r,f,t,d,m)));else Ca(g,r,f,t,d,m)}if(s.length)r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i});if(!e.length)return r;return Promise.all(e).then(()=>r)}var __=_("$ZodObject",(e,t)=>{if(ne.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=Dn(()=>_h(t));ee(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=fo,i=t.catchall,s;e._zod.parse=(a,l)=>{s??(s=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=s.shape;for(let f of s.keys){let g=m[f],b=g._zod.optin==="optional",y=g._zod.optout==="optional",v=g._zod.run({value:u[f],issues:[]},l);if(v instanceof Promise)d.push(v.then((L)=>Ca(L,a,f,u,b,y)));else Ca(v,a,f,u,b,y)}if(!i)return d.length?Promise.all(d).then(()=>a):a;return bh(d,u,a,l,o.value,e)}}),yh=_("$ZodObjectJIT",(e,t)=>{__.init(e,t);let r=e._zod.parse,o=Dn(()=>_h(t)),n=(f)=>{let g=new ll(["shape","payload","ctx"]),b=o.value,y=(x)=>{let Z=Yc(x);return`shape[${Z}]._zod.run({ value: input[${Z}], issues: [] }, ctx)`};g.write("const input = payload.value;");let v=Object.create(null),L=0;for(let x of b.keys)v[x]=`key_${L++}`;g.write("const newResult = {};");for(let x of b.keys){let Z=v[x],R=Yc(x),w=f[x],D=w?._zod?.optin==="optional",X=w?._zod?.optout==="optional";if(g.write(`const ${Z} = ${y(x)};`),D&&X)g.write(`
4
+ `))}}var Cp={major:4,minor:4,patch:3};var ne=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Cp;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let n of o)for(let i of n._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(s,a,l)=>{let u=kr(s),d;for(let m of a){if(m._zod.def.when){if(kd(s))continue;if(!m._zod.def.when(s))continue}else if(u)continue;let f=s.issues.length,g=m._zod.check(s);if(g instanceof Promise&&l?.async===!1)throw new Nt;if(d||g instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await g,s.issues.length===f)return;if(!u)u=kr(s,f)});else{if(s.issues.length===f)continue;if(!u)u=kr(s,f)}}if(d)return d.then(()=>s);return s},i=(s,a,l)=>{if(kr(s))return s.aborted=!0,s;let u=n(a,o,l);if(u instanceof Promise){if(l.async===!1)throw new Nt;return u.then((d)=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let u=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>i(d,s,a));return i(u,s,a)}let l=e._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new Nt;return l.then((u)=>n(u,o,a))}return n(l,o,a)}}ee(e,"~standard",()=>({validate:(n)=>{try{let i=Id(e,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch(i){return Od(e,n).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Ia=_("$ZodString",(e,t)=>{ne.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??up(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}}),ce=_("$ZodStringFormat",(e,t)=>{Jn.init(e,t),Ia.init(e,t)}),Up=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Kd),ce.init(e,t)}),Zp=_("$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=nl(o))}else t.pattern??(t.pattern=nl());ce.init(e,t)}),Dp=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Gd),ce.init(e,t)}),Fp=_("$ZodURL",(e,t)=>{ce.init(e,t),e._zod.check=(r)=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===op.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})}}}),Hp=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Yd()),ce.init(e,t)}),Vp=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Bd),ce.init(e,t)}),Jp=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Dd),ce.init(e,t)}),Bp=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Fd),ce.init(e,t)}),Wp=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Hd),ce.init(e,t)}),Kp=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Vd),ce.init(e,t)}),Gp=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Jd),ce.init(e,t)}),Yp=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=lp(t)),ce.init(e,t)}),Xp=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ip),ce.init(e,t)}),Qp=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=cp(t)),ce.init(e,t)}),eh=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Wd),ce.init(e,t)}),th=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Xd),ce.init(e,t),e._zod.bag.format="ipv4"}),rh=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Qd),ce.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 oh=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ep),ce.init(e,t)}),nh=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=tp),ce.init(e,t),e._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[n,i]=o;if(!i)throw Error();let s=Number(i);if(`${s}`!==i)throw Error();if(s<0||s>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 sh(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 ih=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=rp),ce.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(sh(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function g_(e){if(!sl.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return sh(r)}var ah=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=sl),ce.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(g_(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),ch=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=np),ce.init(e,t)});function S_(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 lh=_("$ZodJWT",(e,t)=>{ce.init(e,t),e._zod.check=(r)=>{if(S_(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var dl=_("$ZodNumber",(e,t)=>{ne.init(e,t),e._zod.pattern=e._zod.bag.pattern??il,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(s){}let n=r.value;if(typeof n==="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i=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,...i?{received:i}:{}}),r}}),uh=_("$ZodNumberFormat",(e,t)=>{bp.init(e,t),dl.init(e,t)}),dh=_("$ZodBoolean",(e,t)=>{ne.init(e,t),e._zod.pattern=pp,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(i){}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 ph=_("$ZodUndefined",(e,t)=>{ne.init(e,t),e._zod.pattern=mp,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}}),hh=_("$ZodNull",(e,t)=>{ne.init(e,t),e._zod.pattern=hp,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}}),mh=_("$ZodAny",(e,t)=>{ne.init(e,t),e._zod.parse=(r)=>r}),fh=_("$ZodUnknown",(e,t)=>{ne.init(e,t),e._zod.parse=(r)=>r}),gh=_("$ZodNever",(e,t)=>{ne.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Ip(e,t,r){if(e.issues.length)t.issues.push(...or(r,e.issues));t.value[r]=e.value}var Sh=_("$ZodArray",(e,t)=>{ne.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 i=[];for(let s=0;s<n.length;s++){let a=n[s],l=t.element._zod.run({value:a,issues:[]},o);if(l instanceof Promise)i.push(l.then((u)=>Ip(u,r,s)));else Ip(l,r,s)}if(i.length)return Promise.all(i).then(()=>r);return r}});function Ca(e,t,r,o,n,i){let s=r in o;if(e.issues.length){if(n&&i&&!s)return;t.issues.push(...or(r,e.issues))}if(!s&&!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(s)t.value[r]=void 0}else t.value[r]=e.value}function _h(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=Td(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function bh(e,t,r,o,n,i){let s=[],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"){s.push(f);continue}let g=l.run({value:t[f],issues:[]},o);if(g instanceof Promise)e.push(g.then((b)=>Ca(b,r,f,t,d,m)));else Ca(g,r,f,t,d,m)}if(s.length)r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i});if(!e.length)return r;return Promise.all(e).then(()=>r)}var __=_("$ZodObject",(e,t)=>{if(ne.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=Dn(()=>_h(t));ee(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=fo,i=t.catchall,s;e._zod.parse=(a,l)=>{s??(s=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=s.shape;for(let f of s.keys){let g=m[f],b=g._zod.optin==="optional",y=g._zod.optout==="optional",v=g._zod.run({value:u[f],issues:[]},l);if(v instanceof Promise)d.push(v.then((L)=>Ca(L,a,f,u,b,y)));else Ca(v,a,f,u,b,y)}if(!i)return d.length?Promise.all(d).then(()=>a):a;return bh(d,u,a,l,o.value,e)}}),yh=_("$ZodObjectJIT",(e,t)=>{__.init(e,t);let r=e._zod.parse,o=Dn(()=>_h(t)),n=(f)=>{let g=new ll(["shape","payload","ctx"]),b=o.value,y=(x)=>{let Z=Yc(x);return`shape[${Z}]._zod.run({ value: input[${Z}], issues: [] }, ctx)`};g.write("const input = payload.value;");let v=Object.create(null),L=0;for(let x of b.keys)v[x]=`key_${L++}`;g.write("const newResult = {};");for(let x of b.keys){let Z=v[x],R=Yc(x),w=f[x],D=w?._zod?.optin==="optional",Q=w?._zod?.optout==="optional";if(g.write(`const ${Z} = ${y(x)};`),D&&Q)g.write(`
5
5
  if (${Z}.issues.length) {
6
6
  if (${R} in input) {
7
7
  payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
@@ -62,23 +62,23 @@ function ya(e){if(e?.failure?.scope!=="project")return"Preview build failed";if(
62
62
 
63
63
  `)}g.write("payload.value = newResult;"),g.write("return payload;");let H=g.compile();return(x,Z)=>H(f,x,Z)},i,s=fo,a=!mo.jitless,u=a&&xd.value,d=t.catchall,m;e._zod.parse=(f,g)=>{m??(m=o.value);let b=f.value;if(!s(b))return f.issues.push({expected:"object",code:"invalid_type",input:b,inst:e}),f;if(a&&u&&g?.async===!1&&g.jitless!==!0){if(!i)i=n(t.shape);if(f=i(f,g),!d)return f;return bh([],b,f,g,m,e)}return r(f,g)}});function Op(e,t,r,o){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let n=e.filter((i)=>!kr(i));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((i)=>i.issues.map((s)=>ct(s,o,Ue())))}),t}var pl=_("$ZodUnion",(e,t)=>{ne.init(e,t),ee(e._zod,"optin",()=>t.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),ee(e._zod,"optout",()=>t.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),ee(e._zod,"values",()=>{if(t.options.every((o)=>o._zod.values))return new Set(t.options.flatMap((o)=>Array.from(o._zod.values)));return}),ee(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)=>xa(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 i=!1,s=[];for(let a of t.options){let l=a._zod.run({value:o.value,issues:[]},n);if(l instanceof Promise)s.push(l),i=!0;else{if(l.issues.length===0)return l;s.push(l)}}if(!i)return Op(s,o,e,n);return Promise.all(s).then((a)=>Op(a,o,e,n))}});var vh=_("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,pl.init(e,t);let r=e._zod.parse;ee(e._zod,"propValues",()=>{let n={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,l]of Object.entries(s)){if(!n[a])n[a]=new Set;for(let u of l)n[a].add(u)}}return n});let o=Dn(()=>{let n=t.options,i=new Map;for(let s of n){let a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let l of a){if(i.has(l))throw Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});e._zod.parse=(n,i)=>{let s=n.value;if(!fo(s))return n.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),n;let a=o.value.get(s?.[t.discriminator]);if(a)return a._zod.run(n,i);if(t.unionFallback||i.direction==="backward")return r(n,i);return n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(o.value.keys()),input:s,path:[t.discriminator],inst:e}),n}}),zh=_("$ZodIntersection",(e,t)=>{ne.init(e,t),e._zod.parse=(r,o)=>{let n=r.value,i=t.left._zod.run({value:n,issues:[]},o),s=t.right._zod.run({value:n,issues:[]},o);if(i instanceof Promise||s instanceof Promise)return Promise.all([i,s]).then(([l,u])=>Np(r,l,u));return Np(r,i,s)}});function ul(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(Er(e)&&Er(t)){let r=Object.keys(t),o=Object.keys(e).filter((i)=>r.indexOf(i)!==-1),n={...e,...t};for(let i of o){let s=ul(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};n[i]=s.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],i=t[o],s=ul(n,i);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Np(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 i=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&n)e.issues.push({...n,keys:i});if(kr(e))return e;let s=ul(t.value,r.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var wh=_("$ZodRecord",(e,t)=>{ne.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Er(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let i=[],s=t.keyType._zod.values;if(s){r.value={};let a=new Set;for(let u of s)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((g)=>ct(g,o,Ue())),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)i.push(f.then((g)=>{if(g.issues.length)r.issues.push(...or(u,g.issues));r.value[m]=g.value}));else{if(f.issues.length)r.issues.push(...or(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"&&il.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)=>ct(m,o,Ue())),input:a,path:[a],inst:e});continue}let d=t.valueType._zod.run({value:n[a],issues:[]},o);if(d instanceof Promise)i.push(d.then((m)=>{if(m.issues.length)r.issues.push(...or(a,m.issues));r.value[l.value]=m.value}));else{if(d.issues.length)r.issues.push(...or(a,d.issues));r.value[l.value]=d.value}}}if(i.length)return Promise.all(i).then(()=>r);return r}});var Rh=_("$ZodEnum",(e,t)=>{ne.init(e,t);let r=wa(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter((n)=>Pd.has(typeof n)).map((n)=>typeof n==="string"?rr(n):n.toString()).join("|")})$`),e._zod.parse=(n,i)=>{let s=n.value;if(o.has(s))return n;return n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),xh=_("$ZodLiteral",(e,t)=>{if(ne.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"?rr(o):o?rr(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,n)=>{let i=o.value;if(r.has(i))return o;return o.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),o}});var Ph=_("$ZodTransform",(e,t)=>{ne.init(e,t),e._zod.optin="optional",e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Un(e.constructor.name);let n=t.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then((s)=>(r.value=s,r.fallback=!0,r));if(n instanceof Promise)throw new Nt;return r.value=n,r.fallback=!0,r}});function Ap(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var hl=_("$ZodOptional",(e,t)=>{ne.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ee(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ee(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${xa(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(t.innerType._zod.optin==="optional"){let n=r.value,i=t.innerType._zod.run(r,o);if(i instanceof Promise)return i.then((s)=>Ap(s,n));return Ap(i,n)}if(r.value===void 0)return r;return t.innerType._zod.run(r,o)}}),Th=_("$ZodExactOptional",(e,t)=>{hl.init(e,t),ee(e._zod,"values",()=>t.innerType._zod.values),ee(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,o)=>t.innerType._zod.run(r,o)}),Eh=_("$ZodNullable",(e,t)=>{ne.init(e,t),ee(e._zod,"optin",()=>t.innerType._zod.optin),ee(e._zod,"optout",()=>t.innerType._zod.optout),ee(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${xa(r.source)}|null)$`):void 0}),ee(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)}}),kh=_("$ZodDefault",(e,t)=>{ne.init(e,t),e._zod.optin="optional",ee(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((i)=>qp(i,t));return qp(n,t)}});function qp(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var $h=_("$ZodPrefault",(e,t)=>{ne.init(e,t),e._zod.optin="optional",ee(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)}}),Ch=_("$ZodNonOptional",(e,t)=>{ne.init(e,t),ee(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((i)=>Mp(i,e));return Mp(n,e)}});function Mp(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 Ih=_("$ZodCatch",(e,t)=>{ne.init(e,t),e._zod.optin="optional",ee(e._zod,"optout",()=>t.innerType._zod.optout),ee(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((i)=>{if(r.value=i.value,i.issues.length)r.value=t.catchValue({...r,error:{issues:i.issues.map((s)=>ct(s,o,Ue()))},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((i)=>ct(i,o,Ue()))},input:r.value}),r.issues=[],r.fallback=!0;return r}});var ml=_("$ZodPipe",(e,t)=>{ne.init(e,t),ee(e._zod,"values",()=>t.in._zod.values),ee(e._zod,"optin",()=>t.in._zod.optin),ee(e._zod,"optout",()=>t.out._zod.optout),ee(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if(o.direction==="backward"){let i=t.out._zod.run(r,o);if(i instanceof Promise)return i.then((s)=>$a(s,t.in,o));return $a(i,t.in,o)}let n=t.in._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>$a(i,t.out,o));return $a(n,t.out,o)}});function $a(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 Oh=_("$ZodPreprocess",(e,t)=>{ml.init(e,t)}),Nh=_("$ZodReadonly",(e,t)=>{ne.init(e,t),ee(e._zod,"propValues",()=>t.innerType._zod.propValues),ee(e._zod,"values",()=>t.innerType._zod.values),ee(e._zod,"optin",()=>t.innerType?._zod?.optin),ee(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(jp);return jp(n)}});function jp(e){return e.value=Object.freeze(e.value),e}var Ah=_("$ZodLazy",(e,t)=>{ne.init(e,t),ee(e._zod,"innerType",()=>{let r=t;if(!r._cachedInner)r._cachedInner=t.getter();return r._cachedInner}),ee(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),ee(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),ee(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),ee(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,o)=>e._zod.innerType._zod.run(r,o)}),qh=_("$ZodCustom",(e,t)=>{Re.init(e,t),ne.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((i)=>Lp(i,r,o,e));Lp(n,r,o,e);return}});function Lp(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($r(n))}}var b_=()=>{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 i=o[n.expected]??n.expected,s=$d(n.input),a=o[s]??s;return`Invalid input: expected ${i}, received ${a}`}case"invalid_value":if(n.values.length===1)return`Invalid input: expected ${el(n.values[0])}`;return`Invalid option: expected one of ${Gc(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${s.unit??"elements"}`;return`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${s.unit}`;return`Too small: expected ${n.origin} to be ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.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":""}: ${Gc(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((s)=>`'${s}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function fl(){return{localeError:b_()}}var Mh,y_=Symbol("ZodOutput"),v_=Symbol("ZodInput");class jh{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 Lh(){return new jh}(Mh=globalThis).__zod_globalRegistry??(Mh.__zod_globalRegistry=Lh());var nr=globalThis.__zod_globalRegistry;function Uh(e,t){return new e({type:"string",...j(t)})}function gl(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...j(t)})}function Sl(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...j(t)})}function Zh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...j(t)})}function Dh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(t)})}function Fh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(t)})}function Hh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(t)})}function _l(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...j(t)})}function Vh(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...j(t)})}function Jh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(t)})}function Bh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...j(t)})}function Wh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(t)})}function Kh(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...j(t)})}function Gh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...j(t)})}function Yh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(t)})}function Xh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(t)})}function Qh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(t)})}function em(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(t)})}function tm(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(t)})}function rm(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...j(t)})}function om(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...j(t)})}function nm(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...j(t)})}function sm(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...j(t)})}function im(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(t)})}function am(e,t){return new e({type:"string",format:"date",check:"string_format",...j(t)})}function cm(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...j(t)})}function lm(e,t){return new e({type:"string",format:"duration",check:"string_format",...j(t)})}function um(e,t){return new e({type:"number",checks:[],...j(t)})}function dm(e,t){return new e({type:"number",coerce:!0,checks:[],...j(t)})}function pm(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...j(t)})}function hm(e,t){return new e({type:"boolean",...j(t)})}function mm(e,t){return new e({type:"undefined",...j(t)})}function fm(e,t){return new e({type:"null",...j(t)})}function gm(e){return new e({type:"any"})}function Sm(e){return new e({type:"unknown"})}function _m(e,t){return new e({type:"never",...j(t)})}function Oa(e,t){return new al({check:"less_than",...j(t),value:e,inclusive:!1})}function Bn(e,t){return new al({check:"less_than",...j(t),value:e,inclusive:!0})}function Na(e,t){return new cl({check:"greater_than",...j(t),value:e,inclusive:!1})}function Wn(e,t){return new cl({check:"greater_than",...j(t),value:e,inclusive:!0})}function Aa(e,t){return new _p({check:"multiple_of",...j(t),value:e})}function qa(e,t){return new yp({check:"max_length",...j(t),maximum:e})}function go(e,t){return new vp({check:"min_length",...j(t),minimum:e})}function Ma(e,t){return new zp({check:"length_equals",...j(t),length:e})}function bl(e,t){return new wp({check:"string_format",format:"regex",...j(t),pattern:e})}function yl(e){return new Rp({check:"string_format",format:"lowercase",...j(e)})}function vl(e){return new xp({check:"string_format",format:"uppercase",...j(e)})}function zl(e,t){return new Pp({check:"string_format",format:"includes",...j(t),includes:e})}function wl(e,t){return new Tp({check:"string_format",format:"starts_with",...j(t),prefix:e})}function Rl(e,t){return new Ep({check:"string_format",format:"ends_with",...j(t),suffix:e})}function sr(e){return new kp({check:"overwrite",tx:e})}function xl(e){return sr((t)=>t.normalize(e))}function Pl(){return sr((e)=>e.trim())}function Tl(){return sr((e)=>e.toLowerCase())}function El(){return sr((e)=>e.toUpperCase())}function kl(){return sr((e)=>Rd(e))}function bm(e,t,r){return new e({type:"array",element:t,...j(r)})}function ym(e,t,r){return new e({type:"custom",check:"custom",fn:t,...j(r)})}function vm(e,t){let r=z_((o)=>(o.addIssue=(n)=>{if(typeof n==="string")o.issues.push($r(n,o.value,r._zod.def));else{let i=n;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=o.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),o.issues.push($r(i))}},e(o.value,o)),t);return r}function z_(e,t){let r=new Re({check:"custom",...j(t)});return r._zod.check=e,r}function Gn(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??nr,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 se(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,i=t.seen.get(e);if(i){if(i.count++,r.schemaPath.includes(e))i.cycle=r.path;return i.schema}let s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s);let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,d);else{let f=s.schema,g=t.processors[n.type];if(!g)throw Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);g(e,t,f,d)}let m=e._zod.parent;if(m){if(!s.ref)s.ref=m;se(m,t,d),t.seen.get(m).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Object.assign(s.schema,l);if(t.io==="input"&&qe(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(o=s.schema).default??(o.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function Yn(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 s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let l=o.get(a);if(l&&l!==s[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,s[0])}}let n=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let m=e.external.registry.get(s[0])?.id,f=e.external.uri??((b)=>b);if(m)return{ref:f(m)};let g=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=g,{defId:g,ref:`${f("__shared")}#/${a}/${g}`}}if(s[1]===r)return{ref:"#"};let u=`${"#"}/${a}/`,d=s[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},i=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:l,defId:u}=n(s);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 s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
64
64
 
65
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){i(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1){if(e.reused==="ref"){i(s);continue}}}}function Xn(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 g=e.seen.get(m),b=g.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&&g.def)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(v in g.def&&JSON.stringify(u[v])===JSON.stringify(g.def[v]))delete u[v]}}let f=a._zod.parent;if(f&&f!==m){o(f);let g=e.seen.get(f);if(g?.schema.$ref){if(u.$ref=g.schema.$ref,g.def)for(let b in u){if(b==="$ref"||b==="allOf")continue;if(b in g.def&&JSON.stringify(u[b])===JSON.stringify(g.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 i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&n.id===i)delete n.id;let s=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;s[l.defId]=l.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")n.$defs=s;else n.definitions=s;try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Kn(t,"input",e.processors),output:Kn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function qe(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 qe(o.element,r);if(o.type==="set")return qe(o.valueType,r);if(o.type==="lazy")return qe(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 qe(o.innerType,r);if(o.type==="intersection")return qe(o.left,r)||qe(o.right,r);if(o.type==="record"||o.type==="map")return qe(o.keyType,r)||qe(o.valueType,r);if(o.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return qe(o.in,r)||qe(o.out,r)}if(o.type==="object"){for(let n in o.shape)if(qe(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(qe(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(qe(n,r))return!0;if(o.rest&&qe(o.rest,r))return!0;return!1}return!1}var zm=(e,t={})=>(r)=>{let o=Gn({...r,processors:t});return se(e,o),Yn(o,e),Xn(o,e)},Kn=(e,t,r={})=>(o)=>{let{libraryOptions:n,target:i}=o??{},s=Gn({...n??{},target:i,io:t,processors:r});return se(e,s),Yn(s,e),Xn(s,e)};var w_={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:i,maximum:s,format:a,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof i==="number")n.minLength=i;if(typeof s==="number")n.maxLength=s;if(a){if(n.format=w_[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}))]}},Cl=(e,t,r,o)=>{let n=r,{minimum:i,maximum:s,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>=(i??Number.NEGATIVE_INFINITY),f=typeof u==="number"&&u<=(s??Number.POSITIVE_INFINITY),g=t.target==="draft-04"||t.target==="openapi-3.0";if(m)if(g)n.minimum=d,n.exclusiveMinimum=!0;else n.exclusiveMinimum=d;else if(typeof i==="number")n.minimum=i;if(f)if(g)n.maximum=u,n.exclusiveMaximum=!0;else n.exclusiveMaximum=u;else if(typeof s==="number")n.maximum=s;if(typeof l==="number")n.multipleOf=l},Il=(e,t,r,o)=>{r.type="boolean"},Rm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},xm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},Ol=(e,t,r,o)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},Nl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},Pm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},Al=(e,t,r,o)=>{r.not={}},ql=(e,t,r,o)=>{},Ml=(e,t,r,o)=>{},Tm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},jl=(e,t,r,o)=>{let n=e._zod.def,i=wa(n.entries);if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";r.enum=i},Ll=(e,t,r,o)=>{let n=e._zod.def,i=[];for(let s of n.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else i.push(Number(s));else i.push(s);if(i.length===0);else if(i.length===1){let s=i[0];if(r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[s];else r.const=s}else{if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";if(i.every((s)=>typeof s==="boolean"))r.type="boolean";if(i.every((s)=>s===null))r.type="null";r.enum=i}},Em=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},km=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},$m=(e,t,r,o)=>{let n=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:l}=e._zod.bag;if(s!==void 0)i.minLength=s;if(a!==void 0)i.maxLength=a;if(l)if(l.length===1)i.contentMediaType=l[0],Object.assign(n,i);else Object.assign(n,i),n.anyOf=l.map((u)=>({contentMediaType:u}));else Object.assign(n,i)},Cm=(e,t,r,o)=>{r.type="boolean"},Ul=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},Im=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},Zl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},Om=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},Nm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},Dl=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")n.minItems=s;if(typeof a==="number")n.maxItems=a;n.type="array",n.items=se(i.element,t,{...o,path:[...o.path,"items"]})},Fl=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object",n.properties={};let s=i.shape;for(let u in s)n.properties[u]=se(s[u],t,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(s)),l=new Set([...a].filter((u)=>{let d=i.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(i.catchall?._zod.def.type==="never")n.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")n.additionalProperties=!1}else if(i.catchall)n.additionalProperties=se(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Hl=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,s=n.options.map((a,l)=>se(a,t,{...o,path:[...o.path,i?"oneOf":"anyOf",l]}));if(i)r.oneOf=s;else r.anyOf=s},Vl=(e,t,r,o)=>{let n=e._zod.def,i=se(n.left,t,{...o,path:[...o.path,"allOf",0]}),s=se(n.right,t,{...o,path:[...o.path,"allOf",1]}),a=(u)=>("allOf"in u)&&Object.keys(u).length===1,l=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=l},Am=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",l=i.items.map((f,g)=>se(f,t,{...o,path:[...o.path,s,g]})),u=i.rest?se(i.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[i.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},Jl=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let s=i.keyType,l=s._zod.bag?.patterns;if(i.mode==="loose"&&l&&l.size>0){let d=se(i.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=se(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});n.additionalProperties=se(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=s._zod.values;if(u){let d=[...u].filter((m)=>typeof m==="string"||typeof m==="number");if(d.length>0)n.required=d}},Bl=(e,t,r,o)=>{let n=e._zod.def,i=se(n.innerType,t,o),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=n.innerType,r.nullable=!0;else r.anyOf=[i,{type:"null"}]},Wl=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Kl=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},Gl=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(n.defaultValue))},Yl=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},Xl=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?n.out:n.in:n.out;se(s,t,o);let a=t.seen.get(e);a.ref=s},Ql=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},qm=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},ja=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},eu=(e,t,r,o)=>{let n=e._zod.innerType;se(n,t,o);let i=t.seen.get(e);i.ref=n},wm={string:$l,number:Cl,boolean:Il,bigint:Rm,symbol:xm,null:Ol,undefined:Nl,void:Pm,never:Al,any:ql,unknown:Ml,date:Tm,enum:jl,literal:Ll,nan:Em,template_literal:km,file:$m,success:Cm,custom:Ul,function:Im,transform:Zl,map:Om,set:Nm,array:Dl,object:Fl,union:Hl,intersection:Vl,tuple:Am,record:Jl,nullable:Bl,nonoptional:Wl,default:Kl,prefault:Gl,catch:Yl,pipe:Xl,readonly:Ql,promise:qm,optional:ja,lazy:eu};function La(e,t){if("_idmap"in e){let o=e,n=Gn({...t,processors:wm}),i={};for(let l of o._idmap.entries()){let[u,d]=l;se(d,n)}let s={},a={registry:o,uri:t?.uri,defs:i};n.external=a;for(let l of o._idmap.entries()){let[u,d]=l;Yn(n,d),s[u]=Xn(n,d)}if(Object.keys(i).length>0){let l=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[l]:i}}return{schemas:s}}let r=Gn({...t,processors:wm});return se(e,r),Yn(r,e),Xn(r,e)}var C_=_("ZodISODateTime",(e,t)=>{Yp.init(e,t),le.init(e,t)});function _o(e){return im(C_,e)}var I_=_("ZodISODate",(e,t)=>{Xp.init(e,t),le.init(e,t)});function tu(e){return am(I_,e)}var O_=_("ZodISOTime",(e,t)=>{Qp.init(e,t),le.init(e,t)});function Mm(e){return cm(O_,e)}var N_=_("ZodISODuration",(e,t)=>{eh.init(e,t),le.init(e,t)});function jm(e){return lm(N_,e)}var A_=(e,t)=>{Ta.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>ol(e,r)},flatten:{value:(r)=>rl(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Zn,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Zn,2)}},isEmpty:{get(){return e.issues.length===0}}})};var We=_("ZodError",A_,{Parent:Error});var Um=Ea(We),Zm=ka(We),Za=Fn(We),Dm=Hn(We),Fm=Nd(We),Hm=Ad(We),Vm=qd(We),Jm=Md(We),Bm=jd(We),Wm=Ld(We),Km=Ud(We),Gm=Zd(We);var Ym=new WeakMap;function Qn(e,t,r){let o=Object.getPrototypeOf(e),n=Ym.get(o);if(!n)n=new Set,Ym.set(o,n);if(n.has(t))return;n.add(t);for(let i in r){let s=r[i];Object.defineProperty(o,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var ie=_("ZodType",(e,t)=>(ne.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Kn(e,"input"),output:Kn(e,"output")}}),e.toJSONSchema=zm(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,o)=>Um(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Za(e,r,o),e.parseAsync=async(r,o)=>Zm(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>Dm(e,r,o),e.spa=e.safeParseAsync,e.encode=(r,o)=>Fm(e,r,o),e.decode=(r,o)=>Hm(e,r,o),e.encodeAsync=async(r,o)=>Vm(e,r,o),e.decodeAsync=async(r,o)=>Jm(e,r,o),e.safeEncode=(r,o)=>Bm(e,r,o),e.safeDecode=(r,o)=>Wm(e,r,o),e.safeEncodeAsync=async(r,o)=>Km(e,r,o),e.safeDecodeAsync=async(r,o)=>Gm(e,r,o),Qn(e,"ZodType",{check(...r){let o=this.def;return this.clone(tr(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 at(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(Rb(r,o))},superRefine(r,o){return this.check(xb(r,o))},overwrite(r){return this.check(sr(r))},optional(){return U(this)},exactOptional(){return ub(this)},nullable(){return tf(this)},nullish(){return U(tf(this))},nonoptional(r){return gb(this,r)},array(){return S(this)},or(r){return T([this,r])},and(r){return At(this,r)},transform(r){return rf(this,pf(r))},default(r){return hb(this,r)},prefault(r){return fb(this,r)},catch(r){return _b(this,r)},pipe(r){return rf(this,r)},readonly(){return vb(this)},describe(r){let o=this.clone();return nr.add(o,{description:r}),o},meta(...r){if(r.length===0)return nr.get(this);let o=this.clone();return nr.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 nr.get(e)?.description},configurable:!0}),e)),of=_("_ZodString",(e,t)=>{Ia.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,i)=>$l(e,o,n,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Qn(e,"_ZodString",{regex(...o){return this.check(bl(...o))},includes(...o){return this.check(zl(...o))},startsWith(...o){return this.check(wl(...o))},endsWith(...o){return this.check(Rl(...o))},min(...o){return this.check(go(...o))},max(...o){return this.check(qa(...o))},length(...o){return this.check(Ma(...o))},nonempty(...o){return this.check(go(1,...o))},lowercase(o){return this.check(yl(o))},uppercase(o){return this.check(vl(o))},trim(){return this.check(Pl())},normalize(...o){return this.check(xl(...o))},toLowerCase(){return this.check(Tl())},toUpperCase(){return this.check(El())},slugify(){return this.check(kl())}})}),nf=_("ZodString",(e,t)=>{Ia.init(e,t),of.init(e,t),e.email=(r)=>e.check(gl(sf,r)),e.url=(r)=>e.check(_l(cf,r)),e.jwt=(r)=>e.check(sm(Y_,r)),e.emoji=(r)=>e.check(Vh(M_,r)),e.guid=(r)=>e.check(Sl(Xm,r)),e.uuid=(r)=>e.check(Zh(Da,r)),e.uuidv4=(r)=>e.check(Dh(Da,r)),e.uuidv6=(r)=>e.check(Fh(Da,r)),e.uuidv7=(r)=>e.check(Hh(Da,r)),e.nanoid=(r)=>e.check(Jh(j_,r)),e.guid=(r)=>e.check(Sl(Xm,r)),e.cuid=(r)=>e.check(Bh(L_,r)),e.cuid2=(r)=>e.check(Wh(U_,r)),e.ulid=(r)=>e.check(Kh(Z_,r)),e.base64=(r)=>e.check(rm(W_,r)),e.base64url=(r)=>e.check(om(K_,r)),e.xid=(r)=>e.check(Gh(D_,r)),e.ksuid=(r)=>e.check(Yh(F_,r)),e.ipv4=(r)=>e.check(Xh(H_,r)),e.ipv6=(r)=>e.check(Qh(V_,r)),e.cidrv4=(r)=>e.check(em(J_,r)),e.cidrv6=(r)=>e.check(tm(B_,r)),e.e164=(r)=>e.check(nm(G_,r)),e.datetime=(r)=>e.check(_o(r)),e.date=(r)=>e.check(tu(r)),e.time=(r)=>e.check(Mm(r)),e.duration=(r)=>e.check(jm(r))});function c(e){return Uh(nf,e)}var le=_("ZodStringFormat",(e,t)=>{ce.init(e,t),of.init(e,t)}),sf=_("ZodEmail",(e,t)=>{Dp.init(e,t),le.init(e,t)});function af(e){return gl(sf,e)}var Xm=_("ZodGUID",(e,t)=>{Up.init(e,t),le.init(e,t)});var Da=_("ZodUUID",(e,t)=>{Zp.init(e,t),le.init(e,t)});var cf=_("ZodURL",(e,t)=>{Fp.init(e,t),le.init(e,t)});function Fa(e){return _l(cf,e)}var M_=_("ZodEmoji",(e,t)=>{Hp.init(e,t),le.init(e,t)});var j_=_("ZodNanoID",(e,t)=>{Vp.init(e,t),le.init(e,t)});var L_=_("ZodCUID",(e,t)=>{Jp.init(e,t),le.init(e,t)});var U_=_("ZodCUID2",(e,t)=>{Bp.init(e,t),le.init(e,t)});var Z_=_("ZodULID",(e,t)=>{Wp.init(e,t),le.init(e,t)});var D_=_("ZodXID",(e,t)=>{Kp.init(e,t),le.init(e,t)});var F_=_("ZodKSUID",(e,t)=>{Gp.init(e,t),le.init(e,t)});var H_=_("ZodIPv4",(e,t)=>{th.init(e,t),le.init(e,t)});var V_=_("ZodIPv6",(e,t)=>{rh.init(e,t),le.init(e,t)});var J_=_("ZodCIDRv4",(e,t)=>{oh.init(e,t),le.init(e,t)});var B_=_("ZodCIDRv6",(e,t)=>{nh.init(e,t),le.init(e,t)});var W_=_("ZodBase64",(e,t)=>{ih.init(e,t),le.init(e,t)});var K_=_("ZodBase64URL",(e,t)=>{ah.init(e,t),le.init(e,t)});var G_=_("ZodE164",(e,t)=>{ch.init(e,t),le.init(e,t)});var Y_=_("ZodJWT",(e,t)=>{lh.init(e,t),le.init(e,t)});var Ha=_("ZodNumber",(e,t)=>{dl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Cl(e,o,n,i),Qn(e,"ZodNumber",{gt(o,n){return this.check(Na(o,n))},gte(o,n){return this.check(Wn(o,n))},min(o,n){return this.check(Wn(o,n))},lt(o,n){return this.check(Oa(o,n))},lte(o,n){return this.check(Bn(o,n))},max(o,n){return this.check(Bn(o,n))},int(o){return this.check(Qm(o))},safe(o){return this.check(Qm(o))},positive(o){return this.check(Na(0,o))},nonnegative(o){return this.check(Wn(0,o))},negative(o){return this.check(Oa(0,o))},nonpositive(o){return this.check(Bn(0,o))},multipleOf(o,n){return this.check(Aa(o,n))},step(o,n){return this.check(Aa(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 um(Ha,e)}var X_=_("ZodNumberFormat",(e,t)=>{uh.init(e,t),Ha.init(e,t)});function Qm(e){return pm(X_,e)}var lf=_("ZodBoolean",(e,t)=>{dh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n)});function E(e){return hm(lf,e)}var Q_=_("ZodUndefined",(e,t)=>{ph.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nl(e,r,o,n)});function ou(e){return mm(Q_,e)}var eb=_("ZodNull",(e,t)=>{hh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n)});function Cr(e){return fm(eb,e)}var tb=_("ZodAny",(e,t)=>{mh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n)});function Va(){return gm(tb)}var rb=_("ZodUnknown",(e,t)=>{fh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n)});function M(){return Sm(rb)}var ob=_("ZodNever",(e,t)=>{gh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n)});function nu(e){return _m(ob,e)}var nb=_("ZodArray",(e,t)=>{Sh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dl(e,r,o,n),e.element=t.element,Qn(e,"ZodArray",{min(r,o){return this.check(go(r,o))},nonempty(r){return this.check(go(1,r))},max(r,o){return this.check(qa(r,o))},length(r,o){return this.check(Ma(r,o))},unwrap(){return this.element}})});function S(e,t){return bm(nb,e,t)}var uf=_("ZodObject",(e,t)=>{yh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n),ee(e,"shape",()=>t.shape),Qn(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:M()})},loose(){return this.clone({...this._zod.def,catchall:M()})},strict(){return this.clone({...this._zod.def,catchall:nu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return l_(this,r)},safeExtend(r){return u_(this,r)},merge(r){return d_(this,r)},pick(r){return a_(this,r)},omit(r){return c_(this,r)},partial(...r){return p_(hf,this,r[0])},required(...r){return h_(mf,this,r[0])}})});function p(e,t){let r={type:"object",shape:e??{},...j(t)};return new uf(r)}function F(e,t){return new uf({type:"object",shape:e,catchall:M(),...j(t)})}var df=_("ZodUnion",(e,t)=>{pl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hl(e,r,o,n),e.options=t.options});function T(e,t){return new df({type:"union",options:e,...j(t)})}var sb=_("ZodDiscriminatedUnion",(e,t)=>{df.init(e,t),vh.init(e,t)});function bo(e,t,r){return new sb({type:"union",options:t,discriminator:e,...j(r)})}var ib=_("ZodIntersection",(e,t)=>{zh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vl(e,r,o,n)});function At(e,t){return new ib({type:"intersection",left:e,right:t})}var ef=_("ZodRecord",(e,t)=>{wh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jl(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function P(e,t,r){if(!t||!t._zod)return new ef({type:"record",keyType:c(),valueType:e,...j(t)});return new ef({type:"record",keyType:e,valueType:t,...j(r)})}var ru=_("ZodEnum",(e,t)=>{Rh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,i)=>jl(e,o,n,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new ru({...t,checks:[],...j(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let s of o)if(r.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new ru({...t,checks:[],...j(n),entries:i})}});function K(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new ru({type:"enum",entries:r,...j(t)})}var ab=_("ZodLiteral",(e,t)=>{xh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(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 ab({type:"literal",values:Array.isArray(e)?e:[e],...j(t)})}var cb=_("ZodTransform",(e,t)=>{Ph.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Un(e.constructor.name);r.addIssue=(i)=>{if(typeof i==="string")r.issues.push($r(i,r.value,t));else{let s=i;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),r.issues.push($r(s))}};let n=t.transform(r.value,r);if(n instanceof Promise)return n.then((i)=>(r.value=i,r.fallback=!0,r));return r.value=n,r.fallback=!0,r}});function pf(e){return new cb({type:"transform",transform:e})}var hf=_("ZodOptional",(e,t)=>{hl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ja(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function U(e){return new hf({type:"optional",innerType:e})}var lb=_("ZodExactOptional",(e,t)=>{Th.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ja(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ub(e){return new lb({type:"optional",innerType:e})}var db=_("ZodNullable",(e,t)=>{Eh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Bl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function tf(e){return new db({type:"nullable",innerType:e})}var pb=_("ZodDefault",(e,t)=>{kh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function hb(e,t){return new pb({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Qc(t)}})}var mb=_("ZodPrefault",(e,t)=>{$h.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function fb(e,t){return new mb({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Qc(t)}})}var mf=_("ZodNonOptional",(e,t)=>{Ch.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function gb(e,t){return new mf({type:"nonoptional",innerType:e,...j(t)})}var Sb=_("ZodCatch",(e,t)=>{Ih.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _b(e,t){return new Sb({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var ff=_("ZodPipe",(e,t)=>{ml.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xl(e,r,o,n),e.in=t.in,e.out=t.out});function rf(e,t){return new ff({type:"pipe",in:e,out:t})}var bb=_("ZodPreprocess",(e,t)=>{ff.init(e,t),Oh.init(e,t)}),yb=_("ZodReadonly",(e,t)=>{Nh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ql(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function vb(e){return new yb({type:"readonly",innerType:e})}var zb=_("ZodLazy",(e,t)=>{Ah.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>eu(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function es(e){return new zb({type:"lazy",getter:e})}var wb=_("ZodCustom",(e,t)=>{qh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n)});function Rb(e,t={}){return ym(wb,e,t)}function xb(e,t){return vm(e,t)}function Ir(e,t){return new bb({type:"pipe",in:pf(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 gf;(function(e){})(gf||(gf={}));function Pb(e){return dm(Ha,e)}Ue(fl());var yo="2025-11-25";var Ja=[yo,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ba="io.modelcontextprotocol/related-task",Mt="io.modelcontextprotocol/protocolVersion",vo="io.modelcontextprotocol/clientInfo",jt="io.modelcontextprotocol/serverInfo",Or="io.modelcontextprotocol/clientCapabilities",ts="io.modelcontextprotocol/subscriptionId",zo="io.modelcontextprotocol/logLevel";var Nr="2.0";var qt=es(()=>T([c(),z(),E(),Cr(),P(c(),qt),S(qt)])),de=P(c(),qt),Wa=S(qt),wo=T([c(),z().int()]),Ro=c(),rs=p({ttl:z().optional()}),os=p({taskId:c()}),xo=F({progressToken:wo.optional(),[Ba]:os.optional()}),ze=p({_meta:xo.optional()}),ar=ze.extend({task:rs.optional()}),pe=p({method:c(),params:ze.loose().optional()}),ke=p({_meta:xo.optional()}),xe=p({method:c(),params:ke.loose().optional()}),Po=F({get[jt](){return Rt.optional().catch(void 0)}}),he=F({_meta:Po.optional()}),lt=T([c(),z().int()]),To=p({jsonrpc:h(Nr),id:lt,...pe.shape}).strict(),Eo=p({jsonrpc:h(Nr),...xe.shape}).strict(),Ar=p({jsonrpc:h(Nr),id:lt,result:he}).strict(),qr=p({jsonrpc:h(Nr),id:lt.optional(),error:p({code:z().int(),message:c(),data:M().optional()})}).strict(),ut=T([To,Eo,Ar,qr]),Ka=T([Ar,qr]),cr=he.strict(),ns=ke.extend({requestId:lt.optional(),reason:c().optional()}),ko=xe.extend({method:h("notifications/cancelled"),params:ns}),ss=p({src:c(),mimeType:c().optional(),sizes:S(c()).optional(),theme:K(["light","dark"]).optional()}),Lt=p({icons:S(ss).optional()}),wt=p({name:c(),title:c().optional()}),Rt=wt.extend({...wt.shape,...Lt.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),Eb=At(p({applyDefaults:E().optional()}),de),kb=Ir((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)&&Object.keys(e).length===0)return{form:{}};return e},At(p({form:Eb.optional(),url:de.optional()}),de.optional())),Ga=F({list:de.optional(),cancel:de.optional(),requests:F({sampling:F({createMessage:de.optional()}).optional(),elicitation:F({create:de.optional()}).optional()}).optional()}),Ya=F({list:de.optional(),cancel:de.optional(),requests:F({tools:F({call:de.optional()}).optional()}).optional()}),is=p({experimental:P(c(),de).optional(),sampling:p({context:de.optional(),tools:de.optional()}).optional(),elicitation:kb.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:Ga.optional(),extensions:P(c(),de).optional()}),as=ze.extend({protocolVersion:c(),capabilities:is,clientInfo:Rt}),$o=pe.extend({method:h("initialize"),params:as}),Co=p({experimental:P(c(),de).optional(),logging:de.optional(),completions:de.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:Ya.optional(),extensions:P(c(),de).optional()}),cs=he.extend({protocolVersion:c(),capabilities:Co,serverInfo:Rt,instructions:c().optional()}),Io=xe.extend({method:h("notifications/initialized"),params:ke.optional()}),ls=pe.extend({method:h("server/discover"),params:ze.optional()}),lr=he.extend({supportedVersions:S(c()),capabilities:Co,instructions:c().optional()}),Oo=pe.extend({method:h("ping"),params:ze.optional()}),us=p({progress:z(),total:U(z()),message:U(c())}),ds=p({...ke.shape,...us.shape,progressToken:wo}),No=xe.extend({method:h("notifications/progress"),params:ds}),ps=ze.extend({cursor:Ro.optional()}),Ut=pe.extend({params:ps.optional()}),Zt=he.extend({nextCursor:Ro.optional()}),Ao=p({uri:c(),mimeType:U(c()),_meta:P(c(),M()).optional()}),qo=Ao.extend({text:c()}),iu=c().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mo=Ao.extend({blob:iu}),Dt=K(["user","assistant"]),xt=p({audience:S(Dt).optional(),priority:z().min(0).max(1).optional(),lastModified:_o({offset:!0}).optional()}),jo=p({...wt.shape,...Lt.shape,uri:c(),description:U(c()),mimeType:U(c()),size:U(z()),annotations:xt.optional(),_meta:U(F({}))}),hs=p({...wt.shape,...Lt.shape,uriTemplate:c(),description:U(c()),mimeType:U(c()),annotations:xt.optional(),_meta:U(F({}))}),ms=Ut.extend({method:h("resources/list")}),fs=Zt.extend({resources:S(jo)}),gs=Ut.extend({method:h("resources/templates/list")}),Ss=Zt.extend({resourceTemplates:S(hs)}),Mr=ze.extend({uri:c()}),_s=Mr,bs=pe.extend({method:h("resources/read"),params:_s}),ys=he.extend({contents:S(T([qo,Mo]))}),vs=xe.extend({method:h("notifications/resources/list_changed"),params:ke.optional()}),zs=Mr,ws=pe.extend({method:h("resources/subscribe"),params:zs}),Rs=Mr,xs=pe.extend({method:h("resources/unsubscribe"),params:Rs}),Lo=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:S(c()).optional()}),Ps=ze.extend({notifications:Lo}),Ts=pe.extend({method:h("subscriptions/listen"),params:Ps}),Es=ke.extend({notifications:Lo}),ks=xe.extend({method:h("notifications/subscriptions/acknowledged"),params:Es}),$s=Po.extend({[ts]:lt}),Cs=he.extend({_meta:$s}),Is=ke.extend({uri:c()}),Os=xe.extend({method:h("notifications/resources/updated"),params:Is}),Ns=p({name:c(),description:U(c()),required:U(E())}),As=p({...wt.shape,...Lt.shape,description:U(c()),arguments:U(S(Ns)),_meta:U(F({}))}),qs=Ut.extend({method:h("prompts/list")}),Ms=Zt.extend({prompts:S(As)}),js=ze.extend({name:c(),arguments:P(c(),c()).optional()}),Ls=pe.extend({method:h("prompts/get"),params:js}),jr=p({type:h("text"),text:c(),annotations:xt.optional(),_meta:P(c(),M()).optional()}),Lr=p({type:h("image"),data:iu,mimeType:c(),annotations:xt.optional(),_meta:P(c(),M()).optional()}),Ur=p({type:h("audio"),data:iu,mimeType:c(),annotations:xt.optional(),_meta:P(c(),M()).optional()}),Us=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),M()),_meta:P(c(),M()).optional()}),Zr=p({type:h("resource"),resource:T([qo,Mo]),annotations:xt.optional(),_meta:P(c(),M()).optional()}),Dr=jo.extend({type:h("resource_link")}),Pt=T([jr,Lr,Ur,Dr,Zr]),Zs=p({role:Dt,content:Pt}),Ds=he.extend({description:c().optional(),messages:S(Zs)}),Fs=xe.extend({method:h("notifications/prompts/list_changed"),params:ke.optional()}),Hs=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Vs=p({taskSupport:K(["required","optional","forbidden"]).optional()}),ur=p({...wt.shape,...Lt.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),qt).optional(),required:S(c()).optional()}).catchall(M()),outputSchema:F({$schema:c().optional()}).optional(),annotations:Hs.optional(),execution:Vs.optional(),_meta:P(c(),M()).optional()}),Js=Ut.extend({method:h("tools/list")}),Bs=Zt.extend({tools:S(ur)}),dr=he.extend({content:S(Pt).default([]),structuredContent:M().optional(),isError:E().optional()}),Xa=dr.or(he.extend({toolResult:M()})),Ws=ar.extend({name:c(),arguments:P(c(),M()).optional()}),Ks=pe.extend({method:h("tools/call"),params:Ws}),Gs=xe.extend({method:h("notifications/tools/list_changed"),params:ke.optional()}),Ys=p({autoRefresh:E().default(!0),debounceMs:z().int().nonnegative().default(300)}),Uo=K(["debug","info","notice","warning","error","critical","alert","emergency"]),Xs=ze.extend({level:Uo}),Qs=pe.extend({method:h("logging/setLevel"),params:Xs}),ei=ke.extend({level:Uo,logger:c().optional(),data:M()}),Fr=xe.extend({method:h("notifications/message"),params:ei}),ti=p({name:c().optional()}),ri=p({hints:S(ti).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),oi=p({mode:K(["auto","required","none"]).optional()}),ni=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:S(Pt),structuredContent:M().optional(),isError:E().optional(),_meta:P(c(),M()).optional()}),si=bo("type",[jr,Lr,Ur]),ir=bo("type",[jr,Lr,Ur,Us,ni]),ii=p({role:Dt,content:T([ir,S(ir)]),_meta:P(c(),M()).optional()}),ai=ar.extend({messages:S(ii),modelPreferences:ri.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:S(c()).optional(),metadata:de.optional(),tools:S(ur).optional(),toolChoice:oi.optional()}),ci=pe.extend({method:h("sampling/createMessage"),params:ai}),li=he.extend({model:c(),stopReason:U(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Dt,content:si}),ui=he.extend({model:c(),stopReason:U(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Dt,content:T([ir,S(ir)])}),Zo=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),Hr=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()}),Vr=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),Do=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),default:c().optional()}),Fo=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:S(p({const:c(),title:c()})),default:c().optional()}),Ho=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),enumNames:S(c()).optional(),default:c().optional()}),di=T([Do,Fo]),Vo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:S(c())}),default:S(c()).optional()}),Jo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:S(p({const:c(),title:c()}))}),default:S(c()).optional()}),pi=T([Vo,Jo]),hi=T([Ho,di,pi]),Bo=T([hi,Zo,Hr,Vr]),Jr=ar.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),Bo),required:S(c()).optional()}).catchall(M())}),mi=ar.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),fi=T([Jr,mi]),gi=pe.extend({method:h("elicitation/create"),params:fi}),Si=ke.extend({elicitationId:c()}),_i=xe.extend({method:h("notifications/elicitation/complete"),params:Si}),bi=he.extend({action:K(["accept","decline","cancel"]),content:Ir((e)=>e===null?void 0:e,P(c(),T([c(),z(),E(),S(c())])).optional())}),yi=p({type:h("ref/resource"),uri:c()}),vi=p({type:h("ref/prompt"),name:c()}),zi=ze.extend({ref:T([vi,yi]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),wi=pe.extend({method:h("completion/complete"),params:zi}),Ri=he.extend({completion:F({values:S(c()).max(100),total:U(z().int()),hasMore:U(E())})}),xi=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),M()).optional()}),Pi=pe.extend({method:h("roots/list"),params:ze.optional()}),Ti=he.extend({roots:S(xi)}),Ei=xe.extend({method:h("notifications/roots/list_changed"),params:ke.optional()}),Qa=F({ttl:z().optional(),pollInterval:z().optional()}),ki=K(["working","input_required","completed","failed","cancelled"]),Ft=p({taskId:c(),status:ki,ttl:T([z(),Cr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:U(z()),statusMessage:U(c())}),ec=he.extend({task:Ft}),$i=ke.merge(Ft),tc=xe.extend({method:h("notifications/tasks/status"),params:$i}),rc=pe.extend({method:h("tasks/get"),params:ze.extend({taskId:c()})}),oc=he.merge(Ft),nc=pe.extend({method:h("tasks/result"),params:ze.extend({taskId:c()})}),sc=he.loose(),ic=Ut.extend({method:h("tasks/list")}),ac=Zt.extend({tasks:S(Ft)}),cc=pe.extend({method:h("tasks/cancel"),params:ze.extend({taskId:c()})}),lc=he.merge(Ft),uc=T([Oo,$o,ls,wi,Qs,Ls,qs,ms,gs,bs,ws,xs,Ts,Ks,Js]),dc=T([ko,No,Io,Ei]),pc=T([cr,li,ui,bi,Ti]),hc=T([Oo,ci,gi,Pi]),mc=T([ko,No,Fr,Os,vs,Gs,Fs,ks,_i]),fc=T([cr,cs,lr,Ri,Ds,Ms,fs,Ss,ys,dr,Bs,Cs]),ve=Fa().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Sf.custom,message:"URL must be parseable",fatal:!0}),Wc}).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"}),Wo=F({resource:c().url(),authorization_servers:S(ve).optional(),jwks_uri:c().url().optional(),scopes_supported:S(c()).optional(),bearer_methods_supported:S(c()).optional(),resource_signing_alg_values_supported:S(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:E().optional(),authorization_details_types_supported:S(c()).optional(),dpop_signing_alg_values_supported:S(c()).optional(),dpop_bound_access_tokens_required:E().optional()}),Br=F({issuer:c(),authorization_endpoint:ve,token_endpoint:ve,registration_endpoint:ve.optional(),scopes_supported:S(c()).optional(),response_types_supported:S(c()),response_modes_supported:S(c()).optional(),grant_types_supported:S(c()).optional(),token_endpoint_auth_methods_supported:S(c()).optional(),token_endpoint_auth_signing_alg_values_supported:S(c()).optional(),service_documentation:ve.optional(),revocation_endpoint:ve.optional(),revocation_endpoint_auth_methods_supported:S(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:S(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:S(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:S(c()).optional(),code_challenge_methods_supported:S(c()).optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0),dpop_signing_alg_values_supported:S(c()).optional()}),Ci=F({issuer:c(),authorization_endpoint:ve,token_endpoint:ve,userinfo_endpoint:ve.optional(),jwks_uri:ve,registration_endpoint:ve.optional(),scopes_supported:S(c()).optional(),response_types_supported:S(c()),response_modes_supported:S(c()).optional(),grant_types_supported:S(c()).optional(),acr_values_supported:S(c()).optional(),subject_types_supported:S(c()),id_token_signing_alg_values_supported:S(c()),id_token_encryption_alg_values_supported:S(c()).optional(),id_token_encryption_enc_values_supported:S(c()).optional(),userinfo_signing_alg_values_supported:S(c()).optional(),userinfo_encryption_alg_values_supported:S(c()).optional(),userinfo_encryption_enc_values_supported:S(c()).optional(),request_object_signing_alg_values_supported:S(c()).optional(),request_object_encryption_alg_values_supported:S(c()).optional(),request_object_encryption_enc_values_supported:S(c()).optional(),token_endpoint_auth_methods_supported:S(c()).optional(),token_endpoint_auth_signing_alg_values_supported:S(c()).optional(),display_values_supported:S(c()).optional(),claim_types_supported:S(c()).optional(),claims_supported:S(c()).optional(),service_documentation:c().optional(),claims_locales_supported:S(c()).optional(),ui_locales_supported:S(c()).optional(),claims_parameter_supported:E().optional(),request_parameter_supported:E().optional(),request_uri_parameter_supported:E().optional(),require_request_uri_registration:E().optional(),op_policy_uri:ve.optional(),op_tos_uri:ve.optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0)}),Ko=p({...Ci.shape,...Br.pick({code_challenge_methods_supported:!0}).shape}),Go=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(),Ii=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(),Yo=p({error:c(),error_description:c().optional(),error_uri:c().optional()}),su=ve.optional().or(h("").transform(()=>{return})),Oi=p({redirect_uris:S(ve),token_endpoint_auth_method:c().optional(),grant_types:S(c()).optional(),response_types:S(c()).optional(),application_type:c().optional(),client_name:c().optional(),client_uri:ve.optional(),logo_uri:su,scope:c().optional(),contacts:S(c()).optional(),tos_uri:su,policy_uri:c().optional(),jwks_uri:ve.optional(),jwks:Va().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Ni=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(),Xo=Oi.merge(Ni),gc=p({error:c(),error_description:c().optional()}).strip(),Sc=p({token:c(),token_type_hint:c().optional()}).strip();var du=Symbol.for("mcp.sdk.errorBrands");function Wr(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,du,{value:r,enumerable:!1,configurable:!0})}function Ke(e,t){try{if(typeof t==="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand==="string"&&Object.prototype.hasOwnProperty.call(t,du)){let r=t[du];if(r&&typeof r.has==="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var Vt=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}({}),Kr=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Ke(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 Ke(this,t)}constructor(t,r,o){super(r);this.code=t,this.errorUri=o,this.name="OAuthError",Wr(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)}},N=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}({}),A=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Ke(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 Ke(this,e)}constructor(e,t,r,o){super(t,o);this.code=e,this.data=r,this.name="SdkError",Wr(this,new.target)}},Tt=class extends A{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 Ff(e){let t=typeof e==="string"?new URL(e):new URL(e.href);return t.hash="",t}function gu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}function Hf({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+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(i)}var Vf="2026-07-28",Su=[Vf];function Jt(e){return e>=Vf}function _u(e){return e.filter((t)=>!Jt(t))}function Ui(e){return e.filter((t)=>Jt(t))}function Jf(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 Bf=["task","inputRequests","requestState"];function $b(e){if(e===null||typeof e!=="object"||Array.isArray(e)||e.content!==void 0||Bf.some((t)=>(t in e)))return e;return{...e,content:[]}}function Cb(){let e=es(()=>T([c(),z(),E(),Cr(),P(c(),e),S(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=p({ttl:z().optional()}),i=p({taskId:c()}),s=F({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),a=p({_meta:s.optional()}),l=a.extend({task:n.optional()}),u=p({method:c(),params:a.loose().optional()}),d=p({_meta:s.optional()}),m=p({method:c(),params:d.loose().optional()}),f=F({_meta:s.optional()}),g=T([c(),z().int()]),b=f.strict(),y=d.extend({requestId:g.optional(),reason:c().optional()}),v=m.extend({method:h("notifications/cancelled"),params:y}),L=p({src:c(),mimeType:c().optional(),sizes:S(c()).optional(),theme:K(["light","dark"]).optional()}),H=p({icons:S(L).optional()}),x=p({name:c(),title:c().optional()}),Z=x.extend({...x.shape,...H.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),R=At(p({applyDefaults:E().optional()}),t),w=Ir((Ee)=>{if(Ee&&typeof Ee==="object"&&!Array.isArray(Ee)&&Object.keys(Ee).length===0)return{form:{}};return Ee},At(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()}),ue=a.extend({protocolVersion:c(),capabilities:Y,clientInfo:Z}),$e=u.extend({method:h("initialize"),params:ue}),oe=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()}),ae=f.extend({protocolVersion:c(),capabilities:oe,serverInfo:Z,instructions:c().optional()}),we=m.extend({method:h("notifications/initialized"),params:d.optional()}),Ce=u.extend({method:h("ping"),params:a.optional()}),mt=p({progress:z(),total:U(z()),message:U(c())}),Me=p({...d.shape,...mt.shape,progressToken:r}),Ye=m.extend({method:h("notifications/progress"),params:Me}),ft=a.extend({cursor:o.optional()}),Fe=u.extend({params:ft.optional()}),Ie=f.extend({nextCursor:o.optional()}),It=p({uri:c(),mimeType:U(c()),_meta:P(c(),M()).optional()}),Ot=It.extend({text:c()}),gt=c().refine((Ee)=>{try{return atob(Ee),!0}catch{return!1}},{message:"Invalid Base64 string"}),Pe=It.extend({blob:gt}),Oe=K(["user","assistant"]),Ne=p({audience:S(Oe).optional(),priority:z().min(0).max(1).optional(),lastModified:_o({offset:!0}).optional()}),st=p({...x.shape,...H.shape,uri:c(),description:U(c()),mimeType:U(c()),size:U(z()),annotations:Ne.optional(),_meta:U(F({}))}),gr=p({...x.shape,...H.shape,uriTemplate:c(),description:U(c()),mimeType:U(c()),annotations:Ne.optional(),_meta:U(F({}))}),He=Fe.extend({method:h("resources/list")}),Ve=Ie.extend({resources:S(st)}),je=Fe.extend({method:h("resources/templates/list")}),Xe=Ie.extend({resourceTemplates:S(gr)}),Qe=a.extend({uri:c()}),St=Qe,_t=u.extend({method:h("resources/read"),params:St}),Yt=f.extend({contents:S(T([Ot,Pe]))}),bt=m.extend({method:h("notifications/resources/list_changed"),params:d.optional()}),Sr=Qe,I=u.extend({method:h("resources/subscribe"),params:Sr}),yt=Qe,V=u.extend({method:h("resources/unsubscribe"),params:yt}),q=d.extend({uri:c()}),G=m.extend({method:h("notifications/resources/updated"),params:q}),O=p({name:c(),description:U(c()),required:U(E())}),C=p({...x.shape,...H.shape,description:U(c()),arguments:U(S(O)),_meta:U(F({}))}),B=Fe.extend({method:h("prompts/list")}),J=Ie.extend({prompts:S(C)}),_e=a.extend({name:c(),arguments:P(c(),c()).optional()}),_r=u.extend({method:h("prompts/get"),params:_e}),vt=p({type:h("text"),text:c(),annotations:Ne.optional(),_meta:P(c(),M()).optional()}),br=p({type:h("image"),data:gt,mimeType:c(),annotations:Ne.optional(),_meta:P(c(),M()).optional()}),yr=p({type:h("audio"),data:gt,mimeType:c(),annotations:Ne.optional(),_meta:P(c(),M()).optional()}),pn=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),M()),_meta:P(c(),M()).optional()}),Xt=p({type:h("resource"),resource:T([Ot,Pe]),annotations:Ne.optional(),_meta:P(c(),M()).optional()}),hn=st.extend({type:h("resource_link")}),et=T([vt,br,yr,hn,Xt]),ro=p({role:Oe,content:et}),oo=f.extend({description:c().optional(),messages:S(ro)}),vr=m.extend({method:h("notifications/prompts/list_changed"),params:d.optional()}),mn=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),no=p({taskSupport:K(["required","optional","forbidden"]).optional()}),zr=p({...x.shape,...H.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:S(c()).optional()}).catchall(M()),outputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:S(c()).optional()}).catchall(M()).optional(),annotations:mn.optional(),execution:no.optional(),_meta:P(c(),M()).optional()}),so=Fe.extend({method:h("tools/list")}),io=Ie.extend({tools:S(zr)}),ao=f.extend({content:S(et),structuredContent:P(c(),M()).optional(),isError:E().optional()}),Te=l.extend({name:c(),arguments:P(c(),M()).optional()}),fn=u.extend({method:h("tools/call"),params:Te}),na=m.extend({method:h("notifications/tools/list_changed"),params:d.optional()}),co=K(["debug","info","notice","warning","error","critical","alert","emergency"]),gn=a.extend({level:co}),Sn=u.extend({method:h("logging/setLevel"),params:gn}),_n=d.extend({level:co,logger:c().optional(),data:M()}),bn=m.extend({method:h("notifications/message"),params:_n}),yn=p({name:c().optional()}),vn=p({hints:S(yn).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),zn=p({mode:K(["auto","required","none"]).optional()}),sa=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:S(et),structuredContent:p({}).loose().optional(),isError:E().optional(),_meta:P(c(),M()).optional()}),wn=bo("type",[vt,br,yr]),Qt=bo("type",[vt,br,yr,pn,sa]),Rn=p({role:Oe,content:T([Qt,S(Qt)]),_meta:P(c(),M()).optional()}),xn=l.extend({messages:S(Rn),modelPreferences:vn.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:S(c()).optional(),metadata:t.optional(),tools:S(zr).optional(),toolChoice:zn.optional()}),Pn=u.extend({method:h("sampling/createMessage"),params:xn}),Tn=f.extend({model:c(),stopReason:U(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Oe,content:wn}),En=f.extend({model:c(),stopReason:U(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Oe,content:T([Qt,S(Qt)])}),kn=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),$n=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()}),Cn=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),In=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),default:c().optional()}),On=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:S(p({const:c(),title:c()})),default:c().optional()}),Nn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),enumNames:S(c()).optional(),default:c().optional()}),An=T([In,On]),wr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:S(c())}),default:S(c()).optional()}),Rr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:S(p({const:c(),title:c()}))}),default:S(c()).optional()}),ia=T([wr,Rr]),aa=T([Nn,An,ia]),Je=T([aa,kn,$n,Cn]),Be=l.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),Je),required:S(c()).optional()}).catchall(M())}),qn=l.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),it=T([Be,qn]),ca=u.extend({method:h("elicitation/create"),params:it}),la=d.extend({elicitationId:c()}),ua=m.extend({method:h("notifications/elicitation/complete"),params:la}),da=f.extend({action:K(["accept","decline","cancel"]),content:Ir((Ee)=>Ee===null?void 0:Ee,P(c(),T([c(),z(),E(),S(c())])).optional())}),pa=p({type:h("ref/resource"),uri:c()}),ha=p({type:h("ref/prompt"),name:c()}),ma=a.extend({ref:T([ha,pa]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),Mn=u.extend({method:h("completion/complete"),params:ma}),fa=f.extend({completion:F({values:S(c()).max(100),total:U(z().int()),hasMore:U(E())})}),ga=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),M()).optional()}),lo=u.extend({method:h("roots/list"),params:a.optional()}),jn=f.extend({roots:S(ga)}),Sa=m.extend({method:h("notifications/roots/list_changed"),params:d.optional()}),_a=F({ttl:z().optional(),pollInterval:z().optional()}),Ln=K(["working","input_required","completed","failed","cancelled"]),er=p({taskId:c(),status:Ln,ttl:T([z(),Cr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:U(z()),statusMessage:U(c())}),Le=f.extend({task:er}),ba=d.merge(er),xr=m.extend({method:h("notifications/tasks/status"),params:ba}),uo=u.extend({method:h("tasks/get"),params:a.extend({taskId:c()})}),po=f.merge(er),ho=u.extend({method:h("tasks/result"),params:a.extend({taskId:c()})}),Bc=f.loose(),Ae=Fe.extend({method:h("tasks/list")}),ge=Ie.extend({tasks:S(er)}),Pr=u.extend({method:h("tasks/cancel"),params:a.extend({taskId:c()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:n,RelatedTaskMetadataSchema:i,RequestMetaSchema:s,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:l,RequestSchema:u,NotificationsParamsSchema:d,NotificationSchema:m,ResultSchema:f,RequestIdSchema:g,EmptyResultSchema:b,CancelledNotificationParamsSchema:y,CancelledNotificationSchema:v,IconSchema:L,IconsSchema:H,BaseMetadataSchema:x,ImplementationSchema:Z,ClientTasksCapabilitySchema:D,ServerTasksCapabilitySchema:X,ClientCapabilitiesSchema:Y,InitializeRequestParamsSchema:ue,InitializeRequestSchema:$e,ServerCapabilitiesSchema:oe,InitializeResultSchema:ae,InitializedNotificationSchema:we,PingRequestSchema:Ce,ProgressSchema:mt,ProgressNotificationParamsSchema:Me,ProgressNotificationSchema:Ye,PaginatedRequestParamsSchema:ft,PaginatedRequestSchema:Fe,PaginatedResultSchema:Ie,ResourceContentsSchema:It,TextResourceContentsSchema:Ot,BlobResourceContentsSchema:Pe,RoleSchema:Oe,AnnotationsSchema:Ne,ResourceSchema:st,ResourceTemplateSchema:gr,ListResourcesRequestSchema:He,ListResourcesResultSchema:Ve,ListResourceTemplatesRequestSchema:je,ListResourceTemplatesResultSchema:Xe,ResourceRequestParamsSchema:Qe,ReadResourceRequestParamsSchema:St,ReadResourceRequestSchema:_t,ReadResourceResultSchema:Yt,ResourceListChangedNotificationSchema:bt,SubscribeRequestParamsSchema:Sr,SubscribeRequestSchema:I,UnsubscribeRequestParamsSchema:yt,UnsubscribeRequestSchema:V,ResourceUpdatedNotificationParamsSchema:q,ResourceUpdatedNotificationSchema:G,PromptArgumentSchema:O,PromptSchema:C,ListPromptsRequestSchema:B,ListPromptsResultSchema:J,GetPromptRequestParamsSchema:_e,GetPromptRequestSchema:_r,TextContentSchema:vt,ImageContentSchema:br,AudioContentSchema:yr,ToolUseContentSchema:pn,EmbeddedResourceSchema:Xt,ResourceLinkSchema:hn,ContentBlockSchema:et,PromptMessageSchema:ro,GetPromptResultSchema:oo,PromptListChangedNotificationSchema:vr,ToolAnnotationsSchema:mn,ToolExecutionSchema:no,ToolSchema:zr,ListToolsRequestSchema:so,ListToolsResultSchema:io,CallToolResultSchema:ao,CallToolRequestParamsSchema:Te,CallToolRequestSchema:fn,ToolListChangedNotificationSchema:na,LoggingLevelSchema:co,SetLevelRequestParamsSchema:gn,SetLevelRequestSchema:Sn,LoggingMessageNotificationParamsSchema:_n,LoggingMessageNotificationSchema:bn,ModelHintSchema:yn,ModelPreferencesSchema:vn,ToolChoiceSchema:zn,ToolResultContentSchema:sa,SamplingContentSchema:wn,SamplingMessageContentBlockSchema:Qt,SamplingMessageSchema:Rn,CreateMessageRequestParamsSchema:xn,CreateMessageRequestSchema:Pn,CreateMessageResultSchema:Tn,CreateMessageResultWithToolsSchema:En,BooleanSchemaSchema:kn,StringSchemaSchema:$n,NumberSchemaSchema:Cn,UntitledSingleSelectEnumSchemaSchema:In,TitledSingleSelectEnumSchemaSchema:On,LegacyTitledEnumSchemaSchema:Nn,SingleSelectEnumSchemaSchema:An,UntitledMultiSelectEnumSchemaSchema:wr,TitledMultiSelectEnumSchemaSchema:Rr,MultiSelectEnumSchemaSchema:ia,EnumSchemaSchema:aa,PrimitiveSchemaDefinitionSchema:Je,ElicitRequestFormParamsSchema:Be,ElicitRequestURLParamsSchema:qn,ElicitRequestParamsSchema:it,ElicitRequestSchema:ca,ElicitationCompleteNotificationParamsSchema:la,ElicitationCompleteNotificationSchema:ua,ElicitResultSchema:da,ResourceTemplateReferenceSchema:pa,PromptReferenceSchema:ha,CompleteRequestParamsSchema:ma,CompleteRequestSchema:Mn,CompleteResultSchema:fa,RootSchema:ga,ListRootsRequestSchema:lo,ListRootsResultSchema:jn,RootsListChangedNotificationSchema:Sa,TaskCreationParamsSchema:_a,TaskStatusSchema:Ln,TaskSchema:er,CreateTaskResultSchema:Le,TaskStatusNotificationParamsSchema:ba,TaskStatusNotificationSchema:xr,GetTaskRequestSchema:uo,GetTaskResultSchema:po,GetTaskPayloadRequestSchema:ho,GetTaskPayloadResultSchema:Bc,ListTasksRequestSchema:Ae,ListTasksResultSchema:ge,CancelTaskRequestSchema:Pr,CancelTaskResultSchema:f.merge(er),ClientRequestSchema:T([Ce,$e,Mn,Sn,_r,B,He,je,_t,I,V,fn,so,uo,ho,Ae,Pr]),ClientNotificationSchema:T([v,Ye,we,Sa,xr]),ClientResultSchema:T([b,Tn,En,da,jn,po,ge,Le]),ServerRequestSchema:T([Ce,Pn,ca,lo,uo,ho,Ae,Pr]),ServerNotificationSchema:T([v,Ye,bn,G,bt,na,vr,xr,ua]),ServerResultSchema:T([b,ae,fa,oo,J,Ve,Xe,Yt,ao,io,po,ge,Le]),CallToolResultWireSchema:M().superRefine((Ee,GS)=>{if(typeof Ee!=="object"||Ee===null||Array.isArray(Ee)||Ee.content!==void 0)return;for(let hd of Bf)if(hd in Ee){GS.addIssue({code:"custom",message:`content is required when the body carries '${hd}' — another result family cannot default into an empty tools/call success`});return}}).transform($b).pipe(ao)}}var Ib;function Wf(){return Ib??=Cb()}function Kf(e){return e.type!=="object"}var Ob=new Set(["const","enum","default","examples"]),Nb=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function kf(e){return e!==void 0&&!(typeof e==="string"&&e.startsWith("#"))}function Ab(e){let t=typeof e.$schema==="string"?e.$schema:void 0;if(kf(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=bd(e.$schema)&&e.$recursiveAnchor!==!0,o=(n,i)=>{if(Array.isArray(n))return n.map((l)=>o(l,!1));if(n===null||typeof n!=="object")return n;if(!i&&kf(n.$id))return n;let s={},a=!1;for(let[l,u]of Object.entries(n))if(i)s[l]=o(u,!1);else if((l==="$ref"||l==="$dynamicRef")&&typeof u==="string")s[l]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u;else if(l==="$recursiveRef"&&u==="#"&&r)a=!0;else if(Ob.has(l))s[l]=u;else if(Nb.has(l))s[l]=o(u,!0);else s[l]=o(u,!1);if(a)if("$ref"in s)s.allOf=[...Array.isArray(s.allOf)?s.allOf:[],{$ref:"#/properties/result"}];else s.$ref="#/properties/result";return s};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}var Gf={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},Yf={"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},qb={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},_c;function bu(){if(_c)return _c;let e=Wf();return _c={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}},_c}function Xf(e){return Object.prototype.hasOwnProperty.call(Gf,e)}function Qf(e){return Object.prototype.hasOwnProperty.call(Yf,e)}function Mb(e){return Object.prototype.hasOwnProperty.call(qb,e)}function jb(e){return Mb(e)?bu().resultSchemas[e]:void 0}function Lb(e){return Xf(e)?bu().requestSchemas[e]:void 0}function Ub(e){return Qf(e)?bu().notificationSchemas[e]:void 0}var Yx=Object.keys(Gf),Xx=Object.keys(Yf);function pu(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function bc(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 $f={ok:!1,reason:"not-in-era"};function Cf(e){return pu(e)&&pu(e.outputSchema)&&Kf(e.outputSchema)}function If(e){return e}var yu={era:"2025-11-25",hasRequestMethod:Xf,hasNotificationMethod:Qf,validateRequest:(e,t)=>bc(Lb(e),t),validateResult:(e,t)=>bc(jb(e),t),validateNotification:(e,t)=>bc(Ub(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>$f,validateInputResponse:()=>$f,samplingResultVariant:(e,t)=>{let r=Wf();return bc(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)},outboundEnvelope:(e)=>{return},validateEnvelopeMeta:(e)=>[],projectCallToolResult(e,t){let r=Jf(e),o=r.structuredContent;if(o===void 0)return r;let n=typeof o!=="object"||o===null||Array.isArray(o),i=t!==void 0&&Kf(t);if(!n&&!i)return r;return{...r,structuredContent:{result:o}}},decodeResult(e,t){if(pu(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:If(r)}}return{kind:"complete",result:If(t)}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;if(!Array.isArray(r)||!r.some((o)=>Cf(o)))return t;return{...t,tools:r.map((o)=>Cf(o)?{...o,outputSchema:Ab(o.outputSchema)}:o)}},encodeErrorCode:(e)=>e===-32002?-32602:e,checkInboundEnvelope:(e)=>{return}};function Zb(){let e=es(()=>T([c(),z(),E(),Cr(),P(c(),e),S(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=T([c(),z().int()]),i=K(["user","assistant"]),s=K(["debug","info","notice","warning","error","critical","alert","emergency"]),a=c().refine((ge)=>{try{return atob(ge),!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()}),g=p({_meta:d.optional()}),b=p({method:c(),params:g.loose().optional()}),y=p({src:c(),mimeType:c().optional(),sizes:S(c()).optional(),theme:K(["light","dark"]).optional()}),v=p({icons:S(y).optional()}),L=p({name:c(),title:c().optional()}),H=L.extend({...L.shape,...v.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),x=At(p({applyDefaults:E().optional()}),t),Z=Ir((ge)=>{if(ge&&typeof ge==="object"&&!Array.isArray(ge)&&Object.keys(ge).length===0)return{form:{}};return ge},At(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:U(z()),message:U(c())}),ue=p({...g.shape,...Y.shape,progressToken:r}),$e=b.extend({method:h("notifications/progress"),params:ue}),oe=g.extend({level:s,logger:c().optional(),data:M()}),ae=b.extend({method:h("notifications/message"),params:oe}),we=p({uri:c(),mimeType:U(c()),_meta:P(c(),M()).optional()}),Ce=we.extend({text:c()}),mt=we.extend({blob:a}),Me=p({audience:S(i).optional(),priority:z().min(0).max(1).optional(),lastModified:_o({offset:!0}).optional()}),Ye=p({...L.shape,...v.shape,uri:c(),description:U(c()),mimeType:U(c()),size:U(z()),annotations:Me.optional(),_meta:U(F({}))}),ft=p({...L.shape,...v.shape,uriTemplate:c(),description:U(c()),mimeType:U(c()),annotations:Me.optional(),_meta:U(F({}))}),Fe=b.extend({method:h("notifications/resources/list_changed"),params:g.optional()}),Ie=g.extend({uri:c()}),It=b.extend({method:h("notifications/resources/updated"),params:Ie}),Ot=p({name:c(),description:U(c()),required:U(E())}),gt=p({...L.shape,...v.shape,description:U(c()),arguments:U(S(Ot)),_meta:U(F({}))}),Pe=b.extend({method:h("notifications/prompts/list_changed"),params:g.optional()}),Oe=p({type:h("text"),text:c(),annotations:Me.optional(),_meta:P(c(),M()).optional()}),Ne=p({type:h("image"),data:a,mimeType:c(),annotations:Me.optional(),_meta:P(c(),M()).optional()}),st=p({type:h("audio"),data:a,mimeType:c(),annotations:Me.optional(),_meta:P(c(),M()).optional()}),gr=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),M()),_meta:P(c(),M()).optional()}),He=p({type:h("resource"),resource:T([Ce,mt]),annotations:Me.optional(),_meta:P(c(),M()).optional()}),Ve=Ye.extend({type:h("resource_link")}),je=T([Oe,Ne,st,Ve,He]),Xe=p({role:i,content:je}),Qe=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),St=b.extend({method:h("notifications/tools/list_changed"),params:g.optional()}),_t=p({name:c().optional()}),Yt=p({hints:S(_t).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),bt=p({mode:K(["auto","required","none"]).optional()}),Sr=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),I=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()}),yt=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:S(c()),default:c().optional()}),q=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:S(p({const:c(),title:c()})),default:c().optional()}),G=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),enumNames:S(c()).optional(),default:c().optional()}),O=T([V,q]),C=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:S(c())}),default:S(c()).optional()}),B=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:S(p({const:c(),title:c()}))}),default:S(c()).optional()}),J=T([C,B]),_e=T([G,O,J]),_r=T([_e,Sr,I,yt]),vt=f.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),_r),required:S(c()).optional()}).catchall(M())}),br=p({type:h("ref/resource"),uri:c()}),yr=p({type:h("ref/prompt"),name:c()}),pn=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),M()).optional()}),Xt=D.shape,hn=p({experimental:Xt.experimental,sampling:Xt.sampling,elicitation:Xt.elicitation,roots:Xt.roots,extensions:Xt.extensions}),et=X.shape,ro=p({experimental:et.experimental,logging:et.logging,completions:et.completions,prompts:et.prompts,resources:et.resources,tools:et.tools,extensions:et.extensions}),oo=F({progressToken:r.optional(),[Mt]:c(),[vo]:H.optional(),[Or]:hn,[zo]:s.optional()}),vr=p({...L.shape,...v.shape,description:c().optional(),inputSchema:F({$schema:c().optional(),type:h("object")}),outputSchema:F({$schema:c().optional()}).optional(),annotations:Qe.optional(),_meta:P(c(),M()).optional()}),mn=p({type:h("tool_result"),toolUseId:c(),content:S(je),structuredContent:M().optional(),isError:E().optional(),_meta:P(c(),M()).optional()}),no=T([Oe,Ne,st,gr,mn]),zr=p({role:i,content:T([no,S(no)]),_meta:P(c(),M()).optional()}),so=c(),io=F({[jt]:H.optional().catch(void 0)}),ao=io.optional();function Te(ge){return F({_meta:ao,resultType:so.default("complete"),...ge})}let fn=Te({}),na=Te({nextCursor:o.optional()}),co=Te({content:S(je),structuredContent:M().optional(),isError:E().optional()}),gn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:S(vr),nextCursor:o.optional()}),Sn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:S(gt),nextCursor:o.optional()}),_n=Te({description:c().optional(),messages:S(Xe)}),bn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:S(Ye),nextCursor:o.optional()}),yn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:S(ft),nextCursor:o.optional()}),vn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:S(T([Ce,mt]))}),zn=Te({completion:p({values:S(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),sa=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"])}),wn=Te({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:S(c()),capabilities:ro,instructions:c().optional()}),Qt=p({messages:S(zr),modelPreferences:Yt.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:S(c()).optional(),metadata:t.optional(),tools:S(vr).optional(),toolChoice:bt.optional()}),Rn=p({method:h("sampling/createMessage"),params:Qt}),xn=p({method:h("roots/list"),params:p({_meta:P(c(),M()).optional()}).optional()}),Pn=p({...zr.shape,model:c(),stopReason:c().optional()}),Tn=p({roots:S(pn)}),En=p({action:K(["accept","decline","cancel"]),content:P(c(),T([c(),z(),E(),S(c())])).optional()}),kn=p({mode:h("url"),message:c(),url:c().url()}),$n=T([vt,kn]),Cn=p({method:h("elicitation/create"),params:$n}),In=T([Rn,xn,Cn]),On=T([Pn,Tn,En]),Nn=P(c(),In),An=P(c(),On),wr=Te({inputRequests:Nn.optional(),requestState:c().optional()}),Rr={inputResponses:An.optional(),requestState:c().optional()},ia=p({_meta:oo,...Rr}),aa=F({progressToken:r.optional()});function Je(ge,Pr){return p({method:h(ge),params:p({_meta:oo,...Pr})})}function Be(ge,Pr){return p({method:h(ge),params:p({_meta:aa.optional(),...Pr}).optional()})}let qn={name:c(),arguments:P(c(),M()).optional(),...Rr},it={cursor:o.optional()},ca=Je("tools/call",qn),la=Je("tools/list",it),ua=Je("prompts/list",it),da=Je("prompts/get",{name:c(),arguments:P(c(),c()).optional(),...Rr}),pa=Je("resources/list",it),ha=Je("resources/templates/list",it),ma=Je("resources/read",{uri:c(),...Rr}),Mn={ref:T([yr,br]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()},fa=Je("completion/complete",Mn),ga=Je("server/discover",{}),lo=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:S(c()).optional()}),jn={notifications:lo},Sa=Je("subscriptions/listen",jn),_a=io.extend({"io.modelcontextprotocol/subscriptionId":n}),Ln=F({_meta:_a,resultType:so.default("complete")}),er={"tools/call":Be("tools/call",qn),"tools/list":Be("tools/list",it),"prompts/get":Be("prompts/get",{name:c(),arguments:P(c(),c()).optional()}),"prompts/list":Be("prompts/list",it),"resources/list":Be("resources/list",it),"resources/templates/list":Be("resources/templates/list",it),"resources/read":Be("resources/read",{uri:c()}),"completion/complete":Be("completion/complete",Mn),"server/discover":Be("server/discover",{}),"subscriptions/listen":Be("subscriptions/listen",jn)};function Le(ge){return F({_meta:ao,...ge})}let ba={"tools/call":Le({content:S(je),structuredContent:M().optional(),isError:E().optional()}),"tools/list":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:S(vr),nextCursor:o.optional()}),"prompts/get":Le({description:c().optional(),messages:S(Xe)}),"prompts/list":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:S(gt),nextCursor:o.optional()}),"resources/list":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:S(Ye),nextCursor:o.optional()}),"resources/templates/list":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:S(ft),nextCursor:o.optional()}),"resources/read":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:S(T([Ce,mt]))}),"completion/complete":Le({completion:p({values:S(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":Le({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:S(c()),capabilities:ro,instructions:c().optional()}),"subscriptions/listen":Le({})},xr=F({"io.modelcontextprotocol/subscriptionId":n.optional()}),uo=p({method:h("notifications/subscriptions/acknowledged"),params:p({_meta:xr.optional(),notifications:lo})}),po=p({_meta:xr.optional(),requestId:n,reason:c().optional()}),ho=p({method:h("notifications/cancelled"),params:po}),Bc={"notifications/cancelled":ho,"notifications/progress":$e,"notifications/message":ae,"notifications/resources/updated":It,"notifications/resources/list_changed":Fe,"notifications/tools/list_changed":St,"notifications/prompts/list_changed":Pe,"notifications/subscriptions/acknowledged":uo},Ae=(ge)=>p({jsonrpc:h("2.0"),id:T([c(),z().int()]),result:ge}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:n,RoleSchema:i,LoggingLevelSchema:s,TaskMetadataSchema:l,RelatedTaskMetadataSchema:u,RequestMetaSchema:d,BaseRequestParamsSchema:m,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:g,NotificationSchema:b,IconSchema:y,IconsSchema:v,BaseMetadataSchema:L,ImplementationSchema:H,ClientTasksCapabilitySchema:R,ServerTasksCapabilitySchema:w,ClientCapabilitiesSchema:D,ServerCapabilitiesSchema:X,ProgressSchema:Y,ProgressNotificationParamsSchema:ue,ProgressNotificationSchema:$e,LoggingMessageNotificationParamsSchema:oe,LoggingMessageNotificationSchema:ae,ResourceContentsSchema:we,TextResourceContentsSchema:Ce,BlobResourceContentsSchema:mt,AnnotationsSchema:Me,ResourceSchema:Ye,ResourceTemplateSchema:ft,ResourceListChangedNotificationSchema:Fe,ResourceUpdatedNotificationParamsSchema:Ie,ResourceUpdatedNotificationSchema:It,PromptArgumentSchema:Ot,PromptSchema:gt,PromptListChangedNotificationSchema:Pe,TextContentSchema:Oe,ImageContentSchema:Ne,AudioContentSchema:st,ToolUseContentSchema:gr,EmbeddedResourceSchema:He,ResourceLinkSchema:Ve,ContentBlockSchema:je,PromptMessageSchema:Xe,ToolAnnotationsSchema:Qe,ToolListChangedNotificationSchema:St,ModelHintSchema:_t,ModelPreferencesSchema:Yt,ToolChoiceSchema:bt,BooleanSchemaSchema:Sr,StringSchemaSchema:I,NumberSchemaSchema:yt,UntitledSingleSelectEnumSchemaSchema:V,TitledSingleSelectEnumSchemaSchema:q,LegacyTitledEnumSchemaSchema:G,SingleSelectEnumSchemaSchema:O,UntitledMultiSelectEnumSchemaSchema:C,TitledMultiSelectEnumSchemaSchema:B,MultiSelectEnumSchemaSchema:J,EnumSchemaSchema:_e,PrimitiveSchemaDefinitionSchema:_r,ElicitRequestFormParamsSchema:vt,ResourceTemplateReferenceSchema:br,PromptReferenceSchema:yr,RootSchema:pn,ClientCapabilities2026Schema:hn,ServerCapabilities2026Schema:ro,RequestMetaEnvelopeSchema:oo,ToolSchema:vr,ToolResultContentSchema:mn,SamplingMessageContentBlockSchema:no,SamplingMessageSchema:zr,ResultTypeSchema:so,ResultMetaSchema:io,ResultSchema:fn,PaginatedResultSchema:na,CallToolResultSchema:co,ListToolsResultSchema:gn,ListPromptsResultSchema:Sn,GetPromptResultSchema:_n,ListResourcesResultSchema:bn,ListResourceTemplatesResultSchema:yn,ReadResourceResultSchema:vn,CompleteResultSchema:zn,CacheableResultSchema:sa,DiscoverResultSchema:wn,CreateMessageRequestParamsSchema:Qt,CreateMessageRequestSchema:Rn,ListRootsRequestSchema:xn,CreateMessageResultSchema:Pn,ListRootsResultSchema:Tn,ElicitResultSchema:En,ElicitRequestURLParamsSchema:kn,ElicitRequestParamsSchema:$n,ElicitRequestSchema:Cn,InputRequestSchema:In,InputResponseSchema:On,InputRequestsSchema:Nn,InputResponsesSchema:An,InputRequiredResultSchema:wr,InputResponseRequestParamsSchema:ia,CallToolRequestSchema:ca,ListToolsRequestSchema:la,ListPromptsRequestSchema:ua,GetPromptRequestSchema:da,ListResourcesRequestSchema:pa,ListResourceTemplatesRequestSchema:ha,ReadResourceRequestSchema:ma,CompleteRequestSchema:fa,DiscoverRequestSchema:ga,SubscriptionFilterSchema:lo,SubscriptionsListenRequestSchema:Sa,SubscriptionsListenResultMetaSchema:_a,SubscriptionsListenResultSchema:Ln,dispatchRequestSchemas:er,dispatchResultSchemas:ba,NotificationMetaSchema:xr,SubscriptionsAcknowledgedNotificationSchema:uo,CancelledNotificationParamsSchema:po,CancelledNotificationSchema:ho,notificationSchemas2026:Bc,JSONRPCResultResponseSchema:Ae(fn),CallToolResultResponseSchema:Ae(T([co,wr])),ListToolsResultResponseSchema:Ae(gn),ListPromptsResultResponseSchema:Ae(Sn),GetPromptResultResponseSchema:Ae(T([_n,wr])),ListResourcesResultResponseSchema:Ae(bn),ListResourceTemplatesResultResponseSchema:Ae(yn),ReadResourceResultResponseSchema:Ae(T([vn,wr])),CompleteResultResponseSchema:Ae(zn),DiscoverResultResponseSchema:Ae(wn),SubscriptionsListenResultResponseSchema:Ae(Ln)}}var Db;function pr(){return Db??=Zb()}var Fb=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function Hb(e){return Fb.includes(e)}var vu=Symbol("modelcontextprotocol.resultCacheHintFallback");function Vb(e){return e[vu]}function eg(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function tg(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}({}),re=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Ke(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 Ke(this,t)}constructor(t,r,o){super(r);this.code=t,this.data=o,this.name="ProtocolError",Wr(this,new.target)}static fromError(t,r,o){if(t===W.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new og(n.elicitations,r)}if(t===W.UnsupportedProtocolVersion&&o){let n=o;if(Array.isArray(n.supported)&&typeof n.requested==="string")return new Rc({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 rg(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 ng({requiredCapabilities:n.requiredCapabilities},r)}return new e(t,r,o)}},rg=class extends re{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}},og=class extends re{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??[]}},Rc=class extends re{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}},ng=class extends re{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}},Jb=0,Bb="private",Wb=["tools/call","prompts/get","resources/read"];function Kb(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete")return t;if(Wb.includes(e))return t;throw new re(W.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function Gb(e,t){let r=Vb(t);if(t.resultType!=="complete"||!Hb(e))return r===void 0?t:ty(t);let o=t,n=eg(o.ttlMs)?o.ttlMs:Qb(r),i=tg(o.cacheScope)?o.cacheScope:ey(r),s={...o,ttlMs:n,cacheScope:i};return delete s[vu],s}function Yb(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Xb(e,t){if(t===void 0)return e;let r=e._meta;if(r===void 0)return{...e,_meta:{[jt]:t}};if(!Yb(r))return e;if(r[jt]!==void 0)return e;return{...e,_meta:{...r,[jt]:t}}}function Qb(e){return e!==void 0&&eg(e.ttlMs)?e.ttlMs:Jb}function ey(e){return e!==void 0&&tg(e.cacheScope)?e.cacheScope:Bb}function ty(e){let t={...e};return delete t[vu],t}var ry=["elicitation/create","sampling/createMessage","roots/list"],yc;function sg(){if(yc)return yc;let e=pr();return yc={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}},yc}function ig(e){return ry.includes(e)}function au(e){return ig(e)?sg().request[e]:void 0}function oy(e){return ig(e)?sg().response[e]:void 0}var zu={"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},ag={"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 cg(e){return Object.prototype.hasOwnProperty.call(zu,e)}function lg(e){return Object.prototype.hasOwnProperty.call(ag,e)}function ny(e){return Object.prototype.hasOwnProperty.call(zu,e)}function sy(e){return cg(e)?pr().dispatchRequestSchemas[e]:void 0}function iy(e){return ny(e)?pr().dispatchResultSchemas[e]:void 0}function ay(e){return lg(e)?pr().notificationSchemas2026[e]:void 0}var Qx=Object.keys(zu),eP=Object.keys(ag);function Mi(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Ai(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 cy={ok:!1,reason:"not-in-era"},ly=[Mt,Or];function uy(e,t){let r=t,o=!1,n=()=>{if(!o)r={...r},o=!0;return r},i=t.tools;if(e==="tools/list"&&Array.isArray(i)&&i.some((a)=>Mi(a)&&("execution"in a)))n().tools=i.map((a)=>{if(!Mi(a)||!("execution"in a))return a;let l={...a};return delete l.execution,l});let s=t.capabilities;if(Mi(s)&&"tasks"in s){let a={...s};delete a.tasks,n().capabilities=a}return r}var wu={era:"2026-07-28",hasRequestMethod:cg,hasNotificationMethod:lg,hasInputRequestMethod:(e)=>au(e)!==void 0,validateRequest:(e,t)=>Ai(sy(e),t),validateResult:(e,t)=>Ai(iy(e),t),validateNotification:(e,t)=>Ai(ay(e),t),validateInputRequest:(e,t)=>Ai(au(e),t),validateInputResponse:(e,t)=>Ai(oy(e),t),samplingResultVariant:()=>cy,outboundEnvelope(e){return{[Mt]:e.protocolVersion,[vo]:e.clientInfo,[Or]:e.clientCapabilities,...e.logLevel!==void 0&&{[zo]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of ly)if(!(o in e))t.push({key:o,problem:"missing"});let r=pr().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let n=o.path.map(String),i=n.length>0?n.join("."):"_meta";if(n.length===1&&t.some((s)=>s.key===i&&s.problem==="missing"))continue;t.push({key:i,problem:o.message})}return t},projectCallToolResult:(e)=>Jf(e),inputRequestSchema:au,decodeResult(e,t){if(!Mi(t))return{kind:"invalid",error:new A(N.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new A(N.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 A(N.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let s=t.inputRequests,a=Mi(s)?s:{},l=t.requestState,u=t._meta===void 0?void 0:pr().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 A(N.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 A(N.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=dy(),n=Object.hasOwn(o,e)?o[e]:void 0;if(n!==void 0){let s=n.safeParse(t);if(!s.success)return{kind:"invalid",error:new A(N.InvalidResult,`Invalid result for ${e}: ${s.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return Xb(Gb(e,Kb(e,uy(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=pr().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("; ")}`}},vc;function dy(){if(vc)return vc;let e=pr();return vc={"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},vc}var xc="2026-07-28";function Ht(e){return e!==void 0&&Jt(e)?wu:yu}function Of(e){if(e.revision!==void 0)return Ht(e.revision).era;return e.era==="modern"?wu.era:yu.era}function cu(e){return ug.some((t)=>t.hasRequestMethod(e))}function lu(e){return ug.some((t)=>t.hasNotificationMethod(e))}function Nf(e){return e==="tasks/get"||e==="tasks/cancel"}var ug=[yu,wu],py=gd({AnnotationsSchema:()=>xt,AudioContentSchema:()=>Ur,BaseMetadataSchema:()=>wt,BaseRequestParamsSchema:()=>ze,BlobResourceContentsSchema:()=>Mo,BooleanSchemaSchema:()=>Zo,CallToolRequestParamsSchema:()=>Ws,CallToolRequestSchema:()=>Ks,CallToolResultSchema:()=>dr,CancelTaskRequestSchema:()=>cc,CancelTaskResultSchema:()=>lc,CancelledNotificationParamsSchema:()=>ns,CancelledNotificationSchema:()=>ko,ClientCapabilitiesSchema:()=>is,ClientNotificationSchema:()=>dc,ClientRequestSchema:()=>uc,ClientResultSchema:()=>pc,ClientTasksCapabilitySchema:()=>Ga,CompatibilityCallToolResultSchema:()=>Xa,CompleteRequestParamsSchema:()=>zi,CompleteRequestSchema:()=>wi,CompleteResultSchema:()=>Ri,ContentBlockSchema:()=>Pt,CreateMessageRequestParamsSchema:()=>ai,CreateMessageRequestSchema:()=>ci,CreateMessageResultSchema:()=>li,CreateMessageResultWithToolsSchema:()=>ui,CreateTaskResultSchema:()=>ec,CursorSchema:()=>Ro,DiscoverRequestSchema:()=>ls,DiscoverResultSchema:()=>lr,ElicitRequestFormParamsSchema:()=>Jr,ElicitRequestParamsSchema:()=>fi,ElicitRequestSchema:()=>gi,ElicitRequestURLParamsSchema:()=>mi,ElicitResultSchema:()=>bi,ElicitationCompleteNotificationParamsSchema:()=>Si,ElicitationCompleteNotificationSchema:()=>_i,EmbeddedResourceSchema:()=>Zr,EmptyResultSchema:()=>cr,EnumSchemaSchema:()=>hi,GetPromptRequestParamsSchema:()=>js,GetPromptRequestSchema:()=>Ls,GetPromptResultSchema:()=>Ds,GetTaskPayloadRequestSchema:()=>nc,GetTaskPayloadResultSchema:()=>sc,GetTaskRequestSchema:()=>rc,GetTaskResultSchema:()=>oc,IconSchema:()=>ss,IconsSchema:()=>Lt,ImageContentSchema:()=>Lr,ImplementationSchema:()=>Rt,InitializeRequestParamsSchema:()=>as,InitializeRequestSchema:()=>$o,InitializeResultSchema:()=>cs,InitializedNotificationSchema:()=>Io,JSONArraySchema:()=>Wa,JSONObjectSchema:()=>de,JSONRPCErrorResponseSchema:()=>qr,JSONRPCMessageSchema:()=>ut,JSONRPCNotificationSchema:()=>Eo,JSONRPCRequestSchema:()=>To,JSONRPCResponseSchema:()=>Ka,JSONRPCResultResponseSchema:()=>Ar,JSONValueSchema:()=>qt,LegacyTitledEnumSchemaSchema:()=>Ho,ListChangedOptionsBaseSchema:()=>Ys,ListPromptsRequestSchema:()=>qs,ListPromptsResultSchema:()=>Ms,ListResourceTemplatesRequestSchema:()=>gs,ListResourceTemplatesResultSchema:()=>Ss,ListResourcesRequestSchema:()=>ms,ListResourcesResultSchema:()=>fs,ListRootsRequestSchema:()=>Pi,ListRootsResultSchema:()=>Ti,ListTasksRequestSchema:()=>ic,ListTasksResultSchema:()=>ac,ListToolsRequestSchema:()=>Js,ListToolsResultSchema:()=>Bs,LoggingLevelSchema:()=>Uo,LoggingMessageNotificationParamsSchema:()=>ei,LoggingMessageNotificationSchema:()=>Fr,ModelHintSchema:()=>ti,ModelPreferencesSchema:()=>ri,MultiSelectEnumSchemaSchema:()=>pi,NotificationSchema:()=>xe,NotificationsParamsSchema:()=>ke,NumberSchemaSchema:()=>Vr,PaginatedRequestParamsSchema:()=>ps,PaginatedRequestSchema:()=>Ut,PaginatedResultSchema:()=>Zt,PingRequestSchema:()=>Oo,PrimitiveSchemaDefinitionSchema:()=>Bo,ProgressNotificationParamsSchema:()=>ds,ProgressNotificationSchema:()=>No,ProgressSchema:()=>us,ProgressTokenSchema:()=>wo,PromptArgumentSchema:()=>Ns,PromptListChangedNotificationSchema:()=>Fs,PromptMessageSchema:()=>Zs,PromptReferenceSchema:()=>vi,PromptSchema:()=>As,ReadResourceRequestParamsSchema:()=>_s,ReadResourceRequestSchema:()=>bs,ReadResourceResultSchema:()=>ys,RelatedTaskMetadataSchema:()=>os,RequestIdSchema:()=>lt,RequestMetaSchema:()=>xo,RequestSchema:()=>pe,ResourceContentsSchema:()=>Ao,ResourceLinkSchema:()=>Dr,ResourceListChangedNotificationSchema:()=>vs,ResourceRequestParamsSchema:()=>Mr,ResourceSchema:()=>jo,ResourceTemplateReferenceSchema:()=>yi,ResourceTemplateSchema:()=>hs,ResourceUpdatedNotificationParamsSchema:()=>Is,ResourceUpdatedNotificationSchema:()=>Os,ResultMetaObjectSchema:()=>Po,ResultSchema:()=>he,RoleSchema:()=>Dt,RootSchema:()=>xi,RootsListChangedNotificationSchema:()=>Ei,SamplingContentSchema:()=>si,SamplingMessageContentBlockSchema:()=>ir,SamplingMessageSchema:()=>ii,ServerCapabilitiesSchema:()=>Co,ServerNotificationSchema:()=>mc,ServerRequestSchema:()=>hc,ServerResultSchema:()=>fc,ServerTasksCapabilitySchema:()=>Ya,SetLevelRequestParamsSchema:()=>Xs,SetLevelRequestSchema:()=>Qs,SingleSelectEnumSchemaSchema:()=>di,StringSchemaSchema:()=>Hr,SubscribeRequestParamsSchema:()=>zs,SubscribeRequestSchema:()=>ws,SubscriptionFilterSchema:()=>Lo,SubscriptionsAcknowledgedNotificationParamsSchema:()=>Es,SubscriptionsAcknowledgedNotificationSchema:()=>ks,SubscriptionsListenRequestParamsSchema:()=>Ps,SubscriptionsListenRequestSchema:()=>Ts,SubscriptionsListenResultMetaSchema:()=>$s,SubscriptionsListenResultSchema:()=>Cs,TaskAugmentedRequestParamsSchema:()=>ar,TaskCreationParamsSchema:()=>Qa,TaskMetadataSchema:()=>rs,TaskSchema:()=>Ft,TaskStatusNotificationParamsSchema:()=>$i,TaskStatusNotificationSchema:()=>tc,TaskStatusSchema:()=>ki,TextContentSchema:()=>jr,TextResourceContentsSchema:()=>qo,TitledMultiSelectEnumSchemaSchema:()=>Jo,TitledSingleSelectEnumSchemaSchema:()=>Fo,ToolAnnotationsSchema:()=>Hs,ToolChoiceSchema:()=>oi,ToolExecutionSchema:()=>Vs,ToolListChangedNotificationSchema:()=>Gs,ToolResultContentSchema:()=>ni,ToolSchema:()=>ur,ToolUseContentSchema:()=>Us,UnsubscribeRequestParamsSchema:()=>Rs,UnsubscribeRequestSchema:()=>xs,UntitledMultiSelectEnumSchemaSchema:()=>Vo,UntitledSingleSelectEnumSchemaSchema:()=>Do});var Gr=(e)=>To.safeParse(e).success,dg=(e)=>Eo.safeParse(e).success,en=(e)=>Ar.safeParse(e).success,tn=(e)=>qr.safeParse(e).success;var pg=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var Ru=(e)=>$o.safeParse(e).success,hg=(e)=>Io.safeParse(e).success;var hy="Mcp-Param-",Af="x-mcp-header",my=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,fy=new Set(["string","integer","boolean","number"]);function xu(e){let t=[],r=new Map,o=(i,s,a)=>{if(i===null||typeof i!=="object")return;let l=i;if(Af in l){if(!a||s.length===0)return`${zc(s)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let d=l[Af];if(typeof d!=="string"||d.length===0)return`${zc(s)}: x-mcp-header MUST be a non-empty string`;if(!my.test(d))return`${zc(s)}: 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||!fy.has(m))return`${zc(s)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${m??"<none>"}`;let f=d.toLowerCase(),g=r.get(f);if(g!==void 0)return`x-mcp-header '${d}' is not case-insensitively unique (also declared as '${g}')`;r.set(f,d),t.push({path:s,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,[...s,d],a);if(f!==void 0)return f}for(let d of gy){let m=l[d];if(m===void 0)continue;let f=Array.isArray(m)?m:m!==null&&typeof m==="object"&&Sy.has(d)?Object.values(m):[m];for(let g of f){let b=o(g,[...s,`<${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 gy=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],Sy=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function zc(e){return e.length===0?"<root>":e.join(".")}var mg="=?base64?",fg="?=";function _y(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 by(e){if(e.length===0)return!0;if(e.startsWith(mg)&&e.endsWith(fg))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 yy(e){let t=new TextEncoder().encode(e),r="";for(let o of t)r+=String.fromCodePoint(o);return btoa(r)}function Pu(e){return by(e)?`${mg}${yy(e)}${fg}`:e}function vy(e,t){let r=e;for(let o of t){if(r===null||typeof r!=="object")return;r=r[o]}return r}function gg(e,t){let r={};for(let o of e){let n=vy(t,o.path);if(n===void 0||n===null)continue;let i=_y(n);if(i===void 0)continue;r[`${hy}${o.headerName}`]=Pu(i)}return r}var Qo=-32020,tP=[{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:[Qo,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:[Qo],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:[Qo],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."}],rP={[W.ParseError]:400,[W.InvalidRequest]:400,[W.MethodNotFound]:404,[W.UnsupportedProtocolVersion]:400,[W.MissingRequiredClientCapability]:400,[Qo]:400},qf={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function Sg(e,t){let r=Object.hasOwn(qf,e)?qf[e]:void 0;if(r===void 0)return;let o=zy(t)?t[r]:void 0;return{field:r,value:typeof o==="string"?o:void 0}}function zy(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Pc(e,t){return Za(e,t)}function qi(e){return new Set(e.flatMap((t)=>Object.keys(t.shape)))}function hu(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 Mf=!1,mu="draft-2020-12";function wy(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:mu});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(!Mf)Mf=!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=La(e,{target:mu,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 _g(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 _g(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"||_g(o)))}return!1}function Ry(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 uu(e,t){let r=await e["~standard"].validate(t);if(r.issues&&r.issues.length>0)return{success:!1,error:r.issues.map((o)=>Ry(o)).join(", ")};return{success:!0,data:r.value}}function xy(e){let t=La(e,{target:mu,io:"input"});return typeof t.pattern==="string"?t.pattern:void 0}var Py=/\\\.\\d\{(\d+)\}/;function Ty(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((i)=>_o({local:o,offset:n,precision:i}))))}function Ey(e,t){let r;switch(e){case"email":r=[af()];break;case"uri":r=[Fa()];break;case"date":r=[tu()];break;case"date-time":r=Ty(t);break}return new Set(r.map((o)=>xy(o)).filter((o)=>o!==void 0))}function ky(e,t,r){if(r!=="zod")return!0;return Ey(e,t).has(t)}function Li(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function $y(e){try{return wy(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new re(W.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}var Cy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function Tu(e){return Cy.has(e)||e.startsWith("x-")}var Iy=new Set(["$schema",...Object.keys(Jr.shape.requestedSchema.shape)]),jf={string:qi([Hr,Do,Fo,Ho]),number:qi([Vr]),integer:qi([Vr]),boolean:qi([Zo]),array:qi([Vo,Jo])},Oy=new Set(Hr.shape.format.unwrap().options);function Ny(e,t,r,o){if(!Li(e))return e;let n=typeof e.type==="string"&&Object.hasOwn(jf,e.type)?jf[e.type]:void 0;if(n===void 0)return e;let i={};for(let[s,a]of Object.entries(e))if(n.has(s)||Tu(s))i[s]=a;else if(s==="pattern"&&e.type==="string"&&typeof e.format==="string"){if(!Oy.has(e.format))i[s]=a;else if(typeof a!=="string"||!ky(e.format,a,r))o.push(`${t}.${s}`)}else o.push(`${t}.${s}`);return i}function Ay(e,t){let r={},o=[];for(let[n,i]of Object.entries(e))if(n==="properties"&&Li(i))r[n]=Object.fromEntries(Object.entries(i).map(([s,a])=>[s,Ny(a,`properties.${s}`,t,o)]));else if(Iy.has(n))r[n]=i;else if(!Tu(n))o.push(n);if(o.length>0)throw new re(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}function qy(e,t){if(!Li(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!Pc(Bo,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}function fu(e,t,r=""){if(Array.isArray(e)&&Array.isArray(t))return e.flatMap((o,n)=>fu(o,t[n],`${r}[${n}]`));if(!Li(e)||!Li(t))return[];return Object.entries(e).flatMap(([o,n])=>{let i=r?`${r}.${o}`:o;if(!Object.prototype.hasOwnProperty.call(t,o))return Tu(o)?[]:[i];return fu(n,t[o],i)})}function My(e){if(!hu(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=Ay($y(e.requestedSchema),t),o=Pc(Jr.shape.requestedSchema,r);if(!o.success)throw new re(W.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${qy(r,o.error.message)}`);let n=fu(r,o.data);if(n.length>0)throw new re(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);let i=(o.data.required??[]).filter((s)=>!Object.prototype.hasOwnProperty.call(o.data.properties,s));if(i.length>0)throw new re(W.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function jy(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 oP=Object.assign(jy,{elicit(e){try{return{method:"elicitation/create",params:My(e)}}catch(t){throw t instanceof re?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 Ly=!0,Uy=10,Zy=250;function bg(e){return{autoFulfill:e?.autoFulfill??Ly,maxRounds:e?.maxRounds??Uy}}function Dy(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 Fy(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Hy(e,t){return new Promise((r,o)=>{if(t?.aborted){o(t.reason instanceof A?t.reason:new A(N.RequestTimeout,String(t.reason)));return}let n=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(n),o(t?.reason instanceof A?t.reason:new A(N.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",i,{once:!0})})}function Vy(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 Jy(e){let{config:t,method:r,originalParams:o,requestOptions:n,hooks:i,signal:s}=e,a=e.flowStartedAt??Date.now(),l=e.firstPayload,u=0;while(!0){if(u+=1,u>t.maxRounds)throw new A(N.InputRequiredRoundsExceeded,Fy(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=Vy(s);try{let y=await Promise.all(d.map(async([v,L])=>{try{return[v,await i.dispatchInputRequest(v,L,b.signal)]}catch(H){throw b.abort(H),H}}));m=Object.fromEntries(y)}finally{b.dispose()}}else await Hy(Zy,s);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 A(N.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:b});f.maxTotalTimeout=y}let g=await i.retry(Dy(o,m,l.requestState),f);if(pg(g)){l={inputRequests:g.inputRequests??{},...g.requestState!==void 0&&{requestState:g.requestState}};continue}return g}}var By=["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"],Wy={IdJagTokenExchangeResponseSchema:Ii,OAuthClientInformationFullSchema:Xo,OAuthClientInformationSchema:Ni,OAuthClientMetadataSchema:Oi,OAuthClientRegistrationErrorSchema:gc,OAuthErrorResponseSchema:Yo,OAuthMetadataSchema:Br,OAuthProtectedResourceMetadataSchema:Wo,OAuthTokenRevocationRequestSchema:Sc,OAuthTokensSchema:Go,OpenIdProviderDiscoveryMetadataSchema:Ko,OpenIdProviderMetadataSchema:Ci},yg={},vg={};function zg(e,t){let r=e.slice(0,-6);yg[r]=t,vg[r]=(o)=>t.safeParse(o).success}for(let e of By)zg(e,py[e]);for(let[e,t]of Object.entries(Wy))zg(e,t);var Ky=Object.freeze(yg),wg=Object.freeze(vg);function Gy(e){switch(e){case"initialize":case"notifications/initialized":return Ht(void 0);case"server/discover":return Ht(xc);default:return}}var Tc=60000,Yy=[Mt,vo,Or,zo],Xy=["inputResponses","requestState"];function Lf(e,t){let r=e.params;if(!ji(r))return{message:e,lifted:{}};let o=r._meta,n=ji(o)?Yy.filter((l)=>(l in o)):[],i=t==="request"?Xy.filter((l)=>(l in r)):[];if(n.length===0&&i.length===0)return{message:e,lifted:{}};let s={},a={...r};if(n.length>0&&ji(o)){let l={},u={...o};for(let d of n)l[d]=o[d],delete u[d];if(s.envelope=l,Object.keys(u).length>0)a._meta=u;else delete a._meta}for(let l of i){if(l==="inputResponses")s.inputResponses=a[l];if(l==="requestState")s.requestState=a[l];delete a[l]}return{message:{...e,params:a},lifted:s}}function Uf(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 Eu(e){return()=>e}var Qy=Eu(void 0),ev,Ec=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{ev=(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 A(N.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 A(N.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,i)=>{if(o?.(n,i),en(n)||tn(n))this._onresponse(n);else if(Gr(n))this._onrequest(n,i);else if(dg(n))this._onnotification(n,i);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 A(N.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}=Lf(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let s=Of(t.classification);if(s!==o.era){this._onerror(Error(`Era mismatch on inbound notification '${r.method}': classified as ${s} but this instance serves ${o.era}`));return}}if(lu(r.method)&&!o.hasNotificationMethod(r.method))return;let n=this._notificationHandlers.get(r.method),i=this.fallbackNotificationHandler;if(n===void 0&&i===void 0)return;Promise.resolve().then(()=>n===void 0?i(r):n(r,o)).catch((s)=>this._onerror(Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){let{message:r,lifted:o}=Lf(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 i=this._transport,s=(y,v,L)=>{let H={jsonrpc:"2.0",id:r.id,error:{code:y,message:v,...L!==void 0&&{data:L}}};i?.send(H).catch((x)=>this._onerror(Error(`Failed to send an error response: ${x}`)))};if(t?.classification!==void 0){let y=Of(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;s(W.UnsupportedProtocolVersion,`Unsupported protocol version: ${v}`,{supported:this._supportedProtocolVersions,requested:v});return}}if(cu(r.method)&&!n.hasRequestMethod(r.method)&&!(Nf(r.method)&&this._customSchemaRequestMethods.has(r.method))){s(W.MethodNotFound,"Method not found");return}let a=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(a===void 0){s(W.MethodNotFound,"Method not found");return}let l=n.checkInboundEnvelope(o);if(l!==void 0){s(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:tv(o.inputResponses),g={sessionId:i?.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?Qy:Eu(o.requestState),signal:m.signal,send:(y,v,L)=>{let H=this._resolveOutboundCodec(y.method);if(this._assertOutboundRequestInEra(H,y.method),hu(v))return d(y,v,L);let x=Uf(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(g,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}`)),s(W.InternalError,"Internal error");return}let L={result:v,jsonrpc:"2.0",id:r.id};await i?.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 i?.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 i=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(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),en(e))r(e);else r(re.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(hu(t)){if(!Nf(e.method))this._assertOutboundRequestInEra(o,e.method);return this._requestWithSchemaViaCodec(o,e,t,r)}this._assertOutboundRequestInEra(o,e.method);let n=Uf(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 Ht(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Gy(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(cu(t)&&!e.hasRequestMethod(t))throw new A(N.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:i,onresumptiontoken:s,headers:a}=o??{},l=Date.now(),u,d;return new Promise((m,f)=>{let g=(w)=>{f(w)};if(!this._transport){g(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(w){g(w);return}if(o?.signal?.aborted){let w=o.signal.reason;throw w instanceof A?w:new A(N.RequestTimeout,String(w))}let b=e.era===xc&&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),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:i,onresumptiontoken:s}).catch((D)=>this._onerror(Error(`Failed to send cancellation: ${D}`)))}else b.abort();f(w instanceof A?w:new A(N.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(sv(D));let Y={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:l,retry:(ue,$e)=>this._requestWithSchemaViaCodec(e,ue===void 0?{method:t.method}:{method:t.method,params:ue},r,$e)};return m(this._resolveNonCompleteResult(D,Y))}let X=D.result;uu(r,X).then((Y)=>{if(Y.success)m(Y.data);else f(new A(N.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??Tc,R=()=>x(new A(N.RequestTimeout,"Request timed out",{timeout:Z}));this._setupTimeout(y,Z,o?.maxTotalTimeout,R,o?.resetTimeoutOnProgress??!1),this._transport.send(L,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s,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 A(N.NotConnected,"Not connected");if(lu(t.method)&&!e.hasNotificationMethod(t.method))throw new A(N.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(!cu(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=(n,i)=>{let s=this._negotiatedWireCodec(),a=s.validateRequest(e,n);if(!a.ok&&a.reason==="not-in-era")a=s.validateInputRequest(e,n);if(!a.ok){if(a.reason==="not-in-era")throw new re(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(a.message)}return Promise.resolve(t(a.value,i))}}else if(r)o=async(n,i)=>{let s=await uu(t.params,{...n.params});if(!s.success)throw new re(W.InvalidParams,`Invalid params for ${e}: ${s.error}`);return r(s.data,i)};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(!lu(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 i=n.validateNotification(e,o);if(!i.ok){if(i.reason==="not-in-era")throw new re(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(i.message)}return Promise.resolve(t(i.value))});return}if(!r)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async(o)=>{let n=await uu(t.params,{...o.params});if(!n.success)throw new re(W.InvalidParams,`Invalid params for notification ${e}: ${n.error}`);await r(n.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function ji(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Rg(e,t){let r={...e};for(let o in t){let n=o,i=t[n];if(i===void 0)continue;let s=r[n];r[n]=ji(s)&&ji(i)?{...s,...i}:i}return r}function wc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function tv(e){let t={},r=[];if(!wc(e))return{accepted:t,droppedKeys:r};for(let[o,n]of Object.entries(e)){if(!wc(n)||"method"in n||"result"in n){r.push(o);continue}t[o]=n}return{accepted:t,droppedKeys:r}}function Zf(e){throw new A(N.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 rv(e,t,r,o,n){return{sessionId:n,mcpReq:{id:e,method:t,_meta:r?._meta,requestState:Eu(void 0),signal:o,send:()=>Zf("send"),notify:()=>Zf("notify")}}}async function ov(e,t,r,o,n){if(!wc(o)||typeof o.method!=="string")throw new A(N.InvalidResult,`Invalid input request '${r}': each inputRequests entry must be an embedded request object with a method`,{key:r});let i=o.method;if(!t.hasInputRequestMethod(i))throw new A(N.InvalidResult,`Invalid input request '${r}': '${i}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:r,method:i});let s=e.getRequestHandler(i);if(s===void 0)throw new A(N.CapabilityNotSupported,`Cannot fulfil input request '${r}': no handler is registered for '${i}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:r,method:i});let a=wc(o.params)?o.params:void 0;return await s({jsonrpc:"2.0",id:r,method:i,...a!==void 0&&{params:a}},e.buildContext(rv(r,i,a,n,e.sessionId)))}function nv(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 xg(e,t,r,o){let{codec:n,request:i,options:s,flowStartedAt:a}=o,l={inputRequests:r.inputRequests,...r.requestState!==void 0&&{requestState:r.requestState}},u={dispatchInputRequest:(d,m,f)=>ov(e,n,d,m,f),retry:(d,m)=>o.retry(d,nv(s,m))};return Jy({config:t,method:i.method,originalParams:i.params,firstPayload:l,flowStartedAt:a,signal:s?.signal,requestOptions:{...s?.timeout!==void 0&&{timeout:s.timeout},...s?.maxTotalTimeout!==void 0&&{maxTotalTimeout:s.maxTotalTimeout},...s?.onprogress!==void 0&&{onprogress:s.onprogress}},hooks:u})}function sv(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 s of e.seen.entries()){let a=s[1];if(t===s[0]){i(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1){if(e.reused==="ref"){i(s);continue}}}}function Xn(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 g=e.seen.get(m),b=g.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&&g.def)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(v in g.def&&JSON.stringify(u[v])===JSON.stringify(g.def[v]))delete u[v]}}let f=a._zod.parent;if(f&&f!==m){o(f);let g=e.seen.get(f);if(g?.schema.$ref){if(u.$ref=g.schema.$ref,g.def)for(let b in u){if(b==="$ref"||b==="allOf")continue;if(b in g.def&&JSON.stringify(u[b])===JSON.stringify(g.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 i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&n.id===i)delete n.id;let s=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;s[l.defId]=l.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")n.$defs=s;else n.definitions=s;try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Kn(t,"input",e.processors),output:Kn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function qe(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 qe(o.element,r);if(o.type==="set")return qe(o.valueType,r);if(o.type==="lazy")return qe(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 qe(o.innerType,r);if(o.type==="intersection")return qe(o.left,r)||qe(o.right,r);if(o.type==="record"||o.type==="map")return qe(o.keyType,r)||qe(o.valueType,r);if(o.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return qe(o.in,r)||qe(o.out,r)}if(o.type==="object"){for(let n in o.shape)if(qe(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(qe(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(qe(n,r))return!0;if(o.rest&&qe(o.rest,r))return!0;return!1}return!1}var zm=(e,t={})=>(r)=>{let o=Gn({...r,processors:t});return se(e,o),Yn(o,e),Xn(o,e)},Kn=(e,t,r={})=>(o)=>{let{libraryOptions:n,target:i}=o??{},s=Gn({...n??{},target:i,io:t,processors:r});return se(e,s),Yn(s,e),Xn(s,e)};var w_={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:i,maximum:s,format:a,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof i==="number")n.minLength=i;if(typeof s==="number")n.maxLength=s;if(a){if(n.format=w_[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}))]}},Cl=(e,t,r,o)=>{let n=r,{minimum:i,maximum:s,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>=(i??Number.NEGATIVE_INFINITY),f=typeof u==="number"&&u<=(s??Number.POSITIVE_INFINITY),g=t.target==="draft-04"||t.target==="openapi-3.0";if(m)if(g)n.minimum=d,n.exclusiveMinimum=!0;else n.exclusiveMinimum=d;else if(typeof i==="number")n.minimum=i;if(f)if(g)n.maximum=u,n.exclusiveMaximum=!0;else n.exclusiveMaximum=u;else if(typeof s==="number")n.maximum=s;if(typeof l==="number")n.multipleOf=l},Il=(e,t,r,o)=>{r.type="boolean"},Rm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},xm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},Ol=(e,t,r,o)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},Nl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},Pm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},Al=(e,t,r,o)=>{r.not={}},ql=(e,t,r,o)=>{},Ml=(e,t,r,o)=>{},Tm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},jl=(e,t,r,o)=>{let n=e._zod.def,i=wa(n.entries);if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";r.enum=i},Ll=(e,t,r,o)=>{let n=e._zod.def,i=[];for(let s of n.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else i.push(Number(s));else i.push(s);if(i.length===0);else if(i.length===1){let s=i[0];if(r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[s];else r.const=s}else{if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";if(i.every((s)=>typeof s==="boolean"))r.type="boolean";if(i.every((s)=>s===null))r.type="null";r.enum=i}},Em=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},km=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},$m=(e,t,r,o)=>{let n=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:l}=e._zod.bag;if(s!==void 0)i.minLength=s;if(a!==void 0)i.maxLength=a;if(l)if(l.length===1)i.contentMediaType=l[0],Object.assign(n,i);else Object.assign(n,i),n.anyOf=l.map((u)=>({contentMediaType:u}));else Object.assign(n,i)},Cm=(e,t,r,o)=>{r.type="boolean"},Ul=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},Im=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},Zl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},Om=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},Nm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},Dl=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")n.minItems=s;if(typeof a==="number")n.maxItems=a;n.type="array",n.items=se(i.element,t,{...o,path:[...o.path,"items"]})},Fl=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object",n.properties={};let s=i.shape;for(let u in s)n.properties[u]=se(s[u],t,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(s)),l=new Set([...a].filter((u)=>{let d=i.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(i.catchall?._zod.def.type==="never")n.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")n.additionalProperties=!1}else if(i.catchall)n.additionalProperties=se(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Hl=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,s=n.options.map((a,l)=>se(a,t,{...o,path:[...o.path,i?"oneOf":"anyOf",l]}));if(i)r.oneOf=s;else r.anyOf=s},Vl=(e,t,r,o)=>{let n=e._zod.def,i=se(n.left,t,{...o,path:[...o.path,"allOf",0]}),s=se(n.right,t,{...o,path:[...o.path,"allOf",1]}),a=(u)=>("allOf"in u)&&Object.keys(u).length===1,l=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=l},Am=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",l=i.items.map((f,g)=>se(f,t,{...o,path:[...o.path,s,g]})),u=i.rest?se(i.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[i.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},Jl=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let s=i.keyType,l=s._zod.bag?.patterns;if(i.mode==="loose"&&l&&l.size>0){let d=se(i.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=se(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});n.additionalProperties=se(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=s._zod.values;if(u){let d=[...u].filter((m)=>typeof m==="string"||typeof m==="number");if(d.length>0)n.required=d}},Bl=(e,t,r,o)=>{let n=e._zod.def,i=se(n.innerType,t,o),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=n.innerType,r.nullable=!0;else r.anyOf=[i,{type:"null"}]},Wl=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Kl=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},Gl=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(n.defaultValue))},Yl=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},Xl=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?n.out:n.in:n.out;se(s,t,o);let a=t.seen.get(e);a.ref=s},Ql=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},qm=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},ja=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},eu=(e,t,r,o)=>{let n=e._zod.innerType;se(n,t,o);let i=t.seen.get(e);i.ref=n},wm={string:$l,number:Cl,boolean:Il,bigint:Rm,symbol:xm,null:Ol,undefined:Nl,void:Pm,never:Al,any:ql,unknown:Ml,date:Tm,enum:jl,literal:Ll,nan:Em,template_literal:km,file:$m,success:Cm,custom:Ul,function:Im,transform:Zl,map:Om,set:Nm,array:Dl,object:Fl,union:Hl,intersection:Vl,tuple:Am,record:Jl,nullable:Bl,nonoptional:Wl,default:Kl,prefault:Gl,catch:Yl,pipe:Xl,readonly:Ql,promise:qm,optional:ja,lazy:eu};function La(e,t){if("_idmap"in e){let o=e,n=Gn({...t,processors:wm}),i={};for(let l of o._idmap.entries()){let[u,d]=l;se(d,n)}let s={},a={registry:o,uri:t?.uri,defs:i};n.external=a;for(let l of o._idmap.entries()){let[u,d]=l;Yn(n,d),s[u]=Xn(n,d)}if(Object.keys(i).length>0){let l=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[l]:i}}return{schemas:s}}let r=Gn({...t,processors:wm});return se(e,r),Yn(r,e),Xn(r,e)}var C_=_("ZodISODateTime",(e,t)=>{Yp.init(e,t),le.init(e,t)});function _o(e){return im(C_,e)}var I_=_("ZodISODate",(e,t)=>{Xp.init(e,t),le.init(e,t)});function tu(e){return am(I_,e)}var O_=_("ZodISOTime",(e,t)=>{Qp.init(e,t),le.init(e,t)});function Mm(e){return cm(O_,e)}var N_=_("ZodISODuration",(e,t)=>{eh.init(e,t),le.init(e,t)});function jm(e){return lm(N_,e)}var A_=(e,t)=>{Ta.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>ol(e,r)},flatten:{value:(r)=>rl(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Zn,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Zn,2)}},isEmpty:{get(){return e.issues.length===0}}})};var We=_("ZodError",A_,{Parent:Error});var Um=Ea(We),Zm=ka(We),Za=Fn(We),Dm=Hn(We),Fm=Nd(We),Hm=Ad(We),Vm=qd(We),Jm=Md(We),Bm=jd(We),Wm=Ld(We),Km=Ud(We),Gm=Zd(We);var Ym=new WeakMap;function Qn(e,t,r){let o=Object.getPrototypeOf(e),n=Ym.get(o);if(!n)n=new Set,Ym.set(o,n);if(n.has(t))return;n.add(t);for(let i in r){let s=r[i];Object.defineProperty(o,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var ie=_("ZodType",(e,t)=>(ne.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Kn(e,"input"),output:Kn(e,"output")}}),e.toJSONSchema=zm(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,o)=>Um(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Za(e,r,o),e.parseAsync=async(r,o)=>Zm(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>Dm(e,r,o),e.spa=e.safeParseAsync,e.encode=(r,o)=>Fm(e,r,o),e.decode=(r,o)=>Hm(e,r,o),e.encodeAsync=async(r,o)=>Vm(e,r,o),e.decodeAsync=async(r,o)=>Jm(e,r,o),e.safeEncode=(r,o)=>Bm(e,r,o),e.safeDecode=(r,o)=>Wm(e,r,o),e.safeEncodeAsync=async(r,o)=>Km(e,r,o),e.safeDecodeAsync=async(r,o)=>Gm(e,r,o),Qn(e,"ZodType",{check(...r){let o=this.def;return this.clone(tr(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 at(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(Rb(r,o))},superRefine(r,o){return this.check(xb(r,o))},overwrite(r){return this.check(sr(r))},optional(){return U(this)},exactOptional(){return ub(this)},nullable(){return tf(this)},nullish(){return U(tf(this))},nonoptional(r){return gb(this,r)},array(){return S(this)},or(r){return T([this,r])},and(r){return At(this,r)},transform(r){return rf(this,pf(r))},default(r){return hb(this,r)},prefault(r){return fb(this,r)},catch(r){return _b(this,r)},pipe(r){return rf(this,r)},readonly(){return vb(this)},describe(r){let o=this.clone();return nr.add(o,{description:r}),o},meta(...r){if(r.length===0)return nr.get(this);let o=this.clone();return nr.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 nr.get(e)?.description},configurable:!0}),e)),of=_("_ZodString",(e,t)=>{Ia.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,i)=>$l(e,o,n,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Qn(e,"_ZodString",{regex(...o){return this.check(bl(...o))},includes(...o){return this.check(zl(...o))},startsWith(...o){return this.check(wl(...o))},endsWith(...o){return this.check(Rl(...o))},min(...o){return this.check(go(...o))},max(...o){return this.check(qa(...o))},length(...o){return this.check(Ma(...o))},nonempty(...o){return this.check(go(1,...o))},lowercase(o){return this.check(yl(o))},uppercase(o){return this.check(vl(o))},trim(){return this.check(Pl())},normalize(...o){return this.check(xl(...o))},toLowerCase(){return this.check(Tl())},toUpperCase(){return this.check(El())},slugify(){return this.check(kl())}})}),nf=_("ZodString",(e,t)=>{Ia.init(e,t),of.init(e,t),e.email=(r)=>e.check(gl(sf,r)),e.url=(r)=>e.check(_l(cf,r)),e.jwt=(r)=>e.check(sm(Y_,r)),e.emoji=(r)=>e.check(Vh(M_,r)),e.guid=(r)=>e.check(Sl(Xm,r)),e.uuid=(r)=>e.check(Zh(Da,r)),e.uuidv4=(r)=>e.check(Dh(Da,r)),e.uuidv6=(r)=>e.check(Fh(Da,r)),e.uuidv7=(r)=>e.check(Hh(Da,r)),e.nanoid=(r)=>e.check(Jh(j_,r)),e.guid=(r)=>e.check(Sl(Xm,r)),e.cuid=(r)=>e.check(Bh(L_,r)),e.cuid2=(r)=>e.check(Wh(U_,r)),e.ulid=(r)=>e.check(Kh(Z_,r)),e.base64=(r)=>e.check(rm(W_,r)),e.base64url=(r)=>e.check(om(K_,r)),e.xid=(r)=>e.check(Gh(D_,r)),e.ksuid=(r)=>e.check(Yh(F_,r)),e.ipv4=(r)=>e.check(Xh(H_,r)),e.ipv6=(r)=>e.check(Qh(V_,r)),e.cidrv4=(r)=>e.check(em(J_,r)),e.cidrv6=(r)=>e.check(tm(B_,r)),e.e164=(r)=>e.check(nm(G_,r)),e.datetime=(r)=>e.check(_o(r)),e.date=(r)=>e.check(tu(r)),e.time=(r)=>e.check(Mm(r)),e.duration=(r)=>e.check(jm(r))});function c(e){return Uh(nf,e)}var le=_("ZodStringFormat",(e,t)=>{ce.init(e,t),of.init(e,t)}),sf=_("ZodEmail",(e,t)=>{Dp.init(e,t),le.init(e,t)});function af(e){return gl(sf,e)}var Xm=_("ZodGUID",(e,t)=>{Up.init(e,t),le.init(e,t)});var Da=_("ZodUUID",(e,t)=>{Zp.init(e,t),le.init(e,t)});var cf=_("ZodURL",(e,t)=>{Fp.init(e,t),le.init(e,t)});function Fa(e){return _l(cf,e)}var M_=_("ZodEmoji",(e,t)=>{Hp.init(e,t),le.init(e,t)});var j_=_("ZodNanoID",(e,t)=>{Vp.init(e,t),le.init(e,t)});var L_=_("ZodCUID",(e,t)=>{Jp.init(e,t),le.init(e,t)});var U_=_("ZodCUID2",(e,t)=>{Bp.init(e,t),le.init(e,t)});var Z_=_("ZodULID",(e,t)=>{Wp.init(e,t),le.init(e,t)});var D_=_("ZodXID",(e,t)=>{Kp.init(e,t),le.init(e,t)});var F_=_("ZodKSUID",(e,t)=>{Gp.init(e,t),le.init(e,t)});var H_=_("ZodIPv4",(e,t)=>{th.init(e,t),le.init(e,t)});var V_=_("ZodIPv6",(e,t)=>{rh.init(e,t),le.init(e,t)});var J_=_("ZodCIDRv4",(e,t)=>{oh.init(e,t),le.init(e,t)});var B_=_("ZodCIDRv6",(e,t)=>{nh.init(e,t),le.init(e,t)});var W_=_("ZodBase64",(e,t)=>{ih.init(e,t),le.init(e,t)});var K_=_("ZodBase64URL",(e,t)=>{ah.init(e,t),le.init(e,t)});var G_=_("ZodE164",(e,t)=>{ch.init(e,t),le.init(e,t)});var Y_=_("ZodJWT",(e,t)=>{lh.init(e,t),le.init(e,t)});var Ha=_("ZodNumber",(e,t)=>{dl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Cl(e,o,n,i),Qn(e,"ZodNumber",{gt(o,n){return this.check(Na(o,n))},gte(o,n){return this.check(Wn(o,n))},min(o,n){return this.check(Wn(o,n))},lt(o,n){return this.check(Oa(o,n))},lte(o,n){return this.check(Bn(o,n))},max(o,n){return this.check(Bn(o,n))},int(o){return this.check(Qm(o))},safe(o){return this.check(Qm(o))},positive(o){return this.check(Na(0,o))},nonnegative(o){return this.check(Wn(0,o))},negative(o){return this.check(Oa(0,o))},nonpositive(o){return this.check(Bn(0,o))},multipleOf(o,n){return this.check(Aa(o,n))},step(o,n){return this.check(Aa(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 um(Ha,e)}var X_=_("ZodNumberFormat",(e,t)=>{uh.init(e,t),Ha.init(e,t)});function Qm(e){return pm(X_,e)}var lf=_("ZodBoolean",(e,t)=>{dh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n)});function E(e){return hm(lf,e)}var Q_=_("ZodUndefined",(e,t)=>{ph.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nl(e,r,o,n)});function ou(e){return mm(Q_,e)}var eb=_("ZodNull",(e,t)=>{hh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n)});function Cr(e){return fm(eb,e)}var tb=_("ZodAny",(e,t)=>{mh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n)});function Va(){return gm(tb)}var rb=_("ZodUnknown",(e,t)=>{fh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n)});function M(){return Sm(rb)}var ob=_("ZodNever",(e,t)=>{gh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n)});function nu(e){return _m(ob,e)}var nb=_("ZodArray",(e,t)=>{Sh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dl(e,r,o,n),e.element=t.element,Qn(e,"ZodArray",{min(r,o){return this.check(go(r,o))},nonempty(r){return this.check(go(1,r))},max(r,o){return this.check(qa(r,o))},length(r,o){return this.check(Ma(r,o))},unwrap(){return this.element}})});function S(e,t){return bm(nb,e,t)}var uf=_("ZodObject",(e,t)=>{yh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n),ee(e,"shape",()=>t.shape),Qn(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:M()})},loose(){return this.clone({...this._zod.def,catchall:M()})},strict(){return this.clone({...this._zod.def,catchall:nu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return l_(this,r)},safeExtend(r){return u_(this,r)},merge(r){return d_(this,r)},pick(r){return a_(this,r)},omit(r){return c_(this,r)},partial(...r){return p_(hf,this,r[0])},required(...r){return h_(mf,this,r[0])}})});function p(e,t){let r={type:"object",shape:e??{},...j(t)};return new uf(r)}function F(e,t){return new uf({type:"object",shape:e,catchall:M(),...j(t)})}var df=_("ZodUnion",(e,t)=>{pl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hl(e,r,o,n),e.options=t.options});function T(e,t){return new df({type:"union",options:e,...j(t)})}var sb=_("ZodDiscriminatedUnion",(e,t)=>{df.init(e,t),vh.init(e,t)});function bo(e,t,r){return new sb({type:"union",options:t,discriminator:e,...j(r)})}var ib=_("ZodIntersection",(e,t)=>{zh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vl(e,r,o,n)});function At(e,t){return new ib({type:"intersection",left:e,right:t})}var ef=_("ZodRecord",(e,t)=>{wh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jl(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function P(e,t,r){if(!t||!t._zod)return new ef({type:"record",keyType:c(),valueType:e,...j(t)});return new ef({type:"record",keyType:e,valueType:t,...j(r)})}var ru=_("ZodEnum",(e,t)=>{Rh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,i)=>jl(e,o,n,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new ru({...t,checks:[],...j(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let s of o)if(r.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new ru({...t,checks:[],...j(n),entries:i})}});function K(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new ru({type:"enum",entries:r,...j(t)})}var ab=_("ZodLiteral",(e,t)=>{xh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(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 ab({type:"literal",values:Array.isArray(e)?e:[e],...j(t)})}var cb=_("ZodTransform",(e,t)=>{Ph.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Un(e.constructor.name);r.addIssue=(i)=>{if(typeof i==="string")r.issues.push($r(i,r.value,t));else{let s=i;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),r.issues.push($r(s))}};let n=t.transform(r.value,r);if(n instanceof Promise)return n.then((i)=>(r.value=i,r.fallback=!0,r));return r.value=n,r.fallback=!0,r}});function pf(e){return new cb({type:"transform",transform:e})}var hf=_("ZodOptional",(e,t)=>{hl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ja(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function U(e){return new hf({type:"optional",innerType:e})}var lb=_("ZodExactOptional",(e,t)=>{Th.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ja(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ub(e){return new lb({type:"optional",innerType:e})}var db=_("ZodNullable",(e,t)=>{Eh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Bl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function tf(e){return new db({type:"nullable",innerType:e})}var pb=_("ZodDefault",(e,t)=>{kh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function hb(e,t){return new pb({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Qc(t)}})}var mb=_("ZodPrefault",(e,t)=>{$h.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function fb(e,t){return new mb({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Qc(t)}})}var mf=_("ZodNonOptional",(e,t)=>{Ch.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function gb(e,t){return new mf({type:"nonoptional",innerType:e,...j(t)})}var Sb=_("ZodCatch",(e,t)=>{Ih.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _b(e,t){return new Sb({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var ff=_("ZodPipe",(e,t)=>{ml.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xl(e,r,o,n),e.in=t.in,e.out=t.out});function rf(e,t){return new ff({type:"pipe",in:e,out:t})}var bb=_("ZodPreprocess",(e,t)=>{ff.init(e,t),Oh.init(e,t)}),yb=_("ZodReadonly",(e,t)=>{Nh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ql(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function vb(e){return new yb({type:"readonly",innerType:e})}var zb=_("ZodLazy",(e,t)=>{Ah.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>eu(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function es(e){return new zb({type:"lazy",getter:e})}var wb=_("ZodCustom",(e,t)=>{qh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n)});function Rb(e,t={}){return ym(wb,e,t)}function xb(e,t){return vm(e,t)}function Ir(e,t){return new bb({type:"pipe",in:pf(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 gf;(function(e){})(gf||(gf={}));function Pb(e){return dm(Ha,e)}Ue(fl());var yo="2025-11-25";var Ja=[yo,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ba="io.modelcontextprotocol/related-task",Mt="io.modelcontextprotocol/protocolVersion",vo="io.modelcontextprotocol/clientInfo",jt="io.modelcontextprotocol/serverInfo",Or="io.modelcontextprotocol/clientCapabilities",ts="io.modelcontextprotocol/subscriptionId",zo="io.modelcontextprotocol/logLevel";var Nr="2.0";var qt=es(()=>T([c(),z(),E(),Cr(),P(c(),qt),S(qt)])),de=P(c(),qt),Wa=S(qt),wo=T([c(),z().int()]),Ro=c(),rs=p({ttl:z().optional()}),os=p({taskId:c()}),xo=F({progressToken:wo.optional(),[Ba]:os.optional()}),ze=p({_meta:xo.optional()}),ar=ze.extend({task:rs.optional()}),pe=p({method:c(),params:ze.loose().optional()}),ke=p({_meta:xo.optional()}),xe=p({method:c(),params:ke.loose().optional()}),Po=F({get[jt](){return Rt.optional().catch(void 0)}}),he=F({_meta:Po.optional()}),lt=T([c(),z().int()]),To=p({jsonrpc:h(Nr),id:lt,...pe.shape}).strict(),Eo=p({jsonrpc:h(Nr),...xe.shape}).strict(),Ar=p({jsonrpc:h(Nr),id:lt,result:he}).strict(),qr=p({jsonrpc:h(Nr),id:lt.optional(),error:p({code:z().int(),message:c(),data:M().optional()})}).strict(),ut=T([To,Eo,Ar,qr]),Ka=T([Ar,qr]),cr=he.strict(),ns=ke.extend({requestId:lt.optional(),reason:c().optional()}),ko=xe.extend({method:h("notifications/cancelled"),params:ns}),ss=p({src:c(),mimeType:c().optional(),sizes:S(c()).optional(),theme:K(["light","dark"]).optional()}),Lt=p({icons:S(ss).optional()}),wt=p({name:c(),title:c().optional()}),Rt=wt.extend({...wt.shape,...Lt.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),Eb=At(p({applyDefaults:E().optional()}),de),kb=Ir((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)&&Object.keys(e).length===0)return{form:{}};return e},At(p({form:Eb.optional(),url:de.optional()}),de.optional())),Ga=F({list:de.optional(),cancel:de.optional(),requests:F({sampling:F({createMessage:de.optional()}).optional(),elicitation:F({create:de.optional()}).optional()}).optional()}),Ya=F({list:de.optional(),cancel:de.optional(),requests:F({tools:F({call:de.optional()}).optional()}).optional()}),is=p({experimental:P(c(),de).optional(),sampling:p({context:de.optional(),tools:de.optional()}).optional(),elicitation:kb.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:Ga.optional(),extensions:P(c(),de).optional()}),as=ze.extend({protocolVersion:c(),capabilities:is,clientInfo:Rt}),$o=pe.extend({method:h("initialize"),params:as}),Co=p({experimental:P(c(),de).optional(),logging:de.optional(),completions:de.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:Ya.optional(),extensions:P(c(),de).optional()}),cs=he.extend({protocolVersion:c(),capabilities:Co,serverInfo:Rt,instructions:c().optional()}),Io=xe.extend({method:h("notifications/initialized"),params:ke.optional()}),ls=pe.extend({method:h("server/discover"),params:ze.optional()}),lr=he.extend({supportedVersions:S(c()),capabilities:Co,instructions:c().optional()}),Oo=pe.extend({method:h("ping"),params:ze.optional()}),us=p({progress:z(),total:U(z()),message:U(c())}),ds=p({...ke.shape,...us.shape,progressToken:wo}),No=xe.extend({method:h("notifications/progress"),params:ds}),ps=ze.extend({cursor:Ro.optional()}),Ut=pe.extend({params:ps.optional()}),Zt=he.extend({nextCursor:Ro.optional()}),Ao=p({uri:c(),mimeType:U(c()),_meta:P(c(),M()).optional()}),qo=Ao.extend({text:c()}),iu=c().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mo=Ao.extend({blob:iu}),Dt=K(["user","assistant"]),xt=p({audience:S(Dt).optional(),priority:z().min(0).max(1).optional(),lastModified:_o({offset:!0}).optional()}),jo=p({...wt.shape,...Lt.shape,uri:c(),description:U(c()),mimeType:U(c()),size:U(z()),annotations:xt.optional(),_meta:U(F({}))}),hs=p({...wt.shape,...Lt.shape,uriTemplate:c(),description:U(c()),mimeType:U(c()),annotations:xt.optional(),_meta:U(F({}))}),ms=Ut.extend({method:h("resources/list")}),fs=Zt.extend({resources:S(jo)}),gs=Ut.extend({method:h("resources/templates/list")}),Ss=Zt.extend({resourceTemplates:S(hs)}),Mr=ze.extend({uri:c()}),_s=Mr,bs=pe.extend({method:h("resources/read"),params:_s}),ys=he.extend({contents:S(T([qo,Mo]))}),vs=xe.extend({method:h("notifications/resources/list_changed"),params:ke.optional()}),zs=Mr,ws=pe.extend({method:h("resources/subscribe"),params:zs}),Rs=Mr,xs=pe.extend({method:h("resources/unsubscribe"),params:Rs}),Lo=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:S(c()).optional()}),Ps=ze.extend({notifications:Lo}),Ts=pe.extend({method:h("subscriptions/listen"),params:Ps}),Es=ke.extend({notifications:Lo}),ks=xe.extend({method:h("notifications/subscriptions/acknowledged"),params:Es}),$s=Po.extend({[ts]:lt}),Cs=he.extend({_meta:$s}),Is=ke.extend({uri:c()}),Os=xe.extend({method:h("notifications/resources/updated"),params:Is}),Ns=p({name:c(),description:U(c()),required:U(E())}),As=p({...wt.shape,...Lt.shape,description:U(c()),arguments:U(S(Ns)),_meta:U(F({}))}),qs=Ut.extend({method:h("prompts/list")}),Ms=Zt.extend({prompts:S(As)}),js=ze.extend({name:c(),arguments:P(c(),c()).optional()}),Ls=pe.extend({method:h("prompts/get"),params:js}),jr=p({type:h("text"),text:c(),annotations:xt.optional(),_meta:P(c(),M()).optional()}),Lr=p({type:h("image"),data:iu,mimeType:c(),annotations:xt.optional(),_meta:P(c(),M()).optional()}),Ur=p({type:h("audio"),data:iu,mimeType:c(),annotations:xt.optional(),_meta:P(c(),M()).optional()}),Us=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),M()),_meta:P(c(),M()).optional()}),Zr=p({type:h("resource"),resource:T([qo,Mo]),annotations:xt.optional(),_meta:P(c(),M()).optional()}),Dr=jo.extend({type:h("resource_link")}),Pt=T([jr,Lr,Ur,Dr,Zr]),Zs=p({role:Dt,content:Pt}),Ds=he.extend({description:c().optional(),messages:S(Zs)}),Fs=xe.extend({method:h("notifications/prompts/list_changed"),params:ke.optional()}),Hs=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Vs=p({taskSupport:K(["required","optional","forbidden"]).optional()}),ur=p({...wt.shape,...Lt.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),qt).optional(),required:S(c()).optional()}).catchall(M()),outputSchema:F({$schema:c().optional()}).optional(),annotations:Hs.optional(),execution:Vs.optional(),_meta:P(c(),M()).optional()}),Js=Ut.extend({method:h("tools/list")}),Bs=Zt.extend({tools:S(ur)}),dr=he.extend({content:S(Pt).default([]),structuredContent:M().optional(),isError:E().optional()}),Xa=dr.or(he.extend({toolResult:M()})),Ws=ar.extend({name:c(),arguments:P(c(),M()).optional()}),Ks=pe.extend({method:h("tools/call"),params:Ws}),Gs=xe.extend({method:h("notifications/tools/list_changed"),params:ke.optional()}),Ys=p({autoRefresh:E().default(!0),debounceMs:z().int().nonnegative().default(300)}),Uo=K(["debug","info","notice","warning","error","critical","alert","emergency"]),Xs=ze.extend({level:Uo}),Qs=pe.extend({method:h("logging/setLevel"),params:Xs}),ei=ke.extend({level:Uo,logger:c().optional(),data:M()}),Fr=xe.extend({method:h("notifications/message"),params:ei}),ti=p({name:c().optional()}),ri=p({hints:S(ti).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),oi=p({mode:K(["auto","required","none"]).optional()}),ni=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:S(Pt),structuredContent:M().optional(),isError:E().optional(),_meta:P(c(),M()).optional()}),si=bo("type",[jr,Lr,Ur]),ir=bo("type",[jr,Lr,Ur,Us,ni]),ii=p({role:Dt,content:T([ir,S(ir)]),_meta:P(c(),M()).optional()}),ai=ar.extend({messages:S(ii),modelPreferences:ri.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:S(c()).optional(),metadata:de.optional(),tools:S(ur).optional(),toolChoice:oi.optional()}),ci=pe.extend({method:h("sampling/createMessage"),params:ai}),li=he.extend({model:c(),stopReason:U(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Dt,content:si}),ui=he.extend({model:c(),stopReason:U(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Dt,content:T([ir,S(ir)])}),Zo=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),Hr=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()}),Vr=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),Do=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),default:c().optional()}),Fo=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:S(p({const:c(),title:c()})),default:c().optional()}),Ho=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),enumNames:S(c()).optional(),default:c().optional()}),di=T([Do,Fo]),Vo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:S(c())}),default:S(c()).optional()}),Jo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:S(p({const:c(),title:c()}))}),default:S(c()).optional()}),pi=T([Vo,Jo]),hi=T([Ho,di,pi]),Bo=T([hi,Zo,Hr,Vr]),Jr=ar.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),Bo),required:S(c()).optional()}).catchall(M())}),mi=ar.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),fi=T([Jr,mi]),gi=pe.extend({method:h("elicitation/create"),params:fi}),Si=ke.extend({elicitationId:c()}),_i=xe.extend({method:h("notifications/elicitation/complete"),params:Si}),bi=he.extend({action:K(["accept","decline","cancel"]),content:Ir((e)=>e===null?void 0:e,P(c(),T([c(),z(),E(),S(c())])).optional())}),yi=p({type:h("ref/resource"),uri:c()}),vi=p({type:h("ref/prompt"),name:c()}),zi=ze.extend({ref:T([vi,yi]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),wi=pe.extend({method:h("completion/complete"),params:zi}),Ri=he.extend({completion:F({values:S(c()).max(100),total:U(z().int()),hasMore:U(E())})}),xi=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),M()).optional()}),Pi=pe.extend({method:h("roots/list"),params:ze.optional()}),Ti=he.extend({roots:S(xi)}),Ei=xe.extend({method:h("notifications/roots/list_changed"),params:ke.optional()}),Qa=F({ttl:z().optional(),pollInterval:z().optional()}),ki=K(["working","input_required","completed","failed","cancelled"]),Ft=p({taskId:c(),status:ki,ttl:T([z(),Cr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:U(z()),statusMessage:U(c())}),ec=he.extend({task:Ft}),$i=ke.merge(Ft),tc=xe.extend({method:h("notifications/tasks/status"),params:$i}),rc=pe.extend({method:h("tasks/get"),params:ze.extend({taskId:c()})}),oc=he.merge(Ft),nc=pe.extend({method:h("tasks/result"),params:ze.extend({taskId:c()})}),sc=he.loose(),ic=Ut.extend({method:h("tasks/list")}),ac=Zt.extend({tasks:S(Ft)}),cc=pe.extend({method:h("tasks/cancel"),params:ze.extend({taskId:c()})}),lc=he.merge(Ft),uc=T([Oo,$o,ls,wi,Qs,Ls,qs,ms,gs,bs,ws,xs,Ts,Ks,Js]),dc=T([ko,No,Io,Ei]),pc=T([cr,li,ui,bi,Ti]),hc=T([Oo,ci,gi,Pi]),mc=T([ko,No,Fr,Os,vs,Gs,Fs,ks,_i]),fc=T([cr,cs,lr,Ri,Ds,Ms,fs,Ss,ys,dr,Bs,Cs]),ve=Fa().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Sf.custom,message:"URL must be parseable",fatal:!0}),Wc}).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"}),Wo=F({resource:c().url(),authorization_servers:S(ve).optional(),jwks_uri:c().url().optional(),scopes_supported:S(c()).optional(),bearer_methods_supported:S(c()).optional(),resource_signing_alg_values_supported:S(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:E().optional(),authorization_details_types_supported:S(c()).optional(),dpop_signing_alg_values_supported:S(c()).optional(),dpop_bound_access_tokens_required:E().optional()}),Br=F({issuer:c(),authorization_endpoint:ve,token_endpoint:ve,registration_endpoint:ve.optional(),scopes_supported:S(c()).optional(),response_types_supported:S(c()),response_modes_supported:S(c()).optional(),grant_types_supported:S(c()).optional(),token_endpoint_auth_methods_supported:S(c()).optional(),token_endpoint_auth_signing_alg_values_supported:S(c()).optional(),service_documentation:ve.optional(),revocation_endpoint:ve.optional(),revocation_endpoint_auth_methods_supported:S(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:S(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:S(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:S(c()).optional(),code_challenge_methods_supported:S(c()).optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0),dpop_signing_alg_values_supported:S(c()).optional()}),Ci=F({issuer:c(),authorization_endpoint:ve,token_endpoint:ve,userinfo_endpoint:ve.optional(),jwks_uri:ve,registration_endpoint:ve.optional(),scopes_supported:S(c()).optional(),response_types_supported:S(c()),response_modes_supported:S(c()).optional(),grant_types_supported:S(c()).optional(),acr_values_supported:S(c()).optional(),subject_types_supported:S(c()),id_token_signing_alg_values_supported:S(c()),id_token_encryption_alg_values_supported:S(c()).optional(),id_token_encryption_enc_values_supported:S(c()).optional(),userinfo_signing_alg_values_supported:S(c()).optional(),userinfo_encryption_alg_values_supported:S(c()).optional(),userinfo_encryption_enc_values_supported:S(c()).optional(),request_object_signing_alg_values_supported:S(c()).optional(),request_object_encryption_alg_values_supported:S(c()).optional(),request_object_encryption_enc_values_supported:S(c()).optional(),token_endpoint_auth_methods_supported:S(c()).optional(),token_endpoint_auth_signing_alg_values_supported:S(c()).optional(),display_values_supported:S(c()).optional(),claim_types_supported:S(c()).optional(),claims_supported:S(c()).optional(),service_documentation:c().optional(),claims_locales_supported:S(c()).optional(),ui_locales_supported:S(c()).optional(),claims_parameter_supported:E().optional(),request_parameter_supported:E().optional(),request_uri_parameter_supported:E().optional(),require_request_uri_registration:E().optional(),op_policy_uri:ve.optional(),op_tos_uri:ve.optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0)}),Ko=p({...Ci.shape,...Br.pick({code_challenge_methods_supported:!0}).shape}),Go=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(),Ii=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(),Yo=p({error:c(),error_description:c().optional(),error_uri:c().optional()}),su=ve.optional().or(h("").transform(()=>{return})),Oi=p({redirect_uris:S(ve),token_endpoint_auth_method:c().optional(),grant_types:S(c()).optional(),response_types:S(c()).optional(),application_type:c().optional(),client_name:c().optional(),client_uri:ve.optional(),logo_uri:su,scope:c().optional(),contacts:S(c()).optional(),tos_uri:su,policy_uri:c().optional(),jwks_uri:ve.optional(),jwks:Va().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Ni=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(),Xo=Oi.merge(Ni),gc=p({error:c(),error_description:c().optional()}).strip(),Sc=p({token:c(),token_type_hint:c().optional()}).strip();var du=Symbol.for("mcp.sdk.errorBrands");function Wr(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,du,{value:r,enumerable:!1,configurable:!0})}function Ke(e,t){try{if(typeof t==="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand==="string"&&Object.prototype.hasOwnProperty.call(t,du)){let r=t[du];if(r&&typeof r.has==="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var Vt=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}({}),Kr=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Ke(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 Ke(this,t)}constructor(t,r,o){super(r);this.code=t,this.errorUri=o,this.name="OAuthError",Wr(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)}},N=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}({}),A=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Ke(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 Ke(this,e)}constructor(e,t,r,o){super(t,o);this.code=e,this.data=r,this.name="SdkError",Wr(this,new.target)}},Tt=class extends A{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 Ff(e){let t=typeof e==="string"?new URL(e):new URL(e.href);return t.hash="",t}function gu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}function Hf({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+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(i)}var Vf="2026-07-28",Su=[Vf];function Jt(e){return e>=Vf}function _u(e){return e.filter((t)=>!Jt(t))}function Ui(e){return e.filter((t)=>Jt(t))}function Jf(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 Bf=["task","inputRequests","requestState"];function $b(e){if(e===null||typeof e!=="object"||Array.isArray(e)||e.content!==void 0||Bf.some((t)=>(t in e)))return e;return{...e,content:[]}}function Cb(){let e=es(()=>T([c(),z(),E(),Cr(),P(c(),e),S(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=p({ttl:z().optional()}),i=p({taskId:c()}),s=F({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),a=p({_meta:s.optional()}),l=a.extend({task:n.optional()}),u=p({method:c(),params:a.loose().optional()}),d=p({_meta:s.optional()}),m=p({method:c(),params:d.loose().optional()}),f=F({_meta:s.optional()}),g=T([c(),z().int()]),b=f.strict(),y=d.extend({requestId:g.optional(),reason:c().optional()}),v=m.extend({method:h("notifications/cancelled"),params:y}),L=p({src:c(),mimeType:c().optional(),sizes:S(c()).optional(),theme:K(["light","dark"]).optional()}),H=p({icons:S(L).optional()}),x=p({name:c(),title:c().optional()}),Z=x.extend({...x.shape,...H.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),R=At(p({applyDefaults:E().optional()}),t),w=Ir((Ee)=>{if(Ee&&typeof Ee==="object"&&!Array.isArray(Ee)&&Object.keys(Ee).length===0)return{form:{}};return Ee},At(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()}),Q=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()}),ue=a.extend({protocolVersion:c(),capabilities:Y,clientInfo:Z}),$e=u.extend({method:h("initialize"),params:ue}),oe=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:Q.optional(),extensions:P(c(),t).optional()}),ae=f.extend({protocolVersion:c(),capabilities:oe,serverInfo:Z,instructions:c().optional()}),we=m.extend({method:h("notifications/initialized"),params:d.optional()}),Ce=u.extend({method:h("ping"),params:a.optional()}),mt=p({progress:z(),total:U(z()),message:U(c())}),Me=p({...d.shape,...mt.shape,progressToken:r}),Ye=m.extend({method:h("notifications/progress"),params:Me}),ft=a.extend({cursor:o.optional()}),Fe=u.extend({params:ft.optional()}),Ie=f.extend({nextCursor:o.optional()}),It=p({uri:c(),mimeType:U(c()),_meta:P(c(),M()).optional()}),Ot=It.extend({text:c()}),gt=c().refine((Ee)=>{try{return atob(Ee),!0}catch{return!1}},{message:"Invalid Base64 string"}),Pe=It.extend({blob:gt}),Oe=K(["user","assistant"]),Ne=p({audience:S(Oe).optional(),priority:z().min(0).max(1).optional(),lastModified:_o({offset:!0}).optional()}),st=p({...x.shape,...H.shape,uri:c(),description:U(c()),mimeType:U(c()),size:U(z()),annotations:Ne.optional(),_meta:U(F({}))}),gr=p({...x.shape,...H.shape,uriTemplate:c(),description:U(c()),mimeType:U(c()),annotations:Ne.optional(),_meta:U(F({}))}),He=Fe.extend({method:h("resources/list")}),Ve=Ie.extend({resources:S(st)}),je=Fe.extend({method:h("resources/templates/list")}),Xe=Ie.extend({resourceTemplates:S(gr)}),Qe=a.extend({uri:c()}),St=Qe,_t=u.extend({method:h("resources/read"),params:St}),Yt=f.extend({contents:S(T([Ot,Pe]))}),bt=m.extend({method:h("notifications/resources/list_changed"),params:d.optional()}),Sr=Qe,I=u.extend({method:h("resources/subscribe"),params:Sr}),yt=Qe,V=u.extend({method:h("resources/unsubscribe"),params:yt}),q=d.extend({uri:c()}),G=m.extend({method:h("notifications/resources/updated"),params:q}),O=p({name:c(),description:U(c()),required:U(E())}),C=p({...x.shape,...H.shape,description:U(c()),arguments:U(S(O)),_meta:U(F({}))}),B=Fe.extend({method:h("prompts/list")}),J=Ie.extend({prompts:S(C)}),_e=a.extend({name:c(),arguments:P(c(),c()).optional()}),_r=u.extend({method:h("prompts/get"),params:_e}),vt=p({type:h("text"),text:c(),annotations:Ne.optional(),_meta:P(c(),M()).optional()}),br=p({type:h("image"),data:gt,mimeType:c(),annotations:Ne.optional(),_meta:P(c(),M()).optional()}),yr=p({type:h("audio"),data:gt,mimeType:c(),annotations:Ne.optional(),_meta:P(c(),M()).optional()}),pn=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),M()),_meta:P(c(),M()).optional()}),Xt=p({type:h("resource"),resource:T([Ot,Pe]),annotations:Ne.optional(),_meta:P(c(),M()).optional()}),hn=st.extend({type:h("resource_link")}),et=T([vt,br,yr,hn,Xt]),ro=p({role:Oe,content:et}),oo=f.extend({description:c().optional(),messages:S(ro)}),vr=m.extend({method:h("notifications/prompts/list_changed"),params:d.optional()}),mn=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),no=p({taskSupport:K(["required","optional","forbidden"]).optional()}),zr=p({...x.shape,...H.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:S(c()).optional()}).catchall(M()),outputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:S(c()).optional()}).catchall(M()).optional(),annotations:mn.optional(),execution:no.optional(),_meta:P(c(),M()).optional()}),so=Fe.extend({method:h("tools/list")}),io=Ie.extend({tools:S(zr)}),ao=f.extend({content:S(et),structuredContent:P(c(),M()).optional(),isError:E().optional()}),Te=l.extend({name:c(),arguments:P(c(),M()).optional()}),fn=u.extend({method:h("tools/call"),params:Te}),na=m.extend({method:h("notifications/tools/list_changed"),params:d.optional()}),co=K(["debug","info","notice","warning","error","critical","alert","emergency"]),gn=a.extend({level:co}),Sn=u.extend({method:h("logging/setLevel"),params:gn}),_n=d.extend({level:co,logger:c().optional(),data:M()}),bn=m.extend({method:h("notifications/message"),params:_n}),yn=p({name:c().optional()}),vn=p({hints:S(yn).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),zn=p({mode:K(["auto","required","none"]).optional()}),sa=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:S(et),structuredContent:p({}).loose().optional(),isError:E().optional(),_meta:P(c(),M()).optional()}),wn=bo("type",[vt,br,yr]),Qt=bo("type",[vt,br,yr,pn,sa]),Rn=p({role:Oe,content:T([Qt,S(Qt)]),_meta:P(c(),M()).optional()}),xn=l.extend({messages:S(Rn),modelPreferences:vn.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:S(c()).optional(),metadata:t.optional(),tools:S(zr).optional(),toolChoice:zn.optional()}),Pn=u.extend({method:h("sampling/createMessage"),params:xn}),Tn=f.extend({model:c(),stopReason:U(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Oe,content:wn}),En=f.extend({model:c(),stopReason:U(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Oe,content:T([Qt,S(Qt)])}),kn=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),$n=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()}),Cn=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),In=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),default:c().optional()}),On=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:S(p({const:c(),title:c()})),default:c().optional()}),Nn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),enumNames:S(c()).optional(),default:c().optional()}),An=T([In,On]),wr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:S(c())}),default:S(c()).optional()}),Rr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:S(p({const:c(),title:c()}))}),default:S(c()).optional()}),ia=T([wr,Rr]),aa=T([Nn,An,ia]),Je=T([aa,kn,$n,Cn]),Be=l.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),Je),required:S(c()).optional()}).catchall(M())}),qn=l.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),it=T([Be,qn]),ca=u.extend({method:h("elicitation/create"),params:it}),la=d.extend({elicitationId:c()}),ua=m.extend({method:h("notifications/elicitation/complete"),params:la}),da=f.extend({action:K(["accept","decline","cancel"]),content:Ir((Ee)=>Ee===null?void 0:Ee,P(c(),T([c(),z(),E(),S(c())])).optional())}),pa=p({type:h("ref/resource"),uri:c()}),ha=p({type:h("ref/prompt"),name:c()}),ma=a.extend({ref:T([ha,pa]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),Mn=u.extend({method:h("completion/complete"),params:ma}),fa=f.extend({completion:F({values:S(c()).max(100),total:U(z().int()),hasMore:U(E())})}),ga=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),M()).optional()}),lo=u.extend({method:h("roots/list"),params:a.optional()}),jn=f.extend({roots:S(ga)}),Sa=m.extend({method:h("notifications/roots/list_changed"),params:d.optional()}),_a=F({ttl:z().optional(),pollInterval:z().optional()}),Ln=K(["working","input_required","completed","failed","cancelled"]),er=p({taskId:c(),status:Ln,ttl:T([z(),Cr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:U(z()),statusMessage:U(c())}),Le=f.extend({task:er}),ba=d.merge(er),xr=m.extend({method:h("notifications/tasks/status"),params:ba}),uo=u.extend({method:h("tasks/get"),params:a.extend({taskId:c()})}),po=f.merge(er),ho=u.extend({method:h("tasks/result"),params:a.extend({taskId:c()})}),Bc=f.loose(),Ae=Fe.extend({method:h("tasks/list")}),ge=Ie.extend({tasks:S(er)}),Pr=u.extend({method:h("tasks/cancel"),params:a.extend({taskId:c()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:n,RelatedTaskMetadataSchema:i,RequestMetaSchema:s,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:l,RequestSchema:u,NotificationsParamsSchema:d,NotificationSchema:m,ResultSchema:f,RequestIdSchema:g,EmptyResultSchema:b,CancelledNotificationParamsSchema:y,CancelledNotificationSchema:v,IconSchema:L,IconsSchema:H,BaseMetadataSchema:x,ImplementationSchema:Z,ClientTasksCapabilitySchema:D,ServerTasksCapabilitySchema:Q,ClientCapabilitiesSchema:Y,InitializeRequestParamsSchema:ue,InitializeRequestSchema:$e,ServerCapabilitiesSchema:oe,InitializeResultSchema:ae,InitializedNotificationSchema:we,PingRequestSchema:Ce,ProgressSchema:mt,ProgressNotificationParamsSchema:Me,ProgressNotificationSchema:Ye,PaginatedRequestParamsSchema:ft,PaginatedRequestSchema:Fe,PaginatedResultSchema:Ie,ResourceContentsSchema:It,TextResourceContentsSchema:Ot,BlobResourceContentsSchema:Pe,RoleSchema:Oe,AnnotationsSchema:Ne,ResourceSchema:st,ResourceTemplateSchema:gr,ListResourcesRequestSchema:He,ListResourcesResultSchema:Ve,ListResourceTemplatesRequestSchema:je,ListResourceTemplatesResultSchema:Xe,ResourceRequestParamsSchema:Qe,ReadResourceRequestParamsSchema:St,ReadResourceRequestSchema:_t,ReadResourceResultSchema:Yt,ResourceListChangedNotificationSchema:bt,SubscribeRequestParamsSchema:Sr,SubscribeRequestSchema:I,UnsubscribeRequestParamsSchema:yt,UnsubscribeRequestSchema:V,ResourceUpdatedNotificationParamsSchema:q,ResourceUpdatedNotificationSchema:G,PromptArgumentSchema:O,PromptSchema:C,ListPromptsRequestSchema:B,ListPromptsResultSchema:J,GetPromptRequestParamsSchema:_e,GetPromptRequestSchema:_r,TextContentSchema:vt,ImageContentSchema:br,AudioContentSchema:yr,ToolUseContentSchema:pn,EmbeddedResourceSchema:Xt,ResourceLinkSchema:hn,ContentBlockSchema:et,PromptMessageSchema:ro,GetPromptResultSchema:oo,PromptListChangedNotificationSchema:vr,ToolAnnotationsSchema:mn,ToolExecutionSchema:no,ToolSchema:zr,ListToolsRequestSchema:so,ListToolsResultSchema:io,CallToolResultSchema:ao,CallToolRequestParamsSchema:Te,CallToolRequestSchema:fn,ToolListChangedNotificationSchema:na,LoggingLevelSchema:co,SetLevelRequestParamsSchema:gn,SetLevelRequestSchema:Sn,LoggingMessageNotificationParamsSchema:_n,LoggingMessageNotificationSchema:bn,ModelHintSchema:yn,ModelPreferencesSchema:vn,ToolChoiceSchema:zn,ToolResultContentSchema:sa,SamplingContentSchema:wn,SamplingMessageContentBlockSchema:Qt,SamplingMessageSchema:Rn,CreateMessageRequestParamsSchema:xn,CreateMessageRequestSchema:Pn,CreateMessageResultSchema:Tn,CreateMessageResultWithToolsSchema:En,BooleanSchemaSchema:kn,StringSchemaSchema:$n,NumberSchemaSchema:Cn,UntitledSingleSelectEnumSchemaSchema:In,TitledSingleSelectEnumSchemaSchema:On,LegacyTitledEnumSchemaSchema:Nn,SingleSelectEnumSchemaSchema:An,UntitledMultiSelectEnumSchemaSchema:wr,TitledMultiSelectEnumSchemaSchema:Rr,MultiSelectEnumSchemaSchema:ia,EnumSchemaSchema:aa,PrimitiveSchemaDefinitionSchema:Je,ElicitRequestFormParamsSchema:Be,ElicitRequestURLParamsSchema:qn,ElicitRequestParamsSchema:it,ElicitRequestSchema:ca,ElicitationCompleteNotificationParamsSchema:la,ElicitationCompleteNotificationSchema:ua,ElicitResultSchema:da,ResourceTemplateReferenceSchema:pa,PromptReferenceSchema:ha,CompleteRequestParamsSchema:ma,CompleteRequestSchema:Mn,CompleteResultSchema:fa,RootSchema:ga,ListRootsRequestSchema:lo,ListRootsResultSchema:jn,RootsListChangedNotificationSchema:Sa,TaskCreationParamsSchema:_a,TaskStatusSchema:Ln,TaskSchema:er,CreateTaskResultSchema:Le,TaskStatusNotificationParamsSchema:ba,TaskStatusNotificationSchema:xr,GetTaskRequestSchema:uo,GetTaskResultSchema:po,GetTaskPayloadRequestSchema:ho,GetTaskPayloadResultSchema:Bc,ListTasksRequestSchema:Ae,ListTasksResultSchema:ge,CancelTaskRequestSchema:Pr,CancelTaskResultSchema:f.merge(er),ClientRequestSchema:T([Ce,$e,Mn,Sn,_r,B,He,je,_t,I,V,fn,so,uo,ho,Ae,Pr]),ClientNotificationSchema:T([v,Ye,we,Sa,xr]),ClientResultSchema:T([b,Tn,En,da,jn,po,ge,Le]),ServerRequestSchema:T([Ce,Pn,ca,lo,uo,ho,Ae,Pr]),ServerNotificationSchema:T([v,Ye,bn,G,bt,na,vr,xr,ua]),ServerResultSchema:T([b,ae,fa,oo,J,Ve,Xe,Yt,ao,io,po,ge,Le]),CallToolResultWireSchema:M().superRefine((Ee,GS)=>{if(typeof Ee!=="object"||Ee===null||Array.isArray(Ee)||Ee.content!==void 0)return;for(let hd of Bf)if(hd in Ee){GS.addIssue({code:"custom",message:`content is required when the body carries '${hd}' — another result family cannot default into an empty tools/call success`});return}}).transform($b).pipe(ao)}}var Ib;function Wf(){return Ib??=Cb()}function Kf(e){return e.type!=="object"}var Ob=new Set(["const","enum","default","examples"]),Nb=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function kf(e){return e!==void 0&&!(typeof e==="string"&&e.startsWith("#"))}function Ab(e){let t=typeof e.$schema==="string"?e.$schema:void 0;if(kf(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=bd(e.$schema)&&e.$recursiveAnchor!==!0,o=(n,i)=>{if(Array.isArray(n))return n.map((l)=>o(l,!1));if(n===null||typeof n!=="object")return n;if(!i&&kf(n.$id))return n;let s={},a=!1;for(let[l,u]of Object.entries(n))if(i)s[l]=o(u,!1);else if((l==="$ref"||l==="$dynamicRef")&&typeof u==="string")s[l]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u;else if(l==="$recursiveRef"&&u==="#"&&r)a=!0;else if(Ob.has(l))s[l]=u;else if(Nb.has(l))s[l]=o(u,!0);else s[l]=o(u,!1);if(a)if("$ref"in s)s.allOf=[...Array.isArray(s.allOf)?s.allOf:[],{$ref:"#/properties/result"}];else s.$ref="#/properties/result";return s};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}var Gf={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},Yf={"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},qb={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},_c;function bu(){if(_c)return _c;let e=Wf();return _c={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}},_c}function Xf(e){return Object.prototype.hasOwnProperty.call(Gf,e)}function Qf(e){return Object.prototype.hasOwnProperty.call(Yf,e)}function Mb(e){return Object.prototype.hasOwnProperty.call(qb,e)}function jb(e){return Mb(e)?bu().resultSchemas[e]:void 0}function Lb(e){return Xf(e)?bu().requestSchemas[e]:void 0}function Ub(e){return Qf(e)?bu().notificationSchemas[e]:void 0}var Yx=Object.keys(Gf),Xx=Object.keys(Yf);function pu(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function bc(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 $f={ok:!1,reason:"not-in-era"};function Cf(e){return pu(e)&&pu(e.outputSchema)&&Kf(e.outputSchema)}function If(e){return e}var yu={era:"2025-11-25",hasRequestMethod:Xf,hasNotificationMethod:Qf,validateRequest:(e,t)=>bc(Lb(e),t),validateResult:(e,t)=>bc(jb(e),t),validateNotification:(e,t)=>bc(Ub(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>$f,validateInputResponse:()=>$f,samplingResultVariant:(e,t)=>{let r=Wf();return bc(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)},outboundEnvelope:(e)=>{return},validateEnvelopeMeta:(e)=>[],projectCallToolResult(e,t){let r=Jf(e),o=r.structuredContent;if(o===void 0)return r;let n=typeof o!=="object"||o===null||Array.isArray(o),i=t!==void 0&&Kf(t);if(!n&&!i)return r;return{...r,structuredContent:{result:o}}},decodeResult(e,t){if(pu(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:If(r)}}return{kind:"complete",result:If(t)}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;if(!Array.isArray(r)||!r.some((o)=>Cf(o)))return t;return{...t,tools:r.map((o)=>Cf(o)?{...o,outputSchema:Ab(o.outputSchema)}:o)}},encodeErrorCode:(e)=>e===-32002?-32602:e,checkInboundEnvelope:(e)=>{return}};function Zb(){let e=es(()=>T([c(),z(),E(),Cr(),P(c(),e),S(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=T([c(),z().int()]),i=K(["user","assistant"]),s=K(["debug","info","notice","warning","error","critical","alert","emergency"]),a=c().refine((ge)=>{try{return atob(ge),!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()}),g=p({_meta:d.optional()}),b=p({method:c(),params:g.loose().optional()}),y=p({src:c(),mimeType:c().optional(),sizes:S(c()).optional(),theme:K(["light","dark"]).optional()}),v=p({icons:S(y).optional()}),L=p({name:c(),title:c().optional()}),H=L.extend({...L.shape,...v.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),x=At(p({applyDefaults:E().optional()}),t),Z=Ir((ge)=>{if(ge&&typeof ge==="object"&&!Array.isArray(ge)&&Object.keys(ge).length===0)return{form:{}};return ge},At(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()}),Q=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:U(z()),message:U(c())}),ue=p({...g.shape,...Y.shape,progressToken:r}),$e=b.extend({method:h("notifications/progress"),params:ue}),oe=g.extend({level:s,logger:c().optional(),data:M()}),ae=b.extend({method:h("notifications/message"),params:oe}),we=p({uri:c(),mimeType:U(c()),_meta:P(c(),M()).optional()}),Ce=we.extend({text:c()}),mt=we.extend({blob:a}),Me=p({audience:S(i).optional(),priority:z().min(0).max(1).optional(),lastModified:_o({offset:!0}).optional()}),Ye=p({...L.shape,...v.shape,uri:c(),description:U(c()),mimeType:U(c()),size:U(z()),annotations:Me.optional(),_meta:U(F({}))}),ft=p({...L.shape,...v.shape,uriTemplate:c(),description:U(c()),mimeType:U(c()),annotations:Me.optional(),_meta:U(F({}))}),Fe=b.extend({method:h("notifications/resources/list_changed"),params:g.optional()}),Ie=g.extend({uri:c()}),It=b.extend({method:h("notifications/resources/updated"),params:Ie}),Ot=p({name:c(),description:U(c()),required:U(E())}),gt=p({...L.shape,...v.shape,description:U(c()),arguments:U(S(Ot)),_meta:U(F({}))}),Pe=b.extend({method:h("notifications/prompts/list_changed"),params:g.optional()}),Oe=p({type:h("text"),text:c(),annotations:Me.optional(),_meta:P(c(),M()).optional()}),Ne=p({type:h("image"),data:a,mimeType:c(),annotations:Me.optional(),_meta:P(c(),M()).optional()}),st=p({type:h("audio"),data:a,mimeType:c(),annotations:Me.optional(),_meta:P(c(),M()).optional()}),gr=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),M()),_meta:P(c(),M()).optional()}),He=p({type:h("resource"),resource:T([Ce,mt]),annotations:Me.optional(),_meta:P(c(),M()).optional()}),Ve=Ye.extend({type:h("resource_link")}),je=T([Oe,Ne,st,Ve,He]),Xe=p({role:i,content:je}),Qe=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),St=b.extend({method:h("notifications/tools/list_changed"),params:g.optional()}),_t=p({name:c().optional()}),Yt=p({hints:S(_t).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),bt=p({mode:K(["auto","required","none"]).optional()}),Sr=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),I=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()}),yt=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:S(c()),default:c().optional()}),q=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:S(p({const:c(),title:c()})),default:c().optional()}),G=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),enumNames:S(c()).optional(),default:c().optional()}),O=T([V,q]),C=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:S(c())}),default:S(c()).optional()}),B=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:S(p({const:c(),title:c()}))}),default:S(c()).optional()}),J=T([C,B]),_e=T([G,O,J]),_r=T([_e,Sr,I,yt]),vt=f.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),_r),required:S(c()).optional()}).catchall(M())}),br=p({type:h("ref/resource"),uri:c()}),yr=p({type:h("ref/prompt"),name:c()}),pn=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),M()).optional()}),Xt=D.shape,hn=p({experimental:Xt.experimental,sampling:Xt.sampling,elicitation:Xt.elicitation,roots:Xt.roots,extensions:Xt.extensions}),et=Q.shape,ro=p({experimental:et.experimental,logging:et.logging,completions:et.completions,prompts:et.prompts,resources:et.resources,tools:et.tools,extensions:et.extensions}),oo=F({progressToken:r.optional(),[Mt]:c(),[vo]:H.optional(),[Or]:hn,[zo]:s.optional()}),vr=p({...L.shape,...v.shape,description:c().optional(),inputSchema:F({$schema:c().optional(),type:h("object")}),outputSchema:F({$schema:c().optional()}).optional(),annotations:Qe.optional(),_meta:P(c(),M()).optional()}),mn=p({type:h("tool_result"),toolUseId:c(),content:S(je),structuredContent:M().optional(),isError:E().optional(),_meta:P(c(),M()).optional()}),no=T([Oe,Ne,st,gr,mn]),zr=p({role:i,content:T([no,S(no)]),_meta:P(c(),M()).optional()}),so=c(),io=F({[jt]:H.optional().catch(void 0)}),ao=io.optional();function Te(ge){return F({_meta:ao,resultType:so.default("complete"),...ge})}let fn=Te({}),na=Te({nextCursor:o.optional()}),co=Te({content:S(je),structuredContent:M().optional(),isError:E().optional()}),gn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:S(vr),nextCursor:o.optional()}),Sn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:S(gt),nextCursor:o.optional()}),_n=Te({description:c().optional(),messages:S(Xe)}),bn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:S(Ye),nextCursor:o.optional()}),yn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:S(ft),nextCursor:o.optional()}),vn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:S(T([Ce,mt]))}),zn=Te({completion:p({values:S(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),sa=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"])}),wn=Te({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:S(c()),capabilities:ro,instructions:c().optional()}),Qt=p({messages:S(zr),modelPreferences:Yt.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:S(c()).optional(),metadata:t.optional(),tools:S(vr).optional(),toolChoice:bt.optional()}),Rn=p({method:h("sampling/createMessage"),params:Qt}),xn=p({method:h("roots/list"),params:p({_meta:P(c(),M()).optional()}).optional()}),Pn=p({...zr.shape,model:c(),stopReason:c().optional()}),Tn=p({roots:S(pn)}),En=p({action:K(["accept","decline","cancel"]),content:P(c(),T([c(),z(),E(),S(c())])).optional()}),kn=p({mode:h("url"),message:c(),url:c().url()}),$n=T([vt,kn]),Cn=p({method:h("elicitation/create"),params:$n}),In=T([Rn,xn,Cn]),On=T([Pn,Tn,En]),Nn=P(c(),In),An=P(c(),On),wr=Te({inputRequests:Nn.optional(),requestState:c().optional()}),Rr={inputResponses:An.optional(),requestState:c().optional()},ia=p({_meta:oo,...Rr}),aa=F({progressToken:r.optional()});function Je(ge,Pr){return p({method:h(ge),params:p({_meta:oo,...Pr})})}function Be(ge,Pr){return p({method:h(ge),params:p({_meta:aa.optional(),...Pr}).optional()})}let qn={name:c(),arguments:P(c(),M()).optional(),...Rr},it={cursor:o.optional()},ca=Je("tools/call",qn),la=Je("tools/list",it),ua=Je("prompts/list",it),da=Je("prompts/get",{name:c(),arguments:P(c(),c()).optional(),...Rr}),pa=Je("resources/list",it),ha=Je("resources/templates/list",it),ma=Je("resources/read",{uri:c(),...Rr}),Mn={ref:T([yr,br]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()},fa=Je("completion/complete",Mn),ga=Je("server/discover",{}),lo=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:S(c()).optional()}),jn={notifications:lo},Sa=Je("subscriptions/listen",jn),_a=io.extend({"io.modelcontextprotocol/subscriptionId":n}),Ln=F({_meta:_a,resultType:so.default("complete")}),er={"tools/call":Be("tools/call",qn),"tools/list":Be("tools/list",it),"prompts/get":Be("prompts/get",{name:c(),arguments:P(c(),c()).optional()}),"prompts/list":Be("prompts/list",it),"resources/list":Be("resources/list",it),"resources/templates/list":Be("resources/templates/list",it),"resources/read":Be("resources/read",{uri:c()}),"completion/complete":Be("completion/complete",Mn),"server/discover":Be("server/discover",{}),"subscriptions/listen":Be("subscriptions/listen",jn)};function Le(ge){return F({_meta:ao,...ge})}let ba={"tools/call":Le({content:S(je),structuredContent:M().optional(),isError:E().optional()}),"tools/list":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:S(vr),nextCursor:o.optional()}),"prompts/get":Le({description:c().optional(),messages:S(Xe)}),"prompts/list":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:S(gt),nextCursor:o.optional()}),"resources/list":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:S(Ye),nextCursor:o.optional()}),"resources/templates/list":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:S(ft),nextCursor:o.optional()}),"resources/read":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:S(T([Ce,mt]))}),"completion/complete":Le({completion:p({values:S(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":Le({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:S(c()),capabilities:ro,instructions:c().optional()}),"subscriptions/listen":Le({})},xr=F({"io.modelcontextprotocol/subscriptionId":n.optional()}),uo=p({method:h("notifications/subscriptions/acknowledged"),params:p({_meta:xr.optional(),notifications:lo})}),po=p({_meta:xr.optional(),requestId:n,reason:c().optional()}),ho=p({method:h("notifications/cancelled"),params:po}),Bc={"notifications/cancelled":ho,"notifications/progress":$e,"notifications/message":ae,"notifications/resources/updated":It,"notifications/resources/list_changed":Fe,"notifications/tools/list_changed":St,"notifications/prompts/list_changed":Pe,"notifications/subscriptions/acknowledged":uo},Ae=(ge)=>p({jsonrpc:h("2.0"),id:T([c(),z().int()]),result:ge}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:n,RoleSchema:i,LoggingLevelSchema:s,TaskMetadataSchema:l,RelatedTaskMetadataSchema:u,RequestMetaSchema:d,BaseRequestParamsSchema:m,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:g,NotificationSchema:b,IconSchema:y,IconsSchema:v,BaseMetadataSchema:L,ImplementationSchema:H,ClientTasksCapabilitySchema:R,ServerTasksCapabilitySchema:w,ClientCapabilitiesSchema:D,ServerCapabilitiesSchema:Q,ProgressSchema:Y,ProgressNotificationParamsSchema:ue,ProgressNotificationSchema:$e,LoggingMessageNotificationParamsSchema:oe,LoggingMessageNotificationSchema:ae,ResourceContentsSchema:we,TextResourceContentsSchema:Ce,BlobResourceContentsSchema:mt,AnnotationsSchema:Me,ResourceSchema:Ye,ResourceTemplateSchema:ft,ResourceListChangedNotificationSchema:Fe,ResourceUpdatedNotificationParamsSchema:Ie,ResourceUpdatedNotificationSchema:It,PromptArgumentSchema:Ot,PromptSchema:gt,PromptListChangedNotificationSchema:Pe,TextContentSchema:Oe,ImageContentSchema:Ne,AudioContentSchema:st,ToolUseContentSchema:gr,EmbeddedResourceSchema:He,ResourceLinkSchema:Ve,ContentBlockSchema:je,PromptMessageSchema:Xe,ToolAnnotationsSchema:Qe,ToolListChangedNotificationSchema:St,ModelHintSchema:_t,ModelPreferencesSchema:Yt,ToolChoiceSchema:bt,BooleanSchemaSchema:Sr,StringSchemaSchema:I,NumberSchemaSchema:yt,UntitledSingleSelectEnumSchemaSchema:V,TitledSingleSelectEnumSchemaSchema:q,LegacyTitledEnumSchemaSchema:G,SingleSelectEnumSchemaSchema:O,UntitledMultiSelectEnumSchemaSchema:C,TitledMultiSelectEnumSchemaSchema:B,MultiSelectEnumSchemaSchema:J,EnumSchemaSchema:_e,PrimitiveSchemaDefinitionSchema:_r,ElicitRequestFormParamsSchema:vt,ResourceTemplateReferenceSchema:br,PromptReferenceSchema:yr,RootSchema:pn,ClientCapabilities2026Schema:hn,ServerCapabilities2026Schema:ro,RequestMetaEnvelopeSchema:oo,ToolSchema:vr,ToolResultContentSchema:mn,SamplingMessageContentBlockSchema:no,SamplingMessageSchema:zr,ResultTypeSchema:so,ResultMetaSchema:io,ResultSchema:fn,PaginatedResultSchema:na,CallToolResultSchema:co,ListToolsResultSchema:gn,ListPromptsResultSchema:Sn,GetPromptResultSchema:_n,ListResourcesResultSchema:bn,ListResourceTemplatesResultSchema:yn,ReadResourceResultSchema:vn,CompleteResultSchema:zn,CacheableResultSchema:sa,DiscoverResultSchema:wn,CreateMessageRequestParamsSchema:Qt,CreateMessageRequestSchema:Rn,ListRootsRequestSchema:xn,CreateMessageResultSchema:Pn,ListRootsResultSchema:Tn,ElicitResultSchema:En,ElicitRequestURLParamsSchema:kn,ElicitRequestParamsSchema:$n,ElicitRequestSchema:Cn,InputRequestSchema:In,InputResponseSchema:On,InputRequestsSchema:Nn,InputResponsesSchema:An,InputRequiredResultSchema:wr,InputResponseRequestParamsSchema:ia,CallToolRequestSchema:ca,ListToolsRequestSchema:la,ListPromptsRequestSchema:ua,GetPromptRequestSchema:da,ListResourcesRequestSchema:pa,ListResourceTemplatesRequestSchema:ha,ReadResourceRequestSchema:ma,CompleteRequestSchema:fa,DiscoverRequestSchema:ga,SubscriptionFilterSchema:lo,SubscriptionsListenRequestSchema:Sa,SubscriptionsListenResultMetaSchema:_a,SubscriptionsListenResultSchema:Ln,dispatchRequestSchemas:er,dispatchResultSchemas:ba,NotificationMetaSchema:xr,SubscriptionsAcknowledgedNotificationSchema:uo,CancelledNotificationParamsSchema:po,CancelledNotificationSchema:ho,notificationSchemas2026:Bc,JSONRPCResultResponseSchema:Ae(fn),CallToolResultResponseSchema:Ae(T([co,wr])),ListToolsResultResponseSchema:Ae(gn),ListPromptsResultResponseSchema:Ae(Sn),GetPromptResultResponseSchema:Ae(T([_n,wr])),ListResourcesResultResponseSchema:Ae(bn),ListResourceTemplatesResultResponseSchema:Ae(yn),ReadResourceResultResponseSchema:Ae(T([vn,wr])),CompleteResultResponseSchema:Ae(zn),DiscoverResultResponseSchema:Ae(wn),SubscriptionsListenResultResponseSchema:Ae(Ln)}}var Db;function pr(){return Db??=Zb()}var Fb=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function Hb(e){return Fb.includes(e)}var vu=Symbol("modelcontextprotocol.resultCacheHintFallback");function Vb(e){return e[vu]}function eg(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function tg(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}({}),re=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Ke(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 Ke(this,t)}constructor(t,r,o){super(r);this.code=t,this.data=o,this.name="ProtocolError",Wr(this,new.target)}static fromError(t,r,o){if(t===W.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new og(n.elicitations,r)}if(t===W.UnsupportedProtocolVersion&&o){let n=o;if(Array.isArray(n.supported)&&typeof n.requested==="string")return new Rc({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 rg(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 ng({requiredCapabilities:n.requiredCapabilities},r)}return new e(t,r,o)}},rg=class extends re{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}},og=class extends re{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??[]}},Rc=class extends re{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}},ng=class extends re{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}},Jb=0,Bb="private",Wb=["tools/call","prompts/get","resources/read"];function Kb(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete")return t;if(Wb.includes(e))return t;throw new re(W.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function Gb(e,t){let r=Vb(t);if(t.resultType!=="complete"||!Hb(e))return r===void 0?t:ty(t);let o=t,n=eg(o.ttlMs)?o.ttlMs:Qb(r),i=tg(o.cacheScope)?o.cacheScope:ey(r),s={...o,ttlMs:n,cacheScope:i};return delete s[vu],s}function Yb(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Xb(e,t){if(t===void 0)return e;let r=e._meta;if(r===void 0)return{...e,_meta:{[jt]:t}};if(!Yb(r))return e;if(r[jt]!==void 0)return e;return{...e,_meta:{...r,[jt]:t}}}function Qb(e){return e!==void 0&&eg(e.ttlMs)?e.ttlMs:Jb}function ey(e){return e!==void 0&&tg(e.cacheScope)?e.cacheScope:Bb}function ty(e){let t={...e};return delete t[vu],t}var ry=["elicitation/create","sampling/createMessage","roots/list"],yc;function sg(){if(yc)return yc;let e=pr();return yc={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}},yc}function ig(e){return ry.includes(e)}function au(e){return ig(e)?sg().request[e]:void 0}function oy(e){return ig(e)?sg().response[e]:void 0}var zu={"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},ag={"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 cg(e){return Object.prototype.hasOwnProperty.call(zu,e)}function lg(e){return Object.prototype.hasOwnProperty.call(ag,e)}function ny(e){return Object.prototype.hasOwnProperty.call(zu,e)}function sy(e){return cg(e)?pr().dispatchRequestSchemas[e]:void 0}function iy(e){return ny(e)?pr().dispatchResultSchemas[e]:void 0}function ay(e){return lg(e)?pr().notificationSchemas2026[e]:void 0}var Qx=Object.keys(zu),eP=Object.keys(ag);function Mi(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Ai(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 cy={ok:!1,reason:"not-in-era"},ly=[Mt,Or];function uy(e,t){let r=t,o=!1,n=()=>{if(!o)r={...r},o=!0;return r},i=t.tools;if(e==="tools/list"&&Array.isArray(i)&&i.some((a)=>Mi(a)&&("execution"in a)))n().tools=i.map((a)=>{if(!Mi(a)||!("execution"in a))return a;let l={...a};return delete l.execution,l});let s=t.capabilities;if(Mi(s)&&"tasks"in s){let a={...s};delete a.tasks,n().capabilities=a}return r}var wu={era:"2026-07-28",hasRequestMethod:cg,hasNotificationMethod:lg,hasInputRequestMethod:(e)=>au(e)!==void 0,validateRequest:(e,t)=>Ai(sy(e),t),validateResult:(e,t)=>Ai(iy(e),t),validateNotification:(e,t)=>Ai(ay(e),t),validateInputRequest:(e,t)=>Ai(au(e),t),validateInputResponse:(e,t)=>Ai(oy(e),t),samplingResultVariant:()=>cy,outboundEnvelope(e){return{[Mt]:e.protocolVersion,[vo]:e.clientInfo,[Or]:e.clientCapabilities,...e.logLevel!==void 0&&{[zo]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of ly)if(!(o in e))t.push({key:o,problem:"missing"});let r=pr().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let n=o.path.map(String),i=n.length>0?n.join("."):"_meta";if(n.length===1&&t.some((s)=>s.key===i&&s.problem==="missing"))continue;t.push({key:i,problem:o.message})}return t},projectCallToolResult:(e)=>Jf(e),inputRequestSchema:au,decodeResult(e,t){if(!Mi(t))return{kind:"invalid",error:new A(N.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new A(N.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 A(N.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let s=t.inputRequests,a=Mi(s)?s:{},l=t.requestState,u=t._meta===void 0?void 0:pr().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 A(N.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 A(N.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=dy(),n=Object.hasOwn(o,e)?o[e]:void 0;if(n!==void 0){let s=n.safeParse(t);if(!s.success)return{kind:"invalid",error:new A(N.InvalidResult,`Invalid result for ${e}: ${s.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return Xb(Gb(e,Kb(e,uy(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=pr().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("; ")}`}},vc;function dy(){if(vc)return vc;let e=pr();return vc={"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},vc}var xc="2026-07-28";function Ht(e){return e!==void 0&&Jt(e)?wu:yu}function Of(e){if(e.revision!==void 0)return Ht(e.revision).era;return e.era==="modern"?wu.era:yu.era}function cu(e){return ug.some((t)=>t.hasRequestMethod(e))}function lu(e){return ug.some((t)=>t.hasNotificationMethod(e))}function Nf(e){return e==="tasks/get"||e==="tasks/cancel"}var ug=[yu,wu],py=gd({AnnotationsSchema:()=>xt,AudioContentSchema:()=>Ur,BaseMetadataSchema:()=>wt,BaseRequestParamsSchema:()=>ze,BlobResourceContentsSchema:()=>Mo,BooleanSchemaSchema:()=>Zo,CallToolRequestParamsSchema:()=>Ws,CallToolRequestSchema:()=>Ks,CallToolResultSchema:()=>dr,CancelTaskRequestSchema:()=>cc,CancelTaskResultSchema:()=>lc,CancelledNotificationParamsSchema:()=>ns,CancelledNotificationSchema:()=>ko,ClientCapabilitiesSchema:()=>is,ClientNotificationSchema:()=>dc,ClientRequestSchema:()=>uc,ClientResultSchema:()=>pc,ClientTasksCapabilitySchema:()=>Ga,CompatibilityCallToolResultSchema:()=>Xa,CompleteRequestParamsSchema:()=>zi,CompleteRequestSchema:()=>wi,CompleteResultSchema:()=>Ri,ContentBlockSchema:()=>Pt,CreateMessageRequestParamsSchema:()=>ai,CreateMessageRequestSchema:()=>ci,CreateMessageResultSchema:()=>li,CreateMessageResultWithToolsSchema:()=>ui,CreateTaskResultSchema:()=>ec,CursorSchema:()=>Ro,DiscoverRequestSchema:()=>ls,DiscoverResultSchema:()=>lr,ElicitRequestFormParamsSchema:()=>Jr,ElicitRequestParamsSchema:()=>fi,ElicitRequestSchema:()=>gi,ElicitRequestURLParamsSchema:()=>mi,ElicitResultSchema:()=>bi,ElicitationCompleteNotificationParamsSchema:()=>Si,ElicitationCompleteNotificationSchema:()=>_i,EmbeddedResourceSchema:()=>Zr,EmptyResultSchema:()=>cr,EnumSchemaSchema:()=>hi,GetPromptRequestParamsSchema:()=>js,GetPromptRequestSchema:()=>Ls,GetPromptResultSchema:()=>Ds,GetTaskPayloadRequestSchema:()=>nc,GetTaskPayloadResultSchema:()=>sc,GetTaskRequestSchema:()=>rc,GetTaskResultSchema:()=>oc,IconSchema:()=>ss,IconsSchema:()=>Lt,ImageContentSchema:()=>Lr,ImplementationSchema:()=>Rt,InitializeRequestParamsSchema:()=>as,InitializeRequestSchema:()=>$o,InitializeResultSchema:()=>cs,InitializedNotificationSchema:()=>Io,JSONArraySchema:()=>Wa,JSONObjectSchema:()=>de,JSONRPCErrorResponseSchema:()=>qr,JSONRPCMessageSchema:()=>ut,JSONRPCNotificationSchema:()=>Eo,JSONRPCRequestSchema:()=>To,JSONRPCResponseSchema:()=>Ka,JSONRPCResultResponseSchema:()=>Ar,JSONValueSchema:()=>qt,LegacyTitledEnumSchemaSchema:()=>Ho,ListChangedOptionsBaseSchema:()=>Ys,ListPromptsRequestSchema:()=>qs,ListPromptsResultSchema:()=>Ms,ListResourceTemplatesRequestSchema:()=>gs,ListResourceTemplatesResultSchema:()=>Ss,ListResourcesRequestSchema:()=>ms,ListResourcesResultSchema:()=>fs,ListRootsRequestSchema:()=>Pi,ListRootsResultSchema:()=>Ti,ListTasksRequestSchema:()=>ic,ListTasksResultSchema:()=>ac,ListToolsRequestSchema:()=>Js,ListToolsResultSchema:()=>Bs,LoggingLevelSchema:()=>Uo,LoggingMessageNotificationParamsSchema:()=>ei,LoggingMessageNotificationSchema:()=>Fr,ModelHintSchema:()=>ti,ModelPreferencesSchema:()=>ri,MultiSelectEnumSchemaSchema:()=>pi,NotificationSchema:()=>xe,NotificationsParamsSchema:()=>ke,NumberSchemaSchema:()=>Vr,PaginatedRequestParamsSchema:()=>ps,PaginatedRequestSchema:()=>Ut,PaginatedResultSchema:()=>Zt,PingRequestSchema:()=>Oo,PrimitiveSchemaDefinitionSchema:()=>Bo,ProgressNotificationParamsSchema:()=>ds,ProgressNotificationSchema:()=>No,ProgressSchema:()=>us,ProgressTokenSchema:()=>wo,PromptArgumentSchema:()=>Ns,PromptListChangedNotificationSchema:()=>Fs,PromptMessageSchema:()=>Zs,PromptReferenceSchema:()=>vi,PromptSchema:()=>As,ReadResourceRequestParamsSchema:()=>_s,ReadResourceRequestSchema:()=>bs,ReadResourceResultSchema:()=>ys,RelatedTaskMetadataSchema:()=>os,RequestIdSchema:()=>lt,RequestMetaSchema:()=>xo,RequestSchema:()=>pe,ResourceContentsSchema:()=>Ao,ResourceLinkSchema:()=>Dr,ResourceListChangedNotificationSchema:()=>vs,ResourceRequestParamsSchema:()=>Mr,ResourceSchema:()=>jo,ResourceTemplateReferenceSchema:()=>yi,ResourceTemplateSchema:()=>hs,ResourceUpdatedNotificationParamsSchema:()=>Is,ResourceUpdatedNotificationSchema:()=>Os,ResultMetaObjectSchema:()=>Po,ResultSchema:()=>he,RoleSchema:()=>Dt,RootSchema:()=>xi,RootsListChangedNotificationSchema:()=>Ei,SamplingContentSchema:()=>si,SamplingMessageContentBlockSchema:()=>ir,SamplingMessageSchema:()=>ii,ServerCapabilitiesSchema:()=>Co,ServerNotificationSchema:()=>mc,ServerRequestSchema:()=>hc,ServerResultSchema:()=>fc,ServerTasksCapabilitySchema:()=>Ya,SetLevelRequestParamsSchema:()=>Xs,SetLevelRequestSchema:()=>Qs,SingleSelectEnumSchemaSchema:()=>di,StringSchemaSchema:()=>Hr,SubscribeRequestParamsSchema:()=>zs,SubscribeRequestSchema:()=>ws,SubscriptionFilterSchema:()=>Lo,SubscriptionsAcknowledgedNotificationParamsSchema:()=>Es,SubscriptionsAcknowledgedNotificationSchema:()=>ks,SubscriptionsListenRequestParamsSchema:()=>Ps,SubscriptionsListenRequestSchema:()=>Ts,SubscriptionsListenResultMetaSchema:()=>$s,SubscriptionsListenResultSchema:()=>Cs,TaskAugmentedRequestParamsSchema:()=>ar,TaskCreationParamsSchema:()=>Qa,TaskMetadataSchema:()=>rs,TaskSchema:()=>Ft,TaskStatusNotificationParamsSchema:()=>$i,TaskStatusNotificationSchema:()=>tc,TaskStatusSchema:()=>ki,TextContentSchema:()=>jr,TextResourceContentsSchema:()=>qo,TitledMultiSelectEnumSchemaSchema:()=>Jo,TitledSingleSelectEnumSchemaSchema:()=>Fo,ToolAnnotationsSchema:()=>Hs,ToolChoiceSchema:()=>oi,ToolExecutionSchema:()=>Vs,ToolListChangedNotificationSchema:()=>Gs,ToolResultContentSchema:()=>ni,ToolSchema:()=>ur,ToolUseContentSchema:()=>Us,UnsubscribeRequestParamsSchema:()=>Rs,UnsubscribeRequestSchema:()=>xs,UntitledMultiSelectEnumSchemaSchema:()=>Vo,UntitledSingleSelectEnumSchemaSchema:()=>Do});var Gr=(e)=>To.safeParse(e).success,dg=(e)=>Eo.safeParse(e).success,en=(e)=>Ar.safeParse(e).success,tn=(e)=>qr.safeParse(e).success;var pg=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var Ru=(e)=>$o.safeParse(e).success,hg=(e)=>Io.safeParse(e).success;var hy="Mcp-Param-",Af="x-mcp-header",my=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,fy=new Set(["string","integer","boolean","number"]);function xu(e){let t=[],r=new Map,o=(i,s,a)=>{if(i===null||typeof i!=="object")return;let l=i;if(Af in l){if(!a||s.length===0)return`${zc(s)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let d=l[Af];if(typeof d!=="string"||d.length===0)return`${zc(s)}: x-mcp-header MUST be a non-empty string`;if(!my.test(d))return`${zc(s)}: 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||!fy.has(m))return`${zc(s)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${m??"<none>"}`;let f=d.toLowerCase(),g=r.get(f);if(g!==void 0)return`x-mcp-header '${d}' is not case-insensitively unique (also declared as '${g}')`;r.set(f,d),t.push({path:s,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,[...s,d],a);if(f!==void 0)return f}for(let d of gy){let m=l[d];if(m===void 0)continue;let f=Array.isArray(m)?m:m!==null&&typeof m==="object"&&Sy.has(d)?Object.values(m):[m];for(let g of f){let b=o(g,[...s,`<${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 gy=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],Sy=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function zc(e){return e.length===0?"<root>":e.join(".")}var mg="=?base64?",fg="?=";function _y(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 by(e){if(e.length===0)return!0;if(e.startsWith(mg)&&e.endsWith(fg))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 yy(e){let t=new TextEncoder().encode(e),r="";for(let o of t)r+=String.fromCodePoint(o);return btoa(r)}function Pu(e){return by(e)?`${mg}${yy(e)}${fg}`:e}function vy(e,t){let r=e;for(let o of t){if(r===null||typeof r!=="object")return;r=r[o]}return r}function gg(e,t){let r={};for(let o of e){let n=vy(t,o.path);if(n===void 0||n===null)continue;let i=_y(n);if(i===void 0)continue;r[`${hy}${o.headerName}`]=Pu(i)}return r}var Qo=-32020,tP=[{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:[Qo,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:[Qo],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:[Qo],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."}],rP={[W.ParseError]:400,[W.InvalidRequest]:400,[W.MethodNotFound]:404,[W.UnsupportedProtocolVersion]:400,[W.MissingRequiredClientCapability]:400,[Qo]:400},qf={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function Sg(e,t){let r=Object.hasOwn(qf,e)?qf[e]:void 0;if(r===void 0)return;let o=zy(t)?t[r]:void 0;return{field:r,value:typeof o==="string"?o:void 0}}function zy(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Pc(e,t){return Za(e,t)}function qi(e){return new Set(e.flatMap((t)=>Object.keys(t.shape)))}function hu(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 Mf=!1,mu="draft-2020-12";function wy(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:mu});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(!Mf)Mf=!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=La(e,{target:mu,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 _g(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 _g(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"||_g(o)))}return!1}function Ry(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 uu(e,t){let r=await e["~standard"].validate(t);if(r.issues&&r.issues.length>0)return{success:!1,error:r.issues.map((o)=>Ry(o)).join(", ")};return{success:!0,data:r.value}}function xy(e){let t=La(e,{target:mu,io:"input"});return typeof t.pattern==="string"?t.pattern:void 0}var Py=/\\\.\\d\{(\d+)\}/;function Ty(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((i)=>_o({local:o,offset:n,precision:i}))))}function Ey(e,t){let r;switch(e){case"email":r=[af()];break;case"uri":r=[Fa()];break;case"date":r=[tu()];break;case"date-time":r=Ty(t);break}return new Set(r.map((o)=>xy(o)).filter((o)=>o!==void 0))}function ky(e,t,r){if(r!=="zod")return!0;return Ey(e,t).has(t)}function Li(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function $y(e){try{return wy(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new re(W.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}var Cy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function Tu(e){return Cy.has(e)||e.startsWith("x-")}var Iy=new Set(["$schema",...Object.keys(Jr.shape.requestedSchema.shape)]),jf={string:qi([Hr,Do,Fo,Ho]),number:qi([Vr]),integer:qi([Vr]),boolean:qi([Zo]),array:qi([Vo,Jo])},Oy=new Set(Hr.shape.format.unwrap().options);function Ny(e,t,r,o){if(!Li(e))return e;let n=typeof e.type==="string"&&Object.hasOwn(jf,e.type)?jf[e.type]:void 0;if(n===void 0)return e;let i={};for(let[s,a]of Object.entries(e))if(n.has(s)||Tu(s))i[s]=a;else if(s==="pattern"&&e.type==="string"&&typeof e.format==="string"){if(!Oy.has(e.format))i[s]=a;else if(typeof a!=="string"||!ky(e.format,a,r))o.push(`${t}.${s}`)}else o.push(`${t}.${s}`);return i}function Ay(e,t){let r={},o=[];for(let[n,i]of Object.entries(e))if(n==="properties"&&Li(i))r[n]=Object.fromEntries(Object.entries(i).map(([s,a])=>[s,Ny(a,`properties.${s}`,t,o)]));else if(Iy.has(n))r[n]=i;else if(!Tu(n))o.push(n);if(o.length>0)throw new re(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}function qy(e,t){if(!Li(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!Pc(Bo,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}function fu(e,t,r=""){if(Array.isArray(e)&&Array.isArray(t))return e.flatMap((o,n)=>fu(o,t[n],`${r}[${n}]`));if(!Li(e)||!Li(t))return[];return Object.entries(e).flatMap(([o,n])=>{let i=r?`${r}.${o}`:o;if(!Object.prototype.hasOwnProperty.call(t,o))return Tu(o)?[]:[i];return fu(n,t[o],i)})}function My(e){if(!hu(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=Ay($y(e.requestedSchema),t),o=Pc(Jr.shape.requestedSchema,r);if(!o.success)throw new re(W.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${qy(r,o.error.message)}`);let n=fu(r,o.data);if(n.length>0)throw new re(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);let i=(o.data.required??[]).filter((s)=>!Object.prototype.hasOwnProperty.call(o.data.properties,s));if(i.length>0)throw new re(W.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function jy(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 oP=Object.assign(jy,{elicit(e){try{return{method:"elicitation/create",params:My(e)}}catch(t){throw t instanceof re?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 Ly=!0,Uy=10,Zy=250;function bg(e){return{autoFulfill:e?.autoFulfill??Ly,maxRounds:e?.maxRounds??Uy}}function Dy(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 Fy(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Hy(e,t){return new Promise((r,o)=>{if(t?.aborted){o(t.reason instanceof A?t.reason:new A(N.RequestTimeout,String(t.reason)));return}let n=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(n),o(t?.reason instanceof A?t.reason:new A(N.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",i,{once:!0})})}function Vy(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 Jy(e){let{config:t,method:r,originalParams:o,requestOptions:n,hooks:i,signal:s}=e,a=e.flowStartedAt??Date.now(),l=e.firstPayload,u=0;while(!0){if(u+=1,u>t.maxRounds)throw new A(N.InputRequiredRoundsExceeded,Fy(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=Vy(s);try{let y=await Promise.all(d.map(async([v,L])=>{try{return[v,await i.dispatchInputRequest(v,L,b.signal)]}catch(H){throw b.abort(H),H}}));m=Object.fromEntries(y)}finally{b.dispose()}}else await Hy(Zy,s);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 A(N.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:b});f.maxTotalTimeout=y}let g=await i.retry(Dy(o,m,l.requestState),f);if(pg(g)){l={inputRequests:g.inputRequests??{},...g.requestState!==void 0&&{requestState:g.requestState}};continue}return g}}var By=["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"],Wy={IdJagTokenExchangeResponseSchema:Ii,OAuthClientInformationFullSchema:Xo,OAuthClientInformationSchema:Ni,OAuthClientMetadataSchema:Oi,OAuthClientRegistrationErrorSchema:gc,OAuthErrorResponseSchema:Yo,OAuthMetadataSchema:Br,OAuthProtectedResourceMetadataSchema:Wo,OAuthTokenRevocationRequestSchema:Sc,OAuthTokensSchema:Go,OpenIdProviderDiscoveryMetadataSchema:Ko,OpenIdProviderMetadataSchema:Ci},yg={},vg={};function zg(e,t){let r=e.slice(0,-6);yg[r]=t,vg[r]=(o)=>t.safeParse(o).success}for(let e of By)zg(e,py[e]);for(let[e,t]of Object.entries(Wy))zg(e,t);var Ky=Object.freeze(yg),wg=Object.freeze(vg);function Gy(e){switch(e){case"initialize":case"notifications/initialized":return Ht(void 0);case"server/discover":return Ht(xc);default:return}}var Tc=60000,Yy=[Mt,vo,Or,zo],Xy=["inputResponses","requestState"];function Lf(e,t){let r=e.params;if(!ji(r))return{message:e,lifted:{}};let o=r._meta,n=ji(o)?Yy.filter((l)=>(l in o)):[],i=t==="request"?Xy.filter((l)=>(l in r)):[];if(n.length===0&&i.length===0)return{message:e,lifted:{}};let s={},a={...r};if(n.length>0&&ji(o)){let l={},u={...o};for(let d of n)l[d]=o[d],delete u[d];if(s.envelope=l,Object.keys(u).length>0)a._meta=u;else delete a._meta}for(let l of i){if(l==="inputResponses")s.inputResponses=a[l];if(l==="requestState")s.requestState=a[l];delete a[l]}return{message:{...e,params:a},lifted:s}}function Uf(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 Eu(e){return()=>e}var Qy=Eu(void 0),ev,Ec=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{ev=(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 A(N.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 A(N.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,i)=>{if(o?.(n,i),en(n)||tn(n))this._onresponse(n);else if(Gr(n))this._onrequest(n,i);else if(dg(n))this._onnotification(n,i);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 A(N.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}=Lf(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let s=Of(t.classification);if(s!==o.era){this._onerror(Error(`Era mismatch on inbound notification '${r.method}': classified as ${s} but this instance serves ${o.era}`));return}}if(lu(r.method)&&!o.hasNotificationMethod(r.method))return;let n=this._notificationHandlers.get(r.method),i=this.fallbackNotificationHandler;if(n===void 0&&i===void 0)return;Promise.resolve().then(()=>n===void 0?i(r):n(r,o)).catch((s)=>this._onerror(Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){let{message:r,lifted:o}=Lf(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 i=this._transport,s=(y,v,L)=>{let H={jsonrpc:"2.0",id:r.id,error:{code:y,message:v,...L!==void 0&&{data:L}}};i?.send(H).catch((x)=>this._onerror(Error(`Failed to send an error response: ${x}`)))};if(t?.classification!==void 0){let y=Of(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;s(W.UnsupportedProtocolVersion,`Unsupported protocol version: ${v}`,{supported:this._supportedProtocolVersions,requested:v});return}}if(cu(r.method)&&!n.hasRequestMethod(r.method)&&!(Nf(r.method)&&this._customSchemaRequestMethods.has(r.method))){s(W.MethodNotFound,"Method not found");return}let a=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(a===void 0){s(W.MethodNotFound,"Method not found");return}let l=n.checkInboundEnvelope(o);if(l!==void 0){s(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:tv(o.inputResponses),g={sessionId:i?.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?Qy:Eu(o.requestState),signal:m.signal,send:(y,v,L)=>{let H=this._resolveOutboundCodec(y.method);if(this._assertOutboundRequestInEra(H,y.method),hu(v))return d(y,v,L);let x=Uf(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(g,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}`)),s(W.InternalError,"Internal error");return}let L={result:v,jsonrpc:"2.0",id:r.id};await i?.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 i?.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 i=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(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),en(e))r(e);else r(re.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(hu(t)){if(!Nf(e.method))this._assertOutboundRequestInEra(o,e.method);return this._requestWithSchemaViaCodec(o,e,t,r)}this._assertOutboundRequestInEra(o,e.method);let n=Uf(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 Ht(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Gy(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(cu(t)&&!e.hasRequestMethod(t))throw new A(N.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:i,onresumptiontoken:s,headers:a}=o??{},l=Date.now(),u,d;return new Promise((m,f)=>{let g=(w)=>{f(w)};if(!this._transport){g(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(w){g(w);return}if(o?.signal?.aborted){let w=o.signal.reason;throw w instanceof A?w:new A(N.RequestTimeout,String(w))}let b=e.era===xc&&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),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:i,onresumptiontoken:s}).catch((D)=>this._onerror(Error(`Failed to send cancellation: ${D}`)))}else b.abort();f(w instanceof A?w:new A(N.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(sv(D));let Y={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:l,retry:(ue,$e)=>this._requestWithSchemaViaCodec(e,ue===void 0?{method:t.method}:{method:t.method,params:ue},r,$e)};return m(this._resolveNonCompleteResult(D,Y))}let Q=D.result;uu(r,Q).then((Y)=>{if(Y.success)m(Y.data);else f(new A(N.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??Tc,R=()=>x(new A(N.RequestTimeout,"Request timed out",{timeout:Z}));this._setupTimeout(y,Z,o?.maxTotalTimeout,R,o?.resetTimeoutOnProgress??!1),this._transport.send(L,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s,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 A(N.NotConnected,"Not connected");if(lu(t.method)&&!e.hasNotificationMethod(t.method))throw new A(N.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(!cu(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=(n,i)=>{let s=this._negotiatedWireCodec(),a=s.validateRequest(e,n);if(!a.ok&&a.reason==="not-in-era")a=s.validateInputRequest(e,n);if(!a.ok){if(a.reason==="not-in-era")throw new re(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(a.message)}return Promise.resolve(t(a.value,i))}}else if(r)o=async(n,i)=>{let s=await uu(t.params,{...n.params});if(!s.success)throw new re(W.InvalidParams,`Invalid params for ${e}: ${s.error}`);return r(s.data,i)};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(!lu(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 i=n.validateNotification(e,o);if(!i.ok){if(i.reason==="not-in-era")throw new re(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(i.message)}return Promise.resolve(t(i.value))});return}if(!r)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async(o)=>{let n=await uu(t.params,{...o.params});if(!n.success)throw new re(W.InvalidParams,`Invalid params for notification ${e}: ${n.error}`);await r(n.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function ji(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Rg(e,t){let r={...e};for(let o in t){let n=o,i=t[n];if(i===void 0)continue;let s=r[n];r[n]=ji(s)&&ji(i)?{...s,...i}:i}return r}function wc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function tv(e){let t={},r=[];if(!wc(e))return{accepted:t,droppedKeys:r};for(let[o,n]of Object.entries(e)){if(!wc(n)||"method"in n||"result"in n){r.push(o);continue}t[o]=n}return{accepted:t,droppedKeys:r}}function Zf(e){throw new A(N.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 rv(e,t,r,o,n){return{sessionId:n,mcpReq:{id:e,method:t,_meta:r?._meta,requestState:Eu(void 0),signal:o,send:()=>Zf("send"),notify:()=>Zf("notify")}}}async function ov(e,t,r,o,n){if(!wc(o)||typeof o.method!=="string")throw new A(N.InvalidResult,`Invalid input request '${r}': each inputRequests entry must be an embedded request object with a method`,{key:r});let i=o.method;if(!t.hasInputRequestMethod(i))throw new A(N.InvalidResult,`Invalid input request '${r}': '${i}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:r,method:i});let s=e.getRequestHandler(i);if(s===void 0)throw new A(N.CapabilityNotSupported,`Cannot fulfil input request '${r}': no handler is registered for '${i}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:r,method:i});let a=wc(o.params)?o.params:void 0;return await s({jsonrpc:"2.0",id:r,method:i,...a!==void 0&&{params:a}},e.buildContext(rv(r,i,a,n,e.sessionId)))}function nv(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 xg(e,t,r,o){let{codec:n,request:i,options:s,flowStartedAt:a}=o,l={inputRequests:r.inputRequests,...r.requestState!==void 0&&{requestState:r.requestState}},u={dispatchInputRequest:(d,m,f)=>ov(e,n,d,m,f),retry:(d,m)=>o.retry(d,nv(s,m))};return Jy({config:t,method:i.method,originalParams:i.params,firstPayload:l,flowStartedAt:a,signal:s?.signal,requestOptions:{...s?.timeout!==void 0&&{timeout:s.timeout},...s?.maxTotalTimeout!==void 0&&{maxTotalTimeout:s.maxTotalTimeout},...s?.onprogress!==void 0&&{onprogress:s.onprogress}},hooks:u})}function sv(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}/*!
66
66
  * content-type
67
67
  * Copyright(c) 2015 Douglas Christopher Wilson
68
68
  * MIT Licensed
69
- */var iv=fd((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"?i(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 s(d.toLowerCase());if(u!==-1){var f,g,b;t.lastIndex=u;while(g=t.exec(l)){if(g.index!==u)throw TypeError("invalid parameter format");if(u+=g[0].length,f=g[1].toLowerCase(),b=g[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 i(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 s(a){this.parameters=Object.create(null),this.type=a}}),av=Sd(iv(),1);function Pg(e){if(!e)return;try{return av.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();if(t===""||e.slice(t.length).includes(","))return;return t}}function Df(e){if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Array.isArray(e))return Object.fromEntries(e);return{...e}}function Tg(e=fetch,t){if(!t)return e;return async(r,o)=>e(r,{...t,...o,headers:o?.headers?{...Df(t.headers),...Df(o.headers)}:t.headers})}var cv=new Set([301,302,303,307,308]),lv=5;function uv(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 Eg(e,t){let r=cv.has(t.status)?t.headers?.get("location"):void 0;if(!r)return;try{return new URL(r,e)}catch{return}}var kg=new WeakSet;function $g(e){let t=(r,o)=>e(r,o);return kg.add(t),t}function Zi(e){if(kg.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 i=0;;i++){let s=await e(n,{...r,redirect:"manual"}),a=Eg(n,s);if(!a||i===lv)return s;let l=new URL(n),u=o==="GET"||s.status===307||s.status===308,d=!(a.username||a.password)||a.username===l.username&&a.password===l.password;if(!u||!d||!uv(l,a))return s;await s.text?.().catch(()=>{}),n=a}}}function Cg(e,t){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";let r=Eg(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 Di(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(!Di(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 i of o)if(!Di(e[i],t[i]))return!1;return!0}return e===t}function dt(e){return encodeURI(dv(e))}function dv(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var pv={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},hv={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},mv={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},fv=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 Yr(e,t=Object.create(null),r=fv,o=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let s=new URL(i,r.href);if(s.hash.length>1)t[s.href]=e;else if(s.hash="",o==="")r=s;else Yr(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 i=new URL(e.$ref,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=new URL(e.$recursiveRef,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=new URL("#"+e.$anchor,r.href);t[i.href]=e}for(let i in e){if(mv[i])continue;let s=`${o}/${dt(i)}`,a=e[i];if(Array.isArray(a)){if(pv[i]){let l=a.length;for(let u=0;u<l;u++)Yr(a[u],t,r,`${s}/${u}`)}}else if(hv[i])for(let l in a)Yr(a[l],t,r,`${s}/${dt(l)}`);else Yr(a,t,r,s)}return t}var gv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Sv=[0,31,28,31,30,31,30,31,31,30,31,30,31],_v=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,bv=/^(?=.{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,yv=/^(?:[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,vv=/^(?:(?:[^\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,zv=/^(?:(?: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,wv=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Rv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,xv=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Pv=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Tv=(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))},Ev=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,kv=/^((([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,$v=(e)=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function Et(e){return e.test.bind(e)}var Ig={date:Og,time:Ng.bind(void 0,!1),"date-time":Ov,duration:$v,uri:qv,"uri-reference":Et(yv),"uri-template":Et(vv),url:Et(zv),email:Tv,hostname:Et(bv),ipv4:Et(Ev),ipv6:Et(kv),regex:jv,uuid:Et(wv),"json-pointer":Et(Rv),"json-pointer-uri-fragment":Et(xv),"relative-json-pointer":Et(Pv)};function Cv(e){return e%4===0&&(e%100!==0||e%400===0)}function Og(e){let t=e.match(gv);if(!t)return!1;let r=+t[1],o=+t[2],n=+t[3];return o>=1&&o<=12&&n>=1&&n<=(o==2&&Cv(r)?29:Sv[o])}function Ng(e,t){let r=t.match(_v);if(!r)return!1;let o=+r[1],n=+r[2],i=+r[3],s=!!r[5];return(o<=23&&n<=59&&i<=59||o==23&&n==59&&i==60)&&(!e||s)}var Iv=/t|\s/i;function Ov(e){let t=e.split(Iv);return t.length==2&&Og(t[0])&&Ng(!0,t[1])}var Nv=/\/|:/,Av=/^(?:[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 qv(e){return Nv.test(e)&&Av.test(e)}var Mv=/[^\\]\\Z/;function jv(e){if(Mv.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function Lv(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 me(e,t,r="2019-09",o=Yr(t),n=!0,i=null,s="#",a="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};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:g,type:b,const:y,enum:v,required:L,not:H,anyOf:x,allOf:Z,oneOf:R,if:w,then:D,else:X,format:Y,properties:ue,patternProperties:$e,additionalProperties:oe,unevaluatedProperties:ae,minProperties:we,maxProperties:Ce,propertyNames:mt,dependentRequired:Me,dependentSchemas:Ye,dependencies:ft,prefixItems:Fe,items:Ie,additionalItems:It,unevaluatedItems:Ot,contains:gt,minContains:Pe,maxContains:Oe,minItems:Ne,maxItems:st,uniqueItems:gr,minimum:He,maximum:Ve,exclusiveMinimum:je,exclusiveMaximum:Xe,multipleOf:Qe,minLength:St,maxLength:_t,pattern:Yt,__absolute_ref__:bt,__absolute_recursive_ref__:Sr}=t,I=[];if(g===!0&&i===null)i=t;if(f==="#"){let V=i===null?o[Sr]:i,q=`${a}/$recursiveRef`,G=me(e,i===null?t:i,r,o,n,V,s,q,l);if(!G.valid)I.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:q,error:"A subschema had errors."},...G.errors)}if(m!==void 0){let V=o[bt||m];if(V===void 0){let O=`Unresolved $ref "${m}".`;if(bt&&bt!==m)O+=` Absolute URI "${bt}".`;throw O+=`
69
+ */var iv=fd((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"?i(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 s(d.toLowerCase());if(u!==-1){var f,g,b;t.lastIndex=u;while(g=t.exec(l)){if(g.index!==u)throw TypeError("invalid parameter format");if(u+=g[0].length,f=g[1].toLowerCase(),b=g[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 i(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 s(a){this.parameters=Object.create(null),this.type=a}}),av=Sd(iv(),1);function Pg(e){if(!e)return;try{return av.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();if(t===""||e.slice(t.length).includes(","))return;return t}}function Df(e){if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Array.isArray(e))return Object.fromEntries(e);return{...e}}function Tg(e=fetch,t){if(!t)return e;return async(r,o)=>e(r,{...t,...o,headers:o?.headers?{...Df(t.headers),...Df(o.headers)}:t.headers})}var cv=new Set([301,302,303,307,308]),lv=5;function uv(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 Eg(e,t){let r=cv.has(t.status)?t.headers?.get("location"):void 0;if(!r)return;try{return new URL(r,e)}catch{return}}var kg=new WeakSet;function $g(e){let t=(r,o)=>e(r,o);return kg.add(t),t}function Zi(e){if(kg.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 i=0;;i++){let s=await e(n,{...r,redirect:"manual"}),a=Eg(n,s);if(!a||i===lv)return s;let l=new URL(n),u=o==="GET"||s.status===307||s.status===308,d=!(a.username||a.password)||a.username===l.username&&a.password===l.password;if(!u||!d||!uv(l,a))return s;await s.text?.().catch(()=>{}),n=a}}}function Cg(e,t){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";let r=Eg(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 Di(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(!Di(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 i of o)if(!Di(e[i],t[i]))return!1;return!0}return e===t}function dt(e){return encodeURI(dv(e))}function dv(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var pv={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},hv={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},mv={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},fv=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 Yr(e,t=Object.create(null),r=fv,o=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let s=new URL(i,r.href);if(s.hash.length>1)t[s.href]=e;else if(s.hash="",o==="")r=s;else Yr(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 i=new URL(e.$ref,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=new URL(e.$recursiveRef,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=new URL("#"+e.$anchor,r.href);t[i.href]=e}for(let i in e){if(mv[i])continue;let s=`${o}/${dt(i)}`,a=e[i];if(Array.isArray(a)){if(pv[i]){let l=a.length;for(let u=0;u<l;u++)Yr(a[u],t,r,`${s}/${u}`)}}else if(hv[i])for(let l in a)Yr(a[l],t,r,`${s}/${dt(l)}`);else Yr(a,t,r,s)}return t}var gv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Sv=[0,31,28,31,30,31,30,31,31,30,31,30,31],_v=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,bv=/^(?=.{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,yv=/^(?:[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,vv=/^(?:(?:[^\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,zv=/^(?:(?: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,wv=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Rv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,xv=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Pv=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Tv=(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))},Ev=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,kv=/^((([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,$v=(e)=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function Et(e){return e.test.bind(e)}var Ig={date:Og,time:Ng.bind(void 0,!1),"date-time":Ov,duration:$v,uri:qv,"uri-reference":Et(yv),"uri-template":Et(vv),url:Et(zv),email:Tv,hostname:Et(bv),ipv4:Et(Ev),ipv6:Et(kv),regex:jv,uuid:Et(wv),"json-pointer":Et(Rv),"json-pointer-uri-fragment":Et(xv),"relative-json-pointer":Et(Pv)};function Cv(e){return e%4===0&&(e%100!==0||e%400===0)}function Og(e){let t=e.match(gv);if(!t)return!1;let r=+t[1],o=+t[2],n=+t[3];return o>=1&&o<=12&&n>=1&&n<=(o==2&&Cv(r)?29:Sv[o])}function Ng(e,t){let r=t.match(_v);if(!r)return!1;let o=+r[1],n=+r[2],i=+r[3],s=!!r[5];return(o<=23&&n<=59&&i<=59||o==23&&n==59&&i==60)&&(!e||s)}var Iv=/t|\s/i;function Ov(e){let t=e.split(Iv);return t.length==2&&Og(t[0])&&Ng(!0,t[1])}var Nv=/\/|:/,Av=/^(?:[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 qv(e){return Nv.test(e)&&Av.test(e)}var Mv=/[^\\]\\Z/;function jv(e){if(Mv.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function Lv(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 me(e,t,r="2019-09",o=Yr(t),n=!0,i=null,s="#",a="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};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:g,type:b,const:y,enum:v,required:L,not:H,anyOf:x,allOf:Z,oneOf:R,if:w,then:D,else:Q,format:Y,properties:ue,patternProperties:$e,additionalProperties:oe,unevaluatedProperties:ae,minProperties:we,maxProperties:Ce,propertyNames:mt,dependentRequired:Me,dependentSchemas:Ye,dependencies:ft,prefixItems:Fe,items:Ie,additionalItems:It,unevaluatedItems:Ot,contains:gt,minContains:Pe,maxContains:Oe,minItems:Ne,maxItems:st,uniqueItems:gr,minimum:He,maximum:Ve,exclusiveMinimum:je,exclusiveMaximum:Xe,multipleOf:Qe,minLength:St,maxLength:_t,pattern:Yt,__absolute_ref__:bt,__absolute_recursive_ref__:Sr}=t,I=[];if(g===!0&&i===null)i=t;if(f==="#"){let V=i===null?o[Sr]:i,q=`${a}/$recursiveRef`,G=me(e,i===null?t:i,r,o,n,V,s,q,l);if(!G.valid)I.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:q,error:"A subschema had errors."},...G.errors)}if(m!==void 0){let V=o[bt||m];if(V===void 0){let O=`Unresolved $ref "${m}".`;if(bt&&bt!==m)O+=` Absolute URI "${bt}".`;throw O+=`
70
70
  Known schemas:
71
71
  - ${Object.keys(o).join(`
72
- - `)}`,Error(O)}let q=`${a}/$ref`,G=me(e,V,r,o,n,i,s,q,l);if(!G.valid)I.push({instanceLocation:s,keyword:"$ref",keywordLocation:q,error:"A subschema had errors."},...G.errors);if(r==="4"||r==="7")return{valid:I.length===0,errors:I}}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)I.push({instanceLocation:s,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)I.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`})}else if(b!==void 0&&d!==b)I.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`});if(y!==void 0){if(d==="object"||d==="array"){if(!Di(e,y))I.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}else if(e!==y)I.push({instanceLocation:s,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)=>Di(e,V)))I.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}else if(!v.some((V)=>e===V))I.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}if(H!==void 0){let V=`${a}/not`;if(me(e,H,r,o,n,i,s,V).valid)I.push({instanceLocation:s,keyword:"not",keywordLocation:V,error:'Instance matched "not" schema.'})}let yt=[];if(x!==void 0){let V=`${a}/anyOf`,q=I.length,G=!1;for(let O=0;O<x.length;O++){let C=x[O],B=Object.create(l),J=me(e,C,r,o,n,g===!0?i:null,s,`${V}/${O}`,B);if(I.push(...J.errors),G=G||J.valid,J.valid)yt.push(B)}if(G)I.length=q;else I.splice(q,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:V,error:"Instance does not match any subschemas."})}if(Z!==void 0){let V=`${a}/allOf`,q=I.length,G=!0;for(let O=0;O<Z.length;O++){let C=Z[O],B=Object.create(l),J=me(e,C,r,o,n,g===!0?i:null,s,`${V}/${O}`,B);if(I.push(...J.errors),G=G&&J.valid,J.valid)yt.push(B)}if(G)I.length=q;else I.splice(q,0,{instanceLocation:s,keyword:"allOf",keywordLocation:V,error:"Instance does not match every subschema."})}if(R!==void 0){let V=`${a}/oneOf`,q=I.length,G=R.filter((O,C)=>{let B=Object.create(l),J=me(e,O,r,o,n,g===!0?i:null,s,`${V}/${C}`,B);if(I.push(...J.errors),J.valid)yt.push(B);return J.valid}).length;if(G===1)I.length=q;else I.splice(q,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:V,error:`Instance does not match exactly one subschema (${G} matches).`})}if(d==="object"||d==="array")Object.assign(l,...yt);if(w!==void 0){let V=`${a}/if`;if(me(e,w,r,o,n,i,s,V,l).valid){if(D!==void 0){let q=me(e,D,r,o,n,i,s,`${a}/then`,l);if(!q.valid)I.push({instanceLocation:s,keyword:"if",keywordLocation:V,error:'Instance does not match "then" schema.'},...q.errors)}}else if(X!==void 0){let q=me(e,X,r,o,n,i,s,`${a}/else`,l);if(!q.valid)I.push({instanceLocation:s,keyword:"if",keywordLocation:V,error:'Instance does not match "else" schema.'},...q.errors)}}if(d==="object"){if(L!==void 0){for(let O of L)if(!(O in e))I.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${O}".`})}let V=Object.keys(e);if(we!==void 0&&V.length<we)I.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${we} properties.`});if(Ce!==void 0&&V.length>Ce)I.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${Ce} properties.`});if(mt!==void 0){let O=`${a}/propertyNames`;for(let C in e){let B=`${s}/${dt(C)}`,J=me(C,mt,r,o,n,i,B,O);if(!J.valid)I.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:O,error:`Property name "${C}" does not match schema.`},...J.errors)}}if(Me!==void 0){let O=`${a}/dependantRequired`;for(let C in Me)if(C in e){let B=Me[C];for(let J of B)if(!(J in e))I.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:O,error:`Instance has "${C}" but does not have "${J}".`})}}if(Ye!==void 0)for(let O in Ye){let C=`${a}/dependentSchemas`;if(O in e){let B=me(e,Ye[O],r,o,n,i,s,`${C}/${dt(O)}`,l);if(!B.valid)I.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:C,error:`Instance has "${O}" but does not match dependant schema.`},...B.errors)}}if(ft!==void 0){let O=`${a}/dependencies`;for(let C in ft)if(C in e){let B=ft[C];if(Array.isArray(B)){for(let J of B)if(!(J in e))I.push({instanceLocation:s,keyword:"dependencies",keywordLocation:O,error:`Instance has "${C}" but does not have "${J}".`})}else{let J=me(e,B,r,o,n,i,s,`${O}/${dt(C)}`);if(!J.valid)I.push({instanceLocation:s,keyword:"dependencies",keywordLocation:O,error:`Instance has "${C}" but does not match dependant schema.`},...J.errors)}}}let q=Object.create(null),G=!1;if(ue!==void 0){let O=`${a}/properties`;for(let C in ue){if(!(C in e))continue;let B=`${s}/${dt(C)}`,J=me(e[C],ue[C],r,o,n,i,B,`${O}/${dt(C)}`);if(J.valid)l[C]=q[C]=!0;else if(G=n,I.push({instanceLocation:s,keyword:"properties",keywordLocation:O,error:`Property "${C}" does not match schema.`},...J.errors),G)break}}if(!G&&$e!==void 0){let O=`${a}/patternProperties`;for(let C in $e){let B=new RegExp(C,"u"),J=$e[C];for(let _e in e){if(!B.test(_e))continue;let _r=`${s}/${dt(_e)}`,vt=me(e[_e],J,r,o,n,i,_r,`${O}/${dt(C)}`);if(vt.valid)l[_e]=q[_e]=!0;else G=n,I.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:O,error:`Property "${_e}" matches pattern "${C}" but does not match associated schema.`},...vt.errors)}}}if(!G&&oe!==void 0){let O=`${a}/additionalProperties`;for(let C in e){if(q[C])continue;let B=`${s}/${dt(C)}`,J=me(e[C],oe,r,o,n,i,B,O);if(J.valid)l[C]=!0;else G=n,I.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:O,error:`Property "${C}" does not match additional properties schema.`},...J.errors)}}else if(!G&&ae!==void 0){let O=`${a}/unevaluatedProperties`;for(let C in e)if(!l[C]){let B=`${s}/${dt(C)}`,J=me(e[C],ae,r,o,n,i,B,O);if(J.valid)l[C]=!0;else I.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:O,error:`Property "${C}" does not match unevaluated properties schema.`},...J.errors)}}}else if(d==="array"){if(st!==void 0&&e.length>st)I.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${st}).`});if(Ne!==void 0&&e.length<Ne)I.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Ne}).`});let V=e.length,q=0,G=!1;if(Fe!==void 0){let O=`${a}/prefixItems`,C=Math.min(Fe.length,V);for(;q<C;q++){let B=me(e[q],Fe[q],r,o,n,i,`${s}/${q}`,`${O}/${q}`);if(l[q]=!0,!B.valid){if(G=n,I.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:O,error:"Items did not match schema."},...B.errors),G)break}}}if(Ie!==void 0){let O=`${a}/items`;if(Array.isArray(Ie)){let C=Math.min(Ie.length,V);for(;q<C;q++){let B=me(e[q],Ie[q],r,o,n,i,`${s}/${q}`,`${O}/${q}`);if(l[q]=!0,!B.valid){if(G=n,I.push({instanceLocation:s,keyword:"items",keywordLocation:O,error:"Items did not match schema."},...B.errors),G)break}}}else for(;q<V;q++){let C=me(e[q],Ie,r,o,n,i,`${s}/${q}`,O);if(l[q]=!0,!C.valid){if(G=n,I.push({instanceLocation:s,keyword:"items",keywordLocation:O,error:"Items did not match schema."},...C.errors),G)break}}if(!G&&It!==void 0){let C=`${a}/additionalItems`;for(;q<V;q++){let B=me(e[q],It,r,o,n,i,`${s}/${q}`,C);if(l[q]=!0,!B.valid)G=n,I.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:C,error:"Items did not match additional items schema."},...B.errors)}}}if(gt!==void 0)if(V===0&&Pe===void 0)I.push({instanceLocation:s,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Pe!==void 0&&V<Pe)I.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${V}) than minContains (${Pe}).`});else{let O=`${a}/contains`,C=I.length,B=0;for(let J=0;J<V;J++){let _e=me(e[J],gt,r,o,n,i,`${s}/${J}`,O);if(_e.valid)l[J]=!0,B++;else I.push(..._e.errors)}if(B>=(Pe||0))I.length=C;if(Pe===void 0&&Oe===void 0&&B===0)I.splice(C,0,{instanceLocation:s,keyword:"contains",keywordLocation:O,error:"Array does not contain item matching schema."});else if(Pe!==void 0&&B<Pe)I.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Pe} items matching schema. Only ${B} items were found.`});else if(Oe!==void 0&&B>Oe)I.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Oe} items matching schema. ${B} items were found.`})}if(!G&&Ot!==void 0){let O=`${a}/unevaluatedItems`;for(;q<V;q++){if(l[q])continue;let C=me(e[q],Ot,r,o,n,i,`${s}/${q}`,O);if(l[q]=!0,!C.valid)I.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:O,error:"Items did not match unevaluated items schema."},...C.errors)}}if(gr)for(let O=0;O<V;O++){let C=e[O],B=typeof C==="object"&&C!==null;for(let J=0;J<V;J++){if(O===J)continue;let _e=e[J];if(C===_e||B&&typeof _e==="object"&&_e!==null&&Di(C,_e))I.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${O} and ${J}.`}),O=Number.MAX_SAFE_INTEGER,J=Number.MAX_SAFE_INTEGER}}}else if(d==="number"){if(r==="4"){if(He!==void 0&&(je===!0&&e<=He||e<He))I.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${je?"or equal to ":""} ${He}.`});if(Ve!==void 0&&(Xe===!0&&e>=Ve||e>Ve))I.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Xe?"or equal to ":""} ${Ve}.`})}else{if(He!==void 0&&e<He)I.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${He}.`});if(Ve!==void 0&&e>Ve)I.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Ve}.`});if(je!==void 0&&e<=je)I.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${je}.`});if(Xe!==void 0&&e>=Xe)I.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Xe}.`})}if(Qe!==void 0){let V=e%Qe;if(Math.abs(0-V)>=0.00000011920929&&Math.abs(Qe-V)>=0.00000011920929)I.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Qe}.`})}}else if(d==="string"){let V=St===void 0&&_t===void 0?0:Lv(e);if(St!==void 0&&V<St)I.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${V} < ${St}).`});if(_t!==void 0&&V>_t)I.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${V} > ${_t}).`});if(Yt!==void 0&&!new RegExp(Yt,"u").test(e))I.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(Y!==void 0&&Ig[Y]&&!Ig[Y](e))I.push({instanceLocation:s,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${Y}".`})}return{valid:I.length===0,errors:I}}var Uv=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=Yr(e)}validate(e){return me(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){if(t)e={...e,$id:t};Yr(e,this.lookup)}},ku=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=yd(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){let t=new Uv(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 Ag=!0;var $u;$u=globalThis.crypto;async function Zv(e){return(await $u).getRandomValues(new Uint8Array(e))}async function Dv(e){let r=Math.pow(2,8)-Math.pow(2,8)%66,o="";while(o.length<e){let n=await Zv(e-o.length);for(let i of n)if(i<r)o+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[i%66]}return o}async function Fv(e){return await Dv(e)}async function Hv(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 Cu(e){if(!e)e=43;if(e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Fv(e),r=await Hv(t);return{code_verifier:t,code_challenge:r}}class kc 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 qg=10,Vv=13,Xr=32;function Iu(e){}function Lg(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=Iu,onError:r=Iu,onRetry:o=Iu,onComment:n,maxBufferSize:i}=e,s=[],a=0,l=!0,u,d="",m=0,f,g=!1;function b(R){if(g)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))),s.length===0){let X=v(R);X!==""&&(s.push(X),a=X.length),y();return}if(R.indexOf(`
72
+ - `)}`,Error(O)}let q=`${a}/$ref`,G=me(e,V,r,o,n,i,s,q,l);if(!G.valid)I.push({instanceLocation:s,keyword:"$ref",keywordLocation:q,error:"A subschema had errors."},...G.errors);if(r==="4"||r==="7")return{valid:I.length===0,errors:I}}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)I.push({instanceLocation:s,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)I.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`})}else if(b!==void 0&&d!==b)I.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`});if(y!==void 0){if(d==="object"||d==="array"){if(!Di(e,y))I.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}else if(e!==y)I.push({instanceLocation:s,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)=>Di(e,V)))I.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}else if(!v.some((V)=>e===V))I.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}if(H!==void 0){let V=`${a}/not`;if(me(e,H,r,o,n,i,s,V).valid)I.push({instanceLocation:s,keyword:"not",keywordLocation:V,error:'Instance matched "not" schema.'})}let yt=[];if(x!==void 0){let V=`${a}/anyOf`,q=I.length,G=!1;for(let O=0;O<x.length;O++){let C=x[O],B=Object.create(l),J=me(e,C,r,o,n,g===!0?i:null,s,`${V}/${O}`,B);if(I.push(...J.errors),G=G||J.valid,J.valid)yt.push(B)}if(G)I.length=q;else I.splice(q,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:V,error:"Instance does not match any subschemas."})}if(Z!==void 0){let V=`${a}/allOf`,q=I.length,G=!0;for(let O=0;O<Z.length;O++){let C=Z[O],B=Object.create(l),J=me(e,C,r,o,n,g===!0?i:null,s,`${V}/${O}`,B);if(I.push(...J.errors),G=G&&J.valid,J.valid)yt.push(B)}if(G)I.length=q;else I.splice(q,0,{instanceLocation:s,keyword:"allOf",keywordLocation:V,error:"Instance does not match every subschema."})}if(R!==void 0){let V=`${a}/oneOf`,q=I.length,G=R.filter((O,C)=>{let B=Object.create(l),J=me(e,O,r,o,n,g===!0?i:null,s,`${V}/${C}`,B);if(I.push(...J.errors),J.valid)yt.push(B);return J.valid}).length;if(G===1)I.length=q;else I.splice(q,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:V,error:`Instance does not match exactly one subschema (${G} matches).`})}if(d==="object"||d==="array")Object.assign(l,...yt);if(w!==void 0){let V=`${a}/if`;if(me(e,w,r,o,n,i,s,V,l).valid){if(D!==void 0){let q=me(e,D,r,o,n,i,s,`${a}/then`,l);if(!q.valid)I.push({instanceLocation:s,keyword:"if",keywordLocation:V,error:'Instance does not match "then" schema.'},...q.errors)}}else if(Q!==void 0){let q=me(e,Q,r,o,n,i,s,`${a}/else`,l);if(!q.valid)I.push({instanceLocation:s,keyword:"if",keywordLocation:V,error:'Instance does not match "else" schema.'},...q.errors)}}if(d==="object"){if(L!==void 0){for(let O of L)if(!(O in e))I.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${O}".`})}let V=Object.keys(e);if(we!==void 0&&V.length<we)I.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${we} properties.`});if(Ce!==void 0&&V.length>Ce)I.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${Ce} properties.`});if(mt!==void 0){let O=`${a}/propertyNames`;for(let C in e){let B=`${s}/${dt(C)}`,J=me(C,mt,r,o,n,i,B,O);if(!J.valid)I.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:O,error:`Property name "${C}" does not match schema.`},...J.errors)}}if(Me!==void 0){let O=`${a}/dependantRequired`;for(let C in Me)if(C in e){let B=Me[C];for(let J of B)if(!(J in e))I.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:O,error:`Instance has "${C}" but does not have "${J}".`})}}if(Ye!==void 0)for(let O in Ye){let C=`${a}/dependentSchemas`;if(O in e){let B=me(e,Ye[O],r,o,n,i,s,`${C}/${dt(O)}`,l);if(!B.valid)I.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:C,error:`Instance has "${O}" but does not match dependant schema.`},...B.errors)}}if(ft!==void 0){let O=`${a}/dependencies`;for(let C in ft)if(C in e){let B=ft[C];if(Array.isArray(B)){for(let J of B)if(!(J in e))I.push({instanceLocation:s,keyword:"dependencies",keywordLocation:O,error:`Instance has "${C}" but does not have "${J}".`})}else{let J=me(e,B,r,o,n,i,s,`${O}/${dt(C)}`);if(!J.valid)I.push({instanceLocation:s,keyword:"dependencies",keywordLocation:O,error:`Instance has "${C}" but does not match dependant schema.`},...J.errors)}}}let q=Object.create(null),G=!1;if(ue!==void 0){let O=`${a}/properties`;for(let C in ue){if(!(C in e))continue;let B=`${s}/${dt(C)}`,J=me(e[C],ue[C],r,o,n,i,B,`${O}/${dt(C)}`);if(J.valid)l[C]=q[C]=!0;else if(G=n,I.push({instanceLocation:s,keyword:"properties",keywordLocation:O,error:`Property "${C}" does not match schema.`},...J.errors),G)break}}if(!G&&$e!==void 0){let O=`${a}/patternProperties`;for(let C in $e){let B=new RegExp(C,"u"),J=$e[C];for(let _e in e){if(!B.test(_e))continue;let _r=`${s}/${dt(_e)}`,vt=me(e[_e],J,r,o,n,i,_r,`${O}/${dt(C)}`);if(vt.valid)l[_e]=q[_e]=!0;else G=n,I.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:O,error:`Property "${_e}" matches pattern "${C}" but does not match associated schema.`},...vt.errors)}}}if(!G&&oe!==void 0){let O=`${a}/additionalProperties`;for(let C in e){if(q[C])continue;let B=`${s}/${dt(C)}`,J=me(e[C],oe,r,o,n,i,B,O);if(J.valid)l[C]=!0;else G=n,I.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:O,error:`Property "${C}" does not match additional properties schema.`},...J.errors)}}else if(!G&&ae!==void 0){let O=`${a}/unevaluatedProperties`;for(let C in e)if(!l[C]){let B=`${s}/${dt(C)}`,J=me(e[C],ae,r,o,n,i,B,O);if(J.valid)l[C]=!0;else I.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:O,error:`Property "${C}" does not match unevaluated properties schema.`},...J.errors)}}}else if(d==="array"){if(st!==void 0&&e.length>st)I.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${st}).`});if(Ne!==void 0&&e.length<Ne)I.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Ne}).`});let V=e.length,q=0,G=!1;if(Fe!==void 0){let O=`${a}/prefixItems`,C=Math.min(Fe.length,V);for(;q<C;q++){let B=me(e[q],Fe[q],r,o,n,i,`${s}/${q}`,`${O}/${q}`);if(l[q]=!0,!B.valid){if(G=n,I.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:O,error:"Items did not match schema."},...B.errors),G)break}}}if(Ie!==void 0){let O=`${a}/items`;if(Array.isArray(Ie)){let C=Math.min(Ie.length,V);for(;q<C;q++){let B=me(e[q],Ie[q],r,o,n,i,`${s}/${q}`,`${O}/${q}`);if(l[q]=!0,!B.valid){if(G=n,I.push({instanceLocation:s,keyword:"items",keywordLocation:O,error:"Items did not match schema."},...B.errors),G)break}}}else for(;q<V;q++){let C=me(e[q],Ie,r,o,n,i,`${s}/${q}`,O);if(l[q]=!0,!C.valid){if(G=n,I.push({instanceLocation:s,keyword:"items",keywordLocation:O,error:"Items did not match schema."},...C.errors),G)break}}if(!G&&It!==void 0){let C=`${a}/additionalItems`;for(;q<V;q++){let B=me(e[q],It,r,o,n,i,`${s}/${q}`,C);if(l[q]=!0,!B.valid)G=n,I.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:C,error:"Items did not match additional items schema."},...B.errors)}}}if(gt!==void 0)if(V===0&&Pe===void 0)I.push({instanceLocation:s,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Pe!==void 0&&V<Pe)I.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${V}) than minContains (${Pe}).`});else{let O=`${a}/contains`,C=I.length,B=0;for(let J=0;J<V;J++){let _e=me(e[J],gt,r,o,n,i,`${s}/${J}`,O);if(_e.valid)l[J]=!0,B++;else I.push(..._e.errors)}if(B>=(Pe||0))I.length=C;if(Pe===void 0&&Oe===void 0&&B===0)I.splice(C,0,{instanceLocation:s,keyword:"contains",keywordLocation:O,error:"Array does not contain item matching schema."});else if(Pe!==void 0&&B<Pe)I.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Pe} items matching schema. Only ${B} items were found.`});else if(Oe!==void 0&&B>Oe)I.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Oe} items matching schema. ${B} items were found.`})}if(!G&&Ot!==void 0){let O=`${a}/unevaluatedItems`;for(;q<V;q++){if(l[q])continue;let C=me(e[q],Ot,r,o,n,i,`${s}/${q}`,O);if(l[q]=!0,!C.valid)I.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:O,error:"Items did not match unevaluated items schema."},...C.errors)}}if(gr)for(let O=0;O<V;O++){let C=e[O],B=typeof C==="object"&&C!==null;for(let J=0;J<V;J++){if(O===J)continue;let _e=e[J];if(C===_e||B&&typeof _e==="object"&&_e!==null&&Di(C,_e))I.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${O} and ${J}.`}),O=Number.MAX_SAFE_INTEGER,J=Number.MAX_SAFE_INTEGER}}}else if(d==="number"){if(r==="4"){if(He!==void 0&&(je===!0&&e<=He||e<He))I.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${je?"or equal to ":""} ${He}.`});if(Ve!==void 0&&(Xe===!0&&e>=Ve||e>Ve))I.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Xe?"or equal to ":""} ${Ve}.`})}else{if(He!==void 0&&e<He)I.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${He}.`});if(Ve!==void 0&&e>Ve)I.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Ve}.`});if(je!==void 0&&e<=je)I.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${je}.`});if(Xe!==void 0&&e>=Xe)I.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Xe}.`})}if(Qe!==void 0){let V=e%Qe;if(Math.abs(0-V)>=0.00000011920929&&Math.abs(Qe-V)>=0.00000011920929)I.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Qe}.`})}}else if(d==="string"){let V=St===void 0&&_t===void 0?0:Lv(e);if(St!==void 0&&V<St)I.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${V} < ${St}).`});if(_t!==void 0&&V>_t)I.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${V} > ${_t}).`});if(Yt!==void 0&&!new RegExp(Yt,"u").test(e))I.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(Y!==void 0&&Ig[Y]&&!Ig[Y](e))I.push({instanceLocation:s,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${Y}".`})}return{valid:I.length===0,errors:I}}var Uv=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=Yr(e)}validate(e){return me(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){if(t)e={...e,$id:t};Yr(e,this.lookup)}},ku=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=yd(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){let t=new Uv(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 Ag=!0;var $u;$u=globalThis.crypto;async function Zv(e){return(await $u).getRandomValues(new Uint8Array(e))}async function Dv(e){let r=Math.pow(2,8)-Math.pow(2,8)%66,o="";while(o.length<e){let n=await Zv(e-o.length);for(let i of n)if(i<r)o+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[i%66]}return o}async function Fv(e){return await Dv(e)}async function Hv(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 Cu(e){if(!e)e=43;if(e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Fv(e),r=await Hv(t);return{code_verifier:t,code_challenge:r}}class kc 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 qg=10,Vv=13,Xr=32;function Iu(e){}function Lg(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=Iu,onError:r=Iu,onRetry:o=Iu,onComment:n,maxBufferSize:i}=e,s=[],a=0,l=!0,u,d="",m=0,f,g=!1;function b(R){if(g)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))),s.length===0){let Q=v(R);Q!==""&&(s.push(Q),a=Q.length),y();return}if(R.indexOf(`
73
73
  `)===-1&&R.indexOf("\r")===-1){s.push(R),a+=R.length,y();return}s.push(R);let w=s.join("");s.length=0,a=0;let D=v(w);D!==""&&(s.push(D),a=D.length),y()}function y(){i!==void 0&&(a+d.length<=i||(g=!0,s.length=0,a=0,u=void 0,d="",m=0,f=void 0,r(new kc(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function v(R){let w=0;if(R.indexOf("\r")===-1){let D=R.indexOf(`
74
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(Mg(R,w,X)){let Y=R.charCodeAt(w+5)===Xr?w+6:w+5,ue=R.slice(Y,D);if(m===0&&R.charCodeAt(D+1)===qg){t({id:u,event:f,data:ue}),u=void 0,d="",f=void 0,w=D+2,D=R.indexOf(`
75
+ `,w);continue}let Q=R.charCodeAt(w);if(Mg(R,w,Q)){let Y=R.charCodeAt(w+5)===Xr?w+6:w+5,ue=R.slice(Y,D);if(m===0&&R.charCodeAt(D+1)===qg){t({id:u,event:f,data:ue}),u=void 0,d="",f=void 0,w=D+2,D=R.indexOf(`
76
76
  `,w);continue}d=m===0?ue:`${d}
77
- ${ue}`,m++}else jg(R,w,X)?f=R.slice(R.charCodeAt(w+6)===Xr?w+7:w+6,D)||void 0:L(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;L(R,w,Y),w=Y+1,R.charCodeAt(w-1)===Vv&&R.charCodeAt(w)===qg&&w++}return R.slice(w)}function L(R,w,D){if(w===D){x();return}let X=R.charCodeAt(w);if(Mg(R,w,X)){let we=R.charCodeAt(w+5)===Xr?w+6:w+5,Ce=R.slice(we,D);d=m===0?Ce:`${d}
80
- ${Ce}`,m++;return}if(jg(R,w,X)){f=R.slice(R.charCodeAt(w+6)===Xr?w+7:w+6,D)||void 0;return}if(X===105&&R.charCodeAt(w+1)===100&&R.charCodeAt(w+2)===58){let we=R.slice(R.charCodeAt(w+3)===Xr?w+4:w+3,D);we.includes("\x00")||(u=we);return}if(X===58){if(n){let we=R.slice(w,D);n(we.slice(R.charCodeAt(w+1)===Xr?2:1))}return}let Y=R.slice(w,D),ue=Y.indexOf(":");if(ue===-1){H(Y,"",Y);return}let $e=Y.slice(0,ue),oe=Y.charCodeAt(ue+1)===Xr?2:1,ae=Y.slice(ue+oe);H($e,ae,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 kc(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:D}));break;default:r(new kc(`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&&s.length>0){let w=s.join("");L(w,0,w.length)}l=!0,u=void 0,d="",m=0,f=void 0,s.length=0,a=0,g=!1}return{feed:b,reset:Z}}function Mg(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 jg(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 Ou extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:o}={}){let n;super({start(i){n=Lg({onEvent:(s)=>{i.enqueue(s)},onError(s){typeof e=="function"&&e(s),(e==="terminate"||s.type==="max-buffer-size-exceeded")&&i.error(s)},onRetry:t,onComment:r,maxBufferSize:o})},transform(i){n.feed(i)}})}}var Hi=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Ke(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 Ke(this,e)}constructor(e){super(e);this.name=new.target.name,Wr(this,new.target)}},Uu=class extends Hi{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}},Jv=class extends Hi{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}},Xg=class extends Hi{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}},Ic=class extends Hi{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}},Ug=class extends Hi{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 Zu(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 Qg(e.issuer,t)?e:void 0}function Qg(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function Bv(e){if(e==null)return!1;let t=e;return typeof t.tokens==="function"&&typeof t.clientInformation==="function"}async function Wv(e,t,r){let{resourceMetadataUrl:o,scope:n}=Fi(t.response);if(await Du(e,{serverUrl:t.serverUrl,resourceMetadataUrl:o,scope:n,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new kt}function Kv(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async(r)=>Wv(e,r,t)}}var kt=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Ke(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 Ke(this,e)}constructor(e){super(e??"Unauthorized");this.name="UnauthorizedError",Wr(this,new.target)}};function Hu(e){return e?.authorization_response_iss_parameter_supported===!0}function Vu({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t===void 0)return;if(e===void 0){if(r)throw new Uu("authorization_response",t,void 0);return}if(e!==t)throw new Uu("authorization_response",t,e)}function Nu(...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 Gv(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 Yv(e,t,r,o,n){if(typeof e==="string")return{authorizationCode:e,iss:t};let i=e.get("iss")??void 0,s=e.get("code");if(s)return{authorizationCode:s,iss:i};let a=(await r.discoveryState?.())?.authorizationServerMetadata;if(!a)try{a=(await nS(o,n)).authorizationServerMetadata}catch{a=void 0}if(!a)throw new kt("Authorization callback failed and the issuer could not be verified");Vu({iss:i,expectedIssuer:a.issuer,issParameterSupported:Hu(a)});let l=e.get("error");if(l)throw new Kr(l,e.get("error_description")??l,e.get("error_uri")??void 0);throw new kt("Authorization callback contained neither `code` nor `error`")}function Xv(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var Au="code",qu="S256";function Qv(e,t){let r=e.client_secret!==void 0;if("token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Xv(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 ez(e,t,r,o){let{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":tz(n,i,r);return;case"client_secret_post":rz(n,i,o);return;case"none":oz(n,o);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function tz(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 rz(e,t,r){if(r.set("client_id",e),t)r.set("client_secret",t)}function oz(e,t){t.set("client_id",e)}function eS(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function nz(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!eS(t.hostname))throw new Xg(t.href);return t}function sz(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(eS(r.hostname))return"native"}return"web"}function iz(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??sz(t.redirect_uris)}}async function Zg(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Yo.parse(JSON.parse(r));return Kr.fromResponse(o)}catch(o){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Kr(Vt.ServerError,n)}}function Dg(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 Du(e,t){try{return await Mu(e,t)}catch(r){if(r instanceof Kr){if(r.code===Vt.InvalidClient||r.code===Vt.UnauthorizedClient)return Dg(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Mu(e,t);else if(r.code===Vt.InvalidGrant||r.code===Vt.InvalidDpopProof)return Dg(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await Mu(e,t)}throw r}}function az(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:n}=e,i=t||r?.scopes_supported?.join(" ")||n.scope;if(i&&o?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&n.grant_types?.includes("refresh_token"))i=`${i} offline_access`;return i}async function Mu(e,{serverUrl:t,authorizationCode:r,iss:o,scope:n,resourceMetadataUrl:i,fetchFn:s,skipIssuerMetadataValidation:a,forceReauthorization:l}){let u=iz(e),d=await e.discoveryState?.(),m,f,g,b,y=i;if(!y&&d?.resourceMetadataUrl)y=new URL(d.resourceMetadataUrl);if(d?.authorizationServerUrl){if(f=d.authorizationServerUrl,m=d.resourceMetadata,g=d.authorizationServerMetadata??await oS(f,{fetchFn:s,skipIssuerValidation:a}),!m)try{m=await tS(t,{resourceMetadataUrl:y},s)}catch(oe){if(oe instanceof TypeError)throw oe}if(g!==d.authorizationServerMetadata||m!==d.resourceMetadata)await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:g})}else{let oe=await nS(t,{resourceMetadataUrl:y,fetchFn:s,skipIssuerMetadataValidation:a});f=oe.authorizationServerUrl,g=oe.authorizationServerMetadata,m=oe.resourceMetadata,b={authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:g}}let v=g?.issuer??String(f),L={issuer:v};if(await e.saveAuthorizationServerUrl?.(v),r!==void 0){let oe=d?.authorizationServerMetadata?.issuer??d?.authorizationServerUrl;if(oe===void 0){if(e.saveDiscoveryState!==void 0)throw new Ic("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(!Qg(oe,v))throw new Ic(oe,v)}if(b)await e.saveDiscoveryState?.(b);let H=await lz(t,e,m),x=H&&m&&!e.validateResourceURL?m.resource:H;if(x)await e.saveResourceUrl?.(Ju(x));let Z=az({requestedScope:n,resourceMetadata:m,authServerMetadata:g,clientMetadata:e.clientMetadata}),R=await Promise.resolve(e.clientInformation(L)),w=Zu(R,v,{canPersistStamp:e.saveClientInformation!==void 0});if(w===void 0&&R?.issuer&&e.saveClientInformation===void 0)throw new Ic(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 oe=g?.client_id_metadata_document_supported===!0,ae=e.clientMetadataUrl;if(ae&&!cz(ae))throw new Kr(Vt.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ae}`);if(oe&&ae)w={client_id:ae,issuer:v},await e.saveClientInformation?.(w,L);else{if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");w={...await bz(f,{metadata:g,clientMetadata:u,scope:Z,fetchFn:s}),issuer:v},await e.saveClientInformation(w,L)}}let D=!e.redirectUrl;if(r!==void 0||D){if(r!==void 0)Vu({iss:o,expectedIssuer:g?.issuer,issParameterSupported:Hu(g)});let oe=await _z(e,f,{metadata:g,resource:x,authorizationCode:r,iss:o,scope:Z,fetchFn:s});return await e.saveTokens({...oe,issuer:v},L),"AUTHORIZED"}let X=Zu(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 oe;try{oe=await Sz(f,{metadata:g,clientInformation:w,refreshToken:X.refresh_token,resource:x,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:s})}catch(ae){if(ae instanceof Xg)throw ae;if(!(ae instanceof Kr)||ae.code===Vt.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(ae instanceof Error?ae.message:String(ae))}`);else throw ae}if(oe)return await e.saveTokens({...oe,issuer:v},L),"AUTHORIZED"}let Y=e.state?await e.state():void 0,{authorizationUrl:ue,codeVerifier:$e}=await fz(f,{metadata:g,clientInformation:w,state:Y,redirectUrl:e.redirectUrl,scope:Z,resource:x});return await e.saveCodeVerifier($e),await e.redirectToAuthorization(ue),"REDIRECT"}function cz(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function lz(e,t,r){let o=Ff(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(!r)return;if(!Hf({requestedResource:o,configuredResource:r.resource}))throw Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}var uz=new Set(["bearer","dpop"]);function Fi(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!uz.has(r.toLowerCase())||!o)return{};let n=$c(e,"resource_metadata")||void 0,i;if(n)try{i=new URL(n)}catch{}let s=$c(e,"scope")||void 0,a=$c(e,"error")||void 0,l=$c(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:s,error:a,errorDescription:l}}function $c(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 i=n[1]||n[2];if(i)return i}return null}async function tS(e,t,r=fetch){let o=await hz(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 Wo.parse(await o.json())}async function rS(e,t,r=fetch){let o=Zi(r);try{return await o(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!Ag)throw n;if(t)try{return await o(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}function dz(e,t="",r={}){if(t.endsWith("/"))t=t.slice(0,-1);return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Fg(e,t,r=fetch){return await rS(e,{"MCP-Protocol-Version":t},r)}function pz(e,t){if(!e)return!0;if(t==="/")return!1;return!e.ok&&e.status<500||e.status===502}async function hz(e,t,r,o){let n=new URL(e),i=o?.protocolVersion??yo,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let l=dz(t,n.pathname);s=new URL(l,o?.metadataServerUrl??n),s.search=n.search}let a=await Fg(s,i,r);if(!o?.metadataUrl&&pz(a,n.pathname))a=await Fg(new URL(`/.well-known/${t}`,n),i,r);return a}function mz(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 oS(e,{fetchFn:t=fetch,protocolVersion:r=yo,skipIssuerValidation:o=!1}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},i=mz(e);for(let{url:s,type:a}of i){let l=await rS(s,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 ${s}`)}let u=a==="oauth"?Br.parse(await l.json()):Ko.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 Uu("metadata",d,u.issuer)}return u}}async function nS(e,t){let r,o;try{if(r=await tS(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0)o=r.authorization_servers[0]}catch(i){if(i instanceof TypeError)throw i}if(!o)o=String(new URL("/",e));let n=await oS(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function Ju(e){return typeof e==="string"?e:e.href}async function fz(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:i,resource:s}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Au))throw Error(`Incompatible auth server: does not support response type ${Au}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(qu))throw Error(`Incompatible auth server: does not support code challenge method ${qu}`)}else a=new URL("/authorize",e);let l=await Cu(),{code_verifier:u,code_challenge:d}=l;if(a.searchParams.set("response_type",Au),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",qu),a.searchParams.set("redirect_uri",String(o)),i)a.searchParams.set("state",i);if(n)a.searchParams.set("scope",n);if(n?.split(" ").includes("offline_access"))a.searchParams.append("prompt","consent");if(s)a.searchParams.set("resource",Ju(s));return{authorizationUrl:a,codeVerifier:u}}function gz(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function sS(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:i,dpop:s,fetchFn:a}){let l=nz(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i)r.set("resource",Ju(i));if(!n&&o)ez(Qv(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let d=async()=>{let g=new Headers(u);if(n)await n(g,r,l,t);if(s)g.set("DPoP",await s.buildProof({htm:"POST",htu:l}));return Zi(a??fetch)(l,{method:"POST",headers:g,body:r})},m=await d();if(s&&m.status===400){if((await m.clone().json().catch(()=>{}))?.error===Vt.UseDpopNonce)s.observeNonce(m,l),m=await d()}if(s?.observeNonce(m,l),!m.ok)throw await Zg(m);let f=await m.json();try{return Go.parse(gu(f))}catch(g){if(typeof f==="object"&&f!==null&&"error"in f)throw await Zg(JSON.stringify(f));throw g}}async function Sz(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:i,dpop:s,fetchFn:a}){return{refresh_token:o,...await sS(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:i,resource:n,dpop:s,fetchFn:a})}}async function _z(e,t,{metadata:r,resource:o,authorizationCode:n,iss:i,scope:s,fetchFn:a}={}){if(n!==void 0)Vu({iss:i,expectedIssuer:r?.issuer,issParameterSupported:Hu(r)});let l=r?.issuer??String(t),u=async()=>{let g=await e.clientInformation({issuer:l}),b=Zu(g,l,{canPersistStamp:!1});if(g&&b===void 0)throw new Ic(String(g.issuer),l);return b},d=await u(),m=s??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=gz(n,await e.codeVerifier(),e.redirectUrl)}return d??=await u(),sS(t,{metadata:r,tokenRequestParams:f,clientInformation:d,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:a})}async function bz(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:n}){let i;if(t){if(!t.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let s={...r,...o===void 0?{}:{scope:o}},a=await Zi(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok)throw new Jv({status:a.status,body:await a.text(),submittedMetadata:s});return Xo.parse(gu(await a.json()))}var Cc=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),yz=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(ju(e))}set(e,t){let r=ju(e),o=Cc.has(e.method),n=!this._entries.has(r);if(!o&&n&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let s of this._entries.keys())if(!Cc.has(s.slice(0,s.indexOf("\x00")))){this._entries.delete(s),this._cappedSize--;break}}let i=++this._stamp;if(this._entries.set(r,{...t,stamp:i}),n&&!o)this._cappedSize++;return i}delete(e){if(this._entries.delete(ju(e))&&!Cc.has(e.method))this._cappedSize--}evict(e){let t=`${e}\x00`,r=Cc.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 ju(e){return`${e.method}\x00${JSON.stringify([e.partition??"",e.params??""])}`}function Lu(e,t){return t===void 0?e:`${e}\x00${t}`}var vz=86400000,zz=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 i=this._partitionFor("public");if(i===o)return;let s=await this._store.get({...r,partition:i});return s?.scope==="public"?s:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){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=Lu(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=Lu(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(Lu(e,o?.params))??0)!==r)return;let n=o?.params??"",i=this._partitionFor("private"),s=this._partitionFor("public"),a=(o?.scope??"private")==="public"?s:i;try{await this._store.set({method:e,params:n,partition:a},{value:wz(t),expiresAt:o?.expiresAt,scope:o?.scope})}catch(l){this._reportError(l)}if(s!==i)try{await this._store.delete({method:e,params:n,partition:a===i?s:i})}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 i of o.tools){let s=t(i);if(s!==void 0)n.set(i.name,s)}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 wz(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 iS=Symbol.for("mcp.authSeamEscape");function tt(e){if(typeof e==="object"&&e!==null||typeof e==="function")try{Object.defineProperty(e,iS,{value:!0,configurable:!0})}catch{}return e}function Rz(e){return(typeof e==="object"&&e!==null||typeof e==="function")&&e[iS]===!0}var xz=-32022,Pz=new Set([-32001,-32020,-32021]);function Tz(e,t){switch(e.kind){case"result":return Ez(e.result,t);case"rpc-error":return aS(e,t);case"http-error":return kz(e,t);case"network-error":return Hg(e.error,t);case"unusable-reply":return{kind:"error",error:new A(N.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${cS(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 Hg(Error("Connection closed during the version negotiation probe"),t);case"timeout":if(t.transportKind==="stdio")return{kind:"legacy"};return{kind:"error",error:new A(N.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function Ez(e,t){let r=Ht(xc).validateResult("server/discover",e);if(!r.ok)return{kind:"legacy"};let o=r.value.supportedVersions,n=t.clientModernVersions.find((i)=>o.includes(i));if(n!==void 0)return{kind:"modern",version:n,discover:r.value};if(t.fallbackAvailable)return{kind:"legacy"};return{kind:"error",error:new Rc({supported:[...o],requested:t.requestedVersion})}}function aS(e,t){let{code:r,message:o,data:n}=e;if(r===xz){let i=Cz(n);if(i===void 0)return{kind:"legacy"};let s=new Rc({supported:i,requested:Iz(n)??t.requestedVersion},o),a=Ui(i),l=t.clientModernVersions.find((u)=>a.includes(u));if(l!==void 0)return{kind:"corrective",version:l,error:s};if(a.length>0)return{kind:"error",error:s};return t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:s}}if(Pz.has(r))return{kind:"legacy"};return{kind:"legacy"}}function kz(e,t){if(e.status===401||e.status===403){let o=e.status===403;return{kind:"error",error:new Tt(o?N.ClientHttpForbidden:N.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 Tt(N.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let r=Oz(e.body);if(r!==void 0)return aS(r,t);return{kind:"legacy"}}function Hg(e,t){if(t.environment==="browser"&&$z(e))return{kind:"legacy"};return{kind:"error",error:new A(N.EraNegotiationFailed,`Version negotiation probe failed: ${cS(e)}`,{cause:e},{cause:e})}}function $z(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function cS(e){return e instanceof Error?e.message:String(e)}function Cz(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 Iz(e){if(typeof e!=="object"||e===null)return;let t=e.requested;return typeof t==="string"?t:void 0}function Oz(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:i}=r;if(typeof o!=="number")return;return{code:o,message:typeof n==="string"?n:"",data:i}}var Nz="legacy";function Az(e,t){let r=e?.mode??Nz;if(r==="legacy")return{kind:"legacy"};let o=e?.probe??{};if(typeof r==="object"){if(!Jt(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?Ui(t):[];return{kind:"auto",modernVersions:n.length>0?n:[...Su],fallbackAvailable:t?_u(t).length>0:!0,probe:o}}function Vg(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function Jg(e){return"stderr"in e&&"pid"in e?"stdio":"http"}var qz=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&&(en(o)||tn(o))&&o.id===n.id){if(r._pending=void 0,en(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 i=!1,s=(l)=>{if(i)return;if(i=!0,clearTimeout(a),this._pending?.id===o)this._pending=void 0;n(l)},a=setTimeout(()=>s({kind:"timeout"}),r);this._pending={id:o,resolve:s},this._transport.send(t(o)).catch((l)=>s({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,Fu.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)}}},Fu=new WeakMap;function Bg(e){let t=Fu.get(e);Fu.delete(e),t?.()}function Mz(e,t,r,o){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:Ht(t).outboundEnvelope({protocolVersion:t,clientInfo:r,clientCapabilities:o})}}}function jz(e){if(e instanceof A&&e.code===N.ClientHttpUnexpectedContent)return!0;return e instanceof Error&&e.name==="SyntaxError"}function Lz(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(Rz(r)||r instanceof kt||r instanceof Error&&r.name==="UnauthorizedError")return{kind:"auth-required",error:r};if(r instanceof Tt){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(jz(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 lS(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,i=e.kind==="auto"&&e.fallbackAvailable,s=await qz.open(t.transport),a=async()=>{let u=n[0],d=!1,m=o;for(;;){let f=await s.exchange((y)=>Mz(y,u,t.clientInfo,t.capabilities),r);if(f.kind==="timeout"&&m>0){m--;continue}let g=Lz(f,r),b=Tz(g,{clientModernVersions:n,requestedVersion:u,fallbackAvailable:i,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=g.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new A(N.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 A(N.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 A(N.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 s.detach(),u}return s.release(),l}function Uz(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 Zz(e,t,r,o){let i=new t.constructor({...r,stderr:"ignore"}),s=t.close,a=!1,l,u=new Promise((m,f)=>{l=()=>f(Wg())});t.close=async function(){return a=!0,l?.(),s.call(t)};let d;try{let m=lS(e,{...o,transport:i,transportKind:"stdio",disposableProbe:!0});m.catch(()=>{}),d=await Promise.race([m,u])}finally{await Dz(i),t.close=s}if(a)throw Wg();return d}function Wg(){return new A(N.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function Dz(e){try{let t=e._dispose;await(typeof t==="function"?t.call(e):e.close())}catch{}}function Kg(e){let t=e._meta?.[jt];return wg.Implementation(t)?t:void 0}function Oc(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 i=o[n];if(r[n]===void 0&&Object.prototype.hasOwnProperty.call(i,"default"))r[n]=i.default;if(r[n]!==void 0)Oc(i,r[n])}}if(Array.isArray(e.anyOf)){for(let r of e.anyOf)if(typeof r!=="boolean")Oc(r,t)}if(Array.isArray(e.oneOf)){for(let r of e.oneOf)if(typeof r!=="boolean")Oc(r,t)}}function Fz(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 Hz(e){if(typeof e==="object"&&e!==null){if(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e))return e;if(e.kind==="modern"&&lr.safeParse(e.discover).success)return e}throw new A(N.EraNegotiationFailed,"connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }")}var Gg={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},Vz=64,uS=class extends Ec{_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 A(N.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 ku,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=bg(t?.inputRequired),this._cache=new zz(t?.responseCacheStore??new yz,t?.responseCacheStore!==void 0,(r)=>this._reportStoreError(r),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??Vz,t?.listChanged)this._listChangedConfig=t.listChanged}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&Jt(this._negotiatedProtocolVersion)&&Gr(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 A(N.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 xg({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=Rg(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=Ht(this._negotiatedProtocolVersion),i=n.validateRequest("elicitation/create",r);if(!i.ok&&i.reason==="not-in-era")i=n.validateInputRequest("elicitation/create",r);if(!i.ok)throw new re(i.reason==="not-in-era"?W.InternalError:W.InvalidParams,i.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${i.message}`);let{params:s}=i.value;s.mode=s.mode??"form";let{supportsFormMode:a,supportsUrlMode:l}=Fz(this._capabilities.elicitation);if(s.mode==="form"&&!a)throw new re(W.InvalidParams,"Client does not support form-mode elicitation requests");if(s.mode==="url"&&!l)throw new re(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 re(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=s.mode==="form"?s.requestedSchema:void 0;if(s.mode==="form"&&m.action==="accept"&&m.content&&f&&this._capabilities.elicitation?.form?.applyDefaults)try{Oc(f,m.content)}catch{}return m};if(e==="sampling/createMessage")return async(r,o)=>{let n=Ht(this._negotiatedProtocolVersion),i=n.validateRequest("sampling/createMessage",r);if(!i.ok&&i.reason==="not-in-era")i=n.validateInputRequest("sampling/createMessage",r);if(!i.ok)throw new re(i.reason==="not-in-era"?W.InternalError:W.InvalidParams,i.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${i.message}`);let{params:s}=i.value,a=await t(r,o),l=Boolean(s.tools||s.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 re(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 A(N.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,Hz(t.prior),t);let r=Az(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=_u(this._supportedProtocolVersions);try{let o=r[0];if(o===void 0)throw new A(N.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=Jg(e),i={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:Vg(),defaultTimeoutMs:r?.timeout??Tc},s=n==="stdio"?Uz(e):void 0;o=s===void 0?await lS(t,{...i,transport:e,transportKind:n}):await Zz(t,e,s,i)}catch(n){throw await e.close().catch(()=>{}),Bg(e),n}if(Bg(e),await super.connect(e),o.era==="legacy"){await this._legacyHandshake(e,r);return}if(this._serverCapabilities=o.discover.capabilities,this._serverVersion=Kg(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,i=this._serverCapabilities,s={...n.tools&&i?.tools?.listChanged&&{tools:n.tools},...n.prompts&&i?.prompts?.listChanged&&{prompts:n.prompts},...n.resources&&i?.resources?.listChanged&&{resources:n.resources}},a=!0;try{this._setupListChangedHandlers(s)}catch(u){a=!1,this.onerror?.(u instanceof Error?u:Error(String(u)))}let l=a?{...s.tools&&{toolsListChanged:!0},...s.prompts&&{promptsListChanged:!0},...s.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,i=(n&&Ui(n).length>0?Ui(n):Su).find((s)=>o.supportedVersions.includes(s));if(i===void 0)throw new A(N.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=Kg(o),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.instructions,this._negotiatedProtocolVersion=i,e.setProtocolVersion?.(i),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(s){this.onerror?.(s instanceof Error?s:Error(String(s)))}}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 Jt(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new A(N.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new A(N.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 A(N.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new A(N.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new A(N.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new A(N.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 A(N.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 A(N.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new A(N.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new A(N.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"},lr,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 i=r?.cacheMode==="bypass",s=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 A(N.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),i)return a;return await this._cache.write(e,a,s,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),vz),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 A?n:new A(N.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:xu(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 i=this._freshness(n,e.uri);if(i.expiresAt>this._cache.now())await this._cache.write("resources/read",n,o,i);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 A(N.NotConnected,"Not connected");let r=this._negotiatedProtocolVersion;if(r===void 0||!Jt(r))throw new A(N.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 A?x:new A(N.RequestTimeout,String(x))}let o=new AbortController,n=`listen:${this._nextListenId++}`,i="opening",s,a,l,u,d=new Promise((x,Z)=>{l=x,u=Z}),m,f=new Promise((x)=>{m=x}),g=(x)=>{if(i==="closed")return;let Z=i==="opening";if(s!==void 0)clearTimeout(s),s=void 0;if("ack"in x){i="open",l(x.ack);return}if(i="closed",a!==void 0)t?.signal?.removeEventListener("abort",a);if(this._listenState.delete(n),o.abort(),m(x.cause),Z)u(x.error??new A(N.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(i==="closed")return;g({cause:"local"}),await b()};this._listenState.set(n,{settle:g});let v=t?.timeout??Tc;if(s=setTimeout(()=>{g({cause:"remote",error:new A(N.RequestTimeout,"subscriptions/listen ack timed out",{timeout:v})}),b().catch(()=>{})},v),t?.signal){let x=t.signal;a=()=>{if(i==="closed")return;let Z=x.reason;g({cause:"local",error:Z instanceof Error?Z:Error(String(Z??"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}},H=(x)=>{g({cause:"remote",error:x instanceof Error?x:Error(String(x))})};try{this.transport.send(L,{requestSignal:o.signal,onRequestStreamEnd:()=>g({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(Gg,e.method)?Gg[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?.[ts],n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){let i=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);n.settle({ack:i.ok?i.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(tn(e))r.settle({cause:"remote",error:re.fromError(e.error.code,e.error.message,e.error.data)});else r.settle({cause:"graceful",error:new A(N.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new A(N.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"&&Vg()!=="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=gg(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),i=()=>{if(n===void 0||n.ok)return;let l=n.compileError,u=(l instanceof Error?l.message:String(l)).slice(0,200);throw new re(W.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${u}`)};i();let s;try{s=await this.request({method:"tools/call",params:e},await o())}catch(l){let u=l instanceof re&&l.code===Qo;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)),i(),s=await this.request({method:"tools/call",params:e},await o())}let a=n!==void 0&&n.ok?n.validator:void 0;if(a){if(s.structuredContent===void 0&&!s.isError)throw new re(W.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent!==void 0&&!s.isError)try{let l=a(s.structuredContent);if(!l.valid)throw new re(W.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)}catch(l){if(l instanceof re)throw l;throw new re(W.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)}}return s}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){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||Jg(this.transport)==="stdio")return;let t=e.tools.filter((r)=>{let o=xu(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=Pc(Ys,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:i,debounceMs:s}=n.data,{onChanged:a}=r,l=async()=>{if(!i){a(null,null);return}try{a(null,await o())}catch(d){a(d instanceof Error?d:Error(String(d)),null)}},u=()=>{if(s){let d=this._listChangedDebounceTimers.get(e);if(d)clearTimeout(d);let m=setTimeout(l,s);this._listChangedDebounceTimers.set(e,m)}else l()};this.setNotificationHandler(t,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function Jz(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function Bz(e){if(e.status!==401)return!1;let t=e.headers.get("www-authenticate")??"";return Jz(t)&&/use_dpop_nonce/i.test(t)}var Wz=(e,t)=>(r)=>{let o=typeof e==="function"?e:()=>e;return async(n,i)=>{let s=(i?.method??"GET").toUpperCase(),a=new URL(n.toString()),l=await o();if(!l)return r(n,i);let u=async()=>{let m=await t();if(!m)return r(n,i);let f=new Headers(i?.headers),g=await l.buildProof({htm:s,htu:a,accessToken:m});return f.set("Authorization",`DPoP ${m}`),f.set("DPoP",g),r(n,{...i,headers:f})},d=await u();if(Bz(d)&&d.headers.has("dpop-nonce"))l.observeNonce(d,a),await d.text?.().catch(()=>{}),d=await u();return l.observeNonce(d,a),d}},Kz=(e)=>Wz(async()=>{try{return await e.dpop?.()}catch(t){throw tt(t)}},async()=>{let t;try{t=await e.tokens()}catch(r){throw tt(r)}return t?.token_type?.toLowerCase()==="dpop"?t.access_token:void 0});var FP=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Ke(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 Ke(this,e)}constructor(e,t,r){super(`SSE error: ${t}`);this.code=e,this.event=r,Wr(this,new.target)}};var Gz=1,Yz={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2},Xz=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function Yg(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",i)};function n(){o(),r.abort(e.reason)}function i(){o(),r.abort(t.reason)}return e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",i,{once:!0}),r.signal}var dS=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,Bv(t?.authProvider)){if(this._oauthProvider=t.authProvider,this._authProvider=Kv(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop)this._fetch=Kz(t.authProvider)(t.fetch??fetch)}else this._authProvider=t?.authProvider;if(this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=Tg(t?.fetch,t?.requestInit),this._redirectPolicy==="follow")this._fetchWithInit=$g(this._fetchWithInit);this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??Yz,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??Gz)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(r){throw tt(r)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new Ug({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new Ug({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new Tt(N.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=Nu(this._scope,r?.scope,e.scope);this._scope=o;let n=Gv(o,r?.scope);return Du(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:Zi(e)}_unfollowedRedirect(e,t){let r=this._redirectPolicy==="follow"?void 0:Cg(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 tt(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)||!Gr(t))return;let r=t.params?._meta?.[Mt];if(typeof r!=="string")return;e.set("mcp-protocol-version",r),e.set("mcp-method",t.method);let o=Sg(t.method,t.params);if(o?.value!==void 0)e.set("mcp-name",Pu(o.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Gr(e))return!1;let t=e.params?._meta?.[Mt];return typeof t==="string"&&Jt(t)}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:o,requestSignal:n}=e,i=()=>this._abortController?.signal.aborted===!0||n?.aborted===!0;try{let s=await this._commonHeaders(),a=[...s.get("accept")?.split(",").map((m)=>m.trim().toLowerCase())??[],"text/event-stream"];if(s.set("accept",[...new Set(a)].join(", ")),o)s.set("last-event-id",o);let l=this._abortController?.signal,u=n!==void 0&&l!==void 0?Yg(l,n):n??l,d=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:s,signal:u});if(!d.ok){if(d.status===401&&this._authProvider){if(d.headers.has("www-authenticate")){let{resourceMetadataUrl:f,scope:g}=Fi(d);this._resourceMetadataUrl=f,this._scope=Nu(this._scope,g)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:d,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(f){throw tt(f)}return await d.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r)}if(await d.text?.().catch(()=>{}),t)throw tt(new Tt(N.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:d.statusText}));throw tt(new kt)}if(d.status===403){let{resourceMetadataUrl:f,scope:g,error:b,errorDescription:y}=Fi(d);if(b==="insufficient_scope"){let v=await d.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:g,resourceMetadataUrl:f,errorDescription:y,statusText:d.statusText,text:v},r)!=="AUTHORIZED")throw tt(new kt);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 Tt(N.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${m}`,{status:d.status,statusText:d.statusText})}this._handleSseStream(d.body,e,!0)}catch(s){if(!i())this.onerror?.(s);throw s}}_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((i)=>{if(this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this.onerror?.(Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`));try{this._scheduleReconnection(e,t+1)}catch(s){this.onerror?.(s instanceof Error?s:Error(String(s)))}})};if(this._reconnectionScheduler){let i=this._reconnectionScheduler(n,o,t);this._cancelReconnection=typeof i==="function"?i:void 0}else{let i=setTimeout(n,o);this._cancelReconnection=()=>clearTimeout(i)}}_handleSseStream(e,t,r){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:o,replayMessageId:n,requestSignal:i,onRequestStreamEnd:s}=t,a=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0,l,u=!1,d=!1;(async()=>{try{let f=e.pipeThrough(new TextDecoderStream).pipeThrough(new Ou({onRetry:(g)=>{this._serverRetryMs=g}})).getReader();while(!0){let{value:g,done:b}=await f.read();if(b)break;if(g.id)l=g.id,u=!0,o?.(g.id);if(!g.data)continue;if(!g.event||g.event==="message")try{let y=ut.parse(JSON.parse(g.data));if(en(y)||tn(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:i,onRequestStreamEnd:s},0);else if(!a())s?.()}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:i,onRequestStreamEnd:s},0)}catch(g){this.onerror?.(Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`)),s?.()}else s?.()}})()}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 kt("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:o}=await Yv(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await Du(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:o,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new kt("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:i}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Gr(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch((v)=>this.onerror?.(v));return}let s=await this._commonHeaders();this._applyBodyDerivedHeaders(s,e);let a=Array.isArray(e)?e.some((v)=>Ru(v)):Ru(e);if(a)s.delete("mcp-session-id");if(t?.headers!==void 0)for(let[v,L]of Object.entries(t.headers)){if(Xz.has(v.toLowerCase()))continue;s.set(v,L)}s.set("content-type","application/json");let l=[...s.get("accept")?.split(",").map((v)=>v.trim().toLowerCase())??[],"application/json","text/event-stream"];s.set("accept",[...new Set(l)].join(", "));let u=this._abortController?.signal,d=t?.requestSignal!==void 0&&u!==void 0?Yg(u,t.requestSignal):t?.requestSignal??u,m={...this._requestInit,method:"POST",headers:s,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}=Fi(f);this._resourceMetadataUrl=H,this._scope=Nu(this._scope,x)}if(this._authProvider.onUnauthorized&&!r){try{await this._authProvider.onUnauthorized({response:f,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(H){throw tt(H)}return await f.text?.().catch(()=>{}),this._send(e,t,!0,o)}if(await f.text?.().catch(()=>{}),r)throw tt(new Tt(N.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:f.statusText}));throw tt(new kt)}let v=await f.text?.().catch(()=>null);if(f.status===403){let{resourceMetadataUrl:H,scope:x,error:Z,errorDescription:R}=Fi(f);if(Z==="insufficient_scope"){if(await this._stepUpAuthorize({scope:x,resourceMetadataUrl:H,errorDescription:R,statusText:f.statusText,text:v},o)!=="AUTHORIZED")throw tt(new kt);return this._send(e,t,r,o+1)}}if(f.status===400&&typeof v==="string"&&this._isModernEnvelopedRequest(e))try{let H=ut.parse(JSON.parse(v)),x=(Array.isArray(e)?e:[e]).filter((Z)=>Gr(Z));if(tn(H)&&x.some((Z)=>Z.id===H.id)){this.onmessage?.(H);return}}catch{}let L=this._unfollowedRedirect(this._url,f)??v;throw new Tt(N.ClientHttpNotImplemented,`Error POSTing to endpoint: ${L}`,{status:f.status,statusText:f.statusText,text:v})}if(f.status===202){if(await f.text?.().catch(()=>{}),hg(e))this._startOrAuthSse({resumptionToken:void 0}).catch((v)=>this.onerror?.(v));return}let g=(Array.isArray(e)?e:[e]).some((v)=>("method"in v)&&("id"in v)&&v.id!==void 0),b=f.headers.get("content-type"),y=Pg(b);if(g)if(y==="text/event-stream")this._handleSseStream(f.body,{onresumptiontoken:i,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(y==="application/json"){let v=await f.json(),L=Array.isArray(v)?v.map((H)=>ut.parse(H)):[ut.parse(v)];for(let H of L)this.onmessage?.(H)}else throw await f.text?.().catch(()=>{}),new A(N.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 Tt(N.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 SS{_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 _S{_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 pS=new Set;function hS(e,t){let[r,o]=t,n=r?.shape;if(typeof n?.method?.value!=="string")return;let i=n.method.value,s=e==="request"?"setRequestHandler":"setNotificationHandler";if(!pS.has(s))pS.add(s),console.warn(`[ext-apps] ${s}(Schema, handler) is deprecated; use ${s}("${i}", { params: Schema.shape.params }, handler).`);let a=o;return[i,{params:n.params},e==="request"?(l,u)=>a({method:i,params:l},Qz(u)):(l)=>a({method:i,params:l})]}function Qz(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 bS="2026-01-26";var ew="ui/notifications/tool-input-partial";var tw=T([h("light"),h("dark")]).describe("Color theme preference for the host environment."),Vi=T([h("inline"),h("fullscreen"),h("pip")]).describe("Display mode for UI presentation."),rw=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."),ow=P(rw.describe(`Style variables for theming MCP apps.
77
+ ${ue}`,m++}else jg(R,w,Q)?f=R.slice(R.charCodeAt(w+6)===Xr?w+7:w+6,D)||void 0:L(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),Q=R.indexOf(`
79
+ `,w),Y=-1;if(D!==-1&&Q!==-1?Y=D<Q?D:Q:D!==-1?D===R.length-1?Y=-1:Y=D:Q!==-1&&(Y=Q),Y===-1)break;L(R,w,Y),w=Y+1,R.charCodeAt(w-1)===Vv&&R.charCodeAt(w)===qg&&w++}return R.slice(w)}function L(R,w,D){if(w===D){x();return}let Q=R.charCodeAt(w);if(Mg(R,w,Q)){let we=R.charCodeAt(w+5)===Xr?w+6:w+5,Ce=R.slice(we,D);d=m===0?Ce:`${d}
80
+ ${Ce}`,m++;return}if(jg(R,w,Q)){f=R.slice(R.charCodeAt(w+6)===Xr?w+7:w+6,D)||void 0;return}if(Q===105&&R.charCodeAt(w+1)===100&&R.charCodeAt(w+2)===58){let we=R.slice(R.charCodeAt(w+3)===Xr?w+4:w+3,D);we.includes("\x00")||(u=we);return}if(Q===58){if(n){let we=R.slice(w,D);n(we.slice(R.charCodeAt(w+1)===Xr?2:1))}return}let Y=R.slice(w,D),ue=Y.indexOf(":");if(ue===-1){H(Y,"",Y);return}let $e=Y.slice(0,ue),oe=Y.charCodeAt(ue+1)===Xr?2:1,ae=Y.slice(ue+oe);H($e,ae,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 kc(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:D}));break;default:r(new kc(`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&&s.length>0){let w=s.join("");L(w,0,w.length)}l=!0,u=void 0,d="",m=0,f=void 0,s.length=0,a=0,g=!1}return{feed:b,reset:Z}}function Mg(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 jg(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 Ou extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:o}={}){let n;super({start(i){n=Lg({onEvent:(s)=>{i.enqueue(s)},onError(s){typeof e=="function"&&e(s),(e==="terminate"||s.type==="max-buffer-size-exceeded")&&i.error(s)},onRetry:t,onComment:r,maxBufferSize:o})},transform(i){n.feed(i)}})}}var Hi=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Ke(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 Ke(this,e)}constructor(e){super(e);this.name=new.target.name,Wr(this,new.target)}},Uu=class extends Hi{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}},Jv=class extends Hi{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}},Xg=class extends Hi{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}},Ic=class extends Hi{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}},Ug=class extends Hi{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 Zu(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 Qg(e.issuer,t)?e:void 0}function Qg(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function Bv(e){if(e==null)return!1;let t=e;return typeof t.tokens==="function"&&typeof t.clientInformation==="function"}async function Wv(e,t,r){let{resourceMetadataUrl:o,scope:n}=Fi(t.response);if(await Du(e,{serverUrl:t.serverUrl,resourceMetadataUrl:o,scope:n,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new kt}function Kv(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async(r)=>Wv(e,r,t)}}var kt=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Ke(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 Ke(this,e)}constructor(e){super(e??"Unauthorized");this.name="UnauthorizedError",Wr(this,new.target)}};function Hu(e){return e?.authorization_response_iss_parameter_supported===!0}function Vu({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t===void 0)return;if(e===void 0){if(r)throw new Uu("authorization_response",t,void 0);return}if(e!==t)throw new Uu("authorization_response",t,e)}function Nu(...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 Gv(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 Yv(e,t,r,o,n){if(typeof e==="string")return{authorizationCode:e,iss:t};let i=e.get("iss")??void 0,s=e.get("code");if(s)return{authorizationCode:s,iss:i};let a=(await r.discoveryState?.())?.authorizationServerMetadata;if(!a)try{a=(await nS(o,n)).authorizationServerMetadata}catch{a=void 0}if(!a)throw new kt("Authorization callback failed and the issuer could not be verified");Vu({iss:i,expectedIssuer:a.issuer,issParameterSupported:Hu(a)});let l=e.get("error");if(l)throw new Kr(l,e.get("error_description")??l,e.get("error_uri")??void 0);throw new kt("Authorization callback contained neither `code` nor `error`")}function Xv(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var Au="code",qu="S256";function Qv(e,t){let r=e.client_secret!==void 0;if("token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Xv(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 ez(e,t,r,o){let{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":tz(n,i,r);return;case"client_secret_post":rz(n,i,o);return;case"none":oz(n,o);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function tz(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 rz(e,t,r){if(r.set("client_id",e),t)r.set("client_secret",t)}function oz(e,t){t.set("client_id",e)}function eS(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function nz(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!eS(t.hostname))throw new Xg(t.href);return t}function sz(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(eS(r.hostname))return"native"}return"web"}function iz(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??sz(t.redirect_uris)}}async function Zg(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Yo.parse(JSON.parse(r));return Kr.fromResponse(o)}catch(o){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Kr(Vt.ServerError,n)}}function Dg(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 Du(e,t){try{return await Mu(e,t)}catch(r){if(r instanceof Kr){if(r.code===Vt.InvalidClient||r.code===Vt.UnauthorizedClient)return Dg(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Mu(e,t);else if(r.code===Vt.InvalidGrant||r.code===Vt.InvalidDpopProof)return Dg(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await Mu(e,t)}throw r}}function az(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:n}=e,i=t||r?.scopes_supported?.join(" ")||n.scope;if(i&&o?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&n.grant_types?.includes("refresh_token"))i=`${i} offline_access`;return i}async function Mu(e,{serverUrl:t,authorizationCode:r,iss:o,scope:n,resourceMetadataUrl:i,fetchFn:s,skipIssuerMetadataValidation:a,forceReauthorization:l}){let u=iz(e),d=await e.discoveryState?.(),m,f,g,b,y=i;if(!y&&d?.resourceMetadataUrl)y=new URL(d.resourceMetadataUrl);if(d?.authorizationServerUrl){if(f=d.authorizationServerUrl,m=d.resourceMetadata,g=d.authorizationServerMetadata??await oS(f,{fetchFn:s,skipIssuerValidation:a}),!m)try{m=await tS(t,{resourceMetadataUrl:y},s)}catch(oe){if(oe instanceof TypeError)throw oe}if(g!==d.authorizationServerMetadata||m!==d.resourceMetadata)await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:g})}else{let oe=await nS(t,{resourceMetadataUrl:y,fetchFn:s,skipIssuerMetadataValidation:a});f=oe.authorizationServerUrl,g=oe.authorizationServerMetadata,m=oe.resourceMetadata,b={authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:g}}let v=g?.issuer??String(f),L={issuer:v};if(await e.saveAuthorizationServerUrl?.(v),r!==void 0){let oe=d?.authorizationServerMetadata?.issuer??d?.authorizationServerUrl;if(oe===void 0){if(e.saveDiscoveryState!==void 0)throw new Ic("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(!Qg(oe,v))throw new Ic(oe,v)}if(b)await e.saveDiscoveryState?.(b);let H=await lz(t,e,m),x=H&&m&&!e.validateResourceURL?m.resource:H;if(x)await e.saveResourceUrl?.(Ju(x));let Z=az({requestedScope:n,resourceMetadata:m,authServerMetadata:g,clientMetadata:e.clientMetadata}),R=await Promise.resolve(e.clientInformation(L)),w=Zu(R,v,{canPersistStamp:e.saveClientInformation!==void 0});if(w===void 0&&R?.issuer&&e.saveClientInformation===void 0)throw new Ic(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 oe=g?.client_id_metadata_document_supported===!0,ae=e.clientMetadataUrl;if(ae&&!cz(ae))throw new Kr(Vt.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ae}`);if(oe&&ae)w={client_id:ae,issuer:v},await e.saveClientInformation?.(w,L);else{if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");w={...await bz(f,{metadata:g,clientMetadata:u,scope:Z,fetchFn:s}),issuer:v},await e.saveClientInformation(w,L)}}let D=!e.redirectUrl;if(r!==void 0||D){if(r!==void 0)Vu({iss:o,expectedIssuer:g?.issuer,issParameterSupported:Hu(g)});let oe=await _z(e,f,{metadata:g,resource:x,authorizationCode:r,iss:o,scope:Z,fetchFn:s});return await e.saveTokens({...oe,issuer:v},L),"AUTHORIZED"}let Q=Zu(await e.tokens(L),v);if(Q&&Q.issuer===void 0)Q={...Q,issuer:v},await e.saveTokens(Q,L);if(Q?.refresh_token&&!l){let oe;try{oe=await Sz(f,{metadata:g,clientInformation:w,refreshToken:Q.refresh_token,resource:x,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:s})}catch(ae){if(ae instanceof Xg)throw ae;if(!(ae instanceof Kr)||ae.code===Vt.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(ae instanceof Error?ae.message:String(ae))}`);else throw ae}if(oe)return await e.saveTokens({...oe,issuer:v},L),"AUTHORIZED"}let Y=e.state?await e.state():void 0,{authorizationUrl:ue,codeVerifier:$e}=await fz(f,{metadata:g,clientInformation:w,state:Y,redirectUrl:e.redirectUrl,scope:Z,resource:x});return await e.saveCodeVerifier($e),await e.redirectToAuthorization(ue),"REDIRECT"}function cz(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function lz(e,t,r){let o=Ff(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(!r)return;if(!Hf({requestedResource:o,configuredResource:r.resource}))throw Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}var uz=new Set(["bearer","dpop"]);function Fi(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!uz.has(r.toLowerCase())||!o)return{};let n=$c(e,"resource_metadata")||void 0,i;if(n)try{i=new URL(n)}catch{}let s=$c(e,"scope")||void 0,a=$c(e,"error")||void 0,l=$c(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:s,error:a,errorDescription:l}}function $c(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 i=n[1]||n[2];if(i)return i}return null}async function tS(e,t,r=fetch){let o=await hz(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 Wo.parse(await o.json())}async function rS(e,t,r=fetch){let o=Zi(r);try{return await o(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!Ag)throw n;if(t)try{return await o(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}function dz(e,t="",r={}){if(t.endsWith("/"))t=t.slice(0,-1);return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Fg(e,t,r=fetch){return await rS(e,{"MCP-Protocol-Version":t},r)}function pz(e,t){if(!e)return!0;if(t==="/")return!1;return!e.ok&&e.status<500||e.status===502}async function hz(e,t,r,o){let n=new URL(e),i=o?.protocolVersion??yo,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let l=dz(t,n.pathname);s=new URL(l,o?.metadataServerUrl??n),s.search=n.search}let a=await Fg(s,i,r);if(!o?.metadataUrl&&pz(a,n.pathname))a=await Fg(new URL(`/.well-known/${t}`,n),i,r);return a}function mz(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 oS(e,{fetchFn:t=fetch,protocolVersion:r=yo,skipIssuerValidation:o=!1}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},i=mz(e);for(let{url:s,type:a}of i){let l=await rS(s,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 ${s}`)}let u=a==="oauth"?Br.parse(await l.json()):Ko.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 Uu("metadata",d,u.issuer)}return u}}async function nS(e,t){let r,o;try{if(r=await tS(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0)o=r.authorization_servers[0]}catch(i){if(i instanceof TypeError)throw i}if(!o)o=String(new URL("/",e));let n=await oS(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function Ju(e){return typeof e==="string"?e:e.href}async function fz(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:i,resource:s}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Au))throw Error(`Incompatible auth server: does not support response type ${Au}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(qu))throw Error(`Incompatible auth server: does not support code challenge method ${qu}`)}else a=new URL("/authorize",e);let l=await Cu(),{code_verifier:u,code_challenge:d}=l;if(a.searchParams.set("response_type",Au),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",qu),a.searchParams.set("redirect_uri",String(o)),i)a.searchParams.set("state",i);if(n)a.searchParams.set("scope",n);if(n?.split(" ").includes("offline_access"))a.searchParams.append("prompt","consent");if(s)a.searchParams.set("resource",Ju(s));return{authorizationUrl:a,codeVerifier:u}}function gz(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function sS(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:i,dpop:s,fetchFn:a}){let l=nz(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i)r.set("resource",Ju(i));if(!n&&o)ez(Qv(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let d=async()=>{let g=new Headers(u);if(n)await n(g,r,l,t);if(s)g.set("DPoP",await s.buildProof({htm:"POST",htu:l}));return Zi(a??fetch)(l,{method:"POST",headers:g,body:r})},m=await d();if(s&&m.status===400){if((await m.clone().json().catch(()=>{}))?.error===Vt.UseDpopNonce)s.observeNonce(m,l),m=await d()}if(s?.observeNonce(m,l),!m.ok)throw await Zg(m);let f=await m.json();try{return Go.parse(gu(f))}catch(g){if(typeof f==="object"&&f!==null&&"error"in f)throw await Zg(JSON.stringify(f));throw g}}async function Sz(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:i,dpop:s,fetchFn:a}){return{refresh_token:o,...await sS(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:i,resource:n,dpop:s,fetchFn:a})}}async function _z(e,t,{metadata:r,resource:o,authorizationCode:n,iss:i,scope:s,fetchFn:a}={}){if(n!==void 0)Vu({iss:i,expectedIssuer:r?.issuer,issParameterSupported:Hu(r)});let l=r?.issuer??String(t),u=async()=>{let g=await e.clientInformation({issuer:l}),b=Zu(g,l,{canPersistStamp:!1});if(g&&b===void 0)throw new Ic(String(g.issuer),l);return b},d=await u(),m=s??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=gz(n,await e.codeVerifier(),e.redirectUrl)}return d??=await u(),sS(t,{metadata:r,tokenRequestParams:f,clientInformation:d,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:a})}async function bz(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:n}){let i;if(t){if(!t.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let s={...r,...o===void 0?{}:{scope:o}},a=await Zi(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok)throw new Jv({status:a.status,body:await a.text(),submittedMetadata:s});return Xo.parse(gu(await a.json()))}var Cc=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),yz=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(ju(e))}set(e,t){let r=ju(e),o=Cc.has(e.method),n=!this._entries.has(r);if(!o&&n&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let s of this._entries.keys())if(!Cc.has(s.slice(0,s.indexOf("\x00")))){this._entries.delete(s),this._cappedSize--;break}}let i=++this._stamp;if(this._entries.set(r,{...t,stamp:i}),n&&!o)this._cappedSize++;return i}delete(e){if(this._entries.delete(ju(e))&&!Cc.has(e.method))this._cappedSize--}evict(e){let t=`${e}\x00`,r=Cc.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 ju(e){return`${e.method}\x00${JSON.stringify([e.partition??"",e.params??""])}`}function Lu(e,t){return t===void 0?e:`${e}\x00${t}`}var vz=86400000,zz=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 i=this._partitionFor("public");if(i===o)return;let s=await this._store.get({...r,partition:i});return s?.scope==="public"?s:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){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=Lu(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=Lu(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(Lu(e,o?.params))??0)!==r)return;let n=o?.params??"",i=this._partitionFor("private"),s=this._partitionFor("public"),a=(o?.scope??"private")==="public"?s:i;try{await this._store.set({method:e,params:n,partition:a},{value:wz(t),expiresAt:o?.expiresAt,scope:o?.scope})}catch(l){this._reportError(l)}if(s!==i)try{await this._store.delete({method:e,params:n,partition:a===i?s:i})}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 i of o.tools){let s=t(i);if(s!==void 0)n.set(i.name,s)}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 wz(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 iS=Symbol.for("mcp.authSeamEscape");function tt(e){if(typeof e==="object"&&e!==null||typeof e==="function")try{Object.defineProperty(e,iS,{value:!0,configurable:!0})}catch{}return e}function Rz(e){return(typeof e==="object"&&e!==null||typeof e==="function")&&e[iS]===!0}var xz=-32022,Pz=new Set([-32001,-32020,-32021]);function Tz(e,t){switch(e.kind){case"result":return Ez(e.result,t);case"rpc-error":return aS(e,t);case"http-error":return kz(e,t);case"network-error":return Hg(e.error,t);case"unusable-reply":return{kind:"error",error:new A(N.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${cS(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 Hg(Error("Connection closed during the version negotiation probe"),t);case"timeout":if(t.transportKind==="stdio")return{kind:"legacy"};return{kind:"error",error:new A(N.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function Ez(e,t){let r=Ht(xc).validateResult("server/discover",e);if(!r.ok)return{kind:"legacy"};let o=r.value.supportedVersions,n=t.clientModernVersions.find((i)=>o.includes(i));if(n!==void 0)return{kind:"modern",version:n,discover:r.value};if(t.fallbackAvailable)return{kind:"legacy"};return{kind:"error",error:new Rc({supported:[...o],requested:t.requestedVersion})}}function aS(e,t){let{code:r,message:o,data:n}=e;if(r===xz){let i=Cz(n);if(i===void 0)return{kind:"legacy"};let s=new Rc({supported:i,requested:Iz(n)??t.requestedVersion},o),a=Ui(i),l=t.clientModernVersions.find((u)=>a.includes(u));if(l!==void 0)return{kind:"corrective",version:l,error:s};if(a.length>0)return{kind:"error",error:s};return t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:s}}if(Pz.has(r))return{kind:"legacy"};return{kind:"legacy"}}function kz(e,t){if(e.status===401||e.status===403){let o=e.status===403;return{kind:"error",error:new Tt(o?N.ClientHttpForbidden:N.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 Tt(N.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let r=Oz(e.body);if(r!==void 0)return aS(r,t);return{kind:"legacy"}}function Hg(e,t){if(t.environment==="browser"&&$z(e))return{kind:"legacy"};return{kind:"error",error:new A(N.EraNegotiationFailed,`Version negotiation probe failed: ${cS(e)}`,{cause:e},{cause:e})}}function $z(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function cS(e){return e instanceof Error?e.message:String(e)}function Cz(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 Iz(e){if(typeof e!=="object"||e===null)return;let t=e.requested;return typeof t==="string"?t:void 0}function Oz(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:i}=r;if(typeof o!=="number")return;return{code:o,message:typeof n==="string"?n:"",data:i}}var Nz="legacy";function Az(e,t){let r=e?.mode??Nz;if(r==="legacy")return{kind:"legacy"};let o=e?.probe??{};if(typeof r==="object"){if(!Jt(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?Ui(t):[];return{kind:"auto",modernVersions:n.length>0?n:[...Su],fallbackAvailable:t?_u(t).length>0:!0,probe:o}}function Vg(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function Jg(e){return"stderr"in e&&"pid"in e?"stdio":"http"}var qz=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&&(en(o)||tn(o))&&o.id===n.id){if(r._pending=void 0,en(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 i=!1,s=(l)=>{if(i)return;if(i=!0,clearTimeout(a),this._pending?.id===o)this._pending=void 0;n(l)},a=setTimeout(()=>s({kind:"timeout"}),r);this._pending={id:o,resolve:s},this._transport.send(t(o)).catch((l)=>s({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,Fu.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)}}},Fu=new WeakMap;function Bg(e){let t=Fu.get(e);Fu.delete(e),t?.()}function Mz(e,t,r,o){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:Ht(t).outboundEnvelope({protocolVersion:t,clientInfo:r,clientCapabilities:o})}}}function jz(e){if(e instanceof A&&e.code===N.ClientHttpUnexpectedContent)return!0;return e instanceof Error&&e.name==="SyntaxError"}function Lz(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(Rz(r)||r instanceof kt||r instanceof Error&&r.name==="UnauthorizedError")return{kind:"auth-required",error:r};if(r instanceof Tt){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(jz(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 lS(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,i=e.kind==="auto"&&e.fallbackAvailable,s=await qz.open(t.transport),a=async()=>{let u=n[0],d=!1,m=o;for(;;){let f=await s.exchange((y)=>Mz(y,u,t.clientInfo,t.capabilities),r);if(f.kind==="timeout"&&m>0){m--;continue}let g=Lz(f,r),b=Tz(g,{clientModernVersions:n,requestedVersion:u,fallbackAvailable:i,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=g.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new A(N.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 A(N.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 A(N.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 s.detach(),u}return s.release(),l}function Uz(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 Zz(e,t,r,o){let i=new t.constructor({...r,stderr:"ignore"}),s=t.close,a=!1,l,u=new Promise((m,f)=>{l=()=>f(Wg())});t.close=async function(){return a=!0,l?.(),s.call(t)};let d;try{let m=lS(e,{...o,transport:i,transportKind:"stdio",disposableProbe:!0});m.catch(()=>{}),d=await Promise.race([m,u])}finally{await Dz(i),t.close=s}if(a)throw Wg();return d}function Wg(){return new A(N.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function Dz(e){try{let t=e._dispose;await(typeof t==="function"?t.call(e):e.close())}catch{}}function Kg(e){let t=e._meta?.[jt];return wg.Implementation(t)?t:void 0}function Oc(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 i=o[n];if(r[n]===void 0&&Object.prototype.hasOwnProperty.call(i,"default"))r[n]=i.default;if(r[n]!==void 0)Oc(i,r[n])}}if(Array.isArray(e.anyOf)){for(let r of e.anyOf)if(typeof r!=="boolean")Oc(r,t)}if(Array.isArray(e.oneOf)){for(let r of e.oneOf)if(typeof r!=="boolean")Oc(r,t)}}function Fz(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 Hz(e){if(typeof e==="object"&&e!==null){if(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e))return e;if(e.kind==="modern"&&lr.safeParse(e.discover).success)return e}throw new A(N.EraNegotiationFailed,"connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }")}var Gg={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},Vz=64,uS=class extends Ec{_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 A(N.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 ku,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=bg(t?.inputRequired),this._cache=new zz(t?.responseCacheStore??new yz,t?.responseCacheStore!==void 0,(r)=>this._reportStoreError(r),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??Vz,t?.listChanged)this._listChangedConfig=t.listChanged}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&Jt(this._negotiatedProtocolVersion)&&Gr(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 A(N.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 xg({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=Rg(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=Ht(this._negotiatedProtocolVersion),i=n.validateRequest("elicitation/create",r);if(!i.ok&&i.reason==="not-in-era")i=n.validateInputRequest("elicitation/create",r);if(!i.ok)throw new re(i.reason==="not-in-era"?W.InternalError:W.InvalidParams,i.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${i.message}`);let{params:s}=i.value;s.mode=s.mode??"form";let{supportsFormMode:a,supportsUrlMode:l}=Fz(this._capabilities.elicitation);if(s.mode==="form"&&!a)throw new re(W.InvalidParams,"Client does not support form-mode elicitation requests");if(s.mode==="url"&&!l)throw new re(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 re(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=s.mode==="form"?s.requestedSchema:void 0;if(s.mode==="form"&&m.action==="accept"&&m.content&&f&&this._capabilities.elicitation?.form?.applyDefaults)try{Oc(f,m.content)}catch{}return m};if(e==="sampling/createMessage")return async(r,o)=>{let n=Ht(this._negotiatedProtocolVersion),i=n.validateRequest("sampling/createMessage",r);if(!i.ok&&i.reason==="not-in-era")i=n.validateInputRequest("sampling/createMessage",r);if(!i.ok)throw new re(i.reason==="not-in-era"?W.InternalError:W.InvalidParams,i.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${i.message}`);let{params:s}=i.value,a=await t(r,o),l=Boolean(s.tools||s.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 re(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 A(N.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,Hz(t.prior),t);let r=Az(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=_u(this._supportedProtocolVersions);try{let o=r[0];if(o===void 0)throw new A(N.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=Jg(e),i={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:Vg(),defaultTimeoutMs:r?.timeout??Tc},s=n==="stdio"?Uz(e):void 0;o=s===void 0?await lS(t,{...i,transport:e,transportKind:n}):await Zz(t,e,s,i)}catch(n){throw await e.close().catch(()=>{}),Bg(e),n}if(Bg(e),await super.connect(e),o.era==="legacy"){await this._legacyHandshake(e,r);return}if(this._serverCapabilities=o.discover.capabilities,this._serverVersion=Kg(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,i=this._serverCapabilities,s={...n.tools&&i?.tools?.listChanged&&{tools:n.tools},...n.prompts&&i?.prompts?.listChanged&&{prompts:n.prompts},...n.resources&&i?.resources?.listChanged&&{resources:n.resources}},a=!0;try{this._setupListChangedHandlers(s)}catch(u){a=!1,this.onerror?.(u instanceof Error?u:Error(String(u)))}let l=a?{...s.tools&&{toolsListChanged:!0},...s.prompts&&{promptsListChanged:!0},...s.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,i=(n&&Ui(n).length>0?Ui(n):Su).find((s)=>o.supportedVersions.includes(s));if(i===void 0)throw new A(N.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=Kg(o),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.instructions,this._negotiatedProtocolVersion=i,e.setProtocolVersion?.(i),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(s){this.onerror?.(s instanceof Error?s:Error(String(s)))}}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 Jt(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new A(N.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new A(N.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 A(N.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new A(N.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new A(N.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new A(N.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 A(N.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 A(N.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new A(N.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new A(N.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"},lr,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 i=r?.cacheMode==="bypass",s=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 A(N.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),i)return a;return await this._cache.write(e,a,s,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),vz),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 A?n:new A(N.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:xu(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 i=this._freshness(n,e.uri);if(i.expiresAt>this._cache.now())await this._cache.write("resources/read",n,o,i);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 A(N.NotConnected,"Not connected");let r=this._negotiatedProtocolVersion;if(r===void 0||!Jt(r))throw new A(N.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 A?x:new A(N.RequestTimeout,String(x))}let o=new AbortController,n=`listen:${this._nextListenId++}`,i="opening",s,a,l,u,d=new Promise((x,Z)=>{l=x,u=Z}),m,f=new Promise((x)=>{m=x}),g=(x)=>{if(i==="closed")return;let Z=i==="opening";if(s!==void 0)clearTimeout(s),s=void 0;if("ack"in x){i="open",l(x.ack);return}if(i="closed",a!==void 0)t?.signal?.removeEventListener("abort",a);if(this._listenState.delete(n),o.abort(),m(x.cause),Z)u(x.error??new A(N.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(i==="closed")return;g({cause:"local"}),await b()};this._listenState.set(n,{settle:g});let v=t?.timeout??Tc;if(s=setTimeout(()=>{g({cause:"remote",error:new A(N.RequestTimeout,"subscriptions/listen ack timed out",{timeout:v})}),b().catch(()=>{})},v),t?.signal){let x=t.signal;a=()=>{if(i==="closed")return;let Z=x.reason;g({cause:"local",error:Z instanceof Error?Z:Error(String(Z??"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}},H=(x)=>{g({cause:"remote",error:x instanceof Error?x:Error(String(x))})};try{this.transport.send(L,{requestSignal:o.signal,onRequestStreamEnd:()=>g({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(Gg,e.method)?Gg[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?.[ts],n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){let i=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);n.settle({ack:i.ok?i.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(tn(e))r.settle({cause:"remote",error:re.fromError(e.error.code,e.error.message,e.error.data)});else r.settle({cause:"graceful",error:new A(N.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new A(N.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"&&Vg()!=="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=gg(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),i=()=>{if(n===void 0||n.ok)return;let l=n.compileError,u=(l instanceof Error?l.message:String(l)).slice(0,200);throw new re(W.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${u}`)};i();let s;try{s=await this.request({method:"tools/call",params:e},await o())}catch(l){let u=l instanceof re&&l.code===Qo;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)),i(),s=await this.request({method:"tools/call",params:e},await o())}let a=n!==void 0&&n.ok?n.validator:void 0;if(a){if(s.structuredContent===void 0&&!s.isError)throw new re(W.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent!==void 0&&!s.isError)try{let l=a(s.structuredContent);if(!l.valid)throw new re(W.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)}catch(l){if(l instanceof re)throw l;throw new re(W.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)}}return s}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){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||Jg(this.transport)==="stdio")return;let t=e.tools.filter((r)=>{let o=xu(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=Pc(Ys,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:i,debounceMs:s}=n.data,{onChanged:a}=r,l=async()=>{if(!i){a(null,null);return}try{a(null,await o())}catch(d){a(d instanceof Error?d:Error(String(d)),null)}},u=()=>{if(s){let d=this._listChangedDebounceTimers.get(e);if(d)clearTimeout(d);let m=setTimeout(l,s);this._listChangedDebounceTimers.set(e,m)}else l()};this.setNotificationHandler(t,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function Jz(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function Bz(e){if(e.status!==401)return!1;let t=e.headers.get("www-authenticate")??"";return Jz(t)&&/use_dpop_nonce/i.test(t)}var Wz=(e,t)=>(r)=>{let o=typeof e==="function"?e:()=>e;return async(n,i)=>{let s=(i?.method??"GET").toUpperCase(),a=new URL(n.toString()),l=await o();if(!l)return r(n,i);let u=async()=>{let m=await t();if(!m)return r(n,i);let f=new Headers(i?.headers),g=await l.buildProof({htm:s,htu:a,accessToken:m});return f.set("Authorization",`DPoP ${m}`),f.set("DPoP",g),r(n,{...i,headers:f})},d=await u();if(Bz(d)&&d.headers.has("dpop-nonce"))l.observeNonce(d,a),await d.text?.().catch(()=>{}),d=await u();return l.observeNonce(d,a),d}},Kz=(e)=>Wz(async()=>{try{return await e.dpop?.()}catch(t){throw tt(t)}},async()=>{let t;try{t=await e.tokens()}catch(r){throw tt(r)}return t?.token_type?.toLowerCase()==="dpop"?t.access_token:void 0});var FP=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Ke(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 Ke(this,e)}constructor(e,t,r){super(`SSE error: ${t}`);this.code=e,this.event=r,Wr(this,new.target)}};var Gz=1,Yz={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2},Xz=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function Yg(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",i)};function n(){o(),r.abort(e.reason)}function i(){o(),r.abort(t.reason)}return e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",i,{once:!0}),r.signal}var dS=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,Bv(t?.authProvider)){if(this._oauthProvider=t.authProvider,this._authProvider=Kv(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop)this._fetch=Kz(t.authProvider)(t.fetch??fetch)}else this._authProvider=t?.authProvider;if(this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=Tg(t?.fetch,t?.requestInit),this._redirectPolicy==="follow")this._fetchWithInit=$g(this._fetchWithInit);this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??Yz,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??Gz)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(r){throw tt(r)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new Ug({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new Ug({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new Tt(N.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=Nu(this._scope,r?.scope,e.scope);this._scope=o;let n=Gv(o,r?.scope);return Du(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:Zi(e)}_unfollowedRedirect(e,t){let r=this._redirectPolicy==="follow"?void 0:Cg(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 tt(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)||!Gr(t))return;let r=t.params?._meta?.[Mt];if(typeof r!=="string")return;e.set("mcp-protocol-version",r),e.set("mcp-method",t.method);let o=Sg(t.method,t.params);if(o?.value!==void 0)e.set("mcp-name",Pu(o.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Gr(e))return!1;let t=e.params?._meta?.[Mt];return typeof t==="string"&&Jt(t)}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:o,requestSignal:n}=e,i=()=>this._abortController?.signal.aborted===!0||n?.aborted===!0;try{let s=await this._commonHeaders(),a=[...s.get("accept")?.split(",").map((m)=>m.trim().toLowerCase())??[],"text/event-stream"];if(s.set("accept",[...new Set(a)].join(", ")),o)s.set("last-event-id",o);let l=this._abortController?.signal,u=n!==void 0&&l!==void 0?Yg(l,n):n??l,d=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:s,signal:u});if(!d.ok){if(d.status===401&&this._authProvider){if(d.headers.has("www-authenticate")){let{resourceMetadataUrl:f,scope:g}=Fi(d);this._resourceMetadataUrl=f,this._scope=Nu(this._scope,g)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:d,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(f){throw tt(f)}return await d.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r)}if(await d.text?.().catch(()=>{}),t)throw tt(new Tt(N.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:d.statusText}));throw tt(new kt)}if(d.status===403){let{resourceMetadataUrl:f,scope:g,error:b,errorDescription:y}=Fi(d);if(b==="insufficient_scope"){let v=await d.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:g,resourceMetadataUrl:f,errorDescription:y,statusText:d.statusText,text:v},r)!=="AUTHORIZED")throw tt(new kt);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 Tt(N.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${m}`,{status:d.status,statusText:d.statusText})}this._handleSseStream(d.body,e,!0)}catch(s){if(!i())this.onerror?.(s);throw s}}_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((i)=>{if(this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this.onerror?.(Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`));try{this._scheduleReconnection(e,t+1)}catch(s){this.onerror?.(s instanceof Error?s:Error(String(s)))}})};if(this._reconnectionScheduler){let i=this._reconnectionScheduler(n,o,t);this._cancelReconnection=typeof i==="function"?i:void 0}else{let i=setTimeout(n,o);this._cancelReconnection=()=>clearTimeout(i)}}_handleSseStream(e,t,r){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:o,replayMessageId:n,requestSignal:i,onRequestStreamEnd:s}=t,a=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0,l,u=!1,d=!1;(async()=>{try{let f=e.pipeThrough(new TextDecoderStream).pipeThrough(new Ou({onRetry:(g)=>{this._serverRetryMs=g}})).getReader();while(!0){let{value:g,done:b}=await f.read();if(b)break;if(g.id)l=g.id,u=!0,o?.(g.id);if(!g.data)continue;if(!g.event||g.event==="message")try{let y=ut.parse(JSON.parse(g.data));if(en(y)||tn(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:i,onRequestStreamEnd:s},0);else if(!a())s?.()}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:i,onRequestStreamEnd:s},0)}catch(g){this.onerror?.(Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`)),s?.()}else s?.()}})()}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 kt("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:o}=await Yv(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await Du(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:o,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new kt("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:i}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Gr(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch((v)=>this.onerror?.(v));return}let s=await this._commonHeaders();this._applyBodyDerivedHeaders(s,e);let a=Array.isArray(e)?e.some((v)=>Ru(v)):Ru(e);if(a)s.delete("mcp-session-id");if(t?.headers!==void 0)for(let[v,L]of Object.entries(t.headers)){if(Xz.has(v.toLowerCase()))continue;s.set(v,L)}s.set("content-type","application/json");let l=[...s.get("accept")?.split(",").map((v)=>v.trim().toLowerCase())??[],"application/json","text/event-stream"];s.set("accept",[...new Set(l)].join(", "));let u=this._abortController?.signal,d=t?.requestSignal!==void 0&&u!==void 0?Yg(u,t.requestSignal):t?.requestSignal??u,m={...this._requestInit,method:"POST",headers:s,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}=Fi(f);this._resourceMetadataUrl=H,this._scope=Nu(this._scope,x)}if(this._authProvider.onUnauthorized&&!r){try{await this._authProvider.onUnauthorized({response:f,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(H){throw tt(H)}return await f.text?.().catch(()=>{}),this._send(e,t,!0,o)}if(await f.text?.().catch(()=>{}),r)throw tt(new Tt(N.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:f.statusText}));throw tt(new kt)}let v=await f.text?.().catch(()=>null);if(f.status===403){let{resourceMetadataUrl:H,scope:x,error:Z,errorDescription:R}=Fi(f);if(Z==="insufficient_scope"){if(await this._stepUpAuthorize({scope:x,resourceMetadataUrl:H,errorDescription:R,statusText:f.statusText,text:v},o)!=="AUTHORIZED")throw tt(new kt);return this._send(e,t,r,o+1)}}if(f.status===400&&typeof v==="string"&&this._isModernEnvelopedRequest(e))try{let H=ut.parse(JSON.parse(v)),x=(Array.isArray(e)?e:[e]).filter((Z)=>Gr(Z));if(tn(H)&&x.some((Z)=>Z.id===H.id)){this.onmessage?.(H);return}}catch{}let L=this._unfollowedRedirect(this._url,f)??v;throw new Tt(N.ClientHttpNotImplemented,`Error POSTing to endpoint: ${L}`,{status:f.status,statusText:f.statusText,text:v})}if(f.status===202){if(await f.text?.().catch(()=>{}),hg(e))this._startOrAuthSse({resumptionToken:void 0}).catch((v)=>this.onerror?.(v));return}let g=(Array.isArray(e)?e:[e]).some((v)=>("method"in v)&&("id"in v)&&v.id!==void 0),b=f.headers.get("content-type"),y=Pg(b);if(g)if(y==="text/event-stream")this._handleSseStream(f.body,{onresumptiontoken:i,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(y==="application/json"){let v=await f.json(),L=Array.isArray(v)?v.map((H)=>ut.parse(H)):[ut.parse(v)];for(let H of L)this.onmessage?.(H)}else throw await f.text?.().catch(()=>{}),new A(N.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 Tt(N.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 SS{_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 _S{_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 pS=new Set;function hS(e,t){let[r,o]=t,n=r?.shape;if(typeof n?.method?.value!=="string")return;let i=n.method.value,s=e==="request"?"setRequestHandler":"setNotificationHandler";if(!pS.has(s))pS.add(s),console.warn(`[ext-apps] ${s}(Schema, handler) is deprecated; use ${s}("${i}", { params: Schema.shape.params }, handler).`);let a=o;return[i,{params:n.params},e==="request"?(l,u)=>a({method:i,params:l},Qz(u)):(l)=>a({method:i,params:l})]}function Qz(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 bS="2026-01-26";var ew="ui/notifications/tool-input-partial";var tw=T([h("light"),h("dark")]).describe("Color theme preference for the host environment."),Vi=T([h("inline"),h("fullscreen"),h("pip")]).describe("Display mode for UI presentation."),rw=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."),ow=P(rw.describe(`Style variables for theming MCP apps.
82
82
 
83
83
  Individual style keys are optional - hosts may provide any subset of these values.
84
84
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
@@ -116,7 +116,7 @@ Boolean requesting whether a visible border and background is provided by the ho
116
116
  - omitted: host decides border`)}),fS=p({method:h("ui/request-display-mode"),params:p({mode:Vi.describe("The display mode being requested.")})}),gS=p({mode:Vi.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),Sw=T([h("model"),h("app")]).describe("Tool visibility scope - who can access the tool."),mT=p({resourceUri:c().optional(),visibility:S(Sw).optional().describe(`Who can access this tool. Default: ["model", "app"]
117
117
  - "model": Tool visible to and callable by the agent
118
118
  - "app": Tool callable by the app from this server only`),csp:nu().optional(),permissions:nu().optional()}),fT=p({mimeTypes:S(c()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),_w=p({method:h("ui/download-file"),params:p({contents:S(T([Zr,Dr])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),bw=p({method:h("ui/message"),params:p({role:h("user").describe('Message role, currently only "user" is supported.'),content:S(Pt).describe("Message content blocks (text, image, etc.).")})}),gT=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:Bu.optional().describe("CSP configuration from resource metadata."),permissions:Wu.optional().describe("Sandbox permissions from resource metadata.")})}),ST=p({method:h("ui/notifications/tool-result"),params:dr.describe("Standard MCP tool execution result.")}),yS=p({toolInfo:p({id:lt.optional().describe("JSON-RPC id of the tools/call request."),tool:ur.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:tw.optional().describe("Current color theme preference."),styles:dw.optional().describe("Style configuration for theming the app."),displayMode:Vi.optional().describe("How the UI is currently displayed."),availableDisplayModes:S(Vi).optional().describe("Display modes the host supports."),containerDimensions:T([p({height:z().describe("Fixed container height in pixels.")}),p({maxHeight:T([z(),ou()]).optional().describe("Maximum container height in pixels.")})]).and(T([p({width:z().describe("Fixed container width in pixels.")}),p({maxWidth:T([z(),ou()]).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(),_T=p({method:h("ui/notifications/host-context-changed"),params:yS.describe("Partial context update containing only changed fields.")}),yw=p({method:h("ui/update-model-context"),params:p({content:S(Pt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:P(c(),M().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),vw=p({method:h("ui/initialize"),params:p({appInfo:Rt.describe("App identification (name and version)."),appCapabilities:fw.describe("Features and capabilities this app provides."),protocolVersion:c().describe("Protocol version this app supports.")})}),zw=p({protocolVersion:c().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Rt.describe("Host application identification and version."),hostCapabilities:mw.describe("Features and capabilities provided by the host."),hostContext:yS.describe("Rich context about the host environment.")}).passthrough();class Ji{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=ut.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!==ew)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var ww=[bS];class Bi extends Ec{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new SS;_methods=new _S;setRequestHandler=(...e)=>{let[t,...r]=hS("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...r)};setNotificationHandler=(...e)=>{let[t,...r]=hS("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:lw,sandboxready:cw,initialized:gw,requestteardown:hw,loggingmessage:Fr};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:vw.shape.params,result:zw},(n)=>this._onAppsInitialize(n)),this.replaceRequestHandler("ping",(n,i)=>(this.onping?.(n.params,i),{})),this.replaceRequestHandler("ui/request-display-mode",{params:fS.shape.params,result:gS},()=>({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:bw.shape.params,result:aw},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:nw.shape.params,result:sw},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:_w.shape.params,result:iw},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:fS.shape.params,result:gS},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:yw.shape.params,result:cr},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:ww.includes(t)?t:bS,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],i=e[o];if(Rw(n,i))continue;t[o]=i,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},pw,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 Rw(e,t){return JSON.stringify(e)===JSON.stringify(t)}var vS=[200,800],xw=(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 i=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),s=()=>{clearTimeout(i),t.removeEventListener("abort",s),o(t.reason)};t?.addEventListener("abort",s,{once:!0})})}function zS(e,{signal:t,onDiagnostic:r,wait:o=Pw}={}){return async(n)=>{for(let i=1;;i++){t?.throwIfAborted();try{let s=await e(n);if(t?.throwIfAborted(),i>1)r?.({state:"recovered",uri:n.uri,attempt:i});return s}catch(s){if(t?.throwIfAborted(),!xw(s))throw s;if(i>vS.length)throw r?.({state:"exhausted",uri:n.uri,attempt:i,message:s.message}),Object.assign(Error(`MCP resource transport failed for ${n.uri} after ${i} attempts: ${s.message}. Inspect the host connection and browser network diagnostics; this resource-loading error does not establish a component assertion failure.`,{cause:s}),{code:"ADS_RESOURCE_TRANSPORT"});let a=vS[i-1];r?.({state:"retry",uri:n.uri,attempt:i,nextAttempt:i+1,delayMs:a,message:s.message}),await o(a,t)}}}}function wS(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 xS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:i,callTool:s,context:a,onError:l,onState:u}){let d={slot:e,title:t,sandboxUrl:r,resourceUri:o,readResource:i,callTool:s,context:a,onError:l,onState:u},m=n,f,g,b,y=!1;function v(){if(y||b)return;u?.({state:"loading"}),b=Promise.resolve().then(async()=>{if(await g,await f?.close(),y)return;g=RS({...d,result:m,onReopen:v});try{f=await g}finally{g=void 0}}).catch((L)=>{if(!y)l(L)}).finally(()=>{b=void 0})}g=RS({...d,result:m,onReopen:v});try{f=await g}finally{g=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 RS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:i,callTool:s,context:a,onError:l,onState:u,onReopen:d}){let m=!1,g=(await i({uri:o})).contents.find((x)=>x.mimeType==="text/html;profile=mcp-app"&&typeof x.text==="string");if(!g)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 Bi(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:a(b)});y.onreadresource=i,y.oncalltool=s,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,Z)=>{v=setTimeout(()=>Z(Error("Comparison App initialization timed out.")),15000),y.oninitialized=()=>{clearTimeout(v),x()}});y.onsandboxready=()=>y.sendSandboxResourceReady({html:g.text,csp:g._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});let H=new ResizeObserver(()=>y.setHostContext(a(b)));try{await Promise.all([y.connect(new Ji(b.contentWindow,b.contentWindow)),L]),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 Ku(e,t){return t===e||t.startsWith(e+"/")||t.startsWith(e+".")}function PS(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}:{}}])),i=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=i.get(l.id);i.set(l.id,{...u,...l,kind:"tokens",drafts:u?.drafts??[]})}let s=(l,u)=>l==="tokens"&&u.kind==="tokens"||(u.unit?u.unit===l:Ku(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)=>s(f,d)))continue;let m=i.get(d.id);if(!m)m={...d,draftOnly:!0,drafts:[]},i.set(d.id,m);a(m,l)}}for(let l of r)for(let u of l.units){let d=u.split("/")[0];if(!["brand","tokens","components","patterns","composition"].includes(d))continue;let m=[...i.values()].filter((f)=>s(u,f));if(m.length)for(let f of m)a(f,l);else i.set(u,{id:u,unit:u,title:u.split("/").at(-1),kind:d,draftOnly:!0,pendingDraftScenario:!0,drafts:[n.get(l.id)]})}return{scenarios:[...i.values()],categories:[...i.values()].filter((l)=>l.kind==="tokens")}}function TS(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),i=o?n?.scenarios?.find((l)=>l.id===e.id)??n:t?.previews?.find((l)=>l.id===e.id)??e.build,s=i?.state==="error"?"error":i?.state==="checking"||i?.live?"checking":i?.building||["queued","building"].includes(i?.state)?"building":i?.current?"ready":i?.stale?"stale":"unreported",a={error:ya(i),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:s,label:`${o?"Draft · ":""}${a[s]}${o&&s==="ready"?" · unaccepted":""}`}}var ES={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 Nc="ads://project/icons";function Q(e,t={},...r){let o=Object.assign(document.createElement(e),t);return o.append(...r.filter((n)=>n!==null&&n!==void 0&&n!==!1)),o}var Tw={fill:"black",stroke:"none","stroke-width":"1","stroke-linecap":"butt","stroke-linejoin":"miter","stroke-miterlimit":"4","stroke-dasharray":"none","fill-opacity":"1","stroke-opacity":"1","fill-rule":"nonzero"};function Ew(e){let t=new DOMParser().parseFromString(e,"image/svg+xml").documentElement;if(t.namespaceURI!=="http://www.w3.org/2000/svg"||t.localName!=="svg")return null;for(let o of t.querySelectorAll("*"))if(["script","foreignObject","iframe","image","a","animate","set","animateTransform","animateMotion"].includes(o.localName)||o.namespaceURI!=="http://www.w3.org/2000/svg")o.remove();for(let o of[t,...t.querySelectorAll("*")])for(let n of Array.from(o.attributes))if(/^on/i.test(n.name)||/href$/i.test(n.name)&&!n.value.trim().startsWith("#"))o.removeAttribute(n.name);let r=document.importNode(t,!0);for(let o of["width","height","class"])r.removeAttribute(o);for(let[o,n]of Object.entries(Tw))if(!r.style.getPropertyValue(o))r.style.setProperty(o,r.getAttribute(o)??n);return r.setAttribute("aria-hidden","true"),r.setAttribute("focusable","false"),r}function Gu(e,t,r){let o=Q("span",{className:"icons-glyph"});o.style.width=o.style.height=`${t}px`;let n=Ew(e.svg);if(n)o.append(n);if(r)o.setAttribute("role","img"),o.setAttribute("aria-label",r),o.title=r;else o.setAttribute("aria-hidden","true");return o}function kw(e){let t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("class","icons-grid"),t.setAttribute("aria-hidden","true"),t.setAttribute("viewBox",`${e.x} ${e.y} ${e.width} ${e.height}`),t.setAttribute("preserveAspectRatio","xMidYMid meet");let r=Math.max(1,Math.ceil(Math.max(e.width,e.height)/48)),o=(n,i,s,a,l)=>{let u=document.createElementNS("http://www.w3.org/2000/svg","line");for(let[d,m]of Object.entries({x1:n,y1:i,x2:s,y2:a}))u.setAttribute(d,m);if(l)u.setAttribute("class","mid");t.append(u)};for(let n=0;n<=e.width;n+=r)o(e.x+n,e.y,e.x+n,e.y+e.height,n*2===e.width);for(let n=0;n<=e.height;n+=r)o(e.x,e.y+n,e.x+e.width,e.y+n,n*2===e.height);if(e.width%2&&r===1)o(e.x+e.width/2,e.y,e.x+e.width/2,e.y+e.height,!0);if(e.height%2&&r===1)o(e.x,e.y+e.height/2,e.x+e.width,e.y+e.height/2,!0);return t}var Yu=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function $w(e){let t=e.filter((r)=>r.severity==="error").length;return t===e.length?Yu(t,"error"):Yu(e.length,"issue")}function kS(e){return Q("p",{className:"icons-finding",title:e.file??""},Q("strong",{textContent:e.rule})," ",e.message)}function Cw(e,t){let r=Q("article",{className:"icons-card"});if(r.dataset.glyph=e.name,e.findings.length)r.dataset.findings=String(e.findings.length);let o=Q("div",{className:"icons-card-head"},Q("h3",{textContent:e.name}),e.findings.length?Q("span",{className:"icons-badge",textContent:$w(e.findings)}):null),n=Q("div",{className:"icons-mag"});if(e.grid)n.append(kw(e.grid));n.append(Gu(e,96));let i=Q("div",{className:"icons-sizes"},...t.map((s)=>Q("span",{className:"icons-size"},Gu(e,s.px),Q("small",{textContent:String(s.px),title:s.token}))));return r.append(...[o,Q("p",{className:"icons-alias",textContent:e.aliases.length?`alias: ${e.aliases.join(", ")}`:"",title:e.aliases.join(", ")}),n,i,...e.findings.map(kS)].filter(Boolean)),r.setAttribute("aria-label",e.name),r}function Iw(e){let t=Q("figure",{className:"icons-logo"});if(t.dataset.logo=e.name,e.tooLarge)return t.append(Q("figcaption",{textContent:`${e.name} (over 1 MB; not shown)`})),t;let r=Q("span",{className:"icons-logo-muted",title:`${e.name}, muted`});return r.setAttribute("aria-hidden","true"),r.style.maskImage=r.style.webkitMaskImage=`url("${e.src}")`,t.append(Q("img",{src:e.src,alt:e.name,title:e.file}),r,Q("figcaption",{textContent:e.name})),t}var Ow=(e,t)=>!t||[e.name,...e.aliases].some((r)=>r.toLowerCase().includes(t));function $S(e,t){let r=e.querySelector(":scope > .icons-view"),o=r?.querySelector("input[type=search]")?.value??"",n=r?.scrollTop??0;if(r=Q("div",{className:"icons-view"}),r.setAttribute("role","region"),r.setAttribute("aria-label","Icons"),!t?.configured)return r.append(Q("h1",{textContent:"Icons"}),Q("p",{className:"icons-summary",textContent:"The project configures no glyph set (assets.glyphs)."})),e.replaceChildren(r),r;let i=t.mixed?"mixed grids":t.grid?`${/^(?:8|11|18)(?!\d)|^8/.test(String(t.grid.width))?"an":"a"} ${t.grid.width}×${t.grid.height} grid`:"no viewBox",s=`${t.source} · ${Yu(t.glyphs.length,"glyph")} on ${i} · ${t.aliasCount} ${t.aliasCount===1?"alias":"aliases"}`,a=Q("input",{type:"search",placeholder:"Search name or alias",value:o});a.setAttribute("aria-label","Search glyphs by name or alias");let l=Q("div",{className:"icons-set"});l.setAttribute("role","list"),l.setAttribute("aria-label","The set");let u=Q("div",{className:"icons-cards"}),d=Q("p",{className:"icons-empty",hidden:!0}),m=t.textSize;r.append(Q("div",{className:"icons-head"},Q("div",{},Q("h1",{textContent:"Icons"}),Q("p",{className:"icons-summary",textContent:s})),a),...t.findings.map(kS),Q("h2",{},"The set ",Q("small",{textContent:m?`every glyph at ${m.px} px, the size used beside text`:"every glyph"})),l,Q("h2",{},"Glyphs ",Q("small",{textContent:t.sizes.length?"each on its grid, at every icon size":"each on its grid"})),d,u);for(let g of t.glyphs){let b=Q("span",{className:"icons-set-item"},Gu(g,m?.px??18,g.name));b.dataset.glyph=g.name,b.setAttribute("role","listitem"),l.append(b),u.append(Cw(g,t.sizes))}if(t.logos)r.append(Q("h2",{},"Other products' logos ",Q("small",{textContent:`${t.logos.source} · in color and muted`})),t.logos.files.length?Q("div",{className:"icons-logos"},...t.logos.files.map(Iw)):Q("p",{className:"icons-summary",textContent:"No images yet."}));let f=()=>{let g=a.value.trim().toLowerCase(),b=0;t.glyphs.forEach((y,v)=>{let L=Ow(y,g);l.children[v].hidden=u.children[v].hidden=!L,b+=L}),d.hidden=b>0,d.textContent=`No glyph matches “${a.value.trim()}”.`};if(a.addEventListener("input",f),f(),e.replaceChildren(r),r.scrollTop=n,o&&document.activeElement===document.body)a.focus();return r}var k=(e)=>document.getElementById(e),De=new URLSearchParams(location.search),CS=De.get("scenario")??De.get("category"),Nw=["brand","tokens","icons","components","patterns","composition"],Mc=!1,sn=[],be,jc=De.get("draft"),nd=[],NS=[],sd=new Map,ln=De.get("split")==="1",ed,fr=[],$t=0,Fc;async function Qi(){let e=fr;fr=[],await Promise.allSettled(e.map((t)=>t.close()))}var nt=document.createElement("button");nt.id="split-view";nt.setAttribute("aria-label","Split view");nt.setAttribute("aria-pressed","false");nt.disabled=!0;nt.title="Select a draft with an accepted version to compare";nt.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>';k("viewport").before(nt);var te="brand",Ze={},IS=new Map,Wi=!0,id=[],Hc=[],Vc=[],rt,ea,fe,ye,rn,Gi,an,Lc,on,Ge=0,cn=De.get("capture")!=="1"&&De.get("viewport")==="phone",ot=[{name:"light",scheme:"light"},{name:"dark",scheme:"dark"}],Kt=De.get("capture")==="1"&&De.get("theme")||"light";if(De.get("capture")==="1")document.documentElement.dataset.capture="true";var td=()=>ot.find((e)=>e.name===Kt)?.scheme??"light";function AS(){document.documentElement.dataset.theme=td();let e=ot[(ot.findIndex((r)=>r.name===Kt)+1)%ot.length],t=ot.length>1?`Use ${e.name} theme`:`Theme: ${Kt}`;k("theme").setAttribute("aria-label",t),k("theme").title=t,k("theme").disabled=ot.length<2,k("theme").querySelector("svg").innerHTML=td()==="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"/>'}document.documentElement.dataset.theme="light";var Qr=[],pt=De.get("capture")==="1"&&De.get("brand")||null;function qS(){let e=k("brand-select");if(e.hidden=!Qr.length,e.options.length!==Qr.length||Qr.some((t,r)=>e.options[r].value!==t.name))e.replaceChildren(...Qr.map((t)=>Object.assign(document.createElement("option"),{value:t.name,textContent:t.name})));if(pt)e.value=pt,e.title=`Brand: ${pt}`}var Xu,MS=!0,Ac=!1,Uc,rd,Jc=!1,Yi=!1,hr,Bt,Qu=0,Ki,eo=new AbortController,Ct=new uS({name:"ads-showcase",version:"1.0.0"},{versionNegotiation:{mode:"auto"},capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}),jS=(e,t={},r={})=>Ct.callTool({name:e,arguments:t},{signal:eo.signal,...r}),Zc=zS((e)=>Ct.readResource(e,{signal:eo.signal}),{signal:eo.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)}}),ad=async(e)=>JSON.parse((await Zc({uri:e})).contents.find((t)=>typeof t.text==="string").text);function LS(e){let t=Vc.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 Ct.callTool(e)}function Se(e,t=!1,r=t?"error":e?"checking":"ready"){let o=e||"Preview is up to date.";if(k("preview-error").hidden=!t,k("preview-error-message").textContent=t?o.split(`
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(),_T=p({method:h("ui/notifications/host-context-changed"),params:yS.describe("Partial context update containing only changed fields.")}),yw=p({method:h("ui/update-model-context"),params:p({content:S(Pt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:P(c(),M().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),vw=p({method:h("ui/initialize"),params:p({appInfo:Rt.describe("App identification (name and version)."),appCapabilities:fw.describe("Features and capabilities this app provides."),protocolVersion:c().describe("Protocol version this app supports.")})}),zw=p({protocolVersion:c().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Rt.describe("Host application identification and version."),hostCapabilities:mw.describe("Features and capabilities provided by the host."),hostContext:yS.describe("Rich context about the host environment.")}).passthrough();class Ji{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=ut.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!==ew)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var ww=[bS];class Bi extends Ec{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new SS;_methods=new _S;setRequestHandler=(...e)=>{let[t,...r]=hS("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...r)};setNotificationHandler=(...e)=>{let[t,...r]=hS("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:lw,sandboxready:cw,initialized:gw,requestteardown:hw,loggingmessage:Fr};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:vw.shape.params,result:zw},(n)=>this._onAppsInitialize(n)),this.replaceRequestHandler("ping",(n,i)=>(this.onping?.(n.params,i),{})),this.replaceRequestHandler("ui/request-display-mode",{params:fS.shape.params,result:gS},()=>({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:bw.shape.params,result:aw},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:nw.shape.params,result:sw},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:_w.shape.params,result:iw},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:fS.shape.params,result:gS},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:yw.shape.params,result:cr},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:ww.includes(t)?t:bS,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],i=e[o];if(Rw(n,i))continue;t[o]=i,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},pw,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 Rw(e,t){return JSON.stringify(e)===JSON.stringify(t)}var vS=[200,800],xw=(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 i=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),s=()=>{clearTimeout(i),t.removeEventListener("abort",s),o(t.reason)};t?.addEventListener("abort",s,{once:!0})})}function zS(e,{signal:t,onDiagnostic:r,wait:o=Pw}={}){return async(n)=>{for(let i=1;;i++){t?.throwIfAborted();try{let s=await e(n);if(t?.throwIfAborted(),i>1)r?.({state:"recovered",uri:n.uri,attempt:i});return s}catch(s){if(t?.throwIfAborted(),!xw(s))throw s;if(i>vS.length)throw r?.({state:"exhausted",uri:n.uri,attempt:i,message:s.message}),Object.assign(Error(`MCP resource transport failed for ${n.uri} after ${i} attempts: ${s.message}. Inspect the host connection and browser network diagnostics; this resource-loading error does not establish a component assertion failure.`,{cause:s}),{code:"ADS_RESOURCE_TRANSPORT"});let a=vS[i-1];r?.({state:"retry",uri:n.uri,attempt:i,nextAttempt:i+1,delayMs:a,message:s.message}),await o(a,t)}}}}function wS(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 xS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:i,callTool:s,context:a,onError:l,onState:u}){let d={slot:e,title:t,sandboxUrl:r,resourceUri:o,readResource:i,callTool:s,context:a,onError:l,onState:u},m=n,f,g,b,y=!1;function v(){if(y||b)return;u?.({state:"loading"}),b=Promise.resolve().then(async()=>{if(await g,await f?.close(),y)return;g=RS({...d,result:m,onReopen:v});try{f=await g}finally{g=void 0}}).catch((L)=>{if(!y)l(L)}).finally(()=>{b=void 0})}g=RS({...d,result:m,onReopen:v});try{f=await g}finally{g=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 RS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:i,callTool:s,context:a,onError:l,onState:u,onReopen:d}){let m=!1,g=(await i({uri:o})).contents.find((x)=>x.mimeType==="text/html;profile=mcp-app"&&typeof x.text==="string");if(!g)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 Bi(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:a(b)});y.onreadresource=i,y.oncalltool=s,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,Z)=>{v=setTimeout(()=>Z(Error("Comparison App initialization timed out.")),15000),y.oninitialized=()=>{clearTimeout(v),x()}});y.onsandboxready=()=>y.sendSandboxResourceReady({html:g.text,csp:g._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});let H=new ResizeObserver(()=>y.setHostContext(a(b)));try{await Promise.all([y.connect(new Ji(b.contentWindow,b.contentWindow)),L]),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 Ku(e,t){return t===e||t.startsWith(e+"/")||t.startsWith(e+".")}function PS(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}:{}}])),i=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=i.get(l.id);i.set(l.id,{...u,...l,kind:"tokens",drafts:u?.drafts??[]})}let s=(l,u)=>l==="tokens"&&u.kind==="tokens"||(u.unit?u.unit===l:Ku(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)=>s(f,d)))continue;let m=i.get(d.id);if(!m)m={...d,draftOnly:!0,drafts:[]},i.set(d.id,m);a(m,l)}}for(let l of r)for(let u of l.units){let d=u.split("/")[0];if(!["brand","tokens","components","patterns","composition"].includes(d))continue;let m=[...i.values()].filter((f)=>s(u,f));if(m.length)for(let f of m)a(f,l);else i.set(u,{id:u,unit:u,title:u.split("/").at(-1),kind:d,draftOnly:!0,pendingDraftScenario:!0,drafts:[n.get(l.id)]})}return{scenarios:[...i.values()],categories:[...i.values()].filter((l)=>l.kind==="tokens")}}function TS(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),i=o?n?.scenarios?.find((l)=>l.id===e.id)??n:t?.previews?.find((l)=>l.id===e.id)??e.build,s=i?.state==="error"?"error":i?.state==="checking"||i?.live?"checking":i?.building||["queued","building"].includes(i?.state)?"building":i?.current?"ready":i?.stale?"stale":"unreported",a={error:ya(i),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:s,label:`${o?"Draft · ":""}${a[s]}${o&&s==="ready"?" · unaccepted":""}`}}var ES={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 Nc="ads://project/icons";function X(e,t={},...r){let o=Object.assign(document.createElement(e),t);return o.append(...r.filter((n)=>n!==null&&n!==void 0&&n!==!1)),o}var Tw={fill:"black",stroke:"none","stroke-width":"1","stroke-linecap":"butt","stroke-linejoin":"miter","stroke-miterlimit":"4","stroke-dasharray":"none","fill-opacity":"1","stroke-opacity":"1","fill-rule":"nonzero"};function Ew(e){let t=new DOMParser().parseFromString(e,"image/svg+xml").documentElement;if(t.namespaceURI!=="http://www.w3.org/2000/svg"||t.localName!=="svg")return null;for(let o of t.querySelectorAll("*"))if(["script","foreignObject","iframe","image","a","animate","set","animateTransform","animateMotion"].includes(o.localName)||o.namespaceURI!=="http://www.w3.org/2000/svg")o.remove();for(let o of[t,...t.querySelectorAll("*")])for(let n of Array.from(o.attributes))if(/^on/i.test(n.name)||/href$/i.test(n.name)&&!n.value.trim().startsWith("#"))o.removeAttribute(n.name);let r=document.importNode(t,!0);for(let o of["width","height","class"])r.removeAttribute(o);for(let[o,n]of Object.entries(Tw))if(!r.style.getPropertyValue(o))r.style.setProperty(o,r.getAttribute(o)??n);return r.setAttribute("aria-hidden","true"),r.setAttribute("focusable","false"),r}function Gu(e,t,r){let o=X("span",{className:"icons-glyph"});o.style.width=o.style.height=`${t}px`;let n=Ew(e.svg);if(n)o.append(n);if(r)o.setAttribute("role","img"),o.setAttribute("aria-label",r),o.title=r;else o.setAttribute("aria-hidden","true");return o}function kw(e){let t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("class","icons-grid"),t.setAttribute("aria-hidden","true"),t.setAttribute("viewBox",`${e.x} ${e.y} ${e.width} ${e.height}`),t.setAttribute("preserveAspectRatio","xMidYMid meet");let r=Math.max(1,Math.ceil(Math.max(e.width,e.height)/48)),o=(n,i,s,a,l)=>{let u=document.createElementNS("http://www.w3.org/2000/svg","line");for(let[d,m]of Object.entries({x1:n,y1:i,x2:s,y2:a}))u.setAttribute(d,m);if(l)u.setAttribute("class","mid");t.append(u)};for(let n=0;n<=e.width;n+=r)o(e.x+n,e.y,e.x+n,e.y+e.height,n*2===e.width);for(let n=0;n<=e.height;n+=r)o(e.x,e.y+n,e.x+e.width,e.y+n,n*2===e.height);if(e.width%2&&r===1)o(e.x+e.width/2,e.y,e.x+e.width/2,e.y+e.height,!0);if(e.height%2&&r===1)o(e.x,e.y+e.height/2,e.x+e.width,e.y+e.height/2,!0);return t}var Yu=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function $w(e){let t=e.filter((r)=>r.severity==="error").length;return t===e.length?Yu(t,"error"):Yu(e.length,"issue")}function kS(e){return X("p",{className:"icons-finding",title:e.file??""},X("strong",{textContent:e.rule})," ",e.message)}function Cw(e,t){let r=X("article",{className:"icons-card"});if(r.dataset.glyph=e.name,e.findings.length)r.dataset.findings=String(e.findings.length);let o=X("div",{className:"icons-card-head"},X("h3",{textContent:e.name}),e.findings.length?X("span",{className:"icons-badge",textContent:$w(e.findings)}):null),n=X("div",{className:"icons-mag"});if(e.grid)n.append(kw(e.grid));n.append(Gu(e,96));let i=X("div",{className:"icons-sizes"},...t.map((s)=>X("span",{className:"icons-size"},Gu(e,s.px),X("small",{textContent:String(s.px),title:s.token}))));return r.append(...[o,X("p",{className:"icons-alias",textContent:e.aliases.length?`alias: ${e.aliases.join(", ")}`:"",title:e.aliases.join(", ")}),n,i,...e.findings.map(kS)].filter(Boolean)),r.setAttribute("aria-label",e.name),r}function Iw(e){let t=X("figure",{className:"icons-logo"});if(t.dataset.logo=e.name,e.tooLarge)return t.append(X("figcaption",{textContent:`${e.name} (over 1 MB; not shown)`})),t;return t.append(X("span",{className:"icons-logo-tile"},X("img",{src:e.src,alt:e.name,title:e.file})),X("span",{className:"icons-logo-tile icons-logo-tile-black"},X("img",{src:e.src,alt:""})),X("figcaption",{textContent:e.name})),t}var Ow=(e,t)=>!t||[e.name,...e.aliases].some((r)=>r.toLowerCase().includes(t));function $S(e,t){let r=e.querySelector(":scope > .icons-view"),o=r?.querySelector("input[type=search]")?.value??"",n=r?.scrollTop??0;if(r=X("div",{className:"icons-view"}),r.setAttribute("role","region"),r.setAttribute("aria-label","Icons"),!t?.configured)return r.append(X("h1",{textContent:"Icons"}),X("p",{className:"icons-summary",textContent:"The project configures no glyph set (assets.glyphs)."})),e.replaceChildren(r),r;let i=t.mixed?"mixed grids":t.grid?`${/^(?:8|11|18)(?!\d)|^8/.test(String(t.grid.width))?"an":"a"} ${t.grid.width}×${t.grid.height} grid`:"no viewBox",s=`${t.source} · ${Yu(t.glyphs.length,"glyph")} on ${i} · ${t.aliasCount} ${t.aliasCount===1?"alias":"aliases"}`,a=X("input",{type:"search",placeholder:"Search name or alias",value:o});a.setAttribute("aria-label","Search glyphs by name or alias");let l=X("div",{className:"icons-set"});l.setAttribute("role","list"),l.setAttribute("aria-label","The set");let u=X("div",{className:"icons-cards"}),d=X("p",{className:"icons-empty",hidden:!0}),m=t.textSize;r.append(X("div",{className:"icons-head"},X("div",{},X("h1",{textContent:"Icons"}),X("p",{className:"icons-summary",textContent:s})),a),...t.findings.map(kS),X("h2",{},"The set ",X("small",{textContent:m?`every glyph at ${m.px} px, the size used beside text`:"every glyph"})),l,X("h2",{},"Glyphs ",X("small",{textContent:t.sizes.length?"each on its grid, at every icon size":"each on its grid"})),d,u);for(let g of t.glyphs){let b=X("span",{className:"icons-set-item"},Gu(g,m?.px??18,g.name));b.dataset.glyph=g.name,b.setAttribute("role","listitem"),l.append(b),u.append(Cw(g,t.sizes))}if(t.logos)r.append(X("h2",{},"Other products' logos ",X("small",{textContent:t.logos.source})),t.logos.files.length?X("div",{className:"icons-logos"},...t.logos.files.map(Iw)):X("p",{className:"icons-summary",textContent:"No images yet."}));let f=()=>{let g=a.value.trim().toLowerCase(),b=0;t.glyphs.forEach((y,v)=>{let L=Ow(y,g);l.children[v].hidden=u.children[v].hidden=!L,b+=L}),d.hidden=b>0,d.textContent=`No glyph matches “${a.value.trim()}”.`};if(a.addEventListener("input",f),f(),e.replaceChildren(r),r.scrollTop=n,o&&document.activeElement===document.body)a.focus();return r}var k=(e)=>document.getElementById(e),De=new URLSearchParams(location.search),CS=De.get("scenario")??De.get("category"),Nw=["brand","tokens","icons","components","patterns","composition"],Mc=!1,sn=[],be,jc=De.get("draft"),nd=[],NS=[],sd=new Map,ln=De.get("split")==="1",ed,fr=[],$t=0,Fc;async function Qi(){let e=fr;fr=[],await Promise.allSettled(e.map((t)=>t.close()))}var nt=document.createElement("button");nt.id="split-view";nt.setAttribute("aria-label","Split view");nt.setAttribute("aria-pressed","false");nt.disabled=!0;nt.title="Select a draft with an accepted version to compare";nt.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>';k("viewport").before(nt);var te="brand",Ze={},IS=new Map,Wi=!0,id=[],Hc=[],Vc=[],rt,ea,fe,ye,rn,Gi,an,Lc,on,Ge=0,cn=De.get("capture")!=="1"&&De.get("viewport")==="phone",ot=[{name:"light",scheme:"light"},{name:"dark",scheme:"dark"}],Kt=De.get("capture")==="1"&&De.get("theme")||"light";if(De.get("capture")==="1")document.documentElement.dataset.capture="true";var td=()=>ot.find((e)=>e.name===Kt)?.scheme??"light";function AS(){document.documentElement.dataset.theme=td();let e=ot[(ot.findIndex((r)=>r.name===Kt)+1)%ot.length],t=ot.length>1?`Use ${e.name} theme`:`Theme: ${Kt}`;k("theme").setAttribute("aria-label",t),k("theme").title=t,k("theme").disabled=ot.length<2,k("theme").querySelector("svg").innerHTML=td()==="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"/>'}document.documentElement.dataset.theme="light";var Qr=[],pt=De.get("capture")==="1"&&De.get("brand")||null;function qS(){let e=k("brand-select");if(e.hidden=!Qr.length,e.options.length!==Qr.length||Qr.some((t,r)=>e.options[r].value!==t.name))e.replaceChildren(...Qr.map((t)=>Object.assign(document.createElement("option"),{value:t.name,textContent:t.name})));if(pt)e.value=pt,e.title=`Brand: ${pt}`}var Xu,MS=!0,Ac=!1,Uc,rd,Jc=!1,Yi=!1,hr,Bt,Qu=0,Ki,eo=new AbortController,Ct=new uS({name:"ads-showcase",version:"1.0.0"},{versionNegotiation:{mode:"auto"},capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}),jS=(e,t={},r={})=>Ct.callTool({name:e,arguments:t},{signal:eo.signal,...r}),Zc=zS((e)=>Ct.readResource(e,{signal:eo.signal}),{signal:eo.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)}}),ad=async(e)=>JSON.parse((await Zc({uri:e})).contents.find((t)=>typeof t.text==="string").text);function LS(e){let t=Vc.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 Ct.callTool(e)}function Se(e,t=!1,r=t?"error":e?"checking":"ready"){let o=e||"Preview is up to date.";if(k("preview-error").hidden=!t,k("preview-error-message").textContent=t?o.split(`
120
120
  `)[0]:"",k("preview-error-message").title=t?o:"",k("status").textContent=o,k("status").dataset.error=String(t),!t)for(let n of["errorCategory","errorCode","resourceUri"])delete k("status").dataset[n];if(t)k("status").removeAttribute("role");else k("status").setAttribute("role","status");k("preview-status").dataset.phase=r,k("preview-status").title=o,k("preview-status").setAttribute("aria-label",`Preview status: ${o.split(`
121
121
  `)[0]}`),US()}function US(){let e=ea?.warmup,t=e?`Background views: ${e.completed}/${e.total} compiled${e.failed?`; ${e.failed} failed`:""}.`:"";k("warmup-status").hidden=!e,k("warmup-status").textContent=t,k("preview-status").dataset.warmup=e?.state??"disabled",k("preview-status").title=[k("status").textContent,t].filter(Boolean).join(`
122
122
  `)}function ZS(){Se(fe?"Updating preview…":"Opening preview…",!1,"reloading")}function un(){return ta().find((e)=>e.id===Ze[te])}function dn(e=un()){let t=sn.find((r)=>r.id===jc&&sd.get(r.id)?.scenario===e?.id);return e?.drafts?.find((r)=>r.id===jc)??t??e?.drafts?.[0]}function cd(){return Boolean(dn()&&(un()?.draftOnly||ln))}function Xi(){return`${te}:${Ze[te]}${cd()?`:draft:${dn().id}`:""}`}function qc(e=fe){return e?.key===Xi()}function DS(e=ea){if(cd()){let t=e?.drafts?.find((r)=>r.id===dn()?.id);return t?.scenarios?.find((r)=>r.id===Ze[te])??t}return e?.previews?.find((t)=>t.id===Ze[te])}var FS=(e)=>JSON.stringify(e&&[e.session,e.revision,e.current,e.live]);function HS(){({scenarios:Hc,categories:id}=PS(nd,NS,sn,sd))}function Aw(e){sd.set(e.structuredContent.id,e.structuredContent),HS()}async function od(e,t,r=eo.signal){let o=(rt?.previewWatch?.buildTimeoutMs??30000)+15000;try{return await jS(e,t,{signal:AbortSignal.any([eo.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 ld(e,t,r){let o=un()?.id===t&&un().pendingDraftScenario||e.units?.includes(t)&&!nd.some((i)=>i.id===t),n=await od("ads_show_draft",{id:e.id,...!o&&t?{scenario:t}:{}},r);if(n.isError)throw Error(n.content?.find((i)=>i.type==="text")?.text??"Draft preview failed.");if(o){let i=n.structuredContent.scenarios.find((s)=>t==="tokens"?s.kind==="tokens":s.unit?s.unit===t:Ku(t,s.id));if(!i)throw Error("Draft owner has no scenario yet. Add an independently mountable scenario before previewing it.");if(i.id!==n.structuredContent.scenario)n=await od("ads_show_draft",{id:e.id,scenario:i.id},r);if(n.isError)throw Error(n.content?.find((s)=>s.type==="text")?.text??"Draft preview failed.")}return Aw(n),n}function Wt(e=!1){if(e)on=fe?.key;an=void 0,k("loader").hidden=!0,k("preview").setAttribute("aria-busy","false")}function OS(e){let t=new URL(location.href);for(let n of["scenario","category","draft","split","section"])t.searchParams.delete(n);if(te==="icons")return t.searchParams.set("section","icons"),t.pathname+t.search+t.hash;if(e)t.searchParams.set("scenario",e);let r=ta().find((n)=>n.id===e),o=dn(r);if(o&&(r.draftOnly||ln)){if(t.searchParams.set("draft",o.id),!r.draftOnly)t.searchParams.set("split","1")}return t.pathname+t.search+t.hash}function ta(){return te==="tokens"?id:te==="icons"?[]:Hc.filter((e)=>e.kind===te)}function VS(e,t){let{state:r,label:o}=TS(t,ea,jc),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">${ES[r]}</svg>`,e.dataset.buildState=r,e.setAttribute("aria-description",o)}var nn=!1;function to(){return{theme:td(),adsTheme:Kt,...pt?{adsBrand:pt}:{},gridOverlay:nn,displayMode:"inline",containerDimensions:{width:k("frame-slot").clientWidth,height:k("frame-slot").clientHeight}}}function ra(){let e=Hc.some((n)=>n.kind==="brand");if(k("sections").querySelector('[data-section="brand"]').hidden=!e,te==="brand"&&!e)te="tokens";if(k("sections").querySelector('[data-section="icons"]').hidden=!rt?.icons,te==="icons"&&!rt?.icons)te="tokens";document.body.dataset.activeSection=te;let t=ta();if(!t.some((n)=>n.id===Ze[te]))Ze[te]=t[0]?.id??null;history.replaceState(null,"",OS(Ze[te]));let r=k("sidebar").scrollTop;k("entries").setAttribute("aria-label",te[0].toUpperCase()+te.slice(1));let o=(n)=>{let i=document.createElement("a");if(i.textContent=n.title,n.drafts?.length){let s=document.createElement("span");s.className="draft-badge",s.textContent=n.drafts.length>1?`Drafts ${n.drafts.length}`:"Draft",s.title=n.draftOnly?"Draft only; no accepted version yet":"Draft available; use Split view to compare",i.append(" ",s)}if(i.href=OS(n.id),i.dataset.scenario=n.id,VS(i,n),n.id===Ze[te])i.setAttribute("aria-current","page");return i.addEventListener("click",(s)=>{if(s.button||s.metaKey||s.ctrlKey||s.shiftKey||s.altKey)return;s.preventDefault(),Ze[te]=n.id,ra(),Gt().catch(ht)}),i};k("entries").replaceChildren(...wS(t).flatMap((n)=>{if(!n.label)return n.entries.map(o);let i=`${te}:${n.label}`,s=document.createElement("details");s.className="entry-group",s.open=IS.get(i)??!0;let a=document.createElement("summary");a.textContent=n.label;let l=document.createElement("div");return l.setAttribute("role","group"),l.setAttribute("aria-label",n.label),l.append(...n.entries.map(o)),s.append(a,l),s.addEventListener("toggle",()=>{if(s.isConnected)IS.set(i,s.open)}),[s]})),k("sidebar").scrollTop=r;for(let n of k("sections").querySelectorAll("button"))if(n.dataset.section===te)n.setAttribute("aria-current","page");else n.removeAttribute("aria-current");Dc()}function ht(e){if(!Jc&&!Yi)Wt(),k("status").dataset.errorCategory=e.category??(e.code==="ADS_RESOURCE_TRANSPORT"?"transport":"runner"),k("status").dataset.errorCode=e.code??"ADS_HOST_STARTUP",Se(`${e.message}${fe?`