@mieubrisse/notion-mcp-server 2.0.1 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.mjs
CHANGED
|
@@ -143,7 +143,7 @@ data:
|
|
|
143
143
|
`;return i&&(o+=`id: ${i}
|
|
144
144
|
`),o+=`data: ${JSON.stringify(n)}
|
|
145
145
|
|
|
146
|
-
`,t.enqueue(r.encode(o)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(t,r){try{let n=t.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let i=t.headers.get("content-type");if(!i||!i.includes("application/json"))return this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let o={headers:Object.fromEntries(t.headers.entries())},a;if(r?.parsedBody!==void 0)a=r.parsedBody;else try{a=await t.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let s;try{Array.isArray(a)?s=a.map(y=>Ka.parse(y)):s=[Ka.parse(a)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let u=s.some(Ya);if(u){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(s.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!u){let y=this.validateSession(t);if(y)return y;let x=this.validateProtocolVersion(t);if(x)return x}if(!s.some(On)){for(let y of s)this.onmessage?.(y,{authInfo:r?.authInfo,requestInfo:o});return new Response(null,{status:202})}let l=crypto.randomUUID(),p=s.find(y=>Ya(y)),d=p?p.params.protocolVersion:t.headers.get("mcp-protocol-version")??Rw;if(this._enableJsonResponse)return new Promise(y=>{this._streamMapping.set(l,{resolveJson:y,cleanup:()=>{this._streamMapping.delete(l)}});for(let x of s)On(x)&&this._requestToStreamMapping.set(x.id,l);for(let x of s)this.onmessage?.(x,{authInfo:r?.authInfo,requestInfo:o})});let m=new TextEncoder,f,h=new ReadableStream({start:y=>{f=y},cancel:()=>{this._streamMapping.delete(l)}}),v={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(v["mcp-session-id"]=this.sessionId);for(let y of s)On(y)&&(this._streamMapping.set(l,{controller:f,encoder:m,cleanup:()=>{this._streamMapping.delete(l);try{f.close()}catch{}}}),this._requestToStreamMapping.set(y.id,l));await this.writePrimingEvent(f,m,l,d);for(let y of s){let x,_;On(y)&&this._eventStore&&d>="2025-11-25"&&(x=()=>{this.closeSSEStream(y.id)},_=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(y,{authInfo:r?.authInfo,requestInfo:o,closeSSEStream:x,closeStandaloneSSEStream:_})}return new Response(h,{status:200,headers:v})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(t){let r=this.validateSession(t);if(r)return r;let n=this.validateProtocolVersion(t);return n||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(t){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=t.headers.get("mcp-session-id");if(!r)return this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(t){let r=t.headers.get("mcp-protocol-version");if(r!==null&&!Ga.includes(r))return this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Ga.join(", ")})`)}async close(){this._streamMapping.forEach(({cleanup:t})=>{t()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(t){let r=this._requestToStreamMapping.get(t);if(!r)return;let n=this._streamMapping.get(r);n&&n.cleanup()}closeStandaloneSSEStream(){let t=this._streamMapping.get(this._standaloneSseStreamId);t&&t.cleanup()}async send(t,r){let n=r?.relatedRequestId;if((on(t)||ro(t))&&(n=t.id),n===void 0){if(on(t)||ro(t))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let a;this._eventStore&&(a=await this._eventStore.storeEvent(this._standaloneSseStreamId,t));let s=this._streamMapping.get(this._standaloneSseStreamId);if(s===void 0)return;s.controller&&s.encoder&&this.writeSSEEvent(s.controller,s.encoder,t,a);return}let i=this._requestToStreamMapping.get(n);if(!i)throw new Error(`No connection established for request ID: ${String(n)}`);let o=this._streamMapping.get(i);if(!this._enableJsonResponse&&o?.controller&&o?.encoder){let a;this._eventStore&&(a=await this._eventStore.storeEvent(i,t)),this.writeSSEEvent(o.controller,o.encoder,t,a)}if(on(t)||ro(t)){this._requestResponseMap.set(n,t);let a=Array.from(this._requestToStreamMapping.entries()).filter(([u,c])=>c===i).map(([u])=>u);if(a.every(u=>this._requestResponseMap.has(u))){if(!o)throw new Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&o.resolveJson){let u={"Content-Type":"application/json"};this.sessionId!==void 0&&(u["mcp-session-id"]=this.sessionId);let c=a.map(l=>this._requestResponseMap.get(l));c.length===1?o.resolveJson(new Response(JSON.stringify(c[0]),{status:200,headers:u})):o.resolveJson(new Response(JSON.stringify(c),{status:200,headers:u}))}else o.cleanup();for(let u of a)this._requestResponseMap.delete(u),this._requestToStreamMapping.delete(u)}}}};var dl=class{constructor(t={}){this._requestContext=new WeakMap,this._webStandardTransport=new pl(t),this._requestListener=kh(async r=>{let n=this._requestContext.get(r);return this._webStandardTransport.handleRequest(r,{authInfo:n?.authInfo,parsedBody:n?.parsedBody})})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(t){this._webStandardTransport.onclose=t}get onclose(){return this._webStandardTransport.onclose}set onerror(t){this._webStandardTransport.onerror=t}get onerror(){return this._webStandardTransport.onerror}set onmessage(t){this._webStandardTransport.onmessage=t}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(t,r){return this._webStandardTransport.send(t,r)}async handleRequest(t,r,n){let i=t.auth;await kh(async a=>this._webStandardTransport.handleRequest(a,{authInfo:i,parsedBody:n}))(t,r)}closeSSEStream(t){this._webStandardTransport.closeSSEStream(t)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};var E0=Aa(NI(),1);import{randomUUID as Xre,randomBytes as Yre}from"node:crypto";import Jre from"node:fs";import Gre from"node:path";var re;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(s=>typeof i[i[s]]!="number"),a={};for(let s of o)a[s]=i[s];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},e.find=(i,o)=>{for(let a of i)if(o(a))return a},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(re||(re={}));var qI;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(qI||(qI={}));var z=re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),cn=e=>{switch(typeof e){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(e)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(e)?z.array:e===null?z.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?z.promise:typeof Map<"u"&&e instanceof Map?z.map:typeof Set<"u"&&e instanceof Set?z.set:typeof Date<"u"&&e instanceof Date?z.date:z.object;default:return z.unknown}};var E=re.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var ar=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let s=n,u=0;for(;u<a.path.length;){let c=a.path[u];u===a.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(r(a))):s[c]=s[c]||{_errors:[]},s=s[c],u++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,re.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r=Object.create(null),n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};ar.create=e=>new ar(e);var t7=(e,t)=>{let r;switch(e.code){case E.invalid_type:e.received===z.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case E.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,re.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:r=`Unrecognized key(s) in object: ${re.joinValues(e.keys,", ")}`;break;case E.invalid_union:r="Invalid input";break;case E.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${re.joinValues(e.options)}`;break;case E.invalid_enum_value:r=`Invalid enum value. Expected ${re.joinValues(e.options)}, received '${e.received}'`;break;case E.invalid_arguments:r="Invalid function arguments";break;case E.invalid_return_type:r="Invalid function return type";break;case E.invalid_date:r="Invalid date";break;case E.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:re.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case E.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case E.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case E.custom:r="Invalid input";break;case E.invalid_intersection_types:r="Intersection results could not be merged";break;case E.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case E.not_finite:r="Number must be finite";break;default:r=t.defaultError,re.assertNever(e)}return{message:r}},qn=t7;var r7=qn;function oc(){return r7}var wp=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let s="",u=n.filter(c=>!!c).slice().reverse();for(let c of u)s=c(a,{data:t,defaultError:s}).message;return{...i,path:o,message:s}};function T(e,t){let r=oc(),n=wp({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===qn?void 0:qn].filter(i=>!!i)});e.common.issues.push(n)}var wt=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return Z;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let o=await i.key,a=await i.value;n.push({key:o,value:a})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return Z;o.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(n[o.value]=a.value)}return{status:t.value,value:n}}},Z=Object.freeze({status:"aborted"}),Mo=e=>({status:"dirty",value:e}),Ct=e=>({status:"valid",value:e}),Ng=e=>e.status==="aborted",qg=e=>e.status==="dirty",Ei=e=>e.status==="valid",ac=e=>typeof Promise<"u"&&e instanceof Promise;var C;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(C||(C={}));var fr=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},DI=(e,t)=>{if(Ei(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new ar(e.common.issues);return this._error=r,this._error}}};function J(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(a,s)=>{let{message:u}=e;return a.code==="invalid_enum_value"?{message:u??s.defaultError}:typeof s.data>"u"?{message:u??n??s.defaultError}:a.code!=="invalid_type"?{message:s.defaultError}:{message:u??r??s.defaultError}},description:i}}var X=class{get description(){return this._def.description}_getType(t){return cn(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:cn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new wt,ctx:{common:t.parent.common,data:t.data,parsedType:cn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(ac(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:cn(t)},i=this._parseSync({data:t,path:n.path,parent:n});return DI(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:cn(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return Ei(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Ei(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:cn(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(ac(i)?i:Promise.resolve(i));return DI(n,o)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let a=t(i),s=()=>o.addIssue({code:E.custom,...n(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(s(),!1)):a?!0:(s(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new Er({schema:this,typeName:F.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Sr.create(this,this._def)}nullable(){return pn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Un.create(this)}promise(){return Oi.create(this,this._def)}or(t){return Vo.create([this,t],this._def)}and(t){return Ho.create(this,t,this._def)}transform(t){return new Er({...J(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new Xo({...J(this._def),innerType:this,defaultValue:r,typeName:F.ZodDefault})}brand(){return new kp({typeName:F.ZodBranded,type:this,...J(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new Yo({...J(this._def),innerType:this,catchValue:r,typeName:F.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return $p.create(this,t)}readonly(){return Qo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},n7=/^c[^\s-]{8,}$/i,i7=/^[0-9a-z]+$/,o7=/^[0-9A-HJKMNP-TV-Z]{26}$/i,a7=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,s7=/^[a-z0-9_-]{21}$/i,c7=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,u7=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,l7=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,p7="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Dg,d7=/^(?:(?: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])$/,f7=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,m7=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,h7=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,v7=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,g7=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,UI="((\\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])))",y7=new RegExp(`^${UI}$`);function MI(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function x7(e){return new RegExp(`^${MI(e)}$`)}function b7(e){let t=`${UI}T${MI(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function _7(e,t){return!!((t==="v4"||!t)&&d7.test(e)||(t==="v6"||!t)&&m7.test(e))}function w7(e,t){if(!c7.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function k7(e,t){return!!((t==="v4"||!t)&&f7.test(e)||(t==="v6"||!t)&&h7.test(e))}var Fo=class e extends X{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==z.string){let o=this._getOrReturnCtx(t);return T(o,{code:E.invalid_type,expected:z.string,received:o.parsedType}),Z}let n=new wt,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),T(i,{code:E.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),T(i,{code:E.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let a=t.data.length>o.value,s=t.data.length<o.value;(a||s)&&(i=this._getOrReturnCtx(t,i),a?T(i,{code:E.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):s&&T(i,{code:E.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")l7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"email",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Dg||(Dg=new RegExp(p7,"u")),Dg.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"emoji",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")a7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"uuid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")s7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"nanoid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")n7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"cuid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")i7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"cuid2",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")o7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"ulid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),T(i,{validation:"url",code:E.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"regex",code:E.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),T(i,{code:E.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),T(i,{code:E.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),T(i,{code:E.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?b7(o).test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{code:E.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?y7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{code:E.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?x7(o).test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{code:E.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?u7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"duration",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?_7(t.data,o.version)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"ip",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?w7(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"jwt",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?k7(t.data,o.version)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"cidr",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?v7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"base64",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?g7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"base64url",code:E.invalid_string,message:o.message}),n.dirty()):re.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:E.invalid_string,...C.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...C.errToObj(t)})}url(t){return this._addCheck({kind:"url",...C.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...C.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...C.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...C.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...C.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...C.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...C.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...C.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...C.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...C.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...C.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...C.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...C.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...C.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...C.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...C.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...C.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...C.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...C.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...C.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...C.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...C.errToObj(r)})}nonempty(t){return this.min(1,C.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Fo.create=e=>new Fo({checks:[],typeName:F.ZodString,coerce:e?.coerce??!1,...J(e)});function $7(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return o%a/10**i}var sc=class e extends X{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==z.number){let o=this._getOrReturnCtx(t);return T(o,{code:E.invalid_type,expected:z.number,received:o.parsedType}),Z}let n,i=new wt;for(let o of this._def.checks)o.kind==="int"?re.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),T(n,{code:E.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),T(n,{code:E.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),T(n,{code:E.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?$7(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),T(n,{code:E.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),T(n,{code:E.not_finite,message:o.message}),i.dirty()):re.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,C.toString(r))}gt(t,r){return this.setLimit("min",t,!1,C.toString(r))}lte(t,r){return this.setLimit("max",t,!0,C.toString(r))}lt(t,r){return this.setLimit("max",t,!1,C.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:C.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:C.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:C.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:C.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&re.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};sc.create=e=>new sc({checks:[],typeName:F.ZodNumber,coerce:e?.coerce||!1,...J(e)});var cc=class e extends X{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==z.bigint)return this._getInvalidInput(t);let n,i=new wt;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),T(n,{code:E.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),T(n,{code:E.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),T(n,{code:E.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):re.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return T(r,{code:E.invalid_type,expected:z.bigint,received:r.parsedType}),Z}gte(t,r){return this.setLimit("min",t,!0,C.toString(r))}gt(t,r){return this.setLimit("min",t,!1,C.toString(r))}lte(t,r){return this.setLimit("max",t,!0,C.toString(r))}lt(t,r){return this.setLimit("max",t,!1,C.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:C.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:C.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};cc.create=e=>new cc({checks:[],typeName:F.ZodBigInt,coerce:e?.coerce??!1,...J(e)});var uc=class extends X{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==z.boolean){let n=this._getOrReturnCtx(t);return T(n,{code:E.invalid_type,expected:z.boolean,received:n.parsedType}),Z}return Ct(t.data)}};uc.create=e=>new uc({typeName:F.ZodBoolean,coerce:e?.coerce||!1,...J(e)});var lc=class e extends X{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==z.date){let o=this._getOrReturnCtx(t);return T(o,{code:E.invalid_type,expected:z.date,received:o.parsedType}),Z}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return T(o,{code:E.invalid_date}),Z}let n=new wt,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),T(i,{code:E.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),T(i,{code:E.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):re.assertNever(o);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:C.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:C.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};lc.create=e=>new lc({checks:[],coerce:e?.coerce||!1,typeName:F.ZodDate,...J(e)});var pc=class extends X{_parse(t){if(this._getType(t)!==z.symbol){let n=this._getOrReturnCtx(t);return T(n,{code:E.invalid_type,expected:z.symbol,received:n.parsedType}),Z}return Ct(t.data)}};pc.create=e=>new pc({typeName:F.ZodSymbol,...J(e)});var Zo=class extends X{_parse(t){if(this._getType(t)!==z.undefined){let n=this._getOrReturnCtx(t);return T(n,{code:E.invalid_type,expected:z.undefined,received:n.parsedType}),Z}return Ct(t.data)}};Zo.create=e=>new Zo({typeName:F.ZodUndefined,...J(e)});var Bo=class extends X{_parse(t){if(this._getType(t)!==z.null){let n=this._getOrReturnCtx(t);return T(n,{code:E.invalid_type,expected:z.null,received:n.parsedType}),Z}return Ct(t.data)}};Bo.create=e=>new Bo({typeName:F.ZodNull,...J(e)});var dc=class extends X{constructor(){super(...arguments),this._any=!0}_parse(t){return Ct(t.data)}};dc.create=e=>new dc({typeName:F.ZodAny,...J(e)});var Dn=class extends X{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ct(t.data)}};Dn.create=e=>new Dn({typeName:F.ZodUnknown,...J(e)});var Vr=class extends X{_parse(t){let r=this._getOrReturnCtx(t);return T(r,{code:E.invalid_type,expected:z.never,received:r.parsedType}),Z}};Vr.create=e=>new Vr({typeName:F.ZodNever,...J(e)});var fc=class extends X{_parse(t){if(this._getType(t)!==z.undefined){let n=this._getOrReturnCtx(t);return T(n,{code:E.invalid_type,expected:z.void,received:n.parsedType}),Z}return Ct(t.data)}};fc.create=e=>new fc({typeName:F.ZodVoid,...J(e)});var Un=class e extends X{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==z.array)return T(r,{code:E.invalid_type,expected:z.array,received:r.parsedType}),Z;if(i.exactLength!==null){let a=r.data.length>i.exactLength.value,s=r.data.length<i.exactLength.value;(a||s)&&(T(r,{code:a?E.too_big:E.too_small,minimum:s?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(T(r,{code:E.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(T(r,{code:E.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,s)=>i.type._parseAsync(new fr(r,a,r.path,s)))).then(a=>wt.mergeArray(n,a));let o=[...r.data].map((a,s)=>i.type._parseSync(new fr(r,a,r.path,s)));return wt.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:C.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:C.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:C.toString(r)}})}nonempty(t){return this.min(1,t)}};Un.create=(e,t)=>new Un({type:e,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...J(t)});function Lo(e){if(e instanceof sr){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Sr.create(Lo(n))}return new sr({...e._def,shape:()=>t})}else return e instanceof Un?new Un({...e._def,type:Lo(e.element)}):e instanceof Sr?Sr.create(Lo(e.unwrap())):e instanceof pn?pn.create(Lo(e.unwrap())):e instanceof ln?ln.create(e.items.map(t=>Lo(t))):e}var sr=class e extends X{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=re.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==z.object){let c=this._getOrReturnCtx(t);return T(c,{code:E.invalid_type,expected:z.object,received:c.parsedType}),Z}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof Vr&&this._def.unknownKeys==="strip"))for(let c in i.data)a.includes(c)||s.push(c);let u=[];for(let c of a){let l=o[c],p=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new fr(i,p,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof Vr){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of s)u.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(c==="strict")s.length>0&&(T(i,{code:E.unrecognized_keys,keys:s}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of s){let p=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new fr(i,p,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let l of u){let p=await l.key,d=await l.value;c.push({key:p,value:d,alwaysSet:l.alwaysSet})}return c}).then(c=>wt.mergeObjectSync(n,c)):wt.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(t){return C.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:C.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:F.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of re.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of re.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return Lo(this)}partial(t){let r={};for(let n of re.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of re.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Sr;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return LI(re.objectKeys(this.shape))}};sr.create=(e,t)=>new sr({shape:()=>e,unknownKeys:"strip",catchall:Vr.create(),typeName:F.ZodObject,...J(t)});sr.strictCreate=(e,t)=>new sr({shape:()=>e,unknownKeys:"strict",catchall:Vr.create(),typeName:F.ZodObject,...J(t)});sr.lazycreate=(e,t)=>new sr({shape:e,unknownKeys:"strip",catchall:Vr.create(),typeName:F.ZodObject,...J(t)});var Vo=class extends X{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(o){for(let s of o)if(s.result.status==="valid")return s.result;for(let s of o)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(s=>new ar(s.ctx.common.issues));return T(r,{code:E.invalid_union,unionErrors:a}),Z}if(r.common.async)return Promise.all(n.map(async o=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let u of n){let c={...r,common:{...r.common,issues:[]},parent:null},l=u._parseSync({data:r.data,path:r.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let s=a.map(u=>new ar(u));return T(r,{code:E.invalid_union,unionErrors:s}),Z}}get options(){return this._def.options}};Vo.create=(e,t)=>new Vo({options:e,typeName:F.ZodUnion,...J(t)});var un=e=>e instanceof Jo?un(e.schema):e instanceof Er?un(e.innerType()):e instanceof Go?[e.value]:e instanceof Wo?e.options:e instanceof Ko?re.objectValues(e.enum):e instanceof Xo?un(e._def.innerType):e instanceof Zo?[void 0]:e instanceof Bo?[null]:e instanceof Sr?[void 0,...un(e.unwrap())]:e instanceof pn?[null,...un(e.unwrap())]:e instanceof kp||e instanceof Qo?un(e.unwrap()):e instanceof Yo?un(e._def.innerType):[],Ug=class e extends X{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==z.object)return T(r,{code:E.invalid_type,expected:z.object,received:r.parsedType}),Z;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(T(r,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Z)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let o of r){let a=un(o.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let s of a){if(i.has(s))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(s)}`);i.set(s,o)}}return new e({typeName:F.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...J(n)})}};function Mg(e,t){let r=cn(e),n=cn(t);if(e===t)return{valid:!0,data:e};if(r===z.object&&n===z.object){let i=re.objectKeys(t),o=re.objectKeys(e).filter(s=>i.indexOf(s)!==-1),a={...e,...t};for(let s of o){let u=Mg(e[s],t[s]);if(!u.valid)return{valid:!1};a[s]=u.data}return{valid:!0,data:a}}else if(r===z.array&&n===z.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let a=e[o],s=t[o],u=Mg(a,s);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===z.date&&n===z.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Ho=class extends X{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,a)=>{if(Ng(o)||Ng(a))return Z;let s=Mg(o.value,a.value);return s.valid?((qg(o)||qg(a))&&r.dirty(),{status:r.value,value:s.data}):(T(n,{code:E.invalid_intersection_types}),Z)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,a])=>i(o,a)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Ho.create=(e,t,r)=>new Ho({left:e,right:t,typeName:F.ZodIntersection,...J(r)});var ln=class e extends X{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==z.array)return T(n,{code:E.invalid_type,expected:z.array,received:n.parsedType}),Z;if(n.data.length<this._def.items.length)return T(n,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Z;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((a,s)=>{let u=this._def.items[s]||this._def.rest;return u?u._parse(new fr(n,a,n.path,s)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>wt.mergeArray(r,a)):wt.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ln.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ln({items:e,typeName:F.ZodTuple,rest:null,...J(t)})};var Lg=class e extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==z.object)return T(n,{code:E.invalid_type,expected:z.object,received:n.parsedType}),Z;let i=[],o=this._def.keyType,a=this._def.valueType;for(let s in n.data)i.push({key:o._parse(new fr(n,s,n.path,s)),value:a._parse(new fr(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?wt.mergeObjectAsync(r,i):wt.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof X?new e({keyType:t,valueType:r,typeName:F.ZodRecord,...J(n)}):new e({keyType:Fo.create(),valueType:t,typeName:F.ZodRecord,...J(r)})}},mc=class extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==z.map)return T(n,{code:E.invalid_type,expected:z.map,received:n.parsedType}),Z;let i=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([s,u],c)=>({key:i._parse(new fr(n,s,n.path,[c,"key"])),value:o._parse(new fr(n,u,n.path,[c,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let u of a){let c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return Z;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),s.set(c.value,l.value)}return{status:r.value,value:s}})}else{let s=new Map;for(let u of a){let c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return Z;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),s.set(c.value,l.value)}return{status:r.value,value:s}}}};mc.create=(e,t,r)=>new mc({valueType:t,keyType:e,typeName:F.ZodMap,...J(r)});var hc=class e extends X{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==z.set)return T(n,{code:E.invalid_type,expected:z.set,received:n.parsedType}),Z;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(T(n,{code:E.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(T(n,{code:E.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function a(u){let c=new Set;for(let l of u){if(l.status==="aborted")return Z;l.status==="dirty"&&r.dirty(),c.add(l.value)}return{status:r.value,value:c}}let s=[...n.data.values()].map((u,c)=>o._parse(new fr(n,u,n.path,c)));return n.common.async?Promise.all(s).then(u=>a(u)):a(s)}min(t,r){return new e({...this._def,minSize:{value:t,message:C.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:C.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};hc.create=(e,t)=>new hc({valueType:e,minSize:null,maxSize:null,typeName:F.ZodSet,...J(t)});var Fg=class e extends X{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==z.function)return T(r,{code:E.invalid_type,expected:z.function,received:r.parsedType}),Z;function n(s,u){return wp({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,oc(),qn].filter(c=>!!c),issueData:{code:E.invalid_arguments,argumentsError:u}})}function i(s,u){return wp({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,oc(),qn].filter(c=>!!c),issueData:{code:E.invalid_return_type,returnTypeError:u}})}let o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Oi){let s=this;return Ct(async function(...u){let c=new ar([]),l=await s._def.args.parseAsync(u,o).catch(m=>{throw c.addIssue(n(u,m)),c}),p=await Reflect.apply(a,this,l);return await s._def.returns._def.type.parseAsync(p,o).catch(m=>{throw c.addIssue(i(p,m)),c})})}else{let s=this;return Ct(function(...u){let c=s._def.args.safeParse(u,o);if(!c.success)throw new ar([n(u,c.error)]);let l=Reflect.apply(a,this,c.data),p=s._def.returns.safeParse(l,o);if(!p.success)throw new ar([i(l,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ln.create(t).rest(Dn.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||ln.create([]).rest(Dn.create()),returns:r||Dn.create(),typeName:F.ZodFunction,...J(n)})}},Jo=class extends X{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Jo.create=(e,t)=>new Jo({getter:e,typeName:F.ZodLazy,...J(t)});var Go=class extends X{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return T(r,{received:r.data,code:E.invalid_literal,expected:this._def.value}),Z}return{status:"valid",value:t.data}}get value(){return this._def.value}};Go.create=(e,t)=>new Go({value:e,typeName:F.ZodLiteral,...J(t)});function LI(e,t){return new Wo({values:e,typeName:F.ZodEnum,...J(t)})}var Wo=class e extends X{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return T(r,{expected:re.joinValues(n),received:r.parsedType,code:E.invalid_type}),Z}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return T(r,{received:r.data,code:E.invalid_enum_value,options:n}),Z}return Ct(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};Wo.create=LI;var Ko=class extends X{_parse(t){let r=re.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==z.string&&n.parsedType!==z.number){let i=re.objectValues(r);return T(n,{expected:re.joinValues(i),received:n.parsedType,code:E.invalid_type}),Z}if(this._cache||(this._cache=new Set(re.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=re.objectValues(r);return T(n,{received:n.data,code:E.invalid_enum_value,options:i}),Z}return Ct(t.data)}get enum(){return this._def.values}};Ko.create=(e,t)=>new Ko({values:e,typeName:F.ZodNativeEnum,...J(t)});var Oi=class extends X{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==z.promise&&r.common.async===!1)return T(r,{code:E.invalid_type,expected:z.promise,received:r.parsedType}),Z;let n=r.parsedType===z.promise?r.data:Promise.resolve(r.data);return Ct(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Oi.create=(e,t)=>new Oi({type:e,typeName:F.ZodPromise,...J(t)});var Er=class extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:a=>{T(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async s=>{if(r.value==="aborted")return Z;let u=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return u.status==="aborted"?Z:u.status==="dirty"?Mo(u.value):r.value==="dirty"?Mo(u.value):u});{if(r.value==="aborted")return Z;let s=this._def.schema._parseSync({data:a,path:n.path,parent:n});return s.status==="aborted"?Z:s.status==="dirty"?Mo(s.value):r.value==="dirty"?Mo(s.value):s}}if(i.type==="refinement"){let a=s=>{let u=i.refinement(s,o);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Z:(s.status==="dirty"&&r.dirty(),a(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?Z:(s.status==="dirty"&&r.dirty(),a(s.value).then(()=>({status:r.value,value:s.value}))))}if(i.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ei(a))return Z;let s=i.transform(a.value,o);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Ei(a)?Promise.resolve(i.transform(a.value,o)).then(s=>({status:r.value,value:s})):Z);re.assertNever(i)}};Er.create=(e,t,r)=>new Er({schema:e,typeName:F.ZodEffects,effect:t,...J(r)});Er.createWithPreprocess=(e,t,r)=>new Er({schema:t,effect:{type:"preprocess",transform:e},typeName:F.ZodEffects,...J(r)});var Sr=class extends X{_parse(t){return this._getType(t)===z.undefined?Ct(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Sr.create=(e,t)=>new Sr({innerType:e,typeName:F.ZodOptional,...J(t)});var pn=class extends X{_parse(t){return this._getType(t)===z.null?Ct(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};pn.create=(e,t)=>new pn({innerType:e,typeName:F.ZodNullable,...J(t)});var Xo=class extends X{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Xo.create=(e,t)=>new Xo({innerType:e,typeName:F.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...J(t)});var Yo=class extends X{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ac(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ar(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ar(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Yo.create=(e,t)=>new Yo({innerType:e,typeName:F.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...J(t)});var vc=class extends X{_parse(t){if(this._getType(t)!==z.nan){let n=this._getOrReturnCtx(t);return T(n,{code:E.invalid_type,expected:z.nan,received:n.parsedType}),Z}return{status:"valid",value:t.data}}};vc.create=e=>new vc({typeName:F.ZodNaN,...J(e)});var ale=Symbol("zod_brand"),kp=class extends X{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},$p=class e extends X{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Z:o.status==="dirty"?(r.dirty(),Mo(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Z:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:F.ZodPipeline})}},Qo=class extends X{_parse(t){let r=this._def.innerType._parse(t),n=i=>(Ei(i)&&(i.value=Object.freeze(i.value)),i);return ac(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Qo.create=(e,t)=>new Qo({innerType:e,typeName:F.ZodReadonly,...J(t)});var sle={object:sr.lazycreate},F;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(F||(F={}));var cle=Fo.create,ule=sc.create,lle=vc.create,ple=cc.create,dle=uc.create,fle=lc.create,mle=pc.create,hle=Zo.create,vle=Bo.create,gle=dc.create,yle=Dn.create,xle=Vr.create,ble=fc.create,_le=Un.create,S7=sr.create,wle=sr.strictCreate,kle=Vo.create,$le=Ug.create,Sle=Ho.create,Ele=ln.create,Ole=Lg.create,Ile=mc.create,Tle=hc.create,zle=Fg.create,Ple=Jo.create,jle=Go.create,Ale=Wo.create,Cle=Ko.create,Rle=Oi.create,Nle=Er.create,qle=Sr.create,Dle=pn.create,Ule=Er.createWithPreprocess,Mle=$p.create;function ea(e){return!!e._zod}function Mn(e,t){return ea(e)?Qi(e,t):e.safeParse(t)}function Sp(e){if(!e)return;let t;if(ea(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function BI(e){if(ea(e)){let o=e._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}function Ln(e){return e==="completed"||e==="failed"||e==="cancelled"}var j7=Symbol("Let zodToJsonSchema decide on which parser to use");var ode=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Zg(e){let r=Sp(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=BI(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Bg(e,t){let r=Mn(e,t);if(!r.success)throw r.error;return r.data}var D7=6e4,Ep=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Gu,r=>{this._oncancel(r)}),this.setNotificationHandler(Xu,r=>{this._onprogress(r)}),this.setRequestHandler(Ku,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Yu,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new W(ie.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(el,async(r,n)=>{let i=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(s.type==="response"||s.type==="error"){let u=s.message,c=u.id,l=this._requestResolvers.get(c);if(l)if(this._requestResolvers.delete(c),s.type==="response")l(u);else{let p=u,d=new W(p.error.code,p.error.message,p.error.data);l(d)}else{let p=s.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}let a=await this._taskStore.getTask(o,n.sessionId);if(!a)throw new W(ie.InvalidParams,`Task not found: ${o}`);if(!Ln(a.status))return await this._waitForTaskUpdate(o,n.signal),await i();if(Ln(a.status)){let s=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[En]:{taskId:o}}}}return await i()};return await i()}),this.setRequestHandler(tl,async(r,n)=>{try{let{tasks:i,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:o,_meta:{}}}catch(i){throw new W(ie.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(nl,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new W(ie.InvalidParams,`Task not found: ${r.params.taskId}`);if(Ln(i.status))throw new W(ie.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new W(ie.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(i){throw i instanceof W?i:new W(ie.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,i,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:i})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),W.fromError(ie.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let i=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{i?.(o,a),on(o)||ro(o)?this._onresponse(o):On(o)?this._onrequest(o,a):Lw(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=W.fromError(ie.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,i=this._transport,o=t.params?._meta?.[En]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:ie.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},i?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):i?.send(l).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);let s=Dw(t.params)?t.params.task:void 0,u=this._taskStore?this.requestTaskStore(t,i?.sessionId):void 0,c={signal:a.signal,sessionId:i?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{let p={relatedRequestId:t.id};o&&(p.relatedTask={taskId:o}),await this.notification(l,p)},sendRequest:async(l,p,d)=>{let m={...d,relatedRequestId:t.id};o&&!m.relatedTask&&(m.relatedTask={taskId:o});let f=m.relatedTask?.taskId??o;return f&&u&&await u.updateTaskStatus(f,"input_required"),await this.request(l,p,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:o,taskStore:u,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async l=>{if(a.signal.aborted)return;let p={result:l,jsonrpc:"2.0",id:t.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)},async l=>{if(a.signal.aborted)return;let p={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:ie.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,i=Number(r),o=this._progressHandlers.get(i);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let a=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(u){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),a(u);return}o(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),on(t))n(t);else{let a=new W(t.error.code,t.error.message,t.error.data);n(a)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(on(t)&&t.result&&typeof t.result=="object"){let a=t.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,r))}}if(o||this._progressHandlers.delete(r),on(t))i(t);else{let a=W.fromError(t.error.code,t.error.message,t.error.data);i(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:i}=n??{};if(!i){try{yield{type:"result",result:await this.request(t,r,n)}}catch(a){yield{type:"error",error:a instanceof W?a:new W(ie.InternalError,String(a))}}return}let o;try{let a=await this.request(t,no,n);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new W(ie.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:s},Ln(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:s.status==="failed"?yield{type:"error",error:new W(ie.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new W(ie.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let u=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,u)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof W?a:new W(ie.InternalError,String(a))}}}request(t,r,n){let{relatedRequestId:i,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:u}=n??{};return new Promise((c,l)=>{let p=x=>{l(x)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(x){p(x);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:d}}),s&&(m.params={...m.params,task:s}),u&&(m.params={...m.params,_meta:{...m.params?._meta||{},[En]:u}});let f=x=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(x)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:a}).catch($=>this._onerror(new Error(`Failed to send cancellation: ${$}`)));let _=x instanceof W?x:new W(ie.RequestTimeout,String(x));l(_)};this._responseHandlers.set(d,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return l(x);try{let _=Mn(r,x.result);_.success?c(_.data):l(_.error)}catch(_){l(_)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let h=n?.timeout??D7,v=()=>f(W.fromError(ie.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(d,h,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let y=u?.taskId;if(y){let x=_=>{let $=this._responseHandlers.get(d);$?$(_):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,x),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(d),l(_)})}else this._transport.send(m,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:a}).catch(x=>{this._cleanupTimeout(d),l(x)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Qu,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},rl,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Zw,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[En]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[En]:r.relatedTask}}}),this._transport?.send(s,r).catch(u=>this._onerror(u))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[En]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){let n=Zg(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,o)=>{let a=Bg(t,i);return Promise.resolve(r(a,o))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=Zg(t);this._notificationHandlers.set(n,i=>{let o=Bg(t,i);return Promise.resolve(r(o))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,i)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let i of n)if(i.type==="request"&&On(i.message)){let o=i.message.id,a=this._requestResolvers.get(o);a?(a(new W(ie.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(t);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,o)=>{if(r.aborted){o(new W(ie.InvalidRequest,"Request cancelled"));return}let a=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(a),o(new W(ie.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!t)throw new Error("No request provided");return await n.createTask(i,t.id,{method:t.method,params:t.params},r)},getTask:async i=>{let o=await n.getTask(i,r);if(!o)throw new W(ie.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(i,o,a)=>{await n.storeTaskResult(i,o,a,r);let s=await n.getTask(i,r);if(s){let u=rs.parse({method:"notifications/tasks/status",params:s});await this.notification(u),Ln(s.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,o,a)=>{let s=await n.getTask(i,r);if(!s)throw new W(ie.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(Ln(s.status))throw new W(ie.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,o,a,r);let u=await n.getTask(i,r);if(u){let c=rs.parse({method:"notifications/tasks/status",params:u});await this.notification(c),Ln(u.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function VI(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function HI(e,t){let r={...e};for(let n in t){let i=n,o=t[i];if(o===void 0)continue;let a=r[i];VI(a)&&VI(o)?r[i]={...a,...o}:r[i]=o}return r}var DP=Aa(Ix(),1),UP=Aa(qP(),1);function OK(){let e=new DP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,UP.default)(e),e}var cd=class{constructor(t){this._ajv=t??OK()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var ud=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function MP(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function LP(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var ld=class extends Ep{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(os.options.map((n,i)=>[n,i])),this.isMessageIgnored=(n,i)=>{let o=this._loggingLevels.get(i);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new cd,this.setRequestHandler(Wu,n=>this._oninitialize(n)),this.setNotificationHandler(sh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(hh,async(n,i)=>{let o=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,s=os.safeParse(a);return s.success&&this._loggingLevels.set(o,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ud(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=HI(this._capabilities,t)}setRequestHandler(t,r){let i=Sp(t)?.method;if(!i)throw new Error("Schema is missing a method literal");let o;if(ea(i)){let s=i;o=s._zod?.def?.value??s.value}else{let s=i;o=s._def?.value??s.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(u,c)=>{let l=Mn(is,u);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new W(ie.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:p}=l.data,d=await Promise.resolve(r(u,c));if(p.task){let f=Mn(no,d);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new W(ie.InvalidParams,`Invalid task creation result: ${h}`)}return f.data}let m=Mn(il,d);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new W(ie.InvalidParams,`Invalid tools/call result: ${f}`)}return m.data};return super.setRequestHandler(t,s)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){LP(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&MP(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:Ga.includes(r)?r:nh,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Ju)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],i=Array.isArray(n.content)?n.content:[n.content],o=i.some(c=>c.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],u=s.some(c=>c.type==="tool_use");if(o){if(i.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let c=new Set(s.filter(p=>p.type==="tool_use").map(p=>p.id)),l=new Set(i.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(c.size!==l.size||![...c].every(p=>l.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},gh,r):this.request({method:"sampling/createMessage",params:t},vh,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let i=t;return this.request({method:"elicitation/create",params:i},ol,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let i=t.mode==="form"?t:{...t,mode:"form"},o=await this.request({method:"elicitation/create",params:i},ol,r);if(o.action==="accept"&&o.content&&i.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(i.requestedSchema)(o.content);if(!s.valid)throw new W(ie.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof W?a:new W(ie.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return o}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},yh,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}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"})}};var pd=class{constructor(t){this.openApiSpec=t;this.schemaCache={};this.nameCounter=0}internalResolveRef(t,r){if(!t.startsWith("#/")||r.has(t))return null;let n=t.replace(/^#\//,"").split("/"),i=this.openApiSpec;for(let o of n)if(i=i[o],!i)return null;return r.add(t),i}convertOpenApiSchemaToJsonSchema(t,r,n=!1){if("$ref"in t){let o=t.$ref;if(!n){if(o.startsWith("#/components/schemas/"))return{$ref:o.replace(/^#\/components\/schemas\//,"#/$defs/"),..."description"in t?{description:t.description}:{}};console.error(`Attempting to resolve ref ${o} not found in components collection.`)}let a={$ref:o};if("description"in t&&t.description&&(a.description=t.description),this.schemaCache[o])return this.schemaCache[o];let s=this.internalResolveRef(o,r);if(s){let u=this.convertOpenApiSchemaToJsonSchema(s,r,n);return this.schemaCache[o]=u,u}else return console.error(`Failed to resolve ref ${o}`),{$ref:o.replace(/^#\/components\/schemas\//,"#/$defs/"),description:"description"in t?t.description??"":""}}let i={};if(t.type&&(i.type=t.type),t.format==="binary"){i.format="uri-reference";let o="absolute paths to local files";i.description=t.description?`${t.description} (${o})`:o}else t.format&&(i.format=t.format),t.description&&(i.description=t.description);if(t.enum&&(i.enum=t.enum),t.default!==void 0&&(i.default=t.default),t.type==="object"){if(i.type="object",t.properties){i.properties={};for(let[o,a]of Object.entries(t.properties))i.properties[o]=this.convertOpenApiSchemaToJsonSchema(a,r,n)}t.required&&(i.required=t.required),t.additionalProperties===!0||t.additionalProperties===void 0?i.additionalProperties=!0:t.additionalProperties&&typeof t.additionalProperties=="object"?i.additionalProperties=this.convertOpenApiSchemaToJsonSchema(t.additionalProperties,r,n):i.additionalProperties=!1}return t.type==="array"&&t.items&&(i.type="array",i.items=this.convertOpenApiSchemaToJsonSchema(t.items,r,n)),t.oneOf&&(i.oneOf=t.oneOf.map(o=>this.convertOpenApiSchemaToJsonSchema(o,r,n))),t.anyOf&&(i.anyOf=t.anyOf.map(o=>this.convertOpenApiSchemaToJsonSchema(o,r,n))),t.allOf&&(i.allOf=t.allOf.map(o=>this.convertOpenApiSchemaToJsonSchema(o,r,n))),i}convertToMCPTools(){let t="API",r={},n={[t]:{methods:[]}},i={};for(let[o,a]of Object.entries(this.openApiSpec.paths||{}))if(a)for(let[s,u]of Object.entries(a)){if(!this.isOperation(s,u))continue;let c=this.convertOperationToMCPMethod(u,s,o);if(c){let l=this.ensureUniqueName(c.name);c.name=l,c.description=this.getDescription(c.description),n[t].methods.push(c),r[t+"-"+l]={...u,method:s,path:o},i[t+"-"+l]={openApi:{...u,method:s,path:o},mcp:c}}}return{tools:n,openApiLookup:r,zip:i}}convertToOpenAITools(){let t=[];for(let[r,n]of Object.entries(this.openApiSpec.paths||{}))if(n)for(let[i,o]of Object.entries(n)){if(!this.isOperation(i,o))continue;let a=this.convertOperationToJsonSchema(o,i,r),s={type:"function",function:{name:o.operationId,description:this.getDescription(o.summary||o.description||""),parameters:a}};t.push(s)}return t}convertToAnthropicTools(){let t=[];for(let[r,n]of Object.entries(this.openApiSpec.paths||{}))if(n)for(let[i,o]of Object.entries(n)){if(!this.isOperation(i,o))continue;let a=this.convertOperationToJsonSchema(o,i,r),s={name:o.operationId,description:this.getDescription(o.summary||o.description||""),input_schema:a};t.push(s)}return t}convertComponentsToJsonSchema(){let t=this.openApiSpec.components||{},r={};for(let[n,i]of Object.entries(t.schemas||{}))r[n]=this.convertOpenApiSchemaToJsonSchema(i,new Set);return r}convertOperationToJsonSchema(t,r,n){let i={type:"object",properties:{},required:[],$defs:this.convertComponentsToJsonSchema()};if(t.parameters)for(let o of t.parameters){let a=this.resolveParameter(o);if(a&&a.schema){let s=this.convertOpenApiSchemaToJsonSchema(a.schema,new Set);a.description&&(s.description=a.description),i.properties[a.name]=s,a.required&&i.required.push(a.name)}}if(t.requestBody){let o=this.resolveRequestBody(t.requestBody);if(o?.content&&o.content["application/json"]?.schema){let a=this.convertOpenApiSchemaToJsonSchema(o.content["application/json"].schema,new Set);if(a.type==="object"&&a.properties){for(let[s,u]of Object.entries(a.properties))i.properties[s]=u;a.required&&i.required.push(...a.required)}}}return i}isOperation(t,r){return["get","post","put","delete","patch"].includes(t.toLowerCase())}isParameterObject(t){return!("$ref"in t)}isRequestBodyObject(t){return!("$ref"in t)}resolveParameter(t){if(this.isParameterObject(t))return t;{let r=this.internalResolveRef(t.$ref,new Set);if(r&&r.name)return r}return null}resolveRequestBody(t){if(this.isRequestBodyObject(t))return t;{let r=this.internalResolveRef(t.$ref,new Set);if(r)return r}return null}resolveResponse(t){if("$ref"in t){let r=this.internalResolveRef(t.$ref,new Set);return r||null}return t}convertOperationToMCPMethod(t,r,n){if(!t.operationId)return console.warn(`Operation without operationId at ${r} ${n}`),null;let i=t.operationId,o={$defs:this.convertComponentsToJsonSchema(),type:"object",properties:{},required:[]};if(t.parameters)for(let u of t.parameters){let c=this.resolveParameter(u);if(c&&c.schema){let l=this.convertOpenApiSchemaToJsonSchema(c.schema,new Set,!1);c.description&&(l.description=c.description),o.properties[c.name]=l,c.required&&o.required.push(c.name)}}if(t.requestBody){let u=this.resolveRequestBody(t.requestBody);if(u?.content){if(u.content["multipart/form-data"]?.schema){let c=this.convertOpenApiSchemaToJsonSchema(u.content["multipart/form-data"].schema,new Set,!1);if(c.type==="object"&&c.properties){for(let[l,p]of Object.entries(c.properties))o.properties[l]=p;c.required&&o.required.push(...c.required)}}else if(u.content["application/json"]?.schema){let c=this.convertOpenApiSchemaToJsonSchema(u.content["application/json"].schema,new Set,!1);if(c.type==="object"&&c.properties){for(let[l,p]of Object.entries(c.properties))o.properties[l]=p;c.required&&o.required.push(...c.required)}else o.properties.body=c,o.required.push("body")}}}let a=t.summary||t.description||"";if(t.responses){let u=Object.entries(t.responses).filter(([c])=>c.startsWith("4")||c.startsWith("5")).map(([c,l])=>{let d=this.resolveResponse(l)?.description||"";return`${c}: ${d}`});u.length>0&&(a+=`
|
|
146
|
+
`,t.enqueue(r.encode(o)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(t,r){try{let n=t.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let i=t.headers.get("content-type");if(!i||!i.includes("application/json"))return this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let o={headers:Object.fromEntries(t.headers.entries())},a;if(r?.parsedBody!==void 0)a=r.parsedBody;else try{a=await t.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let s;try{Array.isArray(a)?s=a.map(y=>Ka.parse(y)):s=[Ka.parse(a)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let u=s.some(Ya);if(u){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(s.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!u){let y=this.validateSession(t);if(y)return y;let x=this.validateProtocolVersion(t);if(x)return x}if(!s.some(On)){for(let y of s)this.onmessage?.(y,{authInfo:r?.authInfo,requestInfo:o});return new Response(null,{status:202})}let l=crypto.randomUUID(),p=s.find(y=>Ya(y)),d=p?p.params.protocolVersion:t.headers.get("mcp-protocol-version")??Rw;if(this._enableJsonResponse)return new Promise(y=>{this._streamMapping.set(l,{resolveJson:y,cleanup:()=>{this._streamMapping.delete(l)}});for(let x of s)On(x)&&this._requestToStreamMapping.set(x.id,l);for(let x of s)this.onmessage?.(x,{authInfo:r?.authInfo,requestInfo:o})});let m=new TextEncoder,f,h=new ReadableStream({start:y=>{f=y},cancel:()=>{this._streamMapping.delete(l)}}),v={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(v["mcp-session-id"]=this.sessionId);for(let y of s)On(y)&&(this._streamMapping.set(l,{controller:f,encoder:m,cleanup:()=>{this._streamMapping.delete(l);try{f.close()}catch{}}}),this._requestToStreamMapping.set(y.id,l));await this.writePrimingEvent(f,m,l,d);for(let y of s){let x,_;On(y)&&this._eventStore&&d>="2025-11-25"&&(x=()=>{this.closeSSEStream(y.id)},_=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(y,{authInfo:r?.authInfo,requestInfo:o,closeSSEStream:x,closeStandaloneSSEStream:_})}return new Response(h,{status:200,headers:v})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(t){let r=this.validateSession(t);if(r)return r;let n=this.validateProtocolVersion(t);return n||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(t){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=t.headers.get("mcp-session-id");if(!r)return this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(t){let r=t.headers.get("mcp-protocol-version");if(r!==null&&!Ga.includes(r))return this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Ga.join(", ")})`)}async close(){this._streamMapping.forEach(({cleanup:t})=>{t()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(t){let r=this._requestToStreamMapping.get(t);if(!r)return;let n=this._streamMapping.get(r);n&&n.cleanup()}closeStandaloneSSEStream(){let t=this._streamMapping.get(this._standaloneSseStreamId);t&&t.cleanup()}async send(t,r){let n=r?.relatedRequestId;if((on(t)||ro(t))&&(n=t.id),n===void 0){if(on(t)||ro(t))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let a;this._eventStore&&(a=await this._eventStore.storeEvent(this._standaloneSseStreamId,t));let s=this._streamMapping.get(this._standaloneSseStreamId);if(s===void 0)return;s.controller&&s.encoder&&this.writeSSEEvent(s.controller,s.encoder,t,a);return}let i=this._requestToStreamMapping.get(n);if(!i)throw new Error(`No connection established for request ID: ${String(n)}`);let o=this._streamMapping.get(i);if(!this._enableJsonResponse&&o?.controller&&o?.encoder){let a;this._eventStore&&(a=await this._eventStore.storeEvent(i,t)),this.writeSSEEvent(o.controller,o.encoder,t,a)}if(on(t)||ro(t)){this._requestResponseMap.set(n,t);let a=Array.from(this._requestToStreamMapping.entries()).filter(([u,c])=>c===i).map(([u])=>u);if(a.every(u=>this._requestResponseMap.has(u))){if(!o)throw new Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&o.resolveJson){let u={"Content-Type":"application/json"};this.sessionId!==void 0&&(u["mcp-session-id"]=this.sessionId);let c=a.map(l=>this._requestResponseMap.get(l));c.length===1?o.resolveJson(new Response(JSON.stringify(c[0]),{status:200,headers:u})):o.resolveJson(new Response(JSON.stringify(c),{status:200,headers:u}))}else o.cleanup();for(let u of a)this._requestResponseMap.delete(u),this._requestToStreamMapping.delete(u)}}}};var dl=class{constructor(t={}){this._requestContext=new WeakMap,this._webStandardTransport=new pl(t),this._requestListener=kh(async r=>{let n=this._requestContext.get(r);return this._webStandardTransport.handleRequest(r,{authInfo:n?.authInfo,parsedBody:n?.parsedBody})})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(t){this._webStandardTransport.onclose=t}get onclose(){return this._webStandardTransport.onclose}set onerror(t){this._webStandardTransport.onerror=t}get onerror(){return this._webStandardTransport.onerror}set onmessage(t){this._webStandardTransport.onmessage=t}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(t,r){return this._webStandardTransport.send(t,r)}async handleRequest(t,r,n){let i=t.auth;await kh(async a=>this._webStandardTransport.handleRequest(a,{authInfo:i,parsedBody:n}))(t,r)}closeSSEStream(t){this._webStandardTransport.closeSSEStream(t)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};var E0=Aa(NI(),1);import{randomUUID as Xre,randomBytes as Yre}from"node:crypto";import Jre from"node:fs";import Gre from"node:path";var re;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(s=>typeof i[i[s]]!="number"),a={};for(let s of o)a[s]=i[s];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},e.find=(i,o)=>{for(let a of i)if(o(a))return a},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(re||(re={}));var qI;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(qI||(qI={}));var z=re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),cn=e=>{switch(typeof e){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(e)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(e)?z.array:e===null?z.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?z.promise:typeof Map<"u"&&e instanceof Map?z.map:typeof Set<"u"&&e instanceof Set?z.set:typeof Date<"u"&&e instanceof Date?z.date:z.object;default:return z.unknown}};var E=re.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var ar=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let s=n,u=0;for(;u<a.path.length;){let c=a.path[u];u===a.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(r(a))):s[c]=s[c]||{_errors:[]},s=s[c],u++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,re.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r=Object.create(null),n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};ar.create=e=>new ar(e);var t7=(e,t)=>{let r;switch(e.code){case E.invalid_type:e.received===z.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case E.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,re.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:r=`Unrecognized key(s) in object: ${re.joinValues(e.keys,", ")}`;break;case E.invalid_union:r="Invalid input";break;case E.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${re.joinValues(e.options)}`;break;case E.invalid_enum_value:r=`Invalid enum value. Expected ${re.joinValues(e.options)}, received '${e.received}'`;break;case E.invalid_arguments:r="Invalid function arguments";break;case E.invalid_return_type:r="Invalid function return type";break;case E.invalid_date:r="Invalid date";break;case E.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:re.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case E.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case E.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case E.custom:r="Invalid input";break;case E.invalid_intersection_types:r="Intersection results could not be merged";break;case E.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case E.not_finite:r="Number must be finite";break;default:r=t.defaultError,re.assertNever(e)}return{message:r}},qn=t7;var r7=qn;function oc(){return r7}var wp=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let s="",u=n.filter(c=>!!c).slice().reverse();for(let c of u)s=c(a,{data:t,defaultError:s}).message;return{...i,path:o,message:s}};function T(e,t){let r=oc(),n=wp({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===qn?void 0:qn].filter(i=>!!i)});e.common.issues.push(n)}var wt=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return Z;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let o=await i.key,a=await i.value;n.push({key:o,value:a})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return Z;o.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(n[o.value]=a.value)}return{status:t.value,value:n}}},Z=Object.freeze({status:"aborted"}),Mo=e=>({status:"dirty",value:e}),Ct=e=>({status:"valid",value:e}),Ng=e=>e.status==="aborted",qg=e=>e.status==="dirty",Ei=e=>e.status==="valid",ac=e=>typeof Promise<"u"&&e instanceof Promise;var C;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(C||(C={}));var fr=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},DI=(e,t)=>{if(Ei(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new ar(e.common.issues);return this._error=r,this._error}}};function J(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(a,s)=>{let{message:u}=e;return a.code==="invalid_enum_value"?{message:u??s.defaultError}:typeof s.data>"u"?{message:u??n??s.defaultError}:a.code!=="invalid_type"?{message:s.defaultError}:{message:u??r??s.defaultError}},description:i}}var X=class{get description(){return this._def.description}_getType(t){return cn(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:cn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new wt,ctx:{common:t.parent.common,data:t.data,parsedType:cn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(ac(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:cn(t)},i=this._parseSync({data:t,path:n.path,parent:n});return DI(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:cn(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return Ei(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Ei(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:cn(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(ac(i)?i:Promise.resolve(i));return DI(n,o)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let a=t(i),s=()=>o.addIssue({code:E.custom,...n(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(s(),!1)):a?!0:(s(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new Er({schema:this,typeName:F.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Sr.create(this,this._def)}nullable(){return pn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Un.create(this)}promise(){return Oi.create(this,this._def)}or(t){return Vo.create([this,t],this._def)}and(t){return Ho.create(this,t,this._def)}transform(t){return new Er({...J(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new Xo({...J(this._def),innerType:this,defaultValue:r,typeName:F.ZodDefault})}brand(){return new kp({typeName:F.ZodBranded,type:this,...J(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new Yo({...J(this._def),innerType:this,catchValue:r,typeName:F.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return $p.create(this,t)}readonly(){return Qo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},n7=/^c[^\s-]{8,}$/i,i7=/^[0-9a-z]+$/,o7=/^[0-9A-HJKMNP-TV-Z]{26}$/i,a7=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,s7=/^[a-z0-9_-]{21}$/i,c7=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,u7=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,l7=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,p7="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Dg,d7=/^(?:(?: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])$/,f7=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,m7=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,h7=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,v7=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,g7=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,UI="((\\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])))",y7=new RegExp(`^${UI}$`);function MI(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function x7(e){return new RegExp(`^${MI(e)}$`)}function b7(e){let t=`${UI}T${MI(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function _7(e,t){return!!((t==="v4"||!t)&&d7.test(e)||(t==="v6"||!t)&&m7.test(e))}function w7(e,t){if(!c7.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function k7(e,t){return!!((t==="v4"||!t)&&f7.test(e)||(t==="v6"||!t)&&h7.test(e))}var Fo=class e extends X{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==z.string){let o=this._getOrReturnCtx(t);return T(o,{code:E.invalid_type,expected:z.string,received:o.parsedType}),Z}let n=new wt,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),T(i,{code:E.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),T(i,{code:E.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let a=t.data.length>o.value,s=t.data.length<o.value;(a||s)&&(i=this._getOrReturnCtx(t,i),a?T(i,{code:E.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):s&&T(i,{code:E.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")l7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"email",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Dg||(Dg=new RegExp(p7,"u")),Dg.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"emoji",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")a7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"uuid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")s7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"nanoid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")n7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"cuid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")i7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"cuid2",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")o7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"ulid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),T(i,{validation:"url",code:E.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"regex",code:E.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),T(i,{code:E.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),T(i,{code:E.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),T(i,{code:E.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?b7(o).test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{code:E.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?y7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{code:E.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?x7(o).test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{code:E.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?u7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"duration",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?_7(t.data,o.version)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"ip",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?w7(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"jwt",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?k7(t.data,o.version)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"cidr",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?v7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"base64",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?g7.test(t.data)||(i=this._getOrReturnCtx(t,i),T(i,{validation:"base64url",code:E.invalid_string,message:o.message}),n.dirty()):re.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:E.invalid_string,...C.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...C.errToObj(t)})}url(t){return this._addCheck({kind:"url",...C.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...C.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...C.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...C.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...C.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...C.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...C.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...C.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...C.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...C.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...C.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...C.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...C.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...C.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...C.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...C.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...C.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...C.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...C.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...C.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...C.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...C.errToObj(r)})}nonempty(t){return this.min(1,C.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Fo.create=e=>new Fo({checks:[],typeName:F.ZodString,coerce:e?.coerce??!1,...J(e)});function $7(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return o%a/10**i}var sc=class e extends X{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==z.number){let o=this._getOrReturnCtx(t);return T(o,{code:E.invalid_type,expected:z.number,received:o.parsedType}),Z}let n,i=new wt;for(let o of this._def.checks)o.kind==="int"?re.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),T(n,{code:E.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),T(n,{code:E.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),T(n,{code:E.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?$7(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),T(n,{code:E.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),T(n,{code:E.not_finite,message:o.message}),i.dirty()):re.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,C.toString(r))}gt(t,r){return this.setLimit("min",t,!1,C.toString(r))}lte(t,r){return this.setLimit("max",t,!0,C.toString(r))}lt(t,r){return this.setLimit("max",t,!1,C.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:C.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:C.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:C.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:C.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&re.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};sc.create=e=>new sc({checks:[],typeName:F.ZodNumber,coerce:e?.coerce||!1,...J(e)});var cc=class e extends X{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==z.bigint)return this._getInvalidInput(t);let n,i=new wt;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),T(n,{code:E.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),T(n,{code:E.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),T(n,{code:E.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):re.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return T(r,{code:E.invalid_type,expected:z.bigint,received:r.parsedType}),Z}gte(t,r){return this.setLimit("min",t,!0,C.toString(r))}gt(t,r){return this.setLimit("min",t,!1,C.toString(r))}lte(t,r){return this.setLimit("max",t,!0,C.toString(r))}lt(t,r){return this.setLimit("max",t,!1,C.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:C.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:C.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};cc.create=e=>new cc({checks:[],typeName:F.ZodBigInt,coerce:e?.coerce??!1,...J(e)});var uc=class extends X{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==z.boolean){let n=this._getOrReturnCtx(t);return T(n,{code:E.invalid_type,expected:z.boolean,received:n.parsedType}),Z}return Ct(t.data)}};uc.create=e=>new uc({typeName:F.ZodBoolean,coerce:e?.coerce||!1,...J(e)});var lc=class e extends X{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==z.date){let o=this._getOrReturnCtx(t);return T(o,{code:E.invalid_type,expected:z.date,received:o.parsedType}),Z}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return T(o,{code:E.invalid_date}),Z}let n=new wt,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),T(i,{code:E.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),T(i,{code:E.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):re.assertNever(o);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:C.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:C.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};lc.create=e=>new lc({checks:[],coerce:e?.coerce||!1,typeName:F.ZodDate,...J(e)});var pc=class extends X{_parse(t){if(this._getType(t)!==z.symbol){let n=this._getOrReturnCtx(t);return T(n,{code:E.invalid_type,expected:z.symbol,received:n.parsedType}),Z}return Ct(t.data)}};pc.create=e=>new pc({typeName:F.ZodSymbol,...J(e)});var Zo=class extends X{_parse(t){if(this._getType(t)!==z.undefined){let n=this._getOrReturnCtx(t);return T(n,{code:E.invalid_type,expected:z.undefined,received:n.parsedType}),Z}return Ct(t.data)}};Zo.create=e=>new Zo({typeName:F.ZodUndefined,...J(e)});var Bo=class extends X{_parse(t){if(this._getType(t)!==z.null){let n=this._getOrReturnCtx(t);return T(n,{code:E.invalid_type,expected:z.null,received:n.parsedType}),Z}return Ct(t.data)}};Bo.create=e=>new Bo({typeName:F.ZodNull,...J(e)});var dc=class extends X{constructor(){super(...arguments),this._any=!0}_parse(t){return Ct(t.data)}};dc.create=e=>new dc({typeName:F.ZodAny,...J(e)});var Dn=class extends X{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ct(t.data)}};Dn.create=e=>new Dn({typeName:F.ZodUnknown,...J(e)});var Vr=class extends X{_parse(t){let r=this._getOrReturnCtx(t);return T(r,{code:E.invalid_type,expected:z.never,received:r.parsedType}),Z}};Vr.create=e=>new Vr({typeName:F.ZodNever,...J(e)});var fc=class extends X{_parse(t){if(this._getType(t)!==z.undefined){let n=this._getOrReturnCtx(t);return T(n,{code:E.invalid_type,expected:z.void,received:n.parsedType}),Z}return Ct(t.data)}};fc.create=e=>new fc({typeName:F.ZodVoid,...J(e)});var Un=class e extends X{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==z.array)return T(r,{code:E.invalid_type,expected:z.array,received:r.parsedType}),Z;if(i.exactLength!==null){let a=r.data.length>i.exactLength.value,s=r.data.length<i.exactLength.value;(a||s)&&(T(r,{code:a?E.too_big:E.too_small,minimum:s?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(T(r,{code:E.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(T(r,{code:E.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,s)=>i.type._parseAsync(new fr(r,a,r.path,s)))).then(a=>wt.mergeArray(n,a));let o=[...r.data].map((a,s)=>i.type._parseSync(new fr(r,a,r.path,s)));return wt.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:C.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:C.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:C.toString(r)}})}nonempty(t){return this.min(1,t)}};Un.create=(e,t)=>new Un({type:e,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...J(t)});function Lo(e){if(e instanceof sr){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Sr.create(Lo(n))}return new sr({...e._def,shape:()=>t})}else return e instanceof Un?new Un({...e._def,type:Lo(e.element)}):e instanceof Sr?Sr.create(Lo(e.unwrap())):e instanceof pn?pn.create(Lo(e.unwrap())):e instanceof ln?ln.create(e.items.map(t=>Lo(t))):e}var sr=class e extends X{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=re.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==z.object){let c=this._getOrReturnCtx(t);return T(c,{code:E.invalid_type,expected:z.object,received:c.parsedType}),Z}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof Vr&&this._def.unknownKeys==="strip"))for(let c in i.data)a.includes(c)||s.push(c);let u=[];for(let c of a){let l=o[c],p=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new fr(i,p,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof Vr){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of s)u.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(c==="strict")s.length>0&&(T(i,{code:E.unrecognized_keys,keys:s}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of s){let p=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new fr(i,p,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let l of u){let p=await l.key,d=await l.value;c.push({key:p,value:d,alwaysSet:l.alwaysSet})}return c}).then(c=>wt.mergeObjectSync(n,c)):wt.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(t){return C.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:C.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:F.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of re.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of re.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return Lo(this)}partial(t){let r={};for(let n of re.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of re.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Sr;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return LI(re.objectKeys(this.shape))}};sr.create=(e,t)=>new sr({shape:()=>e,unknownKeys:"strip",catchall:Vr.create(),typeName:F.ZodObject,...J(t)});sr.strictCreate=(e,t)=>new sr({shape:()=>e,unknownKeys:"strict",catchall:Vr.create(),typeName:F.ZodObject,...J(t)});sr.lazycreate=(e,t)=>new sr({shape:e,unknownKeys:"strip",catchall:Vr.create(),typeName:F.ZodObject,...J(t)});var Vo=class extends X{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(o){for(let s of o)if(s.result.status==="valid")return s.result;for(let s of o)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(s=>new ar(s.ctx.common.issues));return T(r,{code:E.invalid_union,unionErrors:a}),Z}if(r.common.async)return Promise.all(n.map(async o=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let u of n){let c={...r,common:{...r.common,issues:[]},parent:null},l=u._parseSync({data:r.data,path:r.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let s=a.map(u=>new ar(u));return T(r,{code:E.invalid_union,unionErrors:s}),Z}}get options(){return this._def.options}};Vo.create=(e,t)=>new Vo({options:e,typeName:F.ZodUnion,...J(t)});var un=e=>e instanceof Jo?un(e.schema):e instanceof Er?un(e.innerType()):e instanceof Go?[e.value]:e instanceof Wo?e.options:e instanceof Ko?re.objectValues(e.enum):e instanceof Xo?un(e._def.innerType):e instanceof Zo?[void 0]:e instanceof Bo?[null]:e instanceof Sr?[void 0,...un(e.unwrap())]:e instanceof pn?[null,...un(e.unwrap())]:e instanceof kp||e instanceof Qo?un(e.unwrap()):e instanceof Yo?un(e._def.innerType):[],Ug=class e extends X{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==z.object)return T(r,{code:E.invalid_type,expected:z.object,received:r.parsedType}),Z;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(T(r,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Z)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let o of r){let a=un(o.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let s of a){if(i.has(s))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(s)}`);i.set(s,o)}}return new e({typeName:F.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...J(n)})}};function Mg(e,t){let r=cn(e),n=cn(t);if(e===t)return{valid:!0,data:e};if(r===z.object&&n===z.object){let i=re.objectKeys(t),o=re.objectKeys(e).filter(s=>i.indexOf(s)!==-1),a={...e,...t};for(let s of o){let u=Mg(e[s],t[s]);if(!u.valid)return{valid:!1};a[s]=u.data}return{valid:!0,data:a}}else if(r===z.array&&n===z.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let a=e[o],s=t[o],u=Mg(a,s);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return r===z.date&&n===z.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Ho=class extends X{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,a)=>{if(Ng(o)||Ng(a))return Z;let s=Mg(o.value,a.value);return s.valid?((qg(o)||qg(a))&&r.dirty(),{status:r.value,value:s.data}):(T(n,{code:E.invalid_intersection_types}),Z)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,a])=>i(o,a)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Ho.create=(e,t,r)=>new Ho({left:e,right:t,typeName:F.ZodIntersection,...J(r)});var ln=class e extends X{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==z.array)return T(n,{code:E.invalid_type,expected:z.array,received:n.parsedType}),Z;if(n.data.length<this._def.items.length)return T(n,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Z;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((a,s)=>{let u=this._def.items[s]||this._def.rest;return u?u._parse(new fr(n,a,n.path,s)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>wt.mergeArray(r,a)):wt.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ln.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ln({items:e,typeName:F.ZodTuple,rest:null,...J(t)})};var Lg=class e extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==z.object)return T(n,{code:E.invalid_type,expected:z.object,received:n.parsedType}),Z;let i=[],o=this._def.keyType,a=this._def.valueType;for(let s in n.data)i.push({key:o._parse(new fr(n,s,n.path,s)),value:a._parse(new fr(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?wt.mergeObjectAsync(r,i):wt.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof X?new e({keyType:t,valueType:r,typeName:F.ZodRecord,...J(n)}):new e({keyType:Fo.create(),valueType:t,typeName:F.ZodRecord,...J(r)})}},mc=class extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==z.map)return T(n,{code:E.invalid_type,expected:z.map,received:n.parsedType}),Z;let i=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([s,u],c)=>({key:i._parse(new fr(n,s,n.path,[c,"key"])),value:o._parse(new fr(n,u,n.path,[c,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let u of a){let c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return Z;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),s.set(c.value,l.value)}return{status:r.value,value:s}})}else{let s=new Map;for(let u of a){let c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return Z;(c.status==="dirty"||l.status==="dirty")&&r.dirty(),s.set(c.value,l.value)}return{status:r.value,value:s}}}};mc.create=(e,t,r)=>new mc({valueType:t,keyType:e,typeName:F.ZodMap,...J(r)});var hc=class e extends X{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==z.set)return T(n,{code:E.invalid_type,expected:z.set,received:n.parsedType}),Z;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(T(n,{code:E.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(T(n,{code:E.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function a(u){let c=new Set;for(let l of u){if(l.status==="aborted")return Z;l.status==="dirty"&&r.dirty(),c.add(l.value)}return{status:r.value,value:c}}let s=[...n.data.values()].map((u,c)=>o._parse(new fr(n,u,n.path,c)));return n.common.async?Promise.all(s).then(u=>a(u)):a(s)}min(t,r){return new e({...this._def,minSize:{value:t,message:C.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:C.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};hc.create=(e,t)=>new hc({valueType:e,minSize:null,maxSize:null,typeName:F.ZodSet,...J(t)});var Fg=class e extends X{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==z.function)return T(r,{code:E.invalid_type,expected:z.function,received:r.parsedType}),Z;function n(s,u){return wp({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,oc(),qn].filter(c=>!!c),issueData:{code:E.invalid_arguments,argumentsError:u}})}function i(s,u){return wp({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,oc(),qn].filter(c=>!!c),issueData:{code:E.invalid_return_type,returnTypeError:u}})}let o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Oi){let s=this;return Ct(async function(...u){let c=new ar([]),l=await s._def.args.parseAsync(u,o).catch(m=>{throw c.addIssue(n(u,m)),c}),p=await Reflect.apply(a,this,l);return await s._def.returns._def.type.parseAsync(p,o).catch(m=>{throw c.addIssue(i(p,m)),c})})}else{let s=this;return Ct(function(...u){let c=s._def.args.safeParse(u,o);if(!c.success)throw new ar([n(u,c.error)]);let l=Reflect.apply(a,this,c.data),p=s._def.returns.safeParse(l,o);if(!p.success)throw new ar([i(l,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ln.create(t).rest(Dn.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||ln.create([]).rest(Dn.create()),returns:r||Dn.create(),typeName:F.ZodFunction,...J(n)})}},Jo=class extends X{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Jo.create=(e,t)=>new Jo({getter:e,typeName:F.ZodLazy,...J(t)});var Go=class extends X{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return T(r,{received:r.data,code:E.invalid_literal,expected:this._def.value}),Z}return{status:"valid",value:t.data}}get value(){return this._def.value}};Go.create=(e,t)=>new Go({value:e,typeName:F.ZodLiteral,...J(t)});function LI(e,t){return new Wo({values:e,typeName:F.ZodEnum,...J(t)})}var Wo=class e extends X{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return T(r,{expected:re.joinValues(n),received:r.parsedType,code:E.invalid_type}),Z}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return T(r,{received:r.data,code:E.invalid_enum_value,options:n}),Z}return Ct(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};Wo.create=LI;var Ko=class extends X{_parse(t){let r=re.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==z.string&&n.parsedType!==z.number){let i=re.objectValues(r);return T(n,{expected:re.joinValues(i),received:n.parsedType,code:E.invalid_type}),Z}if(this._cache||(this._cache=new Set(re.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=re.objectValues(r);return T(n,{received:n.data,code:E.invalid_enum_value,options:i}),Z}return Ct(t.data)}get enum(){return this._def.values}};Ko.create=(e,t)=>new Ko({values:e,typeName:F.ZodNativeEnum,...J(t)});var Oi=class extends X{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==z.promise&&r.common.async===!1)return T(r,{code:E.invalid_type,expected:z.promise,received:r.parsedType}),Z;let n=r.parsedType===z.promise?r.data:Promise.resolve(r.data);return Ct(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Oi.create=(e,t)=>new Oi({type:e,typeName:F.ZodPromise,...J(t)});var Er=class extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:a=>{T(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async s=>{if(r.value==="aborted")return Z;let u=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return u.status==="aborted"?Z:u.status==="dirty"?Mo(u.value):r.value==="dirty"?Mo(u.value):u});{if(r.value==="aborted")return Z;let s=this._def.schema._parseSync({data:a,path:n.path,parent:n});return s.status==="aborted"?Z:s.status==="dirty"?Mo(s.value):r.value==="dirty"?Mo(s.value):s}}if(i.type==="refinement"){let a=s=>{let u=i.refinement(s,o);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Z:(s.status==="dirty"&&r.dirty(),a(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?Z:(s.status==="dirty"&&r.dirty(),a(s.value).then(()=>({status:r.value,value:s.value}))))}if(i.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ei(a))return Z;let s=i.transform(a.value,o);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Ei(a)?Promise.resolve(i.transform(a.value,o)).then(s=>({status:r.value,value:s})):Z);re.assertNever(i)}};Er.create=(e,t,r)=>new Er({schema:e,typeName:F.ZodEffects,effect:t,...J(r)});Er.createWithPreprocess=(e,t,r)=>new Er({schema:t,effect:{type:"preprocess",transform:e},typeName:F.ZodEffects,...J(r)});var Sr=class extends X{_parse(t){return this._getType(t)===z.undefined?Ct(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Sr.create=(e,t)=>new Sr({innerType:e,typeName:F.ZodOptional,...J(t)});var pn=class extends X{_parse(t){return this._getType(t)===z.null?Ct(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};pn.create=(e,t)=>new pn({innerType:e,typeName:F.ZodNullable,...J(t)});var Xo=class extends X{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Xo.create=(e,t)=>new Xo({innerType:e,typeName:F.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...J(t)});var Yo=class extends X{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ac(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ar(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ar(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Yo.create=(e,t)=>new Yo({innerType:e,typeName:F.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...J(t)});var vc=class extends X{_parse(t){if(this._getType(t)!==z.nan){let n=this._getOrReturnCtx(t);return T(n,{code:E.invalid_type,expected:z.nan,received:n.parsedType}),Z}return{status:"valid",value:t.data}}};vc.create=e=>new vc({typeName:F.ZodNaN,...J(e)});var ale=Symbol("zod_brand"),kp=class extends X{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},$p=class e extends X{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Z:o.status==="dirty"?(r.dirty(),Mo(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Z:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:F.ZodPipeline})}},Qo=class extends X{_parse(t){let r=this._def.innerType._parse(t),n=i=>(Ei(i)&&(i.value=Object.freeze(i.value)),i);return ac(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Qo.create=(e,t)=>new Qo({innerType:e,typeName:F.ZodReadonly,...J(t)});var sle={object:sr.lazycreate},F;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(F||(F={}));var cle=Fo.create,ule=sc.create,lle=vc.create,ple=cc.create,dle=uc.create,fle=lc.create,mle=pc.create,hle=Zo.create,vle=Bo.create,gle=dc.create,yle=Dn.create,xle=Vr.create,ble=fc.create,_le=Un.create,S7=sr.create,wle=sr.strictCreate,kle=Vo.create,$le=Ug.create,Sle=Ho.create,Ele=ln.create,Ole=Lg.create,Ile=mc.create,Tle=hc.create,zle=Fg.create,Ple=Jo.create,jle=Go.create,Ale=Wo.create,Cle=Ko.create,Rle=Oi.create,Nle=Er.create,qle=Sr.create,Dle=pn.create,Ule=Er.createWithPreprocess,Mle=$p.create;function ea(e){return!!e._zod}function Mn(e,t){return ea(e)?Qi(e,t):e.safeParse(t)}function Sp(e){if(!e)return;let t;if(ea(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function BI(e){if(ea(e)){let o=e._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}function Ln(e){return e==="completed"||e==="failed"||e==="cancelled"}var j7=Symbol("Let zodToJsonSchema decide on which parser to use");var ode=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Zg(e){let r=Sp(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=BI(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Bg(e,t){let r=Mn(e,t);if(!r.success)throw r.error;return r.data}var D7=6e4,Ep=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Gu,r=>{this._oncancel(r)}),this.setNotificationHandler(Xu,r=>{this._onprogress(r)}),this.setRequestHandler(Ku,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Yu,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new W(ie.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(el,async(r,n)=>{let i=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(s.type==="response"||s.type==="error"){let u=s.message,c=u.id,l=this._requestResolvers.get(c);if(l)if(this._requestResolvers.delete(c),s.type==="response")l(u);else{let p=u,d=new W(p.error.code,p.error.message,p.error.data);l(d)}else{let p=s.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}let a=await this._taskStore.getTask(o,n.sessionId);if(!a)throw new W(ie.InvalidParams,`Task not found: ${o}`);if(!Ln(a.status))return await this._waitForTaskUpdate(o,n.signal),await i();if(Ln(a.status)){let s=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[En]:{taskId:o}}}}return await i()};return await i()}),this.setRequestHandler(tl,async(r,n)=>{try{let{tasks:i,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:o,_meta:{}}}catch(i){throw new W(ie.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(nl,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new W(ie.InvalidParams,`Task not found: ${r.params.taskId}`);if(Ln(i.status))throw new W(ie.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new W(ie.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(i){throw i instanceof W?i:new W(ie.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,i,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:i})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),W.fromError(ie.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let i=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{i?.(o,a),on(o)||ro(o)?this._onresponse(o):On(o)?this._onrequest(o,a):Lw(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=W.fromError(ie.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,i=this._transport,o=t.params?._meta?.[En]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:ie.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},i?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):i?.send(l).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);let s=Dw(t.params)?t.params.task:void 0,u=this._taskStore?this.requestTaskStore(t,i?.sessionId):void 0,c={signal:a.signal,sessionId:i?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{let p={relatedRequestId:t.id};o&&(p.relatedTask={taskId:o}),await this.notification(l,p)},sendRequest:async(l,p,d)=>{let m={...d,relatedRequestId:t.id};o&&!m.relatedTask&&(m.relatedTask={taskId:o});let f=m.relatedTask?.taskId??o;return f&&u&&await u.updateTaskStatus(f,"input_required"),await this.request(l,p,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:o,taskStore:u,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async l=>{if(a.signal.aborted)return;let p={result:l,jsonrpc:"2.0",id:t.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)},async l=>{if(a.signal.aborted)return;let p={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:ie.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,i=Number(r),o=this._progressHandlers.get(i);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let a=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(u){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),a(u);return}o(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),on(t))n(t);else{let a=new W(t.error.code,t.error.message,t.error.data);n(a)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(on(t)&&t.result&&typeof t.result=="object"){let a=t.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,r))}}if(o||this._progressHandlers.delete(r),on(t))i(t);else{let a=W.fromError(t.error.code,t.error.message,t.error.data);i(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:i}=n??{};if(!i){try{yield{type:"result",result:await this.request(t,r,n)}}catch(a){yield{type:"error",error:a instanceof W?a:new W(ie.InternalError,String(a))}}return}let o;try{let a=await this.request(t,no,n);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new W(ie.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:s},Ln(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:s.status==="failed"?yield{type:"error",error:new W(ie.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new W(ie.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let u=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,u)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof W?a:new W(ie.InternalError,String(a))}}}request(t,r,n){let{relatedRequestId:i,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:u}=n??{};return new Promise((c,l)=>{let p=x=>{l(x)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(x){p(x);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:d}}),s&&(m.params={...m.params,task:s}),u&&(m.params={...m.params,_meta:{...m.params?._meta||{},[En]:u}});let f=x=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(x)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:a}).catch($=>this._onerror(new Error(`Failed to send cancellation: ${$}`)));let _=x instanceof W?x:new W(ie.RequestTimeout,String(x));l(_)};this._responseHandlers.set(d,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return l(x);try{let _=Mn(r,x.result);_.success?c(_.data):l(_.error)}catch(_){l(_)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let h=n?.timeout??D7,v=()=>f(W.fromError(ie.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(d,h,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let y=u?.taskId;if(y){let x=_=>{let $=this._responseHandlers.get(d);$?$(_):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,x),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(d),l(_)})}else this._transport.send(m,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:a}).catch(x=>{this._cleanupTimeout(d),l(x)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Qu,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},rl,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Zw,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[En]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[En]:r.relatedTask}}}),this._transport?.send(s,r).catch(u=>this._onerror(u))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[En]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){let n=Zg(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,o)=>{let a=Bg(t,i);return Promise.resolve(r(a,o))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=Zg(t);this._notificationHandlers.set(n,i=>{let o=Bg(t,i);return Promise.resolve(r(o))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,i)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let i of n)if(i.type==="request"&&On(i.message)){let o=i.message.id,a=this._requestResolvers.get(o);a?(a(new W(ie.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(t);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,o)=>{if(r.aborted){o(new W(ie.InvalidRequest,"Request cancelled"));return}let a=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(a),o(new W(ie.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!t)throw new Error("No request provided");return await n.createTask(i,t.id,{method:t.method,params:t.params},r)},getTask:async i=>{let o=await n.getTask(i,r);if(!o)throw new W(ie.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(i,o,a)=>{await n.storeTaskResult(i,o,a,r);let s=await n.getTask(i,r);if(s){let u=rs.parse({method:"notifications/tasks/status",params:s});await this.notification(u),Ln(s.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,o,a)=>{let s=await n.getTask(i,r);if(!s)throw new W(ie.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(Ln(s.status))throw new W(ie.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,o,a,r);let u=await n.getTask(i,r);if(u){let c=rs.parse({method:"notifications/tasks/status",params:u});await this.notification(c),Ln(u.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function VI(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function HI(e,t){let r={...e};for(let n in t){let i=n,o=t[i];if(o===void 0)continue;let a=r[i];VI(a)&&VI(o)?r[i]={...a,...o}:r[i]=o}return r}var DP=Aa(Ix(),1),UP=Aa(qP(),1);function OK(){let e=new DP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,UP.default)(e),e}var cd=class{constructor(t){this._ajv=t??OK()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var ud=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function MP(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function LP(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var ld=class extends Ep{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(os.options.map((n,i)=>[n,i])),this.isMessageIgnored=(n,i)=>{let o=this._loggingLevels.get(i);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new cd,this.setRequestHandler(Wu,n=>this._oninitialize(n)),this.setNotificationHandler(sh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(hh,async(n,i)=>{let o=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,s=os.safeParse(a);return s.success&&this._loggingLevels.set(o,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ud(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=HI(this._capabilities,t)}setRequestHandler(t,r){let i=Sp(t)?.method;if(!i)throw new Error("Schema is missing a method literal");let o;if(ea(i)){let s=i;o=s._zod?.def?.value??s.value}else{let s=i;o=s._def?.value??s.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(u,c)=>{let l=Mn(is,u);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new W(ie.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:p}=l.data,d=await Promise.resolve(r(u,c));if(p.task){let f=Mn(no,d);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new W(ie.InvalidParams,`Invalid task creation result: ${h}`)}return f.data}let m=Mn(il,d);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new W(ie.InvalidParams,`Invalid tools/call result: ${f}`)}return m.data};return super.setRequestHandler(t,s)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){LP(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&MP(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:Ga.includes(r)?r:nh,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Ju)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],i=Array.isArray(n.content)?n.content:[n.content],o=i.some(c=>c.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],u=s.some(c=>c.type==="tool_use");if(o){if(i.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let c=new Set(s.filter(p=>p.type==="tool_use").map(p=>p.id)),l=new Set(i.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(c.size!==l.size||![...c].every(p=>l.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},gh,r):this.request({method:"sampling/createMessage",params:t},vh,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let i=t;return this.request({method:"elicitation/create",params:i},ol,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let i=t.mode==="form"?t:{...t,mode:"form"},o=await this.request({method:"elicitation/create",params:i},ol,r);if(o.action==="accept"&&o.content&&i.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(i.requestedSchema)(o.content);if(!s.valid)throw new W(ie.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof W?a:new W(ie.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return o}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},yh,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}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"})}};var pd=class{constructor(t){this.openApiSpec=t;this.schemaCache={};this.nameCounter=0}internalResolveRef(t,r){if(!t.startsWith("#/")||r.has(t))return null;let n=t.replace(/^#\//,"").split("/"),i=this.openApiSpec;for(let o of n)if(i=i[o],!i)return null;return r.add(t),i}convertOpenApiSchemaToJsonSchema(t,r,n=!1){if("$ref"in t){let o=t.$ref;if(!n){if(o.startsWith("#/components/schemas/"))return{$ref:o.replace(/^#\/components\/schemas\//,"#/$defs/"),..."description"in t?{description:t.description}:{}};console.error(`Attempting to resolve ref ${o} not found in components collection.`)}let a={$ref:o};if("description"in t&&t.description&&(a.description=t.description),this.schemaCache[o])return this.schemaCache[o];let s=this.internalResolveRef(o,r);if(s){let u=this.convertOpenApiSchemaToJsonSchema(s,r,n);return this.schemaCache[o]=u,u}else return console.error(`Failed to resolve ref ${o}`),{$ref:o.replace(/^#\/components\/schemas\//,"#/$defs/"),description:"description"in t?t.description??"":""}}let i={};if(t.type&&(i.type=t.type),t.format==="binary"){i.format="uri-reference";let o="absolute paths to local files";i.description=t.description?`${t.description} (${o})`:o}else t.format&&(i.format=t.format),t.description&&(i.description=t.description);if(t.enum&&(i.enum=t.enum),"const"in t&&t.const!==void 0&&(i.const=t.const),t.default!==void 0&&(i.default=t.default),t.type==="object"){if(i.type="object",t.properties){i.properties={};for(let[o,a]of Object.entries(t.properties))i.properties[o]=this.convertOpenApiSchemaToJsonSchema(a,r,n)}t.required&&(i.required=t.required),t.additionalProperties===!0||t.additionalProperties===void 0?i.additionalProperties=!0:t.additionalProperties&&typeof t.additionalProperties=="object"?i.additionalProperties=this.convertOpenApiSchemaToJsonSchema(t.additionalProperties,r,n):i.additionalProperties=!1}return t.type==="array"&&t.items&&(i.type="array",i.items=this.convertOpenApiSchemaToJsonSchema(t.items,r,n)),t.oneOf&&(i.oneOf=t.oneOf.map(o=>this.convertOpenApiSchemaToJsonSchema(o,r,n))),t.anyOf&&(i.anyOf=t.anyOf.map(o=>this.convertOpenApiSchemaToJsonSchema(o,r,n))),t.allOf&&(i.allOf=t.allOf.map(o=>this.convertOpenApiSchemaToJsonSchema(o,r,n))),i}convertToMCPTools(){let t="API",r={},n={[t]:{methods:[]}},i={};for(let[o,a]of Object.entries(this.openApiSpec.paths||{}))if(a)for(let[s,u]of Object.entries(a)){if(!this.isOperation(s,u))continue;let c=this.convertOperationToMCPMethod(u,s,o);if(c){let l=this.ensureUniqueName(c.name);c.name=l,c.description=this.getDescription(c.description),n[t].methods.push(c),r[t+"-"+l]={...u,method:s,path:o},i[t+"-"+l]={openApi:{...u,method:s,path:o},mcp:c}}}return{tools:n,openApiLookup:r,zip:i}}convertToOpenAITools(){let t=[];for(let[r,n]of Object.entries(this.openApiSpec.paths||{}))if(n)for(let[i,o]of Object.entries(n)){if(!this.isOperation(i,o))continue;let a=this.convertOperationToJsonSchema(o,i,r),s={type:"function",function:{name:o.operationId,description:this.getDescription(o.summary||o.description||""),parameters:a}};t.push(s)}return t}convertToAnthropicTools(){let t=[];for(let[r,n]of Object.entries(this.openApiSpec.paths||{}))if(n)for(let[i,o]of Object.entries(n)){if(!this.isOperation(i,o))continue;let a=this.convertOperationToJsonSchema(o,i,r),s={name:o.operationId,description:this.getDescription(o.summary||o.description||""),input_schema:a};t.push(s)}return t}convertComponentsToJsonSchema(){let t=this.openApiSpec.components||{},r={};for(let[n,i]of Object.entries(t.schemas||{}))r[n]=this.convertOpenApiSchemaToJsonSchema(i,new Set);return r}convertOperationToJsonSchema(t,r,n){let i={type:"object",properties:{},required:[],$defs:this.convertComponentsToJsonSchema()};if(t.parameters)for(let o of t.parameters){let a=this.resolveParameter(o);if(a&&a.schema){let s=this.convertOpenApiSchemaToJsonSchema(a.schema,new Set);a.description&&(s.description=a.description),i.properties[a.name]=s,a.required&&i.required.push(a.name)}}if(t.requestBody){let o=this.resolveRequestBody(t.requestBody);if(o?.content&&o.content["application/json"]?.schema){let a=this.convertOpenApiSchemaToJsonSchema(o.content["application/json"].schema,new Set);if(a.type==="object"&&a.properties){for(let[s,u]of Object.entries(a.properties))i.properties[s]=u;a.required&&i.required.push(...a.required)}}}return i}isOperation(t,r){return["get","post","put","delete","patch"].includes(t.toLowerCase())}isParameterObject(t){return!("$ref"in t)}isRequestBodyObject(t){return!("$ref"in t)}resolveParameter(t){if(this.isParameterObject(t))return t;{let r=this.internalResolveRef(t.$ref,new Set);if(r&&r.name)return r}return null}resolveRequestBody(t){if(this.isRequestBodyObject(t))return t;{let r=this.internalResolveRef(t.$ref,new Set);if(r)return r}return null}resolveResponse(t){if("$ref"in t){let r=this.internalResolveRef(t.$ref,new Set);return r||null}return t}convertOperationToMCPMethod(t,r,n){if(!t.operationId)return console.warn(`Operation without operationId at ${r} ${n}`),null;let i=t.operationId,o={$defs:this.convertComponentsToJsonSchema(),type:"object",properties:{},required:[]};if(t.parameters)for(let u of t.parameters){let c=this.resolveParameter(u);if(c&&c.schema){let l=this.convertOpenApiSchemaToJsonSchema(c.schema,new Set,!1);c.description&&(l.description=c.description),o.properties[c.name]=l,c.required&&o.required.push(c.name)}}if(t.requestBody){let u=this.resolveRequestBody(t.requestBody);if(u?.content){if(u.content["multipart/form-data"]?.schema){let c=this.convertOpenApiSchemaToJsonSchema(u.content["multipart/form-data"].schema,new Set,!1);if(c.type==="object"&&c.properties){for(let[l,p]of Object.entries(c.properties))o.properties[l]=p;c.required&&o.required.push(...c.required)}}else if(u.content["application/json"]?.schema){let c=this.convertOpenApiSchemaToJsonSchema(u.content["application/json"].schema,new Set,!1);if(c.type==="object"&&c.properties){for(let[l,p]of Object.entries(c.properties))o.properties[l]=p;c.required&&o.required.push(...c.required)}else o.properties.body=c,o.required.push("body")}}}let a=t.summary||t.description||"";if(t.responses){let u=Object.entries(t.responses).filter(([c])=>c.startsWith("4")||c.startsWith("5")).map(([c,l])=>{let d=this.resolveResponse(l)?.description||"";return`${c}: ${d}`});u.length>0&&(a+=`
|
|
147
147
|
Error Responses:
|
|
148
148
|
`+u.join(`
|
|
149
149
|
`))}let s=this.extractResponseType(t.responses);try{return{name:i,description:a,inputSchema:o,...s?{returnSchema:s}:{}}}catch(u){return console.warn(`Failed to generate Zod schema for ${i}:`,u),{name:i,description:a,inputSchema:o,...s?{returnSchema:s}:{}}}}extractResponseType(t){let r=t?.["200"]||t?.["201"]||t?.["202"]||t?.["204"];if(!r)return null;let n=this.resolveResponse(r);if(!n||!n.content)return null;if(n.content["application/json"]?.schema){let i=this.convertOpenApiSchemaToJsonSchema(n.content["application/json"].schema,new Set,!1);return i.$defs=this.convertComponentsToJsonSchema(),n.description&&!i.description&&(i.description=n.description),i}return n.content["image/png"]||n.content["image/jpeg"]?{type:"string",format:"binary",description:n.description||""}:{type:"string",description:n.description||""}}ensureUniqueName(t){if(t.length<=64)return t;let r=t.slice(0,59),n=this.generateUniqueSuffix();return`${r}-${n}`}generateUniqueSuffix(){return this.nameCounter+=1,this.nameCounter.toString().padStart(4,"0")}getDescription(t){return this.openApiSpec.info.title==="Notion API"?"Notion | "+t:t}};var $0=Aa(fA(),1),hA=Aa(Hx(),1);import Hre from"fs";var w0=class{constructor(t){this.headers=new Map;t&&Object.entries(t).forEach(([r,n])=>{this.append(r,n)})}append(t,r){let n=t.toLowerCase();this.headers.has(n)||this.headers.set(n,[]),this.headers.get(n).push(r)}get(t){let r=t.toLowerCase();return this.headers.has(r)?this.headers.get(r).join(", "):null}},Vre=typeof global<"u"&&"Headers"in global?global.Headers:void 0,k0=Vre||w0;function mA(e){let t=[];if(!e.requestBody)return t;let i=(e.requestBody.content||{})["multipart/form-data"];if(!i?.schema)return t;let o=i.schema;return o.type!=="object"||!o.properties||Object.entries(o.properties).forEach(([a,s])=>{let u=s;if(u.type==="string"&&u.format==="binary"&&t.push(a),u.type==="array"&&u.items){let c=u.items;c.type==="string"&&c.format==="binary"&&t.push(a)}}),t}var pu=class extends Error{constructor(r,n,i,o){super(`${n} ${r}`);this.status=n;this.data=i;this.headers=o;this.name="HttpClientError"}},Gd=class{constructor(t,r){this.client=new($0.default.default??$0.default)({definition:r,axiosConfigDefaults:{baseURL:t.baseUrl,headers:{"Content-Type":"application/json","User-Agent":"notion-mcp-server",...t.headers}}}),this.api=this.client.init()}async prepareFileUpload(t,r){let n=mA(t);if(n.length===0)return null;let i=new hA.default;for(let a of n){let u=function(c,l){try{let p=Hre.createReadStream(l);i.append(c,p)}catch(p){throw new Error(`Failed to read file at ${l}: ${p}`)}};var o=u;let s=r[a];if(!s)throw new Error(`File path must be provided for parameter: ${a}`);switch(typeof s){case"string":u(a,s);break;case"object":if(Array.isArray(s)){let c=0;for(let l of s)u(a,l),c++;break}default:throw new Error(`Unsupported file type: ${typeof s}`)}}for(let[a,s]of Object.entries(r))n.includes(a)||i.append(a,s);return i}async executeOperation(t,r={}){let n=await this.api,i=t.operationId;if(!i)throw new Error("Operation ID is required");let o=await this.prepareFileUpload(t,r),a={},s=o||{...r};if(t.parameters)for(let c of t.parameters)"name"in c&&c.name&&c.in&&(c.in==="path"||c.in==="query")&&r[c.name]!==void 0&&(a[c.name]=r[c.name],o||delete s[c.name]);if(!t.requestBody&&!o)for(let c in s)s[c]!==void 0&&(a[c]=s[c],delete s[c]);let u=n[i];if(!u)throw new Error(`Operation ${i} not found`);try{let c=Object.keys(s).length>0,p={headers:{...o?o.getHeaders():{...c?{"Content-Type":"application/json"}:{"Content-Type":null}}}},d=await u(a,c?s:void 0,p),m=new k0;return Object.entries(d.headers).forEach(([f,h])=>{h&&m.append(f,h.toString())}),{data:d.data,status:d.status,headers:m}}catch(c){if(c.response){process.env.NODE_ENV!=="test"&&console.error("Error in http client",{status:c.response.status,statusText:c.response.statusText,data:c.response.data});let l=new k0;throw Object.entries(c.response.headers).forEach(([p,d])=>{d&&l.append(p,d.toString())}),new pu(c.response.statusText||"Request failed",c.response.status,c.response.data,l)}throw c}}};function vA(e){let t={};for(let[r,n]of Object.entries(e)){if(typeof n=="string"){let i=n.trim();if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let o=JSON.parse(n);if(typeof o=="object"&&o!==null){t[r]=Array.isArray(o)?o:vA(o);continue}}catch{}}t[r]=n}return t}var Wd=class{constructor(t,r){this.server=new ld({name:t,version:"1.0.0"},{capabilities:{tools:{}}});let n=r.servers?.[0].url;if(!n)throw new Error("No base URL found in OpenAPI spec");this.httpClient=new Gd({baseUrl:n,headers:this.parseHeadersFromEnv()},r);let i=new pd(r),{tools:o,openApiLookup:a}=i.convertToMCPTools();this.tools=o,this.openApiLookup=a,this.setupHandlers()}setupHandlers(){this.server.setRequestHandler(mh,async()=>{let t=[];return Object.entries(this.tools).forEach(([r,n])=>{n.methods.forEach(i=>{let o=`${r}-${i.name}`,a=this.truncateToolName(o),c=this.openApiLookup[o]?.method?.toLowerCase()==="get";t.push({name:a,description:i.description,inputSchema:i.inputSchema,annotations:{title:this.operationIdToTitle(i.name),...c?{readOnlyHint:!0}:{destructiveHint:!0}}})})}),{tools:t}}),this.server.setRequestHandler(is,async t=>{let{name:r,arguments:n}=t.params,i=this.findOperation(r);if(!i)throw new Error(`Method ${r} not found`);let o=n?vA(n):{};try{let a=await this.httpClient.executeOperation(i,o);return{content:[{type:"text",text:JSON.stringify(a.data)}]}}catch(a){if(console.error("Error in tool call",a),a instanceof pu){console.error("HttpClientError encountered, returning structured error",a);let s=a.data?.response?.data??a.data??{};return{content:[{type:"text",text:JSON.stringify({status:"error",...typeof s=="object"?s:{data:s}})}]}}throw a}})}findOperation(t){return this.openApiLookup[t]??null}parseHeadersFromEnv(){let t=process.env.OPENAPI_MCP_HEADERS;if(t)try{let n=JSON.parse(t);if(typeof n!="object"||n===null)console.warn("OPENAPI_MCP_HEADERS environment variable must be a JSON object, got:",typeof n);else if(Object.keys(n).length>0)return n}catch(n){console.warn("Failed to parse OPENAPI_MCP_HEADERS environment variable:",n)}let r=process.env.NOTION_TOKEN;return r?{Authorization:`Bearer ${r}`,"Notion-Version":"2025-09-03"}:{}}getContentType(t){let r=t.get("content-type");return r?r.includes("text")||r.includes("json")?"text":r.includes("image")?"image":"binary":"binary"}truncateToolName(t){return t.length<=64?t:t.slice(0,64)}operationIdToTitle(t){return t.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[\s_-]+/).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ")}async connect(t){await this.server.connect(t)}getServer(){return this.server}};var du=class extends Error{constructor(r){super("OpenAPI validation failed");this.errors=r;this.name="ValidationError"}};async function Wre(e,t){let r;try{r=Jre.readFileSync(Gre.resolve(process.cwd(),e),"utf-8")}catch(n){console.error("Failed to read OpenAPI specification file:",n.message),process.exit(1)}try{let n=JSON.parse(r);return t&&(n.servers[0].url=t),n}catch(n){if(n instanceof du)throw n;console.error("Failed to parse OpenAPI spec:",n.message),process.exit(1)}}async function S0(e,t){let r=await Wre(e,t);return new Wd("Notion API",r)}async function Qre(e=process.argv){let t=Kre(import.meta.url),r=gA.dirname(t),n=gA.resolve(r,"../scripts/notion-openapi.json"),i=process.env.BASE_URL??void 0;function o(){let u=process.argv.slice(2),c="stdio",l=3e3,p;for(let d=0;d<u.length;d++)u[d]==="--transport"&&d+1<u.length?(c=u[d+1],d++):u[d]==="--port"&&d+1<u.length?(l=parseInt(u[d+1],10),d++):u[d]==="--auth-token"&&d+1<u.length?(p=u[d+1],d++):(u[d]==="--help"||u[d]==="-h")&&(console.log(`
|
package/package.json
CHANGED
|
@@ -1109,63 +1109,7 @@
|
|
|
1109
1109
|
"properties": {
|
|
1110
1110
|
"description": "The property values to update for the page. The keys are the names or IDs of the property and the values are property values. If a page property ID is not included, then it is not changed.",
|
|
1111
1111
|
"type": "object",
|
|
1112
|
-
"
|
|
1113
|
-
"title": {
|
|
1114
|
-
"type": "array",
|
|
1115
|
-
"items": {
|
|
1116
|
-
"type": "object",
|
|
1117
|
-
"properties": {
|
|
1118
|
-
"text": {
|
|
1119
|
-
"type": "object",
|
|
1120
|
-
"properties": {
|
|
1121
|
-
"content": {
|
|
1122
|
-
"type": "string"
|
|
1123
|
-
},
|
|
1124
|
-
"link": {
|
|
1125
|
-
"type": [
|
|
1126
|
-
"object",
|
|
1127
|
-
"null"
|
|
1128
|
-
],
|
|
1129
|
-
"properties": {
|
|
1130
|
-
"url": {
|
|
1131
|
-
"type": "string"
|
|
1132
|
-
}
|
|
1133
|
-
},
|
|
1134
|
-
"required": [
|
|
1135
|
-
"url"
|
|
1136
|
-
]
|
|
1137
|
-
}
|
|
1138
|
-
},
|
|
1139
|
-
"additionalProperties": false,
|
|
1140
|
-
"required": [
|
|
1141
|
-
"content"
|
|
1142
|
-
]
|
|
1143
|
-
},
|
|
1144
|
-
"type": {
|
|
1145
|
-
"enum": [
|
|
1146
|
-
"text"
|
|
1147
|
-
],
|
|
1148
|
-
"type": "string"
|
|
1149
|
-
}
|
|
1150
|
-
},
|
|
1151
|
-
"additionalProperties": false,
|
|
1152
|
-
"required": [
|
|
1153
|
-
"text"
|
|
1154
|
-
]
|
|
1155
|
-
},
|
|
1156
|
-
"maxItems": 100
|
|
1157
|
-
},
|
|
1158
|
-
"type": {
|
|
1159
|
-
"enum": [
|
|
1160
|
-
"title"
|
|
1161
|
-
],
|
|
1162
|
-
"type": "string"
|
|
1163
|
-
}
|
|
1164
|
-
},
|
|
1165
|
-
"additionalProperties": false,
|
|
1166
|
-
"required": [
|
|
1167
|
-
"title"
|
|
1168
|
-
]
|
|
1112
|
+
"additionalProperties": true
|
|
1169
1113
|
},
|
|
1170
1114
|
"in_trash": {
|
|
1171
1115
|
"type": "boolean",
|
|
@@ -1287,42 +1231,9 @@
|
|
|
1287
1231
|
"$ref": "#/components/schemas/parentRequest"
|
|
1288
1232
|
},
|
|
1289
1233
|
"properties": {
|
|
1234
|
+
"description": "The property values for the new page. The keys are the names or IDs of the property and the values are property values.",
|
|
1290
1235
|
"type": "object",
|
|
1291
|
-
"
|
|
1292
|
-
"title": {
|
|
1293
|
-
"type": "array",
|
|
1294
|
-
"items": {
|
|
1295
|
-
"type": "object",
|
|
1296
|
-
"required": [
|
|
1297
|
-
"text"
|
|
1298
|
-
],
|
|
1299
|
-
"properties": {
|
|
1300
|
-
"text": {
|
|
1301
|
-
"type": "object",
|
|
1302
|
-
"required": [
|
|
1303
|
-
"content"
|
|
1304
|
-
],
|
|
1305
|
-
"properties": {
|
|
1306
|
-
"content": {
|
|
1307
|
-
"type": "string"
|
|
1308
|
-
}
|
|
1309
|
-
}
|
|
1310
|
-
}
|
|
1311
|
-
}
|
|
1312
|
-
},
|
|
1313
|
-
"maxItems": 100
|
|
1314
|
-
},
|
|
1315
|
-
"type": {
|
|
1316
|
-
"enum": [
|
|
1317
|
-
"title"
|
|
1318
|
-
],
|
|
1319
|
-
"type": "string"
|
|
1320
|
-
}
|
|
1321
|
-
},
|
|
1322
|
-
"additionalProperties": false,
|
|
1323
|
-
"required": [
|
|
1324
|
-
"title"
|
|
1325
|
-
]
|
|
1236
|
+
"additionalProperties": true
|
|
1326
1237
|
},
|
|
1327
1238
|
"children": {
|
|
1328
1239
|
"type": "array",
|
|
@@ -848,6 +848,100 @@ describe('OpenAPIToMCPConverter', () => {
|
|
|
848
848
|
description: 'A schema description',
|
|
849
849
|
})
|
|
850
850
|
})
|
|
851
|
+
|
|
852
|
+
it('preserves const values for oneOf discriminators', () => {
|
|
853
|
+
// Using 'as any' because OpenAPIV3 types don't include 'const' but the actual spec supports it
|
|
854
|
+
const spec = {
|
|
855
|
+
openapi: '3.0.0',
|
|
856
|
+
info: { title: 'Test API', version: '1.0.0' },
|
|
857
|
+
paths: {
|
|
858
|
+
'/resource': {
|
|
859
|
+
post: {
|
|
860
|
+
operationId: 'createResource',
|
|
861
|
+
summary: 'Create a resource with discriminated union',
|
|
862
|
+
requestBody: {
|
|
863
|
+
required: true,
|
|
864
|
+
content: {
|
|
865
|
+
'application/json': {
|
|
866
|
+
schema: {
|
|
867
|
+
type: 'object',
|
|
868
|
+
required: ['parent'],
|
|
869
|
+
properties: {
|
|
870
|
+
parent: {
|
|
871
|
+
$ref: '#/components/schemas/ParentRequest',
|
|
872
|
+
},
|
|
873
|
+
},
|
|
874
|
+
},
|
|
875
|
+
},
|
|
876
|
+
},
|
|
877
|
+
},
|
|
878
|
+
responses: {
|
|
879
|
+
'200': {
|
|
880
|
+
description: 'Success',
|
|
881
|
+
content: {
|
|
882
|
+
'application/json': {
|
|
883
|
+
schema: { type: 'object' },
|
|
884
|
+
},
|
|
885
|
+
},
|
|
886
|
+
},
|
|
887
|
+
},
|
|
888
|
+
},
|
|
889
|
+
},
|
|
890
|
+
},
|
|
891
|
+
components: {
|
|
892
|
+
schemas: {
|
|
893
|
+
PageIdParent: {
|
|
894
|
+
type: 'object',
|
|
895
|
+
properties: {
|
|
896
|
+
page_id: { type: 'string', format: 'uuid' },
|
|
897
|
+
},
|
|
898
|
+
required: ['page_id'],
|
|
899
|
+
},
|
|
900
|
+
DatabaseIdParent: {
|
|
901
|
+
type: 'object',
|
|
902
|
+
properties: {
|
|
903
|
+
type: { type: 'string', const: 'database_id' },
|
|
904
|
+
database_id: { type: 'string', format: 'uuid' },
|
|
905
|
+
},
|
|
906
|
+
required: ['database_id'],
|
|
907
|
+
},
|
|
908
|
+
ParentRequest: {
|
|
909
|
+
oneOf: [
|
|
910
|
+
{ $ref: '#/components/schemas/PageIdParent' },
|
|
911
|
+
{ $ref: '#/components/schemas/DatabaseIdParent' },
|
|
912
|
+
{
|
|
913
|
+
type: 'object',
|
|
914
|
+
properties: {
|
|
915
|
+
type: { const: 'workspace' },
|
|
916
|
+
},
|
|
917
|
+
required: ['type'],
|
|
918
|
+
},
|
|
919
|
+
],
|
|
920
|
+
},
|
|
921
|
+
},
|
|
922
|
+
},
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
const converter = new OpenAPIToMCPConverter(spec as unknown as OpenAPIV3.Document)
|
|
926
|
+
const { tools } = converter.convertToMCPTools()
|
|
927
|
+
|
|
928
|
+
const createResourceMethod = tools.API.methods.find((m) => m.name === 'createResource')
|
|
929
|
+
expect(createResourceMethod).toBeDefined()
|
|
930
|
+
|
|
931
|
+
// Verify const values are preserved in DatabaseIdParent
|
|
932
|
+
const databaseIdParent = createResourceMethod!.inputSchema.$defs?.DatabaseIdParent as any
|
|
933
|
+
expect(databaseIdParent).toBeDefined()
|
|
934
|
+
expect(databaseIdParent.properties.type.const).toBe('database_id')
|
|
935
|
+
|
|
936
|
+
// Verify const values are preserved in the inline workspace option
|
|
937
|
+
const parentRequest = createResourceMethod!.inputSchema.$defs?.ParentRequest as any
|
|
938
|
+
expect(parentRequest).toBeDefined()
|
|
939
|
+
expect(parentRequest.oneOf).toHaveLength(3)
|
|
940
|
+
|
|
941
|
+
// The third option is the workspace inline schema
|
|
942
|
+
const workspaceOption = parentRequest.oneOf[2]
|
|
943
|
+
expect(workspaceOption.properties.type.const).toBe('workspace')
|
|
944
|
+
})
|
|
851
945
|
})
|
|
852
946
|
|
|
853
947
|
// Additional complex test scenarios as a table test
|
|
@@ -118,6 +118,11 @@ export class OpenAPIToMCPConverter {
|
|
|
118
118
|
result.enum = schema.enum
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
+
// Handle const values (important for oneOf discriminators)
|
|
122
|
+
if ('const' in schema && schema.const !== undefined) {
|
|
123
|
+
result.const = schema.const as IJsonSchema['const']
|
|
124
|
+
}
|
|
125
|
+
|
|
121
126
|
if (schema.default !== undefined) {
|
|
122
127
|
result.default = schema.default
|
|
123
128
|
}
|