@mcp-b/global 5.1.0 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -65
- package/dist/index.d.ts +2 -11
- package/dist/index.iife.js +11 -6
- package/dist/index.js +24 -73
- package/dist/index.js.map +1 -1
- package/package.json +5 -8
package/dist/index.iife.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var WebMCP=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t;let n=Object.freeze({status:`aborted`});function r(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var i=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},a=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(t=globalThis).__zod_globalConfig??(t.__zod_globalConfig={});let o=globalThis.__zod_globalConfig;function s(e){return e&&Object.assign(o,e),o}function c(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function l(e,t){return typeof t==`bigint`?t.toString():t}function u(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}throw Error(`cached value already set`)}}}function d(e){return e==null}function f(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function p(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}let m=Symbol(`evaluating`);function h(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==m)return r===void 0&&(r=m,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function g(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function _(...e){let t={};for(let n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function ee(e){return JSON.stringify(e)}function te(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}let ne=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function re(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}let ie=u(()=>{if(o.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function ae(e){if(re(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(re(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function oe(e){return ae(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let se=new Set([`string`,`number`,`symbol`]);function ce(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function v(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function y(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}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function le(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}let ue={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function de(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return v(e,_(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return g(this,`shape`,e),e},checks:[]}))}function fe(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return v(e,_(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return g(this,`shape`,r),r},checks:[]}))}function pe(e,t){if(!ae(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return v(e,_(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return g(this,`shape`,n),n}}))}function me(e,t){if(!ae(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return v(e,_(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return g(this,`shape`,n),n}}))}function he(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return v(e,_(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return g(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function ge(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return v(t,_(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return g(this,`shape`,i),i},checks:[]}))}function _e(e,t,n){return v(t,_(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return g(this,`shape`,i),i}}))}function ve(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function ye(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function be(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function b(e){return typeof e==`string`?e:e?.message}function x(e,t,n){let r=e.message?e.message:b(e.inst?._zod.def?.error?.(e))??b(t?.error?.(e))??b(n.customError?.(e))??b(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function xe(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Se(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}let Ce=(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,l,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},we=r(`$ZodError`,Ce),S=r(`$ZodError`,Ce,{Parent:Error});function Te(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ee(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}let De=e=>(t,n,r,a)=>{let o=r?{...r,async:!1}:{async:!1},c=t._zod.run({value:n,issues:[]},o);if(c instanceof Promise)throw new i;if(c.issues.length){let t=new(a?.Err??e)(c.issues.map(e=>x(e,o,s())));throw ne(t,a?.callee),t}return c.value},Oe=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>x(e,a,s())));throw ne(t,i?.callee),t}return o.value},ke=e=>(t,n,r)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new i;return o.issues.length?{success:!1,error:new(e??we)(o.issues.map(e=>x(e,a,s())))}:{success:!0,data:o.value}},Ae=ke(S),je=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>x(e,i,s())))}:{success:!0,data:a.value}},Me=je(S),C=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return De(e)(t,n,i)},Ne=e=>(t,n,r)=>De(e)(t,n,r),Pe=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Oe(e)(t,n,i)},Fe=e=>async(t,n,r)=>Oe(e)(t,n,r),Ie=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ke(e)(t,n,i)},Le=e=>(t,n,r)=>ke(e)(t,n,r),Re=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return je(e)(t,n,i)},ze=e=>async(t,n,r)=>je(e)(t,n,r),Be=/^[cC][0-9a-z]{6,}$/,Ve=/^[0-9a-z]+$/,He=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ue=/^[0-9a-vA-V]{20}$/,We=/^[A-Za-z0-9]{27}$/,Ge=/^[a-zA-Z0-9_-]{21}$/,Ke=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,qe=/^([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})$/,Je=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Ye=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function Xe(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}let Ze=/^(?:(?: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])$/,Qe=/^(([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}|:))$/,$e=/^((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])$/,et=/^(([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])$/,tt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,nt=/^[A-Za-z0-9_-]*$/,rt=/^https?$/,w=/^\+[1-9]\d{6,14}$/,it=`(?:(?:\\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])))`,at=RegExp(`^${it}$`);function ot(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function st(e){return RegExp(`^${ot(e)}$`)}function ct(e){let t=ot({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${it}T(?:${r})$`)}let lt=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},ut=/^-?\d+$/,dt=/^-?\d+(?:\.\d+)?$/,ft=/^(?:true|false)$/i,pt=/^null$/i,mt=/^[^A-Z]*$/,ht=/^[^a-z]*$/,T=r(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),gt={number:`number`,bigint:`bigint`,object:`date`},_t=r(`$ZodCheckLessThan`,(e,t)=>{T.init(e,t);let n=gt[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),vt=r(`$ZodCheckGreaterThan`,(e,t)=>{T.init(e,t);let n=gt[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),yt=r(`$ZodCheckMultipleOf`,(e,t)=>{T.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):p(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),bt=r(`$ZodCheckNumberFormat`,(e,t)=>{T.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=ue[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=ut)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),xt=r(`$ZodCheckMaxLength`,(e,t)=>{var n;T.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!d(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=xe(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),St=r(`$ZodCheckMinLength`,(e,t)=>{var n;T.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!d(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=xe(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ct=r(`$ZodCheckLengthEquals`,(e,t)=>{var n;T.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!d(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=xe(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),wt=r(`$ZodCheckStringFormat`,(e,t)=>{var n,r;T.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&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})}):(r=e._zod).check??(r.check=()=>{})}),Tt=r(`$ZodCheckRegex`,(e,t)=>{wt.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Et=r(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=mt,wt.init(e,t)}),Dt=r(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=ht,wt.init(e,t)}),Ot=r(`$ZodCheckIncludes`,(e,t)=>{T.init(e,t);let n=ce(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),kt=r(`$ZodCheckStartsWith`,(e,t)=>{T.init(e,t);let n=RegExp(`^${ce(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),At=r(`$ZodCheckEndsWith`,(e,t)=>{T.init(e,t);let n=RegExp(`.*${ce(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),jt=r(`$ZodCheckOverwrite`,(e,t)=>{T.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Mt=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
1
|
+
var WebMCP=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t;let n=Object.freeze({status:`aborted`});function r(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var i=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},a=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(t=globalThis).__zod_globalConfig??(t.__zod_globalConfig={});let o=globalThis.__zod_globalConfig;function s(e){return e&&Object.assign(o,e),o}function c(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function l(e,t){return typeof t==`bigint`?t.toString():t}function u(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}throw Error(`cached value already set`)}}}function d(e){return e==null}function f(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function p(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}let m=Symbol(`evaluating`);function h(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==m)return r===void 0&&(r=m,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function g(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function _(...e){let t={};for(let n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function ee(e){return JSON.stringify(e)}function te(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}let ne=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function re(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}let ie=u(()=>{if(o.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function ae(e){if(re(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(re(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function oe(e){return ae(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let se=new Set([`string`,`number`,`symbol`]);function ce(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function le(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function v(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}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function ue(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}let de={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function fe(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return le(e,_(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return g(this,`shape`,e),e},checks:[]}))}function pe(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return le(e,_(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return g(this,`shape`,r),r},checks:[]}))}function me(e,t){if(!ae(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return le(e,_(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return g(this,`shape`,n),n}}))}function he(e,t){if(!ae(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return le(e,_(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return g(this,`shape`,n),n}}))}function ge(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return le(e,_(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return g(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function _e(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return le(t,_(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return g(this,`shape`,i),i},checks:[]}))}function ve(e,t,n){return le(t,_(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return g(this,`shape`,i),i}}))}function ye(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function be(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function xe(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function y(e){return typeof e==`string`?e:e?.message}function b(e,t,n){let r=e.message?e.message:y(e.inst?._zod.def?.error?.(e))??y(t?.error?.(e))??y(n.customError?.(e))??y(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function Se(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Ce(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}let we=(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,l,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Te=r(`$ZodError`,we),x=r(`$ZodError`,we,{Parent:Error});function Ee(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function De(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}let Oe=e=>(t,n,r,a)=>{let o=r?{...r,async:!1}:{async:!1},c=t._zod.run({value:n,issues:[]},o);if(c instanceof Promise)throw new i;if(c.issues.length){let t=new(a?.Err??e)(c.issues.map(e=>b(e,o,s())));throw ne(t,a?.callee),t}return c.value},ke=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>b(e,a,s())));throw ne(t,i?.callee),t}return o.value},Ae=e=>(t,n,r)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new i;return o.issues.length?{success:!1,error:new(e??Te)(o.issues.map(e=>b(e,a,s())))}:{success:!0,data:o.value}},je=Ae(x),Me=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>b(e,i,s())))}:{success:!0,data:a.value}},Ne=Me(x),S=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Oe(e)(t,n,i)},Pe=e=>(t,n,r)=>Oe(e)(t,n,r),Fe=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ke(e)(t,n,i)},Ie=e=>async(t,n,r)=>ke(e)(t,n,r),Le=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ae(e)(t,n,i)},Re=e=>(t,n,r)=>Ae(e)(t,n,r),ze=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Me(e)(t,n,i)},Be=e=>async(t,n,r)=>Me(e)(t,n,r),Ve=/^[cC][0-9a-z]{6,}$/,He=/^[0-9a-z]+$/,Ue=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,We=/^[0-9a-vA-V]{20}$/,Ge=/^[A-Za-z0-9]{27}$/,Ke=/^[a-zA-Z0-9_-]{21}$/,qe=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Je=/^([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})$/,Ye=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Xe=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function Ze(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}let Qe=/^(?:(?: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])$/,$e=/^(([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}|:))$/,et=/^((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])$/,tt=/^(([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])$/,nt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,rt=/^[A-Za-z0-9_-]*$/,it=/^https?$/,C=/^\+[1-9]\d{6,14}$/,at=`(?:(?:\\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])))`,ot=RegExp(`^${at}$`);function st(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ct(e){return RegExp(`^${st(e)}$`)}function lt(e){let t=st({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${at}T(?:${r})$`)}let ut=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},dt=/^-?\d+$/,ft=/^-?\d+(?:\.\d+)?$/,pt=/^(?:true|false)$/i,mt=/^null$/i,ht=/^[^A-Z]*$/,gt=/^[^a-z]*$/,w=r(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),_t={number:`number`,bigint:`bigint`,object:`date`},vt=r(`$ZodCheckLessThan`,(e,t)=>{w.init(e,t);let n=_t[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),yt=r(`$ZodCheckGreaterThan`,(e,t)=>{w.init(e,t);let n=_t[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),bt=r(`$ZodCheckMultipleOf`,(e,t)=>{w.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):p(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),xt=r(`$ZodCheckNumberFormat`,(e,t)=>{w.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=de[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=dt)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),St=r(`$ZodCheckMaxLength`,(e,t)=>{var n;w.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!d(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=Se(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ct=r(`$ZodCheckMinLength`,(e,t)=>{var n;w.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!d(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=Se(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),wt=r(`$ZodCheckLengthEquals`,(e,t)=>{var n;w.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!d(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=Se(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Tt=r(`$ZodCheckStringFormat`,(e,t)=>{var n,r;w.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&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})}):(r=e._zod).check??(r.check=()=>{})}),Et=r(`$ZodCheckRegex`,(e,t)=>{Tt.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Dt=r(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=ht,Tt.init(e,t)}),Ot=r(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=gt,Tt.init(e,t)}),kt=r(`$ZodCheckIncludes`,(e,t)=>{w.init(e,t);let n=ce(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),At=r(`$ZodCheckStartsWith`,(e,t)=>{w.init(e,t);let n=RegExp(`^${ce(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),jt=r(`$ZodCheckEndsWith`,(e,t)=>{w.init(e,t);let n=RegExp(`.*${ce(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Mt=r(`$ZodCheckOverwrite`,(e,t)=>{w.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Nt=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
2
2
|
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
|
|
3
|
-
`))}};let
|
|
3
|
+
`))}};let Pt={major:4,minor:4,patch:3},T=r(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Pt;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=ye(e),a;for(let o of t){if(o._zod.def.when){if(be(e)||!o._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,s=o._zod.check(e);if(s instanceof Promise&&n?.async===!1)throw new i;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,e.issues.length!==t&&(r||=ye(e,t))});else{if(e.issues.length===t)continue;r||=ye(e,t)}}return a?a.then(()=>e):e},n=(n,a,o)=>{if(ye(n))return n.aborted=!0,n;let s=t(a,r,o);if(s instanceof Promise){if(o.async===!1)throw new i;return s.then(t=>e._zod.parse(t,o))}return e._zod.parse(s,o)};e._zod.run=(a,o)=>{if(o.skipChecks)return e._zod.parse(a,o);if(o.direction===`backward`){let t=e._zod.parse({value:a.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,a,o)):n(t,a,o)}let s=e._zod.parse(a,o);if(s instanceof Promise){if(o.async===!1)throw new i;return s.then(e=>t(e,r,o))}return t(s,r,o)}}h(e,`~standard`,()=>({validate:t=>{try{let n=je(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Ne(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),Ft=r(`$ZodString`,(e,t)=>{T.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ut(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),E=r(`$ZodStringFormat`,(e,t)=>{Tt.init(e,t),Ft.init(e,t)}),It=r(`$ZodGUID`,(e,t)=>{t.pattern??=Je,E.init(e,t)}),Lt=r(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Ye(e)}else t.pattern??=Ye();E.init(e,t)}),Rt=r(`$ZodEmail`,(e,t)=>{t.pattern??=Xe,E.init(e,t)}),zt=r(`$ZodURL`,(e,t)=>{E.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===it.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Bt=r(`$ZodEmoji`,(e,t)=>{t.pattern??=Ze(),E.init(e,t)}),Vt=r(`$ZodNanoID`,(e,t)=>{t.pattern??=Ke,E.init(e,t)}),Ht=r(`$ZodCUID`,(e,t)=>{t.pattern??=Ve,E.init(e,t)}),Ut=r(`$ZodCUID2`,(e,t)=>{t.pattern??=He,E.init(e,t)}),Wt=r(`$ZodULID`,(e,t)=>{t.pattern??=Ue,E.init(e,t)}),Gt=r(`$ZodXID`,(e,t)=>{t.pattern??=We,E.init(e,t)}),Kt=r(`$ZodKSUID`,(e,t)=>{t.pattern??=Ge,E.init(e,t)}),qt=r(`$ZodISODateTime`,(e,t)=>{t.pattern??=lt(t),E.init(e,t)}),Jt=r(`$ZodISODate`,(e,t)=>{t.pattern??=ot,E.init(e,t)}),Yt=r(`$ZodISOTime`,(e,t)=>{t.pattern??=ct(t),E.init(e,t)}),Xt=r(`$ZodISODuration`,(e,t)=>{t.pattern??=qe,E.init(e,t)}),Zt=r(`$ZodIPv4`,(e,t)=>{t.pattern??=Qe,E.init(e,t),e._zod.bag.format=`ipv4`}),Qt=r(`$ZodIPv6`,(e,t)=>{t.pattern??=$e,E.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),$t=r(`$ZodCIDRv4`,(e,t)=>{t.pattern??=et,E.init(e,t)}),en=r(`$ZodCIDRv6`,(e,t)=>{t.pattern??=tt,E.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function tn(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let nn=r(`$ZodBase64`,(e,t)=>{t.pattern??=nt,E.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{tn(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function rn(e){if(!rt.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return tn(t.padEnd(Math.ceil(t.length/4)*4,`=`))}let an=r(`$ZodBase64URL`,(e,t)=>{t.pattern??=rt,E.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{rn(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),on=r(`$ZodE164`,(e,t)=>{t.pattern??=C,E.init(e,t)});function sn(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}let cn=r(`$ZodJWT`,(e,t)=>{E.init(e,t),e._zod.check=n=>{sn(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),ln=r(`$ZodNumber`,(e,t)=>{T.init(e,t),e._zod.pattern=e._zod.bag.pattern??ft,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),un=r(`$ZodNumberFormat`,(e,t)=>{xt.init(e,t),ln.init(e,t)}),dn=r(`$ZodBoolean`,(e,t)=>{T.init(e,t),e._zod.pattern=pt,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),fn=r(`$ZodNull`,(e,t)=>{T.init(e,t),e._zod.pattern=mt,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),pn=r(`$ZodAny`,(e,t)=>{T.init(e,t),e._zod.parse=e=>e}),mn=r(`$ZodUnknown`,(e,t)=>{T.init(e,t),e._zod.parse=e=>e}),hn=r(`$ZodNever`,(e,t)=>{T.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function gn(e,t,n){e.issues.length&&t.issues.push(...xe(n,e.issues)),t.value[n]=e.value}let _n=r(`$ZodArray`,(e,t)=>{T.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>gn(t,n,e))):gn(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function vn(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...xe(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function yn(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=ue(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function bn(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>vn(e,n,i,t,u,d))):vn(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}let xn=r(`$ZodObject`,(e,t)=>{if(T.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=u(()=>yn(t));h(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=re,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>vn(n,t,e,s,r,i))):vn(a,t,e,s,r,i)}return i?bn(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Sn=r(`$ZodObjectJIT`,(e,t)=>{xn.init(e,t);let n=e._zod.parse,r=u(()=>yn(t)),i=e=>{let t=new Nt([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=ee(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=ee(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(`
|
|
4
4
|
if (${n}.issues.length) {
|
|
5
5
|
if (${o} in input) {
|
|
6
6
|
payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
@@ -59,13 +59,18 @@ var WebMCP=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Modul
|
|
|
59
59
|
}
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
-
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,s=re,c=!o.jitless,l=c&&ie.value,d=t.catchall,f;e._zod.parse=(o,u)=>{f??=r.value;let p=o.value;return s(p)?c&&l&&u?.async===!1&&u.jitless!==!0?(a||=i(t.shape),o=a(o,u),d?yn([],p,o,u,f,e):o):n(o,u):(o.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),o)}});function Sn(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!ve(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>x(e,r,s())))}),t)}let Cn=r(`$ZodUnion`,(e,t)=>{E.init(e,t),h(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),h(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),h(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),h(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>f(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Sn(t,r,e,i)):Sn(o,r,e,i)}}),wn=r(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Cn.init(e,t);let n=e._zod.parse;h(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(let r of n)e[t].add(r)}}return e});let r=u(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!re(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),Tn=r(`$ZodIntersection`,(e,t)=>{E.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Dn(e,t,n)):Dn(e,i,a)}});function En(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(ae(e)&&ae(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=En(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=En(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Dn(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),ve(e))return e;let o=En(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}let On=r(`$ZodRecord`,(e,t)=>{E.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!ae(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let c=new Set;for(let l of o)if(typeof l==`string`||typeof l==`number`||typeof l==`symbol`){c.add(typeof l==`number`?l.toString():l);let o=t.keyType._zod.run({value:l,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>x(e,r,s())),input:l,path:[l],inst:e});continue}let u=o.value,d=t.valueType._zod.run({value:i[l],issues:[]},r);d instanceof Promise?a.push(d.then(e=>{e.issues.length&&n.issues.push(...be(l,e.issues)),n.value[u]=e.value})):(d.issues.length&&n.issues.push(...be(l,d.issues)),n.value[u]=d.value)}let l;for(let e in i)c.has(e)||(l??=[],l.push(e));l&&l.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:l})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let c=t.keyType._zod.run({value:o,issues:[]},r);if(c instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&dt.test(o)&&c.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(c=e)}if(c.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:c.issues.map(e=>x(e,r,s())),input:o,path:[o],inst:e});continue}let l=t.valueType._zod.run({value:i[o],issues:[]},r);l instanceof Promise?a.push(l.then(e=>{e.issues.length&&n.issues.push(...be(o,e.issues)),n.value[c.value]=e.value})):(l.issues.length&&n.issues.push(...be(o,l.issues)),n.value[c.value]=l.value)}}return a.length?Promise.all(a).then(()=>n):n}}),kn=r(`$ZodEnum`,(e,t)=>{E.init(e,t);let n=c(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>se.has(typeof e)).map(e=>typeof e==`string`?ce(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),An=r(`$ZodLiteral`,(e,t)=>{if(E.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?ce(e):e?ce(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),jn=r(`$ZodTransform`,(e,t)=>{E.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new a(e.constructor.name);let o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(e=>(n.value=e,n.fallback=!0,n));if(o instanceof Promise)throw new i;return n.value=o,n.fallback=!0,n}});function Mn(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}let Nn=r(`$ZodOptional`,(e,t)=>{E.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,h(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),h(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${f(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>Mn(e,r)):Mn(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Pn=r(`$ZodExactOptional`,(e,t)=>{Nn.init(e,t),h(e._zod,`values`,()=>t.innerType._zod.values),h(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Fn=r(`$ZodNullable`,(e,t)=>{E.init(e,t),h(e._zod,`optin`,()=>t.innerType._zod.optin),h(e._zod,`optout`,()=>t.innerType._zod.optout),h(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${f(e.source)}|null)$`):void 0}),h(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),In=r(`$ZodDefault`,(e,t)=>{E.init(e,t),e._zod.optin=`optional`,h(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Ln(e,t)):Ln(r,t)}});function Ln(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}let Rn=r(`$ZodPrefault`,(e,t)=>{E.init(e,t),e._zod.optin=`optional`,h(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),zn=r(`$ZodNonOptional`,(e,t)=>{E.init(e,t),h(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Bn(t,e)):Bn(i,e)}});function Bn(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}let Vn=r(`$ZodCatch`,(e,t)=>{E.init(e,t),e._zod.optin=`optional`,h(e._zod,`optout`,()=>t.innerType._zod.optout),h(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>x(e,n,s()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>x(e,n,s()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Hn=r(`$ZodPipe`,(e,t)=>{E.init(e,t),h(e._zod,`values`,()=>t.in._zod.values),h(e._zod,`optin`,()=>t.in._zod.optin),h(e._zod,`optout`,()=>t.out._zod.optout),h(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Un(e,t.in,n)):Un(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Un(e,t.out,n)):Un(r,t.out,n)}});function Un(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}let Wn=r(`$ZodPreprocess`,(e,t)=>{Hn.init(e,t)}),Gn=r(`$ZodReadonly`,(e,t)=>{E.init(e,t),h(e._zod,`propValues`,()=>t.innerType._zod.propValues),h(e._zod,`values`,()=>t.innerType._zod.values),h(e._zod,`optin`,()=>t.innerType?._zod?.optin),h(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Kn):Kn(r)}});function Kn(e){return e.value=Object.freeze(e.value),e}let qn=r(`$ZodLazy`,(e,t)=>{E.init(e,t),h(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),h(e._zod,`pattern`,()=>e._zod.innerType?._zod?.pattern),h(e._zod,`propValues`,()=>e._zod.innerType?._zod?.propValues),h(e._zod,`optin`,()=>e._zod.innerType?._zod?.optin??void 0),h(e._zod,`optout`,()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Jn=r(`$ZodCustom`,(e,t)=>{T.init(e,t),E.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Yn(t,n,r,e));Yn(i,n,r,e)}});function Yn(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Se(e))}}var Xn,Zn=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Qn(){return new Zn}(Xn=globalThis).__zod_globalRegistry??(Xn.__zod_globalRegistry=Qn());let $n=globalThis.__zod_globalRegistry;function er(e,t){return new e({type:`string`,...y(t)})}function tr(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...y(t)})}function nr(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...y(t)})}function rr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...y(t)})}function ir(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...y(t)})}function ar(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...y(t)})}function or(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...y(t)})}function sr(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...y(t)})}function cr(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...y(t)})}function lr(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...y(t)})}function ur(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...y(t)})}function dr(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...y(t)})}function fr(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...y(t)})}function pr(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...y(t)})}function mr(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...y(t)})}function hr(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...y(t)})}function gr(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...y(t)})}function _r(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...y(t)})}function vr(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...y(t)})}function yr(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...y(t)})}function br(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...y(t)})}function xr(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...y(t)})}function Sr(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...y(t)})}function Cr(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...y(t)})}function wr(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...y(t)})}function Tr(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...y(t)})}function Er(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...y(t)})}function Dr(e,t){return new e({type:`number`,checks:[],...y(t)})}function Or(e,t){return new e({type:`number`,coerce:!0,checks:[],...y(t)})}function kr(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...y(t)})}function Ar(e,t){return new e({type:`boolean`,...y(t)})}function jr(e,t){return new e({type:`null`,...y(t)})}function Mr(e){return new e({type:`any`})}function Nr(e){return new e({type:`unknown`})}function Pr(e,t){return new e({type:`never`,...y(t)})}function Fr(e,t){return new _t({check:`less_than`,...y(t),value:e,inclusive:!1})}function Ir(e,t){return new _t({check:`less_than`,...y(t),value:e,inclusive:!0})}function Lr(e,t){return new vt({check:`greater_than`,...y(t),value:e,inclusive:!1})}function Rr(e,t){return new vt({check:`greater_than`,...y(t),value:e,inclusive:!0})}function zr(e,t){return new yt({check:`multiple_of`,...y(t),value:e})}function Br(e,t){return new xt({check:`max_length`,...y(t),maximum:e})}function Vr(e,t){return new St({check:`min_length`,...y(t),minimum:e})}function Hr(e,t){return new Ct({check:`length_equals`,...y(t),length:e})}function Ur(e,t){return new Tt({check:`string_format`,format:`regex`,...y(t),pattern:e})}function Wr(e){return new Et({check:`string_format`,format:`lowercase`,...y(e)})}function Gr(e){return new Dt({check:`string_format`,format:`uppercase`,...y(e)})}function Kr(e,t){return new Ot({check:`string_format`,format:`includes`,...y(t),includes:e})}function qr(e,t){return new kt({check:`string_format`,format:`starts_with`,...y(t),prefix:e})}function Jr(e,t){return new At({check:`string_format`,format:`ends_with`,...y(t),suffix:e})}function Yr(e){return new jt({check:`overwrite`,tx:e})}function Xr(e){return Yr(t=>t.normalize(e))}function Zr(){return Yr(e=>e.trim())}function Qr(){return Yr(e=>e.toLowerCase())}function $r(){return Yr(e=>e.toUpperCase())}function ei(){return Yr(e=>te(e))}function ti(e,t,n){return new e({type:`array`,element:t,...y(n)})}function ni(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...y(n)})}function ri(e,t){let n=ii(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Se(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Se(r))}},e(t.value,t)),t);return n}function ii(e,t){let n=new T({check:`custom`,...y(t)});return n._zod.check=e,n}function ai(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??$n,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 O(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,O(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&ci(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function oi(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
62
|
+
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,s=re,c=!o.jitless,l=c&&ie.value,d=t.catchall,f;e._zod.parse=(o,u)=>{f??=r.value;let p=o.value;return s(p)?c&&l&&u?.async===!1&&u.jitless!==!0?(a||=i(t.shape),o=a(o,u),d?bn([],p,o,u,f,e):o):n(o,u):(o.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),o)}});function Cn(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!ye(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>b(e,r,s())))}),t)}let wn=r(`$ZodUnion`,(e,t)=>{T.init(e,t),h(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),h(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),h(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),h(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>f(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Cn(t,r,e,i)):Cn(o,r,e,i)}}),Tn=r(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,wn.init(e,t);let n=e._zod.parse;h(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(let r of n)e[t].add(r)}}return e});let r=u(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!re(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),En=r(`$ZodIntersection`,(e,t)=>{T.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>On(e,t,n)):On(e,i,a)}});function Dn(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(ae(e)&&ae(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Dn(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Dn(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function On(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),ye(e))return e;let o=Dn(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}let kn=r(`$ZodRecord`,(e,t)=>{T.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!ae(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let c=new Set;for(let l of o)if(typeof l==`string`||typeof l==`number`||typeof l==`symbol`){c.add(typeof l==`number`?l.toString():l);let o=t.keyType._zod.run({value:l,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>b(e,r,s())),input:l,path:[l],inst:e});continue}let u=o.value,d=t.valueType._zod.run({value:i[l],issues:[]},r);d instanceof Promise?a.push(d.then(e=>{e.issues.length&&n.issues.push(...xe(l,e.issues)),n.value[u]=e.value})):(d.issues.length&&n.issues.push(...xe(l,d.issues)),n.value[u]=d.value)}let l;for(let e in i)c.has(e)||(l??=[],l.push(e));l&&l.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:l})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let c=t.keyType._zod.run({value:o,issues:[]},r);if(c instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&ft.test(o)&&c.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(c=e)}if(c.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:c.issues.map(e=>b(e,r,s())),input:o,path:[o],inst:e});continue}let l=t.valueType._zod.run({value:i[o],issues:[]},r);l instanceof Promise?a.push(l.then(e=>{e.issues.length&&n.issues.push(...xe(o,e.issues)),n.value[c.value]=e.value})):(l.issues.length&&n.issues.push(...xe(o,l.issues)),n.value[c.value]=l.value)}}return a.length?Promise.all(a).then(()=>n):n}}),An=r(`$ZodEnum`,(e,t)=>{T.init(e,t);let n=c(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>se.has(typeof e)).map(e=>typeof e==`string`?ce(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),jn=r(`$ZodLiteral`,(e,t)=>{if(T.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?ce(e):e?ce(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Mn=r(`$ZodTransform`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new a(e.constructor.name);let o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(e=>(n.value=e,n.fallback=!0,n));if(o instanceof Promise)throw new i;return n.value=o,n.fallback=!0,n}});function Nn(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}let Pn=r(`$ZodOptional`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,h(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),h(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${f(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>Nn(e,r)):Nn(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Fn=r(`$ZodExactOptional`,(e,t)=>{Pn.init(e,t),h(e._zod,`values`,()=>t.innerType._zod.values),h(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),In=r(`$ZodNullable`,(e,t)=>{T.init(e,t),h(e._zod,`optin`,()=>t.innerType._zod.optin),h(e._zod,`optout`,()=>t.innerType._zod.optout),h(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${f(e.source)}|null)$`):void 0}),h(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Ln=r(`$ZodDefault`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,h(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Rn(e,t)):Rn(r,t)}});function Rn(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}let zn=r(`$ZodPrefault`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,h(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Bn=r(`$ZodNonOptional`,(e,t)=>{T.init(e,t),h(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Vn(t,e)):Vn(i,e)}});function Vn(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}let Hn=r(`$ZodCatch`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,h(e._zod,`optout`,()=>t.innerType._zod.optout),h(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>b(e,n,s()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>b(e,n,s()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Un=r(`$ZodPipe`,(e,t)=>{T.init(e,t),h(e._zod,`values`,()=>t.in._zod.values),h(e._zod,`optin`,()=>t.in._zod.optin),h(e._zod,`optout`,()=>t.out._zod.optout),h(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Wn(e,t.in,n)):Wn(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Wn(e,t.out,n)):Wn(r,t.out,n)}});function Wn(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}let Gn=r(`$ZodPreprocess`,(e,t)=>{Un.init(e,t)}),Kn=r(`$ZodReadonly`,(e,t)=>{T.init(e,t),h(e._zod,`propValues`,()=>t.innerType._zod.propValues),h(e._zod,`values`,()=>t.innerType._zod.values),h(e._zod,`optin`,()=>t.innerType?._zod?.optin),h(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(qn):qn(r)}});function qn(e){return e.value=Object.freeze(e.value),e}let Jn=r(`$ZodLazy`,(e,t)=>{T.init(e,t),h(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),h(e._zod,`pattern`,()=>e._zod.innerType?._zod?.pattern),h(e._zod,`propValues`,()=>e._zod.innerType?._zod?.propValues),h(e._zod,`optin`,()=>e._zod.innerType?._zod?.optin??void 0),h(e._zod,`optout`,()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Yn=r(`$ZodCustom`,(e,t)=>{w.init(e,t),T.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Xn(t,n,r,e));Xn(i,n,r,e)}});function Xn(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Ce(e))}}var Zn,Qn=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function $n(){return new Qn}(Zn=globalThis).__zod_globalRegistry??(Zn.__zod_globalRegistry=$n());let er=globalThis.__zod_globalRegistry;function tr(e,t){return new e({type:`string`,...v(t)})}function nr(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...v(t)})}function rr(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...v(t)})}function ir(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...v(t)})}function ar(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...v(t)})}function or(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...v(t)})}function sr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...v(t)})}function cr(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...v(t)})}function lr(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...v(t)})}function ur(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...v(t)})}function dr(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...v(t)})}function fr(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...v(t)})}function pr(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...v(t)})}function mr(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...v(t)})}function hr(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...v(t)})}function gr(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...v(t)})}function _r(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...v(t)})}function vr(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...v(t)})}function yr(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...v(t)})}function br(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...v(t)})}function xr(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...v(t)})}function Sr(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...v(t)})}function Cr(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...v(t)})}function wr(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...v(t)})}function Tr(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...v(t)})}function Er(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...v(t)})}function Dr(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...v(t)})}function Or(e,t){return new e({type:`number`,checks:[],...v(t)})}function kr(e,t){return new e({type:`number`,coerce:!0,checks:[],...v(t)})}function Ar(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...v(t)})}function jr(e,t){return new e({type:`boolean`,...v(t)})}function Mr(e,t){return new e({type:`null`,...v(t)})}function Nr(e){return new e({type:`any`})}function Pr(e){return new e({type:`unknown`})}function Fr(e,t){return new e({type:`never`,...v(t)})}function Ir(e,t){return new vt({check:`less_than`,...v(t),value:e,inclusive:!1})}function Lr(e,t){return new vt({check:`less_than`,...v(t),value:e,inclusive:!0})}function Rr(e,t){return new yt({check:`greater_than`,...v(t),value:e,inclusive:!1})}function zr(e,t){return new yt({check:`greater_than`,...v(t),value:e,inclusive:!0})}function Br(e,t){return new bt({check:`multiple_of`,...v(t),value:e})}function Vr(e,t){return new St({check:`max_length`,...v(t),maximum:e})}function Hr(e,t){return new Ct({check:`min_length`,...v(t),minimum:e})}function Ur(e,t){return new wt({check:`length_equals`,...v(t),length:e})}function Wr(e,t){return new Et({check:`string_format`,format:`regex`,...v(t),pattern:e})}function Gr(e){return new Dt({check:`string_format`,format:`lowercase`,...v(e)})}function Kr(e){return new Ot({check:`string_format`,format:`uppercase`,...v(e)})}function qr(e,t){return new kt({check:`string_format`,format:`includes`,...v(t),includes:e})}function Jr(e,t){return new At({check:`string_format`,format:`starts_with`,...v(t),prefix:e})}function Yr(e,t){return new jt({check:`string_format`,format:`ends_with`,...v(t),suffix:e})}function Xr(e){return new Mt({check:`overwrite`,tx:e})}function Zr(e){return Xr(t=>t.normalize(e))}function Qr(){return Xr(e=>e.trim())}function $r(){return Xr(e=>e.toLowerCase())}function ei(){return Xr(e=>e.toUpperCase())}function ti(){return Xr(e=>te(e))}function ni(e,t,n){return new e({type:`array`,element:t,...v(n)})}function ri(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...v(n)})}function ii(e,t){let n=ai(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Ce(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Ce(r))}},e(t.value,t)),t);return n}function ai(e,t){let n=new w({check:`custom`,...v(t)});return n._zod.check=e,n}function oi(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??er,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 D(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,D(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&li(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function si(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
63
63
|
|
|
64
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function si(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:ui(t,`input`,e.processors),output:ui(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function ci(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return ci(r.element,n);if(r.type===`set`)return ci(r.valueType,n);if(r.type===`lazy`)return ci(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return ci(r.innerType,n);if(r.type===`intersection`)return ci(r.left,n)||ci(r.right,n);if(r.type===`record`||r.type===`map`)return ci(r.keyType,n)||ci(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:ci(r.in,n)||ci(r.out,n);if(r.type===`object`){for(let e in r.shape)if(ci(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(ci(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(ci(e,n))return!0;return!!(r.rest&&ci(r.rest,n))}return!1}let li=(e,t={})=>n=>{let r=ai({...n,processors:t});return O(e,r),oi(r,e),si(r,e)},ui=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=ai({...i??{},target:a,io:t,processors:n});return O(e,o),oi(o,e),si(o,e)},di={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},fi=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=di[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},pi=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},mi=(e,t,n,r)=>{n.type=`boolean`},hi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},gi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},_i=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},vi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},yi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},bi=(e,t,n,r)=>{n.not={}},xi=(e,t,n,r)=>{},Si=(e,t,n,r)=>{},Ci=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},wi=(e,t,n,r)=>{let i=e._zod.def,a=c(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Ti=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},Ei=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},Di=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Oi=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},ki=(e,t,n,r)=>{n.type=`boolean`},Ai=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},ji=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},Mi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Ni=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},Pi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},Fi=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=O(a.element,t,{...r,path:[...r.path,`items`]})},Ii=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=O(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=O(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Li=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>O(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ri=(e,t,n,r)=>{let i=e._zod.def,a=O(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=O(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},zi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>O(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?O(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},Bi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=O(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=O(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=O(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},Vi=(e,t,n,r)=>{let i=e._zod.def,a=O(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Hi=(e,t,n,r)=>{let i=e._zod.def;O(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ui=(e,t,n,r)=>{let i=e._zod.def;O(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Wi=(e,t,n,r)=>{let i=e._zod.def;O(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Gi=(e,t,n,r)=>{let i=e._zod.def;O(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},Ki=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;O(o,t,r);let s=t.seen.get(e);s.ref=o},qi=(e,t,n,r)=>{let i=e._zod.def;O(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Ji=(e,t,n,r)=>{let i=e._zod.def;O(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Yi=(e,t,n,r)=>{let i=e._zod.def;O(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xi=(e,t,n,r)=>{let i=e._zod.innerType;O(i,t,r);let a=t.seen.get(e);a.ref=i},Zi={string:fi,number:pi,boolean:mi,bigint:hi,symbol:gi,null:_i,undefined:vi,void:yi,never:bi,any:xi,unknown:Si,date:Ci,enum:wi,literal:Ti,nan:Ei,template_literal:Di,file:Oi,success:ki,custom:Ai,function:ji,transform:Mi,map:Ni,set:Pi,array:Fi,object:Ii,union:Li,intersection:Ri,tuple:zi,record:Bi,nullable:Vi,nonoptional:Hi,default:Ui,prefault:Wi,catch:Gi,pipe:Ki,readonly:qi,promise:Ji,optional:Yi,lazy:Xi};function Qi(e,t){if(`_idmap`in e){let n=e,r=ai({...t,processors:Zi}),i={};for(let e of n._idmap.entries()){let[t,n]=e;O(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;oi(r,n),a[t]=si(r,n)}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=ai({...t,processors:Zi});return O(e,n),oi(n,e),si(n,e)}let $i=r(`ZodISODateTime`,(e,t)=>{Kt.init(e,t),j.init(e,t)});function ea(e){return Cr($i,e)}let ta=r(`ZodISODate`,(e,t)=>{qt.init(e,t),j.init(e,t)});function na(e){return wr(ta,e)}let ra=r(`ZodISOTime`,(e,t)=>{Jt.init(e,t),j.init(e,t)});function ia(e){return Tr(ra,e)}let aa=r(`ZodISODuration`,(e,t)=>{Yt.init(e,t),j.init(e,t)});function oa(e){return Er(aa,e)}let sa=r(`ZodError`,(e,t)=>{we.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Ee(e,t)},flatten:{value:t=>Te(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,l,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,l,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),ca=De(sa),la=Oe(sa),ua=ke(sa),da=je(sa),fa=C(sa),pa=Ne(sa),ma=Pe(sa),ha=Fe(sa),ga=Ie(sa),_a=Le(sa),va=Re(sa),ya=ze(sa),ba=new WeakMap;function xa(e,t,n){let r=Object.getPrototypeOf(e),i=ba.get(r);if(i||(i=new Set,ba.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}let k=r(`ZodType`,(e,t)=>(E.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:ui(e,`input`),output:ui(e,`output`)}}),e.toJSONSchema=li(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>ca(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ua(e,t,n),e.parseAsync=async(t,n)=>la(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>da(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>fa(e,t,n),e.decode=(t,n)=>pa(e,t,n),e.encodeAsync=async(t,n)=>ma(e,t,n),e.decodeAsync=async(t,n)=>ha(e,t,n),e.safeEncode=(t,n)=>ga(e,t,n),e.safeDecode=(t,n)=>_a(e,t,n),e.safeEncodeAsync=async(t,n)=>va(e,t,n),e.safeDecodeAsync=async(t,n)=>ya(e,t,n),xa(e,`ZodType`,{check(...e){let t=this.def;return this.clone(_(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return v(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Io(e,t))},superRefine(e,t){return this.check(Lo(e,t))},overwrite(e){return this.check(Yr(e))},optional(){return H(this)},exactOptional(){return _o(this)},nullable(){return yo(this)},nullish(){return H(yo(this))},nonoptional(e){return To(this,e)},array(){return F(this)},or(e){return R([this,e])},and(e){return co(this,e)},transform(e){return ko(this,mo(e))},default(e){return xo(this,e)},prefault(e){return Co(this,e)},catch(e){return Do(this,e)},pipe(e){return ko(this,e)},readonly(){return Mo(this)},describe(e){let t=this.clone();return $n.add(t,{description:e}),t},meta(...e){if(e.length===0)return $n.get(this);let t=this.clone();return $n.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return $n.get(e)?.description},configurable:!0}),e)),Sa=r(`_ZodString`,(e,t)=>{Pt.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,xa(e,`_ZodString`,{regex(...e){return this.check(Ur(...e))},includes(...e){return this.check(Kr(...e))},startsWith(...e){return this.check(qr(...e))},endsWith(...e){return this.check(Jr(...e))},min(...e){return this.check(Vr(...e))},max(...e){return this.check(Br(...e))},length(...e){return this.check(Hr(...e))},nonempty(...e){return this.check(Vr(1,...e))},lowercase(e){return this.check(Wr(e))},uppercase(e){return this.check(Gr(e))},trim(){return this.check(Zr())},normalize(...e){return this.check(Xr(...e))},toLowerCase(){return this.check(Qr())},toUpperCase(){return this.check($r())},slugify(){return this.check(ei())}})}),Ca=r(`ZodString`,(e,t)=>{Pt.init(e,t),Sa.init(e,t),e.email=t=>e.check(tr(wa,t)),e.url=t=>e.check(sr(Oa,t)),e.jwt=t=>e.check(Sr(Wa,t)),e.emoji=t=>e.check(cr(Aa,t)),e.guid=t=>e.check(nr(Ea,t)),e.uuid=t=>e.check(rr(Da,t)),e.uuidv4=t=>e.check(ir(Da,t)),e.uuidv6=t=>e.check(ar(Da,t)),e.uuidv7=t=>e.check(or(Da,t)),e.nanoid=t=>e.check(lr(ja,t)),e.guid=t=>e.check(nr(Ea,t)),e.cuid=t=>e.check(ur(Ma,t)),e.cuid2=t=>e.check(dr(Na,t)),e.ulid=t=>e.check(fr(Pa,t)),e.base64=t=>e.check(yr(Va,t)),e.base64url=t=>e.check(br(Ha,t)),e.xid=t=>e.check(pr(Fa,t)),e.ksuid=t=>e.check(mr(Ia,t)),e.ipv4=t=>e.check(hr(La,t)),e.ipv6=t=>e.check(gr(Ra,t)),e.cidrv4=t=>e.check(_r(za,t)),e.cidrv6=t=>e.check(vr(Ba,t)),e.e164=t=>e.check(xr(Ua,t)),e.datetime=t=>e.check(ea(t)),e.date=t=>e.check(na(t)),e.time=t=>e.check(ia(t)),e.duration=t=>e.check(oa(t))});function A(e){return er(Ca,e)}let j=r(`ZodStringFormat`,(e,t)=>{D.init(e,t),Sa.init(e,t)}),wa=r(`ZodEmail`,(e,t)=>{Lt.init(e,t),j.init(e,t)});function Ta(e){return tr(wa,e)}let Ea=r(`ZodGUID`,(e,t)=>{Ft.init(e,t),j.init(e,t)}),Da=r(`ZodUUID`,(e,t)=>{It.init(e,t),j.init(e,t)}),Oa=r(`ZodURL`,(e,t)=>{Rt.init(e,t),j.init(e,t)});function ka(e){return sr(Oa,e)}let Aa=r(`ZodEmoji`,(e,t)=>{zt.init(e,t),j.init(e,t)}),ja=r(`ZodNanoID`,(e,t)=>{Bt.init(e,t),j.init(e,t)}),Ma=r(`ZodCUID`,(e,t)=>{Vt.init(e,t),j.init(e,t)}),Na=r(`ZodCUID2`,(e,t)=>{Ht.init(e,t),j.init(e,t)}),Pa=r(`ZodULID`,(e,t)=>{Ut.init(e,t),j.init(e,t)}),Fa=r(`ZodXID`,(e,t)=>{Wt.init(e,t),j.init(e,t)}),Ia=r(`ZodKSUID`,(e,t)=>{Gt.init(e,t),j.init(e,t)}),La=r(`ZodIPv4`,(e,t)=>{Xt.init(e,t),j.init(e,t)}),Ra=r(`ZodIPv6`,(e,t)=>{Zt.init(e,t),j.init(e,t)}),za=r(`ZodCIDRv4`,(e,t)=>{Qt.init(e,t),j.init(e,t)}),Ba=r(`ZodCIDRv6`,(e,t)=>{$t.init(e,t),j.init(e,t)}),Va=r(`ZodBase64`,(e,t)=>{tn.init(e,t),j.init(e,t)}),Ha=r(`ZodBase64URL`,(e,t)=>{rn.init(e,t),j.init(e,t)}),Ua=r(`ZodE164`,(e,t)=>{an.init(e,t),j.init(e,t)}),Wa=r(`ZodJWT`,(e,t)=>{sn.init(e,t),j.init(e,t)}),Ga=r(`ZodNumber`,(e,t)=>{cn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pi(e,t,n,r),xa(e,`ZodNumber`,{gt(e,t){return this.check(Lr(e,t))},gte(e,t){return this.check(Rr(e,t))},min(e,t){return this.check(Rr(e,t))},lt(e,t){return this.check(Fr(e,t))},lte(e,t){return this.check(Ir(e,t))},max(e,t){return this.check(Ir(e,t))},int(e){return this.check(qa(e))},safe(e){return this.check(qa(e))},positive(e){return this.check(Lr(0,e))},nonnegative(e){return this.check(Rr(0,e))},negative(e){return this.check(Fr(0,e))},nonpositive(e){return this.check(Ir(0,e))},multipleOf(e,t){return this.check(zr(e,t))},step(e,t){return this.check(zr(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function M(e){return Dr(Ga,e)}let Ka=r(`ZodNumberFormat`,(e,t)=>{ln.init(e,t),Ga.init(e,t)});function qa(e){return kr(Ka,e)}let Ja=r(`ZodBoolean`,(e,t)=>{un.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mi(e,t,n,r)});function N(e){return Ar(Ja,e)}let Ya=r(`ZodNull`,(e,t)=>{dn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_i(e,t,n,r)});function Xa(e){return jr(Ya,e)}let Za=r(`ZodAny`,(e,t)=>{fn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Qa(){return Mr(Za)}let $a=r(`ZodUnknown`,(e,t)=>{pn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function P(){return Nr($a)}let eo=r(`ZodNever`,(e,t)=>{mn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bi(e,t,n,r)});function to(e){return Pr(eo,e)}let no=r(`ZodArray`,(e,t)=>{gn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fi(e,t,n,r),e.element=t.element,xa(e,`ZodArray`,{min(e,t){return this.check(Vr(e,t))},nonempty(e){return this.check(Vr(1,e))},max(e,t){return this.check(Br(e,t))},length(e,t){return this.check(Hr(e,t))},unwrap(){return this.element}})});function F(e,t){return ti(no,e,t)}let ro=r(`ZodObject`,(e,t)=>{xn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ii(e,t,n,r),h(e,`shape`,()=>t.shape),xa(e,`ZodObject`,{keyof(){return B(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:P()})},loose(){return this.clone({...this._zod.def,catchall:P()})},strict(){return this.clone({...this._zod.def,catchall:to()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return pe(this,e)},safeExtend(e){return me(this,e)},merge(e){return he(this,e)},pick(e){return de(this,e)},omit(e){return fe(this,e)},partial(...e){return ge(ho,this,e[0])},required(...e){return _e(wo,this,e[0])}})});function I(e,t){return new ro({type:`object`,shape:e??{},...y(t)})}function L(e,t){return new ro({type:`object`,shape:e,catchall:P(),...y(t)})}let io=r(`ZodUnion`,(e,t)=>{Cn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Li(e,t,n,r),e.options=t.options});function R(e,t){return new io({type:`union`,options:e,...y(t)})}let ao=r(`ZodDiscriminatedUnion`,(e,t)=>{io.init(e,t),wn.init(e,t)});function oo(e,t,n){return new ao({type:`union`,options:t,discriminator:e,...y(n)})}let so=r(`ZodIntersection`,(e,t)=>{Tn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ri(e,t,n,r)});function co(e,t){return new so({type:`intersection`,left:e,right:t})}let lo=r(`ZodRecord`,(e,t)=>{On.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bi(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function z(e,t,n){return!t||!t._zod?new lo({type:`record`,keyType:A(),valueType:e,...y(t)}):new lo({type:`record`,keyType:e,valueType:t,...y(n)})}let uo=r(`ZodEnum`,(e,t)=>{kn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wi(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new uo({...t,checks:[],...y(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new uo({...t,checks:[],...y(r),entries:i})}});function B(e,t){return new uo({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...y(t)})}let fo=r(`ZodLiteral`,(e,t)=>{An.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ti(e,t,n,r),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 V(e,t){return new fo({type:`literal`,values:Array.isArray(e)?e:[e],...y(t)})}let po=r(`ZodTransform`,(e,t)=>{jn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mi(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new a(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Se(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Se(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function mo(e){return new po({type:`transform`,transform:e})}let ho=r(`ZodOptional`,(e,t)=>{Nn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function H(e){return new ho({type:`optional`,innerType:e})}let go=r(`ZodExactOptional`,(e,t)=>{Pn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function _o(e){return new go({type:`optional`,innerType:e})}let vo=r(`ZodNullable`,(e,t)=>{Fn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function yo(e){return new vo({type:`nullable`,innerType:e})}let bo=r(`ZodDefault`,(e,t)=>{In.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ui(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function xo(e,t){return new bo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():oe(t)}})}let So=r(`ZodPrefault`,(e,t)=>{Rn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Co(e,t){return new So({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():oe(t)}})}let wo=r(`ZodNonOptional`,(e,t)=>{zn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function To(e,t){return new wo({type:`nonoptional`,innerType:e,...y(t)})}let Eo=r(`ZodCatch`,(e,t)=>{Vn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Do(e,t){return new Eo({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}let Oo=r(`ZodPipe`,(e,t)=>{Hn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ki(e,t,n,r),e.in=t.in,e.out=t.out});function ko(e,t){return new Oo({type:`pipe`,in:e,out:t})}let Ao=r(`ZodPreprocess`,(e,t)=>{Oo.init(e,t),Wn.init(e,t)}),jo=r(`ZodReadonly`,(e,t)=>{Gn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Mo(e){return new jo({type:`readonly`,innerType:e})}let No=r(`ZodLazy`,(e,t)=>{qn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xi(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Po(e){return new No({type:`lazy`,getter:e})}let Fo=r(`ZodCustom`,(e,t)=>{Jn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ai(e,t,n,r)});function Io(e,t={}){return ni(Fo,e,t)}function Lo(e,t){return ri(e,t)}function Ro(e,t){return new Ao({type:`pipe`,in:mo(e),out:t})}let zo={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 Bo;Bo||={};function Vo(e){return Or(Ga,e)}let Ho=[`2025-11-25`,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Uo=`io.modelcontextprotocol/protocolVersion`,Wo=`io.modelcontextprotocol/clientInfo`,Go=`io.modelcontextprotocol/serverInfo`,Ko=`io.modelcontextprotocol/clientCapabilities`,qo=`io.modelcontextprotocol/logLevel`,Jo=Po(()=>R([A(),M(),N(),Xa(),z(A(),Jo),F(Jo)])),U=z(A(),Jo),Yo=F(Jo),Xo=R([A(),M().int()]),Zo=A(),Qo=I({ttl:M().optional()}),$o=I({taskId:A()}),es=L({progressToken:Xo.optional(),"io.modelcontextprotocol/related-task":$o.optional()}),W=I({_meta:es.optional()}),ts=W.extend({task:Qo.optional()}),G=I({method:A(),params:W.loose().optional()}),ns=I({_meta:es.optional()}),rs=I({method:A(),params:ns.loose().optional()}),is=L({get[Go](){return vs.optional().catch(void 0)}}),K=L({_meta:is.optional()}),as=R([A(),M().int()]),os=I({jsonrpc:V(`2.0`),id:as,...G.shape}).strict(),ss=I({jsonrpc:V(`2.0`),...rs.shape}).strict(),cs=I({jsonrpc:V(`2.0`),id:as,result:K}).strict(),ls=I({jsonrpc:V(`2.0`),id:as.optional(),error:I({code:M().int(),message:A(),data:P().optional()})}).strict(),us=R([os,ss,cs,ls]),ds=R([cs,ls]),fs=K.strict(),ps=ns.extend({requestId:as.optional(),reason:A().optional()}),ms=rs.extend({method:V(`notifications/cancelled`),params:ps}),hs=I({src:A(),mimeType:A().optional(),sizes:F(A()).optional(),theme:B([`light`,`dark`]).optional()}),gs=I({icons:F(hs).optional()}),_s=I({name:A(),title:A().optional()}),vs=_s.extend({..._s.shape,...gs.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),ys=Ro(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,co(I({form:co(I({applyDefaults:N().optional()}),U).optional(),url:U.optional()}),U.optional())),bs=L({list:U.optional(),cancel:U.optional(),requests:L({sampling:L({createMessage:U.optional()}).optional(),elicitation:L({create:U.optional()}).optional()}).optional()}),xs=L({list:U.optional(),cancel:U.optional(),requests:L({tools:L({call:U.optional()}).optional()}).optional()}),Ss=I({experimental:z(A(),U).optional(),sampling:I({context:U.optional(),tools:U.optional()}).optional(),elicitation:ys.optional(),roots:I({listChanged:N().optional()}).optional(),tasks:bs.optional(),extensions:z(A(),U).optional()}),Cs=W.extend({protocolVersion:A(),capabilities:Ss,clientInfo:vs}),ws=G.extend({method:V(`initialize`),params:Cs}),Ts=I({experimental:z(A(),U).optional(),logging:U.optional(),completions:U.optional(),prompts:I({listChanged:N().optional()}).optional(),resources:I({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:I({listChanged:N().optional()}).optional(),tasks:xs.optional(),extensions:z(A(),U).optional()}),Es=K.extend({protocolVersion:A(),capabilities:Ts,serverInfo:vs,instructions:A().optional()}),Ds=rs.extend({method:V(`notifications/initialized`),params:ns.optional()}),Os=G.extend({method:V(`server/discover`),params:W.optional()}),ks=K.extend({supportedVersions:F(A()),capabilities:Ts,instructions:A().optional()}),As=G.extend({method:V(`ping`),params:W.optional()}),js=I({progress:M(),total:H(M()),message:H(A())}),Ms=I({...ns.shape,...js.shape,progressToken:Xo}),Ns=rs.extend({method:V(`notifications/progress`),params:Ms}),Ps=W.extend({cursor:Zo.optional()}),Fs=G.extend({params:Ps.optional()}),Is=K.extend({nextCursor:Zo.optional()}),Ls=I({uri:A(),mimeType:H(A()),_meta:z(A(),P()).optional()}),Rs=Ls.extend({text:A()}),zs=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Bs=Ls.extend({blob:zs}),Vs=B([`user`,`assistant`]),Hs=I({audience:F(Vs).optional(),priority:M().min(0).max(1).optional(),lastModified:ea({offset:!0}).optional()}),Us=I({..._s.shape,...gs.shape,uri:A(),description:H(A()),mimeType:H(A()),size:H(M()),annotations:Hs.optional(),_meta:H(L({}))}),Ws=I({..._s.shape,...gs.shape,uriTemplate:A(),description:H(A()),mimeType:H(A()),annotations:Hs.optional(),_meta:H(L({}))}),Gs=Fs.extend({method:V(`resources/list`)}),Ks=Is.extend({resources:F(Us)}),qs=Fs.extend({method:V(`resources/templates/list`)}),Js=Is.extend({resourceTemplates:F(Ws)}),Ys=W.extend({uri:A()}),Xs=Ys,Zs=G.extend({method:V(`resources/read`),params:Xs}),Qs=K.extend({contents:F(R([Rs,Bs]))}),$s=rs.extend({method:V(`notifications/resources/list_changed`),params:ns.optional()}),ec=Ys,tc=G.extend({method:V(`resources/subscribe`),params:ec}),nc=Ys,rc=G.extend({method:V(`resources/unsubscribe`),params:nc}),ic=I({toolsListChanged:N().optional(),promptsListChanged:N().optional(),resourcesListChanged:N().optional(),resourceSubscriptions:F(A()).optional()}),ac=W.extend({notifications:ic}),oc=G.extend({method:V(`subscriptions/listen`),params:ac}),sc=ns.extend({notifications:ic}),cc=rs.extend({method:V(`notifications/subscriptions/acknowledged`),params:sc}),lc=is.extend({"io.modelcontextprotocol/subscriptionId":as}),uc=K.extend({_meta:lc}),dc=ns.extend({uri:A()}),fc=rs.extend({method:V(`notifications/resources/updated`),params:dc}),pc=I({name:A(),description:H(A()),required:H(N())}),mc=I({..._s.shape,...gs.shape,description:H(A()),arguments:H(F(pc)),_meta:H(L({}))}),hc=Fs.extend({method:V(`prompts/list`)}),gc=Is.extend({prompts:F(mc)}),_c=W.extend({name:A(),arguments:z(A(),A()).optional()}),vc=G.extend({method:V(`prompts/get`),params:_c}),yc=I({type:V(`text`),text:A(),annotations:Hs.optional(),_meta:z(A(),P()).optional()}),bc=I({type:V(`image`),data:zs,mimeType:A(),annotations:Hs.optional(),_meta:z(A(),P()).optional()}),xc=I({type:V(`audio`),data:zs,mimeType:A(),annotations:Hs.optional(),_meta:z(A(),P()).optional()}),Sc=I({type:V(`tool_use`),name:A(),id:A(),input:z(A(),P()),_meta:z(A(),P()).optional()}),Cc=I({type:V(`resource`),resource:R([Rs,Bs]),annotations:Hs.optional(),_meta:z(A(),P()).optional()}),wc=Us.extend({type:V(`resource_link`)}),Tc=R([yc,bc,xc,wc,Cc]),Ec=I({role:Vs,content:Tc}),Dc=K.extend({description:A().optional(),messages:F(Ec)}),Oc=rs.extend({method:V(`notifications/prompts/list_changed`),params:ns.optional()}),kc=I({title:A().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),Ac=I({taskSupport:B([`required`,`optional`,`forbidden`]).optional()}),jc=I({..._s.shape,...gs.shape,description:A().optional(),inputSchema:I({type:V(`object`),properties:z(A(),Jo).optional(),required:F(A()).optional()}).catchall(P()),outputSchema:L({$schema:A().optional()}).optional(),annotations:kc.optional(),execution:Ac.optional(),_meta:z(A(),P()).optional()}),Mc=Fs.extend({method:V(`tools/list`)}),Nc=Is.extend({tools:F(jc)}),Pc=K.extend({content:F(Tc).default([]),structuredContent:P().optional(),isError:N().optional()}),Fc=Pc.or(K.extend({toolResult:P()})),Ic=ts.extend({name:A(),arguments:z(A(),P()).optional()}),Lc=G.extend({method:V(`tools/call`),params:Ic}),Rc=rs.extend({method:V(`notifications/tools/list_changed`),params:ns.optional()}),zc=I({autoRefresh:N().default(!0),debounceMs:M().int().nonnegative().default(300)}),Bc=B([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Vc=W.extend({level:Bc}),Hc=G.extend({method:V(`logging/setLevel`),params:Vc}),Uc=ns.extend({level:Bc,logger:A().optional(),data:P()}),Wc=rs.extend({method:V(`notifications/message`),params:Uc}),Gc=I({name:A().optional()}),Kc=I({hints:F(Gc).optional(),costPriority:M().min(0).max(1).optional(),speedPriority:M().min(0).max(1).optional(),intelligencePriority:M().min(0).max(1).optional()}),qc=I({mode:B([`auto`,`required`,`none`]).optional()}),Jc=I({type:V(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:F(Tc),structuredContent:P().optional(),isError:N().optional(),_meta:z(A(),P()).optional()}),Yc=oo(`type`,[yc,bc,xc]),Xc=oo(`type`,[yc,bc,xc,Sc,Jc]),Zc=I({role:Vs,content:R([Xc,F(Xc)]),_meta:z(A(),P()).optional()}),Qc=ts.extend({messages:F(Zc),modelPreferences:Kc.optional(),systemPrompt:A().optional(),includeContext:B([`none`,`thisServer`,`allServers`]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:F(A()).optional(),metadata:U.optional(),tools:F(jc).optional(),toolChoice:qc.optional()}),$c=G.extend({method:V(`sampling/createMessage`),params:Qc}),el=K.extend({model:A(),stopReason:H(B([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:Vs,content:Yc}),tl=K.extend({model:A(),stopReason:H(B([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:Vs,content:R([Xc,F(Xc)])}),nl=I({type:V(`boolean`),title:A().optional(),description:A().optional(),default:N().optional()}),rl=I({type:V(`string`),title:A().optional(),description:A().optional(),minLength:M().optional(),maxLength:M().optional(),format:B([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),il=I({type:B([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),al=I({type:V(`string`),title:A().optional(),description:A().optional(),enum:F(A()),default:A().optional()}),ol=I({type:V(`string`),title:A().optional(),description:A().optional(),oneOf:F(I({const:A(),title:A()})),default:A().optional()}),sl=I({type:V(`string`),title:A().optional(),description:A().optional(),enum:F(A()),enumNames:F(A()).optional(),default:A().optional()}),cl=R([al,ol]),ll=I({type:V(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({type:V(`string`),enum:F(A())}),default:F(A()).optional()}),ul=I({type:V(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({anyOf:F(I({const:A(),title:A()}))}),default:F(A()).optional()}),dl=R([ll,ul]),fl=R([sl,cl,dl]),pl=R([fl,nl,rl,il]),ml=ts.extend({mode:V(`form`).optional(),message:A(),requestedSchema:I({type:V(`object`),properties:z(A(),pl),required:F(A()).optional()}).catchall(P())}),hl=ts.extend({mode:V(`url`),message:A(),elicitationId:A(),url:A().url()}),gl=R([ml,hl]),_l=G.extend({method:V(`elicitation/create`),params:gl}),vl=ns.extend({elicitationId:A()}),yl=rs.extend({method:V(`notifications/elicitation/complete`),params:vl}),bl=K.extend({action:B([`accept`,`decline`,`cancel`]),content:Ro(e=>e===null?void 0:e,z(A(),R([A(),M(),N(),F(A())])).optional())}),xl=I({type:V(`ref/resource`),uri:A()}),Sl=I({type:V(`ref/prompt`),name:A()}),Cl=W.extend({ref:R([Sl,xl]),argument:I({name:A(),value:A()}),context:I({arguments:z(A(),A()).optional()}).optional()}),wl=G.extend({method:V(`completion/complete`),params:Cl}),Tl=K.extend({completion:L({values:F(A()).max(100),total:H(M().int()),hasMore:H(N())})}),El=I({uri:A().startsWith(`file://`),name:A().optional(),_meta:z(A(),P()).optional()}),Dl=G.extend({method:V(`roots/list`),params:W.optional()}),Ol=K.extend({roots:F(El)}),kl=rs.extend({method:V(`notifications/roots/list_changed`),params:ns.optional()}),Al=L({ttl:M().optional(),pollInterval:M().optional()}),jl=B([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Ml=I({taskId:A(),status:jl,ttl:R([M(),Xa()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:H(M()),statusMessage:H(A())}),Nl=K.extend({task:Ml}),Pl=ns.merge(Ml),Fl=rs.extend({method:V(`notifications/tasks/status`),params:Pl}),Il=G.extend({method:V(`tasks/get`),params:W.extend({taskId:A()})}),Ll=K.merge(Ml),Rl=G.extend({method:V(`tasks/result`),params:W.extend({taskId:A()})}),zl=K.loose(),Bl=Fs.extend({method:V(`tasks/list`)}),Vl=Is.extend({tasks:F(Ml)}),Hl=G.extend({method:V(`tasks/cancel`),params:W.extend({taskId:A()})}),Ul=K.merge(Ml),Wl=R([As,ws,Os,wl,Hc,vc,hc,Gs,qs,Zs,tc,rc,oc,Lc,Mc]),Gl=R([ms,Ns,Ds,kl]),Kl=R([fs,el,tl,bl,Ol]),ql=R([As,$c,_l,Dl]),Jl=R([ms,Ns,Wc,fc,$s,Rc,Oc,cc,yl]),Yl=R([fs,Es,ks,Tl,Dc,gc,Ks,Js,Qs,Pc,Nc,uc]),q=ka().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:zo.custom,message:`URL must be parseable`,fatal:!0}),n}).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`}),Xl=L({resource:A().url(),authorization_servers:F(q).optional(),jwks_uri:A().url().optional(),scopes_supported:F(A()).optional(),bearer_methods_supported:F(A()).optional(),resource_signing_alg_values_supported:F(A()).optional(),resource_name:A().optional(),resource_documentation:A().optional(),resource_policy_uri:A().url().optional(),resource_tos_uri:A().url().optional(),tls_client_certificate_bound_access_tokens:N().optional(),authorization_details_types_supported:F(A()).optional(),dpop_signing_alg_values_supported:F(A()).optional(),dpop_bound_access_tokens_required:N().optional()}),Zl=L({issuer:A(),authorization_endpoint:q,token_endpoint:q,registration_endpoint:q.optional(),scopes_supported:F(A()).optional(),response_types_supported:F(A()),response_modes_supported:F(A()).optional(),grant_types_supported:F(A()).optional(),token_endpoint_auth_methods_supported:F(A()).optional(),token_endpoint_auth_signing_alg_values_supported:F(A()).optional(),service_documentation:q.optional(),revocation_endpoint:q.optional(),revocation_endpoint_auth_methods_supported:F(A()).optional(),revocation_endpoint_auth_signing_alg_values_supported:F(A()).optional(),introspection_endpoint:A().optional(),introspection_endpoint_auth_methods_supported:F(A()).optional(),introspection_endpoint_auth_signing_alg_values_supported:F(A()).optional(),code_challenge_methods_supported:F(A()).optional(),client_id_metadata_document_supported:N().optional(),authorization_response_iss_parameter_supported:N().optional().catch(void 0)}),Ql=L({issuer:A(),authorization_endpoint:q,token_endpoint:q,userinfo_endpoint:q.optional(),jwks_uri:q,registration_endpoint:q.optional(),scopes_supported:F(A()).optional(),response_types_supported:F(A()),response_modes_supported:F(A()).optional(),grant_types_supported:F(A()).optional(),acr_values_supported:F(A()).optional(),subject_types_supported:F(A()),id_token_signing_alg_values_supported:F(A()),id_token_encryption_alg_values_supported:F(A()).optional(),id_token_encryption_enc_values_supported:F(A()).optional(),userinfo_signing_alg_values_supported:F(A()).optional(),userinfo_encryption_alg_values_supported:F(A()).optional(),userinfo_encryption_enc_values_supported:F(A()).optional(),request_object_signing_alg_values_supported:F(A()).optional(),request_object_encryption_alg_values_supported:F(A()).optional(),request_object_encryption_enc_values_supported:F(A()).optional(),token_endpoint_auth_methods_supported:F(A()).optional(),token_endpoint_auth_signing_alg_values_supported:F(A()).optional(),display_values_supported:F(A()).optional(),claim_types_supported:F(A()).optional(),claims_supported:F(A()).optional(),service_documentation:A().optional(),claims_locales_supported:F(A()).optional(),ui_locales_supported:F(A()).optional(),claims_parameter_supported:N().optional(),request_parameter_supported:N().optional(),request_uri_parameter_supported:N().optional(),require_request_uri_registration:N().optional(),op_policy_uri:q.optional(),op_tos_uri:q.optional(),client_id_metadata_document_supported:N().optional(),authorization_response_iss_parameter_supported:N().optional().catch(void 0)}),$l=I({...Ql.shape,...Zl.pick({code_challenge_methods_supported:!0}).shape}),eu=I({access_token:A(),id_token:A().optional(),token_type:A(),expires_in:Vo().optional(),scope:A().optional(),refresh_token:A().optional()}).strip(),tu=I({issued_token_type:V(`urn:ietf:params:oauth:token-type:id-jag`),access_token:A(),token_type:A().optional(),expires_in:M().optional(),scope:A().optional()}).strip(),nu=I({error:A(),error_description:A().optional(),error_uri:A().optional()}),ru=q.optional().or(V(``).transform(()=>void 0)),iu=I({redirect_uris:F(q),token_endpoint_auth_method:A().optional(),grant_types:F(A()).optional(),response_types:F(A()).optional(),application_type:A().optional(),client_name:A().optional(),client_uri:q.optional(),logo_uri:ru,scope:A().optional(),contacts:F(A()).optional(),tos_uri:ru,policy_uri:A().optional(),jwks_uri:q.optional(),jwks:Qa().optional(),software_id:A().optional(),software_version:A().optional(),software_statement:A().optional()}).strip(),au=I({client_id:A(),client_secret:A().optional(),client_id_issued_at:M().optional(),client_secret_expires_at:M().optional()}).strip(),ou=iu.merge(au),su=I({error:A(),error_description:A().optional()}).strip(),cu=I({token:A(),token_type_hint:A().optional()}).strip();function lu(e,t,n){return typeof e==`object`&&!!e&&Reflect.get(e,`channel`)===t&&Reflect.get(e,`type`)===`mcp`&&Reflect.get(e,`direction`)===n&&Reflect.has(e,`payload`)}function uu(e,t,n,r,i){e.postMessage({channel:n,type:`mcp`,direction:r,payload:i},t)}var du=class{_started=!1;_closed=!1;_allowedOrigins;_channelId;_messageHandler;_clientOrigin;onclientorigin;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins?.length)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=new Set(e.allowedOrigins),this._channelId=e.channelId??`mcp-iframe`}get clientOrigin(){return this._clientOrigin}async start(){if(this._closed)throw Error(`IframeChildTransport cannot be restarted after it closes`);if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(e.source!==window.parent||!this._allowedOrigins.has(`*`)&&!this._allowedOrigins.has(e.origin)||!lu(e.data,this._channelId,`client-to-server`))return;this._clientOrigin!==e.origin&&(this._clientOrigin=e.origin,this.onclientorigin?.(e.origin));let{payload:t}=e.data;if(t===`mcp-check-ready`){this._broadcastServerReady();return}try{let e=us.parse(t);this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,this._broadcastServerReady()}async send(e,t){if(this._closed)throw Error(`Transport is closed`);if(!this._started)throw Error(`Transport not started`);if(!this._clientOrigin){console.debug(`[IframeChildTransport] No client connected, message not sent`);return}if(window.parent===window){console.debug(`[IframeChildTransport] Not running in an iframe, message not sent`);return}uu(window.parent,this._clientOrigin,this._channelId,`server-to-client`,e)}async close(){this._closed||(this._closed=!0,this._started=!1,this._messageHandler&&=(window.removeEventListener(`message`,this._messageHandler),void 0),this._clientOrigin&&window.parent!==window&&uu(window.parent,this._clientOrigin,this._channelId,`server-to-client`,`mcp-server-stopped`),this.onclose?.())}_broadcastServerReady(){window.parent!==window&&uu(window.parent,`*`,this._channelId,`server-to-client`,`mcp-server-ready`)}},fu=class{_started=!1;_closed=!1;_allowedOrigins;_channelId;_messageHandler;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins?.length)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=new Set(e.allowedOrigins),this._channelId=e.channelId??`mcp-default`}async start(){if(this._closed)throw Error(`TabServerTransport cannot be restarted after it closes`);if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(e.source!==window||!this._allowedOrigins.has(`*`)&&!this._allowedOrigins.has(e.origin)||!lu(e.data,this._channelId,`client-to-server`))return;let{payload:t}=e.data;if(t===`mcp-check-ready`){uu(window,`*`,this._channelId,`server-to-client`,`mcp-server-ready`);return}try{let e=us.parse(t);this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,uu(window,`*`,this._channelId,`server-to-client`,`mcp-server-ready`)}async send(e,t){if(this._closed)throw Error(`Transport is closed`);if(!this._started)throw Error(`Transport not started`);uu(window,`*`,this._channelId,`server-to-client`,e)}async close(){this._closed||(this._closed=!0,this._messageHandler&&=(window.removeEventListener(`message`,this._messageHandler),void 0),this._started&&uu(window,`*`,this._channelId,`server-to-client`,`mcp-server-stopped`),this._started=!1,this.onclose?.())}};let pu={type:`object`,properties:{}},mu=`Tool was executed but the invocation failed. For example, the script function threw an error`,hu=[`draft-2020-12`,`draft-07`],gu=/^[A-Za-z0-9_.-]{1,128}$/u;function _u(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vu(e){if(typeof e==`symbol`)throw TypeError(`Symbol values cannot be converted to a DOMString`);return String(e)}function yu(e){let t=Reflect.get(e,`name`),n=Reflect.get(e,`description`),r=Reflect.get(e,`title`);if(t===void 0)throw TypeError(`Tool "name" is required`);if(n===void 0)throw TypeError(`Tool "description" is required`);let i=Reflect.get(e,`annotations`),a=_u(i)?i:{},o=Reflect.get(e,`inputSchema`),s=Reflect.get(e,`outputSchema`),c=Reflect.get(e,`execute`);return{name:vu(t),...r===void 0?{}:{title:vu(r).toWellFormed()},description:vu(n),...o===void 0?{}:{inputSchema:o},...s===void 0?{}:{outputSchema:s},execute:c,...i===void 0?{}:{annotations:{...a.title===void 0?{}:{title:vu(a.title).toWellFormed()},readOnlyHint:!!a.readOnlyHint,...a.destructiveHint===void 0?{}:{destructiveHint:!!a.destructiveHint},...a.idempotentHint===void 0?{}:{idempotentHint:!!a.idempotentHint},...a.openWorldHint===void 0?{}:{openWorldHint:!!a.openWorldHint},untrustedContentHint:!!a.untrustedContentHint}}}}function bu(e){if(!_u(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function xu(e,t=new WeakSet){if(e===null||typeof e==`string`||typeof e==`boolean`)return!0;if(typeof e==`number`)return Number.isFinite(e);if(typeof e!=`object`||t.has(e))return!1;t.add(e);try{return(Array.isArray(e)?e:bu(e)?Object.values(e):null)?.every(e=>xu(e,t))??!1}catch{return!1}finally{t.delete(e)}}function Su(e){return xu(e)?e:void 0}function Cu(e){return _u(e)&&Array.isArray(e.content)}function wu(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Tu(e){if(Cu(e))return e;let t=Su(e);return{content:[{type:`text`,text:wu(e)}],...t===void 0?{}:{structuredContent:t},isError:!1}}function Eu(e){return new DOMException(e,`UnknownError`)}function Du(e){return Eu(e instanceof Error?`${mu}: ${e.message}`:mu)}function Ou(e){return new DOMException(e,`InvalidStateError`)}function ku(e){if(e.name===``)throw Ou(`Tool "name" must be a non-empty string`);if(typeof e.name!=`string`||!gu.test(e.name))throw Ou(`Tool "name" must be 1–128 characters and contain only ASCII alphanumeric, underscore, hyphen, or period`);if(typeof e.description!=`string`||e.description.length===0)throw Ou(`Tool "description" must be a non-empty string`);if(typeof e.execute!=`function`)throw TypeError(`Tool "execute" must be a function`)}function Au(e){return{readOnlyHint:e.readOnlyHint??!1,untrustedContentHint:e.untrustedContentHint??!1}}function ju(e){try{let t=JSON.parse(e);if(Array.isArray(t)||_u(t))return t}catch{}throw Eu(`Failed to parse input arguments`)}function Mu(e){if(typeof e==`object`&&e||typeof e==`function`)try{let t=JSON.stringify(e);if(t)return t}catch{}return String(e)||`Operation succeeded`}function Nu(e,t,n=()=>t?.reason){return t?t.aborted?Promise.reject(n()):new Promise((r,i)=>{let a=()=>{o(),i(n())},o=()=>t.removeEventListener(`abort`,a);t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{o(),r(e)},e=>{o(),i(e)})}):e}function Pu(e){let t=e.origin===`null`?e:new URL(e.origin),n=t.protocol;if([`https:`,`wss:`,`file:`,`chrome-extension:`,`moz-extension:`].includes(n))return!0;let r=t.hostname.toLowerCase(),i=r.split(`.`),a=i.length===4&&i.every(e=>/^\d{1,3}$/u.test(e)&&Number(e)<=255)&&Number(i[0])===127;return r===`::1`||r===`[::1]`||r===`localhost`||r===`localhost.`||r.endsWith(`.localhost`)||r.endsWith(`.localhost.`)||a}function Fu(e){for(let t of e??[]){let e;try{e=new URL(t)}catch{throw new DOMException(`Invalid or untrustworthy origin: ${String(t)}`,`SecurityError`)}if(!Pu(e))throw new DOMException(`Invalid or untrustworthy origin: ${t}`,`SecurityError`)}}function Iu(e){if(Lu(),!e)return;let t=e.defaultView?.DOMException??DOMException,n=!1;try{let t=e.defaultView;n=!!(t&&t.document===e)}catch{}if(!n)throw new t(`The associated document is not fully active`,`InvalidStateError`);let r=Reflect.get(e,`permissionsPolicy`)??Reflect.get(e,`featurePolicy`);if(r&&typeof r==`object`){let e=Reflect.get(r,`features`),n=Reflect.get(r,`allowsFeature`);if(typeof e==`function`&&typeof n==`function`){let i=Reflect.apply(e,r,[]);if(Array.isArray(i)&&i.includes(`tools`)){if(Reflect.apply(n,r,[`tools`])===!0)return;throw new t(`WebMCP is disabled by Permissions Policy`,`NotAllowedError`)}}}let i=e.defaultView;if(!(!i||i.parent===i)){try{i.parent.document;return}catch{}throw new t(`WebMCP in cross-origin frames requires native Permissions Policy support`,`NotAllowedError`)}}function Lu(){if(globalThis.originAgentCluster===!1&&globalThis.location?.protocol!==`file:`)throw new DOMException(``,`SecurityError`)}function Ru(e){try{if(new URL(String(e)).origin!==`null`)return}catch{}throw new DOMException(`Unsupported tool origin: ${String(e)}`,`NotSupportedError`)}function zu(e){if(!_u(e))return null;let t=e[`~standard`];return _u(t)?t:null}function Bu(e){let t=zu(e);return!!(t&&t.version===1&&typeof t.validate==`function`)}function Vu(e){let t=zu(e);return!t||t.version!==1||!_u(t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function Hu(e,t){let n={...e};return Object.defineProperty(n,"~standard",{value:t[`~standard`]}),n}function Uu(e){for(let t of hu)try{let n=Gu(e[`~standard`].jsonSchema.input({target:t})),r=JSON.parse(n);if(!_u(r))throw TypeError(`inputSchema must serialize to an object`);return r}catch{}throw Error(`Failed to convert Standard JSON Schema inputSchema to a JSON Schema object`)}function Wu(e){if(e===void 0)return{inputSchema:pu};if(Vu(e)){let t=Uu(e),n=Gu(t);return{inputSchema:Bu(e)?Hu(t,e):t,registeredInputSchema:n}}if(Bu(e))throw Error(`Standard Schema inputSchema must provide ~standard.jsonSchema.input() for tool metadata`);if(e===null||typeof e!=`object`&&typeof e!=`function`)throw TypeError(`inputSchema must be an object`);let t=Gu(e),n=JSON.parse(t),r=_u(n)?n:void 0;return!r||Object.keys(r).length===0?{inputSchema:pu,registeredInputSchema:t}:{inputSchema:r.type===void 0?{type:`object`,...r}:r,registeredInputSchema:t}}function Gu(e){if(e===null||typeof e!=`object`&&typeof e!=`function`)throw TypeError(`inputSchema must be an object`);let t=JSON.stringify(e);if(t===void 0)throw TypeError(`inputSchema must be JSON-serializable`);return t}let Ku=new WeakSet,qu=new WeakMap,Ju=new WeakMap;function Yu(e){return e.isTrusted&&(Ku.has(e)||e.eventPhase!==Event.NONE&&e.target instanceof HTMLFormElement&&Ju.has(e.target))}function Xu(e,t){if(!Yu(e))throw new DOMException(`respondWith() is only available during an agent-invoked submit event`,`InvalidStateError`);if(!e.defaultPrevented)throw new DOMException(`respondWith() requires preventDefault() during an agent-invoked submit event`,`InvalidStateError`);if(e.eventPhase===Event.NONE)throw new DOMException(`respondWith() is only available while the submit event is being dispatched`,`InvalidStateError`);Ku.add(e);let n=Promise.resolve(t);qu.set(e,n),e.target instanceof HTMLFormElement&&Ju.get(e.target)?.respond(e)}let Zu=new Set([`email`,`password`,`search`,`tel`,`text`,`url`]),Qu=new Set([...Zu,`date`,`datetime-local`,`month`,`number`,`time`,`week`]);function $u(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement}function ed(e){return Reflect.get(HTMLFormElement.prototype,`elements`,e)}function td(e,t){return Reflect.apply(Element.prototype.getAttribute,e,[t])}function nd(e,t){return Reflect.apply(Element.prototype.hasAttribute,e,[t])}function rd(e){return Reflect.get(Node.prototype,`isConnected`,e)}function id(e){return Reflect.get(Element.prototype,`shadowRoot`,e)}function ad(e){return Reflect.apply(HTMLFormElement.prototype.checkValidity,e,[])}function od(e,t){Reflect.apply(HTMLFormElement.prototype.requestSubmit,e,t?[t]:[])}function sd(e){return[...ed(e)].filter(e=>$u(e)&&!e.matches(`:disabled`)&&!(`readOnly`in e&&e.readOnly&&(e instanceof HTMLTextAreaElement||Qu.has(e.type))))}function cd(e){let t=new Map;for(let n of sd(e)){let e=n.name.trim(),r=t.get(e);r?r.push(n):t.set(e,[n])}return t}function ld(e){return[...e.labels??[]].map(e=>{let t=e.cloneNode(!0);return t instanceof HTMLElement?(t.querySelectorAll(`button, input, meter, output, progress, select, textarea`).forEach(e=>e.remove()),t.textContent?.trim()??``):``}).filter(Boolean).join(`; `)}function ud(e,t){for(let n=t[0]?.parentElement;n&&n!==e;n=n.parentElement)if(n instanceof HTMLFieldSetElement&&t.every(e=>n.contains(e)))return n}function dd(e,t){if(t.length===1){let e=t[0];return e&&(e.getAttribute(`toolparamdescription`)||ld(e)||e.getAttribute(`aria-description`))||void 0}return ud(e,t)?.getAttribute(`toolparamdescription`)||void 0}function J(e,t,n,r){let i=dd(t,n),a=i&&r?`${i} (${r})`:i||r;return a?{...e,description:a}:e}function fd(e,t){let n=e.getAttribute(t);if(n===null||n.trim()===``)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function pd(e,t){let n=e/t;return Math.abs(n-Math.round(n))<2**-52*16}function md(e){let t=e.getAttribute(`pattern`);if(t!==null)try{return new RegExp(t,`v`),t}catch{return}}function hd(e,t=!0){let n={type:`number`},r=fd(e,`min`),i=fd(e,`max`);r!==void 0&&(n.minimum=r),i!==void 0&&(n.maximum=i);let a=e.getAttribute(`step`);if(a!==`any`){let t=a===null||a===``?1:Number(a),i=Number.isFinite(t)&&t>0?t:1,o=Number(e.getAttribute(`value`));pd(r??(Number.isFinite(o)?o:0),i)&&(n.multipleOf=i)}let o=t?md(e):void 0;return o!==void 0&&(n.pattern=o),n}function gd(e,t){let n=e.getAttribute(`step`),r=n===null||n===``?60:Number(n),i=Number.isFinite(r)&&r>0?r:60;return i<1?`${t}(:[0-5][0-9](\\.[0-9]{1,3})?)?$`:i<60?`${t}(:[0-5][0-9])?$`:`${t}$`}function _d(e){return{anyOf:e.map(e=>({type:`string`,const:e.value,title:e.textContent??``})),enum:e.map(e=>e.value)}}function vd(e){return{anyOf:e.map(e=>{let t=ld(e);return{type:`string`,const:e.value,...t?{title:t}:{}}}),enum:e.map(e=>e.value)}}function yd(e,t){let n=t[0];if(n){if(t.length>1)return t.every(e=>e instanceof HTMLInputElement)?t.every(e=>e.type===`checkbox`)?J({type:`array`,items:{type:`string`,...vd(t)},uniqueItems:!0},e,t):t.every(e=>e.type===`radio`)?J({type:`string`,...vd(t)},e,t):void 0:void 0;if(n instanceof HTMLTextAreaElement)return J({type:`string`},e,t);if(n instanceof HTMLSelectElement){let r=_d([...n.options]);return J(n.multiple?{type:`array`,items:{type:`string`,...r},uniqueItems:!0}:{type:`string`,...r},e,t)}if(Zu.has(n.type)){let r={type:`string`},i=md(n);return i!==void 0&&(r.pattern=i),J(r,e,t)}if(n.type===`hidden`)return n.getAttribute(`toolparamdescription`)?J({type:`string`},e,t):void 0;if(n.type===`number`)return J(hd(n),e,t);if(n.type===`range`){let r=hd(n,!1);return r.minimum??=0,r.maximum??=100,J(r,e,t)}if(n.type===`checkbox`)return J({type:`boolean`},e,t);if(n.type===`radio`)return J({type:`string`,...vd([n])},e,t);if(n.type===`date`)return J({type:`string`,format:`date`},e,t,`Dates MUST be provided in 'YYYY-MM-DD' format.`);if(n.type===`month`)return J({type:`string`,format:`^[0-9]{4}-(0[1-9]|1[0-2])$`},e,t);if(n.type===`week`)return J({type:`string`,format:`^[0-9]{4}-W(0[1-9]|[1-4][0-9]|5[0-3])$`},e,t);if(n.type===`time`)return J({type:`string`,format:gd(n,`^([01][0-9]|2[0-3]):[0-5][0-9]`)},e,t);if(n.type===`datetime-local`)return J({type:`string`,format:gd(n,`^[0-9]{4}-(0[1-9]|1[0-2])-[0-9]{2}T([01][0-9]|2[0-3]):[0-5][0-9]`)},e,t);if(n.type===`color`)return J({type:`string`,format:`^#[0-9a-zA-Z]{6}$`},e,t)}}function bd(e){let t={},n=[];for(let[r,i]of cd(e)){if(!r)continue;let a=yd(e,i);a&&(Object.defineProperty(t,r,{configurable:!0,enumerable:!0,value:a,writable:!0}),i.some(e=>e.required)&&n.push(r))}return{type:`object`,properties:t,required:n}}function xd(e){return{name:td(e,`toolname`)??``,title:td(e,`tooltitle`)??``,description:td(e,`tooldescription`)??``,inputSchema:bd(e),autosubmit:nd(e,`toolautosubmit`)}}function Sd(e){if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return String(e)}function Cd(e){if(typeof e==`boolean`)return e;if(typeof e==`number`&&Number.isInteger(e))return e!==0;if(typeof e==`string`){if(e===`1`||e.toLowerCase()===`true`)return!0;if(e===`0`||e.toLowerCase()===`false`)return!1}}function wd(e,t){if(!Array.isArray(e))return!1;let n=new Set(t);for(let t of e){let e=Sd(t);if(e===void 0||!n.delete(e))return!1}return!0}function Td(e,t){if(t===``)return e.type!==`number`&&e.type!==`range`;let n=e.ownerDocument.createElement(`input`);return n.type=e.type,n.value=t,n.value!==``}function Ed(e,t,n){let r=t[0];if(!r||!yd(e,t))return!1;if(t.length>1){if(!t.every(e=>e instanceof HTMLInputElement))return!1;if(t.every(e=>e.type===`checkbox`))return wd(n,new Set(t.map(e=>e.value)));if(t.every(e=>e.type===`radio`)){let e=Sd(n);return e!==void 0&&t.some(t=>t.value===e)}return!1}if(r instanceof HTMLSelectElement){let e=new Set([...r.options].map(e=>e.value));if(r.multiple)return wd(n,e);let t=Sd(n);return t!==void 0&&e.has(t)}if(r instanceof HTMLTextAreaElement)return Sd(n)!==void 0;if(r.type===`checkbox`)return Cd(n)!==void 0;if(r.type===`radio`){let e=Sd(n);return e!==void 0&&r.value===e}let i=Sd(n);return i!==void 0&&Td(r,i)}function Dd(e){e.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0}))}function Od(e,t){let n=e instanceof HTMLInputElement?HTMLInputElement.prototype:HTMLTextAreaElement.prototype;Object.getOwnPropertyDescriptor(n,`value`)?.set?.call(e,t)}function kd(e,t){Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,`checked`)?.set?.call(e,t)}function Ad(e,t){let n=e[0];if(!n)return;if(e.length>1&&e.every(e=>e instanceof HTMLInputElement)){if(e.every(e=>e.type===`checkbox`)&&Array.isArray(t)){let n=new Set(t.map(Sd));for(let t of e){let e=n.has(t.value);t.checked!==e&&(kd(t,e),Dd(t))}return}let n=Sd(t),r=e.find(e=>e.value===n);r&&!r.checked&&(kd(r,!0),Dd(r));return}if(n instanceof HTMLSelectElement){if(n.multiple&&Array.isArray(t)){let e=new Set(t.map(Sd)),r=!1;for(let t of n.options){let n=e.has(t.value);t.selected!==n&&(t.selected=n,r=!0)}r&&Dd(n);return}let e=Sd(t);e!==void 0&&n.value!==e&&(n.value=e,Dd(n));return}if(n instanceof HTMLInputElement&&n.type===`checkbox`){let e=Cd(t);e!==void 0&&n.checked!==e&&(kd(n,e),Dd(n));return}if(n instanceof HTMLInputElement&&n.type===`radio`){Sd(t)===n.value&&!n.checked&&(kd(n,!0),Dd(n));return}let r=Sd(t);r!==void 0&&n.value!==r&&(Od(n,r),Dd(n))}function jd(e,t){if(Array.isArray(t))throw TypeError(`Declarative tool input must be an object`);let n=cd(e);for(let[r,i]of Object.entries(t)){let t=n.get(r);if(!t||!Ed(e,t,i))throw TypeError(`Invalid value for declarative form parameter "${r}"`)}for(let[e,r]of Object.entries(t))Ad(n.get(e)??[],r)}function Md(e){return[...ed(e)].find(e=>!e.matches(`:disabled`)&&(e instanceof HTMLButtonElement&&e.type===`submit`||e instanceof HTMLInputElement&&[`image`,`submit`].includes(e.type)))}function Nd(e){let t=[...ed(e)].filter(e=>$u(e)&&e.willValidate&&!e.validity.valid).map(e=>`${e.name.trim()||`{unknown}`}: ${e.validationMessage}`).join(`. `);return new DOMException(`Form validation failed: ${t}`,`UnknownError`)}function Pd(e){let t=new Event(`toolactivated`);return Object.defineProperty(t,"toolName",{enumerable:!0,value:e}),t}function Fd(e,t,n,r){let{form:i}=e;return e.cancelPending?.(new DOMException(`Tool execution cancelled`,`UnknownError`)),new Promise((a,o)=>{let s=!1,c=()=>{Reflect.apply(EventTarget.prototype.removeEventListener,i,[`invalid`,f,!0]),Ju.delete(i),e.cancelPending===u&&delete e.cancelPending},l=e=>{s||(s=!0,c(),e())},u=e=>l(()=>o(e)),d=e=>{e.then(e=>l(()=>a(e)),e=>l(()=>o(e)))},f=e=>{e.isTrusted&&queueMicrotask(()=>{ad(i)||u(Nd(i))})};if(Ju.set(i,{complete(e){queueMicrotask(()=>{let t=qu.get(e);t?d(t):e.defaultPrevented?u(new DOMException(`preventDefault() requires respondWith()`,`UnknownError`)):l(()=>a(void 0))})},direct(){l(()=>a(void 0))},respond(e){queueMicrotask(()=>{let t=qu.get(e);t&&d(t)})}}),e.cancelPending=u,Reflect.apply(EventTarget.prototype.addEventListener,i,[`invalid`,f,!0]),!n){r?.focus(),window.dispatchEvent(Pd(t));return}try{od(i,r),window.dispatchEvent(Pd(t))}catch(e){u(e)}})}function Id(e,t){let n=!0,r=new Map,i=new Map,a=new Map,o=e=>{if(!(e instanceof SubmitEvent)||!e.isTrusted||!(e.target instanceof HTMLFormElement))return;let t=Ju.get(e.target);t&&(Ku.add(e),t.complete(e))},s=e=>{if(!e.isTrusted||!(e.target instanceof HTMLFormElement))return;let t=e.target;queueMicrotask(()=>{e.defaultPrevented||r.get(t)?.cancelPending?.(new DOMException(`Tool execution cancelled by form reset`,`UnknownError`))})};function c(e){a.get(e)?.disconnect(),a.delete(e),e.removeEventListener(`reset`,s,!0),e.removeEventListener(`submit`,o,!0)}function l(e){if(a.has(e))return;let t=new MutationObserver(u);a.set(e,t),t.observe(e,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),e.addEventListener(`reset`,s,!0),e.addEventListener(`submit`,o,!0)}function u(){l(e);for(let e of a.keys())e instanceof ShadowRoot&&!Reflect.get(Node.prototype,`isConnected`,e.host)&&c(e);let n=new Set,o=new Map,s=new Map;for(let e of a.keys())for(let t of e.querySelectorAll(`*`)){let e=id(t);if(e&&l(e),!(t instanceof HTMLFormElement)||!nd(t,`toolname`)||!nd(t,`tooldescription`)||!rd(t))continue;let r=t;n.add(r);let a=xd(r),c=JSON.stringify(a),u=i.get(r);if(u===c)continue;let d=u!==void 0;i.delete(r);let f=s.get(a.name);if(f&&!d){i.set(r,c);continue}if(f){let e=o.get(f);e&&(i.set(f,e.fingerprint),o.delete(f))}s.set(a.name,r),o.set(r,{definition:a,fingerprint:c})}for(let e of i.keys())n.has(e)||i.delete(e);for(let[e,t]of r)o.get(e)?.fingerprint!==t.fingerprint&&(t.cancelPending?.(new DOMException(`Tool execution cancelled because its form changed`,`UnknownError`)),t.controller.abort(),r.delete(e));for(let[e,{definition:n,fingerprint:i}]of o){if(r.has(e))continue;let a=new AbortController,o={controller:a,fingerprint:i,form:e};r.set(e,o),t.registerTool({name:n.name,title:n.title,description:n.description,inputSchema:n.inputSchema,execute(t){let r=Md(e);if(!n.autosubmit&&!r)throw new DOMException(`A declarative form without toolautosubmit requires a submit button`,`UnknownError`);return jd(e,t),Fd(o,n.name,n.autosubmit,r)}},{signal:a.signal}).catch(e=>{a.abort(),e?.name!==`AbortError`&&console.error(`[webmcp] declarative form tool "${n.name}" was not registered:`,e)})}}let d=()=>{},f=e.defaultView?.Element.prototype,p=f?Object.getOwnPropertyDescriptor(f,`attachShadow`):void 0;if(f&&p?.configurable){let t=f.attachShadow,r=function(r){let i=t.call(this,r);return n&&i.mode===`open`&&Reflect.get(Node.prototype,`ownerDocument`,this)===e&&Reflect.get(Node.prototype,`isConnected`,this)&&l(i),i};Object.defineProperty(f,"attachShadow",{...p,value:r}),d=()=>{f.attachShadow===r&&Object.defineProperty(f,"attachShadow",p)}}let m=()=>{},h=e.defaultView?.HTMLFormElement.prototype,g=h?Object.getOwnPropertyDescriptor(h,`submit`):void 0;if(h&&g?.configurable){let e=h.submit,t=function(){e.call(this),n&&Ju.get(this)?.direct()};Object.defineProperty(h,"submit",{...g,value:t}),m=()=>{h.submit===t&&Object.defineProperty(h,"submit",g)}}return u(),()=>{n=!1,m(),d();for(let e of a.keys())c(e);i.clear();for(let e of r.values())e.cancelPending?.(new DOMException(`Tool execution cancelled`,`UnknownError`)),e.controller.abort();r.clear()}}let Ld=Symbol(`registeredInputSchema`),Rd=Symbol(`registrationSignal`),zd=Symbol(`registrationAbort`),Bd=[],Vd=null,Hd=null;function Ud(){return typeof globalThis.origin==`string`?globalThis.origin:globalThis.location?.origin??``}function Wd(e,t,n){let r=Object.getOwnPropertyDescriptor(e,t);try{Object.defineProperty(e,t,n)}catch(e){throw nf(),e}Bd.push({target:e,key:t,previous:r})}var Gd=class extends EventTarget{#e=new Map;#t=null;#n=null;#r=e=>{this.#n?.call(this,e)};#i;#a;constructor(e){super(),this.#a=e,this.#i=e?.defaultView?.DOMException??DOMException,Object.defineProperty(this,"__isWebMCPPolyfill",{value:!0,enumerable:!1,writable:!1,configurable:!1})}get ontoolchange(){return this.#n}set ontoolchange(e){let t=typeof e==`function`?e:null;if(t===null){this.#n=null,super.removeEventListener(`toolchange`,this.#r);return}this.#n===null&&super.addEventListener(`toolchange`,this.#r),this.#n=t}async registerTool(e,t={}){Iu(this.#a);let n=t?.signal,r=Jd(e,this.#e);if(n?.throwIfAborted(),Fu(t?.exposedTo),n?.throwIfAborted(),t?.exposedTo?.length)throw new this.#i(`Cross-document tool exposure requires native WebMCP`,`NotSupportedError`);if(this.#e.set(r.name,r),n){let e=()=>{this.#o(r.name,r)&&this.#c()};r[Rd]=n,r[zd]=e,n.addEventListener(`abort`,e,{once:!0})}if(await this.#c(),n?.aborted)throw n.reason}async getTools(e={}){if(Iu(this.#a),Fu(e?.fromOrigins),e?.fromOrigins?.length)throw new this.#i(`Cross-document tool discovery requires native WebMCP`,`NotSupportedError`);let t=[...this.#e.values()].map(e=>{let t=e[Ld],n=t===void 0?void 0:JSON.parse(t);return{name:e.name,title:e.title??``,description:e.description,..._u(n)?{inputSchema:n}:{},origin:Ud(),window:globalThis.window,...e.annotations?{annotations:Au(e.annotations)}:{}}}).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));return await new Promise(e=>setTimeout(e,0)),t}async executeTool(e,t,n={}){if(Iu(this.#a),typeof e!=`object`||!e)throw TypeError(`RegisteredTool must be an object`);for(let t of[`name`,`description`,`window`,`origin`])if(!(t in e))throw TypeError(`RegisteredTool.${t} is required`);if(Ru(e.origin),e.window!==globalThis.window||e.origin!==Ud())throw Eu(`Tool not found: ${e.name}`);return this.#s(e.name,t,n)}static getTestingShim(e){return e.#t??=new qd(e),e.#t}static getToolInfos(e){return[...e.#e.values()].map(e=>({name:e.name,description:e.description,...e[Ld]===void 0?{}:{inputSchema:e[Ld]}}))}static executeToolForTesting(e,t,n,r){return Iu(e.#a),e.#s(t,n,r)}static dispose(e){for(let t of e.#e.keys())e.#o(t);e.ontoolchange=null,e.#t?.dispose()}#o(e,t){let n=this.#e.get(e);if(!n||t&&n!==t)return!1;let r=n[Rd],i=n[zd];return r&&i&&r.removeEventListener(`abort`,i),this.#e.delete(e)}async#s(e,t,n){n?.signal?.throwIfAborted();let r=this.#e.get(e);if(!r)throw Eu(`Tool not found: ${e}`);let i=ju(t);if(n?.signal?.throwIfAborted(),r[Rd]?.aborted)throw Eu(`Tool unregistered`);let a;try{let e=r[Rd];a=await Nu(Nu(Promise.resolve(r.execute(i)),e,()=>Eu(`Tool unregistered`)),n?.signal)}catch(e){throw n?.signal?.aborted&&e===n.signal.reason||r[Rd]?.aborted?e:Du(e)}return Mu(a)}async#c(){await new Promise(e=>setTimeout(e,0)),this.dispatchEvent(new Event(`toolchange`)),this.#t?.dispatchToolChange()}};let Kd=function(){throw TypeError(`Illegal constructor`)};Object.defineProperty(Kd,"name",{value:`ModelContext`}),Object.defineProperty(Kd,"prototype",{value:Gd.prototype,writable:!1}),Object.setPrototypeOf(Kd,EventTarget),Object.defineProperty(Gd.prototype,"constructor",{configurable:!0,writable:!0,value:Kd}),Object.defineProperty(Gd.prototype,Symbol.toStringTag,{configurable:!0,value:`ModelContext`});for(let e of[`registerTool`,`getTools`,`executeTool`,`ontoolchange`]){let t=Object.getOwnPropertyDescriptor(Gd.prototype,e);t&&Object.defineProperty(Gd.prototype,e,{...t,enumerable:!0})}var qd=class extends EventTarget{_ontoolchange=null;ontoolchangeListener=e=>{this._ontoolchange?.call(this,e)};#e;constructor(e){super(),this.#e=e}listTools(){return Gd.getToolInfos(this.#e)}executeTool(e,t,n){return Gd.executeToolForTesting(this.#e,e,t,n)}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){let t=typeof e==`function`?e:null;if(t===null){this._ontoolchange=null,super.removeEventListener(`toolchange`,this.ontoolchangeListener);return}this._ontoolchange===null&&super.addEventListener(`toolchange`,this.ontoolchangeListener),this._ontoolchange=t}dispatchToolChange(){this.dispatchEvent(new Event(`toolchange`))}dispose(){this.ontoolchange=null}};function Jd(e,t){if(!e||typeof e!=`object`)throw TypeError(`registerTool(tool) requires a tool object`);let n=yu(e);if(ku(n),t.has(n.name))throw Ou(`Tool already registered: ${n.name}`);let r=n.inputSchema===void 0?void 0:Gu(n.inputSchema);return{name:n.name,...n.title===void 0?{}:{title:n.title},description:n.description,...n.inputSchema===void 0?{}:{inputSchema:n.inputSchema},...n.annotations===void 0?{}:{annotations:n.annotations},execute:e=>Reflect.apply(n.execute,void 0,[e]),...r===void 0?{}:{[Ld]:r}}}let Yd=!1,Xd=new WeakMap,{modelContext:Zd}={modelContext(){if(!(this instanceof Document))throw TypeError(`Illegal invocation`);return Xd.get(this)}};Object.defineProperty(Zd,"name",{value:`get modelContext`});function Qd(e,t){Xd.set(e,t),!Object.hasOwn(Document.prototype,`modelContext`)&&Wd(Document.prototype,`modelContext`,{configurable:!0,enumerable:!0,get:Zd})}function $d(e,t){Wd(e,`modelContext`,{configurable:!0,enumerable:!0,get(){return Yd||(Yd=!0,console.warn(`[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document — use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.`)),t}})}function ef(){let e=SubmitEvent.prototype;`agentInvoked`in e||Wd(e,`agentInvoked`,{configurable:!0,enumerable:!0,get(){return Yu(this)}}),`respondWith`in e||Wd(e,`respondWith`,{configurable:!0,enumerable:!0,writable:!0,value(e){Xu(this,e)}})}function tf(e){if(globalThis.isSecureContext===!1)return;let t=typeof navigator>`u`?null:navigator,n=typeof document>`u`?null:document;if(!t||!n||typeof window>`u`||n.modelContext)return;let r=t.modelContext;if(Bd.length>0&&nf(),r){Qd(n,r);return}let i=Object.getOwnPropertyDescriptor(window,`ModelContext`);if(i&&!i.configurable){if(!Object.is(Reflect.get(window,`ModelContext`),Kd))throw TypeError(`Cannot install ModelContext over a non-configurable global`)}else Wd(window,`ModelContext`,{configurable:!0,enumerable:!1,writable:!0,value:Kd});let a=new Gd(n);Vd=a,Qd(n,a),Yd=!1,$d(t,a),ef(),e?.installTestingShim&&!t.modelContextTesting&&Wd(t,`modelContextTesting`,{configurable:!0,enumerable:!0,writable:!1,value:Gd.getTestingShim(a)}),Hd=Id(n,a)}function nf(){Hd?.(),Hd=null,Vd&&Gd.dispose(Vd),Vd=null;for(let{target:e,key:t,previous:n}of[...Bd].reverse())n?Object.defineProperty(e,t,n):Reflect.deleteProperty(e,t);Bd.length=0,Yd=!1}var rf=Object.defineProperty,af=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),of=(e,t)=>{let n={};for(var r in e)rf(n,r,{get:e[r],enumerable:!0});return t&&rf(n,Symbol.toStringTag,{value:`Module`}),n};let sf=new Set([`https://json-schema.org/draft/2020-12/schema`,`http://json-schema.org/draft/2020-12/schema`]),cf=new Set([`https://json-schema.org/draft/2019-09/schema`,`http://json-schema.org/draft/2019-09/schema`]),lf=new Set([`https://json-schema.org/draft-07/schema`,`http://json-schema.org/draft-07/schema`]),uf=new Set([`https://json-schema.org/draft-06/schema`,`http://json-schema.org/draft-06/schema`]);function df(e){return typeof e==`string`&&cf.has(e.replace(/#$/,``))}function ff(e,t){if(!(`$schema`in e)||typeof e.$schema!=`string`)return`2020-12`;let n=e.$schema.replace(/#$/,``);if(sf.has(n))return`2020-12`;if(cf.has(n))return`2019-09`;if(lf.has(n)||uf.has(n))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}`)}let pf=Symbol.for(`mcp.sdk.errorBrands`);function mf(e,t){let n=new Set,r=t;for(;typeof r==`function`;){let e=r.mcpBrand;Object.prototype.hasOwnProperty.call(r,`mcpBrand`)&&typeof e==`string`&&n.add(e),r=Object.getPrototypeOf(r)}n.size!==0&&Object.defineProperty(e,pf,{value:n,enumerable:!1,configurable:!0})}function hf(e,t){try{if(typeof t==`object`&&t&&Object.prototype.hasOwnProperty.call(e,`mcpBrand`)&&typeof e.mcpBrand==`string`&&Object.prototype.hasOwnProperty.call(t,pf)){let n=t[pf];if(n&&typeof n.has==`function`&&n.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}(class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.OAuthError`})}static[Symbol.hasInstance](e){return hf(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 hf(this,e)}constructor(e,t,n){super(t),this.code=e,this.errorUri=n,this.name=`OAuthError`,mf(this,new.target)}toResponseObject(){let e={error:this.code,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}});let Y=function(e){return e.NotConnected=`NOT_CONNECTED`,e.AlreadyConnected=`ALREADY_CONNECTED`,e.NotInitialized=`NOT_INITIALIZED`,e.CapabilityNotSupported=`CAPABILITY_NOT_SUPPORTED`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.ConnectionClosed=`CONNECTION_CLOSED`,e.SendFailed=`SEND_FAILED`,e.InvalidResult=`INVALID_RESULT`,e.UnsupportedResultType=`UNSUPPORTED_RESULT_TYPE`,e.InputRequiredRoundsExceeded=`INPUT_REQUIRED_ROUNDS_EXCEEDED`,e.ListPaginationExceeded=`LIST_PAGINATION_EXCEEDED`,e.MethodNotSupportedByProtocolVersion=`METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION`,e.EraNegotiationFailed=`ERA_NEGOTIATION_FAILED`,e.ClientHttpNotImplemented=`CLIENT_HTTP_NOT_IMPLEMENTED`,e.ClientHttpAuthentication=`CLIENT_HTTP_AUTHENTICATION`,e.ClientHttpForbidden=`CLIENT_HTTP_FORBIDDEN`,e.ClientHttpUnexpectedContent=`CLIENT_HTTP_UNEXPECTED_CONTENT`,e.ClientHttpFailedToOpenStream=`CLIENT_HTTP_FAILED_TO_OPEN_STREAM`,e.ClientHttpFailedToTerminateSession=`CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION`,e}({});var X=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkError`})}static[Symbol.hasInstance](e){return hf(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 hf(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`SdkError`,mf(this,new.target)}};(class extends X{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkHttpError`})}constructor(e,t,n){super(e,t,n),this.name=`SdkHttpError`}get status(){return this.data.status}get statusText(){return this.data.statusText}});function gf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _f(e,t,n){return e===`elicitation`&&t===`form`&&n.form===void 0&&n.url===void 0}function vf(e){switch(e.method){case`elicitation/create`:return e.params?.mode===`url`?{elicitation:{url:{}}}:{elicitation:{form:{}}};case`sampling/createMessage`:{let t=e.params;return t!==void 0&&(t.tools!==void 0||t.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case`roots/list`:return{roots:{}};default:return}}function yf(e,t){let n={};for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=t===void 0?void 0:t[r];if(e===void 0){n[r]=i;continue}if(gf(i)&&gf(e)){let t={};for(let[n,a]of Object.entries(i))a!==void 0&&e[n]===void 0&&!_f(r,n,e)&&(t[n]=a);Object.keys(t).length>0&&(n[r]=t)}}return Object.keys(n).length>0?n:void 0}function bf(e){return e>=`2026-07-28`}function xf(e){return e.filter(e=>!bf(e))}function Sf(e){return e.filter(e=>bf(e))}function Cf(e){let t=e.structuredContent;return t===void 0||!(typeof t!=`object`||!t||Array.isArray(t))||(e.content?.some(e=>e.type===`text`)??!1)?e:{...e,content:[...e.content??[],{type:`text`,text:JSON.stringify(t)}]}}let wf=[`task`,`inputRequests`,`requestState`];function Tf(e){return typeof e!=`object`||!e||Array.isArray(e)||e.content!==void 0||wf.some(t=>t in e)?e:{...e,content:[]}}function Ef(){let e=Po(()=>R([A(),M(),N(),Xa(),z(A(),e),F(e)])),t=z(A(),e),n=R([A(),M().int()]),r=A(),i=I({ttl:M().optional()}),a=I({taskId:A()}),o=L({progressToken:n.optional(),"io.modelcontextprotocol/related-task":a.optional()}),s=I({_meta:o.optional()}),c=s.extend({task:i.optional()}),l=I({method:A(),params:s.loose().optional()}),u=I({_meta:o.optional()}),d=I({method:A(),params:u.loose().optional()}),f=L({_meta:o.optional()}),p=R([A(),M().int()]),m=f.strict(),h=u.extend({requestId:p.optional(),reason:A().optional()}),g=d.extend({method:V(`notifications/cancelled`),params:h}),_=I({src:A(),mimeType:A().optional(),sizes:F(A()).optional(),theme:B([`light`,`dark`]).optional()}),ee=I({icons:F(_).optional()}),te=I({name:A(),title:A().optional()}),ne=te.extend({...te.shape,...ee.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),re=Ro(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,co(I({form:co(I({applyDefaults:N().optional()}),t).optional(),url:t.optional()}),t.optional())),ie=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),ae=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),oe=I({experimental:z(A(),t).optional(),sampling:I({context:t.optional(),tools:t.optional()}).optional(),elicitation:re.optional(),roots:I({listChanged:N().optional()}).optional(),tasks:ie.optional(),extensions:z(A(),t).optional()}),se=s.extend({protocolVersion:A(),capabilities:oe,clientInfo:ne}),ce=l.extend({method:V(`initialize`),params:se}),v=I({experimental:z(A(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:I({listChanged:N().optional()}).optional(),resources:I({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:I({listChanged:N().optional()}).optional(),tasks:ae.optional(),extensions:z(A(),t).optional()}),y=f.extend({protocolVersion:A(),capabilities:v,serverInfo:ne,instructions:A().optional()}),le=d.extend({method:V(`notifications/initialized`),params:u.optional()}),ue=l.extend({method:V(`ping`),params:s.optional()}),de=I({progress:M(),total:H(M()),message:H(A())}),fe=I({...u.shape,...de.shape,progressToken:n}),pe=d.extend({method:V(`notifications/progress`),params:fe}),me=s.extend({cursor:r.optional()}),he=l.extend({params:me.optional()}),ge=f.extend({nextCursor:r.optional()}),_e=I({uri:A(),mimeType:H(A()),_meta:z(A(),P()).optional()}),ve=_e.extend({text:A()}),ye=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),be=_e.extend({blob:ye}),b=B([`user`,`assistant`]),x=I({audience:F(b).optional(),priority:M().min(0).max(1).optional(),lastModified:ea({offset:!0}).optional()}),xe=I({...te.shape,...ee.shape,uri:A(),description:H(A()),mimeType:H(A()),size:H(M()),annotations:x.optional(),_meta:H(L({}))}),Se=I({...te.shape,...ee.shape,uriTemplate:A(),description:H(A()),mimeType:H(A()),annotations:x.optional(),_meta:H(L({}))}),Ce=he.extend({method:V(`resources/list`)}),we=ge.extend({resources:F(xe)}),S=he.extend({method:V(`resources/templates/list`)}),Te=ge.extend({resourceTemplates:F(Se)}),Ee=s.extend({uri:A()}),De=Ee,Oe=l.extend({method:V(`resources/read`),params:De}),ke=f.extend({contents:F(R([ve,be]))}),Ae=d.extend({method:V(`notifications/resources/list_changed`),params:u.optional()}),je=Ee,Me=l.extend({method:V(`resources/subscribe`),params:je}),C=Ee,Ne=l.extend({method:V(`resources/unsubscribe`),params:C}),Pe=u.extend({uri:A()}),Fe=d.extend({method:V(`notifications/resources/updated`),params:Pe}),Ie=I({name:A(),description:H(A()),required:H(N())}),Le=I({...te.shape,...ee.shape,description:H(A()),arguments:H(F(Ie)),_meta:H(L({}))}),Re=he.extend({method:V(`prompts/list`)}),ze=ge.extend({prompts:F(Le)}),Be=s.extend({name:A(),arguments:z(A(),A()).optional()}),Ve=l.extend({method:V(`prompts/get`),params:Be}),He=I({type:V(`text`),text:A(),annotations:x.optional(),_meta:z(A(),P()).optional()}),Ue=I({type:V(`image`),data:ye,mimeType:A(),annotations:x.optional(),_meta:z(A(),P()).optional()}),We=I({type:V(`audio`),data:ye,mimeType:A(),annotations:x.optional(),_meta:z(A(),P()).optional()}),Ge=I({type:V(`tool_use`),name:A(),id:A(),input:z(A(),P()),_meta:z(A(),P()).optional()}),Ke=I({type:V(`resource`),resource:R([ve,be]),annotations:x.optional(),_meta:z(A(),P()).optional()}),qe=xe.extend({type:V(`resource_link`)}),Je=R([He,Ue,We,qe,Ke]),Ye=I({role:b,content:Je}),Xe=f.extend({description:A().optional(),messages:F(Ye)}),Ze=d.extend({method:V(`notifications/prompts/list_changed`),params:u.optional()}),Qe=I({title:A().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),$e=I({taskSupport:B([`required`,`optional`,`forbidden`]).optional()}),et=I({...te.shape,...ee.shape,description:A().optional(),inputSchema:I({type:V(`object`),properties:z(A(),e).optional(),required:F(A()).optional()}).catchall(P()),outputSchema:I({type:V(`object`),properties:z(A(),e).optional(),required:F(A()).optional()}).catchall(P()).optional(),annotations:Qe.optional(),execution:$e.optional(),_meta:z(A(),P()).optional()}),tt=he.extend({method:V(`tools/list`)}),nt=ge.extend({tools:F(et)}),rt=f.extend({content:F(Je),structuredContent:z(A(),P()).optional(),isError:N().optional()}),w=c.extend({name:A(),arguments:z(A(),P()).optional()}),it=l.extend({method:V(`tools/call`),params:w}),at=d.extend({method:V(`notifications/tools/list_changed`),params:u.optional()}),ot=B([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),st=s.extend({level:ot}),ct=l.extend({method:V(`logging/setLevel`),params:st}),lt=u.extend({level:ot,logger:A().optional(),data:P()}),ut=d.extend({method:V(`notifications/message`),params:lt}),dt=I({name:A().optional()}),ft=I({hints:F(dt).optional(),costPriority:M().min(0).max(1).optional(),speedPriority:M().min(0).max(1).optional(),intelligencePriority:M().min(0).max(1).optional()}),pt=I({mode:B([`auto`,`required`,`none`]).optional()}),mt=I({type:V(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:F(Je),structuredContent:I({}).loose().optional(),isError:N().optional(),_meta:z(A(),P()).optional()}),ht=oo(`type`,[He,Ue,We]),T=oo(`type`,[He,Ue,We,Ge,mt]),gt=I({role:b,content:R([T,F(T)]),_meta:z(A(),P()).optional()}),_t=c.extend({messages:F(gt),modelPreferences:ft.optional(),systemPrompt:A().optional(),includeContext:B([`none`,`thisServer`,`allServers`]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:F(A()).optional(),metadata:t.optional(),tools:F(et).optional(),toolChoice:pt.optional()}),vt=l.extend({method:V(`sampling/createMessage`),params:_t}),yt=f.extend({model:A(),stopReason:H(B([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:b,content:ht}),bt=f.extend({model:A(),stopReason:H(B([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:b,content:R([T,F(T)])}),xt=I({type:V(`boolean`),title:A().optional(),description:A().optional(),default:N().optional()}),St=I({type:V(`string`),title:A().optional(),description:A().optional(),minLength:M().optional(),maxLength:M().optional(),format:B([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),Ct=I({type:B([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),wt=I({type:V(`string`),title:A().optional(),description:A().optional(),enum:F(A()),default:A().optional()}),Tt=I({type:V(`string`),title:A().optional(),description:A().optional(),oneOf:F(I({const:A(),title:A()})),default:A().optional()}),Et=I({type:V(`string`),title:A().optional(),description:A().optional(),enum:F(A()),enumNames:F(A()).optional(),default:A().optional()}),Dt=R([wt,Tt]),Ot=I({type:V(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({type:V(`string`),enum:F(A())}),default:F(A()).optional()}),kt=I({type:V(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({anyOf:F(I({const:A(),title:A()}))}),default:F(A()).optional()}),At=R([Ot,kt]),jt=R([Et,Dt,At]),Mt=R([jt,xt,St,Ct]),Nt=c.extend({mode:V(`form`).optional(),message:A(),requestedSchema:I({type:V(`object`),properties:z(A(),Mt),required:F(A()).optional()}).catchall(P())}),E=c.extend({mode:V(`url`),message:A(),elicitationId:A(),url:A().url()}),Pt=R([Nt,E]),D=l.extend({method:V(`elicitation/create`),params:Pt}),Ft=u.extend({elicitationId:A()}),It=d.extend({method:V(`notifications/elicitation/complete`),params:Ft}),Lt=f.extend({action:B([`accept`,`decline`,`cancel`]),content:Ro(e=>e===null?void 0:e,z(A(),R([A(),M(),N(),F(A())])).optional())}),Rt=I({type:V(`ref/resource`),uri:A()}),zt=I({type:V(`ref/prompt`),name:A()}),Bt=s.extend({ref:R([zt,Rt]),argument:I({name:A(),value:A()}),context:I({arguments:z(A(),A()).optional()}).optional()}),Vt=l.extend({method:V(`completion/complete`),params:Bt}),Ht=f.extend({completion:L({values:F(A()).max(100),total:H(M().int()),hasMore:H(N())})}),Ut=I({uri:A().startsWith(`file://`),name:A().optional(),_meta:z(A(),P()).optional()}),Wt=l.extend({method:V(`roots/list`),params:s.optional()}),Gt=f.extend({roots:F(Ut)}),Kt=d.extend({method:V(`notifications/roots/list_changed`),params:u.optional()}),qt=L({ttl:M().optional(),pollInterval:M().optional()}),Jt=B([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Yt=I({taskId:A(),status:Jt,ttl:R([M(),Xa()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:H(M()),statusMessage:H(A())}),Xt=f.extend({task:Yt}),Zt=u.merge(Yt),Qt=d.extend({method:V(`notifications/tasks/status`),params:Zt}),$t=l.extend({method:V(`tasks/get`),params:s.extend({taskId:A()})}),en=f.merge(Yt),tn=l.extend({method:V(`tasks/result`),params:s.extend({taskId:A()})}),nn=f.loose(),rn=he.extend({method:V(`tasks/list`)}),an=ge.extend({tasks:F(Yt)}),on=l.extend({method:V(`tasks/cancel`),params:s.extend({taskId:A()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,TaskMetadataSchema:i,RelatedTaskMetadataSchema:a,RequestMetaSchema:o,BaseRequestParamsSchema:s,TaskAugmentedRequestParamsSchema:c,RequestSchema:l,NotificationsParamsSchema:u,NotificationSchema:d,ResultSchema:f,RequestIdSchema:p,EmptyResultSchema:m,CancelledNotificationParamsSchema:h,CancelledNotificationSchema:g,IconSchema:_,IconsSchema:ee,BaseMetadataSchema:te,ImplementationSchema:ne,ClientTasksCapabilitySchema:ie,ServerTasksCapabilitySchema:ae,ClientCapabilitiesSchema:oe,InitializeRequestParamsSchema:se,InitializeRequestSchema:ce,ServerCapabilitiesSchema:v,InitializeResultSchema:y,InitializedNotificationSchema:le,PingRequestSchema:ue,ProgressSchema:de,ProgressNotificationParamsSchema:fe,ProgressNotificationSchema:pe,PaginatedRequestParamsSchema:me,PaginatedRequestSchema:he,PaginatedResultSchema:ge,ResourceContentsSchema:_e,TextResourceContentsSchema:ve,BlobResourceContentsSchema:be,RoleSchema:b,AnnotationsSchema:x,ResourceSchema:xe,ResourceTemplateSchema:Se,ListResourcesRequestSchema:Ce,ListResourcesResultSchema:we,ListResourceTemplatesRequestSchema:S,ListResourceTemplatesResultSchema:Te,ResourceRequestParamsSchema:Ee,ReadResourceRequestParamsSchema:De,ReadResourceRequestSchema:Oe,ReadResourceResultSchema:ke,ResourceListChangedNotificationSchema:Ae,SubscribeRequestParamsSchema:je,SubscribeRequestSchema:Me,UnsubscribeRequestParamsSchema:C,UnsubscribeRequestSchema:Ne,ResourceUpdatedNotificationParamsSchema:Pe,ResourceUpdatedNotificationSchema:Fe,PromptArgumentSchema:Ie,PromptSchema:Le,ListPromptsRequestSchema:Re,ListPromptsResultSchema:ze,GetPromptRequestParamsSchema:Be,GetPromptRequestSchema:Ve,TextContentSchema:He,ImageContentSchema:Ue,AudioContentSchema:We,ToolUseContentSchema:Ge,EmbeddedResourceSchema:Ke,ResourceLinkSchema:qe,ContentBlockSchema:Je,PromptMessageSchema:Ye,GetPromptResultSchema:Xe,PromptListChangedNotificationSchema:Ze,ToolAnnotationsSchema:Qe,ToolExecutionSchema:$e,ToolSchema:et,ListToolsRequestSchema:tt,ListToolsResultSchema:nt,CallToolResultSchema:rt,CallToolRequestParamsSchema:w,CallToolRequestSchema:it,ToolListChangedNotificationSchema:at,LoggingLevelSchema:ot,SetLevelRequestParamsSchema:st,SetLevelRequestSchema:ct,LoggingMessageNotificationParamsSchema:lt,LoggingMessageNotificationSchema:ut,ModelHintSchema:dt,ModelPreferencesSchema:ft,ToolChoiceSchema:pt,ToolResultContentSchema:mt,SamplingContentSchema:ht,SamplingMessageContentBlockSchema:T,SamplingMessageSchema:gt,CreateMessageRequestParamsSchema:_t,CreateMessageRequestSchema:vt,CreateMessageResultSchema:yt,CreateMessageResultWithToolsSchema:bt,BooleanSchemaSchema:xt,StringSchemaSchema:St,NumberSchemaSchema:Ct,UntitledSingleSelectEnumSchemaSchema:wt,TitledSingleSelectEnumSchemaSchema:Tt,LegacyTitledEnumSchemaSchema:Et,SingleSelectEnumSchemaSchema:Dt,UntitledMultiSelectEnumSchemaSchema:Ot,TitledMultiSelectEnumSchemaSchema:kt,MultiSelectEnumSchemaSchema:At,EnumSchemaSchema:jt,PrimitiveSchemaDefinitionSchema:Mt,ElicitRequestFormParamsSchema:Nt,ElicitRequestURLParamsSchema:E,ElicitRequestParamsSchema:Pt,ElicitRequestSchema:D,ElicitationCompleteNotificationParamsSchema:Ft,ElicitationCompleteNotificationSchema:It,ElicitResultSchema:Lt,ResourceTemplateReferenceSchema:Rt,PromptReferenceSchema:zt,CompleteRequestParamsSchema:Bt,CompleteRequestSchema:Vt,CompleteResultSchema:Ht,RootSchema:Ut,ListRootsRequestSchema:Wt,ListRootsResultSchema:Gt,RootsListChangedNotificationSchema:Kt,TaskCreationParamsSchema:qt,TaskStatusSchema:Jt,TaskSchema:Yt,CreateTaskResultSchema:Xt,TaskStatusNotificationParamsSchema:Zt,TaskStatusNotificationSchema:Qt,GetTaskRequestSchema:$t,GetTaskResultSchema:en,GetTaskPayloadRequestSchema:tn,GetTaskPayloadResultSchema:nn,ListTasksRequestSchema:rn,ListTasksResultSchema:an,CancelTaskRequestSchema:on,CancelTaskResultSchema:f.merge(Yt),ClientRequestSchema:R([ue,ce,Vt,ct,Ve,Re,Ce,S,Oe,Me,Ne,it,tt,$t,tn,rn,on]),ClientNotificationSchema:R([g,pe,le,Kt,Qt]),ClientResultSchema:R([m,yt,bt,Lt,Gt,en,an,Xt]),ServerRequestSchema:R([ue,vt,D,Wt,$t,tn,rn,on]),ServerNotificationSchema:R([g,pe,ut,Fe,Ae,at,Ze,Qt,It]),ServerResultSchema:R([m,y,Ht,Xe,ze,we,Te,ke,rt,nt,en,an,Xt]),CallToolResultWireSchema:P().superRefine((e,t)=>{if(!(typeof e!=`object`||!e||Array.isArray(e)||e.content!==void 0)){for(let n of wf)if(n in e){t.addIssue({code:`custom`,message:`content is required when the body carries '${n}' — another result family cannot default into an empty tools/call success`});return}}}).transform(Tf).pipe(rt)}}let Df;function Of(){return Df??=Ef()}function kf(e){return e.type!==`object`}let Af=new Set([`const`,`enum`,`default`,`examples`]),jf=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`,`dependencies`]);function Mf(e){return e!==void 0&&!(typeof e==`string`&&e.startsWith(`#`))}function Nf(e){let t=typeof e.$schema==`string`?e.$schema:void 0;if(Mf(e.$id))return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:e},required:[`result`]};let n=df(e.$schema)&&e.$recursiveAnchor!==!0,r=(e,t)=>{if(Array.isArray(e))return e.map(e=>r(e,!1));if(typeof e!=`object`||!e||!t&&Mf(e.$id))return e;let i={},a=!1;for(let[o,s]of Object.entries(e))t?i[o]=r(s,!1):(o===`$ref`||o===`$dynamicRef`)&&typeof s==`string`?i[o]=s===`#`?`#/properties/result`:s.startsWith(`#/`)?`#/properties/result${s.slice(1)}`:s:o===`$recursiveRef`&&s===`#`&&n?a=!0:Af.has(o)?i[o]=s:jf.has(o)?i[o]=r(s,!0):i[o]=r(s,!1);return a&&(`$ref`in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:`#/properties/result`}]:i.$ref=`#/properties/result`),i};return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:r(e,!1)},required:[`result`]}}let Pf={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},Ff={"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},If={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},Lf;function Rf(){if(Lf)return Lf;let e=Of();return Lf={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}},Lf}function zf(e){return Object.prototype.hasOwnProperty.call(Pf,e)}function Bf(e){return Object.prototype.hasOwnProperty.call(Ff,e)}function Vf(e){return Object.prototype.hasOwnProperty.call(If,e)}function Hf(e){return Vf(e)?Rf().resultSchemas[e]:void 0}function Uf(e){return zf(e)?Rf().requestSchemas[e]:void 0}function Wf(e){return Bf(e)?Rf().notificationSchemas[e]:void 0}function Gf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Kf(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}let qf={ok:!1,reason:`not-in-era`};function Jf(e){return Gf(e)&&Gf(e.outputSchema)&&kf(e.outputSchema)}function Yf(e){return e}let Xf={era:`2025-11-25`,hasRequestMethod:zf,hasNotificationMethod:Bf,validateRequest:(e,t)=>Kf(Uf(e),t),validateResult:(e,t)=>Kf(Hf(e),t),validateNotification:(e,t)=>Kf(Wf(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>qf,validateInputResponse:()=>qf,samplingResultVariant:((e,t)=>{let n=Of();return Kf(e?n.CreateMessageResultWithToolsSchema:n.CreateMessageResultSchema,t)}),outboundEnvelope:e=>void 0,validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let n=Cf(e),r=n.structuredContent;if(r===void 0)return n;let i=typeof r!=`object`||!r||Array.isArray(r),a=t!==void 0&&kf(t);return!i&&!a?n:{...n,structuredContent:{result:r}}},decodeResult(e,t){if(Gf(t)&&`resultType`in t){let e={...t};return delete e.resultType,{kind:`complete`,result:Yf(e)}}return{kind:`complete`,result:Yf(t)}},encodeResult(e,t){if(e!==`tools/list`)return t;let n=t.tools;return!Array.isArray(n)||!n.some(e=>Jf(e))?t:{...t,tools:n.map(e=>Jf(e)?{...e,outputSchema:Nf(e.outputSchema)}:e)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>void 0};function Zf(){let e=Po(()=>R([A(),M(),N(),Xa(),z(A(),e),F(e)])),t=z(A(),e),n=R([A(),M().int()]),r=A(),i=R([A(),M().int()]),a=B([`user`,`assistant`]),o=B([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),s=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),c=I({ttl:M().optional()}),l=I({taskId:A()}),u=L({progressToken:n.optional(),"io.modelcontextprotocol/related-task":l.optional()}),d=I({_meta:u.optional()}),f=d.extend({task:c.optional()}),p=I({_meta:u.optional()}),m=I({method:A(),params:p.loose().optional()}),h=I({src:A(),mimeType:A().optional(),sizes:F(A()).optional(),theme:B([`light`,`dark`]).optional()}),g=I({icons:F(h).optional()}),_=I({name:A(),title:A().optional()}),ee=_.extend({..._.shape,...g.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),te=Ro(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,co(I({form:co(I({applyDefaults:N().optional()}),t).optional(),url:t.optional()}),t.optional())),ne=L({list:t.optional(),cancel:t.optional(),requests:L({sampling:L({createMessage:t.optional()}).optional(),elicitation:L({create:t.optional()}).optional()}).optional()}),re=L({list:t.optional(),cancel:t.optional(),requests:L({tools:L({call:t.optional()}).optional()}).optional()}),ie=I({experimental:z(A(),t).optional(),sampling:I({context:t.optional(),tools:t.optional()}).optional(),elicitation:te.optional(),roots:I({listChanged:N().optional()}).optional(),tasks:ne.optional(),extensions:z(A(),t).optional()}),ae=I({experimental:z(A(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:I({listChanged:N().optional()}).optional(),resources:I({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:I({listChanged:N().optional()}).optional(),tasks:re.optional(),extensions:z(A(),t).optional()}),oe=I({progress:M(),total:H(M()),message:H(A())}),se=I({...p.shape,...oe.shape,progressToken:n}),ce=m.extend({method:V(`notifications/progress`),params:se}),v=p.extend({level:o,logger:A().optional(),data:P()}),y=m.extend({method:V(`notifications/message`),params:v}),le=I({uri:A(),mimeType:H(A()),_meta:z(A(),P()).optional()}),ue=le.extend({text:A()}),de=le.extend({blob:s}),fe=I({audience:F(a).optional(),priority:M().min(0).max(1).optional(),lastModified:ea({offset:!0}).optional()}),pe=I({..._.shape,...g.shape,uri:A(),description:H(A()),mimeType:H(A()),size:H(M()),annotations:fe.optional(),_meta:H(L({}))}),me=I({..._.shape,...g.shape,uriTemplate:A(),description:H(A()),mimeType:H(A()),annotations:fe.optional(),_meta:H(L({}))}),he=m.extend({method:V(`notifications/resources/list_changed`),params:p.optional()}),ge=p.extend({uri:A()}),_e=m.extend({method:V(`notifications/resources/updated`),params:ge}),ve=I({name:A(),description:H(A()),required:H(N())}),ye=I({..._.shape,...g.shape,description:H(A()),arguments:H(F(ve)),_meta:H(L({}))}),be=m.extend({method:V(`notifications/prompts/list_changed`),params:p.optional()}),b=I({type:V(`text`),text:A(),annotations:fe.optional(),_meta:z(A(),P()).optional()}),x=I({type:V(`image`),data:s,mimeType:A(),annotations:fe.optional(),_meta:z(A(),P()).optional()}),xe=I({type:V(`audio`),data:s,mimeType:A(),annotations:fe.optional(),_meta:z(A(),P()).optional()}),Se=I({type:V(`tool_use`),name:A(),id:A(),input:z(A(),P()),_meta:z(A(),P()).optional()}),Ce=I({type:V(`resource`),resource:R([ue,de]),annotations:fe.optional(),_meta:z(A(),P()).optional()}),we=pe.extend({type:V(`resource_link`)}),S=R([b,x,xe,we,Ce]),Te=I({role:a,content:S}),Ee=I({title:A().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),De=m.extend({method:V(`notifications/tools/list_changed`),params:p.optional()}),Oe=I({name:A().optional()}),ke=I({hints:F(Oe).optional(),costPriority:M().min(0).max(1).optional(),speedPriority:M().min(0).max(1).optional(),intelligencePriority:M().min(0).max(1).optional()}),Ae=I({mode:B([`auto`,`required`,`none`]).optional()}),je=I({type:V(`boolean`),title:A().optional(),description:A().optional(),default:N().optional()}),Me=I({type:V(`string`),title:A().optional(),description:A().optional(),minLength:M().optional(),maxLength:M().optional(),format:B([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),C=I({type:B([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),Ne=I({type:V(`string`),title:A().optional(),description:A().optional(),enum:F(A()),default:A().optional()}),Pe=I({type:V(`string`),title:A().optional(),description:A().optional(),oneOf:F(I({const:A(),title:A()})),default:A().optional()}),Fe=I({type:V(`string`),title:A().optional(),description:A().optional(),enum:F(A()),enumNames:F(A()).optional(),default:A().optional()}),Ie=R([Ne,Pe]),Le=I({type:V(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({type:V(`string`),enum:F(A())}),default:F(A()).optional()}),Re=I({type:V(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({anyOf:F(I({const:A(),title:A()}))}),default:F(A()).optional()}),ze=R([Le,Re]),Be=R([Fe,Ie,ze]),Ve=R([Be,je,Me,C]),He=f.extend({mode:V(`form`).optional(),message:A(),requestedSchema:I({type:V(`object`),properties:z(A(),Ve),required:F(A()).optional()}).catchall(P())}),Ue=I({type:V(`ref/resource`),uri:A()}),We=I({type:V(`ref/prompt`),name:A()}),Ge=I({uri:A().startsWith(`file://`),name:A().optional(),_meta:z(A(),P()).optional()}),Ke=ie.shape,qe=I({experimental:Ke.experimental,sampling:Ke.sampling,elicitation:Ke.elicitation,roots:Ke.roots,extensions:Ke.extensions}),Je=ae.shape,Ye=I({experimental:Je.experimental,logging:Je.logging,completions:Je.completions,prompts:Je.prompts,resources:Je.resources,tools:Je.tools,extensions:Je.extensions}),Xe=L({progressToken:n.optional(),[Uo]:A(),[Wo]:ee.optional(),[Ko]:qe,[qo]:o.optional()}),Ze=I({..._.shape,...g.shape,description:A().optional(),inputSchema:L({$schema:A().optional(),type:V(`object`)}),outputSchema:L({$schema:A().optional()}).optional(),annotations:Ee.optional(),_meta:z(A(),P()).optional()}),Qe=I({type:V(`tool_result`),toolUseId:A(),content:F(S),structuredContent:P().optional(),isError:N().optional(),_meta:z(A(),P()).optional()}),$e=R([b,x,xe,Se,Qe]),et=I({role:a,content:R([$e,F($e)]),_meta:z(A(),P()).optional()}),tt=A(),nt=L({[Go]:ee.optional().catch(void 0)}),rt=nt.optional();function w(e){return L({_meta:rt,resultType:tt.default(`complete`),...e})}let it=w({}),at=w({nextCursor:r.optional()}),ot=w({content:F(S),structuredContent:P().optional(),isError:N().optional()}),st=w({ttlMs:M().int().min(0),cacheScope:B([`public`,`private`]),tools:F(Ze),nextCursor:r.optional()}),ct=w({ttlMs:M().int().min(0),cacheScope:B([`public`,`private`]),prompts:F(ye),nextCursor:r.optional()}),lt=w({description:A().optional(),messages:F(Te)}),ut=w({ttlMs:M().int().min(0),cacheScope:B([`public`,`private`]),resources:F(pe),nextCursor:r.optional()}),dt=w({ttlMs:M().int().min(0),cacheScope:B([`public`,`private`]),resourceTemplates:F(me),nextCursor:r.optional()}),ft=w({ttlMs:M().int().min(0),cacheScope:B([`public`,`private`]),contents:F(R([ue,de]))}),pt=w({completion:I({values:F(A()).max(100),total:M().int().optional(),hasMore:N().optional()}).loose()}),mt=w({ttlMs:M().int().min(0),cacheScope:B([`public`,`private`])}),ht=w({ttlMs:M().int().min(0).catch(0),cacheScope:B([`public`,`private`]).catch(`private`),supportedVersions:F(A()),capabilities:Ye,instructions:A().optional()}),T=I({messages:F(et),modelPreferences:ke.optional(),systemPrompt:A().optional(),includeContext:B([`none`,`thisServer`,`allServers`]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:F(A()).optional(),metadata:t.optional(),tools:F(Ze).optional(),toolChoice:Ae.optional()}),gt=I({method:V(`sampling/createMessage`),params:T}),_t=I({method:V(`roots/list`),params:I({_meta:z(A(),P()).optional()}).optional()}),vt=I({...et.shape,model:A(),stopReason:A().optional()}),yt=I({roots:F(Ge)}),bt=I({action:B([`accept`,`decline`,`cancel`]),content:z(A(),R([A(),M(),N(),F(A())])).optional()}),xt=I({mode:V(`url`),message:A(),url:A().url()}),St=R([He,xt]),Ct=I({method:V(`elicitation/create`),params:St}),wt=R([gt,_t,Ct]),Tt=R([vt,yt,bt]),Et=z(A(),wt),Dt=z(A(),Tt),Ot=w({inputRequests:Et.optional(),requestState:A().optional()}),kt={inputResponses:Dt.optional(),requestState:A().optional()},At=I({_meta:Xe,...kt}),jt=L({progressToken:n.optional()});function Mt(e,t){return I({method:V(e),params:I({_meta:Xe,...t})})}function Nt(e,t){return I({method:V(e),params:I({_meta:jt.optional(),...t}).optional()})}let E={name:A(),arguments:z(A(),P()).optional(),...kt},Pt={cursor:r.optional()},D=Mt(`tools/call`,E),Ft=Mt(`tools/list`,Pt),It=Mt(`prompts/list`,Pt),Lt=Mt(`prompts/get`,{name:A(),arguments:z(A(),A()).optional(),...kt}),Rt=Mt(`resources/list`,Pt),zt=Mt(`resources/templates/list`,Pt),Bt=Mt(`resources/read`,{uri:A(),...kt}),Vt={ref:R([We,Ue]),argument:I({name:A(),value:A()}),context:I({arguments:z(A(),A()).optional()}).optional()},Ht=Mt(`completion/complete`,Vt),Ut=Mt(`server/discover`,{}),Wt=I({toolsListChanged:N().optional(),promptsListChanged:N().optional(),resourcesListChanged:N().optional(),resourceSubscriptions:F(A()).optional()}),Gt={notifications:Wt},Kt=Mt(`subscriptions/listen`,Gt),qt=nt.extend({"io.modelcontextprotocol/subscriptionId":i}),Jt=L({_meta:qt,resultType:tt.default(`complete`)}),Yt={"tools/call":Nt(`tools/call`,E),"tools/list":Nt(`tools/list`,Pt),"prompts/get":Nt(`prompts/get`,{name:A(),arguments:z(A(),A()).optional()}),"prompts/list":Nt(`prompts/list`,Pt),"resources/list":Nt(`resources/list`,Pt),"resources/templates/list":Nt(`resources/templates/list`,Pt),"resources/read":Nt(`resources/read`,{uri:A()}),"completion/complete":Nt(`completion/complete`,Vt),"server/discover":Nt(`server/discover`,{}),"subscriptions/listen":Nt(`subscriptions/listen`,Gt)};function Xt(e){return L({_meta:rt,...e})}let Zt={"tools/call":Xt({content:F(S),structuredContent:P().optional(),isError:N().optional()}),"tools/list":Xt({ttlMs:M().int().min(0),cacheScope:B([`public`,`private`]),tools:F(Ze),nextCursor:r.optional()}),"prompts/get":Xt({description:A().optional(),messages:F(Te)}),"prompts/list":Xt({ttlMs:M().int().min(0),cacheScope:B([`public`,`private`]),prompts:F(ye),nextCursor:r.optional()}),"resources/list":Xt({ttlMs:M().int().min(0),cacheScope:B([`public`,`private`]),resources:F(pe),nextCursor:r.optional()}),"resources/templates/list":Xt({ttlMs:M().int().min(0),cacheScope:B([`public`,`private`]),resourceTemplates:F(me),nextCursor:r.optional()}),"resources/read":Xt({ttlMs:M().int().min(0),cacheScope:B([`public`,`private`]),contents:F(R([ue,de]))}),"completion/complete":Xt({completion:I({values:F(A()).max(100),total:M().int().optional(),hasMore:N().optional()}).loose()}),"server/discover":Xt({ttlMs:M().int().min(0).catch(0),cacheScope:B([`public`,`private`]).catch(`private`),supportedVersions:F(A()),capabilities:Ye,instructions:A().optional()}),"subscriptions/listen":Xt({})},Qt=L({"io.modelcontextprotocol/subscriptionId":i.optional()}),$t=I({method:V(`notifications/subscriptions/acknowledged`),params:I({_meta:Qt.optional(),notifications:Wt})}),en=I({_meta:Qt.optional(),requestId:i,reason:A().optional()}),tn=I({method:V(`notifications/cancelled`),params:en}),nn={"notifications/cancelled":tn,"notifications/progress":ce,"notifications/message":y,"notifications/resources/updated":_e,"notifications/resources/list_changed":he,"notifications/tools/list_changed":De,"notifications/prompts/list_changed":be,"notifications/subscriptions/acknowledged":$t},rn=e=>I({jsonrpc:V(`2.0`),id:R([A(),M().int()]),result:e}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,RequestIdSchema:i,RoleSchema:a,LoggingLevelSchema:o,TaskMetadataSchema:c,RelatedTaskMetadataSchema:l,RequestMetaSchema:u,BaseRequestParamsSchema:d,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:p,NotificationSchema:m,IconSchema:h,IconsSchema:g,BaseMetadataSchema:_,ImplementationSchema:ee,ClientTasksCapabilitySchema:ne,ServerTasksCapabilitySchema:re,ClientCapabilitiesSchema:ie,ServerCapabilitiesSchema:ae,ProgressSchema:oe,ProgressNotificationParamsSchema:se,ProgressNotificationSchema:ce,LoggingMessageNotificationParamsSchema:v,LoggingMessageNotificationSchema:y,ResourceContentsSchema:le,TextResourceContentsSchema:ue,BlobResourceContentsSchema:de,AnnotationsSchema:fe,ResourceSchema:pe,ResourceTemplateSchema:me,ResourceListChangedNotificationSchema:he,ResourceUpdatedNotificationParamsSchema:ge,ResourceUpdatedNotificationSchema:_e,PromptArgumentSchema:ve,PromptSchema:ye,PromptListChangedNotificationSchema:be,TextContentSchema:b,ImageContentSchema:x,AudioContentSchema:xe,ToolUseContentSchema:Se,EmbeddedResourceSchema:Ce,ResourceLinkSchema:we,ContentBlockSchema:S,PromptMessageSchema:Te,ToolAnnotationsSchema:Ee,ToolListChangedNotificationSchema:De,ModelHintSchema:Oe,ModelPreferencesSchema:ke,ToolChoiceSchema:Ae,BooleanSchemaSchema:je,StringSchemaSchema:Me,NumberSchemaSchema:C,UntitledSingleSelectEnumSchemaSchema:Ne,TitledSingleSelectEnumSchemaSchema:Pe,LegacyTitledEnumSchemaSchema:Fe,SingleSelectEnumSchemaSchema:Ie,UntitledMultiSelectEnumSchemaSchema:Le,TitledMultiSelectEnumSchemaSchema:Re,MultiSelectEnumSchemaSchema:ze,EnumSchemaSchema:Be,PrimitiveSchemaDefinitionSchema:Ve,ElicitRequestFormParamsSchema:He,ResourceTemplateReferenceSchema:Ue,PromptReferenceSchema:We,RootSchema:Ge,ClientCapabilities2026Schema:qe,ServerCapabilities2026Schema:Ye,RequestMetaEnvelopeSchema:Xe,ToolSchema:Ze,ToolResultContentSchema:Qe,SamplingMessageContentBlockSchema:$e,SamplingMessageSchema:et,ResultTypeSchema:tt,ResultMetaSchema:nt,ResultSchema:it,PaginatedResultSchema:at,CallToolResultSchema:ot,ListToolsResultSchema:st,ListPromptsResultSchema:ct,GetPromptResultSchema:lt,ListResourcesResultSchema:ut,ListResourceTemplatesResultSchema:dt,ReadResourceResultSchema:ft,CompleteResultSchema:pt,CacheableResultSchema:mt,DiscoverResultSchema:ht,CreateMessageRequestParamsSchema:T,CreateMessageRequestSchema:gt,ListRootsRequestSchema:_t,CreateMessageResultSchema:vt,ListRootsResultSchema:yt,ElicitResultSchema:bt,ElicitRequestURLParamsSchema:xt,ElicitRequestParamsSchema:St,ElicitRequestSchema:Ct,InputRequestSchema:wt,InputResponseSchema:Tt,InputRequestsSchema:Et,InputResponsesSchema:Dt,InputRequiredResultSchema:Ot,InputResponseRequestParamsSchema:At,CallToolRequestSchema:D,ListToolsRequestSchema:Ft,ListPromptsRequestSchema:It,GetPromptRequestSchema:Lt,ListResourcesRequestSchema:Rt,ListResourceTemplatesRequestSchema:zt,ReadResourceRequestSchema:Bt,CompleteRequestSchema:Ht,DiscoverRequestSchema:Ut,SubscriptionFilterSchema:Wt,SubscriptionsListenRequestSchema:Kt,SubscriptionsListenResultMetaSchema:qt,SubscriptionsListenResultSchema:Jt,dispatchRequestSchemas:Yt,dispatchResultSchemas:Zt,NotificationMetaSchema:Qt,SubscriptionsAcknowledgedNotificationSchema:$t,CancelledNotificationParamsSchema:en,CancelledNotificationSchema:tn,notificationSchemas2026:nn,JSONRPCResultResponseSchema:rn(it),CallToolResultResponseSchema:rn(R([ot,Ot])),ListToolsResultResponseSchema:rn(st),ListPromptsResultResponseSchema:rn(ct),GetPromptResultResponseSchema:rn(R([lt,Ot])),ListResourcesResultResponseSchema:rn(ut),ListResourceTemplatesResultResponseSchema:rn(dt),ReadResourceResultResponseSchema:rn(R([ft,Ot])),CompleteResultResponseSchema:rn(pt),DiscoverResultResponseSchema:rn(ht)}}let Qf;function $f(){return Qf??=Zf()}let ep=[`tools/list`,`prompts/list`,`resources/list`,`resources/templates/list`,`resources/read`,`server/discover`];function tp(e){return ep.includes(e)}let np=Symbol(`modelcontextprotocol.resultCacheHintFallback`);function rp(e,t){if(t===void 0)return e;let n=e[np];if(n===void 0)return{...e,[np]:t};let r={},i=n.ttlMs??t.ttlMs;i!==void 0&&(r.ttlMs=i);let a=n.cacheScope??t.cacheScope;return a!==void 0&&(r.cacheScope=a),{...e,[np]:r}}function ip(e){return e[np]}function ap(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function op(e){return e===`public`||e===`private`}function sp(e,t){if(e.ttlMs!==void 0&&!ap(e.ttlMs))throw RangeError(`Invalid cache hint for ${t}: ttlMs must be a non-negative safe integer (got ${String(e.ttlMs)})`);if(e.cacheScope!==void 0&&!op(e.cacheScope))throw RangeError(`Invalid cache hint for ${t}: cacheScope must be 'public' or 'private' (got ${String(e.cacheScope)})`)}let Z=function(e){return e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.ResourceNotFound=-32002]=`ResourceNotFound`,e[e.MissingRequiredClientCapability=-32021]=`MissingRequiredClientCapability`,e[e.UnsupportedProtocolVersion=-32022]=`UnsupportedProtocolVersion`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`,e}({});var Q=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ProtocolError`})}static[Symbol.hasInstance](e){return hf(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 hf(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`ProtocolError`,mf(this,new.target)}static fromError(t,n,r){if(t===Z.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new lp(e.elicitations,n)}if(t===Z.UnsupportedProtocolVersion&&r){let e=r;if(Array.isArray(e.supported)&&typeof e.requested==`string`)return new up({supported:e.supported,requested:e.requested},n)}if(t===Z.InvalidParams||t===Z.ResourceNotFound){let e=r;if(typeof e?.uri==`string`&&(t===Z.ResourceNotFound||Object.keys(e).length===1))return new cp(e.uri,n)}if(t===Z.MissingRequiredClientCapability&&r){let e=r;if(e.requiredCapabilities!==null&&typeof e.requiredCapabilities==`object`&&!Array.isArray(e.requiredCapabilities))return new dp({requiredCapabilities:e.requiredCapabilities},n)}return new e(t,n,r)}},cp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ResourceNotFoundError`})}constructor(e,t=`Resource not found: ${e}`){super(Z.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},lp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UrlElicitationRequiredError`})}constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Z.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},up=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UnsupportedProtocolVersionError`})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(Z.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},dp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.MissingRequiredClientCapabilityError`})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(`, `)}`){super(Z.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}};let fp=[`tools/call`,`prompts/get`,`resources/read`];function pp(e,t){let n=t.resultType;if(n===void 0)return{...t,resultType:`complete`};if(n===`complete`||fp.includes(e))return t;throw new Q(Z.InternalError,`Handler for ${e} returned resultType '${String(n)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function mp(e,t){let n=ip(t);if(t.resultType!==`complete`||!tp(e))return n===void 0?t:yp(t);let r=t,i=ap(r.ttlMs)?r.ttlMs:_p(n),a=op(r.cacheScope)?r.cacheScope:vp(n),o={...r,ttlMs:i,cacheScope:a};return delete o[np],o}function hp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gp(e,t){if(t===void 0)return e;let n=e._meta;return n===void 0?{...e,_meta:{[Go]:t}}:!hp(n)||n[`io.modelcontextprotocol/serverInfo`]!==void 0?e:{...e,_meta:{...n,[Go]:t}}}function _p(e){return e!==void 0&&ap(e.ttlMs)?e.ttlMs:0}function vp(e){return e!==void 0&&op(e.cacheScope)?e.cacheScope:`private`}function yp(e){let t={...e};return delete t[np],t}let bp=[`elicitation/create`,`sampling/createMessage`,`roots/list`],xp;function Sp(){if(xp)return xp;let e=$f();return xp={request:{"elicitation/create":I({method:V(`elicitation/create`),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":I({method:V(`sampling/createMessage`),params:e.CreateMessageRequestParamsSchema}),"roots/list":I({method:V(`roots/list`),params:L({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},xp}function Cp(e){return bp.includes(e)}function wp(e){return Cp(e)?Sp().request[e]:void 0}function Tp(e){return Cp(e)?Sp().response[e]:void 0}let Ep={"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},Dp={"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 Op(e){return Object.prototype.hasOwnProperty.call(Ep,e)}function kp(e){return Object.prototype.hasOwnProperty.call(Dp,e)}function Ap(e){return Object.prototype.hasOwnProperty.call(Ep,e)}function jp(e){return Op(e)?$f().dispatchRequestSchemas[e]:void 0}function Mp(e){return Ap(e)?$f().dispatchResultSchemas[e]:void 0}function Np(e){return kp(e)?$f().notificationSchemas2026[e]:void 0}function Pp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fp(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}let Ip={ok:!1,reason:`not-in-era`},Lp=[Uo,Ko];function Rp(e,t){let n=t,r=!1,i=()=>(r||=(n={...n},!0),n),a=t.tools;e===`tools/list`&&Array.isArray(a)&&a.some(e=>Pp(e)&&`execution`in e)&&(i().tools=a.map(e=>{if(!Pp(e)||!(`execution`in e))return e;let t={...e};return delete t.execution,t}));let o=t.capabilities;if(Pp(o)&&`tasks`in o){let e={...o};delete e.tasks,i().capabilities=e}return n}let zp={era:`2026-07-28`,hasRequestMethod:Op,hasNotificationMethod:kp,hasInputRequestMethod:e=>wp(e)!==void 0,validateRequest:(e,t)=>Fp(jp(e),t),validateResult:(e,t)=>Fp(Mp(e),t),validateNotification:(e,t)=>Fp(Np(e),t),validateInputRequest:(e,t)=>Fp(wp(e),t),validateInputResponse:(e,t)=>Fp(Tp(e),t),samplingResultVariant:()=>Ip,outboundEnvelope(e){return{[Uo]:e.protocolVersion,[Wo]:e.clientInfo,[Ko]:e.clientCapabilities,...e.logLevel!==void 0&&{"io.modelcontextprotocol/logLevel":e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of Lp)n in e||t.push({key:n,problem:`missing`});let n=$f().RequestMetaEnvelopeSchema.safeParse(e);if(!n.success)for(let e of n.error.issues){let n=e.path.map(String),r=n.length>0?n.join(`.`):`_meta`;n.length===1&&t.some(e=>e.key===r&&e.problem===`missing`)||t.push({key:r,problem:e.message})}return t},projectCallToolResult:e=>Cf(e),inputRequestSchema:wp,decodeResult(e,t){if(!Pp(t))return{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let n=t.resultType;if(n===void 0)return{kind:`invalid`,error:new X(Y.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 n!=`string`)return{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:n})};if(n===`input_required`){let n=t.inputRequests,r=Pp(n)?n:{},i=t.requestState;return Object.keys(r).length===0&&typeof i!=`string`?{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:`input-required-missing-both`})}:{kind:`input_required`,inputRequests:r,...typeof i==`string`&&{requestState:i}}}if(n!==`complete`)return{kind:`invalid`,error:new X(Y.UnsupportedResultType,`Unsupported result type '${n}' for ${e}`,{resultType:n,method:e})};let r=Vp(),i=Object.hasOwn(r,e)?r[e]:void 0;if(i!==void 0){let n=i.safeParse(t);if(!n.success)return{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: ${n.error}`,{method:e})}}let a={...t};return delete a.resultType,{kind:`complete`,result:a}},encodeResult(e,t,n){return gp(mp(e,pp(e,Rp(e,t))),n)},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=$f().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(e=>e.message).join(`; `)}`}},Bp;function Vp(){if(Bp)return Bp;let e=$f();return Bp={"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},Bp}function Hp(e){return e!==void 0&&bf(e)?zp:Xf}function Up(e){return e.revision===void 0?e.era===`modern`?zp.era:Xf.era:Hp(e.revision).era}function Wp(e){return Kp.some(t=>t.hasRequestMethod(e))}function Gp(e){return Kp.some(t=>t.hasNotificationMethod(e))}let Kp=[Xf,zp];var qp=of({AnnotationsSchema:()=>Hs,AudioContentSchema:()=>xc,BaseMetadataSchema:()=>_s,BaseRequestParamsSchema:()=>W,BlobResourceContentsSchema:()=>Bs,BooleanSchemaSchema:()=>nl,CallToolRequestParamsSchema:()=>Ic,CallToolRequestSchema:()=>Lc,CallToolResultSchema:()=>Pc,CancelTaskRequestSchema:()=>Hl,CancelTaskResultSchema:()=>Ul,CancelledNotificationParamsSchema:()=>ps,CancelledNotificationSchema:()=>ms,ClientCapabilitiesSchema:()=>Ss,ClientNotificationSchema:()=>Gl,ClientRequestSchema:()=>Wl,ClientResultSchema:()=>Kl,ClientTasksCapabilitySchema:()=>bs,CompatibilityCallToolResultSchema:()=>Fc,CompleteRequestParamsSchema:()=>Cl,CompleteRequestSchema:()=>wl,CompleteResultSchema:()=>Tl,ContentBlockSchema:()=>Tc,CreateMessageRequestParamsSchema:()=>Qc,CreateMessageRequestSchema:()=>$c,CreateMessageResultSchema:()=>el,CreateMessageResultWithToolsSchema:()=>tl,CreateTaskResultSchema:()=>Nl,CursorSchema:()=>Zo,DiscoverRequestSchema:()=>Os,DiscoverResultSchema:()=>ks,ElicitRequestFormParamsSchema:()=>ml,ElicitRequestParamsSchema:()=>gl,ElicitRequestSchema:()=>_l,ElicitRequestURLParamsSchema:()=>hl,ElicitResultSchema:()=>bl,ElicitationCompleteNotificationParamsSchema:()=>vl,ElicitationCompleteNotificationSchema:()=>yl,EmbeddedResourceSchema:()=>Cc,EmptyResultSchema:()=>fs,EnumSchemaSchema:()=>fl,GetPromptRequestParamsSchema:()=>_c,GetPromptRequestSchema:()=>vc,GetPromptResultSchema:()=>Dc,GetTaskPayloadRequestSchema:()=>Rl,GetTaskPayloadResultSchema:()=>zl,GetTaskRequestSchema:()=>Il,GetTaskResultSchema:()=>Ll,IconSchema:()=>hs,IconsSchema:()=>gs,ImageContentSchema:()=>bc,ImplementationSchema:()=>vs,InitializeRequestParamsSchema:()=>Cs,InitializeRequestSchema:()=>ws,InitializeResultSchema:()=>Es,InitializedNotificationSchema:()=>Ds,JSONArraySchema:()=>Yo,JSONObjectSchema:()=>U,JSONRPCErrorResponseSchema:()=>ls,JSONRPCMessageSchema:()=>us,JSONRPCNotificationSchema:()=>ss,JSONRPCRequestSchema:()=>os,JSONRPCResponseSchema:()=>ds,JSONRPCResultResponseSchema:()=>cs,JSONValueSchema:()=>Jo,LegacyTitledEnumSchemaSchema:()=>sl,ListChangedOptionsBaseSchema:()=>zc,ListPromptsRequestSchema:()=>hc,ListPromptsResultSchema:()=>gc,ListResourceTemplatesRequestSchema:()=>qs,ListResourceTemplatesResultSchema:()=>Js,ListResourcesRequestSchema:()=>Gs,ListResourcesResultSchema:()=>Ks,ListRootsRequestSchema:()=>Dl,ListRootsResultSchema:()=>Ol,ListTasksRequestSchema:()=>Bl,ListTasksResultSchema:()=>Vl,ListToolsRequestSchema:()=>Mc,ListToolsResultSchema:()=>Nc,LoggingLevelSchema:()=>Bc,LoggingMessageNotificationParamsSchema:()=>Uc,LoggingMessageNotificationSchema:()=>Wc,ModelHintSchema:()=>Gc,ModelPreferencesSchema:()=>Kc,MultiSelectEnumSchemaSchema:()=>dl,NotificationSchema:()=>rs,NotificationsParamsSchema:()=>ns,NumberSchemaSchema:()=>il,PaginatedRequestParamsSchema:()=>Ps,PaginatedRequestSchema:()=>Fs,PaginatedResultSchema:()=>Is,PingRequestSchema:()=>As,PrimitiveSchemaDefinitionSchema:()=>pl,ProgressNotificationParamsSchema:()=>Ms,ProgressNotificationSchema:()=>Ns,ProgressSchema:()=>js,ProgressTokenSchema:()=>Xo,PromptArgumentSchema:()=>pc,PromptListChangedNotificationSchema:()=>Oc,PromptMessageSchema:()=>Ec,PromptReferenceSchema:()=>Sl,PromptSchema:()=>mc,ReadResourceRequestParamsSchema:()=>Xs,ReadResourceRequestSchema:()=>Zs,ReadResourceResultSchema:()=>Qs,RelatedTaskMetadataSchema:()=>$o,RequestIdSchema:()=>as,RequestMetaSchema:()=>es,RequestSchema:()=>G,ResourceContentsSchema:()=>Ls,ResourceLinkSchema:()=>wc,ResourceListChangedNotificationSchema:()=>$s,ResourceRequestParamsSchema:()=>Ys,ResourceSchema:()=>Us,ResourceTemplateReferenceSchema:()=>xl,ResourceTemplateSchema:()=>Ws,ResourceUpdatedNotificationParamsSchema:()=>dc,ResourceUpdatedNotificationSchema:()=>fc,ResultMetaObjectSchema:()=>is,ResultSchema:()=>K,RoleSchema:()=>Vs,RootSchema:()=>El,RootsListChangedNotificationSchema:()=>kl,SamplingContentSchema:()=>Yc,SamplingMessageContentBlockSchema:()=>Xc,SamplingMessageSchema:()=>Zc,ServerCapabilitiesSchema:()=>Ts,ServerNotificationSchema:()=>Jl,ServerRequestSchema:()=>ql,ServerResultSchema:()=>Yl,ServerTasksCapabilitySchema:()=>xs,SetLevelRequestParamsSchema:()=>Vc,SetLevelRequestSchema:()=>Hc,SingleSelectEnumSchemaSchema:()=>cl,StringSchemaSchema:()=>rl,SubscribeRequestParamsSchema:()=>ec,SubscribeRequestSchema:()=>tc,SubscriptionFilterSchema:()=>ic,SubscriptionsAcknowledgedNotificationParamsSchema:()=>sc,SubscriptionsAcknowledgedNotificationSchema:()=>cc,SubscriptionsListenRequestParamsSchema:()=>ac,SubscriptionsListenRequestSchema:()=>oc,SubscriptionsListenResultMetaSchema:()=>lc,SubscriptionsListenResultSchema:()=>uc,TaskAugmentedRequestParamsSchema:()=>ts,TaskCreationParamsSchema:()=>Al,TaskMetadataSchema:()=>Qo,TaskSchema:()=>Ml,TaskStatusNotificationParamsSchema:()=>Pl,TaskStatusNotificationSchema:()=>Fl,TaskStatusSchema:()=>jl,TextContentSchema:()=>yc,TextResourceContentsSchema:()=>Rs,TitledMultiSelectEnumSchemaSchema:()=>ul,TitledSingleSelectEnumSchemaSchema:()=>ol,ToolAnnotationsSchema:()=>kc,ToolChoiceSchema:()=>qc,ToolExecutionSchema:()=>Ac,ToolListChangedNotificationSchema:()=>Rc,ToolResultContentSchema:()=>Jc,ToolSchema:()=>jc,ToolUseContentSchema:()=>Sc,UnsubscribeRequestParamsSchema:()=>nc,UnsubscribeRequestSchema:()=>rc,UntitledMultiSelectEnumSchemaSchema:()=>ll,UntitledSingleSelectEnumSchemaSchema:()=>al});let Jp=e=>os.safeParse(e).success,Yp=e=>ss.safeParse(e).success,Xp=e=>cs.safeParse(e).success,Zp=e=>ls.safeParse(e).success,Qp=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&e.resultType===`input_required`;function $p(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function em(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}let tm=`x-mcp-header`,nm=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,rm=new Set([`string`,`integer`,`boolean`,`number`]);function im(e){let t=[],n=new Map,r=(e,i,a)=>{if(typeof e!=`object`||!e)return;let o=e;if(tm in o){if(!a||i.length===0)return`${sm(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let e=o[tm];if(typeof e!=`string`||e.length===0)return`${sm(i)}: x-mcp-header MUST be a non-empty string`;if(!nm.test(e))return`${sm(i)}: x-mcp-header '${e}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let r=typeof o.type==`string`?o.type:void 0;if(r===void 0||!rm.has(r))return`${sm(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${r??`<none>`}`;let s=e.toLowerCase(),c=n.get(s);if(c!==void 0)return`x-mcp-header '${e}' is not case-insensitively unique (also declared as '${c}')`;n.set(s,e),t.push({path:i,headerName:e,type:r})}let s=o.properties;if(typeof s==`object`&&s)for(let[e,t]of Object.entries(s)){let n=r(t,[...i,e],a);if(n!==void 0)return n}for(let e of am){let t=o[e];if(t===void 0)continue;let n=Array.isArray(t)?t:typeof t==`object`&&t&&om.has(e)?Object.values(t):[t];for(let t of n){let n=r(t,[...i,`<${e}>`],!1);if(n!==void 0)return n}}},i=r(e,[],!0);return i===void 0?{valid:!0,declarations:t}:{valid:!1,reason:i}}let am=[`items`,`prefixItems`,`contains`,`additionalProperties`,`unevaluatedProperties`,`unevaluatedItems`,`propertyNames`,`patternProperties`,`dependentSchemas`,`oneOf`,`anyOf`,`allOf`,`not`,`if`,`then`,`else`,`$defs`,`definitions`],om=new Set([`patternProperties`,`dependentSchemas`,`$defs`,`definitions`]);function sm(e){return e.length===0?`<root>`:e.join(`.`)}Z.InvalidRequest,Z.UnsupportedProtocolVersion,Z.InvalidParams,Z.MethodNotFound,Z.InvalidParams,Z.MissingRequiredClientCapability,Z.ParseError,Z.InvalidRequest,Z.MethodNotFound,Z.UnsupportedProtocolVersion,Z.MissingRequiredClientCapability;function cm(e,t){return ua(e,t)}function lm(e){return new Set(e.flatMap(e=>Object.keys(e.shape)))}function um(e){if(e==null)return!1;let t=typeof e;return t!==`object`&&t!==`function`||!(`~standard`in e)?!1:typeof e[`~standard`]?.validate==`function`}let dm=!1,fm=`draft-2020-12`;function pm(e,t=`input`){let n=e[`~standard`],r;if(n.jsonSchema)r=n.jsonSchema[t]({target:fm});else if(n.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().`);dm||(dm=!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.")),r=Qi(e,{target:fm,io:t})}else throw Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t===`output`)return r.type===void 0&&mm(r)?{type:`object`,...r}:r;if(r.type!==void 0&&r.type!==`object`)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(r.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:`object`,...r}}function mm(e){if(`properties`in e||`patternProperties`in e||`additionalProperties`in e||`required`in e)return!0;for(let t of[`oneOf`,`anyOf`,`allOf`]){let n=e[t];if(Array.isArray(n)&&n.length>0)return n.every(e=>typeof e==`object`&&!!e&&(e.type===`object`||mm(e)))}return!1}function hm(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function gm(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>hm(e)).join(`, `)}:{success:!0,data:n.value}}function _m(e){let t=Qi(e,{target:fm,io:`input`});return typeof t.pattern==`string`?t.pattern:void 0}let vm=/\\\.\\d\{(\d+)\}/;function ym(e){let t=vm.exec(e),n=[void 0,-1,0];return t&&n.push(Number(t[1])),[!1,!0].flatMap(e=>[!1,!0].flatMap(t=>n.map(n=>ea({local:e,offset:t,precision:n}))))}function bm(e,t){let n;switch(e){case`email`:n=[Ta()];break;case`uri`:n=[ka()];break;case`date`:n=[na()];break;case`date-time`:n=ym(t);break}return new Set(n.map(e=>_m(e)).filter(e=>e!==void 0))}function xm(e,t,n){return n===`zod`?bm(e,t).has(t):!0}function Sm(e){let t=pm(e,`input`),n=t.properties||{},r=t.required||[];return Object.entries(n).map(([e,t])=>({name:e,description:t?.description,required:r.includes(e)}))}function Cm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wm(e){try{return pm(e,`input`)}catch(e){let t=e instanceof Error?e.message:String(e);throw new Q(Z.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${t}`)}}let Tm=new Set([`$comment`,`deprecated`,`description`,`examples`,`readOnly`,`title`,`writeOnly`]);function Em(e){return Tm.has(e)||e.startsWith(`x-`)}let Dm=new Set([`$schema`,...Object.keys(ml.shape.requestedSchema.shape)]),Om={string:lm([rl,al,ol,sl]),number:lm([il]),integer:lm([il]),boolean:lm([nl]),array:lm([ll,ul])},km=new Set(rl.shape.format.unwrap().options);function Am(e,t,n,r){if(!Cm(e))return e;let i=typeof e.type==`string`&&Object.hasOwn(Om,e.type)?Om[e.type]:void 0;if(i===void 0)return e;let a={};for(let[o,s]of Object.entries(e))i.has(o)||Em(o)?a[o]=s:o===`pattern`&&e.type===`string`&&typeof e.format==`string`?km.has(e.format)?(typeof s!=`string`||!xm(e.format,s,n))&&r.push(`${t}.${o}`):a[o]=s:r.push(`${t}.${o}`);return a}function jm(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))i===`properties`&&Cm(a)?n[i]=Object.fromEntries(Object.entries(a).map(([e,n])=>[e,Am(n,`properties.${e}`,t,r)])):Dm.has(i)?n[i]=a:Em(i)||r.push(i);if(r.length>0)throw new Q(Z.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${r.join(`, `)}`);return n}function Mm(e,t){if(!Cm(e.properties))return t;let n=Object.entries(e.properties).filter(([,e])=>!cm(pl,e).success).map(([e])=>`properties.${e}`);return n.length>0?n.join(`, `):t}function Nm(e,t,n=``){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((e,r)=>Nm(e,t[r],`${n}[${r}]`)):!Cm(e)||!Cm(t)?[]:Object.entries(e).flatMap(([e,r])=>{let i=n?`${n}.${e}`:e;return Object.prototype.hasOwnProperty.call(t,e)?Nm(r,t[e],i):Em(e)?[]:[i]})}function Pm(e){if(!um(e.requestedSchema))return{...e,mode:`form`,requestedSchema:e.requestedSchema};let t=e.requestedSchema[`~standard`].vendor,n=jm(wm(e.requestedSchema),t),r=cm(ml.shape.requestedSchema,n);if(!r.success)throw new Q(Z.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Mm(n,r.error.message)}`);let i=Nm(n,r.data);if(i.length>0)throw new Q(Z.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${i.join(`, `)}`);let a=(r.data.required??[]).filter(e=>!Object.prototype.hasOwnProperty.call(r.data.properties,e));if(a.length>0)throw new Q(Z.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${a.join(`, `)}`);return{...e,mode:`form`,requestedSchema:r.data}}function Fm(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,n=typeof e.requestState==`string`;if(!t&&!n)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}}}Object.assign(Fm,{elicit(e){try{return{method:`elicitation/create`,params:Pm(e)}}catch(e){throw e instanceof Q?TypeError(e.message,{cause:e}):e}},elicitUrl(e){return{method:`elicitation/create`,params:{...e,mode:`url`}}},createMessage(e){return{method:`sampling/createMessage`,params:e}},listRoots(){return{method:`roots/list`}}});function Im(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Lm(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason instanceof X?t.reason:new X(Y.RequestTimeout,String(t.reason)));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(t?.reason instanceof X?t.reason:new X(Y.RequestTimeout,String(t?.reason)))};t?.addEventListener(`abort`,a,{once:!0})})}function Rm(e){let t=new AbortController,n=()=>t.abort(e?.reason);return e?.addEventListener(`abort`,n,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:e=>t.abort(e),dispose:()=>e?.removeEventListener(`abort`,n)}}let zm=`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`.split(`.`),Bm={IdJagTokenExchangeResponseSchema:tu,OAuthClientInformationFullSchema:ou,OAuthClientInformationSchema:au,OAuthClientMetadataSchema:iu,OAuthClientRegistrationErrorSchema:su,OAuthErrorResponseSchema:nu,OAuthMetadataSchema:Zl,OAuthProtectedResourceMetadataSchema:Xl,OAuthTokenRevocationRequestSchema:cu,OAuthTokensSchema:eu,OpenIdProviderDiscoveryMetadataSchema:$l,OpenIdProviderMetadataSchema:Ql},Vm={},Hm={};function Um(e,t){let n=e.slice(0,-6);Vm[n]=t,Hm[n]=e=>t.safeParse(e).success}for(let e of zm)Um(e,qp[e]);for(let[e,t]of Object.entries(Bm))Um(e,t);Object.freeze(Vm),Object.freeze(Hm);function Wm(e){switch(e){case`initialize`:case`notifications/initialized`:return Hp(void 0);case`server/discover`:return Hp(`2026-07-28`);default:return}}let Gm=[Uo,Wo,Ko,qo],Km=[`inputResponses`,`requestState`];function qm(e,t){let n=e.params;if(!$m(n))return{message:e,lifted:{}};let r=n._meta,i=$m(r)?Gm.filter(e=>e in r):[],a=t===`request`?Km.filter(e=>e in n):[];if(i.length===0&&a.length===0)return{message:e,lifted:{}};let o={},s={...n};if(i.length>0&&$m(r)){let e={},t={...r};for(let n of i)e[n]=r[n],delete t[n];o.envelope=e,Object.keys(t).length>0?s._meta=t:delete s._meta}for(let e of a)e===`inputResponses`&&(o.inputResponses=s[e]),e===`requestState`&&(o.requestState=s[e]),delete s[e];return{message:{...e,params:s},lifted:o}}function Jm(e,t){let n=e.validateResult(t,void 0);if(!(!n.ok&&n.reason===`not-in-era`))return{"~standard":{version:1,vendor:`mcp-wire-codec`,validate(n){let r=e.validateResult(t,n);return r.ok?{value:r.value}:{issues:[{message:r.reason===`invalid`?r.message:`not-in-era: ${t}`}]}}}}}function Ym(e){return()=>e}let Xm=Ym(void 0);function Zm(e,t){return{...e,mcpReq:{...e.mcpReq,requestState:Ym(t)}}}var Qm=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Ho,this.setNotificationHandler(`notifications/cancelled`,e=>{this._oncancel(e)}),this.setNotificationHandler(`notifications/progress`,e=>{this._onprogress(e)}),this.setRequestHandler(`ping`,e=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let n=e.params??{};return{...e,params:{...n,_meta:{...t,...n._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new X(Y.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new X(Y.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),Xp(e)||Zp(e)?this._onresponse(e):Jp(e)?this._onrequest(e,t):Yp(e)?this._onnotification(e,t):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new X(Y.ConnectionClosed,`Connection closed`);this._transport=void 0;try{this.onclose?.()}finally{for(let t of e.values())t(n);for(let e of t.values())e.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:n}=qm(e,`notification`),r=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`)return;if(t?.classification!==void 0){let e=Up(t.classification);if(e!==r.era){this._onerror(Error(`Era mismatch on inbound notification '${n.method}': classified as ${e} but this instance serves ${r.era}`));return}}if(Gp(n.method)&&!r.hasNotificationMethod(n.method))return;let i=this._notificationHandlers.get(n.method),a=this.fallbackNotificationHandler;i===void 0&&a===void 0||Promise.resolve().then(()=>i===void 0?a(n):i(n,r)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let{message:n,lifted:r}=qm(e,`request`),i=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 a=this._transport,o=(e,t,r)=>{let i={jsonrpc:`2.0`,id:n.id,error:{code:e,message:t,...r!==void 0&&{data:r}}};a?.send(i).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))};if(t?.classification!==void 0){let e=Up(t.classification);if(e!==i.era){this._onerror(Error(`Era mismatch on inbound request '${n.method}': classified as ${e} but this instance serves ${i.era}`));let r=t.classification.revision??e;o(Z.UnsupportedProtocolVersion,`Unsupported protocol version: ${r}`,{supported:this._supportedProtocolVersions,requested:r});return}}if(Wp(n.method)&&!i.hasRequestMethod(n.method)){o(Z.MethodNotFound,`Method not found`);return}let s=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(s===void 0){o(Z.MethodNotFound,`Method not found`);return}let c=i.checkInboundEnvelope(r);if(c!==void 0){o(Z.InvalidParams,c);return}let l=(e,t)=>this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,{...t,relatedRequestId:n.id}),u=(e,t,r)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(e.method),e,t,{...r,relatedRequestId:n.id}),d=new AbortController;this._requestHandlerAbortControllers.set(n.id,d);let f=r.inputResponses===void 0?void 0:nh(r.inputResponses),p={sessionId:a?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...r.envelope!==void 0&&{envelope:r.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:r.requestState===void 0?Xm:Ym(r.requestState),signal:d.signal,send:((e,t,n)=>{let r=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(r,e.method),um(t))return u(e,t,n);let i=Jm(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return u(e,i,t)}),notify:l},http:t?.authInfo?{authInfo:t.authInfo}:void 0},m=this.buildContext(p,t);Promise.resolve().then(()=>s(n,m)).then(async e=>{if(d.signal.aborted)return;let t;try{t=i.encodeResult(n.method,e,this._outboundServerInfo())}catch(e){this._onerror(Error(`Failed to encode result for ${n.method}: ${e}`)),o(Z.InternalError,`Internal error`);return}let r={result:t,jsonrpc:`2.0`,id:n.id};await a?.send(r)},async e=>{if(d.signal.aborted)return;let t=Number.isSafeInteger(e.code)?e.code:Z.InternalError,r={jsonrpc:`2.0`,id:n.id,error:{code:i.encodeErrorCode(t),message:e.message??`Internal error`,...e.data!==void 0&&{data:e.data}}};await a?.send(r)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===d&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Xp(e)?n(e):n(Q.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,n){let r=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(r,e.method),um(t))return this._requestWithSchemaViaCodec(r,e,t,n);let i=Jm(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(r,e,i,t)}_negotiatedWireCodec(){return Hp(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Wm(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Wp(t)&&!e.hasRequestMethod(t))throw new X(Y.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,n){let r=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(r,e.method),this._requestWithSchemaViaCodec(r,e,t,n)}_requestWithSchemaViaCodec(e,t,n,r){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s}=r??{},c=Date.now(),l,u;return new Promise((d,f)=>{let p=e=>{f(e)};if(!this._transport){p(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(e){p(e);return}if(r?.signal?.aborted){let e=r.signal.reason;throw e instanceof X?e:new X(Y.RequestTimeout,String(e))}let m=e.era===`2026-07-28`&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,h=this._requestMessageId++;u=h;let g={...t,jsonrpc:`2.0`,id:h};r?.onprogress&&(this._progressHandlers.set(h,r.onprogress),g.params={...t.params,_meta:{...t.params?._meta,progressToken:h}});let _=this._envelopeOutbound(g),ee=!1,te=e=>{ee||(this._progressHandlers.delete(h),m===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:h,reason:String(e)}}),{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))):m.abort(),f(e instanceof X?e:new X(Y.RequestTimeout,String(e))))};this._responseHandlers.set(h,i=>{if(r?.signal?.aborted)return;if(ee=!0,i instanceof Error)return f(i);let a;try{a=e.decodeResult(t.method,i.result)}catch(e){return f(e instanceof Error?e:Error(String(e)))}if(a.kind===`invalid`)return f(a.error);if(a.kind===`input_required`){if(r?.allowInputRequired===!0)return d(rh(a));let i={codec:e,request:t,resultSchema:n,options:r,flowStartedAt:c,retry:(r,i)=>this._requestWithSchemaViaCodec(e,r===void 0?{method:t.method}:{method:t.method,params:r},n,i)};return d(this._resolveNonCompleteResult(a,i))}let o=a.result;gm(n,o).then(e=>{e.success?d(e.data):f(new X(Y.InvalidResult,`Invalid result for ${t.method}: ${e.error}`))},f)}),l=()=>te(r?.signal?.reason),r?.signal?.addEventListener(`abort`,l,{once:!0});let ne=r?.timeout??6e4;this._setupTimeout(h,ne,r?.maxTotalTimeout,()=>te(new X(Y.RequestTimeout,`Request timed out`,{timeout:ne})),r?.resetTimeoutOnProgress??!1),this._transport.send(_,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s,requestSignal:m?.signal}).catch(e=>{this._progressHandlers.delete(h),f(e)})}).finally(()=>{l&&r?.signal?.removeEventListener(`abort`,l),u!==void 0&&(this._responseHandlers.delete(u),this._cleanupTimeout(u))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,n){if(!this._transport)throw new X(Y.NotConnected,`Not connected`);if(Gp(t.method)&&!e.hasNotificationMethod(t.method))throw new X(Y.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 r=this._envelopeOutbound({jsonrpc:`2.0`,...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!n?.relatedRequestId){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(r,n).catch(e=>this._onerror(e))});return}await this._transport.send(r,n)}setRequestHandler(e,t,n){this.assertRequestHandlerCapability(e);let r;if(typeof t==`function`){if(!Wp(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);r=(n,r)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason===`not-in-era`&&(a=i.validateInputRequest(e,n)),!a.ok)throw a.reason===`not-in-era`?new Q(Z.InternalError,`No wire schema for ${e} in the resolved era`):Error(a.message);return Promise.resolve(t(a.value,r))}}else if(n)r=async(r,i)=>{let a=await gm(t.params,{...r.params});if(!a.success)throw new Q(Z.InvalidParams,`Invalid params for ${e}: ${a.error}`);return n(a.data,i)};else throw TypeError(`setRequestHandler: handler is required`);this._requestHandlers.set(e,this._wrapHandler(e,r))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,n){if(typeof t==`function`){if(!Gp(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,r)=>{let i=r.validateNotification(e,n);if(!i.ok)throw i.reason===`not-in-era`?new Q(Z.InternalError,`No wire schema for ${e} in the resolved era`):Error(i.message);return Promise.resolve(t(i.value))});return}if(!n)throw TypeError(`setNotificationHandler: handler is required`);this._notificationHandlers.set(e,async r=>{let i=await gm(t.params,{...r.params});if(!i.success)throw new Q(Z.InvalidParams,`Invalid params for notification ${e}: ${i.error}`);await n(i.data,r)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function $m(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function eh(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=$m(a)&&$m(i)?{...a,...i}:i}return n}function th(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nh(e){let t={},n=[];if(!th(e))return{accepted:t,droppedKeys:n};for(let[r,i]of Object.entries(e)){if(!th(i)||`method`in i||`result`in i){n.push(r);continue}t[r]=i}return{accepted:t,droppedKeys:n}}function rh(e){return{resultType:`input_required`,inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}
|
|
64
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function ci(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:di(t,`input`,e.processors),output:di(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function li(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return li(r.element,n);if(r.type===`set`)return li(r.valueType,n);if(r.type===`lazy`)return li(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return li(r.innerType,n);if(r.type===`intersection`)return li(r.left,n)||li(r.right,n);if(r.type===`record`||r.type===`map`)return li(r.keyType,n)||li(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:li(r.in,n)||li(r.out,n);if(r.type===`object`){for(let e in r.shape)if(li(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(li(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(li(e,n))return!0;return!!(r.rest&&li(r.rest,n))}return!1}let ui=(e,t={})=>n=>{let r=oi({...n,processors:t});return D(e,r),si(r,e),ci(r,e)},di=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=oi({...i??{},target:a,io:t,processors:n});return D(e,o),si(o,e),ci(o,e)},fi={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},pi=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=fi[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},mi=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},hi=(e,t,n,r)=>{n.type=`boolean`},gi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},_i=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},vi=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},yi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},bi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},xi=(e,t,n,r)=>{n.not={}},Si=(e,t,n,r)=>{},Ci=(e,t,n,r)=>{},wi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},Ti=(e,t,n,r)=>{let i=e._zod.def,a=c(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Ei=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},Di=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},Oi=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},ki=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},Ai=(e,t,n,r)=>{n.type=`boolean`},ji=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Mi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},Ni=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Pi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},Fi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},Ii=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=D(a.element,t,{...r,path:[...r.path,`items`]})},Li=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=D(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=D(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Ri=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>D(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},zi=(e,t,n,r)=>{let i=e._zod.def,a=D(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=D(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},Bi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>D(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?D(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},Vi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=D(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=D(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=D(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},Hi=(e,t,n,r)=>{let i=e._zod.def,a=D(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Ui=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Wi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Gi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Ki=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},qi=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;D(o,t,r);let s=t.seen.get(e);s.ref=o},Ji=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Yi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Zi=(e,t,n,r)=>{let i=e._zod.innerType;D(i,t,r);let a=t.seen.get(e);a.ref=i},Qi={string:pi,number:mi,boolean:hi,bigint:gi,symbol:_i,null:vi,undefined:yi,void:bi,never:xi,any:Si,unknown:Ci,date:wi,enum:Ti,literal:Ei,nan:Di,template_literal:Oi,file:ki,success:Ai,custom:ji,function:Mi,transform:Ni,map:Pi,set:Fi,array:Ii,object:Li,union:Ri,intersection:zi,tuple:Bi,record:Vi,nullable:Hi,nonoptional:Ui,default:Wi,prefault:Gi,catch:Ki,pipe:qi,readonly:Ji,promise:Yi,optional:Xi,lazy:Zi};function $i(e,t){if(`_idmap`in e){let n=e,r=oi({...t,processors:Qi}),i={};for(let e of n._idmap.entries()){let[t,n]=e;D(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;si(r,n),a[t]=ci(r,n)}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=oi({...t,processors:Qi});return D(e,n),si(n,e),ci(n,e)}let ea=r(`ZodISODateTime`,(e,t)=>{qt.init(e,t),A.init(e,t)});function ta(e){return wr(ea,e)}let na=r(`ZodISODate`,(e,t)=>{Jt.init(e,t),A.init(e,t)});function ra(e){return Tr(na,e)}let ia=r(`ZodISOTime`,(e,t)=>{Yt.init(e,t),A.init(e,t)});function aa(e){return Er(ia,e)}let oa=r(`ZodISODuration`,(e,t)=>{Xt.init(e,t),A.init(e,t)});function sa(e){return Dr(oa,e)}let ca=r(`ZodError`,(e,t)=>{Te.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>De(e,t)},flatten:{value:t=>Ee(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,l,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,l,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),la=Oe(ca),ua=ke(ca),da=Ae(ca),fa=Me(ca),pa=S(ca),ma=Pe(ca),ha=Fe(ca),ga=Ie(ca),_a=Le(ca),va=Re(ca),ya=ze(ca),ba=Be(ca),xa=new WeakMap;function Sa(e,t,n){let r=Object.getPrototypeOf(e),i=xa.get(r);if(i||(i=new Set,xa.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}let O=r(`ZodType`,(e,t)=>(T.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:di(e,`input`),output:di(e,`output`)}}),e.toJSONSchema=ui(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>la(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>da(e,t,n),e.parseAsync=async(t,n)=>ua(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>fa(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>pa(e,t,n),e.decode=(t,n)=>ma(e,t,n),e.encodeAsync=async(t,n)=>ha(e,t,n),e.decodeAsync=async(t,n)=>ga(e,t,n),e.safeEncode=(t,n)=>_a(e,t,n),e.safeDecode=(t,n)=>va(e,t,n),e.safeEncodeAsync=async(t,n)=>ya(e,t,n),e.safeDecodeAsync=async(t,n)=>ba(e,t,n),Sa(e,`ZodType`,{check(...e){let t=this.def;return this.clone(_(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return le(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Lo(e,t))},superRefine(e,t){return this.check(Ro(e,t))},overwrite(e){return this.check(Xr(e))},optional(){return V(this)},exactOptional(){return vo(this)},nullable(){return bo(this)},nullish(){return V(bo(this))},nonoptional(e){return Eo(this,e)},array(){return P(this)},or(e){return L([this,e])},and(e){return lo(this,e)},transform(e){return Ao(this,ho(e))},default(e){return So(this,e)},prefault(e){return wo(this,e)},catch(e){return Oo(this,e)},pipe(e){return Ao(this,e)},readonly(){return No(this)},describe(e){let t=this.clone();return er.add(t,{description:e}),t},meta(...e){if(e.length===0)return er.get(this);let t=this.clone();return er.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return er.get(e)?.description},configurable:!0}),e)),Ca=r(`_ZodString`,(e,t)=>{Ft.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Sa(e,`_ZodString`,{regex(...e){return this.check(Wr(...e))},includes(...e){return this.check(qr(...e))},startsWith(...e){return this.check(Jr(...e))},endsWith(...e){return this.check(Yr(...e))},min(...e){return this.check(Hr(...e))},max(...e){return this.check(Vr(...e))},length(...e){return this.check(Ur(...e))},nonempty(...e){return this.check(Hr(1,...e))},lowercase(e){return this.check(Gr(e))},uppercase(e){return this.check(Kr(e))},trim(){return this.check(Qr())},normalize(...e){return this.check(Zr(...e))},toLowerCase(){return this.check($r())},toUpperCase(){return this.check(ei())},slugify(){return this.check(ti())}})}),wa=r(`ZodString`,(e,t)=>{Ft.init(e,t),Ca.init(e,t),e.email=t=>e.check(nr(Ta,t)),e.url=t=>e.check(cr(ka,t)),e.jwt=t=>e.check(Cr(Ga,t)),e.emoji=t=>e.check(lr(ja,t)),e.guid=t=>e.check(rr(Da,t)),e.uuid=t=>e.check(ir(Oa,t)),e.uuidv4=t=>e.check(ar(Oa,t)),e.uuidv6=t=>e.check(or(Oa,t)),e.uuidv7=t=>e.check(sr(Oa,t)),e.nanoid=t=>e.check(ur(Ma,t)),e.guid=t=>e.check(rr(Da,t)),e.cuid=t=>e.check(dr(Na,t)),e.cuid2=t=>e.check(fr(Pa,t)),e.ulid=t=>e.check(pr(Fa,t)),e.base64=t=>e.check(br(Ha,t)),e.base64url=t=>e.check(xr(Ua,t)),e.xid=t=>e.check(mr(Ia,t)),e.ksuid=t=>e.check(hr(La,t)),e.ipv4=t=>e.check(gr(Ra,t)),e.ipv6=t=>e.check(_r(za,t)),e.cidrv4=t=>e.check(vr(Ba,t)),e.cidrv6=t=>e.check(yr(Va,t)),e.e164=t=>e.check(Sr(Wa,t)),e.datetime=t=>e.check(ta(t)),e.date=t=>e.check(ra(t)),e.time=t=>e.check(aa(t)),e.duration=t=>e.check(sa(t))});function k(e){return tr(wa,e)}let A=r(`ZodStringFormat`,(e,t)=>{E.init(e,t),Ca.init(e,t)}),Ta=r(`ZodEmail`,(e,t)=>{Rt.init(e,t),A.init(e,t)});function Ea(e){return nr(Ta,e)}let Da=r(`ZodGUID`,(e,t)=>{It.init(e,t),A.init(e,t)}),Oa=r(`ZodUUID`,(e,t)=>{Lt.init(e,t),A.init(e,t)}),ka=r(`ZodURL`,(e,t)=>{zt.init(e,t),A.init(e,t)});function Aa(e){return cr(ka,e)}let ja=r(`ZodEmoji`,(e,t)=>{Bt.init(e,t),A.init(e,t)}),Ma=r(`ZodNanoID`,(e,t)=>{Vt.init(e,t),A.init(e,t)}),Na=r(`ZodCUID`,(e,t)=>{Ht.init(e,t),A.init(e,t)}),Pa=r(`ZodCUID2`,(e,t)=>{Ut.init(e,t),A.init(e,t)}),Fa=r(`ZodULID`,(e,t)=>{Wt.init(e,t),A.init(e,t)}),Ia=r(`ZodXID`,(e,t)=>{Gt.init(e,t),A.init(e,t)}),La=r(`ZodKSUID`,(e,t)=>{Kt.init(e,t),A.init(e,t)}),Ra=r(`ZodIPv4`,(e,t)=>{Zt.init(e,t),A.init(e,t)}),za=r(`ZodIPv6`,(e,t)=>{Qt.init(e,t),A.init(e,t)}),Ba=r(`ZodCIDRv4`,(e,t)=>{$t.init(e,t),A.init(e,t)}),Va=r(`ZodCIDRv6`,(e,t)=>{en.init(e,t),A.init(e,t)}),Ha=r(`ZodBase64`,(e,t)=>{nn.init(e,t),A.init(e,t)}),Ua=r(`ZodBase64URL`,(e,t)=>{an.init(e,t),A.init(e,t)}),Wa=r(`ZodE164`,(e,t)=>{on.init(e,t),A.init(e,t)}),Ga=r(`ZodJWT`,(e,t)=>{cn.init(e,t),A.init(e,t)}),Ka=r(`ZodNumber`,(e,t)=>{ln.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mi(e,t,n,r),Sa(e,`ZodNumber`,{gt(e,t){return this.check(Rr(e,t))},gte(e,t){return this.check(zr(e,t))},min(e,t){return this.check(zr(e,t))},lt(e,t){return this.check(Ir(e,t))},lte(e,t){return this.check(Lr(e,t))},max(e,t){return this.check(Lr(e,t))},int(e){return this.check(Ja(e))},safe(e){return this.check(Ja(e))},positive(e){return this.check(Rr(0,e))},nonnegative(e){return this.check(zr(0,e))},negative(e){return this.check(Ir(0,e))},nonpositive(e){return this.check(Lr(0,e))},multipleOf(e,t){return this.check(Br(e,t))},step(e,t){return this.check(Br(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function j(e){return Or(Ka,e)}let qa=r(`ZodNumberFormat`,(e,t)=>{un.init(e,t),Ka.init(e,t)});function Ja(e){return Ar(qa,e)}let Ya=r(`ZodBoolean`,(e,t)=>{dn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hi(e,t,n,r)});function M(e){return jr(Ya,e)}let Xa=r(`ZodNull`,(e,t)=>{fn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vi(e,t,n,r)});function Za(e){return Mr(Xa,e)}let Qa=r(`ZodAny`,(e,t)=>{pn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function $a(){return Nr(Qa)}let eo=r(`ZodUnknown`,(e,t)=>{mn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function N(){return Pr(eo)}let to=r(`ZodNever`,(e,t)=>{hn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xi(e,t,n,r)});function no(e){return Fr(to,e)}let ro=r(`ZodArray`,(e,t)=>{_n.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ii(e,t,n,r),e.element=t.element,Sa(e,`ZodArray`,{min(e,t){return this.check(Hr(e,t))},nonempty(e){return this.check(Hr(1,e))},max(e,t){return this.check(Vr(e,t))},length(e,t){return this.check(Ur(e,t))},unwrap(){return this.element}})});function P(e,t){return ni(ro,e,t)}let io=r(`ZodObject`,(e,t)=>{Sn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Li(e,t,n,r),h(e,`shape`,()=>t.shape),Sa(e,`ZodObject`,{keyof(){return z(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:N()})},loose(){return this.clone({...this._zod.def,catchall:N()})},strict(){return this.clone({...this._zod.def,catchall:no()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return me(this,e)},safeExtend(e){return he(this,e)},merge(e){return ge(this,e)},pick(e){return fe(this,e)},omit(e){return pe(this,e)},partial(...e){return _e(go,this,e[0])},required(...e){return ve(To,this,e[0])}})});function F(e,t){return new io({type:`object`,shape:e??{},...v(t)})}function I(e,t){return new io({type:`object`,shape:e,catchall:N(),...v(t)})}let ao=r(`ZodUnion`,(e,t)=>{wn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ri(e,t,n,r),e.options=t.options});function L(e,t){return new ao({type:`union`,options:e,...v(t)})}let oo=r(`ZodDiscriminatedUnion`,(e,t)=>{ao.init(e,t),Tn.init(e,t)});function so(e,t,n){return new oo({type:`union`,options:t,discriminator:e,...v(n)})}let co=r(`ZodIntersection`,(e,t)=>{En.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zi(e,t,n,r)});function lo(e,t){return new co({type:`intersection`,left:e,right:t})}let uo=r(`ZodRecord`,(e,t)=>{kn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vi(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function R(e,t,n){return!t||!t._zod?new uo({type:`record`,keyType:k(),valueType:e,...v(t)}):new uo({type:`record`,keyType:e,valueType:t,...v(n)})}let fo=r(`ZodEnum`,(e,t)=>{An.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ti(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new fo({...t,checks:[],...v(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new fo({...t,checks:[],...v(r),entries:i})}});function z(e,t){return new fo({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...v(t)})}let po=r(`ZodLiteral`,(e,t)=>{jn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ei(e,t,n,r),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 B(e,t){return new po({type:`literal`,values:Array.isArray(e)?e:[e],...v(t)})}let mo=r(`ZodTransform`,(e,t)=>{Mn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ni(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new a(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Ce(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Ce(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function ho(e){return new mo({type:`transform`,transform:e})}let go=r(`ZodOptional`,(e,t)=>{Pn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function V(e){return new go({type:`optional`,innerType:e})}let _o=r(`ZodExactOptional`,(e,t)=>{Fn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function vo(e){return new _o({type:`optional`,innerType:e})}let yo=r(`ZodNullable`,(e,t)=>{In.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function bo(e){return new yo({type:`nullable`,innerType:e})}let xo=r(`ZodDefault`,(e,t)=>{Ln.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function So(e,t){return new xo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():oe(t)}})}let Co=r(`ZodPrefault`,(e,t)=>{zn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wo(e,t){return new Co({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():oe(t)}})}let To=r(`ZodNonOptional`,(e,t)=>{Bn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ui(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Eo(e,t){return new To({type:`nonoptional`,innerType:e,...v(t)})}let Do=r(`ZodCatch`,(e,t)=>{Hn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ki(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Oo(e,t){return new Do({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}let ko=r(`ZodPipe`,(e,t)=>{Un.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qi(e,t,n,r),e.in=t.in,e.out=t.out});function Ao(e,t){return new ko({type:`pipe`,in:e,out:t})}let jo=r(`ZodPreprocess`,(e,t)=>{ko.init(e,t),Gn.init(e,t)}),Mo=r(`ZodReadonly`,(e,t)=>{Kn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ji(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function No(e){return new Mo({type:`readonly`,innerType:e})}let Po=r(`ZodLazy`,(e,t)=>{Jn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zi(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Fo(e){return new Po({type:`lazy`,getter:e})}let Io=r(`ZodCustom`,(e,t)=>{Yn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ji(e,t,n,r)});function Lo(e,t={}){return ri(Io,e,t)}function Ro(e,t){return ii(e,t)}function zo(e,t){return new jo({type:`pipe`,in:ho(e),out:t})}let Bo={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 Vo;Vo||={};function Ho(e){return kr(Ka,e)}let Uo=[`2025-11-25`,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Wo=`io.modelcontextprotocol/protocolVersion`,Go=`io.modelcontextprotocol/clientInfo`,Ko=`io.modelcontextprotocol/serverInfo`,qo=`io.modelcontextprotocol/clientCapabilities`,Jo=`io.modelcontextprotocol/logLevel`,Yo=Fo(()=>L([k(),j(),M(),Za(),R(k(),Yo),P(Yo)])),H=R(k(),Yo),Xo=P(Yo),Zo=L([k(),j().int()]),Qo=k(),$o=F({ttl:j().optional()}),es=F({taskId:k()}),ts=I({progressToken:Zo.optional(),"io.modelcontextprotocol/related-task":es.optional()}),U=F({_meta:ts.optional()}),ns=U.extend({task:$o.optional()}),W=F({method:k(),params:U.loose().optional()}),rs=F({_meta:ts.optional()}),is=F({method:k(),params:rs.loose().optional()}),as=I({get[Ko](){return ys.optional().catch(void 0)}}),G=I({_meta:as.optional()}),os=L([k(),j().int()]),ss=F({jsonrpc:B(`2.0`),id:os,...W.shape}).strict(),cs=F({jsonrpc:B(`2.0`),...is.shape}).strict(),ls=F({jsonrpc:B(`2.0`),id:os,result:G}).strict(),us=F({jsonrpc:B(`2.0`),id:os.optional(),error:F({code:j().int(),message:k(),data:N().optional()})}).strict(),ds=L([ss,cs,ls,us]),fs=L([ls,us]),ps=G.strict(),ms=rs.extend({requestId:os.optional(),reason:k().optional()}),hs=is.extend({method:B(`notifications/cancelled`),params:ms}),gs=F({src:k(),mimeType:k().optional(),sizes:P(k()).optional(),theme:z([`light`,`dark`]).optional()}),_s=F({icons:P(gs).optional()}),vs=F({name:k(),title:k().optional()}),ys=vs.extend({...vs.shape,..._s.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),bs=zo(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,lo(F({form:lo(F({applyDefaults:M().optional()}),H).optional(),url:H.optional()}),H.optional())),xs=I({list:H.optional(),cancel:H.optional(),requests:I({sampling:I({createMessage:H.optional()}).optional(),elicitation:I({create:H.optional()}).optional()}).optional()}),Ss=I({list:H.optional(),cancel:H.optional(),requests:I({tools:I({call:H.optional()}).optional()}).optional()}),Cs=F({experimental:R(k(),H).optional(),sampling:F({context:H.optional(),tools:H.optional()}).optional(),elicitation:bs.optional(),roots:F({listChanged:M().optional()}).optional(),tasks:xs.optional(),extensions:R(k(),H).optional()}),ws=U.extend({protocolVersion:k(),capabilities:Cs,clientInfo:ys}),Ts=W.extend({method:B(`initialize`),params:ws}),Es=F({experimental:R(k(),H).optional(),logging:H.optional(),completions:H.optional(),prompts:F({listChanged:M().optional()}).optional(),resources:F({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:F({listChanged:M().optional()}).optional(),tasks:Ss.optional(),extensions:R(k(),H).optional()}),Ds=G.extend({protocolVersion:k(),capabilities:Es,serverInfo:ys,instructions:k().optional()}),Os=is.extend({method:B(`notifications/initialized`),params:rs.optional()}),ks=W.extend({method:B(`server/discover`),params:U.optional()}),As=G.extend({supportedVersions:P(k()),capabilities:Es,instructions:k().optional()}),js=W.extend({method:B(`ping`),params:U.optional()}),Ms=F({progress:j(),total:V(j()),message:V(k())}),Ns=F({...rs.shape,...Ms.shape,progressToken:Zo}),Ps=is.extend({method:B(`notifications/progress`),params:Ns}),Fs=U.extend({cursor:Qo.optional()}),Is=W.extend({params:Fs.optional()}),Ls=G.extend({nextCursor:Qo.optional()}),Rs=F({uri:k(),mimeType:V(k()),_meta:R(k(),N()).optional()}),zs=Rs.extend({text:k()}),Bs=k().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Vs=Rs.extend({blob:Bs}),Hs=z([`user`,`assistant`]),Us=F({audience:P(Hs).optional(),priority:j().min(0).max(1).optional(),lastModified:ta({offset:!0}).optional()}),Ws=F({...vs.shape,..._s.shape,uri:k(),description:V(k()),mimeType:V(k()),size:V(j()),annotations:Us.optional(),_meta:V(I({}))}),Gs=F({...vs.shape,..._s.shape,uriTemplate:k(),description:V(k()),mimeType:V(k()),annotations:Us.optional(),_meta:V(I({}))}),Ks=Is.extend({method:B(`resources/list`)}),qs=Ls.extend({resources:P(Ws)}),Js=Is.extend({method:B(`resources/templates/list`)}),Ys=Ls.extend({resourceTemplates:P(Gs)}),Xs=U.extend({uri:k()}),Zs=Xs,Qs=W.extend({method:B(`resources/read`),params:Zs}),$s=G.extend({contents:P(L([zs,Vs]))}),ec=is.extend({method:B(`notifications/resources/list_changed`),params:rs.optional()}),tc=Xs,nc=W.extend({method:B(`resources/subscribe`),params:tc}),rc=Xs,ic=W.extend({method:B(`resources/unsubscribe`),params:rc}),ac=F({toolsListChanged:M().optional(),promptsListChanged:M().optional(),resourcesListChanged:M().optional(),resourceSubscriptions:P(k()).optional()}),oc=U.extend({notifications:ac}),sc=W.extend({method:B(`subscriptions/listen`),params:oc}),cc=rs.extend({notifications:ac}),lc=is.extend({method:B(`notifications/subscriptions/acknowledged`),params:cc}),uc=as.extend({"io.modelcontextprotocol/subscriptionId":os}),dc=G.extend({_meta:uc}),fc=rs.extend({uri:k()}),pc=is.extend({method:B(`notifications/resources/updated`),params:fc}),mc=F({name:k(),description:V(k()),required:V(M())}),hc=F({...vs.shape,..._s.shape,description:V(k()),arguments:V(P(mc)),_meta:V(I({}))}),gc=Is.extend({method:B(`prompts/list`)}),_c=Ls.extend({prompts:P(hc)}),vc=U.extend({name:k(),arguments:R(k(),k()).optional()}),yc=W.extend({method:B(`prompts/get`),params:vc}),bc=F({type:B(`text`),text:k(),annotations:Us.optional(),_meta:R(k(),N()).optional()}),xc=F({type:B(`image`),data:Bs,mimeType:k(),annotations:Us.optional(),_meta:R(k(),N()).optional()}),Sc=F({type:B(`audio`),data:Bs,mimeType:k(),annotations:Us.optional(),_meta:R(k(),N()).optional()}),Cc=F({type:B(`tool_use`),name:k(),id:k(),input:R(k(),N()),_meta:R(k(),N()).optional()}),wc=F({type:B(`resource`),resource:L([zs,Vs]),annotations:Us.optional(),_meta:R(k(),N()).optional()}),Tc=Ws.extend({type:B(`resource_link`)}),Ec=L([bc,xc,Sc,Tc,wc]),Dc=F({role:Hs,content:Ec}),Oc=G.extend({description:k().optional(),messages:P(Dc)}),kc=is.extend({method:B(`notifications/prompts/list_changed`),params:rs.optional()}),Ac=F({title:k().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),jc=F({taskSupport:z([`required`,`optional`,`forbidden`]).optional()}),Mc=F({...vs.shape,..._s.shape,description:k().optional(),inputSchema:F({type:B(`object`),properties:R(k(),Yo).optional(),required:P(k()).optional()}).catchall(N()),outputSchema:I({$schema:k().optional()}).optional(),annotations:Ac.optional(),execution:jc.optional(),_meta:R(k(),N()).optional()}),Nc=Is.extend({method:B(`tools/list`)}),Pc=Ls.extend({tools:P(Mc)}),Fc=G.extend({content:P(Ec).default([]),structuredContent:N().optional(),isError:M().optional()}),Ic=Fc.or(G.extend({toolResult:N()})),Lc=ns.extend({name:k(),arguments:R(k(),N()).optional()}),Rc=W.extend({method:B(`tools/call`),params:Lc}),zc=is.extend({method:B(`notifications/tools/list_changed`),params:rs.optional()}),Bc=F({autoRefresh:M().default(!0),debounceMs:j().int().nonnegative().default(300)}),Vc=z([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Hc=U.extend({level:Vc}),Uc=W.extend({method:B(`logging/setLevel`),params:Hc}),Wc=rs.extend({level:Vc,logger:k().optional(),data:N()}),Gc=is.extend({method:B(`notifications/message`),params:Wc}),Kc=F({name:k().optional()}),qc=F({hints:P(Kc).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),Jc=F({mode:z([`auto`,`required`,`none`]).optional()}),Yc=F({type:B(`tool_result`),toolUseId:k().describe(`The unique identifier for the corresponding tool call.`),content:P(Ec),structuredContent:N().optional(),isError:M().optional(),_meta:R(k(),N()).optional()}),Xc=so(`type`,[bc,xc,Sc]),Zc=so(`type`,[bc,xc,Sc,Cc,Yc]),Qc=F({role:Hs,content:L([Zc,P(Zc)]),_meta:R(k(),N()).optional()}),$c=ns.extend({messages:P(Qc),modelPreferences:qc.optional(),systemPrompt:k().optional(),includeContext:z([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:P(k()).optional(),metadata:H.optional(),tools:P(Mc).optional(),toolChoice:Jc.optional()}),el=W.extend({method:B(`sampling/createMessage`),params:$c}),tl=G.extend({model:k(),stopReason:V(z([`endTurn`,`stopSequence`,`maxTokens`]).or(k())),role:Hs,content:Xc}),nl=G.extend({model:k(),stopReason:V(z([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(k())),role:Hs,content:L([Zc,P(Zc)])}),rl=F({type:B(`boolean`),title:k().optional(),description:k().optional(),default:M().optional()}),il=F({type:B(`string`),title:k().optional(),description:k().optional(),minLength:j().optional(),maxLength:j().optional(),format:z([`email`,`uri`,`date`,`date-time`]).optional(),default:k().optional()}),al=F({type:z([`number`,`integer`]),title:k().optional(),description:k().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),ol=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),default:k().optional()}),sl=F({type:B(`string`),title:k().optional(),description:k().optional(),oneOf:P(F({const:k(),title:k()})),default:k().optional()}),cl=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),enumNames:P(k()).optional(),default:k().optional()}),ll=L([ol,sl]),ul=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({type:B(`string`),enum:P(k())}),default:P(k()).optional()}),dl=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({anyOf:P(F({const:k(),title:k()}))}),default:P(k()).optional()}),fl=L([ul,dl]),pl=L([cl,ll,fl]),ml=L([pl,rl,il,al]),hl=ns.extend({mode:B(`form`).optional(),message:k(),requestedSchema:F({type:B(`object`),properties:R(k(),ml),required:P(k()).optional()}).catchall(N())}),gl=ns.extend({mode:B(`url`),message:k(),elicitationId:k(),url:k().url()}),_l=L([hl,gl]),vl=W.extend({method:B(`elicitation/create`),params:_l}),yl=rs.extend({elicitationId:k()}),bl=is.extend({method:B(`notifications/elicitation/complete`),params:yl}),xl=G.extend({action:z([`accept`,`decline`,`cancel`]),content:zo(e=>e===null?void 0:e,R(k(),L([k(),j(),M(),P(k())])).optional())}),Sl=F({type:B(`ref/resource`),uri:k()}),Cl=F({type:B(`ref/prompt`),name:k()}),wl=U.extend({ref:L([Cl,Sl]),argument:F({name:k(),value:k()}),context:F({arguments:R(k(),k()).optional()}).optional()}),Tl=W.extend({method:B(`completion/complete`),params:wl}),El=G.extend({completion:I({values:P(k()).max(100),total:V(j().int()),hasMore:V(M())})}),Dl=F({uri:k().startsWith(`file://`),name:k().optional(),_meta:R(k(),N()).optional()}),Ol=W.extend({method:B(`roots/list`),params:U.optional()}),kl=G.extend({roots:P(Dl)}),Al=is.extend({method:B(`notifications/roots/list_changed`),params:rs.optional()}),jl=I({ttl:j().optional(),pollInterval:j().optional()}),Ml=z([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Nl=F({taskId:k(),status:Ml,ttl:L([j(),Za()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:V(j()),statusMessage:V(k())}),Pl=G.extend({task:Nl}),Fl=rs.merge(Nl),Il=is.extend({method:B(`notifications/tasks/status`),params:Fl}),Ll=W.extend({method:B(`tasks/get`),params:U.extend({taskId:k()})}),Rl=G.merge(Nl),zl=W.extend({method:B(`tasks/result`),params:U.extend({taskId:k()})}),Bl=G.loose(),Vl=Is.extend({method:B(`tasks/list`)}),Hl=Ls.extend({tasks:P(Nl)}),Ul=W.extend({method:B(`tasks/cancel`),params:U.extend({taskId:k()})}),Wl=G.merge(Nl),Gl=L([js,Ts,ks,Tl,Uc,yc,gc,Ks,Js,Qs,nc,ic,sc,Rc,Nc]),Kl=L([hs,Ps,Os,Al]),ql=L([ps,tl,nl,xl,kl]),Jl=L([js,el,vl,Ol]),Yl=L([hs,Ps,Gc,pc,ec,zc,kc,lc,bl]),Xl=L([ps,Ds,As,El,Oc,_c,qs,Ys,$s,Fc,Pc,dc]),K=Aa().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Bo.custom,message:`URL must be parseable`,fatal:!0}),n}).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`}),Zl=I({resource:k().url(),authorization_servers:P(K).optional(),jwks_uri:k().url().optional(),scopes_supported:P(k()).optional(),bearer_methods_supported:P(k()).optional(),resource_signing_alg_values_supported:P(k()).optional(),resource_name:k().optional(),resource_documentation:k().optional(),resource_policy_uri:k().url().optional(),resource_tos_uri:k().url().optional(),tls_client_certificate_bound_access_tokens:M().optional(),authorization_details_types_supported:P(k()).optional(),dpop_signing_alg_values_supported:P(k()).optional(),dpop_bound_access_tokens_required:M().optional()}),Ql=I({issuer:k(),authorization_endpoint:K,token_endpoint:K,registration_endpoint:K.optional(),scopes_supported:P(k()).optional(),response_types_supported:P(k()),response_modes_supported:P(k()).optional(),grant_types_supported:P(k()).optional(),token_endpoint_auth_methods_supported:P(k()).optional(),token_endpoint_auth_signing_alg_values_supported:P(k()).optional(),service_documentation:K.optional(),revocation_endpoint:K.optional(),revocation_endpoint_auth_methods_supported:P(k()).optional(),revocation_endpoint_auth_signing_alg_values_supported:P(k()).optional(),introspection_endpoint:k().optional(),introspection_endpoint_auth_methods_supported:P(k()).optional(),introspection_endpoint_auth_signing_alg_values_supported:P(k()).optional(),code_challenge_methods_supported:P(k()).optional(),client_id_metadata_document_supported:M().optional(),authorization_response_iss_parameter_supported:M().optional().catch(void 0)}),$l=I({issuer:k(),authorization_endpoint:K,token_endpoint:K,userinfo_endpoint:K.optional(),jwks_uri:K,registration_endpoint:K.optional(),scopes_supported:P(k()).optional(),response_types_supported:P(k()),response_modes_supported:P(k()).optional(),grant_types_supported:P(k()).optional(),acr_values_supported:P(k()).optional(),subject_types_supported:P(k()),id_token_signing_alg_values_supported:P(k()),id_token_encryption_alg_values_supported:P(k()).optional(),id_token_encryption_enc_values_supported:P(k()).optional(),userinfo_signing_alg_values_supported:P(k()).optional(),userinfo_encryption_alg_values_supported:P(k()).optional(),userinfo_encryption_enc_values_supported:P(k()).optional(),request_object_signing_alg_values_supported:P(k()).optional(),request_object_encryption_alg_values_supported:P(k()).optional(),request_object_encryption_enc_values_supported:P(k()).optional(),token_endpoint_auth_methods_supported:P(k()).optional(),token_endpoint_auth_signing_alg_values_supported:P(k()).optional(),display_values_supported:P(k()).optional(),claim_types_supported:P(k()).optional(),claims_supported:P(k()).optional(),service_documentation:k().optional(),claims_locales_supported:P(k()).optional(),ui_locales_supported:P(k()).optional(),claims_parameter_supported:M().optional(),request_parameter_supported:M().optional(),request_uri_parameter_supported:M().optional(),require_request_uri_registration:M().optional(),op_policy_uri:K.optional(),op_tos_uri:K.optional(),client_id_metadata_document_supported:M().optional(),authorization_response_iss_parameter_supported:M().optional().catch(void 0)}),eu=F({...$l.shape,...Ql.pick({code_challenge_methods_supported:!0}).shape}),tu=F({access_token:k(),id_token:k().optional(),token_type:k(),expires_in:Ho().optional(),scope:k().optional(),refresh_token:k().optional()}).strip(),nu=F({issued_token_type:B(`urn:ietf:params:oauth:token-type:id-jag`),access_token:k(),token_type:k().optional(),expires_in:j().optional(),scope:k().optional()}).strip(),ru=F({error:k(),error_description:k().optional(),error_uri:k().optional()}),iu=K.optional().or(B(``).transform(()=>void 0)),au=F({redirect_uris:P(K),token_endpoint_auth_method:k().optional(),grant_types:P(k()).optional(),response_types:P(k()).optional(),application_type:k().optional(),client_name:k().optional(),client_uri:K.optional(),logo_uri:iu,scope:k().optional(),contacts:P(k()).optional(),tos_uri:iu,policy_uri:k().optional(),jwks_uri:K.optional(),jwks:$a().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional()}).strip(),ou=F({client_id:k(),client_secret:k().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),su=au.merge(ou),cu=F({error:k(),error_description:k().optional()}).strip(),lu=F({token:k(),token_type_hint:k().optional()}).strip();function uu(e,t,n){return typeof e==`object`&&!!e&&`channel`in e&&e.channel===t&&`type`in e&&e.type===`mcp`&&`direction`in e&&e.direction===n&&`payload`in e}function du(e,t,n,r,i){e.postMessage({channel:n,type:`mcp`,direction:r,payload:i},t)}var fu=class{_started=!1;_closed=!1;_allowedOrigins;_channelId;_messageHandler;_clientOrigin;onclientorigin;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins?.length)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=new Set(e.allowedOrigins),this._channelId=e.channelId??`mcp-iframe`}get clientOrigin(){return this._clientOrigin}async start(){if(this._closed)throw Error(`IframeChildTransport cannot be restarted after it closes`);if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(e.source!==window.parent||!this._allowedOrigins.has(`*`)&&!this._allowedOrigins.has(e.origin)||!uu(e.data,this._channelId,`client-to-server`))return;this._clientOrigin!==e.origin&&(this._clientOrigin=e.origin,this.onclientorigin?.(e.origin));let{payload:t}=e.data;if(t===`mcp-check-ready`){this._broadcastServerReady();return}try{let e=ds.parse(t);this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,this._broadcastServerReady()}async send(e,t){if(this._closed)throw Error(`Transport is closed`);if(!this._started)throw Error(`Transport not started`);if(!this._clientOrigin){console.debug(`[IframeChildTransport] No client connected, message not sent`);return}if(window.parent===window){console.debug(`[IframeChildTransport] Not running in an iframe, message not sent`);return}du(window.parent,this._clientOrigin,this._channelId,`server-to-client`,e)}async close(){this._closed||(this._closed=!0,this._started=!1,this._messageHandler&&=(window.removeEventListener(`message`,this._messageHandler),void 0),this._clientOrigin&&window.parent!==window&&du(window.parent,this._clientOrigin,this._channelId,`server-to-client`,`mcp-server-stopped`),this.onclose?.())}_broadcastServerReady(){window.parent!==window&&du(window.parent,`*`,this._channelId,`server-to-client`,`mcp-server-ready`)}},pu=class{_started=!1;_closed=!1;_allowedOrigins;_channelId;_messageHandler;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins?.length)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=new Set(e.allowedOrigins),this._channelId=e.channelId??`mcp-default`}async start(){if(this._closed)throw Error(`TabServerTransport cannot be restarted after it closes`);if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(e.source!==window||!this._allowedOrigins.has(`*`)&&!this._allowedOrigins.has(e.origin)||!uu(e.data,this._channelId,`client-to-server`))return;let{payload:t}=e.data;if(t===`mcp-check-ready`){du(window,`*`,this._channelId,`server-to-client`,`mcp-server-ready`);return}try{let e=ds.parse(t);this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,du(window,`*`,this._channelId,`server-to-client`,`mcp-server-ready`)}async send(e,t){if(this._closed)throw Error(`Transport is closed`);if(!this._started)throw Error(`Transport not started`);du(window,`*`,this._channelId,`server-to-client`,e)}async close(){this._closed||(this._closed=!0,this._messageHandler&&=(window.removeEventListener(`message`,this._messageHandler),void 0),this._started&&du(window,`*`,this._channelId,`server-to-client`,`mcp-server-stopped`),this._started=!1,this.onclose?.())}};let mu=[`consequentialHint`,`debugging`,`readOnlyHint`,`untrustedContentHint`],hu=`webmcp-polyfill`,gu=globalThis.DOMException;var _u=class{#e;#t;#n;#r=new Set;#i=new Set;#a=Promise.withResolvers();#o=new Map;#s=new Set;#c;#l=!1;constructor(e,t){this.#t=e,this.#e=e.document,this.#n=t,this.#t.addEventListener(`message`,e=>this.#d(e),!0),this.#t.addEventListener(`pagehide`,()=>{this.#l=!0;for(let e of this.#s)e.end()}),this.#t.addEventListener(`pageshow`,e=>{e.persisted&&(this.#l=!1,this.#x())});for(let e of this.#x())this.#i.add(e);this.#i.size===0?this.#a.resolve():setTimeout(()=>{this.#i.clear(),this.#a.resolve()},500)}async allowed(){return this.#l?!1:this.#h(this.#e)}async getTools(e){await this.#a.promise;let t=this.#t.origin,n=[t,...e];return(await Promise.all(this.#b().map(async e=>{if(e===this.#t)return this.#n.getTools(t).map(e=>wu(e,this.#t,t));try{let t=await this.#u(e,n,{kind:`getTools`});if(!Array.isArray(t.value))throw TypeError(`Expected a tool list from the frame`);return t.value.map(n=>wu(Tu(n),e,t.origin))}catch(e){return e instanceof gu&&e.name===`UnknownError`||console.warn(`WebMCP: could not read tools from a frame.`,e),[]}}))).flat()}async execute(e,t,n,r,i){let a=await this.#u(e,[t],{kind:`execute`,name:n,input:r},i);if(typeof a.value!=`string`)throw q();return a.value}async notify(e){await this.#a.promise;let t=[this.#t.origin,...e];for(let e of this.#b()){if(e===this.#t){await this.#n.changed();continue}try{await this.#u(e,t,{kind:`changed`})}catch{}}}#u(e,t,n,r){return new Promise((i,a)=>{if(r?.throwIfAborted(),this.#l||!this.#v(e)){a(q());return}let o=crypto.randomUUID(),{port1:s,port2:c}=new MessageChannel,l,u=()=>{clearTimeout(h),g(),r?.removeEventListener(`abort`,f),this.#o.delete(o),s.close()},d=(e=q())=>{s.postMessage({kind:`cancel`}),u(),a(e)},f=()=>d(r?.reason),p=()=>{l===void 0&&this.#C(e),d()},m=r=>{if(r.source===e){if(this.#o.delete(o),t&&!t.includes(r.origin)){d();return}l=r.origin,clearTimeout(h),n.kind!==`execute`&&n.kind!==`changed`&&(h=setTimeout(p,500)),s.postMessage(n)}},h=setTimeout(p,500),g=this.#w(e,d);s.onmessage=e=>{let t=Du(e.data);if(t?.kind===`error`){d();return}t?.kind!==`result`||l===void 0||(u(),i({value:t.value,origin:l}))},s.onmessageerror=()=>d(),r?.addEventListener(`abort`,f,{once:!0}),this.#o.set(o,m);try{e.postMessage(`${hu}:connect:${o}`,`*`,[c])}catch{c.close(),d()}})}#d(e){let t=Eu(e.data);if(!t)return;e.stopImmediatePropagation();let n=e.source;if(!e.isTrusted||!n||!Ou(n)||!this.#v(n)||e.origin===`null`||this.#l)return;if(t.kind===`announce`){let t=!this.#r.has(n);if(this.#S(n),n.postMessage(`${hu}:present`,e.origin),!t||this.#t!==this.#t.top)return;for(let e of this.#r)e!==n&&e.postMessage(`${hu}:refresh`,`*`);return}if(t.kind===`present`){this.#S(n);return}if(t.kind===`refresh`){n===this.#t.top&&this.#x();return}if(t.kind===`ready`){this.#o.get(t.id)?.(e);return}let[r]=e.ports;t.kind!==`connect`||!t.id||!r||e.ports.length!==1||(this.#S(n),this.#f(n,e.origin,t.id,r))}#f(e,t,n,r){let i=new AbortController,a=!1,o=()=>{clearTimeout(l),u(),r.close()},s=()=>{i.abort(),o()},c=()=>{r.postMessage({kind:`error`}),s()},l=setTimeout(c,500),u=this.#w(e,c);r.onmessageerror=c,r.onmessage=async n=>{let u=Du(n.data);if(u?.kind===`cancel`){s();return}if(!a){a=!0,clearTimeout(l);try{let n=await this.#p(e,t,u,i.signal);r.postMessage({kind:`result`,value:n}),o()}catch{c()}}},e.postMessage(`${hu}:ready:${n}`,t)}async#p(e,t,n,r){if(!n||!this.#v(e))throw q();if(n.kind===`permission`){let{childIndex:e,childOrigin:t}=n;if(typeof e!=`number`||!Number.isInteger(e)||e<0||typeof t!=`string`)throw q();return this.#m(e,t)}if(!await this.allowed()||!await this.#g(e,t)||!this.#v(e))throw q();if(r.throwIfAborted(),n.kind===`getTools`)return this.#n.getTools(t);if(n.kind===`execute`&&typeof n.name==`string`&&typeof n.input==`string`)return this.#n.execute(t,n.name,n.input,r);if(n.kind===`changed`){await this.#n.changed();return}throw q()}async#m(e,t){let n=this.#t[e];return n!==void 0&&await this.allowed()&&vu(this.#e,n,t)}async#h(e){let t=Su(e);if(!t)return!1;let n=Cu(e);if(n!==void 0)return n;if(t===t.parent)return!0;let r=t.location.ancestorOrigins?.[0],i=yu(t.parent,r===void 0||r===t.origin);return i?vu(i,t,t.origin)&&await this.#h(i):this.#_(t,t.origin)}async#g(e,t){let n=yu(e,t===this.#t.origin);return n?this.#h(n):this.#_(e,t)}async#_(e,t){let n=e.parent;if(n===e)return!0;let r=-1;for(let t=0;t<n.length;t++)if(n[t]===e){r=t;break}if(r<0)return!1;if(n===this.#t)return await this.allowed()&&vu(this.#e,e,t);if(await this.#a.promise,!this.#r.has(n))return!1;try{let e=await this.#u(n,void 0,{kind:`permission`,childIndex:r,childOrigin:t});return e.value===!0&&await this.#g(n,e.origin)}catch{return!1}}#v(e){try{return!e.closed&&e!==this.#t&&e.top===this.#t.top}catch{return!1}}#y(){if(this.#t.closed)return[];for(let e of this.#r)this.#v(e)||this.#r.delete(e);let e=[this.#t,...this.#r];for(let t=this.#t.parent;t!==t.parent;t=t.parent)e.push(t);let t=new Set,n=[this.#t.top];for(;n.length;){let r=n.pop();if(t.has(r))continue;t.add(r);let i=[];for(let e=0;e<r.length;e++){let t=r[e];t&&i.push(t)}for(let t of e)t!==r&&t.parent===r&&!i.includes(t)&&i.push(t);n.push(...i.reverse())}return Array.from(t).filter(e=>e===this.#t||this.#v(e))}#b(){return this.#y().filter(e=>e===this.#t||this.#r.has(e))}#x(){let e=this.#y().filter(e=>e!==this.#t);for(let t of e)t.postMessage(`${hu}:announce`,`*`);return e}#S(e){this.#r.add(e),this.#i.delete(e),this.#i.size===0&&this.#a.resolve()}#C(e){this.#r.delete(e),this.#v(e)&&e.postMessage(`${hu}:announce`,`*`)}#w(e,t){let n={peer:e,end:t};return this.#s.add(n),this.#c===void 0&&(this.#c=this.#t.setInterval(()=>{for(let e of this.#s)this.#v(e.peer)||e.end()},100)),()=>{this.#s.delete(n),this.#s.size===0&&(this.#t.clearInterval(this.#c),this.#c=void 0)}}};function vu(e,t,n){let r=e.defaultView?.origin,i=bu(e,t,n===r);if(!i)return!1;let a=(i.getAttribute(`allow`)??``).split(`;`).map(e=>e.trim().split(/\s+/u)).find(([e])=>e===`tools`);if(!a)return n===r;let o=a.length===1?[`'src'`]:a.slice(1);if(o.includes(`'none'`))return!1;let s=i.hasAttribute(`srcdoc`)?null:i.getAttribute(`src`),c=s?URL.parse(s,e.baseURI):null,l=!s||c?.protocol===`about:`?r:c?.origin;return o.some(e=>e===`*`||e===`'self'`&&n===r||e===`'src'`&&n===l||e===n)}function yu(e,t){if(t)try{return e.document}catch{return}}function bu(e,t,n){if(n)try{let n=t.frameElement;if(n?.ownerDocument===e)return n}catch{}return xu(e,t)}function xu(e,t){let n=e.querySelectorAll(`iframe, frame`);for(let e of n)if(e.contentWindow===t)return e;for(let n of e.querySelectorAll(`*`)){if(!n.shadowRoot)continue;let e=xu(n.shadowRoot,t);if(e)return e}}function Su(e){let t=e.defaultView;return t&&!t.closed&&t.document===e?t:void 0}function Cu(e){let t=e,n=Du(t.permissionsPolicy??t.featurePolicy);if(typeof n?.features!=`function`||typeof n.allowsFeature!=`function`)return;let r=n.features();return Array.isArray(r)&&r.includes(`tools`)?!!n.allowsFeature(`tools`):void 0}function wu(e,t,n){let r=e.serializedSchema===void 0?void 0:JSON.parse(e.serializedSchema);return{...e.annotations!==void 0&&{annotations:{...e.annotations}},description:e.description,...r!==void 0&&{inputSchema:r},name:e.name,origin:n,title:e.title,window:t}}function Tu(e){let t=Du(e);if(!t||typeof t.name!=`string`||typeof t.title!=`string`||typeof t.description!=`string`||t.serializedSchema!==void 0&&typeof t.serializedSchema!=`string`)throw TypeError(`Invalid tool metadata from the frame`);let n={name:t.name,title:t.title,description:t.description,annotations:void 0,serializedSchema:t.serializedSchema};if(t.annotations===void 0)return n;let r=Du(t.annotations);if(!r)throw TypeError(`Invalid tool annotations from the frame`);let i={};for(let e of mu){let t=r[e];if(t!==void 0){if(typeof t!=`boolean`)throw TypeError(`Invalid ${e} annotation from the frame`);i[e]=t}}return n.annotations=i,n}function Eu(e){if(typeof e!=`string`)return;let[t,n=``,r=``,i]=e.split(`:`);return t===hu&&i===void 0?{kind:n,id:r}:void 0}function Du(e){if(!(typeof e!=`object`||!e||Array.isArray(e)))return e}function Ou(e){try{return`postMessage`in e&&`window`in e}catch{return!1}}function q(){return new gu(`Tool execution failed`,`UnknownError`)}let ku=new WeakSet,Au=new WeakMap,ju=new WeakMap;function Mu(e){return e.isTrusted&&(ku.has(e)||e.eventPhase!==Event.NONE&&e.target instanceof HTMLFormElement&&ju.has(e.target))}function Nu(e,t){if(!Mu(e))throw new DOMException(`respondWith() is only available during an agent-invoked submit event`,`InvalidStateError`);if(!e.defaultPrevented)throw new DOMException(`respondWith() requires preventDefault() during an agent-invoked submit event`,`InvalidStateError`);if(e.eventPhase===Event.NONE)throw new DOMException(`respondWith() is only available while the submit event is being dispatched`,`InvalidStateError`);ku.add(e);let n=Promise.resolve(t);Au.set(e,n),e.target instanceof HTMLFormElement&&ju.get(e.target)?.respond(e)}let Pu=new Set([`email`,`password`,`search`,`tel`,`text`,`url`]),Fu=new Set([...Pu,`date`,`datetime-local`,`month`,`number`,`time`,`week`]);function Iu(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement}function Lu(e){return Object.getOwnPropertyDescriptor(HTMLFormElement.prototype,`elements`)?.get?.call(e)}function Ru(e,t){return Element.prototype.getAttribute.call(e,t)}function zu(e,t){return Element.prototype.hasAttribute.call(e,t)}function Bu(e){return Object.getOwnPropertyDescriptor(Node.prototype,`isConnected`)?.get?.call(e)}function Vu(e){return Object.getOwnPropertyDescriptor(Element.prototype,`shadowRoot`)?.get?.call(e)}function Hu(e){return HTMLFormElement.prototype.checkValidity.call(e)}function Uu(e,t){HTMLFormElement.prototype.requestSubmit.call(e,t)}function Wu(e){return[...Lu(e)].filter(e=>Iu(e)&&!e.matches(`:disabled`)&&!(`readOnly`in e&&e.readOnly&&(e instanceof HTMLTextAreaElement||Fu.has(e.type))))}function Gu(e){let t=new Map;for(let n of Wu(e)){let e=n.name.trim(),r=t.get(e);r?r.push(n):t.set(e,[n])}return t}function Ku(e){return[...e.labels??[]].map(e=>{let t=e.cloneNode(!0);return t instanceof HTMLElement?(t.querySelectorAll(`button, input, meter, output, progress, select, textarea`).forEach(e=>e.remove()),t.textContent?.trim()??``):``}).filter(Boolean).join(`; `)}function qu(e,t){for(let n=t[0]?.parentElement;n&&n!==e;n=n.parentElement)if(n instanceof HTMLFieldSetElement&&t.every(e=>n.contains(e)))return n}function Ju(e,t){if(t.length===1){let e=t[0];return e&&(e.getAttribute(`toolparamdescription`)||Ku(e)||e.getAttribute(`aria-description`))||void 0}return qu(e,t)?.getAttribute(`toolparamdescription`)||void 0}function Yu(e,t,n,r){let i=Ju(t,n),a=i&&r?`${i} (${r})`:i||r;return a?{...e,description:a}:e}function Xu(e,t){let n=e.getAttribute(t);if(n===null||n.trim()===``)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Zu(e,t){let n=Number(e.getAttribute(`step`));return Number.isFinite(n)&&n>0?n:t}function Qu(e,t){let n=e/t;return Math.abs(n-Math.round(n))<2**-52*16}function $u(e,t){let n=t.getAttribute(`pattern`);if(n===null)return e;try{new RegExp(n,`v`)}catch{return e}return{...e,pattern:n}}function ed(e){let t={type:`number`},n=Xu(e,`min`),r=Xu(e,`max`);if(n!==void 0&&(t.minimum=n),r!==void 0&&(t.maximum=r),e.getAttribute(`step`)!==`any`){let r=Zu(e,1),i=Number(e.getAttribute(`value`));Qu(n??(Number.isFinite(i)?i:0),r)&&(t.multipleOf=r)}return t}function td(e,t){let n=Zu(e,60);return n<1?`${t}(:[0-5][0-9](\\.[0-9]{1,3})?)?$`:n<60?`${t}(:[0-5][0-9])?$`:`${t}$`}function nd(e){return{anyOf:e.map(e=>({type:`string`,const:e.value,title:e.textContent??``})),enum:e.map(e=>e.value)}}function rd(e){return{anyOf:e.map(e=>{let t=Ku(e),n={type:`string`,const:e.value};return t&&(n.title=t),n}),enum:e.map(e=>e.value)}}function id(e,t){return e instanceof HTMLInputElement&&e.type===t}function ad(e){if(Pu.has(e.type))return $u({type:`string`},e);switch(e.type){case`hidden`:return e.getAttribute(`toolparamdescription`)?{type:`string`}:void 0;case`number`:return $u(ed(e),e);case`range`:{let t=ed(e);return t.minimum??=0,t.maximum??=100,t}case`checkbox`:return{type:`boolean`};case`date`:return{type:`string`,format:`date`};case`month`:return{type:`string`,format:`^[0-9]{4}-(0[1-9]|1[0-2])$`};case`week`:return{type:`string`,format:`^[0-9]{4}-W(0[1-9]|[1-4][0-9]|5[0-3])$`};case`time`:return{type:`string`,format:td(e,`^([01][0-9]|2[0-3]):[0-5][0-9]`)};case`datetime-local`:return{type:`string`,format:td(e,`^[0-9]{4}-(0[1-9]|1[0-2])-[0-9]{2}T([01][0-9]|2[0-3]):[0-5][0-9]`)};case`color`:return{type:`string`,format:`^#[0-9a-zA-Z]{6}$`};default:return}}function od(e,t){let[n]=t;if(!n)return;let r;if(t.every(e=>id(e,`radio`)))r={type:`string`,...rd(t)};else if(t.length>1)t.every(e=>id(e,`checkbox`))&&(r={type:`array`,items:{type:`string`,...rd(t)},uniqueItems:!0});else if(n instanceof HTMLTextAreaElement)r={type:`string`};else if(n instanceof HTMLSelectElement){let e=nd([...n.options]);r=n.multiple?{type:`array`,items:{type:`string`,...e},uniqueItems:!0}:{type:`string`,...e}}else r=ad(n);let i=n.type===`date`?`Dates MUST be provided in 'YYYY-MM-DD' format.`:void 0;return r&&Yu(r,e,t,i)}function sd(e){let t={},n=[];for(let[r,i]of Gu(e)){if(!r)continue;let a=od(e,i);a&&(Object.defineProperty(t,r,{configurable:!0,enumerable:!0,value:a,writable:!0}),i.some(e=>e.required)&&n.push(r))}return{type:`object`,properties:t,required:n}}function cd(e){return{name:Ru(e,`toolname`)??``,title:Ru(e,`tooltitle`)??``,description:Ru(e,`tooldescription`)??``,inputSchema:sd(e),autosubmit:zu(e,`toolautosubmit`)}}function ld(e){if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return String(e)}function ud(e){if(typeof e==`boolean`)return e;if(typeof e==`number`&&Number.isInteger(e))return e!==0;if(typeof e==`string`){if(e===`1`||e.toLowerCase()===`true`)return!0;if(e===`0`||e.toLowerCase()===`false`)return!1}}function dd(e,t){if(!Array.isArray(e))return!1;let n=new Set(t);for(let t of e){let e=ld(t);if(e===void 0||!n.delete(e))return!1}return!0}function fd(e,t){if(t===``)return e.type!==`number`&&e.type!==`range`;let n=e.ownerDocument.createElement(`input`);return n.type=e.type,n.value=t,n.value!==``}function pd(e,t,n){let[r]=t;if(!r||!od(e,t))return!1;let i=ld(n);if(t.every(e=>id(e,`radio`)))return t.some(e=>e.value===i);if(t.length>1)return dd(n,new Set(t.map(e=>e.value)));if(r instanceof HTMLSelectElement){let e=new Set([...r.options].map(e=>e.value));return r.multiple?dd(n,e):i!==void 0&&e.has(i)}return r instanceof HTMLTextAreaElement?i!==void 0:r.type===`checkbox`?ud(n)!==void 0:i!==void 0&&fd(r,i)}function md(e){e.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0}))}function hd(e,t){if(e.value===t)return;let n=e instanceof HTMLInputElement?HTMLInputElement.prototype:HTMLTextAreaElement.prototype;Object.getOwnPropertyDescriptor(n,`value`)?.set?.call(e,t),md(e)}function gd(e,t){e.checked!==t&&(Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,`checked`)?.set?.call(e,t),md(e))}function _d(e,t){let[n]=e,r=ld(t),i=new Set(Array.isArray(t)?t.map(ld):[]);if(e.every(e=>id(e,`radio`))){let t=e.find(e=>e.value===r);t&&gd(t,!0)}else if(e.length>1)for(let t of e)t instanceof HTMLInputElement&&gd(t,i.has(t.value));else if(n instanceof HTMLSelectElement)if(n.multiple){let e=!1;for(let t of n.options){let n=i.has(t.value);t.selected!==n&&(t.selected=n,e=!0)}e&&md(n)}else r!==void 0&&n.value!==r&&(n.value=r,md(n));else if(n&&id(n,`checkbox`)){let e=ud(t);e!==void 0&&gd(n,e)}else n&&r!==void 0&&hd(n,r)}function vd(e,t){if(Array.isArray(t))throw q();let n=Gu(e),r=[];for(let[i,a]of Object.entries(t)){let t=n.get(i);if(!t||!pd(e,t,a))throw q();r.push({controls:t,value:a})}for(let{controls:e,value:t}of r)_d(e,t)}function yd(e){return[...Lu(e)].find(e=>!e.matches(`:disabled`)&&(e instanceof HTMLButtonElement&&e.type===`submit`||e instanceof HTMLInputElement&&[`image`,`submit`].includes(e.type)))}function bd(e,t){let n=new Event(e);return Object.defineProperty(n,"toolName",{enumerable:!0,value:t}),n}function xd(e,t,n,r,i){let{form:a}=t;return t.cancelPending?.(q()),new Promise((o,s)=>{let c=!1,l=()=>{EventTarget.prototype.removeEventListener.call(a,`invalid`,p,!0),i.removeEventListener(`abort`,m),ju.delete(a),t.cancelPending===d&&delete t.cancelPending},u=e=>{c||(c=!0,l(),e())},d=e=>u(()=>s(e)),f=e=>{t.cancelPending===d&&delete t.cancelPending,e.then(e=>u(()=>o(e??null)),e=>u(()=>s(e)))},p=e=>{e.isTrusted&&queueMicrotask(()=>{Hu(a)||d(q())})},m=()=>{u(()=>{e.dispatchEvent(bd(`toolcancel`,n.name)),s(i.reason)})};if(ju.set(a,{complete(e){setTimeout(()=>{let t=Au.get(e);t?f(t):e.defaultPrevented?d(q()):u(()=>o(null))})},direct(){u(()=>o(null))},respond(e){queueMicrotask(()=>{let t=Au.get(e);t&&f(t)})}}),t.cancelPending=d,EventTarget.prototype.addEventListener.call(a,`invalid`,p,!0),i.addEventListener(`abort`,m,{once:!0}),!n.autosubmit){r?.focus(),e.dispatchEvent(bd(`toolactivated`,n.name));return}try{Uu(a,r),e.dispatchEvent(bd(`toolactivated`,n.name))}catch(e){d(e)}})}function Sd(e){let t=SubmitEvent.prototype;if(`agentInvoked`in t&&`respondWith`in t)return;`agentInvoked`in t||Object.defineProperty(t,"agentInvoked",{configurable:!0,enumerable:!0,get(){return Mu(this)}}),`respondWith`in t||Object.defineProperty(t,"respondWith",{configurable:!0,enumerable:!0,writable:!0,value(e){Nu(this,e)}});let n=new Map,r=new Map,i=new Map,a=e=>{if(!(e instanceof SubmitEvent)||!e.isTrusted||!(e.target instanceof HTMLFormElement))return;let t=ju.get(e.target);t&&(ku.add(e),t.complete(e))},o=e=>{if(!e.isTrusted||!(e.target instanceof HTMLFormElement))return;let t=e.target;setTimeout(()=>{e.defaultPrevented||n.get(t)?.cancelPending?.(q())})};function s(e){i.get(e)?.disconnect(),i.delete(e),e.removeEventListener(`reset`,o,!0),e.removeEventListener(`submit`,a,!0)}function c(e){if(i.has(e))return;let t=new MutationObserver(l);i.set(e,t),t.observe(e,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),e.addEventListener(`reset`,o,!0),e.addEventListener(`submit`,a,!0)}function l(){c(document);for(let e of i.keys())e instanceof ShadowRoot&&!e.host.isConnected&&s(e);let t=new Set,a=new Map,o=new Map;for(let e of i.keys())for(let n of e.querySelectorAll(`*`)){let e=Vu(n);if(e&&c(e),!(n instanceof HTMLFormElement)||!zu(n,`toolname`)||!zu(n,`tooldescription`)||!Bu(n))continue;let i=n;t.add(i);let s=cd(i),l=JSON.stringify(s),u=r.get(i);if(u===l)continue;r.delete(i);let d=o.get(s.name);if(d){if(u===void 0){r.set(i,l);continue}let e=a.get(d);e&&r.set(d,e.fingerprint),a.delete(d)}o.set(s.name,i),a.set(i,{definition:s,fingerprint:l})}for(let e of r.keys())t.has(e)||r.delete(e);for(let[e,t]of n)a.get(e)?.fingerprint!==t.fingerprint&&(t.cancelPending?.(q()),t.controller.abort(),n.delete(e));for(let[t,{definition:r,fingerprint:i}]of a){if(n.has(t))continue;let a=new AbortController,o={controller:a,fingerprint:i,form:t};n.set(t,o),e.registerTool({name:r.name,title:r.title,description:r.description,inputSchema:r.inputSchema,execute(n,i){let a=yd(t);if(!r.autosubmit&&!a)throw q();return vd(t,n),xd(e,o,r,a,i.signal)}},{signal:a.signal}).catch(e=>{a.abort(),!(e instanceof DOMException&&e.name===`AbortError`)&&console.error(`[webmcp] declarative form tool "${r.name}" was not registered:`,e)})}}let u=Object.getOwnPropertyDescriptor(Element.prototype,`attachShadow`);if(u?.configurable){let e=Element.prototype.attachShadow,t=function(t){let n=e.call(this,t);return n.mode===`open`&&Object.getOwnPropertyDescriptor(Node.prototype,`ownerDocument`)?.get?.call(this)===document&&Bu(this)&&c(n),n};Object.defineProperty(Element.prototype,"attachShadow",{...u,value:t})}let d=Object.getOwnPropertyDescriptor(HTMLFormElement.prototype,`submit`);if(d?.configurable){let e=HTMLFormElement.prototype.submit,t=function(){e.call(this),ju.get(this)?.direct()};Object.defineProperty(HTMLFormElement.prototype,"submit",{...d,value:t})}l()}
|
|
65
|
+
/*!
|
|
66
|
+
* Copyright (c) 2026 WebMCP polyfill contributors
|
|
67
|
+
* SPDX-License-Identifier: MIT
|
|
68
|
+
*/
|
|
69
|
+
let Cd=globalThis.DOMException,wd=Object.getOwnPropertyDescriptor(globalThis,`window`)?.get,Td=new WeakMap;function Ed(){if(typeof document>`u`||!globalThis.isSecureContext||`modelContext`in document)return;let e=Document.prototype,t=Object.getOwnPropertyDescriptor(e,`defaultView`).get,n=Object.getOwnPropertyDescriptor(globalThis,`ModelContext`);if(!Object.isExtensible(e)||n&&!n.configurable||!n&&!Object.isExtensible(globalThis))throw TypeError(`Cannot install WebMCP on this realm`);Object.defineProperty(globalThis,"ModelContext",{value:kd,configurable:!0,writable:!0});let{getModelContext:r}={getModelContext(){t.call(this);let e=Td.get(this);return e||(e=new Dd(this),Td.set(this,e)),e}};Object.defineProperty(r,"name",{value:`get modelContext`}),Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,get:r}),document.modelContext}var Dd=class extends EventTarget{#e;#t=new Map;#n;#r=null;#i=e=>{let t=this.#r;typeof t==`function`&&Reflect.apply(t,this,[e])===!1&&Event.prototype.preventDefault.call(e)};constructor(e){super(),this.#e=e;let t=Su(e);t&&(this.#n=new _u(t,{getTools:e=>this.#s(e),execute:(t,n,r,i)=>{let a=Wd(e).origin;return this.#a(n,r,a,t,i)},changed:()=>this.#c()}))}get ontoolchange(){return this.#r}set ontoolchange(e){let t=Nd(e)?e:null;!this.#r&&t&&this.addEventListener(`toolchange`,this.#i),this.#r&&!t&&this.removeEventListener(`toolchange`,this.#i),this.#r=t}async registerTool(e,t={}){let n=this.#e,{name:r,title:i,description:a,annotations:o,inputSchema:s,execute:c}=Ad(e),l=Pd(t),u=Vd(l.exposedTo),d=Bd(l.signal);Wd(n);let f=()=>{if(this.#t.has(r))throw new Cd(`A tool named ${r} is already registered`,`InvalidStateError`)};if(f(),!/^[A-Za-z0-9_.-]{1,128}$/u.test(r))throw new Cd(`Tool names are 1 to 128 characters of ASCII alphanumerics, "_", "-" or ".": ${r}`,`InvalidStateError`);if(!a)throw new Cd(`A tool description cannot be empty`,`InvalidStateError`);let p=s===void 0?void 0:zd(s);d?.throwIfAborted();let m=Hd(u),h={metadata:{name:r,title:i,description:a,annotations:o,serializedSchema:p},execute:c,exposedTo:m},g=await this.#o();return d?.throwIfAborted(),f(),new Promise((e,t)=>{d?.addEventListener(`abort`,()=>{this.#t.delete(r),g.notify(m),t(d.reason)},{once:!0}),this.#t.set(r,h),g.notify(m).then(e,t)})}async getTools(e={}){let t=this.#e,n=Vd(Pd(e).fromOrigins);Wd(t);let r=await this.#o(),i=Hd(n),a=await r.getTools(i);return a.sort((e,t)=>e.name===t.name?0:e.name<t.name?-1:1),new Promise(e=>{qd(()=>e(a))})}async executeTool(e,t={},n={}){let r=this.#e,i=jd(e),a=Bd(Pd(n).signal);Wd(r);let o=URL.parse(i.origin)?.origin;if(!o||o===`null`)throw new Cd(`Invalid or opaque origin`,`NotSupportedError`);if(!Nd(t))throw TypeError(`inputObject must be an object`);let s=zd(t);a?.throwIfAborted();let c=await this.#o();a?.throwIfAborted();let l=Wd(r);return i.window===l?this.#a(i.name,s,o,l.origin,a):c.execute(i.window,o,i.name,s,a)}#a(e,t,n,r,i){return new Promise((a,o)=>{i?.throwIfAborted();let s=new AbortController,c=!1,l=()=>{o(i.reason),qd(()=>{c||s.abort()})},u=()=>{c=!0,qd(()=>{i?.removeEventListener(`abort`,l),o(q())})},d=e=>{if(c=!0,!i?.aborted)try{let t=zd(e);qd(()=>{i?.removeEventListener(`abort`,l),a(t)})}catch{u()}};i?.addEventListener(`abort`,l,{once:!0}),qd(()=>{if(!i?.aborted)try{let i=Wd(this.#e),a=this.#t.get(e);if(!a||n!==i.origin||!Od(a,i.origin,r)){u();return}let o=JSON.parse(t);if(!Nd(o)){u();return}let c=a.execute,l=c(o,{signal:s.signal});Promise.resolve(l).then(d,u)}catch{u()}})})}async#o(){let e=this.#n;if(!e||!await e.allowed())throw new Cd(`WebMCP is disabled by Permissions Policy`,`NotAllowedError`);return Wd(this.#e),e}#s(e){let t=Wd(this.#e).origin,n=[];for(let r of this.#t.values())Od(r,t,e)&&n.push(r.metadata);return n}#c(){return new Promise(e=>{qd(()=>{this.dispatchEvent(new Event(`toolchange`)),e()})})}};function Od(e,t,n){return t===n||e.exposedTo.includes(n)}let kd=function(){throw TypeError(`Illegal constructor`)};Object.defineProperty(kd,"name",{value:`ModelContext`}),Object.defineProperty(kd,"prototype",{value:Dd.prototype,writable:!1}),Object.setPrototypeOf(kd,EventTarget),Object.defineProperties(Dd.prototype,{constructor:{value:kd,configurable:!0,writable:!0},[Symbol.toStringTag]:{value:`ModelContext`,configurable:!0},registerTool:{enumerable:!0},getTools:{enumerable:!0},executeTool:{enumerable:!0},ontoolchange:{enumerable:!0}});function Ad(e){let t=Pd(e),n=Fd(t.annotations),r=Id(Rd(t.description,`description`)),i=Rd(t.execute,`execute`);if(typeof i!=`function`)throw TypeError(`execute must be a function`);let a=i,o=Md(t.inputSchema),s=Id(Rd(t.name,`name`)),c=t.title;return{name:s,title:c===void 0?``:Ld(c),description:r,annotations:n,inputSchema:o,execute:a}}function jd(e){let t=Pd(e);Fd(t.annotations),Id(Rd(t.description,`description`)),Md(t.inputSchema);let n=Id(Rd(t.name,`name`)),r=Ld(Rd(t.origin,`origin`)),i=t.title;i!==void 0&&Id(i);let a=Rd(t.window,`window`);if(!Nd(a))throw TypeError(`window must be a Window`);return wd.call(a),{name:n,origin:r,window:a}}function Md(e){if(e!==void 0&&!Nd(e))throw TypeError(`inputSchema must be an object`);return e}function Nd(e){return typeof e==`object`&&!!e||typeof e==`function`}function Pd(e){if(e==null)return{};if(!Nd(e))throw TypeError(`Expected a dictionary`);return e}function Fd(e){if(e===void 0)return;let t=Pd(e),n={};for(let e of mu)n[e]=!!t[e];return n}function Id(e){if(typeof e==`symbol`)throw TypeError(`Cannot convert a Symbol to a string`);return String(e)}function Ld(e){return Id(e).toWellFormed()}function Rd(e,t){if(e===void 0)throw TypeError(`${t} is required`);return e}function zd(e){let t=JSON.stringify(e);if(t===void 0)throw TypeError(`Value is not JSON-serializable`);return t}function Bd(e){if(e!==void 0)return AbortSignal.any([e])}function Vd(e){if(e===void 0)return[];if(!Nd(e))throw TypeError(`Origins must be a sequence`);let t=Pd(e)[Symbol.iterator];if(typeof t!=`function`)throw TypeError(`Origins must be a sequence`);let n={[Symbol.iterator](){let n=Reflect.apply(t,e,[]);if(!Nd(n))throw TypeError(`Iterator must be an object`);let r=Pd(n).next;if(typeof r!=`function`)throw TypeError(`Iterator next must be a function`);return{next(){return Reflect.apply(r,n,[])}}}};return Array.from(n,Ld)}function Hd(e){return e.map(e=>{let t=URL.parse(e)?.origin;if(t===void 0)throw new Cd(`Invalid origin`,`SecurityError`);let n=URL.parse(t);if(!n||!Ud(n))throw new Cd(`Origin is not potentially trustworthy`,`SecurityError`);return t})}function Ud({protocol:e,hostname:t}){if([`https:`,`wss:`].includes(e))return!0;let n=t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t),r=t===`localhost`||t===`localhost.`||t.endsWith(`.localhost`)||t.endsWith(`.localhost.`);return[`http:`,`ws:`].includes(e)&&(n||r)}function Wd(e){let t=Su(e);if(!t)throw new Cd(`The document is not fully active`,`InvalidStateError`);if(Cu(e)===!1)throw new Cd(`WebMCP is disabled by Permissions Policy`,`NotAllowedError`);return t}let Gd,Kd=[];function qd(e){if(!Gd){let e=new MessageChannel;e.port1.onmessage=()=>Kd.shift()?.(),Gd=e.port2}Kd.push(e),Gd.postMessage(void 0)}function Jd(){if(typeof document>`u`||!globalThis.isSecureContext||typeof Promise.withResolvers!=`function`||typeof AbortSignal.any!=`function`||typeof String.prototype.toWellFormed!=`function`||typeof URL.parse!=`function`)return;Ed();let e=document.modelContext;e&&Sd(e)}let Yd=/^[A-Za-z0-9_.-]{1,128}$/u;function J(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xd(e){return e!==null&&(typeof e==`object`||typeof e==`function`)}function Zd(e){if(typeof e==`symbol`)throw TypeError(`Symbol values cannot be converted to a DOMString`);return String(e)}function Qd(e){let{name:t,description:n,title:r}=e;if(t===void 0)throw TypeError(`Tool "name" is required`);if(n===void 0)throw TypeError(`Tool "description" is required`);let{annotations:i,inputSchema:a,outputSchema:o,execute:s}=e,c=Zd(t),l=r===void 0?void 0:Zd(r).toWellFormed(),u={name:c,description:Zd(n),execute:s};if(l!==void 0&&(u.title=l),a!==void 0&&(u.inputSchema=a),o!==void 0&&(u.outputSchema=o),i!==void 0){let e=J(i)?i:{},t={readOnlyHint:!!e.readOnlyHint,untrustedContentHint:!!e.untrustedContentHint};e.title!==void 0&&(t.title=Zd(e.title).toWellFormed());for(let n of[`destructiveHint`,`idempotentHint`,`openWorldHint`,`consequentialHint`,`debugging`]){let r=e[n];r!==void 0&&(t[n]=!!r)}u.annotations=t}return ef(u),u}function $d(e){return new DOMException(e,`InvalidStateError`)}function ef(e){if(e.name===``)throw $d(`Tool "name" must be a non-empty string`);if(!Yd.test(e.name))throw $d(`Tool "name" must be 1–128 characters and contain only ASCII alphanumeric, underscore, hyphen, or period`);if(e.description.length===0)throw $d(`Tool "description" must be a non-empty string`);if(typeof e.execute!=`function`)throw TypeError(`Tool "execute" must be a function`)}function tf(e){if(!Xd(e))throw TypeError(`inputSchema must be an object`);let t=JSON.stringify(e);if(t===void 0)throw TypeError(`inputSchema must be JSON-serializable`);return t}let nf={type:`object`,properties:{}},rf=[`draft-2020-12`,`draft-07`];function af(e){if(!J(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function of(e,t=new WeakSet){if(e===null||typeof e==`string`||typeof e==`boolean`)return!0;if(typeof e==`number`)return Number.isFinite(e);if(typeof e!=`object`||t.has(e))return!1;t.add(e);try{return(Array.isArray(e)?e:af(e)?Object.values(e):null)?.every(e=>of(e,t))??!1}catch{return!1}finally{t.delete(e)}}function sf(e){if(!J(e))return!1;switch(e.type){case`text`:return typeof e.text==`string`;case`image`:case`audio`:return typeof e.data==`string`&&typeof e.mimeType==`string`;case`resource_link`:return typeof e.uri==`string`&&typeof e.name==`string`;case`resource`:{let t=e.resource;return J(t)&&typeof t.uri==`string`&&(typeof t.text==`string`||typeof t.blob==`string`)}default:return!1}}function cf(e){return J(e)&&of(e)&&Array.isArray(e.content)&&e.content.every(sf)&&(e.isError===void 0||typeof e.isError==`boolean`)&&(e._meta===void 0||J(e._meta))}function lf(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function uf(e){if(cf(e))return e;let t={content:[{type:`text`,text:lf(e)}],isError:!1};return of(e)&&(t.structuredContent=e),t}function df(e){if(!J(e))return null;let t=e[`~standard`];return J(t)?t:null}function ff(e){let t=df(e);return!!(t&&t.version===1&&typeof t.validate==`function`)}function pf(e){let t=df(e);return!t||t.version!==1||!J(t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function mf(e){let t=df(e);return!!(t&&t.version===1&&typeof t.vendor==`string`&&typeof t.validate==`function`&&J(t.jsonSchema)&&typeof t.jsonSchema.input==`function`&&typeof t.jsonSchema.output==`function`)}function hf(e){for(let t of rf)try{let n=e[`~standard`].jsonSchema.input({target:t}),r=JSON.parse(tf(n));if(J(r))return r}catch{}throw Error(`Failed to convert Standard JSON Schema inputSchema to a JSON Schema object`)}function gf(e){if(e===void 0)return{inputSchema:nf};if(pf(e)){let t=hf(e),n=tf(t);return ff(e)&&Object.defineProperty(t,"~standard",{value:e[`~standard`]}),{inputSchema:t,registeredInputSchema:n}}if(ff(e))throw Error(`Standard Schema inputSchema must provide ~standard.jsonSchema.input() for tool metadata`);let t=tf(e),n=JSON.parse(t);return!J(n)||Object.keys(n).length===0?{inputSchema:nf,registeredInputSchema:t}:{inputSchema:n.type===void 0?{type:`object`,...n}:n,registeredInputSchema:t}}var _f=Object.defineProperty,vf=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),yf=(e,t)=>{let n={};for(var r in e)_f(n,r,{get:e[r],enumerable:!0});return t&&_f(n,Symbol.toStringTag,{value:`Module`}),n};let bf=new Set([`https://json-schema.org/draft/2020-12/schema`,`http://json-schema.org/draft/2020-12/schema`]),xf=new Set([`https://json-schema.org/draft/2019-09/schema`,`http://json-schema.org/draft/2019-09/schema`]),Sf=new Set([`https://json-schema.org/draft-07/schema`,`http://json-schema.org/draft-07/schema`]),Cf=new Set([`https://json-schema.org/draft-06/schema`,`http://json-schema.org/draft-06/schema`]);function wf(e){return typeof e==`string`&&xf.has(e.replace(/#$/,``))}function Tf(e,t){if(!(`$schema`in e)||typeof e.$schema!=`string`)return`2020-12`;let n=e.$schema.replace(/#$/,``);if(bf.has(n))return`2020-12`;if(xf.has(n))return`2019-09`;if(Sf.has(n)||Cf.has(n))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}`)}let Ef=Symbol.for(`mcp.sdk.errorBrands`);function Df(e,t){let n=new Set,r=t;for(;typeof r==`function`;){let e=r.mcpBrand;Object.prototype.hasOwnProperty.call(r,`mcpBrand`)&&typeof e==`string`&&n.add(e),r=Object.getPrototypeOf(r)}n.size!==0&&Object.defineProperty(e,Ef,{value:n,enumerable:!1,configurable:!0})}function Of(e,t){try{if(typeof t==`object`&&t&&Object.prototype.hasOwnProperty.call(e,`mcpBrand`)&&typeof e.mcpBrand==`string`&&Object.prototype.hasOwnProperty.call(t,Ef)){let n=t[Ef];if(n&&typeof n.has==`function`&&n.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}(class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.OAuthError`})}static[Symbol.hasInstance](e){return Of(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 Of(this,e)}constructor(e,t,n){super(t),this.code=e,this.errorUri=n,this.name=`OAuthError`,Df(this,new.target)}toResponseObject(){let e={error:this.code,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}});let Y=function(e){return e.NotConnected=`NOT_CONNECTED`,e.AlreadyConnected=`ALREADY_CONNECTED`,e.NotInitialized=`NOT_INITIALIZED`,e.CapabilityNotSupported=`CAPABILITY_NOT_SUPPORTED`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.ConnectionClosed=`CONNECTION_CLOSED`,e.SendFailed=`SEND_FAILED`,e.InvalidResult=`INVALID_RESULT`,e.UnsupportedResultType=`UNSUPPORTED_RESULT_TYPE`,e.InputRequiredRoundsExceeded=`INPUT_REQUIRED_ROUNDS_EXCEEDED`,e.ListPaginationExceeded=`LIST_PAGINATION_EXCEEDED`,e.MethodNotSupportedByProtocolVersion=`METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION`,e.EraNegotiationFailed=`ERA_NEGOTIATION_FAILED`,e.ClientHttpNotImplemented=`CLIENT_HTTP_NOT_IMPLEMENTED`,e.ClientHttpAuthentication=`CLIENT_HTTP_AUTHENTICATION`,e.ClientHttpForbidden=`CLIENT_HTTP_FORBIDDEN`,e.ClientHttpUnexpectedContent=`CLIENT_HTTP_UNEXPECTED_CONTENT`,e.ClientHttpFailedToOpenStream=`CLIENT_HTTP_FAILED_TO_OPEN_STREAM`,e.ClientHttpFailedToTerminateSession=`CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION`,e}({});var X=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkError`})}static[Symbol.hasInstance](e){return Of(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 Of(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`SdkError`,Df(this,new.target)}};(class extends X{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkHttpError`})}constructor(e,t,n){super(e,t,n),this.name=`SdkHttpError`}get status(){return this.data.status}get statusText(){return this.data.statusText}});function kf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Af(e,t,n){return e===`elicitation`&&t===`form`&&n.form===void 0&&n.url===void 0}function jf(e){switch(e.method){case`elicitation/create`:return e.params?.mode===`url`?{elicitation:{url:{}}}:{elicitation:{form:{}}};case`sampling/createMessage`:{let t=e.params;return t!==void 0&&(t.tools!==void 0||t.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case`roots/list`:return{roots:{}};default:return}}function Mf(e,t){let n={};for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=t===void 0?void 0:t[r];if(e===void 0){n[r]=i;continue}if(kf(i)&&kf(e)){let t={};for(let[n,a]of Object.entries(i))a!==void 0&&e[n]===void 0&&!Af(r,n,e)&&(t[n]=a);Object.keys(t).length>0&&(n[r]=t)}}return Object.keys(n).length>0?n:void 0}function Nf(e){return e>=`2026-07-28`}function Pf(e){return e.filter(e=>!Nf(e))}function Ff(e){return e.filter(e=>Nf(e))}function If(e){let t=e.structuredContent;return t===void 0||!(typeof t!=`object`||!t||Array.isArray(t))||(e.content?.some(e=>e.type===`text`)??!1)?e:{...e,content:[...e.content??[],{type:`text`,text:JSON.stringify(t)}]}}let Lf=[`task`,`inputRequests`,`requestState`];function Rf(e){return typeof e!=`object`||!e||Array.isArray(e)||e.content!==void 0||Lf.some(t=>t in e)?e:{...e,content:[]}}function zf(){let e=Fo(()=>L([k(),j(),M(),Za(),R(k(),e),P(e)])),t=R(k(),e),n=L([k(),j().int()]),r=k(),i=F({ttl:j().optional()}),a=F({taskId:k()}),o=I({progressToken:n.optional(),"io.modelcontextprotocol/related-task":a.optional()}),s=F({_meta:o.optional()}),c=s.extend({task:i.optional()}),l=F({method:k(),params:s.loose().optional()}),u=F({_meta:o.optional()}),d=F({method:k(),params:u.loose().optional()}),f=I({_meta:o.optional()}),p=L([k(),j().int()]),m=f.strict(),h=u.extend({requestId:p.optional(),reason:k().optional()}),g=d.extend({method:B(`notifications/cancelled`),params:h}),_=F({src:k(),mimeType:k().optional(),sizes:P(k()).optional(),theme:z([`light`,`dark`]).optional()}),ee=F({icons:P(_).optional()}),te=F({name:k(),title:k().optional()}),ne=te.extend({...te.shape,...ee.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),re=zo(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,lo(F({form:lo(F({applyDefaults:M().optional()}),t).optional(),url:t.optional()}),t.optional())),ie=I({list:t.optional(),cancel:t.optional(),requests:I({sampling:I({createMessage:t.optional()}).optional(),elicitation:I({create:t.optional()}).optional()}).optional()}),ae=I({list:t.optional(),cancel:t.optional(),requests:I({tools:I({call:t.optional()}).optional()}).optional()}),oe=F({experimental:R(k(),t).optional(),sampling:F({context:t.optional(),tools:t.optional()}).optional(),elicitation:re.optional(),roots:F({listChanged:M().optional()}).optional(),tasks:ie.optional(),extensions:R(k(),t).optional()}),se=s.extend({protocolVersion:k(),capabilities:oe,clientInfo:ne}),ce=l.extend({method:B(`initialize`),params:se}),le=F({experimental:R(k(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:F({listChanged:M().optional()}).optional(),resources:F({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:F({listChanged:M().optional()}).optional(),tasks:ae.optional(),extensions:R(k(),t).optional()}),v=f.extend({protocolVersion:k(),capabilities:le,serverInfo:ne,instructions:k().optional()}),ue=d.extend({method:B(`notifications/initialized`),params:u.optional()}),de=l.extend({method:B(`ping`),params:s.optional()}),fe=F({progress:j(),total:V(j()),message:V(k())}),pe=F({...u.shape,...fe.shape,progressToken:n}),me=d.extend({method:B(`notifications/progress`),params:pe}),he=s.extend({cursor:r.optional()}),ge=l.extend({params:he.optional()}),_e=f.extend({nextCursor:r.optional()}),ve=F({uri:k(),mimeType:V(k()),_meta:R(k(),N()).optional()}),ye=ve.extend({text:k()}),be=k().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),xe=ve.extend({blob:be}),y=z([`user`,`assistant`]),b=F({audience:P(y).optional(),priority:j().min(0).max(1).optional(),lastModified:ta({offset:!0}).optional()}),Se=F({...te.shape,...ee.shape,uri:k(),description:V(k()),mimeType:V(k()),size:V(j()),annotations:b.optional(),_meta:V(I({}))}),Ce=F({...te.shape,...ee.shape,uriTemplate:k(),description:V(k()),mimeType:V(k()),annotations:b.optional(),_meta:V(I({}))}),we=ge.extend({method:B(`resources/list`)}),Te=_e.extend({resources:P(Se)}),x=ge.extend({method:B(`resources/templates/list`)}),Ee=_e.extend({resourceTemplates:P(Ce)}),De=s.extend({uri:k()}),Oe=De,ke=l.extend({method:B(`resources/read`),params:Oe}),Ae=f.extend({contents:P(L([ye,xe]))}),je=d.extend({method:B(`notifications/resources/list_changed`),params:u.optional()}),Me=De,Ne=l.extend({method:B(`resources/subscribe`),params:Me}),S=De,Pe=l.extend({method:B(`resources/unsubscribe`),params:S}),Fe=u.extend({uri:k()}),Ie=d.extend({method:B(`notifications/resources/updated`),params:Fe}),Le=F({name:k(),description:V(k()),required:V(M())}),Re=F({...te.shape,...ee.shape,description:V(k()),arguments:V(P(Le)),_meta:V(I({}))}),ze=ge.extend({method:B(`prompts/list`)}),Be=_e.extend({prompts:P(Re)}),Ve=s.extend({name:k(),arguments:R(k(),k()).optional()}),He=l.extend({method:B(`prompts/get`),params:Ve}),Ue=F({type:B(`text`),text:k(),annotations:b.optional(),_meta:R(k(),N()).optional()}),We=F({type:B(`image`),data:be,mimeType:k(),annotations:b.optional(),_meta:R(k(),N()).optional()}),Ge=F({type:B(`audio`),data:be,mimeType:k(),annotations:b.optional(),_meta:R(k(),N()).optional()}),Ke=F({type:B(`tool_use`),name:k(),id:k(),input:R(k(),N()),_meta:R(k(),N()).optional()}),qe=F({type:B(`resource`),resource:L([ye,xe]),annotations:b.optional(),_meta:R(k(),N()).optional()}),Je=Se.extend({type:B(`resource_link`)}),Ye=L([Ue,We,Ge,Je,qe]),Xe=F({role:y,content:Ye}),Ze=f.extend({description:k().optional(),messages:P(Xe)}),Qe=d.extend({method:B(`notifications/prompts/list_changed`),params:u.optional()}),$e=F({title:k().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),et=F({taskSupport:z([`required`,`optional`,`forbidden`]).optional()}),tt=F({...te.shape,...ee.shape,description:k().optional(),inputSchema:F({type:B(`object`),properties:R(k(),e).optional(),required:P(k()).optional()}).catchall(N()),outputSchema:F({type:B(`object`),properties:R(k(),e).optional(),required:P(k()).optional()}).catchall(N()).optional(),annotations:$e.optional(),execution:et.optional(),_meta:R(k(),N()).optional()}),nt=ge.extend({method:B(`tools/list`)}),rt=_e.extend({tools:P(tt)}),it=f.extend({content:P(Ye),structuredContent:R(k(),N()).optional(),isError:M().optional()}),C=c.extend({name:k(),arguments:R(k(),N()).optional()}),at=l.extend({method:B(`tools/call`),params:C}),ot=d.extend({method:B(`notifications/tools/list_changed`),params:u.optional()}),st=z([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),ct=s.extend({level:st}),lt=l.extend({method:B(`logging/setLevel`),params:ct}),ut=u.extend({level:st,logger:k().optional(),data:N()}),dt=d.extend({method:B(`notifications/message`),params:ut}),ft=F({name:k().optional()}),pt=F({hints:P(ft).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),mt=F({mode:z([`auto`,`required`,`none`]).optional()}),ht=F({type:B(`tool_result`),toolUseId:k().describe(`The unique identifier for the corresponding tool call.`),content:P(Ye),structuredContent:F({}).loose().optional(),isError:M().optional(),_meta:R(k(),N()).optional()}),gt=so(`type`,[Ue,We,Ge]),w=so(`type`,[Ue,We,Ge,Ke,ht]),_t=F({role:y,content:L([w,P(w)]),_meta:R(k(),N()).optional()}),vt=c.extend({messages:P(_t),modelPreferences:pt.optional(),systemPrompt:k().optional(),includeContext:z([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:P(k()).optional(),metadata:t.optional(),tools:P(tt).optional(),toolChoice:mt.optional()}),yt=l.extend({method:B(`sampling/createMessage`),params:vt}),bt=f.extend({model:k(),stopReason:V(z([`endTurn`,`stopSequence`,`maxTokens`]).or(k())),role:y,content:gt}),xt=f.extend({model:k(),stopReason:V(z([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(k())),role:y,content:L([w,P(w)])}),St=F({type:B(`boolean`),title:k().optional(),description:k().optional(),default:M().optional()}),Ct=F({type:B(`string`),title:k().optional(),description:k().optional(),minLength:j().optional(),maxLength:j().optional(),format:z([`email`,`uri`,`date`,`date-time`]).optional(),default:k().optional()}),wt=F({type:z([`number`,`integer`]),title:k().optional(),description:k().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),Tt=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),default:k().optional()}),Et=F({type:B(`string`),title:k().optional(),description:k().optional(),oneOf:P(F({const:k(),title:k()})),default:k().optional()}),Dt=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),enumNames:P(k()).optional(),default:k().optional()}),Ot=L([Tt,Et]),kt=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({type:B(`string`),enum:P(k())}),default:P(k()).optional()}),At=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({anyOf:P(F({const:k(),title:k()}))}),default:P(k()).optional()}),jt=L([kt,At]),Mt=L([Dt,Ot,jt]),Nt=L([Mt,St,Ct,wt]),Pt=c.extend({mode:B(`form`).optional(),message:k(),requestedSchema:F({type:B(`object`),properties:R(k(),Nt),required:P(k()).optional()}).catchall(N())}),T=c.extend({mode:B(`url`),message:k(),elicitationId:k(),url:k().url()}),Ft=L([Pt,T]),E=l.extend({method:B(`elicitation/create`),params:Ft}),It=u.extend({elicitationId:k()}),Lt=d.extend({method:B(`notifications/elicitation/complete`),params:It}),Rt=f.extend({action:z([`accept`,`decline`,`cancel`]),content:zo(e=>e===null?void 0:e,R(k(),L([k(),j(),M(),P(k())])).optional())}),zt=F({type:B(`ref/resource`),uri:k()}),Bt=F({type:B(`ref/prompt`),name:k()}),Vt=s.extend({ref:L([Bt,zt]),argument:F({name:k(),value:k()}),context:F({arguments:R(k(),k()).optional()}).optional()}),Ht=l.extend({method:B(`completion/complete`),params:Vt}),Ut=f.extend({completion:I({values:P(k()).max(100),total:V(j().int()),hasMore:V(M())})}),Wt=F({uri:k().startsWith(`file://`),name:k().optional(),_meta:R(k(),N()).optional()}),Gt=l.extend({method:B(`roots/list`),params:s.optional()}),Kt=f.extend({roots:P(Wt)}),qt=d.extend({method:B(`notifications/roots/list_changed`),params:u.optional()}),Jt=I({ttl:j().optional(),pollInterval:j().optional()}),Yt=z([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Xt=F({taskId:k(),status:Yt,ttl:L([j(),Za()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:V(j()),statusMessage:V(k())}),Zt=f.extend({task:Xt}),Qt=u.merge(Xt),$t=d.extend({method:B(`notifications/tasks/status`),params:Qt}),en=l.extend({method:B(`tasks/get`),params:s.extend({taskId:k()})}),tn=f.merge(Xt),nn=l.extend({method:B(`tasks/result`),params:s.extend({taskId:k()})}),rn=f.loose(),an=ge.extend({method:B(`tasks/list`)}),on=_e.extend({tasks:P(Xt)}),sn=l.extend({method:B(`tasks/cancel`),params:s.extend({taskId:k()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,TaskMetadataSchema:i,RelatedTaskMetadataSchema:a,RequestMetaSchema:o,BaseRequestParamsSchema:s,TaskAugmentedRequestParamsSchema:c,RequestSchema:l,NotificationsParamsSchema:u,NotificationSchema:d,ResultSchema:f,RequestIdSchema:p,EmptyResultSchema:m,CancelledNotificationParamsSchema:h,CancelledNotificationSchema:g,IconSchema:_,IconsSchema:ee,BaseMetadataSchema:te,ImplementationSchema:ne,ClientTasksCapabilitySchema:ie,ServerTasksCapabilitySchema:ae,ClientCapabilitiesSchema:oe,InitializeRequestParamsSchema:se,InitializeRequestSchema:ce,ServerCapabilitiesSchema:le,InitializeResultSchema:v,InitializedNotificationSchema:ue,PingRequestSchema:de,ProgressSchema:fe,ProgressNotificationParamsSchema:pe,ProgressNotificationSchema:me,PaginatedRequestParamsSchema:he,PaginatedRequestSchema:ge,PaginatedResultSchema:_e,ResourceContentsSchema:ve,TextResourceContentsSchema:ye,BlobResourceContentsSchema:xe,RoleSchema:y,AnnotationsSchema:b,ResourceSchema:Se,ResourceTemplateSchema:Ce,ListResourcesRequestSchema:we,ListResourcesResultSchema:Te,ListResourceTemplatesRequestSchema:x,ListResourceTemplatesResultSchema:Ee,ResourceRequestParamsSchema:De,ReadResourceRequestParamsSchema:Oe,ReadResourceRequestSchema:ke,ReadResourceResultSchema:Ae,ResourceListChangedNotificationSchema:je,SubscribeRequestParamsSchema:Me,SubscribeRequestSchema:Ne,UnsubscribeRequestParamsSchema:S,UnsubscribeRequestSchema:Pe,ResourceUpdatedNotificationParamsSchema:Fe,ResourceUpdatedNotificationSchema:Ie,PromptArgumentSchema:Le,PromptSchema:Re,ListPromptsRequestSchema:ze,ListPromptsResultSchema:Be,GetPromptRequestParamsSchema:Ve,GetPromptRequestSchema:He,TextContentSchema:Ue,ImageContentSchema:We,AudioContentSchema:Ge,ToolUseContentSchema:Ke,EmbeddedResourceSchema:qe,ResourceLinkSchema:Je,ContentBlockSchema:Ye,PromptMessageSchema:Xe,GetPromptResultSchema:Ze,PromptListChangedNotificationSchema:Qe,ToolAnnotationsSchema:$e,ToolExecutionSchema:et,ToolSchema:tt,ListToolsRequestSchema:nt,ListToolsResultSchema:rt,CallToolResultSchema:it,CallToolRequestParamsSchema:C,CallToolRequestSchema:at,ToolListChangedNotificationSchema:ot,LoggingLevelSchema:st,SetLevelRequestParamsSchema:ct,SetLevelRequestSchema:lt,LoggingMessageNotificationParamsSchema:ut,LoggingMessageNotificationSchema:dt,ModelHintSchema:ft,ModelPreferencesSchema:pt,ToolChoiceSchema:mt,ToolResultContentSchema:ht,SamplingContentSchema:gt,SamplingMessageContentBlockSchema:w,SamplingMessageSchema:_t,CreateMessageRequestParamsSchema:vt,CreateMessageRequestSchema:yt,CreateMessageResultSchema:bt,CreateMessageResultWithToolsSchema:xt,BooleanSchemaSchema:St,StringSchemaSchema:Ct,NumberSchemaSchema:wt,UntitledSingleSelectEnumSchemaSchema:Tt,TitledSingleSelectEnumSchemaSchema:Et,LegacyTitledEnumSchemaSchema:Dt,SingleSelectEnumSchemaSchema:Ot,UntitledMultiSelectEnumSchemaSchema:kt,TitledMultiSelectEnumSchemaSchema:At,MultiSelectEnumSchemaSchema:jt,EnumSchemaSchema:Mt,PrimitiveSchemaDefinitionSchema:Nt,ElicitRequestFormParamsSchema:Pt,ElicitRequestURLParamsSchema:T,ElicitRequestParamsSchema:Ft,ElicitRequestSchema:E,ElicitationCompleteNotificationParamsSchema:It,ElicitationCompleteNotificationSchema:Lt,ElicitResultSchema:Rt,ResourceTemplateReferenceSchema:zt,PromptReferenceSchema:Bt,CompleteRequestParamsSchema:Vt,CompleteRequestSchema:Ht,CompleteResultSchema:Ut,RootSchema:Wt,ListRootsRequestSchema:Gt,ListRootsResultSchema:Kt,RootsListChangedNotificationSchema:qt,TaskCreationParamsSchema:Jt,TaskStatusSchema:Yt,TaskSchema:Xt,CreateTaskResultSchema:Zt,TaskStatusNotificationParamsSchema:Qt,TaskStatusNotificationSchema:$t,GetTaskRequestSchema:en,GetTaskResultSchema:tn,GetTaskPayloadRequestSchema:nn,GetTaskPayloadResultSchema:rn,ListTasksRequestSchema:an,ListTasksResultSchema:on,CancelTaskRequestSchema:sn,CancelTaskResultSchema:f.merge(Xt),ClientRequestSchema:L([de,ce,Ht,lt,He,ze,we,x,ke,Ne,Pe,at,nt,en,nn,an,sn]),ClientNotificationSchema:L([g,me,ue,qt,$t]),ClientResultSchema:L([m,bt,xt,Rt,Kt,tn,on,Zt]),ServerRequestSchema:L([de,yt,E,Gt,en,nn,an,sn]),ServerNotificationSchema:L([g,me,dt,Ie,je,ot,Qe,$t,Lt]),ServerResultSchema:L([m,v,Ut,Ze,Be,Te,Ee,Ae,it,rt,tn,on,Zt]),CallToolResultWireSchema:N().superRefine((e,t)=>{if(!(typeof e!=`object`||!e||Array.isArray(e)||e.content!==void 0)){for(let n of Lf)if(n in e){t.addIssue({code:`custom`,message:`content is required when the body carries '${n}' — another result family cannot default into an empty tools/call success`});return}}}).transform(Rf).pipe(it)}}let Bf;function Vf(){return Bf??=zf()}function Hf(e){return e.type!==`object`}let Uf=new Set([`const`,`enum`,`default`,`examples`]),Wf=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`,`dependencies`]);function Gf(e){return e!==void 0&&!(typeof e==`string`&&e.startsWith(`#`))}function Kf(e){let t=typeof e.$schema==`string`?e.$schema:void 0;if(Gf(e.$id))return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:e},required:[`result`]};let n=wf(e.$schema)&&e.$recursiveAnchor!==!0,r=(e,t)=>{if(Array.isArray(e))return e.map(e=>r(e,!1));if(typeof e!=`object`||!e||!t&&Gf(e.$id))return e;let i={},a=!1;for(let[o,s]of Object.entries(e))t?i[o]=r(s,!1):(o===`$ref`||o===`$dynamicRef`)&&typeof s==`string`?i[o]=s===`#`?`#/properties/result`:s.startsWith(`#/`)?`#/properties/result${s.slice(1)}`:s:o===`$recursiveRef`&&s===`#`&&n?a=!0:Uf.has(o)?i[o]=s:Wf.has(o)?i[o]=r(s,!0):i[o]=r(s,!1);return a&&(`$ref`in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:`#/properties/result`}]:i.$ref=`#/properties/result`),i};return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:r(e,!1)},required:[`result`]}}let qf={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Jf={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},Yf={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},Xf;function Zf(){if(Xf)return Xf;let e=Vf();return Xf={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}},Xf}function Qf(e){return Object.prototype.hasOwnProperty.call(qf,e)}function $f(e){return Object.prototype.hasOwnProperty.call(Jf,e)}function ep(e){return Object.prototype.hasOwnProperty.call(Yf,e)}function tp(e){return ep(e)?Zf().resultSchemas[e]:void 0}function np(e){return Qf(e)?Zf().requestSchemas[e]:void 0}function rp(e){return $f(e)?Zf().notificationSchemas[e]:void 0}function ip(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ap(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}let op={ok:!1,reason:`not-in-era`};function sp(e){return ip(e)&&ip(e.outputSchema)&&Hf(e.outputSchema)}function cp(e){return e}let lp={era:`2025-11-25`,hasRequestMethod:Qf,hasNotificationMethod:$f,validateRequest:(e,t)=>ap(np(e),t),validateResult:(e,t)=>ap(tp(e),t),validateNotification:(e,t)=>ap(rp(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>op,validateInputResponse:()=>op,samplingResultVariant:((e,t)=>{let n=Vf();return ap(e?n.CreateMessageResultWithToolsSchema:n.CreateMessageResultSchema,t)}),outboundEnvelope:e=>void 0,validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let n=If(e),r=n.structuredContent;if(r===void 0)return n;let i=typeof r!=`object`||!r||Array.isArray(r),a=t!==void 0&&Hf(t);return!i&&!a?n:{...n,structuredContent:{result:r}}},decodeResult(e,t){if(ip(t)&&`resultType`in t){let e={...t};return delete e.resultType,{kind:`complete`,result:cp(e)}}return{kind:`complete`,result:cp(t)}},encodeResult(e,t){if(e!==`tools/list`)return t;let n=t.tools;return!Array.isArray(n)||!n.some(e=>sp(e))?t:{...t,tools:n.map(e=>sp(e)?{...e,outputSchema:Kf(e.outputSchema)}:e)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>void 0};function up(){let e=Fo(()=>L([k(),j(),M(),Za(),R(k(),e),P(e)])),t=R(k(),e),n=L([k(),j().int()]),r=k(),i=L([k(),j().int()]),a=z([`user`,`assistant`]),o=z([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),s=k().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),c=F({ttl:j().optional()}),l=F({taskId:k()}),u=I({progressToken:n.optional(),"io.modelcontextprotocol/related-task":l.optional()}),d=F({_meta:u.optional()}),f=d.extend({task:c.optional()}),p=F({_meta:u.optional()}),m=F({method:k(),params:p.loose().optional()}),h=F({src:k(),mimeType:k().optional(),sizes:P(k()).optional(),theme:z([`light`,`dark`]).optional()}),g=F({icons:P(h).optional()}),_=F({name:k(),title:k().optional()}),ee=_.extend({..._.shape,...g.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),te=zo(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,lo(F({form:lo(F({applyDefaults:M().optional()}),t).optional(),url:t.optional()}),t.optional())),ne=I({list:t.optional(),cancel:t.optional(),requests:I({sampling:I({createMessage:t.optional()}).optional(),elicitation:I({create:t.optional()}).optional()}).optional()}),re=I({list:t.optional(),cancel:t.optional(),requests:I({tools:I({call:t.optional()}).optional()}).optional()}),ie=F({experimental:R(k(),t).optional(),sampling:F({context:t.optional(),tools:t.optional()}).optional(),elicitation:te.optional(),roots:F({listChanged:M().optional()}).optional(),tasks:ne.optional(),extensions:R(k(),t).optional()}),ae=F({experimental:R(k(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:F({listChanged:M().optional()}).optional(),resources:F({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:F({listChanged:M().optional()}).optional(),tasks:re.optional(),extensions:R(k(),t).optional()}),oe=F({progress:j(),total:V(j()),message:V(k())}),se=F({...p.shape,...oe.shape,progressToken:n}),ce=m.extend({method:B(`notifications/progress`),params:se}),le=p.extend({level:o,logger:k().optional(),data:N()}),v=m.extend({method:B(`notifications/message`),params:le}),ue=F({uri:k(),mimeType:V(k()),_meta:R(k(),N()).optional()}),de=ue.extend({text:k()}),fe=ue.extend({blob:s}),pe=F({audience:P(a).optional(),priority:j().min(0).max(1).optional(),lastModified:ta({offset:!0}).optional()}),me=F({..._.shape,...g.shape,uri:k(),description:V(k()),mimeType:V(k()),size:V(j()),annotations:pe.optional(),_meta:V(I({}))}),he=F({..._.shape,...g.shape,uriTemplate:k(),description:V(k()),mimeType:V(k()),annotations:pe.optional(),_meta:V(I({}))}),ge=m.extend({method:B(`notifications/resources/list_changed`),params:p.optional()}),_e=p.extend({uri:k()}),ve=m.extend({method:B(`notifications/resources/updated`),params:_e}),ye=F({name:k(),description:V(k()),required:V(M())}),be=F({..._.shape,...g.shape,description:V(k()),arguments:V(P(ye)),_meta:V(I({}))}),xe=m.extend({method:B(`notifications/prompts/list_changed`),params:p.optional()}),y=F({type:B(`text`),text:k(),annotations:pe.optional(),_meta:R(k(),N()).optional()}),b=F({type:B(`image`),data:s,mimeType:k(),annotations:pe.optional(),_meta:R(k(),N()).optional()}),Se=F({type:B(`audio`),data:s,mimeType:k(),annotations:pe.optional(),_meta:R(k(),N()).optional()}),Ce=F({type:B(`tool_use`),name:k(),id:k(),input:R(k(),N()),_meta:R(k(),N()).optional()}),we=F({type:B(`resource`),resource:L([de,fe]),annotations:pe.optional(),_meta:R(k(),N()).optional()}),Te=me.extend({type:B(`resource_link`)}),x=L([y,b,Se,Te,we]),Ee=F({role:a,content:x}),De=F({title:k().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),Oe=m.extend({method:B(`notifications/tools/list_changed`),params:p.optional()}),ke=F({name:k().optional()}),Ae=F({hints:P(ke).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),je=F({mode:z([`auto`,`required`,`none`]).optional()}),Me=F({type:B(`boolean`),title:k().optional(),description:k().optional(),default:M().optional()}),Ne=F({type:B(`string`),title:k().optional(),description:k().optional(),minLength:j().optional(),maxLength:j().optional(),format:z([`email`,`uri`,`date`,`date-time`]).optional(),default:k().optional()}),S=F({type:z([`number`,`integer`]),title:k().optional(),description:k().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),Pe=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),default:k().optional()}),Fe=F({type:B(`string`),title:k().optional(),description:k().optional(),oneOf:P(F({const:k(),title:k()})),default:k().optional()}),Ie=F({type:B(`string`),title:k().optional(),description:k().optional(),enum:P(k()),enumNames:P(k()).optional(),default:k().optional()}),Le=L([Pe,Fe]),Re=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({type:B(`string`),enum:P(k())}),default:P(k()).optional()}),ze=F({type:B(`array`),title:k().optional(),description:k().optional(),minItems:j().optional(),maxItems:j().optional(),items:F({anyOf:P(F({const:k(),title:k()}))}),default:P(k()).optional()}),Be=L([Re,ze]),Ve=L([Ie,Le,Be]),He=L([Ve,Me,Ne,S]),Ue=f.extend({mode:B(`form`).optional(),message:k(),requestedSchema:F({type:B(`object`),properties:R(k(),He),required:P(k()).optional()}).catchall(N())}),We=F({type:B(`ref/resource`),uri:k()}),Ge=F({type:B(`ref/prompt`),name:k()}),Ke=F({uri:k().startsWith(`file://`),name:k().optional(),_meta:R(k(),N()).optional()}),qe=ie.shape,Je=F({experimental:qe.experimental,sampling:qe.sampling,elicitation:qe.elicitation,roots:qe.roots,extensions:qe.extensions}),Ye=ae.shape,Xe=F({experimental:Ye.experimental,logging:Ye.logging,completions:Ye.completions,prompts:Ye.prompts,resources:Ye.resources,tools:Ye.tools,extensions:Ye.extensions}),Ze=I({progressToken:n.optional(),[Wo]:k(),[Go]:ee.optional(),[qo]:Je,[Jo]:o.optional()}),Qe=F({..._.shape,...g.shape,description:k().optional(),inputSchema:I({$schema:k().optional(),type:B(`object`)}),outputSchema:I({$schema:k().optional()}).optional(),annotations:De.optional(),_meta:R(k(),N()).optional()}),$e=F({type:B(`tool_result`),toolUseId:k(),content:P(x),structuredContent:N().optional(),isError:M().optional(),_meta:R(k(),N()).optional()}),et=L([y,b,Se,Ce,$e]),tt=F({role:a,content:L([et,P(et)]),_meta:R(k(),N()).optional()}),nt=k(),rt=I({[Ko]:ee.optional().catch(void 0)}),it=rt.optional();function C(e){return I({_meta:it,resultType:nt.default(`complete`),...e})}let at=C({}),ot=C({nextCursor:r.optional()}),st=C({content:P(x),structuredContent:N().optional(),isError:M().optional()}),ct=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),tools:P(Qe),nextCursor:r.optional()}),lt=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),prompts:P(be),nextCursor:r.optional()}),ut=C({description:k().optional(),messages:P(Ee)}),dt=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),resources:P(me),nextCursor:r.optional()}),ft=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),resourceTemplates:P(he),nextCursor:r.optional()}),pt=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),contents:P(L([de,fe]))}),mt=C({completion:F({values:P(k()).max(100),total:j().int().optional(),hasMore:M().optional()}).loose()}),ht=C({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`])}),gt=C({ttlMs:j().int().min(0).catch(0),cacheScope:z([`public`,`private`]).catch(`private`),supportedVersions:P(k()),capabilities:Xe,instructions:k().optional()}),w=F({messages:P(tt),modelPreferences:Ae.optional(),systemPrompt:k().optional(),includeContext:z([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:P(k()).optional(),metadata:t.optional(),tools:P(Qe).optional(),toolChoice:je.optional()}),_t=F({method:B(`sampling/createMessage`),params:w}),vt=F({method:B(`roots/list`),params:F({_meta:R(k(),N()).optional()}).optional()}),yt=F({...tt.shape,model:k(),stopReason:k().optional()}),bt=F({roots:P(Ke)}),xt=F({action:z([`accept`,`decline`,`cancel`]),content:R(k(),L([k(),j(),M(),P(k())])).optional()}),St=F({mode:B(`url`),message:k(),url:k().url()}),Ct=L([Ue,St]),wt=F({method:B(`elicitation/create`),params:Ct}),Tt=L([_t,vt,wt]),Et=L([yt,bt,xt]),Dt=R(k(),Tt),Ot=R(k(),Et),kt=C({inputRequests:Dt.optional(),requestState:k().optional()}),At={inputResponses:Ot.optional(),requestState:k().optional()},jt=F({_meta:Ze,...At}),Mt=I({progressToken:n.optional()});function Nt(e,t){return F({method:B(e),params:F({_meta:Ze,...t})})}function Pt(e,t){return F({method:B(e),params:F({_meta:Mt.optional(),...t}).optional()})}let T={name:k(),arguments:R(k(),N()).optional(),...At},Ft={cursor:r.optional()},E=Nt(`tools/call`,T),It=Nt(`tools/list`,Ft),Lt=Nt(`prompts/list`,Ft),Rt=Nt(`prompts/get`,{name:k(),arguments:R(k(),k()).optional(),...At}),zt=Nt(`resources/list`,Ft),Bt=Nt(`resources/templates/list`,Ft),Vt=Nt(`resources/read`,{uri:k(),...At}),Ht={ref:L([Ge,We]),argument:F({name:k(),value:k()}),context:F({arguments:R(k(),k()).optional()}).optional()},Ut=Nt(`completion/complete`,Ht),Wt=Nt(`server/discover`,{}),Gt=F({toolsListChanged:M().optional(),promptsListChanged:M().optional(),resourcesListChanged:M().optional(),resourceSubscriptions:P(k()).optional()}),Kt={notifications:Gt},qt=Nt(`subscriptions/listen`,Kt),Jt=rt.extend({"io.modelcontextprotocol/subscriptionId":i}),Yt=I({_meta:Jt,resultType:nt.default(`complete`)}),Xt={"tools/call":Pt(`tools/call`,T),"tools/list":Pt(`tools/list`,Ft),"prompts/get":Pt(`prompts/get`,{name:k(),arguments:R(k(),k()).optional()}),"prompts/list":Pt(`prompts/list`,Ft),"resources/list":Pt(`resources/list`,Ft),"resources/templates/list":Pt(`resources/templates/list`,Ft),"resources/read":Pt(`resources/read`,{uri:k()}),"completion/complete":Pt(`completion/complete`,Ht),"server/discover":Pt(`server/discover`,{}),"subscriptions/listen":Pt(`subscriptions/listen`,Kt)};function Zt(e){return I({_meta:it,...e})}let Qt={"tools/call":Zt({content:P(x),structuredContent:N().optional(),isError:M().optional()}),"tools/list":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),tools:P(Qe),nextCursor:r.optional()}),"prompts/get":Zt({description:k().optional(),messages:P(Ee)}),"prompts/list":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),prompts:P(be),nextCursor:r.optional()}),"resources/list":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),resources:P(me),nextCursor:r.optional()}),"resources/templates/list":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),resourceTemplates:P(he),nextCursor:r.optional()}),"resources/read":Zt({ttlMs:j().int().min(0),cacheScope:z([`public`,`private`]),contents:P(L([de,fe]))}),"completion/complete":Zt({completion:F({values:P(k()).max(100),total:j().int().optional(),hasMore:M().optional()}).loose()}),"server/discover":Zt({ttlMs:j().int().min(0).catch(0),cacheScope:z([`public`,`private`]).catch(`private`),supportedVersions:P(k()),capabilities:Xe,instructions:k().optional()}),"subscriptions/listen":Zt({})},$t=I({"io.modelcontextprotocol/subscriptionId":i.optional()}),en=F({method:B(`notifications/subscriptions/acknowledged`),params:F({_meta:$t.optional(),notifications:Gt})}),tn=F({_meta:$t.optional(),requestId:i,reason:k().optional()}),nn=F({method:B(`notifications/cancelled`),params:tn}),rn={"notifications/cancelled":nn,"notifications/progress":ce,"notifications/message":v,"notifications/resources/updated":ve,"notifications/resources/list_changed":ge,"notifications/tools/list_changed":Oe,"notifications/prompts/list_changed":xe,"notifications/subscriptions/acknowledged":en},an=e=>F({jsonrpc:B(`2.0`),id:L([k(),j().int()]),result:e}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,RequestIdSchema:i,RoleSchema:a,LoggingLevelSchema:o,TaskMetadataSchema:c,RelatedTaskMetadataSchema:l,RequestMetaSchema:u,BaseRequestParamsSchema:d,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:p,NotificationSchema:m,IconSchema:h,IconsSchema:g,BaseMetadataSchema:_,ImplementationSchema:ee,ClientTasksCapabilitySchema:ne,ServerTasksCapabilitySchema:re,ClientCapabilitiesSchema:ie,ServerCapabilitiesSchema:ae,ProgressSchema:oe,ProgressNotificationParamsSchema:se,ProgressNotificationSchema:ce,LoggingMessageNotificationParamsSchema:le,LoggingMessageNotificationSchema:v,ResourceContentsSchema:ue,TextResourceContentsSchema:de,BlobResourceContentsSchema:fe,AnnotationsSchema:pe,ResourceSchema:me,ResourceTemplateSchema:he,ResourceListChangedNotificationSchema:ge,ResourceUpdatedNotificationParamsSchema:_e,ResourceUpdatedNotificationSchema:ve,PromptArgumentSchema:ye,PromptSchema:be,PromptListChangedNotificationSchema:xe,TextContentSchema:y,ImageContentSchema:b,AudioContentSchema:Se,ToolUseContentSchema:Ce,EmbeddedResourceSchema:we,ResourceLinkSchema:Te,ContentBlockSchema:x,PromptMessageSchema:Ee,ToolAnnotationsSchema:De,ToolListChangedNotificationSchema:Oe,ModelHintSchema:ke,ModelPreferencesSchema:Ae,ToolChoiceSchema:je,BooleanSchemaSchema:Me,StringSchemaSchema:Ne,NumberSchemaSchema:S,UntitledSingleSelectEnumSchemaSchema:Pe,TitledSingleSelectEnumSchemaSchema:Fe,LegacyTitledEnumSchemaSchema:Ie,SingleSelectEnumSchemaSchema:Le,UntitledMultiSelectEnumSchemaSchema:Re,TitledMultiSelectEnumSchemaSchema:ze,MultiSelectEnumSchemaSchema:Be,EnumSchemaSchema:Ve,PrimitiveSchemaDefinitionSchema:He,ElicitRequestFormParamsSchema:Ue,ResourceTemplateReferenceSchema:We,PromptReferenceSchema:Ge,RootSchema:Ke,ClientCapabilities2026Schema:Je,ServerCapabilities2026Schema:Xe,RequestMetaEnvelopeSchema:Ze,ToolSchema:Qe,ToolResultContentSchema:$e,SamplingMessageContentBlockSchema:et,SamplingMessageSchema:tt,ResultTypeSchema:nt,ResultMetaSchema:rt,ResultSchema:at,PaginatedResultSchema:ot,CallToolResultSchema:st,ListToolsResultSchema:ct,ListPromptsResultSchema:lt,GetPromptResultSchema:ut,ListResourcesResultSchema:dt,ListResourceTemplatesResultSchema:ft,ReadResourceResultSchema:pt,CompleteResultSchema:mt,CacheableResultSchema:ht,DiscoverResultSchema:gt,CreateMessageRequestParamsSchema:w,CreateMessageRequestSchema:_t,ListRootsRequestSchema:vt,CreateMessageResultSchema:yt,ListRootsResultSchema:bt,ElicitResultSchema:xt,ElicitRequestURLParamsSchema:St,ElicitRequestParamsSchema:Ct,ElicitRequestSchema:wt,InputRequestSchema:Tt,InputResponseSchema:Et,InputRequestsSchema:Dt,InputResponsesSchema:Ot,InputRequiredResultSchema:kt,InputResponseRequestParamsSchema:jt,CallToolRequestSchema:E,ListToolsRequestSchema:It,ListPromptsRequestSchema:Lt,GetPromptRequestSchema:Rt,ListResourcesRequestSchema:zt,ListResourceTemplatesRequestSchema:Bt,ReadResourceRequestSchema:Vt,CompleteRequestSchema:Ut,DiscoverRequestSchema:Wt,SubscriptionFilterSchema:Gt,SubscriptionsListenRequestSchema:qt,SubscriptionsListenResultMetaSchema:Jt,SubscriptionsListenResultSchema:Yt,dispatchRequestSchemas:Xt,dispatchResultSchemas:Qt,NotificationMetaSchema:$t,SubscriptionsAcknowledgedNotificationSchema:en,CancelledNotificationParamsSchema:tn,CancelledNotificationSchema:nn,notificationSchemas2026:rn,JSONRPCResultResponseSchema:an(at),CallToolResultResponseSchema:an(L([st,kt])),ListToolsResultResponseSchema:an(ct),ListPromptsResultResponseSchema:an(lt),GetPromptResultResponseSchema:an(L([ut,kt])),ListResourcesResultResponseSchema:an(dt),ListResourceTemplatesResultResponseSchema:an(ft),ReadResourceResultResponseSchema:an(L([pt,kt])),CompleteResultResponseSchema:an(mt),DiscoverResultResponseSchema:an(gt)}}let dp;function fp(){return dp??=up()}let pp=[`tools/list`,`prompts/list`,`resources/list`,`resources/templates/list`,`resources/read`,`server/discover`];function mp(e){return pp.includes(e)}let hp=Symbol(`modelcontextprotocol.resultCacheHintFallback`);function gp(e,t){if(t===void 0)return e;let n=e[hp];if(n===void 0)return{...e,[hp]:t};let r={},i=n.ttlMs??t.ttlMs;i!==void 0&&(r.ttlMs=i);let a=n.cacheScope??t.cacheScope;return a!==void 0&&(r.cacheScope=a),{...e,[hp]:r}}function _p(e){return e[hp]}function vp(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function yp(e){return e===`public`||e===`private`}function bp(e,t){if(e.ttlMs!==void 0&&!vp(e.ttlMs))throw RangeError(`Invalid cache hint for ${t}: ttlMs must be a non-negative safe integer (got ${String(e.ttlMs)})`);if(e.cacheScope!==void 0&&!yp(e.cacheScope))throw RangeError(`Invalid cache hint for ${t}: cacheScope must be 'public' or 'private' (got ${String(e.cacheScope)})`)}let Z=function(e){return e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.ResourceNotFound=-32002]=`ResourceNotFound`,e[e.MissingRequiredClientCapability=-32021]=`MissingRequiredClientCapability`,e[e.UnsupportedProtocolVersion=-32022]=`UnsupportedProtocolVersion`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`,e}({});var Q=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ProtocolError`})}static[Symbol.hasInstance](e){return Of(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 Of(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`ProtocolError`,Df(this,new.target)}static fromError(t,n,r){if(t===Z.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Sp(e.elicitations,n)}if(t===Z.UnsupportedProtocolVersion&&r){let e=r;if(Array.isArray(e.supported)&&typeof e.requested==`string`)return new Cp({supported:e.supported,requested:e.requested},n)}if(t===Z.InvalidParams||t===Z.ResourceNotFound){let e=r;if(typeof e?.uri==`string`&&(t===Z.ResourceNotFound||Object.keys(e).length===1))return new xp(e.uri,n)}if(t===Z.MissingRequiredClientCapability&&r){let e=r;if(e.requiredCapabilities!==null&&typeof e.requiredCapabilities==`object`&&!Array.isArray(e.requiredCapabilities))return new wp({requiredCapabilities:e.requiredCapabilities},n)}return new e(t,n,r)}},xp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ResourceNotFoundError`})}constructor(e,t=`Resource not found: ${e}`){super(Z.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Sp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UrlElicitationRequiredError`})}constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Z.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Cp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UnsupportedProtocolVersionError`})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(Z.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},wp=class extends Q{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.MissingRequiredClientCapabilityError`})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(`, `)}`){super(Z.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}};let Tp=[`tools/call`,`prompts/get`,`resources/read`];function Ep(e,t){let n=t.resultType;if(n===void 0)return{...t,resultType:`complete`};if(n===`complete`||Tp.includes(e))return t;throw new Q(Z.InternalError,`Handler for ${e} returned resultType '${String(n)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function Dp(e,t){let n=_p(t);if(t.resultType!==`complete`||!mp(e))return n===void 0?t:Mp(t);let r=t,i=vp(r.ttlMs)?r.ttlMs:Ap(n),a=yp(r.cacheScope)?r.cacheScope:jp(n),o={...r,ttlMs:i,cacheScope:a};return delete o[hp],o}function Op(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kp(e,t){if(t===void 0)return e;let n=e._meta;return n===void 0?{...e,_meta:{[Ko]:t}}:!Op(n)||n[`io.modelcontextprotocol/serverInfo`]!==void 0?e:{...e,_meta:{...n,[Ko]:t}}}function Ap(e){return e!==void 0&&vp(e.ttlMs)?e.ttlMs:0}function jp(e){return e!==void 0&&yp(e.cacheScope)?e.cacheScope:`private`}function Mp(e){let t={...e};return delete t[hp],t}let Np=[`elicitation/create`,`sampling/createMessage`,`roots/list`],Pp;function Fp(){if(Pp)return Pp;let e=fp();return Pp={request:{"elicitation/create":F({method:B(`elicitation/create`),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":F({method:B(`sampling/createMessage`),params:e.CreateMessageRequestParamsSchema}),"roots/list":F({method:B(`roots/list`),params:I({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Pp}function Ip(e){return Np.includes(e)}function Lp(e){return Ip(e)?Fp().request[e]:void 0}function Rp(e){return Ip(e)?Fp().response[e]:void 0}let zp={"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},Bp={"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 Vp(e){return Object.prototype.hasOwnProperty.call(zp,e)}function Hp(e){return Object.prototype.hasOwnProperty.call(Bp,e)}function Up(e){return Object.prototype.hasOwnProperty.call(zp,e)}function Wp(e){return Vp(e)?fp().dispatchRequestSchemas[e]:void 0}function Gp(e){return Up(e)?fp().dispatchResultSchemas[e]:void 0}function Kp(e){return Hp(e)?fp().notificationSchemas2026[e]:void 0}function qp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jp(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}let Yp={ok:!1,reason:`not-in-era`},Xp=[Wo,qo];function Zp(e,t){let n=t,r=!1,i=()=>(r||=(n={...n},!0),n),a=t.tools;e===`tools/list`&&Array.isArray(a)&&a.some(e=>qp(e)&&`execution`in e)&&(i().tools=a.map(e=>{if(!qp(e)||!(`execution`in e))return e;let t={...e};return delete t.execution,t}));let o=t.capabilities;if(qp(o)&&`tasks`in o){let e={...o};delete e.tasks,i().capabilities=e}return n}let Qp={era:`2026-07-28`,hasRequestMethod:Vp,hasNotificationMethod:Hp,hasInputRequestMethod:e=>Lp(e)!==void 0,validateRequest:(e,t)=>Jp(Wp(e),t),validateResult:(e,t)=>Jp(Gp(e),t),validateNotification:(e,t)=>Jp(Kp(e),t),validateInputRequest:(e,t)=>Jp(Lp(e),t),validateInputResponse:(e,t)=>Jp(Rp(e),t),samplingResultVariant:()=>Yp,outboundEnvelope(e){return{[Wo]:e.protocolVersion,[Go]:e.clientInfo,[qo]:e.clientCapabilities,...e.logLevel!==void 0&&{"io.modelcontextprotocol/logLevel":e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of Xp)n in e||t.push({key:n,problem:`missing`});let n=fp().RequestMetaEnvelopeSchema.safeParse(e);if(!n.success)for(let e of n.error.issues){let n=e.path.map(String),r=n.length>0?n.join(`.`):`_meta`;n.length===1&&t.some(e=>e.key===r&&e.problem===`missing`)||t.push({key:r,problem:e.message})}return t},projectCallToolResult:e=>If(e),inputRequestSchema:Lp,decodeResult(e,t){if(!qp(t))return{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let n=t.resultType;if(n===void 0)return{kind:`invalid`,error:new X(Y.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 n!=`string`)return{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:n})};if(n===`input_required`){let n=t.inputRequests,r=qp(n)?n:{},i=t.requestState;return Object.keys(r).length===0&&typeof i!=`string`?{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:`input-required-missing-both`})}:{kind:`input_required`,inputRequests:r,...typeof i==`string`&&{requestState:i}}}if(n!==`complete`)return{kind:`invalid`,error:new X(Y.UnsupportedResultType,`Unsupported result type '${n}' for ${e}`,{resultType:n,method:e})};let r=em(),i=Object.hasOwn(r,e)?r[e]:void 0;if(i!==void 0){let n=i.safeParse(t);if(!n.success)return{kind:`invalid`,error:new X(Y.InvalidResult,`Invalid result for ${e}: ${n.error}`,{method:e})}}let a={...t};return delete a.resultType,{kind:`complete`,result:a}},encodeResult(e,t,n){return kp(Dp(e,Ep(e,Zp(e,t))),n)},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=fp().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(e=>e.message).join(`; `)}`}},$p;function em(){if($p)return $p;let e=fp();return $p={"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},$p}function tm(e){return e!==void 0&&Nf(e)?Qp:lp}function nm(e){return e.revision===void 0?e.era===`modern`?Qp.era:lp.era:tm(e.revision).era}function rm(e){return am.some(t=>t.hasRequestMethod(e))}function im(e){return am.some(t=>t.hasNotificationMethod(e))}let am=[lp,Qp];var om=yf({AnnotationsSchema:()=>Us,AudioContentSchema:()=>Sc,BaseMetadataSchema:()=>vs,BaseRequestParamsSchema:()=>U,BlobResourceContentsSchema:()=>Vs,BooleanSchemaSchema:()=>rl,CallToolRequestParamsSchema:()=>Lc,CallToolRequestSchema:()=>Rc,CallToolResultSchema:()=>Fc,CancelTaskRequestSchema:()=>Ul,CancelTaskResultSchema:()=>Wl,CancelledNotificationParamsSchema:()=>ms,CancelledNotificationSchema:()=>hs,ClientCapabilitiesSchema:()=>Cs,ClientNotificationSchema:()=>Kl,ClientRequestSchema:()=>Gl,ClientResultSchema:()=>ql,ClientTasksCapabilitySchema:()=>xs,CompatibilityCallToolResultSchema:()=>Ic,CompleteRequestParamsSchema:()=>wl,CompleteRequestSchema:()=>Tl,CompleteResultSchema:()=>El,ContentBlockSchema:()=>Ec,CreateMessageRequestParamsSchema:()=>$c,CreateMessageRequestSchema:()=>el,CreateMessageResultSchema:()=>tl,CreateMessageResultWithToolsSchema:()=>nl,CreateTaskResultSchema:()=>Pl,CursorSchema:()=>Qo,DiscoverRequestSchema:()=>ks,DiscoverResultSchema:()=>As,ElicitRequestFormParamsSchema:()=>hl,ElicitRequestParamsSchema:()=>_l,ElicitRequestSchema:()=>vl,ElicitRequestURLParamsSchema:()=>gl,ElicitResultSchema:()=>xl,ElicitationCompleteNotificationParamsSchema:()=>yl,ElicitationCompleteNotificationSchema:()=>bl,EmbeddedResourceSchema:()=>wc,EmptyResultSchema:()=>ps,EnumSchemaSchema:()=>pl,GetPromptRequestParamsSchema:()=>vc,GetPromptRequestSchema:()=>yc,GetPromptResultSchema:()=>Oc,GetTaskPayloadRequestSchema:()=>zl,GetTaskPayloadResultSchema:()=>Bl,GetTaskRequestSchema:()=>Ll,GetTaskResultSchema:()=>Rl,IconSchema:()=>gs,IconsSchema:()=>_s,ImageContentSchema:()=>xc,ImplementationSchema:()=>ys,InitializeRequestParamsSchema:()=>ws,InitializeRequestSchema:()=>Ts,InitializeResultSchema:()=>Ds,InitializedNotificationSchema:()=>Os,JSONArraySchema:()=>Xo,JSONObjectSchema:()=>H,JSONRPCErrorResponseSchema:()=>us,JSONRPCMessageSchema:()=>ds,JSONRPCNotificationSchema:()=>cs,JSONRPCRequestSchema:()=>ss,JSONRPCResponseSchema:()=>fs,JSONRPCResultResponseSchema:()=>ls,JSONValueSchema:()=>Yo,LegacyTitledEnumSchemaSchema:()=>cl,ListChangedOptionsBaseSchema:()=>Bc,ListPromptsRequestSchema:()=>gc,ListPromptsResultSchema:()=>_c,ListResourceTemplatesRequestSchema:()=>Js,ListResourceTemplatesResultSchema:()=>Ys,ListResourcesRequestSchema:()=>Ks,ListResourcesResultSchema:()=>qs,ListRootsRequestSchema:()=>Ol,ListRootsResultSchema:()=>kl,ListTasksRequestSchema:()=>Vl,ListTasksResultSchema:()=>Hl,ListToolsRequestSchema:()=>Nc,ListToolsResultSchema:()=>Pc,LoggingLevelSchema:()=>Vc,LoggingMessageNotificationParamsSchema:()=>Wc,LoggingMessageNotificationSchema:()=>Gc,ModelHintSchema:()=>Kc,ModelPreferencesSchema:()=>qc,MultiSelectEnumSchemaSchema:()=>fl,NotificationSchema:()=>is,NotificationsParamsSchema:()=>rs,NumberSchemaSchema:()=>al,PaginatedRequestParamsSchema:()=>Fs,PaginatedRequestSchema:()=>Is,PaginatedResultSchema:()=>Ls,PingRequestSchema:()=>js,PrimitiveSchemaDefinitionSchema:()=>ml,ProgressNotificationParamsSchema:()=>Ns,ProgressNotificationSchema:()=>Ps,ProgressSchema:()=>Ms,ProgressTokenSchema:()=>Zo,PromptArgumentSchema:()=>mc,PromptListChangedNotificationSchema:()=>kc,PromptMessageSchema:()=>Dc,PromptReferenceSchema:()=>Cl,PromptSchema:()=>hc,ReadResourceRequestParamsSchema:()=>Zs,ReadResourceRequestSchema:()=>Qs,ReadResourceResultSchema:()=>$s,RelatedTaskMetadataSchema:()=>es,RequestIdSchema:()=>os,RequestMetaSchema:()=>ts,RequestSchema:()=>W,ResourceContentsSchema:()=>Rs,ResourceLinkSchema:()=>Tc,ResourceListChangedNotificationSchema:()=>ec,ResourceRequestParamsSchema:()=>Xs,ResourceSchema:()=>Ws,ResourceTemplateReferenceSchema:()=>Sl,ResourceTemplateSchema:()=>Gs,ResourceUpdatedNotificationParamsSchema:()=>fc,ResourceUpdatedNotificationSchema:()=>pc,ResultMetaObjectSchema:()=>as,ResultSchema:()=>G,RoleSchema:()=>Hs,RootSchema:()=>Dl,RootsListChangedNotificationSchema:()=>Al,SamplingContentSchema:()=>Xc,SamplingMessageContentBlockSchema:()=>Zc,SamplingMessageSchema:()=>Qc,ServerCapabilitiesSchema:()=>Es,ServerNotificationSchema:()=>Yl,ServerRequestSchema:()=>Jl,ServerResultSchema:()=>Xl,ServerTasksCapabilitySchema:()=>Ss,SetLevelRequestParamsSchema:()=>Hc,SetLevelRequestSchema:()=>Uc,SingleSelectEnumSchemaSchema:()=>ll,StringSchemaSchema:()=>il,SubscribeRequestParamsSchema:()=>tc,SubscribeRequestSchema:()=>nc,SubscriptionFilterSchema:()=>ac,SubscriptionsAcknowledgedNotificationParamsSchema:()=>cc,SubscriptionsAcknowledgedNotificationSchema:()=>lc,SubscriptionsListenRequestParamsSchema:()=>oc,SubscriptionsListenRequestSchema:()=>sc,SubscriptionsListenResultMetaSchema:()=>uc,SubscriptionsListenResultSchema:()=>dc,TaskAugmentedRequestParamsSchema:()=>ns,TaskCreationParamsSchema:()=>jl,TaskMetadataSchema:()=>$o,TaskSchema:()=>Nl,TaskStatusNotificationParamsSchema:()=>Fl,TaskStatusNotificationSchema:()=>Il,TaskStatusSchema:()=>Ml,TextContentSchema:()=>bc,TextResourceContentsSchema:()=>zs,TitledMultiSelectEnumSchemaSchema:()=>dl,TitledSingleSelectEnumSchemaSchema:()=>sl,ToolAnnotationsSchema:()=>Ac,ToolChoiceSchema:()=>Jc,ToolExecutionSchema:()=>jc,ToolListChangedNotificationSchema:()=>zc,ToolResultContentSchema:()=>Yc,ToolSchema:()=>Mc,ToolUseContentSchema:()=>Cc,UnsubscribeRequestParamsSchema:()=>rc,UnsubscribeRequestSchema:()=>ic,UntitledMultiSelectEnumSchemaSchema:()=>ul,UntitledSingleSelectEnumSchemaSchema:()=>ol});let sm=e=>ss.safeParse(e).success,cm=e=>cs.safeParse(e).success,lm=e=>ls.safeParse(e).success,um=e=>us.safeParse(e).success,dm=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&e.resultType===`input_required`;function fm(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function pm(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}let mm=`x-mcp-header`,hm=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,gm=new Set([`string`,`integer`,`boolean`,`number`]);function _m(e){let t=[],n=new Map,r=(e,i,a)=>{if(typeof e!=`object`||!e)return;let o=e;if(mm in o){if(!a||i.length===0)return`${bm(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let e=o[mm];if(typeof e!=`string`||e.length===0)return`${bm(i)}: x-mcp-header MUST be a non-empty string`;if(!hm.test(e))return`${bm(i)}: x-mcp-header '${e}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let r=typeof o.type==`string`?o.type:void 0;if(r===void 0||!gm.has(r))return`${bm(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${r??`<none>`}`;let s=e.toLowerCase(),c=n.get(s);if(c!==void 0)return`x-mcp-header '${e}' is not case-insensitively unique (also declared as '${c}')`;n.set(s,e),t.push({path:i,headerName:e,type:r})}let s=o.properties;if(typeof s==`object`&&s)for(let[e,t]of Object.entries(s)){let n=r(t,[...i,e],a);if(n!==void 0)return n}for(let e of vm){let t=o[e];if(t===void 0)continue;let n=Array.isArray(t)?t:typeof t==`object`&&t&&ym.has(e)?Object.values(t):[t];for(let t of n){let n=r(t,[...i,`<${e}>`],!1);if(n!==void 0)return n}}},i=r(e,[],!0);return i===void 0?{valid:!0,declarations:t}:{valid:!1,reason:i}}let vm=[`items`,`prefixItems`,`contains`,`additionalProperties`,`unevaluatedProperties`,`unevaluatedItems`,`propertyNames`,`patternProperties`,`dependentSchemas`,`oneOf`,`anyOf`,`allOf`,`not`,`if`,`then`,`else`,`$defs`,`definitions`],ym=new Set([`patternProperties`,`dependentSchemas`,`$defs`,`definitions`]);function bm(e){return e.length===0?`<root>`:e.join(`.`)}Z.InvalidRequest,Z.UnsupportedProtocolVersion,Z.InvalidParams,Z.MethodNotFound,Z.InvalidParams,Z.MissingRequiredClientCapability,Z.ParseError,Z.InvalidRequest,Z.MethodNotFound,Z.UnsupportedProtocolVersion,Z.MissingRequiredClientCapability;function xm(e,t){return da(e,t)}function Sm(e){return new Set(e.flatMap(e=>Object.keys(e.shape)))}function Cm(e){if(e==null)return!1;let t=typeof e;return t!==`object`&&t!==`function`||!(`~standard`in e)?!1:typeof e[`~standard`]?.validate==`function`}let wm=!1,Tm=`draft-2020-12`;function Em(e,t=`input`){let n=e[`~standard`],r;if(n.jsonSchema)r=n.jsonSchema[t]({target:Tm});else if(n.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().`);wm||(wm=!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.")),r=$i(e,{target:Tm,io:t})}else throw Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t===`output`)return r.type===void 0&&Dm(r)?{type:`object`,...r}:r;if(r.type!==void 0&&r.type!==`object`)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(r.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:`object`,...r}}function Dm(e){if(`properties`in e||`patternProperties`in e||`additionalProperties`in e||`required`in e)return!0;for(let t of[`oneOf`,`anyOf`,`allOf`]){let n=e[t];if(Array.isArray(n)&&n.length>0)return n.every(e=>typeof e==`object`&&!!e&&(e.type===`object`||Dm(e)))}return!1}function Om(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function km(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>Om(e)).join(`, `)}:{success:!0,data:n.value}}function Am(e){let t=$i(e,{target:Tm,io:`input`});return typeof t.pattern==`string`?t.pattern:void 0}let jm=/\\\.\\d\{(\d+)\}/;function Mm(e){let t=jm.exec(e),n=[void 0,-1,0];return t&&n.push(Number(t[1])),[!1,!0].flatMap(e=>[!1,!0].flatMap(t=>n.map(n=>ta({local:e,offset:t,precision:n}))))}function Nm(e,t){let n;switch(e){case`email`:n=[Ea()];break;case`uri`:n=[Aa()];break;case`date`:n=[ra()];break;case`date-time`:n=Mm(t);break}return new Set(n.map(e=>Am(e)).filter(e=>e!==void 0))}function Pm(e,t,n){return n===`zod`?Nm(e,t).has(t):!0}function Fm(e){let t=Em(e,`input`),n=t.properties||{},r=t.required||[];return Object.entries(n).map(([e,t])=>({name:e,description:t?.description,required:r.includes(e)}))}function Im(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lm(e){try{return Em(e,`input`)}catch(e){let t=e instanceof Error?e.message:String(e);throw new Q(Z.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${t}`)}}let Rm=new Set([`$comment`,`deprecated`,`description`,`examples`,`readOnly`,`title`,`writeOnly`]);function zm(e){return Rm.has(e)||e.startsWith(`x-`)}let Bm=new Set([`$schema`,...Object.keys(hl.shape.requestedSchema.shape)]),Vm={string:Sm([il,ol,sl,cl]),number:Sm([al]),integer:Sm([al]),boolean:Sm([rl]),array:Sm([ul,dl])},Hm=new Set(il.shape.format.unwrap().options);function Um(e,t,n,r){if(!Im(e))return e;let i=typeof e.type==`string`&&Object.hasOwn(Vm,e.type)?Vm[e.type]:void 0;if(i===void 0)return e;let a={};for(let[o,s]of Object.entries(e))i.has(o)||zm(o)?a[o]=s:o===`pattern`&&e.type===`string`&&typeof e.format==`string`?Hm.has(e.format)?(typeof s!=`string`||!Pm(e.format,s,n))&&r.push(`${t}.${o}`):a[o]=s:r.push(`${t}.${o}`);return a}function Wm(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))i===`properties`&&Im(a)?n[i]=Object.fromEntries(Object.entries(a).map(([e,n])=>[e,Um(n,`properties.${e}`,t,r)])):Bm.has(i)?n[i]=a:zm(i)||r.push(i);if(r.length>0)throw new Q(Z.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${r.join(`, `)}`);return n}function Gm(e,t){if(!Im(e.properties))return t;let n=Object.entries(e.properties).filter(([,e])=>!xm(ml,e).success).map(([e])=>`properties.${e}`);return n.length>0?n.join(`, `):t}function Km(e,t,n=``){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((e,r)=>Km(e,t[r],`${n}[${r}]`)):!Im(e)||!Im(t)?[]:Object.entries(e).flatMap(([e,r])=>{let i=n?`${n}.${e}`:e;return Object.prototype.hasOwnProperty.call(t,e)?Km(r,t[e],i):zm(e)?[]:[i]})}function qm(e){if(!Cm(e.requestedSchema))return{...e,mode:`form`,requestedSchema:e.requestedSchema};let t=e.requestedSchema[`~standard`].vendor,n=Wm(Lm(e.requestedSchema),t),r=xm(hl.shape.requestedSchema,n);if(!r.success)throw new Q(Z.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Gm(n,r.error.message)}`);let i=Km(n,r.data);if(i.length>0)throw new Q(Z.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${i.join(`, `)}`);let a=(r.data.required??[]).filter(e=>!Object.prototype.hasOwnProperty.call(r.data.properties,e));if(a.length>0)throw new Q(Z.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${a.join(`, `)}`);return{...e,mode:`form`,requestedSchema:r.data}}function Jm(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,n=typeof e.requestState==`string`;if(!t&&!n)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}}}Object.assign(Jm,{elicit(e){try{return{method:`elicitation/create`,params:qm(e)}}catch(e){throw e instanceof Q?TypeError(e.message,{cause:e}):e}},elicitUrl(e){return{method:`elicitation/create`,params:{...e,mode:`url`}}},createMessage(e){return{method:`sampling/createMessage`,params:e}},listRoots(){return{method:`roots/list`}}});function Ym(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Xm(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason instanceof X?t.reason:new X(Y.RequestTimeout,String(t.reason)));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(t?.reason instanceof X?t.reason:new X(Y.RequestTimeout,String(t?.reason)))};t?.addEventListener(`abort`,a,{once:!0})})}function Zm(e){let t=new AbortController,n=()=>t.abort(e?.reason);return e?.addEventListener(`abort`,n,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:e=>t.abort(e),dispose:()=>e?.removeEventListener(`abort`,n)}}let Qm=`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`.split(`.`),$m={IdJagTokenExchangeResponseSchema:nu,OAuthClientInformationFullSchema:su,OAuthClientInformationSchema:ou,OAuthClientMetadataSchema:au,OAuthClientRegistrationErrorSchema:cu,OAuthErrorResponseSchema:ru,OAuthMetadataSchema:Ql,OAuthProtectedResourceMetadataSchema:Zl,OAuthTokenRevocationRequestSchema:lu,OAuthTokensSchema:tu,OpenIdProviderDiscoveryMetadataSchema:eu,OpenIdProviderMetadataSchema:$l},eh={},th={};function nh(e,t){let n=e.slice(0,-6);eh[n]=t,th[n]=e=>t.safeParse(e).success}for(let e of Qm)nh(e,om[e]);for(let[e,t]of Object.entries($m))nh(e,t);Object.freeze(eh),Object.freeze(th);function rh(e){switch(e){case`initialize`:case`notifications/initialized`:return tm(void 0);case`server/discover`:return tm(`2026-07-28`);default:return}}let ih=[Wo,Go,qo,Jo],ah=[`inputResponses`,`requestState`];function oh(e,t){let n=e.params;if(!fh(n))return{message:e,lifted:{}};let r=n._meta,i=fh(r)?ih.filter(e=>e in r):[],a=t===`request`?ah.filter(e=>e in n):[];if(i.length===0&&a.length===0)return{message:e,lifted:{}};let o={},s={...n};if(i.length>0&&fh(r)){let e={},t={...r};for(let n of i)e[n]=r[n],delete t[n];o.envelope=e,Object.keys(t).length>0?s._meta=t:delete s._meta}for(let e of a)e===`inputResponses`&&(o.inputResponses=s[e]),e===`requestState`&&(o.requestState=s[e]),delete s[e];return{message:{...e,params:s},lifted:o}}function sh(e,t){let n=e.validateResult(t,void 0);if(!(!n.ok&&n.reason===`not-in-era`))return{"~standard":{version:1,vendor:`mcp-wire-codec`,validate(n){let r=e.validateResult(t,n);return r.ok?{value:r.value}:{issues:[{message:r.reason===`invalid`?r.message:`not-in-era: ${t}`}]}}}}}function ch(e){return()=>e}let lh=ch(void 0);function uh(e,t){return{...e,mcpReq:{...e.mcpReq,requestState:ch(t)}}}var dh=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Uo,this.setNotificationHandler(`notifications/cancelled`,e=>{this._oncancel(e)}),this.setNotificationHandler(`notifications/progress`,e=>{this._onprogress(e)}),this.setRequestHandler(`ping`,e=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let n=e.params??{};return{...e,params:{...n,_meta:{...t,...n._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new X(Y.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new X(Y.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),lm(e)||um(e)?this._onresponse(e):sm(e)?this._onrequest(e,t):cm(e)?this._onnotification(e,t):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new X(Y.ConnectionClosed,`Connection closed`);this._transport=void 0;try{this.onclose?.()}finally{for(let t of e.values())t(n);for(let e of t.values())e.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:n}=oh(e,`notification`),r=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`)return;if(t?.classification!==void 0){let e=nm(t.classification);if(e!==r.era){this._onerror(Error(`Era mismatch on inbound notification '${n.method}': classified as ${e} but this instance serves ${r.era}`));return}}if(im(n.method)&&!r.hasNotificationMethod(n.method))return;let i=this._notificationHandlers.get(n.method),a=this.fallbackNotificationHandler;i===void 0&&a===void 0||Promise.resolve().then(()=>i===void 0?a(n):i(n,r)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let{message:n,lifted:r}=oh(e,`request`),i=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 a=this._transport,o=(e,t,r)=>{let i={jsonrpc:`2.0`,id:n.id,error:{code:e,message:t,...r!==void 0&&{data:r}}};a?.send(i).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))};if(t?.classification!==void 0){let e=nm(t.classification);if(e!==i.era){this._onerror(Error(`Era mismatch on inbound request '${n.method}': classified as ${e} but this instance serves ${i.era}`));let r=t.classification.revision??e;o(Z.UnsupportedProtocolVersion,`Unsupported protocol version: ${r}`,{supported:this._supportedProtocolVersions,requested:r});return}}if(rm(n.method)&&!i.hasRequestMethod(n.method)){o(Z.MethodNotFound,`Method not found`);return}let s=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(s===void 0){o(Z.MethodNotFound,`Method not found`);return}let c=i.checkInboundEnvelope(r);if(c!==void 0){o(Z.InvalidParams,c);return}let l=(e,t)=>this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,{...t,relatedRequestId:n.id}),u=(e,t,r)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(e.method),e,t,{...r,relatedRequestId:n.id}),d=new AbortController;this._requestHandlerAbortControllers.set(n.id,d);let f=r.inputResponses===void 0?void 0:hh(r.inputResponses),p={sessionId:a?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...r.envelope!==void 0&&{envelope:r.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:r.requestState===void 0?lh:ch(r.requestState),signal:d.signal,send:((e,t,n)=>{let r=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(r,e.method),Cm(t))return u(e,t,n);let i=sh(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return u(e,i,t)}),notify:l},http:t?.authInfo?{authInfo:t.authInfo}:void 0},m=this.buildContext(p,t);Promise.resolve().then(()=>s(n,m)).then(async e=>{if(d.signal.aborted)return;let t;try{t=i.encodeResult(n.method,e,this._outboundServerInfo())}catch(e){this._onerror(Error(`Failed to encode result for ${n.method}: ${e}`)),o(Z.InternalError,`Internal error`);return}let r={result:t,jsonrpc:`2.0`,id:n.id};await a?.send(r)},async e=>{if(d.signal.aborted)return;let t=Number.isSafeInteger(e.code)?e.code:Z.InternalError,r={jsonrpc:`2.0`,id:n.id,error:{code:i.encodeErrorCode(t),message:e.message??`Internal error`,...e.data!==void 0&&{data:e.data}}};await a?.send(r)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===d&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),lm(e)?n(e):n(Q.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,n){let r=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(r,e.method),Cm(t))return this._requestWithSchemaViaCodec(r,e,t,n);let i=sh(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(r,e,i,t)}_negotiatedWireCodec(){return tm(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=rh(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(rm(t)&&!e.hasRequestMethod(t))throw new X(Y.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,n){let r=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(r,e.method),this._requestWithSchemaViaCodec(r,e,t,n)}_requestWithSchemaViaCodec(e,t,n,r){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s}=r??{},c=Date.now(),l,u;return new Promise((d,f)=>{let p=e=>{f(e)};if(!this._transport){p(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(e){p(e);return}if(r?.signal?.aborted){let e=r.signal.reason;throw e instanceof X?e:new X(Y.RequestTimeout,String(e))}let m=e.era===`2026-07-28`&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,h=this._requestMessageId++;u=h;let g={...t,jsonrpc:`2.0`,id:h};r?.onprogress&&(this._progressHandlers.set(h,r.onprogress),g.params={...t.params,_meta:{...t.params?._meta,progressToken:h}});let _=this._envelopeOutbound(g),ee=!1,te=e=>{ee||(this._progressHandlers.delete(h),m===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:h,reason:String(e)}}),{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))):m.abort(),f(e instanceof X?e:new X(Y.RequestTimeout,String(e))))};this._responseHandlers.set(h,i=>{if(r?.signal?.aborted)return;if(ee=!0,i instanceof Error)return f(i);let a;try{a=e.decodeResult(t.method,i.result)}catch(e){return f(e instanceof Error?e:Error(String(e)))}if(a.kind===`invalid`)return f(a.error);if(a.kind===`input_required`){if(r?.allowInputRequired===!0)return d(gh(a));let i={codec:e,request:t,resultSchema:n,options:r,flowStartedAt:c,retry:(r,i)=>this._requestWithSchemaViaCodec(e,r===void 0?{method:t.method}:{method:t.method,params:r},n,i)};return d(this._resolveNonCompleteResult(a,i))}let o=a.result;km(n,o).then(e=>{e.success?d(e.data):f(new X(Y.InvalidResult,`Invalid result for ${t.method}: ${e.error}`))},f)}),l=()=>te(r?.signal?.reason),r?.signal?.addEventListener(`abort`,l,{once:!0});let ne=r?.timeout??6e4;this._setupTimeout(h,ne,r?.maxTotalTimeout,()=>te(new X(Y.RequestTimeout,`Request timed out`,{timeout:ne})),r?.resetTimeoutOnProgress??!1),this._transport.send(_,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s,requestSignal:m?.signal}).catch(e=>{this._progressHandlers.delete(h),f(e)})}).finally(()=>{l&&r?.signal?.removeEventListener(`abort`,l),u!==void 0&&(this._responseHandlers.delete(u),this._cleanupTimeout(u))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,n){if(!this._transport)throw new X(Y.NotConnected,`Not connected`);if(im(t.method)&&!e.hasNotificationMethod(t.method))throw new X(Y.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 r=this._envelopeOutbound({jsonrpc:`2.0`,...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!n?.relatedRequestId){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(r,n).catch(e=>this._onerror(e))});return}await this._transport.send(r,n)}setRequestHandler(e,t,n){this.assertRequestHandlerCapability(e);let r;if(typeof t==`function`){if(!rm(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);r=(n,r)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason===`not-in-era`&&(a=i.validateInputRequest(e,n)),!a.ok)throw a.reason===`not-in-era`?new Q(Z.InternalError,`No wire schema for ${e} in the resolved era`):Error(a.message);return Promise.resolve(t(a.value,r))}}else if(n)r=async(r,i)=>{let a=await km(t.params,{...r.params});if(!a.success)throw new Q(Z.InvalidParams,`Invalid params for ${e}: ${a.error}`);return n(a.data,i)};else throw TypeError(`setRequestHandler: handler is required`);this._requestHandlers.set(e,this._wrapHandler(e,r))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,n){if(typeof t==`function`){if(!im(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,r)=>{let i=r.validateNotification(e,n);if(!i.ok)throw i.reason===`not-in-era`?new Q(Z.InternalError,`No wire schema for ${e} in the resolved era`):Error(i.message);return Promise.resolve(t(i.value))});return}if(!n)throw TypeError(`setNotificationHandler: handler is required`);this._notificationHandlers.set(e,async r=>{let i=await km(t.params,{...r.params});if(!i.success)throw new Q(Z.InvalidParams,`Invalid params for notification ${e}: ${i.error}`);await n(i.data,r)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function fh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ph(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=fh(a)&&fh(i)?{...a,...i}:i}return n}function mh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hh(e){let t={},n=[];if(!mh(e))return{accepted:t,droppedKeys:n};for(let[r,i]of Object.entries(e)){if(!mh(i)||`method`in i||`result`in i){n.push(r);continue}t[r]=i}return{accepted:t,droppedKeys:n}}function gh(e){return{resultType:`input_required`,inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}
|
|
65
70
|
/*!
|
|
66
71
|
* content-type
|
|
67
72
|
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
68
73
|
* MIT Licensed
|
|
69
74
|
*/
|
|
70
|
-
af((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,n=/\\([\u000b\u0020-\u00ff])/g,r=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=i;function i(e){if(!e)throw TypeError(`argument string is required`);var i=typeof e==`object`?a(e):e;if(typeof i!=`string`)throw TypeError(`argument string is required to be a string`);var s=i.indexOf(`;`),c=s===-1?i.trim():i.slice(0,s).trim();if(!r.test(c))throw TypeError(`invalid media type`);var l=new o(c.toLowerCase());if(s!==-1){var u,d,f;for(t.lastIndex=s;d=t.exec(i);){if(d.index!==s)throw TypeError(`invalid parameter format`);s+=d[0].length,u=d[1].toLowerCase(),f=d[2],f.charCodeAt(0)===34&&(f=f.slice(1,-1),f.indexOf(`\\`)!==-1&&(f=f.replace(n,`$1`))),l.parameters[u]=f}if(s!==i.length)throw TypeError(`invalid parameter format`)}return l}function a(e){var t;if(typeof e.getHeader==`function`?t=e.getHeader(`content-type`):typeof e.headers==`object`&&(t=e.headers&&e.headers[`content-type`]),typeof t!=`string`)throw TypeError(`content-type header is missing from object`);return t}function o(e){this.parameters=Object.create(null),this.type=e}}))();let ih=/^[A-Za-z0-9._-]{1,128}$/;function ah(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!ih.test(e)){let n=[...e].filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function oh(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function sh(e){let t=ah(e);return oh(e,t.warnings),t.isValid}let ch=1e6,lh=1e6,uh=1e4;var dh=class e{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,n){if(e.length>t)throw Error(`${n} exceeds maximum length of ${t} characters (got ${e.length})`)}template;parts;get variableNames(){return this.parts.flatMap(e=>typeof e==`string`?[]:e.names)}constructor(t){e.validateLength(t,ch,`Template`),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){let n=[],r=``,i=0,a=0;for(;i<t.length;)if(t[i]===`{`){r&&=(n.push(r),``);let o=t.indexOf(`}`,i);if(o===-1)throw Error(`Unclosed template expression`);if(a++,a>uh)throw Error(`Template contains too many expressions (max ${uh})`);let s=t.slice(i+1,o),c=this.getOperator(s),l=s.includes(`*`),u=this.getNames(s),d=u[0];for(let t of u)e.validateLength(t,lh,`Variable name`);n.push({name:d,operator:c,names:u,exploded:l}),i=o+1}else r+=t[i],i++;return r&&n.push(r),n}getOperator(e){return[`+`,`#`,`.`,`/`,`?`,`&`].find(t=>e.startsWith(t))||``}getNames(e){let t=this.getOperator(e);return e.slice(t.length).split(`,`).map(e=>e.replace(`*`,``).trim()).filter(e=>e.length>0)}encodeValue(t,n){return e.validateLength(t,lh,`Variable value`),n===`+`||n===`#`?encodeURI(t):encodeURIComponent(t)}expandPart(e,t){if(e.operator===`?`||e.operator===`&`){let n=e.names.map(n=>{let r=t[n];return r===void 0?``:`${n}=${Array.isArray(r)?r.map(t=>this.encodeValue(t,e.operator)).join(`,`):this.encodeValue(r.toString(),e.operator)}`}).filter(e=>e.length>0);return n.length===0?``:(e.operator===`?`?`?`:`&`)+n.join(`&`)}if(e.names.length>1){let n=e.names.map(e=>t[e]).filter(e=>e!==void 0);return n.length===0?``:n.map(e=>Array.isArray(e)?e[0]:e).join(`,`)}let n=t[e.name];if(n===void 0)return``;let r=(Array.isArray(n)?n:[n]).map(t=>this.encodeValue(t,e.operator));switch(e.operator){case``:return r.join(`,`);case`+`:return r.join(`,`);case`#`:return`#`+r.join(`,`);case`.`:return`.`+r.join(`.`);case`/`:return`/`+r.join(`/`);default:return r.join(`,`)}}expand(e){let t=``,n=!1;for(let r of this.parts){if(typeof r==`string`){t+=r;continue}let i=this.expandPart(r,e);i&&(t+=(r.operator===`?`||r.operator===`&`)&&n?i.replace(`?`,`&`):i,(r.operator===`?`||r.operator===`&`)&&(n=!0))}return t}escapeRegExp(e){return e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(t){let n=[];for(let n of t.names)e.validateLength(n,lh,`Variable name`);if(t.operator===`?`||t.operator===`&`){for(let e=0;e<t.names.length;e++){let r=t.names[e],i=e===0?`\\`+t.operator:`&`;n.push({pattern:i+this.escapeRegExp(r)+`=([^&]+)`,name:r})}return n}let r,i=t.name;switch(t.operator){case``:r=t.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`;break;case`+`:case`#`:r=`(.+)`;break;case`.`:r=String.raw`\.([^/,]+)`;break;case`/`:r=`/`+(t.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`);break;default:r=`([^/]+)`}return n.push({pattern:r,name:i}),n}match(t){e.validateLength(t,ch,`URI`);let n=`^`,r=[];for(let e of this.parts)if(typeof e==`string`)n+=this.escapeRegExp(e);else{let t=this.partToRegExp(e);for(let{pattern:i,name:a}of t)n+=i,r.push({name:a,exploded:e.exploded})}n+=`$`,e.validateLength(n,1e6,`Generated regex pattern`);let i=new RegExp(n),a=t.match(i);if(!a)return null;let o={};for(let[e,t]of r.entries()){let{name:n,exploded:r}=t,i=a[e+1],s=n.replace(`*`,``);o[s]=r&&i.includes(`,`)?i.split(`,`):i}return o}};function fh(e){return typeof e==`object`&&!!e&&`_zod`in e}function ph(e){return typeof e==`object`&&!!e&&!(`_zod`in e)&&`_def`in e&&typeof e._def?.typeName==`string`}function mh(e){if(typeof e!=`object`||!e||um(e))return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.values(e).every(e=>fh(e))}function hh(e){if(e!==void 0){if(mh(e))return I(e);if(typeof e==`object`&&e&&!um(e)&&Object.values(e).some(e=>ph(e)))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!um(e))throw TypeError(`inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).`);return e}}function gh(e,t){let n=t.getValidator(e);return{"~standard":{version:1,vendor:`mcp`,jsonSchema:{input:()=>e,output:()=>e},validate:e=>{let t=n(e);return t.valid?{value:t.data}:{issues:[{message:t.errorMessage}]}}}}}function _h(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!_h(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!_h(e[r],t[r]))return!1;return!0}return e===t}function vh(e){return encodeURI(yh(e))}function yh(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}let bh={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},xh={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Sh={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},Ch=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 wh(e,t=Object.create(null),n=Ch,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:wh(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(Sh[i])continue;let a=`${r}/${vh(i)}`,o=e[i];if(Array.isArray(o)){if(bh[i]){let e=o.length;for(let r=0;r<e;r++)wh(o[r],t,n,`${a}/${r}`)}}else if(xh[i])for(let e in o)wh(o[e],t,n,`${a}/${vh(e)}`);else wh(o,t,n,a)}return t}let Th=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Eh=[0,31,28,31,30,31,30,31,31,30,31,30,31],Dh=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Oh=/^(?=.{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,kh=/^(?:[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,Ah=/^(?:(?:[^\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,jh=/^(?:(?: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,Mh=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Nh=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Ph=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Fh=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Ih=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},Lh=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Rh=/^((([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,zh=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 Bh(e){return e.test.bind(e)}let Vh={date:Uh,time:Wh.bind(void 0,!1),"date-time":Kh,duration:zh,uri:Yh,"uri-reference":Bh(kh),"uri-template":Bh(Ah),url:Bh(jh),email:Ih,hostname:Bh(Oh),ipv4:Bh(Lh),ipv6:Bh(Rh),regex:Zh,uuid:Bh(Mh),"json-pointer":Bh(Nh),"json-pointer-uri-fragment":Bh(Ph),"relative-json-pointer":Bh(Fh)};function Hh(e){return e%4==0&&(e%100!=0||e%400==0)}function Uh(e){let t=e.match(Th);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&Hh(n)?29:Eh[r])}function Wh(e,t){let n=t.match(Dh);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}let Gh=/t|\s/i;function Kh(e){let t=e.split(Gh);return t.length==2&&Uh(t[0])&&Wh(!0,t[1])}let qh=/\/|:/,Jh=/^(?:[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 Yh(e){return qh.test(e)&&Jh.test(e)}let Xh=/[^\\]\\Z/;function Zh(e){if(Xh.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function Qh(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}function $(e,t,n=`2019-09`,r=wh(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:ee,anyOf:te,allOf:ne,oneOf:re,if:ie,then:ae,else:oe,format:se,properties:ce,patternProperties:v,additionalProperties:y,unevaluatedProperties:le,minProperties:ue,maxProperties:de,propertyNames:fe,dependentRequired:pe,dependentSchemas:me,dependencies:he,prefixItems:ge,items:_e,additionalItems:ve,unevaluatedItems:ye,contains:be,minContains:b,maxContains:x,minItems:xe,maxItems:Se,uniqueItems:Ce,minimum:we,maximum:S,exclusiveMinimum:Te,exclusiveMaximum:Ee,multipleOf:De,minLength:Oe,maxLength:ke,pattern:Ae,__absolute_ref__:je,__absolute_recursive_ref__:Me}=t,C=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[Me]:a,u=`${s}/$recursiveRef`,d=$(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||C.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[je||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw je&&je!==d&&(e+=` Absolute URI "${je}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
|
|
71
|
-
- `)}`,Error(e)}let l=`${s}/$ref`,u=$(e,t,n,r,i,a,o,l,c);if(u.valid||C.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:C.length===0,errors:C}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||C.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&C.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&C.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?_h(e,h)||C.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&C.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>_h(e,t))||C.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||C.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),ee!==void 0){let t=`${s}/not`;$(e,ee,n,r,i,a,o,t).valid&&C.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Ne=[];if(te!==void 0){let t=`${s}/anyOf`,l=C.length,u=!1;for(let s=0;s<te.length;s++){let l=te[s],d=Object.create(c),f=$(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);C.push(...f.errors),u||=f.valid,f.valid&&Ne.push(d)}u?C.length=l:C.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(ne!==void 0){let t=`${s}/allOf`,l=C.length,u=!0;for(let s=0;s<ne.length;s++){let l=ne[s],d=Object.create(c),f=$(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);C.push(...f.errors),u&&=f.valid,f.valid&&Ne.push(d)}u?C.length=l:C.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(re!==void 0){let t=`${s}/oneOf`,l=C.length,u=re.filter((s,l)=>{let u=Object.create(c),d=$(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return C.push(...d.errors),d.valid&&Ne.push(u),d.valid}).length;u===1?C.length=l:C.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Ne),ie!==void 0){let t=`${s}/if`;if($(e,ie,n,r,i,a,o,t,c).valid){if(ae!==void 0){let l=$(e,ae,n,r,i,a,o,`${s}/then`,c);l.valid||C.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(oe!==void 0){let l=$(e,oe,n,r,i,a,o,`${s}/else`,c);l.valid||C.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||C.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(ue!==void 0&&t.length<ue&&C.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${ue} properties.`}),de!==void 0&&t.length>de&&C.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${de} properties.`}),fe!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${vh(s)}`,c=$(s,fe,n,r,i,a,e,t);c.valid||C.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(pe!==void 0){let t=`${s}/dependantRequired`;for(let n in pe)if(n in e){let r=pe[n];for(let i of r)i in e||C.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(me!==void 0)for(let t in me){let l=`${s}/dependentSchemas`;if(t in e){let s=$(e,me[t],n,r,i,a,o,`${l}/${vh(t)}`,c);s.valid||C.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(he!==void 0){let t=`${s}/dependencies`;for(let s in he)if(s in e){let c=he[s];if(Array.isArray(c))for(let n of c)n in e||C.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=$(e,c,n,r,i,a,o,`${t}/${vh(s)}`);l.valid||C.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(ce!==void 0){let t=`${s}/properties`;for(let s in ce){if(!(s in e))continue;let d=`${o}/${vh(s)}`,f=$(e[s],ce[s],n,r,i,a,d,`${t}/${vh(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,C.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&v!==void 0){let t=`${s}/patternProperties`;for(let s in v){let d=new RegExp(s,`u`),f=v[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${vh(p)}`,h=$(e[p],f,n,r,i,a,m,`${t}/${vh(s)}`);h.valid?c[p]=l[p]=!0:(u=i,C.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&y!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${vh(s)}`,f=$(e[s],y,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,C.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&le!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${vh(s)}`,u=$(e[s],le,n,r,i,a,l,t);u.valid?c[s]=!0:C.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){Se!==void 0&&e.length>Se&&C.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${Se}).`}),xe!==void 0&&e.length<xe&&C.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${xe}).`});let t=e.length,l=0,u=!1;if(ge!==void 0){let d=`${s}/prefixItems`,f=Math.min(ge.length,t);for(;l<f;l++){let t=$(e[l],ge[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,C.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(_e!==void 0){let d=`${s}/items`;if(Array.isArray(_e)){let s=Math.min(_e.length,t);for(;l<s;l++){let t=$(e[l],_e[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,C.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=$(e[l],_e,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,C.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ve!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=$(e[l],ve,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,C.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(be!==void 0)if(t===0&&b===void 0)C.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(b!==void 0&&t<b)C.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${b}).`});else{let l=`${s}/contains`,u=C.length,d=0;for(let s=0;s<t;s++){let t=$(e[s],be,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):C.push(...t.errors)}d>=(b||0)&&(C.length=u),b===void 0&&x===void 0&&d===0?C.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):b!==void 0&&d<b?C.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${b} items matching schema. Only ${d} items were found.`}):x!==void 0&&d>x&&C.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${x} items matching schema. ${d} items were found.`})}if(!u&&ye!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=$(e[l],ye,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||C.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(Ce)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&_h(r,t))&&(C.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(we!==void 0&&(Te===!0&&e<=we||e<we)&&C.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${Te?`or equal to `:``} ${we}.`}),S!==void 0&&(Ee===!0&&e>=S||e>S)&&C.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${Ee?`or equal to `:``} ${S}.`})):(we!==void 0&&e<we&&C.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${we}.`}),S!==void 0&&e>S&&C.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${S}.`}),Te!==void 0&&e<=Te&&C.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${Te}.`}),Ee!==void 0&&e>=Ee&&C.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ee}.`})),De!==void 0){let t=e%De;Math.abs(0-t)>=1.1920929e-7&&Math.abs(De-t)>=1.1920929e-7&&C.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${De}.`})}}else if(u===`string`){let t=Oe===void 0&&ke===void 0?0:Qh(e);Oe!==void 0&&t<Oe&&C.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${Oe}).`}),ke!==void 0&&t>ke&&C.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${ke}).`}),Ae!==void 0&&!new RegExp(Ae,`u`).test(e)&&C.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),se!==void 0&&Vh[se]&&!Vh[se](e)&&C.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${se}".`})}return{valid:C.length===0,errors:C}}var $h=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=wh(e)}validate(e){return $(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),wh(e,this.lookup)}},eg=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=ff(e,`pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.`);return t===`draft-7`?`7`:t}getValidator(e){let t=new $h(e,this.draft??this._draftFor(e),this.shortcircuit);return e=>{let n=t.validate(e);return n.valid?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:n.errors.map(e=>`${e.instanceLocation}: ${e.error}`).join(`; `)}}}};let tg=Symbol.for(`mcp.completable`);function ng(e){return!!e&&typeof e==`object`&&tg in e}function rg(e){return e[tg]?.complete}function ig(e){if(e?.maxRounds!==void 0&&(!Number.isInteger(e.maxRounds)||e.maxRounds<1))throw RangeError(`inputRequired.maxRounds must be a positive integer (got ${e.maxRounds})`);if(e?.roundTimeoutMs!==void 0&&(!Number.isFinite(e.roundTimeoutMs)||e.roundTimeoutMs<=0))throw RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${e.roundTimeoutMs})`);return{maxRounds:e?.maxRounds??8,roundTimeoutMs:e?.roundTimeoutMs??6e5,legacyShim:e?.legacyShim??!0}}function ag(e,t,n){if(typeof n!=`object`||!n||typeof n.method!=`string`)throw new Q(Z.InternalError,`Handler for ${e} returned an invalid input request '${t}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let r=n,i=vf(r);if(i===void 0)throw new Q(Z.InternalError,`Handler for ${e} returned an input request '${t}' of kind '${r.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:r,required:i}}function og(){let e=globalThis.crypto;if(e?.randomUUID!==void 0)return e.randomUUID();let t=new Uint8Array(16);e.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function sg(e,t){if(e===`tools/call`)return{content:[{type:`text`,text:t}],isError:!0};throw new Q(Z.InternalError,t)}var cg=class{constructor(e){this._host=e}async fulfill(e,t,n,r,i){let{maxRounds:a,roundTimeoutMs:o}=this._host,s=r.mcpReq.signal,c=i,l=0;for(;;){if(l+=1,l>a)return sg(e,Im(e,a));let i=c.inputRequests,u=i!=null&&Object.keys(i).length>0,d=typeof c.requestState==`string`?c.requestState:void 0;if(!u&&d===void 0)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let f;if(u){let t=this._host.resolvedClientCapabilities(r),n=[];for(let[r,a]of Object.entries(i)){let{embedded:i,required:o}=ag(e,r,a);if(i.method!==`roots/list`&&i.params===void 0)throw new Q(Z.InternalError,`Handler for ${e} returned an input request '${r}' of kind '${i.method}' without params`);if(yf(o,t)!==void 0)return sg(e,`Cannot request input '${r}' (${i.method}): the client on this 2025-era connection did not declare the required capability${t===void 0?` (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)`:``}`);n.push([r,i])}let a=Rm(s);try{let e={relatedRequestId:r.mcpReq.id,timeout:o,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:a.signal},t=await Promise.all(n.map(async([t,n])=>{try{return[t,await this._dispatchLeg(n,e)]}catch(e){throw a.abort(e),e}}));f=Object.fromEntries(t)}catch(t){if(s.aborted)throw t;return sg(e,`Fulfilling input required by '${e}' failed: ${t instanceof Error?t.message:String(t)}`)}finally{a.dispose()}}else await Lm(250,s);let p={...r,mcpReq:{...r.mcpReq,inputResponses:f,droppedInputResponseKeys:void 0,requestState:Ym(d)}};if(d!==void 0){let t=await this._host.verifyRequestState(d,p,e);t!==void 0&&(p=Zm(p,t))}let m=await t(n,p);if(!Qp(m))return m;c=m}}async _dispatchLeg(e,t){switch(e.method){case`elicitation/create`:{let n=e.params;return n.mode===`url`&&n.elicitationId===void 0&&(n={...n,elicitationId:og()}),await this._host.sendElicitation(n,t)}case`sampling/createMessage`:return await this._host.sendSampling(e.params,t);case`roots/list`:return await this._host.listRoots(e.params,t)}}};let lg=new Set([`tools/call`,`prompts/get`,`resources/read`]);var ug=class extends Qm{_clientCapabilities;_clientVersion;_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_legacyInputRequiredShim(){return this._legacyShim??=new cg({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:e=>this._inputRequestCapabilityView(e),verifyRequestState:(e,t,n)=>this._verifyRequestState(e,t,n),sendElicitation:(e,t)=>this._sendElicitationLeg(e,t,{validateAcceptedContent:!1}),sendSampling:(e,t)=>this.createMessage(e,t),listRoots:(e,t)=>this.listRoots(e,t)})}oninitialized;constructor(e,t){if(super(t),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new eg,this._requestStateVerify=t?.requestState?.verify,this._inputRequiredServing=ig(t?.inputRequired),t?.cacheHints!==void 0){for(let[e,n]of Object.entries(t.cacheHints))n!==void 0&&sp(n,`cacheHints['${e}']`);this._cacheHints=t.cacheHints}this.setRequestHandler(`initialize`,e=>this._oninitialize(e)),this.setNotificationHandler(`notifications/initialized`,()=>this.oninitialized?.()),Sf(this._supportedProtocolVersions).length>0&&this.setRequestHandler(`server/discover`,()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}_registerLoggingHandler(){this.setRequestHandler(`logging/setLevel`,async(e,t)=>{let n=t.sessionId||t.http?.req?.headers.get(`mcp-session-id`)||void 0,{level:r}=e.params,i=cm(Bc,r);return i.success&&this._loggingLevels.set(n,i.data),{}})}buildContext(e,t){let n=e.http||t?.request||t?.closeSSEStream||t?.closeStandaloneSSEStream;return{...e,mcpReq:{...e.mcpReq,log:(t,n,r)=>{if(!this._capabilities.logging)return Promise.resolve();let i;if(this._servedModernEra()){if(i=e.mcpReq.envelope?.[qo],i===void 0)return Promise.resolve()}else i=this._loggingLevels.get(e.sessionId)??this._loggingLevels.get(void 0);return i!==void 0&&this.LOG_LEVEL_SEVERITY.get(t)<this.LOG_LEVEL_SEVERITY.get(i)?Promise.resolve():e.mcpReq.notify({method:`notifications/message`,params:{level:t,data:n,logger:r}})},elicitInput:(e,t)=>this.elicitInput(e,t),requestSampling:(e,t)=>this.createMessage(e,t)},http:n?{...e.http,req:t?.request,closeSSE:t?.closeSSEStream,closeStandaloneSSE:t?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Bc.options.map((e,t)=>[e,t]));isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1};registerCapabilities(e){if(this.transport)throw new X(Y.AlreadyConnected,`Cannot register capabilities after connecting to transport`);let t=!!this._capabilities.logging;this._capabilities=eh(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(e,t){if(e!==`tools/call`){let n=this._cacheHints?.[e],r=lg.has(e);return n===void 0&&!r?async(n,r)=>{let i=await t(n,r);if(Qp(i))throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return i}:async(i,a)=>{let o=r?await this._invokeInputRequiredCapableHandler(e,t,i,a):await t(i,a);if(Qp(o)){if(!r)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return o}return n===void 0?o:rp(o,n)}}return async(e,n)=>{let r=Hp(this._negotiatedProtocolVersion),i=r.validateRequest(`tools/call`,e);if(!i.ok)throw new Q(i.reason===`not-in-era`?Z.InternalError:Z.InvalidParams,i.reason===`not-in-era`?`No wire schema for tools/call in the resolved era`:`Invalid tools/call request: ${i.message}`);let a=await this._invokeInputRequiredCapableHandler(`tools/call`,t,e,n);if(Qp(a))return a;let o=Tf(a),s=r.validateResult(`tools/call`,o);if(!s.ok)throw new Q(s.reason===`not-in-era`?Z.InternalError:Z.InvalidParams,s.reason===`not-in-era`?`No wire schema for tools/call in the resolved era`:`Invalid tools/call result: ${s.message}`);return s.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&bf(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(e,t,n,r){let i=this._servedModernEra(),a=r.mcpReq.requestState();if(a!==void 0&&typeof a!=`string`)throw new Q(Z.InvalidParams,`Invalid or expired requestState`,{reason:`invalid_request_state`});let o=r;if(typeof a==`string`){let t=await this._verifyRequestState(a,r,e);t!==void 0&&(o=Zm(r,t))}let s;try{s=await t(n,o)}catch(e){throw e instanceof Q&&e.code===Z.UrlElicitationRequired&&i?new Q(Z.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):e}if(!Qp(s))return s;if(!i){if(!this._inputRequiredServing.legacyShim)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??`2025-11-25`}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(e,t,n,o,s)}let c=s.inputRequests,l=c!=null&&Object.keys(c).length>0,u=typeof s.requestState==`string`;if(!l&&!u)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(l){let t=this._inputRequestCapabilityView(r);for(let[n,r]of Object.entries(c)){let{embedded:i,required:a}=ag(e,n,r),o=yf(a,t);if(o!==void 0)throw new dp({requiredCapabilities:o},`Cannot request input '${n}' (${i.method}): the request's client capabilities do not declare the required capability`)}}return s}async _verifyRequestState(e,t,n){if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(e,t)}catch(e){throw this.onerror?.(Error(`requestState verification rejected ${n}: ${e instanceof Error?e.message:String(e)}`)),new Q(Z.InvalidParams,`Invalid or expired requestState`,{reason:`invalid_request_state`})}}_inputRequestCapabilityView(e){return this._servedModernEra()?e.mcpReq.envelope?.[Ko]:this._clientCapabilities}_assertPushApiInServedEra(e){if(this._servedModernEra())throw new X(Y.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${e}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:e,era:`2026-07-28`})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw new X(Y.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw new X(Y.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw new X(Y.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw new X(Y.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw new X(Y.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw new X(Y.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw new X(Y.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw new X(Y.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){switch(e){case`completion/complete`:if(!this._capabilities.completions)throw new X(Y.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw new X(Y.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw new X(Y.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw new X(Y.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw new X(Y.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case`ping`:case`initialize`:break}}async _oninitialize(e){let t=e.params.protocolVersion;this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo;let n=xf(this._supportedProtocolVersions),r=n.includes(t)?t:n[0]??`2025-11-25`;return this._negotiatedProtocolVersion=r,this.transport?.setProtocolVersion?.(r),{protocolVersion:r,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:Sf(this._supportedProtocolVersions),capabilities:dg(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(e,t){return this._wireCodec().projectCallToolResult(e,t)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra(`ping`),this.request({method:`ping`})}async createMessage(e,t){if(this._assertPushApiInServedEra(`sampling/createMessage`),(e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new X(Y.CapabilityNotSupported,`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages.at(-1),n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages.at(-2):void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw new Q(Z.InvalidParams,`The last message must contain only tool_result content if any is present`);if(!o)throw new Q(Z.InvalidParams,`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new Q(Z.InvalidParams,`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}let n=!!(e.tools||e.toolChoice),r=await this.request({method:`sampling/createMessage`,params:e},t),i=this._wireCodec().samplingResultVariant(n,r);if(!i.ok)throw new X(Y.InvalidResult,`Invalid sampling/createMessage result: ${i.reason===`invalid`?i.message:i.reason}`);return i.value}async elicitInput(e,t){switch(this._assertPushApiInServedEra(`elicitation/create`),e.mode??`form`){case`url`:if(!this._clientCapabilities?.elicitation?.url)throw new X(Y.CapabilityNotSupported,`Client does not support url elicitation.`);break;case`form`:if(!this._clientCapabilities?.elicitation?.form)throw new X(Y.CapabilityNotSupported,`Client does not support form elicitation.`);break}return this._sendElicitationLeg(e,t)}async _sendElicitationLeg(e,t,n){let r=e.mode??`form`,i=n?.validateAcceptedContent??!0;switch(r){case`url`:{let n=e;return this.request({method:`elicitation/create`,params:n},t)}case`form`:{let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},t);if(i&&r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Q(Z.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new X(Y.CapabilityNotSupported,`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this._assertPushApiInServedEra(`roots/list`),this.request({method:`roots/list`,params:e},t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};function dg(e){return{...e}}var fg=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(e){let t=this._registeredTools[e];if(!(t===void 0||!t.enabled)){if(Object.hasOwn(this._toolInputSchemaJson,e))return this._toolInputSchemaJson[e];if(t.inputSchema===void 0)return hg;try{let n=pm(t.inputSchema,`input`);return this._toolInputSchemaJson[e]=n,n}catch{return}}}constructor(e,t){this.server=new ug(e,t),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(`tools/list`),this.server.assertCanSetRequestHandler(`tools/call`),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler(`tools/list`,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?pm(t.inputSchema,`input`):hg,annotations:t.annotations,icons:t.icons,execution:t.execution,_meta:t._meta};return t.outputSchema&&(n.outputSchema=pm(t.outputSchema,`output`)),n})})),this.server.setRequestHandler(`tools/call`,async(e,t)=>{let n=this._registeredTools[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Tool ${e.params.name} disabled`);try{let r=await this.validateToolInput(n,e.params.arguments,e.params.name),i=await this.executeToolHandler(n,r,t);return await this.validateToolOutput(n,i,e.params.name),Qp(i)?i:this.server.projectCallToolResult(i,n.outputSchemaJson)}catch(e){if(e instanceof Q&&e.code===Z.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await gm(e.inputSchema,t??{});if(!r.success)throw new Q(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${r.error}`);return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||Qp(t)||t.isError)return;if(t.structuredContent===void 0)throw new Q(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await gm(e.outputSchema,t.structuredContent);if(!r.success)throw new Q(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${r.error}`)}async executeToolHandler(e,t,n){return e.executor(t,n)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(`completion/complete`),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(`completion/complete`,async e=>{switch(e.params.ref.type){case`ref/prompt`:return $p(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return em(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Q(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return yg;let r=Sg(bg(n.argsSchema)?.[e.params.argument.name]);if(!ng(r))return yg;let i=rg(r);return i?vg(await i(e.params.argument.value,e.params.context)):yg}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return yg;throw new Q(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?vg(await r(e.params.argument.value,e.params.context)):yg}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(`resources/list`),this.server.assertCanSetRequestHandler(`resources/templates/list`),this.server.assertCanSetRequestHandler(`resources/read`),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler(`resources/list`,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(`resources/templates/list`,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(`resources/read`,async(e,t)=>{let n;try{n=new URL(e.params.uri)}catch{throw new Q(Z.InvalidParams,`Resource URI ${e.params.uri} is invalid`,{uri:e.params.uri,reason:`invalid_uri`})}let r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Q(Z.InvalidParams,`Resource ${n} disabled`);return rp(await r.readCallback(n,t),r.cacheHint)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return rp(await e.readCallback(n,r,t),e.cacheHint)}throw new cp(e.params.uri)}),!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(`prompts/list`),this.server.assertCanSetRequestHandler(`prompts/get`),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler(`prompts/list`,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Sm(t.argsSchema):void 0,icons:t.icons,_meta:t._meta}))})),this.server.setRequestHandler(`prompts/get`,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} disabled`);return n.handler(e.params.arguments,t)}),!0)}registerResource(e,t,n,r){let i=n.cacheHint,a=n;if(i!==void 0){sp(i,`resource ${e}`);let t={...n};delete t.cacheHint,a=t}if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,n.title,t,a,r);return i!==void 0&&(o.cacheHint=i),this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,t,a,r);return i!==void 0&&(o.cacheHint=i),this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i,a,o){let s=r,c=i,l={title:t,description:n,argsSchema:r,icons:a,_meta:o,handler:_g(e,r,i),enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.icons!==void 0&&(l.icons=t.icons),t._meta!==void 0&&(l._meta=t._meta);let n=!1;t.argsSchema!==void 0&&(l.argsSchema=t.argsSchema,s=t.argsSchema,n=!0),t.callback!==void 0&&(c=t.callback,n=!0),n&&(l.handler=_g(e,s,c)),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=l,r){let e=bg(r);e&&Object.values(e).some(e=>ng(Sg(e)))&&this.setCompletionRequestHandler()}return l}_createRegisteredTool(e,t,n,r,i,a,o,s,c,l){if(sh(e),r!==void 0)try{let t=pm(r,`input`);this._toolInputSchemaJson[e]=t;let n=im(t);n.valid||console.warn(`[mcp-sdk] tool '${e}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${n.reason}`)}catch{}let u=l,d={title:t,description:n,inputSchema:r,outputSchema:i,outputSchemaJson:gg(i),annotations:a,icons:o,execution:s,_meta:c,handler:l,executor:mg(r,l),enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&sh(t.name),delete this._registeredTools[e],delete this._toolInputSchemaJson[e],t.name&&(delete this._toolInputSchemaJson[t.name],this._registeredTools[t.name]=d,e=t.name)),t.title!==void 0&&(d.title=t.title),t.description!==void 0&&(d.description=t.description);let n=!1;t.paramsSchema!==void 0&&(d.inputSchema=t.paramsSchema,delete this._toolInputSchemaJson[e],n=!0),t.callback!==void 0&&(d.handler=t.callback,u=t.callback,n=!0),n&&(d.executor=mg(d.inputSchema,u)),t.outputSchema!==void 0&&(d.outputSchema=t.outputSchema,d.outputSchemaJson=gg(t.outputSchema)),t.annotations!==void 0&&(d.annotations=t.annotations),t.icons!==void 0&&(d.icons=t.icons),t._meta!==void 0&&(d._meta=t._meta),t.enabled!==void 0&&(d.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,icons:c,_meta:l}=t;return this._createRegisteredTool(e,r,i,hh(a),hh(o),s,c,void 0,l,n)}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a,icons:o,_meta:s}=t,c=this._createRegisteredPrompt(e,r,i,hh(a),n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),c}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},pg=class{_uriTemplate;constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new dh(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}};function mg(e,t){if(e){let e=t;return async(t,n)=>e(t,n)}let n=t;return async(e,t)=>n(t)}let hg={type:`object`,properties:{}};function gg(e){if(e!==void 0)try{return pm(e,`output`)}catch{return}}function _g(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await gm(t,n);if(!a.success)throw new Q(Z.InvalidParams,`Invalid arguments for prompt ${e}: ${a.error}`);return r(a.data,i)}}else{let e=n;return async(t,n)=>e(n)}}function vg(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}let yg={completion:{values:[],hasMore:!1}};function bg(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function xg(e){return e?.type===`optional`}function Sg(e){return xg(e)?e.def?.innerType??e:e}let Cg;function wg(e,t){return gh(e,t??(Cg??=new eg))}let Tg=Wu(void 0).inputSchema,Eg=`__isBrowserMcpServer`;function Dg(e){return typeof e==`object`&&!!e&&Eg in e&&e[Eg]===!0}function Og(e){if(e===null)return{content:[{type:`text`,text:`Tool execution interrupted by navigation`}],isError:!0};let t;try{t=JSON.parse(e)}catch{return Tu(e)}return Qp(t)?t:Tu(t)}function kg(e){let t=Object.getOwnPropertyDescriptor(e.inputSchema,`~standard`);return t&&!t.enumerable?e.inputSchema:wg(e.inputSchema)}function Ag(e){if(!e)return;let{untrustedContentHint:t,...n}=e;return n}function jg(e,t,n){let r=e.annotations?Au(e.annotations):void 0;return{name:e.name,...e.title===void 0?{}:{title:e.title},description:e.description,...t===void 0?{}:{inputSchema:t},...r?{annotations:r}:{},execute:n}}var Mg=class extends EventTarget{[Eg]=!0;mcpServer;native;ownerDocument;tools=new Map;peerOrigin;stopObservingPeerOrigin;registrations=new Set;nativeToolAbortControllers=new Map;nativeBackfilledTools=new Map;pendingTools=new Map;removingNativeTools=new Set;nativeSyncQueue=Promise.resolve();nativeToolChangeQueue=Promise.resolve();nativeToolChangeListener;closed=!1;closePromise;ontoolchangeHandler=null;ontoolchangeListener=e=>{this.ontoolchangeHandler?.call(this,e)};constructor(e,t={}){super();let{native:n,...r}=t;this.mcpServer=new fg(e,{...r,capabilities:eh(r.capabilities??{},{tools:{listChanged:!0},resources:{listChanged:!0},prompts:{listChanged:!0}})}),this.native=n,this.ownerDocument=globalThis.document??null,n&&typeof n.addEventListener==`function`&&typeof n.removeEventListener==`function`&&(this.nativeToolChangeListener=()=>{this.closed||(this.nativeToolChangeQueue=this.nativeToolChangeQueue.then(async()=>{try{await this.syncNativeTools()}catch(e){console.warn(`[BrowserMcpServer] Native WebMCP tool reconciliation failed:`,e)}await this.notifyProducerToolsChanged()}))},n.addEventListener(`toolchange`,this.nativeToolChangeListener))}get ontoolchange(){return this.ontoolchangeHandler}set ontoolchange(e){let t=typeof e==`function`?e:null;if(t===null){this.ontoolchangeHandler=null,super.removeEventListener(`toolchange`,this.ontoolchangeListener);return}this.ontoolchangeHandler===null&&super.addEventListener(`toolchange`,this.ontoolchangeListener),this.ontoolchangeHandler=t}async notifyProducerToolsChanged(){this.closed||(await new Promise(e=>setTimeout(e,0)),this.closed||this.dispatchEvent(new Event(`toolchange`)))}getNativeStandardToolsApi(){let e=this.native;return e&&typeof e.executeTool==`function`?e:void 0}async registerNativeToolMirror(e,t,n,r,i){if(!this.native)return;let a=this.native.registerTool,o=n.signal?AbortSignal.any([n.signal,i.signal]):i.signal,s=t.registeredInputSchema===void 0?void 0:JSON.parse(t.registeredInputSchema);this.nativeToolAbortControllers.set(e.name,i);try{await a.call(this.native,jg(e,s,e=>r(e)),{...n,signal:o})}catch(t){throw i.abort(),this.nativeToolAbortControllers.get(e.name)===i&&this.nativeToolAbortControllers.delete(e.name),t}this.nativeToolAbortControllers.get(e.name)===i&&this.removingNativeTools.delete(e.name)}abortNativeToolMirror(e,t=this.nativeToolAbortControllers.get(e)){!t||this.nativeToolAbortControllers.get(e)!==t||(this.removingNativeTools.add(e),t.abort(),this.nativeToolAbortControllers.delete(e))}validateToolDescriptor(e){if(ku(e),this.tools.has(e.name)||this.pendingTools.has(e.name))throw Ou(`Tool already registered: ${e.name}`);return Wu(e.inputSchema)}registerToolInMcp(e,t,n,r){let i=e.outputSchema===void 0?void 0:structuredClone(e.outputSchema),a=i===void 0?void 0:wg(i),o=Ag(e.annotations),s=t.inputSchema.type===void 0||t.inputSchema.type===`object`,c=s?this.mcpServer.registerTool(e.name,{...e.title===void 0?{}:{title:e.title},description:e.description,inputSchema:kg(t),...a?{outputSchema:a}:{},...o?{annotations:o}:{}},async(t,r)=>{let i=await n(t,r.mcpReq.signal);if(Qp(i))throw Error(`WebMCP tool "${e.name}" returned input_required. Multi-round tool flows require BrowserMcpServer.mcpServer.registerTool().`);return Tu(i)}):void 0;return r?.length&&c?.disable(),s||console.warn(`[BrowserMcpServer] Tool "${e.name}" remains available through WebMCP but cannot be exposed over MCP because MCP input schemas require an object root.`),{item:{name:e.name,...e.title===void 0?{}:{title:e.title},description:e.description,inputSchema:t.inputSchema,...i===void 0?{}:{outputSchema:i},...e.annotations?{annotations:e.annotations}:{}},...t.registeredInputSchema===void 0?{}:{registeredInputSchema:t.registeredInputSchema},execute:n,mcpHandle:c,...r?.length?{exposedTo:r}:{}}}registerTool=async(e,t={})=>{let{signal:n,exposedTo:r}=t??{},i={...n?{signal:n}:{},...r?{exposedTo:[...r]}:{}};if(Iu(this.ownerDocument),this.closed)throw Ou(`BrowserMcpServer is closed`);if(!_u(e))throw TypeError(`registerTool(tool) requires a tool object`);let a=yu(e),o=this.validateToolDescriptor(a);i.signal?.throwIfAborted(),Fu(i.exposedTo),i.signal?.throwIfAborted();let s=async(e,t)=>(t?.throwIfAborted(),Nu(Promise.resolve().then(()=>Reflect.apply(a.execute,void 0,[e])),t)),c=new AbortController,l,u=()=>{this.pendingTools.get(a.name)===c&&this.pendingTools.delete(a.name),l&&this.tools.get(a.name)===l?this.removeTool(a.name):this.abortNativeToolMirror(a.name,c)};i.signal?.addEventListener(`abort`,u,{once:!0}),this.pendingTools.set(a.name,c);try{if(await this.registerNativeToolMirror(a,o,i,s,c),this.closed)throw Ou(`BrowserMcpServer is closed`);i.signal?.throwIfAborted(),l=this.registerToolInMcp(a,o,s,i.exposedTo?.map(e=>{let t=new URL(e).origin;return t===`null`?e:t})),this.tools.set(a.name,l),this.applyToolExposure(),i.signal?.aborted&&(u(),i.signal.throwIfAborted())}catch(e){throw this.abortNativeToolMirror(a.name,c),i.signal?.removeEventListener(`abort`,u),i.signal?.throwIfAborted(),e}finally{this.pendingTools.get(a.name)===c&&this.pendingTools.delete(a.name)}if(i.signal&&(l.abortSignal=i.signal,l.abortListener=u),this.tools.get(a.name)===l&&(this.native?await this.nativeToolChangeQueue:await this.notifyProducerToolsChanged()),this.closed)throw Ou(`BrowserMcpServer is closed`);i.signal?.throwIfAborted()};removeTool(e,t){let n=this.tools.get(e);n&&(n.abortSignal&&n.abortListener&&n.abortSignal.removeEventListener(`abort`,n.abortListener),this.tools.delete(e),this.nativeBackfilledTools.delete(e),n.mcpHandle?.remove(),(t?.notify??!0)&&!this.native&&this.notifyProducerToolsChanged()),t?.skipNative||this.abortNativeToolMirror(e)}syncNativeTools(){let e=this.nativeSyncQueue.then(async()=>{if(this.closed)return;let e=this.getNativeStandardToolsApi();e&&await this.backfillNativeStandardTools(e)});return this.nativeSyncQueue=e.then(()=>void 0,()=>void 0),e}async backfillNativeStandardTools(e){let t=await e.getTools();if(this.closed)return;let n=new Map,r=new Set(t.map(({name:e})=>e));for(let e of this.removingNativeTools)r.has(e)||this.removingNativeTools.delete(e);for(let e of t){if(n.has(e.name)||this.pendingTools.has(e.name)||this.removingNativeTools.has(e.name))continue;let t=Tg;if(e.inputSchema!==void 0)try{let n=typeof e.inputSchema==`string`?e.inputSchema:JSON.stringify(e.inputSchema),r=JSON.parse(n);t=_u(r)?r:void 0}catch{t=void 0}if(!t){console.warn(`[BrowserMcpServer] Native tool "${e.name}" was not exposed over MCP because its input schema is malformed.`);continue}let r={name:e.name,...e.title===void 0?{}:{title:e.title},description:e.description,inputSchema:t,...e.annotations?{annotations:e.annotations}:{}};n.set(e.name,{source:e,item:r,fingerprint:JSON.stringify(r)})}for(let[e,t]of this.nativeBackfilledTools){let r=n.get(e);if(!r||r.fingerprint!==t.fingerprint){this.removeTool(e,{skipNative:!0,notify:!1});continue}this.nativeBackfilledTools.set(e,r)}for(let[t,r]of n){if(this.tools.has(t))continue;let n=async(n,r)=>{let i=this.nativeBackfilledTools.get(t)?.source;if(!i)throw Error(`Native tool not found: ${t}`);let a=JSON.stringify(n);return Og(r?await e.executeTool.call(this.native,i,a,{signal:r}):await e.executeTool.call(this.native,i,a))},i={name:t,...r.item.title===void 0?{}:{title:r.item.title},description:r.item.description,inputSchema:r.item.inputSchema,...r.item.annotations?{annotations:r.item.annotations}:{},execute:e=>n(e)};try{let e=this.validateToolDescriptor(i);this.tools.set(i.name,this.registerToolInMcp(i,e,n,void 0)),this.nativeBackfilledTools.set(t,r)}catch(e){console.warn(`[BrowserMcpServer] Native tool "${t}" was not exposed over MCP because its schema could not be compiled:`,e)}}}registerResource(e){if(this.closed)throw Ou(`BrowserMcpServer is closed`);let t={...e},n={...t.description===void 0?{}:{description:t.description},...t.mimeType===void 0?{}:{mimeType:t.mimeType}},r=t.uri.includes(`{`)?new pg(t.uri,{list:void 0}):void 0,i=r?this.mcpServer.registerResource(t.name,r,n,async(e,n)=>t.read(e,n)):this.mcpServer.registerResource(t.name,t.uri,n,async e=>t.read(e));return this.registrations.add(i),{unregister:()=>{this.registrations.delete(i)&&i.remove()}}}registerPrompt(e){if(this.closed)throw Ou(`BrowserMcpServer is closed`);let t={...e,...e.argsSchema===void 0?{}:{argsSchema:structuredClone(e.argsSchema)}},n=t.argsSchema===void 0?void 0:wg(t.argsSchema),r=this.mcpServer.registerPrompt(t.name,{...t.description===void 0?{}:{description:t.description},...n?{argsSchema:n}:{}},async e=>t.get(e??{}));return this.registrations.add(r),{unregister:()=>{this.registrations.delete(r)&&r.remove()}}}listTools(){return structuredClone([...this.tools.values()].map(({item:e})=>e))}async getTools(e){if(Iu(this.ownerDocument),this.closed)throw Ou(`BrowserMcpServer is closed`);if(this.native)return this.native.getTools(e);if(Fu(e?.fromOrigins),e?.fromOrigins?.length)throw new DOMException(`Cross-document tool discovery requires native WebMCP`,`NotSupportedError`);let t=globalThis.location?.origin??``,n=globalThis.window,r=[...this.tools.values()].map(({item:e,registeredInputSchema:r})=>{let i=r===void 0?void 0:JSON.parse(r);return{name:e.name,title:e.title??``,description:e.description,..._u(i)?{inputSchema:i}:{},origin:t,window:n,...e.annotations?{annotations:Au(e.annotations)}:{}}}).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));return await new Promise(e=>setTimeout(e,0)),r}async executeTool(e,t,n){if(Iu(this.ownerDocument),this.closed)throw Ou(`BrowserMcpServer is closed`);let r=this.getNativeStandardToolsApi();if(r)return r.executeTool.call(this.native,e,t,n);if(typeof e!=`object`||!e)throw TypeError(`RegisteredTool must be an object`);for(let t of[`name`,`description`,`window`,`origin`])if(!(t in e))throw TypeError(`RegisteredTool.${t} is required`);Ru(e.origin);let i=globalThis.location?.origin??``,a=globalThis.window;if(e.origin!==i||e.window!==a)throw Eu(`Native tool not found: ${e.name}`);n?.signal?.throwIfAborted();let o=this.tools.get(e.name);if(!o)throw Eu(`Tool not found: ${e.name}`);let s=ju(t);try{return Mu(await Nu(o.execute(s,n?.signal),o.abortSignal,()=>Eu(`Tool unregistered`)))}catch(e){throw n?.signal?.aborted&&e===n.signal.reason||o.abortSignal?.aborted?e:Du(e)}}applyToolExposure(){for(let{exposedTo:e,mcpHandle:t}of this.tools.values()){if(!e?.length||!t)continue;let n=this.peerOrigin!==void 0&&this.peerOrigin!==`null`&&e.includes(this.peerOrigin);n!==t.enabled&&(n?t.enable():t.disable())}}observePeerOrigin(e){if(this.stopObservingPeerOrigin?.(),this.stopObservingPeerOrigin=void 0,this.peerOrigin=void 0,this.applyToolExposure(),!(`clientOrigin`in e))return;let t=e;this.peerOrigin=t.clientOrigin,this.applyToolExposure();let n=t.onclientorigin,r=!0,i=e=>{n?.(e),r&&(this.peerOrigin=e,this.applyToolExposure())};t.onclientorigin=i,this.stopObservingPeerOrigin=()=>{r=!1,t.onclientorigin===i&&(t.onclientorigin=n)}}async connect(e){if(this.closed)throw Ou(`BrowserMcpServer is closed`);if(this.mcpServer.server.transport)throw Ou(`BrowserMcpServer is already connected`);this.observePeerOrigin(e);let t=this.stopObservingPeerOrigin;try{await this.mcpServer.connect(e)}catch(n){throw this.stopObservingPeerOrigin===t&&(t?.(),this.stopObservingPeerOrigin=void 0,this.peerOrigin=void 0,this.applyToolExposure()),this.mcpServer.server.transport===e&&await this.mcpServer.close(),n}}close(){return this.closePromise?this.closePromise:(this.closed=!0,this.stopObservingPeerOrigin?.(),this.stopObservingPeerOrigin=void 0,this.closePromise=(async()=>{this.native&&this.nativeToolChangeListener&&(this.native.removeEventListener(`toolchange`,this.nativeToolChangeListener),this.nativeToolChangeListener=void 0);for(let e of this.nativeToolAbortControllers.keys())this.abortNativeToolMirror(e);for(let e of this.tools.keys())this.removeTool(e,{notify:!1});for(let e of this.registrations)e.remove();this.registrations.clear(),this.nativeBackfilledTools.clear(),this.removingNativeTools.clear(),await this.mcpServer.close()})(),this.closePromise)}};let Ng=null;function Pg(){return typeof window<`u`&&window.navigator!==void 0}function Fg(){return document.modelContext??navigator.modelContext}function Ig(e){let t=Object.getOwnPropertyDescriptor(e,`modelContext`);return t?t.configurable===!0:Object.isExtensible(e)}function Lg(e){Object.defineProperty(document,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:e}),document.modelContext!==e&&console.error(`[WebModelContext] Failed to replace document.modelContext.`,`Descriptor:`,Object.getOwnPropertyDescriptor(document,`modelContext`))}function Rg(e){Object.defineProperty(navigator,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:e}),navigator.modelContext!==e&&console.error(`[WebModelContext] Failed to replace navigator.modelContext.`,`Descriptor:`,Object.getOwnPropertyDescriptor(navigator,`modelContext`))}function zg(e,t,n){n?Object.defineProperty(e,t,n):Reflect.deleteProperty(e,t)}function Bg(e,t,n){try{Lg(e),Rg(e)}catch(e){throw zg(document,`modelContext`,t),zg(navigator,`modelContext`,n),e}}function Vg(e){if(window.parent!==window&&e?.iframeServer!==!1)return new du(typeof e?.iframeServer==`object`?e.iframeServer:{allowedOrigins:[`*`]});if(e?.tabServer===!1)throw Error(`tabServer transport is disabled and iframe transport was not selected`);return new fu(typeof e?.tabServer==`object`?e.tabServer:{allowedOrigins:[`*`]})}function Hg(e){if(!Pg()||globalThis.isSecureContext===!1||Ng)return;let t=Fg();if(t&&Dg(t))return;tf({installTestingShim:e?.installTestingShim??!0});let n=Fg();if(!n)throw Error(`modelContext is not available`);if(!Ig(document)||!Ig(navigator))return;let r=Vg(e?.transport),i=new Mg({name:`${window.location.hostname||`localhost`}-webmcp`,version:`1.0.0`},{native:n}),a=Object.getOwnPropertyDescriptor(document,`modelContext`),o=Object.getOwnPropertyDescriptor(navigator,`modelContext`);try{Bg(i,a,o),Ng={server:i,transport:r,previousDocumentModelContextDescriptor:a,previousNavigatorModelContextDescriptor:o}}catch(e){throw i.close(),r.close(),e}(async()=>{try{await i.syncNativeTools()}catch(e){console.warn(`[WebModelContext] Native WebMCP tool synchronization failed:`,e)}if(Ng?.server===i)try{await i.connect(r)}catch(e){console.error(`[WebModelContext] Failed to connect MCP transport:`,e),Ng?.server===i&&Ug()}})()}function Ug(){if(!Ng)return;let{server:e,transport:t,previousDocumentModelContextDescriptor:n,previousNavigatorModelContextDescriptor:r}=Ng;Ng=null,e.close(),t.close(),zg(document,`modelContext`,n),zg(navigator,`modelContext`,r)}if(typeof window<`u`&&typeof document<`u`){let e=window.__webModelContextOptions;if(e?.autoInitialize!==!1)try{Hg(e)}catch(e){console.error(`[WebModelContext] Auto-initialization failed:`,e)}}return e.cleanupWebModelContext=Ug,e.initializeWebModelContext=Hg,e})({});
|
|
75
|
+
vf((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,n=/\\([\u000b\u0020-\u00ff])/g,r=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=i;function i(e){if(!e)throw TypeError(`argument string is required`);var i=typeof e==`object`?a(e):e;if(typeof i!=`string`)throw TypeError(`argument string is required to be a string`);var s=i.indexOf(`;`),c=s===-1?i.trim():i.slice(0,s).trim();if(!r.test(c))throw TypeError(`invalid media type`);var l=new o(c.toLowerCase());if(s!==-1){var u,d,f;for(t.lastIndex=s;d=t.exec(i);){if(d.index!==s)throw TypeError(`invalid parameter format`);s+=d[0].length,u=d[1].toLowerCase(),f=d[2],f.charCodeAt(0)===34&&(f=f.slice(1,-1),f.indexOf(`\\`)!==-1&&(f=f.replace(n,`$1`))),l.parameters[u]=f}if(s!==i.length)throw TypeError(`invalid parameter format`)}return l}function a(e){var t;if(typeof e.getHeader==`function`?t=e.getHeader(`content-type`):typeof e.headers==`object`&&(t=e.headers&&e.headers[`content-type`]),typeof t!=`string`)throw TypeError(`content-type header is missing from object`);return t}function o(e){this.parameters=Object.create(null),this.type=e}}))();let _h=/^[A-Za-z0-9._-]{1,128}$/;function vh(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!_h.test(e)){let n=[...e].filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function yh(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function bh(e){let t=vh(e);return yh(e,t.warnings),t.isValid}let xh=1e6,Sh=1e6,Ch=1e4;var wh=class e{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,n){if(e.length>t)throw Error(`${n} exceeds maximum length of ${t} characters (got ${e.length})`)}template;parts;get variableNames(){return this.parts.flatMap(e=>typeof e==`string`?[]:e.names)}constructor(t){e.validateLength(t,xh,`Template`),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){let n=[],r=``,i=0,a=0;for(;i<t.length;)if(t[i]===`{`){r&&=(n.push(r),``);let o=t.indexOf(`}`,i);if(o===-1)throw Error(`Unclosed template expression`);if(a++,a>Ch)throw Error(`Template contains too many expressions (max ${Ch})`);let s=t.slice(i+1,o),c=this.getOperator(s),l=s.includes(`*`),u=this.getNames(s),d=u[0];for(let t of u)e.validateLength(t,Sh,`Variable name`);n.push({name:d,operator:c,names:u,exploded:l}),i=o+1}else r+=t[i],i++;return r&&n.push(r),n}getOperator(e){return[`+`,`#`,`.`,`/`,`?`,`&`].find(t=>e.startsWith(t))||``}getNames(e){let t=this.getOperator(e);return e.slice(t.length).split(`,`).map(e=>e.replace(`*`,``).trim()).filter(e=>e.length>0)}encodeValue(t,n){return e.validateLength(t,Sh,`Variable value`),n===`+`||n===`#`?encodeURI(t):encodeURIComponent(t)}expandPart(e,t){if(e.operator===`?`||e.operator===`&`){let n=e.names.map(n=>{let r=t[n];return r===void 0?``:`${n}=${Array.isArray(r)?r.map(t=>this.encodeValue(t,e.operator)).join(`,`):this.encodeValue(r.toString(),e.operator)}`}).filter(e=>e.length>0);return n.length===0?``:(e.operator===`?`?`?`:`&`)+n.join(`&`)}if(e.names.length>1){let n=e.names.map(e=>t[e]).filter(e=>e!==void 0);return n.length===0?``:n.map(e=>Array.isArray(e)?e[0]:e).join(`,`)}let n=t[e.name];if(n===void 0)return``;let r=(Array.isArray(n)?n:[n]).map(t=>this.encodeValue(t,e.operator));switch(e.operator){case``:return r.join(`,`);case`+`:return r.join(`,`);case`#`:return`#`+r.join(`,`);case`.`:return`.`+r.join(`.`);case`/`:return`/`+r.join(`/`);default:return r.join(`,`)}}expand(e){let t=``,n=!1;for(let r of this.parts){if(typeof r==`string`){t+=r;continue}let i=this.expandPart(r,e);i&&(t+=(r.operator===`?`||r.operator===`&`)&&n?i.replace(`?`,`&`):i,(r.operator===`?`||r.operator===`&`)&&(n=!0))}return t}escapeRegExp(e){return e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(t){let n=[];for(let n of t.names)e.validateLength(n,Sh,`Variable name`);if(t.operator===`?`||t.operator===`&`){for(let e=0;e<t.names.length;e++){let r=t.names[e],i=e===0?`\\`+t.operator:`&`;n.push({pattern:i+this.escapeRegExp(r)+`=([^&]+)`,name:r})}return n}let r,i=t.name;switch(t.operator){case``:r=t.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`;break;case`+`:case`#`:r=`(.+)`;break;case`.`:r=String.raw`\.([^/,]+)`;break;case`/`:r=`/`+(t.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`);break;default:r=`([^/]+)`}return n.push({pattern:r,name:i}),n}match(t){e.validateLength(t,xh,`URI`);let n=`^`,r=[];for(let e of this.parts)if(typeof e==`string`)n+=this.escapeRegExp(e);else{let t=this.partToRegExp(e);for(let{pattern:i,name:a}of t)n+=i,r.push({name:a,exploded:e.exploded})}n+=`$`,e.validateLength(n,1e6,`Generated regex pattern`);let i=new RegExp(n),a=t.match(i);if(!a)return null;let o={};for(let[e,t]of r.entries()){let{name:n,exploded:r}=t,i=a[e+1],s=n.replace(`*`,``);o[s]=r&&i.includes(`,`)?i.split(`,`):i}return o}};function Th(e){return typeof e==`object`&&!!e&&`_zod`in e}function Eh(e){return typeof e==`object`&&!!e&&!(`_zod`in e)&&`_def`in e&&typeof e._def?.typeName==`string`}function Dh(e){if(typeof e!=`object`||!e||Cm(e))return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.values(e).every(e=>Th(e))}function Oh(e){if(e!==void 0){if(Dh(e))return F(e);if(typeof e==`object`&&e&&!Cm(e)&&Object.values(e).some(e=>Eh(e)))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!Cm(e))throw TypeError(`inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).`);return e}}function kh(e,t){let n=t.getValidator(e);return{"~standard":{version:1,vendor:`mcp`,jsonSchema:{input:()=>e,output:()=>e},validate:e=>{let t=n(e);return t.valid?{value:t.data}:{issues:[{message:t.errorMessage}]}}}}}function Ah(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!Ah(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Ah(e[r],t[r]))return!1;return!0}return e===t}function jh(e){return encodeURI(Mh(e))}function Mh(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}let Nh={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Ph={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Fh={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},Ih=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 Lh(e,t=Object.create(null),n=Ih,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:Lh(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(Fh[i])continue;let a=`${r}/${jh(i)}`,o=e[i];if(Array.isArray(o)){if(Nh[i]){let e=o.length;for(let r=0;r<e;r++)Lh(o[r],t,n,`${a}/${r}`)}}else if(Ph[i])for(let e in o)Lh(o[e],t,n,`${a}/${jh(e)}`);else Lh(o,t,n,a)}return t}let Rh=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,zh=[0,31,28,31,30,31,30,31,31,30,31,30,31],Bh=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Vh=/^(?=.{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,Hh=/^(?:[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,Uh=/^(?:(?:[^\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,Wh=/^(?:(?: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,Gh=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Kh=/^(?:\/(?:[^~/]|~0|~1)*)*$/,qh=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Jh=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Yh=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},Xh=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Zh=/^((([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,Qh=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 $h(e){return e.test.bind(e)}let eg={date:ng,time:rg.bind(void 0,!1),"date-time":ag,duration:Qh,uri:cg,"uri-reference":$h(Hh),"uri-template":$h(Uh),url:$h(Wh),email:Yh,hostname:$h(Vh),ipv4:$h(Xh),ipv6:$h(Zh),regex:ug,uuid:$h(Gh),"json-pointer":$h(Kh),"json-pointer-uri-fragment":$h(qh),"relative-json-pointer":$h(Jh)};function tg(e){return e%4==0&&(e%100!=0||e%400==0)}function ng(e){let t=e.match(Rh);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&tg(n)?29:zh[r])}function rg(e,t){let n=t.match(Bh);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}let ig=/t|\s/i;function ag(e){let t=e.split(ig);return t.length==2&&ng(t[0])&&rg(!0,t[1])}let og=/\/|:/,sg=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function cg(e){return og.test(e)&&sg.test(e)}let lg=/[^\\]\\Z/;function ug(e){if(lg.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function dg(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}function $(e,t,n=`2019-09`,r=Lh(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:ee,anyOf:te,allOf:ne,oneOf:re,if:ie,then:ae,else:oe,format:se,properties:ce,patternProperties:le,additionalProperties:v,unevaluatedProperties:ue,minProperties:de,maxProperties:fe,propertyNames:pe,dependentRequired:me,dependentSchemas:he,dependencies:ge,prefixItems:_e,items:ve,additionalItems:ye,unevaluatedItems:be,contains:xe,minContains:y,maxContains:b,minItems:Se,maxItems:Ce,uniqueItems:we,minimum:Te,maximum:x,exclusiveMinimum:Ee,exclusiveMaximum:De,multipleOf:Oe,minLength:ke,maxLength:Ae,pattern:je,__absolute_ref__:Me,__absolute_recursive_ref__:Ne}=t,S=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[Ne]:a,u=`${s}/$recursiveRef`,d=$(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||S.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[Me||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw Me&&Me!==d&&(e+=` Absolute URI "${Me}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
|
|
76
|
+
- `)}`,Error(e)}let l=`${s}/$ref`,u=$(e,t,n,r,i,a,o,l,c);if(u.valid||S.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:S.length===0,errors:S}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||S.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&S.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&S.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?Ah(e,h)||S.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&S.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>Ah(e,t))||S.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||S.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),ee!==void 0){let t=`${s}/not`;$(e,ee,n,r,i,a,o,t).valid&&S.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Pe=[];if(te!==void 0){let t=`${s}/anyOf`,l=S.length,u=!1;for(let s=0;s<te.length;s++){let l=te[s],d=Object.create(c),f=$(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);S.push(...f.errors),u||=f.valid,f.valid&&Pe.push(d)}u?S.length=l:S.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(ne!==void 0){let t=`${s}/allOf`,l=S.length,u=!0;for(let s=0;s<ne.length;s++){let l=ne[s],d=Object.create(c),f=$(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);S.push(...f.errors),u&&=f.valid,f.valid&&Pe.push(d)}u?S.length=l:S.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(re!==void 0){let t=`${s}/oneOf`,l=S.length,u=re.filter((s,l)=>{let u=Object.create(c),d=$(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return S.push(...d.errors),d.valid&&Pe.push(u),d.valid}).length;u===1?S.length=l:S.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Pe),ie!==void 0){let t=`${s}/if`;if($(e,ie,n,r,i,a,o,t,c).valid){if(ae!==void 0){let l=$(e,ae,n,r,i,a,o,`${s}/then`,c);l.valid||S.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(oe!==void 0){let l=$(e,oe,n,r,i,a,o,`${s}/else`,c);l.valid||S.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||S.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(de!==void 0&&t.length<de&&S.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${de} properties.`}),fe!==void 0&&t.length>fe&&S.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${fe} properties.`}),pe!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${jh(s)}`,c=$(s,pe,n,r,i,a,e,t);c.valid||S.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(me!==void 0){let t=`${s}/dependantRequired`;for(let n in me)if(n in e){let r=me[n];for(let i of r)i in e||S.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(he!==void 0)for(let t in he){let l=`${s}/dependentSchemas`;if(t in e){let s=$(e,he[t],n,r,i,a,o,`${l}/${jh(t)}`,c);s.valid||S.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(ge!==void 0){let t=`${s}/dependencies`;for(let s in ge)if(s in e){let c=ge[s];if(Array.isArray(c))for(let n of c)n in e||S.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=$(e,c,n,r,i,a,o,`${t}/${jh(s)}`);l.valid||S.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(ce!==void 0){let t=`${s}/properties`;for(let s in ce){if(!(s in e))continue;let d=`${o}/${jh(s)}`,f=$(e[s],ce[s],n,r,i,a,d,`${t}/${jh(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,S.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&le!==void 0){let t=`${s}/patternProperties`;for(let s in le){let d=new RegExp(s,`u`),f=le[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${jh(p)}`,h=$(e[p],f,n,r,i,a,m,`${t}/${jh(s)}`);h.valid?c[p]=l[p]=!0:(u=i,S.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&v!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${jh(s)}`,f=$(e[s],v,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,S.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&ue!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${jh(s)}`,u=$(e[s],ue,n,r,i,a,l,t);u.valid?c[s]=!0:S.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){Ce!==void 0&&e.length>Ce&&S.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${Ce}).`}),Se!==void 0&&e.length<Se&&S.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${Se}).`});let t=e.length,l=0,u=!1;if(_e!==void 0){let d=`${s}/prefixItems`,f=Math.min(_e.length,t);for(;l<f;l++){let t=$(e[l],_e[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,S.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(ve!==void 0){let d=`${s}/items`;if(Array.isArray(ve)){let s=Math.min(ve.length,t);for(;l<s;l++){let t=$(e[l],ve[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,S.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=$(e[l],ve,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,S.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ye!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=$(e[l],ye,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,S.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(xe!==void 0)if(t===0&&y===void 0)S.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(y!==void 0&&t<y)S.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${y}).`});else{let l=`${s}/contains`,u=S.length,d=0;for(let s=0;s<t;s++){let t=$(e[s],xe,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):S.push(...t.errors)}d>=(y||0)&&(S.length=u),y===void 0&&b===void 0&&d===0?S.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):y!==void 0&&d<y?S.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${y} items matching schema. Only ${d} items were found.`}):b!==void 0&&d>b&&S.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${b} items matching schema. ${d} items were found.`})}if(!u&&be!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=$(e[l],be,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||S.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(we)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&Ah(r,t))&&(S.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(Te!==void 0&&(Ee===!0&&e<=Te||e<Te)&&S.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${Ee?`or equal to `:``} ${Te}.`}),x!==void 0&&(De===!0&&e>=x||e>x)&&S.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${De?`or equal to `:``} ${x}.`})):(Te!==void 0&&e<Te&&S.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${Te}.`}),x!==void 0&&e>x&&S.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${x}.`}),Ee!==void 0&&e<=Ee&&S.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${Ee}.`}),De!==void 0&&e>=De&&S.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${De}.`})),Oe!==void 0){let t=e%Oe;Math.abs(0-t)>=1.1920929e-7&&Math.abs(Oe-t)>=1.1920929e-7&&S.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${Oe}.`})}}else if(u===`string`){let t=ke===void 0&&Ae===void 0?0:dg(e);ke!==void 0&&t<ke&&S.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${ke}).`}),Ae!==void 0&&t>Ae&&S.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${Ae}).`}),je!==void 0&&!new RegExp(je,`u`).test(e)&&S.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),se!==void 0&&eg[se]&&!eg[se](e)&&S.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${se}".`})}return{valid:S.length===0,errors:S}}var fg=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Lh(e)}validate(e){return $(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Lh(e,this.lookup)}},pg=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=Tf(e,`pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.`);return t===`draft-7`?`7`:t}getValidator(e){let t=new fg(e,this.draft??this._draftFor(e),this.shortcircuit);return e=>{let n=t.validate(e);return n.valid?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:n.errors.map(e=>`${e.instanceLocation}: ${e.error}`).join(`; `)}}}};let mg=Symbol.for(`mcp.completable`);function hg(e){return!!e&&typeof e==`object`&&mg in e}function gg(e){return e[mg]?.complete}function _g(e){if(e?.maxRounds!==void 0&&(!Number.isInteger(e.maxRounds)||e.maxRounds<1))throw RangeError(`inputRequired.maxRounds must be a positive integer (got ${e.maxRounds})`);if(e?.roundTimeoutMs!==void 0&&(!Number.isFinite(e.roundTimeoutMs)||e.roundTimeoutMs<=0))throw RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${e.roundTimeoutMs})`);return{maxRounds:e?.maxRounds??8,roundTimeoutMs:e?.roundTimeoutMs??6e5,legacyShim:e?.legacyShim??!0}}function vg(e,t,n){if(typeof n!=`object`||!n||typeof n.method!=`string`)throw new Q(Z.InternalError,`Handler for ${e} returned an invalid input request '${t}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let r=n,i=jf(r);if(i===void 0)throw new Q(Z.InternalError,`Handler for ${e} returned an input request '${t}' of kind '${r.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:r,required:i}}function yg(){let e=globalThis.crypto;if(e?.randomUUID!==void 0)return e.randomUUID();let t=new Uint8Array(16);e.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function bg(e,t){if(e===`tools/call`)return{content:[{type:`text`,text:t}],isError:!0};throw new Q(Z.InternalError,t)}var xg=class{constructor(e){this._host=e}async fulfill(e,t,n,r,i){let{maxRounds:a,roundTimeoutMs:o}=this._host,s=r.mcpReq.signal,c=i,l=0;for(;;){if(l+=1,l>a)return bg(e,Ym(e,a));let i=c.inputRequests,u=i!=null&&Object.keys(i).length>0,d=typeof c.requestState==`string`?c.requestState:void 0;if(!u&&d===void 0)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let f;if(u){let t=this._host.resolvedClientCapabilities(r),n=[];for(let[r,a]of Object.entries(i)){let{embedded:i,required:o}=vg(e,r,a);if(i.method!==`roots/list`&&i.params===void 0)throw new Q(Z.InternalError,`Handler for ${e} returned an input request '${r}' of kind '${i.method}' without params`);if(Mf(o,t)!==void 0)return bg(e,`Cannot request input '${r}' (${i.method}): the client on this 2025-era connection did not declare the required capability${t===void 0?` (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)`:``}`);n.push([r,i])}let a=Zm(s);try{let e={relatedRequestId:r.mcpReq.id,timeout:o,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:a.signal},t=await Promise.all(n.map(async([t,n])=>{try{return[t,await this._dispatchLeg(n,e)]}catch(e){throw a.abort(e),e}}));f=Object.fromEntries(t)}catch(t){if(s.aborted)throw t;return bg(e,`Fulfilling input required by '${e}' failed: ${t instanceof Error?t.message:String(t)}`)}finally{a.dispose()}}else await Xm(250,s);let p={...r,mcpReq:{...r.mcpReq,inputResponses:f,droppedInputResponseKeys:void 0,requestState:ch(d)}};if(d!==void 0){let t=await this._host.verifyRequestState(d,p,e);t!==void 0&&(p=uh(p,t))}let m=await t(n,p);if(!dm(m))return m;c=m}}async _dispatchLeg(e,t){switch(e.method){case`elicitation/create`:{let n=e.params;return n.mode===`url`&&n.elicitationId===void 0&&(n={...n,elicitationId:yg()}),await this._host.sendElicitation(n,t)}case`sampling/createMessage`:return await this._host.sendSampling(e.params,t);case`roots/list`:return await this._host.listRoots(e.params,t)}}};let Sg=new Set([`tools/call`,`prompts/get`,`resources/read`]);var Cg=class extends dh{_clientCapabilities;_clientVersion;_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_legacyInputRequiredShim(){return this._legacyShim??=new xg({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:e=>this._inputRequestCapabilityView(e),verifyRequestState:(e,t,n)=>this._verifyRequestState(e,t,n),sendElicitation:(e,t)=>this._sendElicitationLeg(e,t,{validateAcceptedContent:!1}),sendSampling:(e,t)=>this.createMessage(e,t),listRoots:(e,t)=>this.listRoots(e,t)})}oninitialized;constructor(e,t){if(super(t),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new pg,this._requestStateVerify=t?.requestState?.verify,this._inputRequiredServing=_g(t?.inputRequired),t?.cacheHints!==void 0){for(let[e,n]of Object.entries(t.cacheHints))n!==void 0&&bp(n,`cacheHints['${e}']`);this._cacheHints=t.cacheHints}this.setRequestHandler(`initialize`,e=>this._oninitialize(e)),this.setNotificationHandler(`notifications/initialized`,()=>this.oninitialized?.()),Ff(this._supportedProtocolVersions).length>0&&this.setRequestHandler(`server/discover`,()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}_registerLoggingHandler(){this.setRequestHandler(`logging/setLevel`,async(e,t)=>{let n=t.sessionId||t.http?.req?.headers.get(`mcp-session-id`)||void 0,{level:r}=e.params,i=xm(Vc,r);return i.success&&this._loggingLevels.set(n,i.data),{}})}buildContext(e,t){let n=e.http||t?.request||t?.closeSSEStream||t?.closeStandaloneSSEStream;return{...e,mcpReq:{...e.mcpReq,log:(t,n,r)=>{if(!this._capabilities.logging)return Promise.resolve();let i;if(this._servedModernEra()){if(i=e.mcpReq.envelope?.[Jo],i===void 0)return Promise.resolve()}else i=this._loggingLevels.get(e.sessionId)??this._loggingLevels.get(void 0);return i!==void 0&&this.LOG_LEVEL_SEVERITY.get(t)<this.LOG_LEVEL_SEVERITY.get(i)?Promise.resolve():e.mcpReq.notify({method:`notifications/message`,params:{level:t,data:n,logger:r}})},elicitInput:(e,t)=>this.elicitInput(e,t),requestSampling:(e,t)=>this.createMessage(e,t)},http:n?{...e.http,req:t?.request,closeSSE:t?.closeSSEStream,closeStandaloneSSE:t?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Vc.options.map((e,t)=>[e,t]));isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1};registerCapabilities(e){if(this.transport)throw new X(Y.AlreadyConnected,`Cannot register capabilities after connecting to transport`);let t=!!this._capabilities.logging;this._capabilities=ph(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(e,t){if(e!==`tools/call`){let n=this._cacheHints?.[e],r=Sg.has(e);return n===void 0&&!r?async(n,r)=>{let i=await t(n,r);if(dm(i))throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return i}:async(i,a)=>{let o=r?await this._invokeInputRequiredCapableHandler(e,t,i,a):await t(i,a);if(dm(o)){if(!r)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return o}return n===void 0?o:gp(o,n)}}return async(e,n)=>{let r=tm(this._negotiatedProtocolVersion),i=r.validateRequest(`tools/call`,e);if(!i.ok)throw new Q(i.reason===`not-in-era`?Z.InternalError:Z.InvalidParams,i.reason===`not-in-era`?`No wire schema for tools/call in the resolved era`:`Invalid tools/call request: ${i.message}`);let a=await this._invokeInputRequiredCapableHandler(`tools/call`,t,e,n);if(dm(a))return a;let o=Rf(a),s=r.validateResult(`tools/call`,o);if(!s.ok)throw new Q(s.reason===`not-in-era`?Z.InternalError:Z.InvalidParams,s.reason===`not-in-era`?`No wire schema for tools/call in the resolved era`:`Invalid tools/call result: ${s.message}`);return s.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&Nf(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(e,t,n,r){let i=this._servedModernEra(),a=r.mcpReq.requestState();if(a!==void 0&&typeof a!=`string`)throw new Q(Z.InvalidParams,`Invalid or expired requestState`,{reason:`invalid_request_state`});let o=r;if(typeof a==`string`){let t=await this._verifyRequestState(a,r,e);t!==void 0&&(o=uh(r,t))}let s;try{s=await t(n,o)}catch(e){throw e instanceof Q&&e.code===Z.UrlElicitationRequired&&i?new Q(Z.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):e}if(!dm(s))return s;if(!i){if(!this._inputRequiredServing.legacyShim)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??`2025-11-25`}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(e,t,n,o,s)}let c=s.inputRequests,l=c!=null&&Object.keys(c).length>0,u=typeof s.requestState==`string`;if(!l&&!u)throw new Q(Z.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(l){let t=this._inputRequestCapabilityView(r);for(let[n,r]of Object.entries(c)){let{embedded:i,required:a}=vg(e,n,r),o=Mf(a,t);if(o!==void 0)throw new wp({requiredCapabilities:o},`Cannot request input '${n}' (${i.method}): the request's client capabilities do not declare the required capability`)}}return s}async _verifyRequestState(e,t,n){if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(e,t)}catch(e){throw this.onerror?.(Error(`requestState verification rejected ${n}: ${e instanceof Error?e.message:String(e)}`)),new Q(Z.InvalidParams,`Invalid or expired requestState`,{reason:`invalid_request_state`})}}_inputRequestCapabilityView(e){return this._servedModernEra()?e.mcpReq.envelope?.[qo]:this._clientCapabilities}_assertPushApiInServedEra(e){if(this._servedModernEra())throw new X(Y.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${e}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:e,era:`2026-07-28`})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw new X(Y.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw new X(Y.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw new X(Y.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw new X(Y.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw new X(Y.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw new X(Y.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw new X(Y.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw new X(Y.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){switch(e){case`completion/complete`:if(!this._capabilities.completions)throw new X(Y.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw new X(Y.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw new X(Y.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw new X(Y.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw new X(Y.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case`ping`:case`initialize`:break}}async _oninitialize(e){let t=e.params.protocolVersion;this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo;let n=Pf(this._supportedProtocolVersions),r=n.includes(t)?t:n[0]??`2025-11-25`;return this._negotiatedProtocolVersion=r,this.transport?.setProtocolVersion?.(r),{protocolVersion:r,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:Ff(this._supportedProtocolVersions),capabilities:wg(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(e,t){return this._wireCodec().projectCallToolResult(e,t)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra(`ping`),this.request({method:`ping`})}async createMessage(e,t){if(this._assertPushApiInServedEra(`sampling/createMessage`),(e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new X(Y.CapabilityNotSupported,`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages.at(-1),n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages.at(-2):void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw new Q(Z.InvalidParams,`The last message must contain only tool_result content if any is present`);if(!o)throw new Q(Z.InvalidParams,`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new Q(Z.InvalidParams,`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}let n=!!(e.tools||e.toolChoice),r=await this.request({method:`sampling/createMessage`,params:e},t),i=this._wireCodec().samplingResultVariant(n,r);if(!i.ok)throw new X(Y.InvalidResult,`Invalid sampling/createMessage result: ${i.reason===`invalid`?i.message:i.reason}`);return i.value}async elicitInput(e,t){switch(this._assertPushApiInServedEra(`elicitation/create`),e.mode??`form`){case`url`:if(!this._clientCapabilities?.elicitation?.url)throw new X(Y.CapabilityNotSupported,`Client does not support url elicitation.`);break;case`form`:if(!this._clientCapabilities?.elicitation?.form)throw new X(Y.CapabilityNotSupported,`Client does not support form elicitation.`);break}return this._sendElicitationLeg(e,t)}async _sendElicitationLeg(e,t,n){let r=e.mode??`form`,i=n?.validateAcceptedContent??!0;switch(r){case`url`:{let n=e;return this.request({method:`elicitation/create`,params:n},t)}case`form`:{let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},t);if(i&&r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Q(Z.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof Q?e:new Q(Z.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new X(Y.CapabilityNotSupported,`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this._assertPushApiInServedEra(`roots/list`),this.request({method:`roots/list`,params:e},t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};function wg(e){return{...e}}var Tg=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(e){let t=this._registeredTools[e];if(!(t===void 0||!t.enabled)){if(Object.hasOwn(this._toolInputSchemaJson,e))return this._toolInputSchemaJson[e];if(t.inputSchema===void 0)return Og;try{let n=Em(t.inputSchema,`input`);return this._toolInputSchemaJson[e]=n,n}catch{return}}}constructor(e,t){this.server=new Cg(e,t),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(`tools/list`),this.server.assertCanSetRequestHandler(`tools/call`),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler(`tools/list`,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?Em(t.inputSchema,`input`):Og,annotations:t.annotations,icons:t.icons,execution:t.execution,_meta:t._meta};return t.outputSchema&&(n.outputSchema=Em(t.outputSchema,`output`)),n})})),this.server.setRequestHandler(`tools/call`,async(e,t)=>{let n=this._registeredTools[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Tool ${e.params.name} disabled`);try{let r=await this.validateToolInput(n,e.params.arguments,e.params.name),i=await this.executeToolHandler(n,r,t);return await this.validateToolOutput(n,i,e.params.name),dm(i)?i:this.server.projectCallToolResult(i,n.outputSchemaJson)}catch(e){if(e instanceof Q&&e.code===Z.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await km(e.inputSchema,t??{});if(!r.success)throw new Q(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${r.error}`);return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||dm(t)||t.isError)return;if(t.structuredContent===void 0)throw new Q(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await km(e.outputSchema,t.structuredContent);if(!r.success)throw new Q(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${r.error}`)}async executeToolHandler(e,t,n){return e.executor(t,n)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(`completion/complete`),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(`completion/complete`,async e=>{switch(e.params.ref.type){case`ref/prompt`:return fm(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return pm(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Q(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Mg;let r=Fg(Ng(n.argsSchema)?.[e.params.argument.name]);if(!hg(r))return Mg;let i=gg(r);return i?jg(await i(e.params.argument.value,e.params.context)):Mg}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Mg;throw new Q(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?jg(await r(e.params.argument.value,e.params.context)):Mg}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(`resources/list`),this.server.assertCanSetRequestHandler(`resources/templates/list`),this.server.assertCanSetRequestHandler(`resources/read`),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler(`resources/list`,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(`resources/templates/list`,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(`resources/read`,async(e,t)=>{let n;try{n=new URL(e.params.uri)}catch{throw new Q(Z.InvalidParams,`Resource URI ${e.params.uri} is invalid`,{uri:e.params.uri,reason:`invalid_uri`})}let r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Q(Z.InvalidParams,`Resource ${n} disabled`);return gp(await r.readCallback(n,t),r.cacheHint)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return gp(await e.readCallback(n,r,t),e.cacheHint)}throw new xp(e.params.uri)}),!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(`prompts/list`),this.server.assertCanSetRequestHandler(`prompts/get`),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler(`prompts/list`,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Fm(t.argsSchema):void 0,icons:t.icons,_meta:t._meta}))})),this.server.setRequestHandler(`prompts/get`,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Q(Z.InvalidParams,`Prompt ${e.params.name} disabled`);return n.handler(e.params.arguments,t)}),!0)}registerResource(e,t,n,r){let i=n.cacheHint,a=n;if(i!==void 0){bp(i,`resource ${e}`);let t={...n};delete t.cacheHint,a=t}if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,n.title,t,a,r);return i!==void 0&&(o.cacheHint=i),this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,t,a,r);return i!==void 0&&(o.cacheHint=i),this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i,a,o){let s=r,c=i,l={title:t,description:n,argsSchema:r,icons:a,_meta:o,handler:Ag(e,r,i),enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.icons!==void 0&&(l.icons=t.icons),t._meta!==void 0&&(l._meta=t._meta);let n=!1;t.argsSchema!==void 0&&(l.argsSchema=t.argsSchema,s=t.argsSchema,n=!0),t.callback!==void 0&&(c=t.callback,n=!0),n&&(l.handler=Ag(e,s,c)),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=l,r){let e=Ng(r);e&&Object.values(e).some(e=>hg(Fg(e)))&&this.setCompletionRequestHandler()}return l}_createRegisteredTool(e,t,n,r,i,a,o,s,c,l){if(bh(e),r!==void 0)try{let t=Em(r,`input`);this._toolInputSchemaJson[e]=t;let n=_m(t);n.valid||console.warn(`[mcp-sdk] tool '${e}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${n.reason}`)}catch{}let u=l,d={title:t,description:n,inputSchema:r,outputSchema:i,outputSchemaJson:kg(i),annotations:a,icons:o,execution:s,_meta:c,handler:l,executor:Dg(r,l),enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&bh(t.name),delete this._registeredTools[e],delete this._toolInputSchemaJson[e],t.name&&(delete this._toolInputSchemaJson[t.name],this._registeredTools[t.name]=d,e=t.name)),t.title!==void 0&&(d.title=t.title),t.description!==void 0&&(d.description=t.description);let n=!1;t.paramsSchema!==void 0&&(d.inputSchema=t.paramsSchema,delete this._toolInputSchemaJson[e],n=!0),t.callback!==void 0&&(d.handler=t.callback,u=t.callback,n=!0),n&&(d.executor=Dg(d.inputSchema,u)),t.outputSchema!==void 0&&(d.outputSchema=t.outputSchema,d.outputSchemaJson=kg(t.outputSchema)),t.annotations!==void 0&&(d.annotations=t.annotations),t.icons!==void 0&&(d.icons=t.icons),t._meta!==void 0&&(d._meta=t._meta),t.enabled!==void 0&&(d.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,icons:c,_meta:l}=t;return this._createRegisteredTool(e,r,i,Oh(a),Oh(o),s,c,void 0,l,n)}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a,icons:o,_meta:s}=t,c=this._createRegisteredPrompt(e,r,i,Oh(a),n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),c}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Eg=class{_uriTemplate;constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new wh(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}};function Dg(e,t){if(e){let e=t;return async(t,n)=>e(t,n)}let n=t;return async(e,t)=>n(t)}let Og={type:`object`,properties:{}};function kg(e){if(e!==void 0)try{return Em(e,`output`)}catch{return}}function Ag(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await km(t,n);if(!a.success)throw new Q(Z.InvalidParams,`Invalid arguments for prompt ${e}: ${a.error}`);return r(a.data,i)}}else{let e=n;return async(t,n)=>e(n)}}function jg(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}let Mg={completion:{values:[],hasMore:!1}};function Ng(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function Pg(e){return e?.type===`optional`}function Fg(e){return Pg(e)?e.def?.innerType??e:e}let Ig;function Lg(e,t){return kh(e,t??(Ig??=new pg))}let Rg=gf(void 0).inputSchema,zg=`__isBrowserMcpServer`;function Bg(e){return typeof e==`object`&&!!e&&zg in e&&e[zg]===!0}function Vg(e){return`clientOrigin`in e&&(e.clientOrigin===void 0||typeof e.clientOrigin==`string`)&&(!(`onclientorigin`in e)||e.onclientorigin===void 0||typeof e.onclientorigin==`function`)}function Hg(e){let t;try{t=JSON.parse(e)}catch{t=e}return J(t)?t:{content:[{type:`text`,text:typeof t==`string`?t:e}]}}function Ug(e,t){return new Promise((n,r)=>{t.throwIfAborted();let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),Promise.resolve().then(e).then(n,r).finally(()=>t.removeEventListener(`abort`,i))})}function Wg(e){return mf(e.inputSchema)?e.inputSchema:Lg(e.inputSchema)}var Gg=class extends EventTarget{[zg]=!0;mcpServer;native;ownerDocument;tools=new Map;peerOrigin;stopObservingPeerOrigin;registrations=new Set;nativeToolAbortControllers=new Map;nativeBackfilledTools=new Map;pendingTools=new Map;removingNativeTools=new Set;nativeSyncQueue=Promise.resolve();nativeToolChangeQueue=Promise.resolve();nativeToolChangeListener;closed=!1;closePromise;eventHandlers=new Map;eventHandlerListener=e=>{this.eventHandlers.get(e.type)?.call(this,e)};nativeLifecycleListener=e=>{if(this.closed)return;let t=new Event(e.type);`toolName`in e&&Object.defineProperty(t,"toolName",{enumerable:!0,value:e.toolName}),this.dispatchEvent(t)};constructor(e,t={}){super();let{native:n,...r}=t;!n&&!globalThis.document?.modelContext&&Jd(),this.mcpServer=new Tg(e,{...r,capabilities:ph(r.capabilities??{},{tools:{listChanged:!0},resources:{listChanged:!0},prompts:{listChanged:!0}})}),this.native=n??globalThis.document?.modelContext,this.ownerDocument=globalThis.document??null,this.nativeToolChangeListener=()=>{this.closed||(this.nativeToolChangeQueue=this.nativeToolChangeQueue.then(async()=>{try{await this.syncNativeTools()}catch(e){console.warn(`[BrowserMcpServer] Native WebMCP tool reconciliation failed:`,e)}await this.notifyProducerToolsChanged()}))},this.native?.addEventListener(`toolchange`,this.nativeToolChangeListener),this.native?.addEventListener(`toolactivated`,this.nativeLifecycleListener),this.native?.addEventListener(`toolcancel`,this.nativeLifecycleListener)}getEventHandler(e){return this.eventHandlers.get(e)??null}setEventHandler(e,t){typeof t==`function`?(this.eventHandlers.has(e)||super.addEventListener(e,this.eventHandlerListener),this.eventHandlers.set(e,t)):this.eventHandlers.delete(e)&&super.removeEventListener(e,this.eventHandlerListener)}get ontoolchange(){return this.getEventHandler(`toolchange`)}set ontoolchange(e){this.setEventHandler(`toolchange`,e)}get ontoolactivated(){return this.getEventHandler(`toolactivated`)}set ontoolactivated(e){this.setEventHandler(`toolactivated`,e)}get ontoolcancel(){return this.getEventHandler(`toolcancel`)}set ontoolcancel(e){this.setEventHandler(`toolcancel`,e)}async notifyProducerToolsChanged(){this.closed||(await new Promise(e=>setTimeout(e,0)),this.closed||this.dispatchEvent(new Event(`toolchange`)))}async registerNativeToolMirror(e,t,n,r,i){let a=this.native;if(!a)return;let o=n.signal?AbortSignal.any([n.signal,i.signal]):i.signal,s={name:e.name,description:e.description,execute:r};if(e.title!==void 0&&(s.title=e.title),t.registeredInputSchema!==void 0){let e=JSON.parse(t.registeredInputSchema);if(!J(e))throw TypeError(`inputSchema must be an object`);s.inputSchema=e}e.annotations&&(s.annotations=e.annotations),this.nativeToolAbortControllers.set(e.name,i);try{await a.registerTool(s,{...n,signal:o})}catch(t){if(i.abort(),this.nativeToolAbortControllers.get(e.name)===i&&this.nativeToolAbortControllers.delete(e.name),t instanceof DOMException&&t.name===`NotAllowedError`){console.warn(`[BrowserMcpServer] Tool "${e.name}" is available over MCP only: ${t.message}. Grant allow="tools" on the iframe to expose it to WebMCP.`);return}throw t}this.nativeToolAbortControllers.get(e.name)===i&&this.removingNativeTools.delete(e.name)}abortNativeToolMirror(e,t=this.nativeToolAbortControllers.get(e)){!t||this.nativeToolAbortControllers.get(e)!==t||(this.removingNativeTools.add(e),t.abort(),this.nativeToolAbortControllers.delete(e))}registerToolInMcp(e,t,n,r){let i={name:e.name,description:e.description,inputSchema:t.inputSchema};e.title!==void 0&&(i.title=e.title),e.outputSchema!==void 0&&(i.outputSchema=structuredClone(e.outputSchema)),e.annotations&&(i.annotations=e.annotations);let a={description:e.description};if(i.outputSchema!==void 0&&(a.outputSchema=Lg(i.outputSchema)),e.title!==void 0&&(a.title=e.title),e.annotations){let{untrustedContentHint:t,...n}=e.annotations;a.annotations=n}let o;t.inputSchema.type===void 0||t.inputSchema.type===`object`?(a.inputSchema=Wg(t),o=this.mcpServer.registerTool(e.name,a,async(t,r)=>{let i=await n(t,{signal:r.mcpReq.signal});if(dm(i))throw Error(`WebMCP tool "${e.name}" returned input_required. Multi-round tool flows require BrowserMcpServer.mcpServer.registerTool().`);return uf(i)}),o.disable()):console.warn(`[BrowserMcpServer] Tool "${e.name}" remains available through WebMCP but cannot be exposed over MCP because MCP input schemas require an object root.`);let s={item:i,mcpHandle:o};return r?.length&&(s.exposedTo=r),s}registerTool=async(e,t={})=>{let{signal:n,exposedTo:r}=t??{},i={};if(n&&(i.signal=n),r&&(i.exposedTo=[...r]),this.closed)throw $d(`BrowserMcpServer is closed`);if(!J(e))throw TypeError(`registerTool(tool) requires a tool object`);let a=Qd(e);if(this.tools.has(a.name)&&!this.nativeBackfilledTools.has(a.name)||this.pendingTools.has(a.name))throw $d(`Tool already registered: ${a.name}`);let o=gf(a.inputSchema);i.signal?.throwIfAborted();let s=a.execute,c=(e,t)=>Ug(()=>s(e,t),t.signal),l=new AbortController,u=i.exposedTo?.map(e=>URL.parse(e)?.origin??e),d,f=()=>{this.pendingTools.get(a.name)===l&&this.pendingTools.delete(a.name),d&&this.tools.get(a.name)===d?this.removeTool(a.name):(d?.mcpHandle?.remove(),this.abortNativeToolMirror(a.name,l)),d=void 0};i.signal?.addEventListener(`abort`,f,{once:!0}),this.pendingTools.set(a.name,l);try{if(this.nativeBackfilledTools.has(a.name)||(d=this.registerToolInMcp(a,o,c,u)),i.signal?.throwIfAborted(),await this.registerNativeToolMirror(a,o,i,c,l),this.closed)throw $d(`BrowserMcpServer is closed`);i.signal?.throwIfAborted(),this.removeTool(a.name,{skipNative:!0}),d??=this.registerToolInMcp(a,o,c,u),this.tools.set(a.name,d),this.applyToolExposure(),i.signal?.aborted&&(f(),i.signal.throwIfAborted())}catch(e){throw d?.mcpHandle?.remove(),this.abortNativeToolMirror(a.name,l),i.signal?.removeEventListener(`abort`,f),i.signal?.throwIfAborted(),e}finally{this.pendingTools.get(a.name)===l&&this.pendingTools.delete(a.name)}if(i.signal&&(d.abortSignal=i.signal,d.abortListener=f),this.tools.get(a.name)===d&&await this.nativeToolChangeQueue,this.closed)throw $d(`BrowserMcpServer is closed`);i.signal?.throwIfAborted()};removeTool(e,t){let n=this.tools.get(e);n&&(n.abortSignal&&n.abortListener&&n.abortSignal.removeEventListener(`abort`,n.abortListener),this.tools.delete(e),this.nativeBackfilledTools.delete(e),n.mcpHandle?.remove()),t?.skipNative||this.abortNativeToolMirror(e)}syncNativeTools(){let e=this.native,t=this.nativeSyncQueue.then(async()=>{this.closed||!e||await this.backfillNativeStandardTools(e)});return this.nativeSyncQueue=t.then(()=>void 0,()=>void 0),t}async backfillNativeStandardTools(e){let t=this.ownerDocument?.defaultView,n=(await e.getTools()).filter(e=>{if(e.window===t)return!0;if(t?.parent!==t)return!1;let n=e.window;for(;n;){if(n===t)return!0;let e=n.parent;if(e===n)break;n=e}return!1});if(this.closed)return;for(let e of this.removingNativeTools)n.some(n=>n.name===e&&n.window===t)||this.removingNativeTools.delete(e);let r=new Map;for(let e of n){if(r.has(e.name)||this.pendingTools.has(e.name)||this.removingNativeTools.has(e.name))continue;let t;try{t=JSON.parse(tf(e.inputSchema??Rg))}catch{}if(!J(t)){console.warn(`[BrowserMcpServer] Native tool "${e.name}" was not exposed over MCP because its input schema is malformed.`);continue}let n={name:e.name,description:e.description,inputSchema:t};e.title!==void 0&&(n.title=e.title),e.annotations&&(n.annotations=e.annotations),r.set(e.name,{source:e,item:n,fingerprint:JSON.stringify(n)})}for(let[e,t]of this.nativeBackfilledTools){let n=r.get(e);n?.fingerprint===t.fingerprint?this.nativeBackfilledTools.set(e,n):this.removeTool(e,{skipNative:!0})}for(let[t,n]of r){if(this.tools.has(t))continue;let r=async(n,r)=>{let i=this.nativeBackfilledTools.get(t)?.source;if(!i)throw Error(`Native tool not found: ${t}`);try{return Hg(await e.executeTool(i,n,r))}catch(e){throw i.window.closed&&this.nativeToolChangeListener(),e}},i={...n.item,execute:r};try{let e=gf(i.inputSchema);this.tools.set(t,this.registerToolInMcp(i,e,r)),this.nativeBackfilledTools.set(t,n)}catch(e){console.warn(`[BrowserMcpServer] Native tool "${t}" was not exposed over MCP because its schema could not be compiled:`,e)}}this.applyToolExposure()}registerResource(e){if(this.closed)throw $d(`BrowserMcpServer is closed`);let t={...e},n={};t.description!==void 0&&(n.description=t.description),t.mimeType!==void 0&&(n.mimeType=t.mimeType);let r=t.uri.includes(`{`)?new Eg(t.uri,{list:void 0}):void 0,i=r?this.mcpServer.registerResource(t.name,r,n,async(e,n)=>t.read(e,n)):this.mcpServer.registerResource(t.name,t.uri,n,async e=>t.read(e));return this.registrations.add(i),{unregister:()=>{this.registrations.delete(i)&&i.remove()}}}registerPrompt(e){if(this.closed)throw $d(`BrowserMcpServer is closed`);let t={...e};e.argsSchema!==void 0&&(t.argsSchema=structuredClone(e.argsSchema));let n=t.argsSchema===void 0?void 0:Lg(t.argsSchema),r={};t.description!==void 0&&(r.description=t.description),n&&(r.argsSchema=n);let i=this.mcpServer.registerPrompt(t.name,r,async e=>t.get(e??{}));return this.registrations.add(i),{unregister:()=>{this.registrations.delete(i)&&i.remove()}}}listTools(){return structuredClone([...this.tools.values()].map(({item:e})=>e))}async getTools(e){if(this.closed)throw $d(`BrowserMcpServer is closed`);if(!this.native)throw $d(`BrowserMcpServer has no WebMCP context`);return this.native.getTools(e)}async executeTool(...e){if(this.closed)throw $d(`BrowserMcpServer is closed`);if(!this.native)throw $d(`BrowserMcpServer has no WebMCP context`);return this.native.executeTool(...e)}applyToolExposure(){for(let{exposedTo:e,mcpHandle:t}of this.tools.values()){if(!t)continue;let n=!e?.length||this.peerOrigin!==void 0&&this.peerOrigin!==`null`&&e.includes(this.peerOrigin);n!==t.enabled&&(n?t.enable():t.disable())}}observePeerOrigin(e){if(this.stopObservingPeerOrigin?.(),this.stopObservingPeerOrigin=void 0,this.peerOrigin=void 0,this.applyToolExposure(),!Vg(e))return;let t=e;this.peerOrigin=t.clientOrigin,this.applyToolExposure();let n=t.onclientorigin,r=!0,i=e=>{n?.(e),r&&(this.peerOrigin=e,this.applyToolExposure())};t.onclientorigin=i,this.stopObservingPeerOrigin=()=>{r=!1,t.onclientorigin===i&&(t.onclientorigin=n)}}async connect(e){if(this.closed)throw $d(`BrowserMcpServer is closed`);if(this.mcpServer.server.transport)throw $d(`BrowserMcpServer is already connected`);this.observePeerOrigin(e);let t=this.stopObservingPeerOrigin;try{await this.mcpServer.connect(e)}catch(n){throw this.stopObservingPeerOrigin===t&&(t?.(),this.stopObservingPeerOrigin=void 0,this.peerOrigin=void 0,this.applyToolExposure()),this.mcpServer.server.transport===e&&await this.mcpServer.close(),n}}close(){return this.closePromise?this.closePromise:(this.closed=!0,this.stopObservingPeerOrigin?.(),this.stopObservingPeerOrigin=void 0,this.closePromise=(async()=>{this.native?.removeEventListener(`toolchange`,this.nativeToolChangeListener),this.native?.removeEventListener(`toolactivated`,this.nativeLifecycleListener),this.native?.removeEventListener(`toolcancel`,this.nativeLifecycleListener);for(let e of this.nativeToolAbortControllers.keys())this.abortNativeToolMirror(e);for(let e of this.tools.keys())this.removeTool(e);for(let e of this.registrations)e.remove();this.registrations.clear(),this.nativeBackfilledTools.clear(),this.removingNativeTools.clear(),await this.mcpServer.close()})(),this.closePromise)}};let Kg=null;function qg(e){if(window.parent!==window&&e?.iframeServer!==!1)return new fu(e?.iframeServer||{allowedOrigins:[`*`]});if(e?.tabServer===!1)throw Error(`tabServer transport is disabled and iframe transport was not selected`);return new pu(e?.tabServer||{allowedOrigins:[`*`]})}function Jg(e){if(!globalThis.window||!globalThis.document||globalThis.isSecureContext===!1||Kg||Bg(document.modelContext))return;Jd();let t=document.modelContext;if(!t)throw Error(`modelContext is not available`);let n=Object.getOwnPropertyDescriptor(document,`modelContext`);if(n?!n.configurable:!Object.isExtensible(document))return;let r=qg(e?.transport),i=new Gg({name:`${window.location.hostname||`localhost`}-webmcp`,version:`1.0.0`},{native:t});try{Object.defineProperty(document,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:i}),Kg={server:i,transport:r,previousDescriptor:n}}catch(e){throw i.close(),r.close(),e}(async()=>{try{await i.syncNativeTools()}catch(e){console.warn(`[WebModelContext] Native WebMCP tool synchronization failed:`,e)}if(Kg?.server===i)try{await i.connect(r)}catch(e){console.error(`[WebModelContext] Failed to connect MCP transport:`,e),Kg?.server===i&&Yg()}})()}function Yg(){if(!Kg)return;let{server:e,transport:t,previousDescriptor:n}=Kg;Kg=null,e.close(),t.close(),n?Object.defineProperty(document,"modelContext",n):Reflect.deleteProperty(document,`modelContext`)}let Xg=globalThis.window?.__webModelContextOptions;if(Xg?.autoInitialize!==!1)try{Jg(Xg)}catch(e){console.error(`[WebModelContext] Auto-initialization failed:`,e)}return e.cleanupWebModelContext=Yg,e.initializeWebModelContext=Jg,e})({});
|